title: Page title module fallback problem

text:
# Question
Title: Page title module fallback problem
I'm using the Page Title module to set the `<title>` tags on nodes, etc. I'm using the **\[current-page:page-title\]** token in my patterns.

According to the manual, this should let me write a custom page title on node level.

> This allows some nodes to 'inherit' the title from the node title and other nodes have the option to override the \[page-title\] token.
> \[...\] in this case, the author could override the node title and provide a separate page title \[...\]. Note that this field does not allow the admin to completely override the Page Title, but just the \[page-title\] token, which will be inserted as normal into the Pattern for that node type.

And the manual also says:

> So, basically, if you use the \[page-title\] (**or \[current-page:page-title\] in Drupal 7**) token in the patterns/template settings, it will take it's value in the following order:
>
> 1. the value of the "Page Title" field.
> 2. the Entity Title (eg, Node Title, User Name or Term Name), if Page Title field has no value (in 1).
> 3. the value of the title returned by Drupal's "get title" system (i.e. a fallback). This is usually defined by the Menu API system.

However, when the pattern is set to **\[current-page:page-title\]** and I do NOT write anything in the Page Title feed on node level. Then the node gets no title at all. It doesn't fall back to the pattern: It simply doesn't get any title.

Have I misunderstood anything?

# Answer
> 1 votes
You need to choose a specific token context from those available such as \[current-page-what?\]:

```
[current-page-number]   The page number of the current page when viewing     paged lists.
[current-page-path] The URL alias of the current page.
[current-page-path-raw] The URL alias of the current page. Warning: Token value contains raw user input.
[current-page-title]    The title of the current page.
[current-page-url]  The URL of the current page.

```

You should specify your fallback global page titles under '/admin/settings/page-title' and for specific node types, such as 'story' 'page' or 'blog' for example.

You should input the page title tokens as follows;

```
Example 1:  [current-page-path] [page-title]
Example 2:  [page-title] | [site-name]
Example 3:  [page-title] | [site-slogan] - mysite.com

```

Note that you can insert symbols or text between the tokens or after. In this case we've inserted the vertical bar '|' and a hyphen '-' plus the site name 'mysite.com' within the pattern.

I think you've understood correctly.

Although the example above relates to Drupal6, I've tried to recreate your problem in Drupal7 and can't because the default \[current-page:page-title\] | \[site:name\] always kicks in, as it should.

Have you tried completely removing the Page-Title module, running Cron, updating the database and installing the module again?

---
Tags: 7
---


# Question
Title: How can I report to Drupal what is the translation in a language of a string passed to t()?
I'm using Drupal 7. I see that the `t()` function is responsible for translating terms. Where do I go to find the list of translatable terms? For example, suppose I have `t('hello world')` in my code. What file do I edit to tell Drupal 7 that the French version of "hello world" is *bonjour toute le monde*?

# Answer
* You could browse to the Translate interface page (/admin/config/regional/translate/translate).
* You could use a .po file and import it (en/admin/config/regional/translate/import).

You'll have to enable the Locale module for this (it's in core).
More information is available on Translating a site interface to different languages.
> 2 votes

---
Tags: 7, i18n-l10n
---


title: Translation of Menu items

text:
# Question
Title: Translation of Menu items
HI I'm trying to work out how to translate my menu items, weirdly Log Out appears to be the only one which translated from the onset. But I can't see where this was implemented. If I search for the menu name as a string in transate interface/transalte they can't be found. and editing a menu offers no extra fields for translate options??

any body know?

# Answer
OK Its another Module thats required. The Module is called Internationalization this allows you to customise menus/taxonomy and lots of other translation features.
> 0 votes

# Answer
First of all, when you search for translations they are case sensitive. don't include aditional spaces, it has to be exact, but it can be partial. If one translation was previously made and the same word appears in many places it will list it, but what applies is the first translation made (sorted by time) You have to make sure that your Log Out is really a tranlation

in my case it appears in chain: /admin/settings/language as Log out @username, so if I translate this, it works in the other languages there is another Log out in the chain with the same name...so be careful
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Search Drupal from an external application
What I want to do is use the built in search engine I currently have running in my Drupal site, but allow another site to use that same search engine. Basically a legit copy and paste of the form code.

The reason being is I have a separate web application that is running and I am copying the exact look and feel of the Drupal site to make it seem as if the web application is part of the web site. It's separate because the functionality would be a pain to implement in Drupal, and I could do it in Rails in 30 minutes.

So, what things do I need to configure in Drupal and in my web application to make this happen?

EDIT: Just to clarify, my external web application is not consuming any data from Drupal what-so-ever. All I want to do is POST the "copied" search form to the Drupal engine and have it render the search results as if you had searched directly from the Drupal site. It seems like the Services module is used to streamline data to external web applications, and that is not the workflow here at all.

EXAMPLE: Say I have my Rails application sitting at http://app.hostname.com/ and my Drupal site sitting at http://hostname.com/. There is a search form at the root of my Rails application that is pretty much a copy paste of the browser code you'd see as if you had looked at the Drupal site source of the search form. It's just a simple text box with a submit button. When I submit that form from the Rails site, I want it to POST the data to the Drupal site and have the returned results be the exact same as if I had searched from the Drupal site directly (I said this already but it doesn't hurt to re-iterate), leaving the URL bar now saying http://hostname.com/search/node/foo%20bar.

# Answer
Drupal searches can just be normal GET requests w/o going through the form. Try it.

Make a page in your RoR app to catch the POST and parse the search needle. Then 302 to the Drupal site with the proper URL.
> 2 votes

# Answer
You could use the Services module. Please see: Services: An API for remote applications

> Services is a standardized API for Drupal that allows you to create "services", or a collection of methods, intended for consumption by remote applications
> 0 votes

---
Tags: 7, search, database
---


# Question
Title: Is there a way to have two aliases to a user's profile page?
Is there a way to have two aliases to a user's profile page?

We are currently using the user paths setting at admin/build/path/pathauto - but we would like to have another path set up for the same page if that is possible.

Currently we have one path set to be: users/\[content-profile-directory-preferred\_first\_name-raw\]-\[content-profile-directory-lastname-raw\]

We would like to setup a second path to the same user's profile page that would be just: users/\[user-raw\]

Thanks, Greg

# Answer
> 1 votes
Assuming you don't want to manually maintaing the second alias - since pathauto only allows you to generate a single automatic alias - then perhaps the easiest way is to use Rules, instead of pathauto. It's been a few years since I did this, and it was for node aliases, not user page aliases, but I don't see why it wouldn't work.

1. Setup a Rule with multiple steps to create the aliases you need - you can use all the same token substitutions in Rules as you can in pathauto
2. Run the rule when a user is created

---
Tags: path-aliases
---


title: preprocess view fields

text:
# Question
Title: preprocess view fields
I have a view with some fields wich I theme inside `views-view-fields--MYVIEW.tpl.php`. I use a `phptemplate_preprocess_views_view_unformatted__MYVIEW()` to preprocess some `$vars` before the template to have the template as *clean* as possible. But I don't know the right way of preprocessing the fields.

I can access the fieldcontent in the template via `$fields['MYFIELD']->content`. Inside the preprocess function I can't find this explicit `content` value. All I see is something called `last_render` but i'm not sure it's ok (the right way) to use/change this value.

# Answer
> 1 votes
Try to use `debug()` to see the content of `$vars`. As far as I know, in views/themes/theme.inc there are many examples of preprocessing functions.

# Answer
> 1 votes
Try `dsm($vars)`. It allows you to see the contents of `$vars` clearly. Note that you need the Devel module to do this.

---
Tags: views, theming, 6
---


title: Retain values during myform_validate()

text:
# Question
Title: Retain values during myform_validate()
In Drupal 6, I have a custom form validation function, where:

* I copy the value from field A to field B, if field B is empty.
* I call `form_set_error()` when the field B contains more than X characters.

Validation works fine, and the error is set. The problem is that the value in field B is not retained when the form is rebuilt: field B remains empty. I want to keep the value in field B after validation (when the error is set) to make it easy for users to edit it down to the right length.

My validation function looks like this:

```
function myform_validate($form, &$form_state) {
  if (empty($form_state['values']['field_b']['0']['value'])) {
        $form_state['values']['field_b']['0']['value'] = $form_state['values']['field_a']['0']['value'];
      }
      if (strlen($form_state['values']['field_b']['0']['value']) > 260) {
        form_set_error('field_b', 'Text in field b is too long');
      }
    }
  }
}

```

Any suggestions on how to retain the value in field B when the form is rebuilt?

# Answer
> 4 votes
If you want to set a form value from within your validation callback you'll need to use something like form\_set\_value. Values that are assigned directly in the manner shown above will not be retained, but that function should do the trick! It's specifically intended for this purpose - setting a form value during the validation phase.

For example:

```
function myform_validate($form, &$form_state) {
  if (empty($form_state['values']['field_b'])) {
        // Note that the $form array - not $form_state - is used in the first parameter.
        // The second parameter is the value you are setting.
        // Third just pass the $form_state array itself, which will be altered by form_set_vaue().
        form_set_value($form['field_b'], $form_state['values']['field_a'], $form_state);
      }
      if (strlen($form_state['values']['field_b']) > 260) {
        form_set_error('field_b', 'Text in field b is too long');
      }
    }
  }
}

```

---
Tags: entities, 6
---


# Question
Title: Prevent users from editing a node if a CCK field has a specific value
I would like to redirect users to an access denied page, if they try to edit a page with a specific CCK field value.

Any tips?

# Answer
> 2 votes
Since you mention CCK and not fields, I am assuming Drupal 6 here. A brute force approach would look like

```
function foo_init ()
{
  if (arg(0) == "node" && arg(2) == "edit") {
    $nid = (int) arg(1);
    $node = node_load($nid);
    if ($node && $node->nid) {
      $foo = $node->field_foo[0]["value"];
      if ($foo == "foo") {
        drupal_access_denied();
        exit;
      }
    }
  }
}

```

# Answer
> 2 votes
What you want is probably a custom node\_access module - just remember that permissions in Drupal are additive, so your custom module is *granting* permission, rather than taking it away. So, for instance, a user should *not* already have the "edit this content type" permission or they'll have it for ALL nodes of that content type.

Also, why even assume they can attempt to edit? If they don't have permissions to edit that page, short of them manually hitting the /edit URL for a node, they're not going to have a chance - no edit button will be visible.

---
Tags: nodes, entities
---


title: proper way to edit drupal_page_header()

text:
# Question
Title: proper way to edit drupal_page_header()
I can't find a hook for overrideing `drupal_page_header()` in bootstrap.inc and it doesn't feel right to make changes in bootstrap.inc.

Is there another other way that I'm missing?

# Answer
> 3 votes
If you goal is only to change the `Cache-Control` you can use drupal\_add\_http\_header(). According the documentation this function allow you override an existing header. If you add it in you template.php you'll able to change the header without patch the core function.

---
Tags: hooks
---


# Question
Title: How to make block with list of terms from blog postings
I would like to display a navigational block in a sidebar on a single-user blog page which will have a listing of all taxonomy terms used in the blog entries.

I am using a custom content type and Views to make the blog. I have set up a vocab for this content type, with multiple terms from this vocab selectable for each posting.

I set up a block display in the view with a field using *Taxonomy: All terms*. Then a filter limited to my specific vocab. Everything is fine, except that I am getting duplicate terms in the list, as some blog entries have the same terms.

Can anyone please tell me how to remove the duplicate results, or tell me a better way to get what I want?

# Answer
> 1 votes
It sounds as if you have created a view of nodes, and using the *Taxonomy: All terms* field to display the terms of those nodes. That approach will indeed produce duplicate results.

Instead, you need to create a view of Taxonomy Terms. I don't know which versions you are using, but here is the export of such a View made with Drupal 7 & Views 7.x-3.0-rc1.

```
$view = new view;
$view->name = 'tags';
$view->description = '';
$view->tag = '';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Tags';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Tags';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = 1;
/* Sort criterion: Taxonomy term: Name */
$handler->display->display_options['sorts']['name']['id'] = 'name';
$handler->display->display_options['sorts']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['sorts']['name']['field'] = 'name';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'tags' => 'tags',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'tags';

```

---
Tags: views, blocks, nodes
---


# Question
Title: How should I share sessions transparently across domains?
I work on a Drupal site which has multiple domains (not sub-domains) using Domain Access to set different themes, display different content, etc. on each of them. These multiple domains are used for canonical HTTP URLs. Each domain also has a corresponding sub-domain of a common domain which is used with Secure Pages for HTTPS (there's a wildcard certificate). This all works fine.

My next step is to manage to unify the session between HTTP (on the canonical domain) and HTTPS (on the sub-domain of the shared domain). Many other sites accomplish this by redirecting back to their main domain to assign or discover the session cookie and redirect back to a "set cookie" script on the the current domain to set it there too.

A semi-serious search of D.O and with Google didn't turn up anything useful so I'll ask here: has anyone done this before in Drupal before? Is there a module or (more likely) a patch I can use and am I on my own here?

Thanks for any suggestions.

# Answer
There are some related answers and solutions at "Enterprise" authentication, single sign-on and user provisioning for multiple sites.

While you have a more specific question, the goal is similar to what many SSO solutions in Drupal try to achieve.
> 1 votes

# Answer
Sending secured session to unsecured sites is not a good way; you can just pass some variables that not affect your security (e.g., via `$_GET`). Read also Session lost when switching from HTTP to HTTPS in PHP.
> 0 votes

---
Tags: cookies, sessions, ssl
---


# Question
Title: General architectural approach to Drupal for a project
Apologies for the inspecific title, but my question is a relatively generic one!

I'm relatively new to Drupal, and because I've historically had a very different approach to CMS implementation, I think I may be missing the point of the architectural qualities of Drupal.

I'm a .NET developer who's used Umbraco and EPiServer a lot, but had limited experience in Drupal.

What Umbraco offers is a way for users to organise their content in the admin panel, such that items will happily sit in a tree structure under other items.

In the case that you have a news section, you would have the following structure in Umbraco:

News landing page
\- News story 1
\- News story 2
\- News story 3

This hierarchical approach is also easily transferrable to organising other types of content, such as slideshows for a specific page. You could have a homepage which would consist of a slideshow with four slides in it, and that slideshow could be specific to that homepage. This would look like this:

* Homepage
+ \- Slideshow
+ \+ Slide 1
+ \+ Slide 2
+ \+ Slide 3
+ \+ Slide 4

In Drupal, I've noticed that all pages sit together in a sort of "page soup" as someone else coined, and an implementation of a taxonomy is relied upon to ensure that content is organised on the front-end.

I'm aware that Drupal offers a menu structure which allows you to form this structure, but it seems like if you want to organise actual content rather than memory references to content, you're a bit lost.

Another feature I found extremely useful in Umbraco is the ability to programmatically fetch page objects, and to have access to an API allowing me to get the children of that page, and display them within the markup the way that I see fit. The filesystem for this would look like this:

Homepage.aspx
\- Slideshow.ascx

This allows you to drag that slideshow.ascx control onto any page, and the control will go and get the children of its parent, and display those slideshow items automatically.

Is all of this possible within Drupal? Am I missing the point entirely? I would love a bit of direction on this, as I've been floating around the general area of content for a little while now!

Thanks for any help!

# Answer
I've used a collection of modules to achieve what I wanted with Drupal; the most integral of these is Node Hierarchy.

This has allowed me to use the parent-child relationship I was after, and although this may not be how Drupal was intended to structure content, I've certainly found it extremely useful!

I had intended to utilise views as well, but abandoned them as they didn't suit what I was after. However, if you want to programmatically introduce views into your code rather than using the full UI and blocks stuff, you can look at this example:

http://drupal.org/node/685432
> 2 votes

# Answer
This is a common grey area for new developers to Drupal. The root for every "page" is index.php. There is no "page" per se, every dynamically generated "page" is a container. Regions (found in either /themes/bartik/bartik.info file in Drupal 7 installations without any changes or additions to Drupal core yet) establish the sections of the container that you can add different types of content (i.e., blocks, menus, views, etal.) I would recommend reading about the bootstrap process for Drupal, it is during bootstrap that everything gets called on a url by url basis. Using the Drupal interface and adding modules adds ways to "generate" or "contain" different types of content. There are over 10,000 modules (and counting) to add functionality to the Drupal enviroment. There are, generally, a handful of recommended modules that provide the most cohesive and robust ways to develop almost anything within your Drupal site that are recommended. This ultimate flexibility takes a little time to grasp and work with but once you do, you never want to go back.
> 3 votes

# Answer
I think a lot of what you want can be achieved with the Views module. It's a module that creates custom queries of nodes, users, etc. from the database. While the core doesn't really have the sort of admin panel you're talking about, you can create a custom one using views that lists the children of each node. How you create that parent-child relationship can be achieved using taxonomy or CCK node references (in Drupal 6) or the Field API in Drupal 7.

The same goes for your second point. Views provides several default ways to output those queries (pages, blocks, RSS feeds, etc.) and you can always modify the template files to change the output. Views also take arguments, so you can create one view, pass it some arguments and re-use the same view in multiple ways.
> 2 votes

---
Tags: theming, javascript
---


# Question
Title: Showing/Hiding Content-Type Fields Based On User
I have a content-type that has many fields for different translations. How do I set it up in a way that it shows the translation field based on user selection only. I mean user selects his/her language, then only that content-field appears on the post.

Appreciated...

# Answer
> 1 votes
Yeah you could do that as well, though if you have lot of data hidding things on the server side would be better. You could just override the node template page, with something like : `node--nodeType.tpl.php`, then in the variables of that page you will have your node with all its Fields available, you can then do a simple check (cookie or sessions) to render appropriate language.

---
Tags: 7, views, nodes
---


title: Restrict access to parts of admin pages

text:
# Question
Title: Restrict access to parts of admin pages
I've setup a site for a client I want them to have access to edit content, but some of the permissions grant too much control for my liking. Can someone give me a way to be a bit more selective with permissions. These are my areas of interest.

1. I have a custom block which contains 2 editable fields, To allow access I have to grant access to Administer Blocks, which give the user access to reposition the block, I would like this to disabled, and also the Regional and Visability settings to be disabled.
2. When editing a Basic Page node, I have an image field which I dont want the user to be able to adjust.

Any clever people out there know the answers?

# Answer
> 0 votes
The only way I can think of is to implement hook\_form\_alter() and add the "#access" property to the form fields you don't want to be accessible from the user.
Normally you should use code similar to the following one, but every function that returns `FALSE` when the current logged-in user should not access the form field would work too.

```
$form['form_field']['#access'] = user_access("access form_field");

```

The permission the code checks can be any of the permissions the module implements, or other modules implement.

---
Tags: users
---


title: Module does not show up in blocks (6.x)

text:
# Question
Title: Module does not show up in blocks (6.x)
I have a module that I've activated, but it does not show up in the disabled blocks list.

The module is named "My Module." Inside the my\_module folder I have the following files:

* my\_module.module
* my\_module.info

### my\_module.info

```
name = My Module
description = My module description.
core = 6.x
package = My Modules

```

### my\_module.module

```
<?php
function hook_block($op = 'list', $delta = 0, $edit = array()){
  switch ($op) {
    case 'list':
      $block = array();
      //List out all blocks you want to create here
      $block[0]["info"] = t('Display info');
      break;
    case 'view':
      switch ($delta) {
        case 0:
          global $user;
          $block['subject'] = "ADMIN Header of the block";

          if (in_array('Site admin', array_values($user->roles) || $user->uid == 1)) {
            $block['content'] = "input form";
            $block['subject'] = "Header of the block";
          }
          break;
      }
  }
}

```

# Answer
> 2 votes
Change `function hook_block` to `function my_module_block`, and add `return $block;` to the end of the 'list' and 'view' cases.

---
Tags: 7, blocks
---


# Question
Title: 7- OG 'og_users_roles' table doesn't seem to update on Group creation
I recently noticed that when a user of my site create a new group, the `og_users_roles` table do not get updated. Witch basicly means that unless the Group creator goes to the "members management" interface to give himself "Group admin", the newly created group do not have an administrator. So `og_get_users_by_roles` return empty when searching for the "Group admin" rid.

Is this normal? If so how would i go to give a group creator the "Group admin" role by default on group creation ?

# Answer
I fixed that by hooking on node creation and updating the table myself. I'll let the thread open in case anyone have a better solution.
> 1 votes

---
Tags: 7, organic-groups
---


title: Permission Drupal folders

text:
# Question
Title: Permission Drupal folders
I create a website on Linux/Apache and I want move it to Windows/IIS 6 here, my panel is Plesk. I can't upload files and images and my Images that customize with Imagechach module not shown! I guess folder permission not trust. where I can find a list of Drupal folder permission?I don't know how to set permission in Plesk,Please help me ..!? :(

# Answer
Most directories and files in a stock Drupal environment just need read/execute for the IIS user - this allows IIS/PHP to read and execute the .php, .inc, and other files. For your "files" directory - typically in sites/default/files - IIS will also need write permissions, so it can write uploaded files and create new files (for instance, ImageCache derivatives).

As for how to do this in Plesk, it will vary, but here's a guide that should get you pointed in the right direction (depending on your host, some of the user/group names may differ, but should be close):

http://knowledge.3essentials.com/web-hosting/article/478/Setting-file-folder-permissions-from-Plesk-control-panel-for-Windows.html
> 4 votes

---
Tags: users, files, media
---


# Question
Title: Sorting by "aggregation type: count" is not working
I am trying to solve this problem: Drupal 7 Most Popular Tags in a list as a block: How? with Views 7.x-3.0-rc1.

The solution is the answer by Dylan Tack.

> * create a view of terms
> * add a required relationship to "content using tags"
> * set use aggregation: yes
> * add the "term name" field a second time, set one of the to "aggregation type: count"
> * add "term name" as a sort criteria, set "aggregation type: count"
>
> A sample view is at http://drupalbin.com/19467

It works until I try to sort the list; in that case, I get an error when adding a sort criteria. If I set "aggregation type: count" the sort-criteria changes to "Broken/missing handler" and it is not sorting.

Do you have any idea? Am I doing something wrong?

# Answer
This issue has been resolved in the development snapshot version 7.x-3.x-dev.
> 0 votes

---
Tags: views, css-js-aggregation, taxonomy-terms
---


title: View that Shows Result Links

text:
# Question
Title: View that Shows Result Links
I have a view that prints the titles of my 10 most recent news item content. I also want to print the URL to these news items. How do I do this? When I edit the view, under Fields, I see a Link field, but the problem is that it prints the word "view" instead of http://mysites.com/my-first-news-item

# Answer
> 0 votes
I almost got it....the field i'm looking for is called `Content:Path`. Right now, it prints /my-first-news-item. All I need to do now is have it print the domain name as well.....almost there.

**EDIT** Figured out the last part. To print out the absolute path, make sure the field also has the setting `Use absolute link (begins with "http://")` checked

---
Tags: 7, views
---


title: file downloads based on user

text:
# Question
Title: file downloads based on user
My Goal * User Request for a customize version of a file * admin uploads the file for that user. * User Downloads Files.

I am stuck at how to assign a certain file to certain user. How do i accomplish this with views . My idea was to create a node with file upload field and assign certain user to it , I dont know how to do this assign part and filter things with views

Note : i am using drupal 7

# Answer
With Drupal 7 you should be able to add a file field to a user.

Another solution would be a content type with a file filed. After creating the node of this new type make sure the receiving user is set as the owner. Finally make sure the user hass access to all files he owns.
> 1 votes

---
Tags: views, files
---


title: htmlspecialchars in search

text:
# Question
Title: htmlspecialchars in search
When I'm searching my site, I get this error:

> Warning: htmlspecialchars(): Invalid multibyte sequence in argument in check\_plain() (line 1476 of /var/www/includes/bootstrap.inc).

What does it mean and how can I correct it?

EDIT: The problem disappeared after migrating to webhosting server, so the problem should be something in settings in my local computer.

# Answer
> 1 votes
The problem is caused by the search module. It does not handle multibyte characters correctly. Watch this thread: http://drupal.org/node/987472 Fixing the search module fixed the problem for me. However wait for an authorized patch.

Your webhoster doesn't show the error not because it is not there, but because they have a better production settings. The error can be easily suppressed using PHP settings.

# Answer
> 2 votes
Try adding some instrumentation by replacing the check\_plain function with this version:

```
function check_plain($text) {
  $plain = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
  if (empty($plain) && !empty($text)) {
    dpm($text);
    ddebug_backtrace();
  }
}

```

You will need to have the devel module enabled. The next time the error is triggered, the offending text will be displayed along with a backtrace that shows what function triggered the error. With that info, you can search your code and database for the offending text and remove it.

# Answer
> 1 votes
This has occured to me because I had left some Unicode (é, ó...) in a template file or a module, be sure to check this. Generally you need to use the `t()` function and then translate your string in the translate interface `admin/build/translate`.
If you can't do this, you can use `utf8_encode('é')` but that's not very pretty.

# Answer
> 1 votes
Wild guess here, but I suspect something isn't UTF-8 clean.

check\_plain is hardcoded for UTF-8. I suspect that you are some part of your transfer is in ISO-8859-1.

Watch the transfer with Live HTTP Headers. If you see anything other than UTF-8 in requests or responses, then you need to tweak some non-Drupal settings.

---
Tags: 7, search
---


# Question
Title: Merging output of Print.module's printpdf with existing PDFs
Recently, I created an output template for the Print module, such that it dynamically generates a measurement sheet when a certain content type is parsed by its PDF functionality (using dompdf in this case).

Everything works great, but the client's requested file attachment fields for PDFs, such that existing PDFs are added to the end of dompdf's output. For instance, a PDF of a CAD drawing would be attached in Drupal, printpdf/$nid generates the template I've created, and the file locations given from the file upload fields are used to merge the files at those locations with the generated PDF.

dompdf apparently cannot merge PDF documents, so I'm thinking a workaround would be to generate the PDF and save to disk somewhere, run another PDF merger script, then present the merged output to the user.

**How would one go about programmatically saving the output of Print.module's PDF generator to somewhere on the server, then running an external class on that saved output?**

*(Alternately, if you know of a way for dompdf to read PDFs and append them to the document, that'd work even better.)*

# Answer
> 0 votes
I hacked print\_pdf.pages.inc to merge PDFs after creation based on the existence of a filefield:

Starting at line 209, in function \_print\_pdf\_dompdf();

```
    $node = $print['node'];
    if ($node->field_pdf[0]) {
        $meas_pdf = $dompdf->output();
        file_put_contents($base_path . 'sites/default/files/pdf_temp.pdf', $meas_pdf);
        include $base_path . 'sites/all/libraries/PDFMerger/PDFMerger.php';
        $newpdf = new PDFMerger;
        $newpdf->addPDF($base_path . 'sites/default/files/pdf_temp.pdf', 'all');
        foreach ($node->field_pdf as $attach) {
        $newpdf->addPDF($base_path . $attach['filepath'], 'all');
        }
        $newpdf->merge('download', 'measurements.pdf');
    }
    else {$dompdf->stream($filename, array('Attachment' => ($print_pdf_content_disposition == 2))); }
}

```

It'd be great to write a module that undefines Print.module's private \_print\_pdf\_dompdf(); function and replaces it with my own (so I'm not hacking a contrib module); any idea how I'd go about that?

---
Tags: 6, files
---


# Question
Title: Rewrite taxonomy_term_reference urls to read /taxonomy/term/(name)
After creating a view to allow /taxonomy/term/(name) to show content tagged with that term, I am trying to find where I can override the generation of field links (field\_type\_taxonomy\_term\_reference) so that they create links following this format. Currently they still show the id number for the term at the end. I have tried `(mytheme)_preprocess_taxonomy_term` and altering `$variables['term_url']` but that hasn't worked. Can anyone please give me any pointers about how to do this, I am running out of ideas.

Any thoughts welcome.

Cheers Paul

# Answer
> 1 votes
You should be able to set URL aliases for your taxonomy terms using the Path module that comes with Drupal core. (EDIT: As mentioned by jordojuice, you'll also need the Pathauto module to automatically generate these patterns in the manner I instruct below).

1. Go to the Configuration menu and select "Url Aliases" in the "Search and Metadata" section. (admin/config/search/path)
2. In the upper tab of the URL Aliases menu, select "Patterns." Here you can set the path to your taxonomy terms to whatever you'd like.

The only problem is that I don't think Views overwrites the URLs generated. There was a module for this in Drupal 6, but I don't think there is anything similar for D7.

There is a View that comes default in Views that should overwrite the default taxonomy paths; you could see what it does and try to tweak it.

---
Tags: 7, taxonomy-terms, entities, theming
---


# Question
Title: Ajax fired when Filefield "Add Another Item" button is clicked conflicts with my jQuery code
I have a node type with a multi-value file field. I am using some jQuery code used by a custom module to modify some of the form elements, but when I click on the *Add another item* button, it completely breaks and wipes out my custom jQuery code.

How can I fix this?

# Answer
> 1 votes
These tips are correct for **Drupal 7**.
Your custom code should be coordinated with Drupal AJAX Framework.
When you click "Add Another Item" this happens:

1. AJAX handler sends all the form with all values, and with point to element which has triggered AJAX.
2. Server returns fully new field. For example, if there were 4 inputs in your field, server will return 5 inputs, not just last fifth.
3. After that new piece of HTML goes through all the behaviors. As you may know, behavior's attach method has two params: `context` and `settings`. `context` is just new HTML for your field.

So, if you add your JS to this schema correctly it must work.

```
Drupal.behaviors.YOURMODULE = {
  attach: function (context, settings) {
    $('.some-class', context).once('YOURMODULE', function() {
      // Do some work here
    });
  }
}

```

---
Tags: 7, javascript
---


# Question
Title: Embed video code from third party providers
I want embed video to my node, module "Embedded Media Field" do this for some third party providers, but I want embed videos from Aparat which not supported by emfield. is there any other solution?

# Answer
> 1 votes
I looked at the embed code from aparat and it reminded me of Slideshare's code. I tested it by entering its embed code the same way I do with Slideshare (copying the embed code into a **non**-rich text editing window) and it worked.

As with Slideshare, sometimes the video doesn't appear even after loading. The fix if that happens is to refresh. It will show the second time.

---
Tags: 6
---


# Question
Title: Too many passes with Drupal 7 test framework
I'm implementing some tests using the D7 testing framework.

All is good, except that the numbers don't seem to add up, and I wondered how pass/fail was evaluated?

The problem is that I'm getting "6 passes, 0 fails, 4 exceptions, and 2 debug messages" for two test methods.

Obviously I'm missing something, but I had assumed that a single test method would produce a single pass/fail and therefore I should only have two results.

Secondly, how can I find out more information about the exceptions that were reported?

Thanks everyone.

# Answer
Each `assert()`ion you have in your test code will result in a pass, fail or even an exception. The uncaught exceptions are bad fails.

If you're running your tests with `scripts/run-tests.sh`, then use the `--verbose` flag and you'll be able to see the result of each assertion and any associated error/s.
> 5 votes

# Answer
Many, many internal methods run asserts, even `setup`. Almost all drupal\* methods do, for example, `drupalCreateUser`, `drupalCreateUser`, `drupalLogin`, `drupalGet'`drupalPost\`.
> 2 votes

---
Tags: testing
---


# Question
Title: Why are variables & CSS loaded in the overlay?
This seems really weird to me and makes no sense.

I'm using a custom theme, with Seven as the administration theme (inside the overlay).
Why on earth are variables such as `$base_url` loaded in the overlay (and produce errors) when I only called them in my page--front.tpl.php (in my custom theme)? The same goes for the CSS; it is messing up the admin theme.

I even renamed my style.css and used `drupal_add_css()` to call it, but the result is the same.
I don't get why the administrative theme is looking at my custom theme files.

Surely I don't need to add arguments to all the variables, and make my CSS calls more specific, or do I?

# Answer
> 3 votes
There is a misunderstanding on how the Overlay module works.
Suppose you are watching your front page, and you click on a link that opens the overlay. What Drupal will do in that case is:

* render the front page using the theme you have set
* render the overlay using the administrative theme you have set

The overlay is rendered as iframe using the `Drupal.overlay.create()` function defined in a JavaScript file used from the Overlay module.

```
/**
 * Create the underlying markup and behaviors for the overlay.
 */
Drupal.overlay.create = function () {
  this.$container = $(Drupal.theme('overlayContainer'))
    .appendTo(document.body);

  // Overlay uses transparent iframes that cover the full parent window.
  // When the overlay is open the scrollbar of the parent window is hidden.
  // Because some browsers show a white iframe background for a short moment
  // while loading a page into an iframe, overlay uses two iframes. By loading
  // the page in a hidden (inactive) iframe the user doesn't see the white
  // background. When the page is loaded the active and inactive iframes
  // are switched.
  this.activeFrame = this.$iframeA = $(Drupal.theme('overlayElement'))
    .appendTo(this.$container);

  this.inactiveFrame = this.$iframeB = $(Drupal.theme('overlayElement'))
    .appendTo(this.$container);

  this.$iframeA.bind('load.drupal-overlay', { self: this.$iframeA[0], sibling: this.$iframeB }, $.proxy(this, 'loadChild'));
  this.$iframeB.bind('load.drupal-overlay', { self: this.$iframeB[0], sibling: this.$iframeA }, $.proxy(this, 'loadChild'));

  // …
}

/**
 * Theme function to create the overlay iframe element.
 */
Drupal.theme.prototype.overlayContainer = function () {
  return '<div id="overlay-container"><div class="overlay-modal-background"></div></div>';
};

/**
 * Theme function to create an overlay iframe element.
 */
Drupal.theme.prototype.overlayElement = function (url) {
  return '<iframe class="overlay-element" frameborder="0" scrolling="auto" allowtransparency="true"></iframe>';
};

```

About the error you are seeing, it is probably caused by the fact you are accessing the `$base_url` variable without defining it as global variable (using the `global $base_url;` line). You should not need to use that variable to generating the URLs for your site, as Drupal has url() and l(); the first function is used to generate a URL, while the second one is used to generate an anchor link, such as `<a href="/node/1">Example link</a>`.

---
Tags: theming, modal-dialogs
---


# Question
Title: Margin before admin menu with Views admin pages
Screenshot shows the problem:
This margin appears on all **admin** pages which use Views on *Seven* theme and module *Administration menu*. As example, Drupal Commerce products list. Actually this is because of body class `.contextual-links-region`. I didn't find any issues about it. Can anybody comment it?

UPD: Problem disappeared after Drupal update to 7.8.

# Answer
> 1 votes
The admin\_menu module adds a margin to the top of the page so it can sit there. I suspect the toolbar module does the same thing which gives you the double margin.

Looking at your screenshot you're using 3 menu modules, which seems overkill to me. Disable the toolbar module and you should be right. The admin and admin\_menu modules can happily coexist. You can also add custom items to either or both of these menus.

Personally I'd just go with the admin module.

---
Tags: 7, views, theming
---


title: How to modify block menu path

text:
# Question
Title: How to modify block menu path
My goal is to have a menu block on my blog pages with a list of the terms used in the blog posts. So far I have set up a node view for the blog postings. And a term view called *topics* to display the terms.

It's working, but when I click on a term listed in the block the resulting path is *category/topics/term-name*. I would like to have a path such as *blog/topics/term-name* or even better just *blog/term-name*.

I have looked at the *Taxonomy menu* settings under the *taxonomy/edit/vocabulary* but haven't figured out if I can change these settings to get what I want.

I'm using the *Pathauto module*. Not sure where else to look for an answer. I'm using 6.

# Answer
Pathauto gives you the option of defining per taxonomy path patterns. Just set the value for your blog categories taxonomy to `blog/topics/[catpath-raw]` and regenerate your aliases. These settings are controlled in http://example.com/admin/build/path/pathauto
> 2 votes

---
Tags: 6, taxonomy-terms, routes, blocks, nodes
---


# Question
Title: Remove the "Please wait" text on Ajax Call
I am trying to remove the text "please wait" that happen on every Drupal Ajax call. Could anyways one point me the way to achieve this in an elegant manner (without any module or CSS hack)?

Thanks

# Answer
You should be able to do this with `hook_form_alter()` by changing the Ajax settings that control the form's Ajax. There is a 'progress' property in Ajax that will allow you to set or change the 'Please wait...' text. From the API docs:

```
#ajax['progress']['message'] String. An optional message to the user; should be wrapped with t().

```

A sample `hook_form_alter()` that will accomplish this:

```
function mymodule_form_FORM_ID_alter($form, &$form_state) {
  unset($form['element']['#ajax']['progress']['message']);
  // or:
  $form['element']['#ajax']['progress']['message'] = '';
}

```

You should be able to use `print_r($form);` or `dsm($form)` (with Devel module) to locate the form element with Ajax properties set. Use that to locate the proper element and replace my `$form['element']` above with the actual element in question.
> 5 votes

---
Tags: 7, ajax
---


title: Assigning css classes to menu items

text:
# Question
Title: Assigning css classes to menu items
I need to assign different classes to all of the menu items in my primary links because each item is preceded by a different icon. How could I go about doing this?

EDIT: I found a module that seems to achieve this -- http://drupal.org/project/menu\_attributes. Has anyone used it? Is it an effective solution?

# Answer
Yes, the Menu Attributes module works well. I used it on nearly all projects.
> 2 votes

---
Tags: theming, navigation
---


title: Extracting arguments from dynamic URLs

text:
# Question
Title: Extracting arguments from dynamic URLs
I am new to Drupal 7 and am trying to do the following:

1) I have a node that's aliased to domain.com/inventory - the node has code that'll generate dynamic content.

2) My site creates dynamic URLs like domain.com/inventory/ABCD and I need to know how to a) figure out that I'm on the /inventory page and b) extract the argument "ABCD" from the URL.

Can you please help me?

# Answer
If your node is 12, your internal path is node/12 when the alias is 'inventory'. In that case arg(0) gives you 'node' and arg(1) gives you '12'.

In the case of dynamic URLs like inventory/ABCD, I assume that the internal path is 'inventory/ABCD' (so that inventory/ABCD does not have anything to do with node 12). Then arg(0) gives you 'inventory' and arg(1) gives you 'ABCD'.
> 2 votes

# Answer
I think what you need is drupal\_get\_path\_alias.

```
$current_path = drupal_get_path_alias();

```

You can then explode that path on '/' to get your argument.
> 2 votes

# Answer
The answers here are pretty good, also look at `drupal_lookup_path()` and `request_uri()` for related functions around what you're trying to do.
> 0 votes

---
Tags: uri, views
---


# Question
Title: Allow users to sort stories by date or content type
What is the easiest way to allow users to sort a story view by content type or date? Is there a module that would allow you to do so? The idea would be to have a drop down list containing the different content types and a calendar widget (or perhaps also drop down lists) which would allow users to determine a date range.

If this can only be achieved programmatically, no need to provide much detail -- I suspect it would be a rather long explanation and don't want to take that much of anyone's time.

# Answer
> 1 votes
i think you might be confusedly mixing a few different concepts?

"story" is one of the default/example content types distributed with Drupal and is nothing special, ie. not quite sure what you mean by "story view".

I assume from the way that you're phrasing your question that you're new to Drupal, have you discovered Views and CCK?

exposing filters is relatively easy in Views 2 and 3, but exposing sort options in general is more difficult in Views 2 (you'll probably need some basic PHP knowledge to achieve this) but can be done through the UI in Views 3.

popup calendar widgets for date fields exist in the Date module once you install the jQuery UI module.

if you want a calendar widget that is "inline" (doesn't popup from a dropdown menu) then you'll likely have to do a little coding, but it isn't very hard as jquery UI provides a good API for inserting calendars into your page.

---
Tags: nodes, 6
---


# Question
Title: In Open Atrium is there a way to assign a user to a case that user is not in?
I would like to be able to have an admin be assigned to a case that is in a group that user is not a part of. In Open Atrium. Is this possible?

# Answer
No, it isn't possible, at least not by using the Atrium web UI out-of-the-box. Cases can only be assigned to users in the current group.
> 1 votes

---
Tags: distributions
---


title: Hide a menu item for admin user

text:
# Question
Title: Hide a menu item for admin user
How can I remove a menu item when admin is logged in? I used the following code but it doesn't seem to work.

```
function mymodule_menu_alter(&$items) {
     $items['item_x']['access callback'] = 'mymodule_menu_access_callback';
     $items['item_y']['access callback'] = 'mymodule_menu_access_callback';
}
function mymodule_menu_access_callback() {
  global $user;
  if ($user->uid == 1) {
    return FALSE;
  }
  return TRUE;
}

```

# Answer
> 0 votes
User 1 bypass access controls, so that wont work. You could have 2 menus as blocks and use the block system to control which to use.

You could also use theming/CSS to hide the menu.

# Answer
> 0 votes
what googletorp says is true but even more generally, you can't remove permissions to anything in drupal once they've been granted to a user (and user 1 is given all permissions).

i guess it depends whether you're just trying to hide it from display, in which case what googletorp suggests will be sufficient, or if you're actually trying to revoke access to a url from admin users.

a simple workaround (in addition to the suggestions from googletorp) to stop admins visiting said page would be to create a redirect using Rules that sends users with the admin rule somewhere else on that page.

# Answer
> 0 votes
You could assign a specific permission to the menu item, and then give that permission to a role that your non-admin users have.

$items\['item\_x'\]\['access arguments'\] = array('my special permission for this menu item');

hook\_menu http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook\_menu/7

This will work, but keep in mind uid 1 (aka super admin) bypasses access control.

---
Tags: 6, routes
---


# Question
Title: Different CSS files for different browsers
Ideally, if all of the CSS files used should be defined in the theme's .info file, how would I go about using different CSS files for different browsers?

# Answer
> 5 votes
The Conditional Stylesheets module allows themes to easily add conditional stylesheets to a theme's .info file.

This module is already used by the Zen, Layout Studio, and Tendu themes.

# Answer
> 3 votes
Put this in your info file

```
  ; Set the conditional stylesheets that are processed by IE.
  conditional-stylesheets[if IE][all][]       = css/ie.css
  conditional-stylesheets[if lte IE 6][all][] = css/ie6.css

```

This is taken directly from the Zen theme for Drupal 6.

# Answer
> 1 votes
You could use the CSS Browser Selector module which allows you to write cross-browser CSS using selectors like `.ie7`, `.ie`, `.ff`, `.safari`, etc.

---
Tags: 6, theming
---


# Question
Title: set new content-type as product in ubercart
When I install Ubercart, it creates a new content type ("Product"), and uses it for handling products.

Can I create another content type, and use it as product?

# Answer
> 2 votes
Yes, you can. It is a bit confusing the first time you try, as Ubercart terminology is different for some reason; they call it *product class*, but it is just a new content type.

---
Tags: 6, ubercart
---


# Question
Title: Specification of an Image field attached to forum topic node type?
I have somehow a strange issue with Fields : I've created an Image field for each of my content types. This image field allow the insertion of images into the node body with Insert and Colorbox. Everything work as wonder for all the content types... except for forum topics.

Indeed, when creating a new forum topic, my users can't see the Image field in the form. Also :

* Admin can see it, but not other users
* Users can perfectly see Image field when creating a new content of other type.

I've also checked : it's not a question of CSS or other modules hooking the field.

**Do you have any idea of what has to be done ?! :/**

# Answer
have you created one image field that is shared between all of your content types, or a different image field for each content type? if it is the latter, this sounds like it is likely a permissions problem where one of the image fields is restricted to admin users only.

i'm not sure about D7, but there's a module in D6 called "content permissions" that seems like you should enable it but you really should avoid it if you can. There's probably an equivalent in D7 - the module denies access to all new fields for all user roles by default, and you have to explicitly give permissions back.

alternatively, it could be a caching issue. Drupal caching is much less aggressive for admins than for anonymous users so if you've made a few changes to your views that admins can see but anonymous can't, try clearing your site's cache.
> 1 votes

---
Tags: 7, entities, media, nodes
---


# Question
Title: How to create content type programatically
how to create content type programatically and attach field api fields to it? hook\_node\_info() will not work for me since i want to create my node type and its instance in a single method (for testing purposes), so kindly suggest a solution other than hook\_node\_info(). Thanks

# Answer
> 0 votes
To create a node type, call node\_type\_save(). Have a look at the documentation of the Fields API for information on how to attach fields to the node type.

---
Tags: entities, nodes
---


# Question
Title: How do I check if a link exists in a page?
There is a form having a link clicking on which field set will be collapsed to show fields under it. HTML is shown as below.

```
<span class="fieldset-legend">
  <a href="#" class="fieldset-title">
    <span class="fieldset-legend-prefix element-invisible">Hide</span>
    Attach
  </a>
<span class="summary"></span></span>

```

How would I go about checking if this link exists (to click on it), and the fields under it are shown?

# Answer
> 1 votes
To answer my own question, I realized (even without clicking on the link) that fields can be asserted by `DrupalWebTestCase::assertFieldByName()`.

---
Tags: 7, testing
---


# Question
Title: hook_user_login, hook_user_logout not firing
I created a custom module because I want to execute some actions when a users logs in / out.

```
function mymodule_user_login(&$edit, $account) {
  $url = 'https://www.some_url';
  $additionalHeaders = '';

  $process = curl_init($url);
  curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
  curl_setopt($process, CURLOPT_HEADER, 1);
  curl_setopt($process, CURLOPT_USERPWD, $user.":". $password);
  curl_setopt($process, CURLOPT_TIMEOUT, 30);
  curl_setopt($process, CURLOPT_POST, 1);
  curl_setopt($process, CURLOPT_POSTFIELDS, $data);
  curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);

  curl_close($process);
}

function mymodule_user_logout($account) {
  $url = 'https://www.some_url';
  $additionalHeaders = '';

  $process = curl_init($url);
  curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
  curl_setopt($process, CURLOPT_HEADER, 1);
  curl_setopt($process, CURLOPT_USERPWD, $user.":". $password);
  curl_setopt($process, CURLOPT_TIMEOUT, 30);
  curl_setopt($process, CURLOPT_POST, 1);
  curl_setopt($process, CURLOPT_POSTFIELDS, $data);
  curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);

  curl_close($process);
}

```

I tested the code before to put it in the hook implementations, and it works.

Does anyone have the same problem?

# Answer
If you are directly editing the code of a module that is already enabled, then the problem is that the list of hooks implemented by modules are cached by Drupal. Drupal doesn't have a setting for disabling this cache; the only cache you can disable/enable on Drupal is for the content served to the anonymous users.

Both the hooks you are referring are invoked by functions that, directly or indirectly, call module\_implements(), which contains the following code:

```
  if ($reset) {
    $implementations = array();
    cache_set('module_implements', array(), 'cache_bootstrap');
    drupal_static_reset('module_hook_info');
    drupal_static_reset('drupal_alter');
    cache_clear_all('hook_info', 'cache_bootstrap');
    return;
  }

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

```

The cache containing the list of the implemented hooks is cleared when a module is updated, enabled, or disabled. Actually, it is enough you visit the page showing the list of the modules, click on the button to save the configuration, and the cache should be automatically reset; if that doesn't work, then you can disable and then re-enable a module.

I see the code is using variables that are not defined, nor set, by the code you are showing; I take you didn't show all the code, but if you are effectively showing all the code, then the `$user`, `$password`, and `$data` variables are not initialized.

As side note, you should use drupal\_http\_request(), instead of using the cURL functions.
> 4 votes

# Answer
It sounds like Drupal isn't aware of your new hooks. When you add new hooks to a module you need to clear your caches. If you're using drush run `drush cc all` or in your browser visit http://example.com/admin/config/development/performance
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: Pre-Populating a CCK Flexifield/Multigroup?
I'm using a repeating fieldset module (Flexifield, somewhat similar to CCK3 Multigroup) to create a measurement sheet content type. In this, the user is allowed to create an unlimited number of rooms, each defined by five fields: *name*, *level*, *width*, *length*, *area*.

It would be really useful to pre-populate about ten of these rows (e.g. "Kitchen," "Bathroom," "Living Room").

How would one go about programmatically creating and filling CCK fields with number of values set to "Unlimited"?

# Answer
Use the Prepopulate module.
> 1 votes

# Answer
In your custom module's form alter function, you can use this code to alter a multivalue field. I use the form inspect module so I can find the form structure of each field. I haven't tested this as a flexifield, but I think it will still work.

```
$form['field_name']['0']['#default_value']['value'] =t('hello');

$form['field_name']['1']['#default_value']['value'] =t('world');

```
> 1 votes

---
Tags: 6, nodes, entities
---


# Question
Title: How can I make my entity controller class fetch the fields that have been programmatically attached?
I've created a field, an instance of it, and attached it to a bundle that I've defined in hook\_entity\_info().

When I call up a new entity using `entity_get_controller('module_content')->create($type)`, it doesn't have any field attached.

I've heard that I have to call field\_attach\_load(), but that requires an ID for the entity. I'm wondering how to fill out the data for the fields that I've attached to my bundle with a newly created instance of that bundle.

The `create()` method is the following one:

```
  /**
   * Create a default module_content.
   *
   * @param $type
   *   The machine-readable type of the module_content.
   *
   * @return
   *   A module_content object with all default fields initialized.
   */
  public function create($type = '') {
    return (object) array(
      'cid' => '',
      'type' => $type,
      'crc' => '',
      'class' => '',
      'conid' => '',
    );
  }

```

# Answer
> 5 votes
Fields are attached to instances of entities; that is the reason why `field_attach_load()` requires an entity ID.
Suppose you want to attach a field to a node; without knowing which node is, how do you know what value to use for the field?

`DrupalEntityControllerInterface`, the interface that all the entity controllers implement, doesn't define the `DrupalEntityControllerInterface::create()` method, but it defines the DrupalEntityControllerInterface::load() method, that is implemented by DrupalDefaultEntityController in DrupalDefaultEntityController::load(), which in turn calls DrupalDefaultEntityController::attachLoad(). The documentation for this method contains the following paragraph:

> Attaches data to entities upon loading. This will attach fields, if the entity is fieldable. It calls hook\_entity\_load() for modules which need to add data to all entities. It also calls `hook_TYPE_load()` on the loaded entities. For example hook\_node\_load() or hook\_user\_load(). If your `hook_TYPE_load()` expects special parameters apart from the queried entities, you can set `$this->hookLoadArguments` prior to calling the method. See NodeController::attachLoad() for an example.

If your entity controller extends `DrupalDefaultEntityController`, then the code for attaching fields to the entity instance is already implemented in that class, and you don't need to write extra code.

For the code to use when saving the entity, you can take node\_save() as example. You will notice that the function contains the following code:

```
// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

//...

// Call the node specific callback (if any). This can be
// node_invoke($node, 'insert') or
// node_invoke($node, 'update').
node_invoke($node, $op);

// Save fields.
$function = "field_attach_$op";
$function('node', $node);

module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

```

The code calls field\_attach\_insert(), or field\_attach\_update(); those functions are responsible for saving the fields in the appropriate database tables.

The default implementation of an entity controller doesn't have support for saving an entity; there is a third-party module that implement the support for saving entities: the Entity API module.

> * The module provides API functions allowing modules to create, save, delete, view or to determine access for any entity, i.e. `entity_create()`, `entity_save()`, `entity_delete()`, `entity_view()` and `entity_access()`.
> * The entity API introduces a unique place for metadata about entity relationships and entity properties: `hook_entity_property_info()`. This information about entity properties contains the data type and callbacks for how to get and set the data of a property. Modules may rely on this information in order to support any entity property, e.g. Rules and the Search API build upon that.
> * Furthermore the module provides data wrappers that make use of the available information to provide a simple and unified access to entities and their properties. For usage examples have a look at the README or the provided tests.
> * Beside that, the module helps you defining a new entity type. For that, it provides an entity controller, which implements full CRUD functionality for your entities. Optionally, entities may be created based on classes derived from the provided Entity class.

---
Tags: 7, entities
---


# Question
Title: how i can create pages dynamically on users any action?
I want a page creation(dynamically), if user uplooads a design(image) which is (or its info) goes to database. The page name should be on the name of design. How can i do this?

**Update:** Designs(dress designs\[images\] ) are submitted by the users through an application which resides on the root of drupal. Not a module of drupal. As the designs are submitted, they goes to a folder at root and relative info goes to drupal database. As i am using drupal bootstrap to get user info and a little more. So i need a module which listens the request from application(may listen from database updation) and make page of that design with unique path. Please guide me how to handel this situation

any hint/help is appreciated

# Answer
this is how one can do so. First make a content type (also can use *Basic Page* type). Then the below code will make pages(nodes of the content type) dynamically.

```
<?php
// Construct the new node object.
$node = new stdClass();

// Your script will probably pull this information from a database.
$node->title = "My imported node";
$node->body = "The body of my imported node.\n\nAdditional Information";
$node->type = 'mynewpage';   // Your specified content type
$node->created = time();
$node->changed = $node->created;
$node->status = 1;
$node->promote = 1;
$node->sticky = 0;
$node->format = 1;       // Filtered HTML
$node->uid = 1;          // UID of content owner
$node->language = 'en';
// If known, the taxonomy TID values can be added as an array.
$node->taxonomy = array(2,3,1,);

node_save($node);
?>

```

if you need to create nodes at root of Drupal directory you also need to include these lines in start of the code

```
// Bootstrap Drupal
require 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```
> 0 votes

---
Tags: 7
---


# Question
Title: Create a new user from an entry submitted with the module "webform"
i'm using the module webform so that user can ask for the credentials to login to the site. I need to add a button to the the "view" of each submission so that the user that it's viewing that submission can create a user.

Do i have to modify the code of the module to achive this or should i write my own module? If i write my own module what hooks should i implement to add the button, the logic for the button to be present only if i didn't create a user, and the custom action for that button?

# Answer
> 2 votes
I am also looking for a similar solution and would like to reuse an existing one. To assign a role on registration I would try some of existing modules.

Let me summarize what is available:

### To allow a user to choose a role on registration

### To provide a role using a key during registration

### Sold Memberships

### Join role with a password

### Apply for role

### Webform register

See also integration Webform and registration module.

# Answer
> 0 votes
Btw I've not used D7 in anger, so YMMV.

This is not a direct answer to the question :) but you know Drupal has a built-in mechanism for people to create accounts and then administrators approve (or not) them? I would've thought it would make more sense to try and customise that functionality, rather than trying to recreate it with webform.

A direct answer to your question is to check out webform\_hooks.php and specifically hook\_webform\_submission\_actions which lets you create custom actions to be performed on submissions (such as the built-in *Print* and *Resend e-mails*).

# Answer
> 0 votes
It doesn't seem like a Webform submission necessarily needs to create a new user completely. It sounds to me like you just need to have a separate "verified" role for users whose accounts have been separately verified. Poviding verification with a role will allow you to control access permissions based on user levels and is the appropriate way of handling such a task. This can be done with existing, well tested modules via a webform as suggested along with the help of Rules and Webform Rules. Simply create a Webform with your desired fields for allowing a user to apply for th "verified" role and upon submit you can invoke Rules actions to accomplish whatever is necessary - like sending an email to the site administrator or adding the "verified" role to the submitting user's account.

---
Tags: 7, users, webforms
---


# Question
Title: Services 7.3 - Simple Resource Example works only with GET not with POST from Poster
I created a very simple test service here is the code, for some reason only GET works with it in Firefox Poster, but POST returns a 404 Controller not found. Any tips? Here is what works http://mysite.com/services/myendpoint/mytest/retrieve/

with parameter of id = 1

```
<?php

/**
 * Implementation of hook_services_resources().
 */
function mytest_services_resources() {
  return array(
   'mytest' => array(
     'retrieve' => array(
       'help' => 'Retrievs a test',
       'callback' => '_mytest_retrieve',
       'args' => array(
         array(
           'name' => 'id',
           'type' => 'int',
           'description' => 'The id of the test to get',
           'source' => array('path' => '0'),
           'optional' => FALSE,
         ),
       ),
     ),
   ),
  );
}

/**
 * Callback for creating  resources.
 *
 * @param object $data
 * @return object
 */
function _mytest_retrieve($id) {
  return "READY TESTING";
}

?>

```

# Answer
> 5 votes
You need separate callbacks for each of the CRUD operations. You've only implemented 'retrieve', which is the GET callback, you need to implement a 'create' callback for POST to function.

Reading the docs really helps: https://drupal.org/node/783460

# Answer
> 1 votes
you can't POST for any retrieve method.

Post is only for actions, and create methods.

you can read WAY more about it here. http://drupal.org/node/783254

---
Tags: services
---


# Question
Title: What are the pros and cons of using Acquia Drupal install packages?
My firm is considering using the Acquia Drupal install packages at http://acquia.com/downloads as a default boilerplate to start with for new client sites. What are the pros and cons of taking this approach?

# Answer
> 5 votes
Boris Mann once described Drupal as a big box of Lego. Acquia Drupal is just a bigger box of Lego. It still doesn't do anything out of the box, it just gives you more pieces. Given how much stuff went into Drupal 7 core it is mostly redundant - download core, views, wysiwyg and admin and you can start building good sites.

In terms of pros for Acquia Drupal I'm struggling a little. The first is that it helps inexperienced users get onto the Acquia Network. The other is that you don't have to download everything, but this is also a con as you get everything Acquia thinks you need.

One of the biggest cons as I see it is that they dump all the modules under modules/ which is considered bad practice in the Drupal community. Not only is this annoying if you decide to switch back to stock Drupal + contrib or Pressflow + conrib, but it teaches users bad practices from day 1.

I must admit I played with it once and decided against using it. These days I assemble my code using drush make as it gives me only what I want and I'm not dependent on a third party to provide security releases after a module is updated I can just update my make file and reroll my stuff.

\[rant\]These days the community has moved on to building true distros, not just throwing more Lego pieces in a box.\[/rant\]

# Answer
> 1 votes
If I understand, according the datasheet of Acquia, http://acquia.com/files/marketing/Acquia\_Overview\_datasheet-web2.pdf Drupal Acquia has the same Drupal core, but include preinstalled modules and configurations to get versions of Drupal ready to common needs.

Accordign this, about pros, I think that with Drupal Aquia you will have guidance an experience in the selection of modules and configurations, also time savings. Cons, I do not see cons related specifically with your question.

It is my opinion. I will pending of other opinions to learn about other points of view.

see other opinions http://groups.drupal.org/node/17838

# Answer
> 0 votes
**Pros** would be a setup which is primed and ready for a number of uses including addtional contrib modules which are commonly useful...

**Cons**, its generic so it might include some configuration / modules which you will need to remove...

In most cases it will not be a problem and will give you a simple head start on development

# Answer
> 0 votes
Using Acquia Drupal is like having automatic transmission in your car. It takes care of a bunch of things so that you don't have to worry about them. However, if you'd like more control (e.g. specific versions of modules), then you better go with standard Drupal.

One of my clients wanted to go with Acquia, so we did, but it was necessary to drop it later because we needed more up-to-date versions of contributed modules.

---
Tags: installation
---


title: Detect when user accesses the site

text:
# Question
Title: Detect when user accesses the site
I would like to perform an actoin if the user's last access time was last month.

Would this be through hook\_user(), when `$op` is equal to "after\_update"?

I assume the last access variable would be updated, and I could check.

# Answer
Drupal saves the timestamp of a user's last access, but by the time your can react to a user visiting the site, that value has already been overwritten with the current timestamp (that happens in sess\_write()). I don't have a cut-and-paste solution for you, but there are some ideas how to store the previous timestamp for later use in this forum topic.
> 1 votes

---
Tags: users
---


title: Permissions on remote server problem

text:
# Question
Title: Permissions on remote server problem
I have this error message:

```
The specified file temporary://fileYU5WGQ could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

```

I know it's a folder permission problem. But I can't figure out which folder is the cause.

In **sites/default/files** I have these three folders, all of them with permission set to **777**:

tmp

temp

temporary

Then I don't know where is the problem?? I attached a image capture of the sistem file setting:

# Answer
> 1 votes
Did you check what user is the owner of each of your folders in question ? Use chown username:groupname to change owner/group of a folder.

---
Tags: 7, users
---


# Question
Title: Programmatically search nodes according to the value of fields in their bundle
I am working on a script to search groups within the site according to criterias, such as group city, group languages and so on.

So far i am trying to do this by manually querying the database though it s seems to be an unnecessary hassle since the fields i am searching all live in different table like field\_data\_field\_city, field\_data\_field\_language and it can get very tedious task.

So i am wondering if i could to that programmaticaly using views so that it returns me all the NID according to the filters i mentioned above. i'd rather not use views UI as later this data is populated to the page via a Jquery templating system witch is already in place so the best would be to just get all the NID that match my selection.

If anyone had any incite / experience on how i should go to achieve this result would be much appreciated .

# Answer
Personally I would stick to writing your query manually instead of using Views.

This way you have much more control over the final query, and in most scenarios you should be able to make it much smaller (and thus much faster) than that created by Views - by joining only with tables you really need to join in a specific situation, while Views will always do all the joins required by all possible scenarios.

Also, this way you could return the result formatted whichever way you want, without the need of installing additional modules, which is just unnecessary overhead.

IMHO. :)
> 2 votes

# Answer
I think I would just create a view the normal way, using contextual filters (arguments) to filter the results, and use Views Datasource to make the view output json.
> 1 votes

---
Tags: 7, search
---


# Question
Title: Is it possible to define a hook_preprocess function based on entity type such as profile2?
I walked through the possible hooks by using function `hook_preprocess(&$vars, $hook)` and only entity was available to use. Is it possible to do something like `hook_preprocess_profile2_entity()`, or do I have to write an if condition to check the entity type in `hook_preprocess_entity()`?

# Answer
> 15 votes
This adapts the Zen theme pattern for node preprocess functions to entities:

```
<?php

/**
 * Implements template_preprocess_entity().
 *
 * Runs a entity specific preprocess function, if it exists.
 */
function MYTHEME_preprocess_entity(&$variables, $hook) {
  $function = __FUNCTION__ . '_' . $variables['entity_type'];
  if (function_exists($function)) {
    $function($variables, $hook);
  }
}

/**
 * Profile2 specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_entity_profile2(&$variables, $hook) {
}

/**
 * Field Collection specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_entity_field_collection_item(&$variables, $hook) {
}

```

---
Tags: theming
---


title: Running cron without crontab

text:
# Question
Title: Running cron without crontab
I want code to be executed every n minutes. I know there is a way to run cron in Drupal with crontab but in my case it runs every 3 hours.

What would be the best way to achieve this without using crontab? Can I execute code every time a user opens the first page?

# Answer
> 2 votes
For Drupal 6 there is Poormanscron module that runs the Drupal cron operation using normal browser/page requests instead of having to set up a crontab to request the cron.php script. If you use Drupal 7 this functionality is included into core. There are external online services that offer online task scheduling such as www.webbasedcron.com You could also try Elysia Cron or Ultimate Cron modules for more control.

# Answer
> 3 votes
The simplest solution would be to set the cron to run more frequent: every 3 minutes is not unheard of.

However, many modules, including core, do not have a timecheck: they run their code regardless of how long it was since they last ran it. Other modules (also many core) have some "run only every X" implemented.

You will see an impact, but depending on your specific situation, that may, or may not be a problem.

Once that is done, you can implement `hook_cron()`:

```
function yourmodule_cron() {
  $last_run = variable_get('mymodule_cron_last_run', REQUEST_TIME);

  if ($last_run <= (now() - 180)) {//180 seconds is three minutes.
    # DO SOMETHING EPIC!
    variable_set('mymodule_cron_last_run', REQUEST_TIME);
  }
}

```

If, however, you cannot run cron this often, you may want to write a cron bypass. In Drupal 6, the route would be, to create a menu-item, with a "secret" token in it (to avoid external folks from hitting that URL by accident/to overlad your server). In Drupal 7 there are (not well documented, AFAIK) methods to create thin requests: my code below will bootstrap an entire Drupal, while you may need only a very simple database-query to be ran without accessing any Drupal resources or APIs.

```
/**
 * Implementation of hook_menu().
 */
function mymodule_menu() {
  $items = array();

  $items['yourmodule/cron/s0mes3cr3tkey'] = array(
    'title'            => 'not used',
    'description'      => 'not used',
    'page callback'    => 'yourmodule_do_epic_stuff',
    'type'             => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Menu Callback that does epic stuff.
 */
function _mymodule_do_epic_stuff() {
  # Do Epic Stuff.
}

```

You can then add an additional crontab to call only that url.

It is a very bad idea to run such code in the request of a user:

1. You don't know if users are visiting every 3 minutes. Even if you have 1000visitors per minute, there are potential situations where no user visits for, say 10 minutes.
2. You don't want your users to be bothered with maintainance code you run in their request.
3. You don't want your users to experience faults or errors in your cron-tasks. These tasks can, e.g. check whether some external API is up or down and throw errors on network trouble and such.

---
Tags: 7, cron
---


title: Multiple aliases with single login

text:
# Question
Title: Multiple aliases with single login
I have three domains that are pointing to the same website like this:

example.com example.org example.net All of those work from the same db. But If I login to the example.com website and then go to example.org I have to login again.

The second question: If I'm logged in example.com and then go to www.example.com I have to login again! Is it a server that misconfigured or what should I do?

# Answer
If you want a simple solution I can suggest what I did before is to redirect both domain.org and domain.net to domain.com using .htaccess redirect rule then all users will be reffered to domain.com first and then log in once there.

You need something like that in .htaccess (or simillar in your httpd configuration file):

```
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com [NC]
RewriteRule ^(.*)\.html$ http://domain.com/$1.html [R=301,L]

```

Or do you need more complex set up and have separate 3 domains with single sign on ? Then try to use Domain Access module (http://drupal.org/project/domain).
> 2 votes

# Answer
Pretty sure you are running into problem with the cookie domain.

There are a few ways to deal with it. This article provides a start, as will googling for "drupal cookie domain".

Personally, I would always run a site a canonical domain, and redirect the multiple domains to a single one, and pick whether you want the leading www or not. This will solve most of your problems (unless you really do want the multiple domains).

You can put something like this in your `.htaccess` or Apache config.

```
# canonical URL redirection to www.domain.com
RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

```

Just remember to save your `.htaccess` when you update Drupal if you stick this rule here.
> 0 votes

---
Tags: users
---


# Question
Title: Assign all permissions to a user programatically
Is there a way to assign all the permissions to an authenticated user through code, I want to do it in unit tests.

# Answer
You could use rules - when a user is created (could include certain contextual requirements) then all the roles are added.

or the less tidy way

You could get all the roles from the DB and then insert each into the user\_roles table.

Something like:

```
$userID = 'ENTER UID';
$query = db_select('user_roles', 'r')->fields('r')->execute();

while($role = $query->fetchObject()){
    db_insert('user_roles')->fields(array('uid' => $userID, 'rid' => $role->rid))->execute();
}
drupal_static_reset('user_access');  /* Flush the caches */
drupal_static_reset('user_role_permissions');  /* Flush the caches */

```

The code is untested but should be a good foundation.

You can also do the same in Drupal by loading the user object and making the changes, but the above will do the same.
> 1 votes

# Answer
Please see if this helps answer your question:

You could add permissions to an user using this code

> `$this->drupalCreateUser(array('access content', 'create page content'));`

Here is a link for more information on this subject.
> 0 votes

# Answer
If I understand well your scenario, I think that you can review this way to create a role with permissions http://drupal.org/node/271234#comment-3381548 (I think that this way is easy to understand and test). Then assign the user to the role:

http://mattdanger.net/2009/12/programmatically-create-users-in-drupal-6-x/

http://grahammickle.com/blog/php/assign-user-role-programmatically

http://drupal.org/node/28379
> 0 votes

---
Tags: users, testing
---


title: Customize search output

text:
# Question
Title: Customize search output
I was trying to modify the search results page using a preprocess function:

```
function arras_preprocess_search_result(&$variables) {

    $type = $variables['result']['node']->type;
    $variables['search_results'] = '';
    $nodeTypes = node_type_get_types();
    $resultTypes = array();

      $resultTypes[$type][] = $variables['result'];

    foreach ($resultTypes as $resultType => $resultTypeResults)
    {
        echo $resultType;
        $value = "";
        // loop through entries
        foreach ($resultTypeResults as $result)
        {
            $value .= theme('search_result', $result,$resultType);
        }

        // add fieldset
        $variables['search_results'] .= theme('fieldset',
            array(
                '#title' => $nodeTypes[$resultType]->name,
                '#collapsible' => TRUE,
                '#collapsed' => FALSE,
                '#value' => $value,
            )
        );

    };

}

```

but I get this error:

```
( ! ) Fatal error: Unsupported operand types in L:\wamp\www\drupal\includes\theme.inc on line 830

```

i.e on the line

```
        $value .= theme('search_result', $result, 'cameras');

```

What is wrong?

# Answer
From the Drupal 7 API theme\_search\_result:

> This function is never used; see the corresponding template file instead.

Try overriding the page using search-result.tpl.php
> 2 votes

---
Tags: theming
---


title: Limiting term selection

text:
# Question
Title: Limiting term selection
I have a few OG Groups and now I want to limit the taxonomy term selection for each group. For the first part I'm planning on checking if the user is a member of a certain group and then proceeding accordingly. So far, so good. The problem is, that I really have no idea how to actually limit the term selection. I tried something with the form api, but I just keep getting fatal errors when saving a node.

So... Can you guys help me limit the term selection? Telling me what do I actually need to do would really help. Thanks.

# Answer
There is **OG Vocabulary** module for D6 (and just a basic D7 port) that

> "provides each Organic Group with its own vocabularies (i.e. taxonomy). This lets groups logically segregate their content into categories which make sense for them. This module is integrated with Token, Rules and Services modules." read more...
> 2 votes

---
Tags: taxonomy-terms, forms
---


# Question
Title: How to display Facebook friend count on your Drupal site
I was hoping for some insight as to how I should go about getting my Fan Page friend count to display on my Drupal driven site.

Are there any good tuts out there?

Any help would do

Thanks!

# Answer
> 1 votes
Mind you I have the Drupal for Facebook module installed. So this is what I did:

```
function facebook_count($username) {
$url = "https://graph.facebook.com/".$username;
$fbData = json_decode( file_get_contents( $url, 0, null, null ), true );
return intval($fbData['likes']);
}

```

I then displayed it via:

```
<?php echo number_format(facebook_count('Fan_Page_ID') ); ?>

```

Hope this helps!

# Answer
> 0 votes
It's a non-drupal thing. When you login in your facebook fan page, you find instructions to style and get copy n' paste Javascript/iframe code to put a "fan box" or a "like box" in your web pages: http://developers.facebook.com/docs/reference/plugins/like-box/

---
Tags: 7, social-network
---


title: Restrict nodes and terms per user

text:
# Question
Title: Restrict nodes and terms per user
First of all, I'm using Drupal 6.

I'm developing a website where I want the users to automatically have their own "group"; this means they are only able to see their own nodes. If another user creates an account, he won't have access to other users' nodes. Also, users can add new terms to some fields (using "Hierarchical Select") and I want it to be restricted to each user too.

I also want a user (lets call it "user A") creates another user and they can have access to the user A's "group"; this means that they can see user A's nodes and terms.

I was looking for the Organic Groups module, but it doesn't seem able to do this. If it is, I don't know how to do that.

Do you have any suggestion?

# Answer
> 1 votes
To create something both so specific and complex, you probably won't be able to find modules that will solve this problem for you 100%. So to be able to do this you will have to develop some of this yourself (or pay some one to do it for you)

You best bet will be to start of with organic groups, rules might also help. The fact that you want users to be able to create other users complicate things, as that is something usually done by admin users. Most likely you will have to create your own custom form to handle this.

# Answer
> 1 votes
You could try to have a separate subdomain for each group or try to use Spaces module.

Possible solutions for this:

* Drupal Commons
* Open Atrium
* Organic Groups and Spaces (D6, D7 port in progress)

> ## Spaces 3.x
>
> Spaces is an API module intended to make configuration options generally avaliable only at the sitewide level to be configurable and overridden by individual "spaces" on a Drupal site. It has been described as:
>
> * A way to make one Drupal site act like several sites
> * A way to provide much more configurable, full-feature Organic Groups or user homepages
> * A generalized API for contextual configuration"

*(Spaces 3.x README.TXT)*

Read more

---
Tags: 6, organic-groups, users, taxonomy-terms
---


# Question
Title: How to create node and reference it in Drupal 7?
> **Possible Duplicate:**
> Options for “create and reference”

How can I put a link "Add another item" on a node edit page that would create a new node and reference it at the same parent node ?

Also, I need to put Edit link beside the new created & referenced node.

I found modules like the Popups API and Popups: Add and Reference, but, sadly they are not ported to D7

Thanks for any hints!

# Answer
> 2 votes
http://drupal.org/project/noderefcreate

This one is available for D7, and allows you to create & reference nodes within the create / edit form for another node type. Unlike the popups\_reference module, it will only allow you to create the extra nodes with titles (no other fields). You could, however, use this and then write a small custom module that uses `hook_form_alter()` to redirect the user to the edit forms for newly-created nodes to enter the rest of the information.

Not as nice as popups\_reference, but it should work.

# Answer
> 0 votes
I'm not sure what are you trying to do, Samir. Have you tried Node Reference URL Widget (http://drupal.org/project/nodereference\_url)

If it's not the right one, explain a bit more what are you trying to do.

---
Tags: nodes
---


title: Need help with template_preprocess_node

text:
# Question
Title: Need help with template_preprocess_node
I have a block with a select box and submit button. The main purpose of the select box is to store a variable in the session. I used template\_preprocess\_node to filter contents based on user selection.

```
function blackout_preprocess_node(&$vars) {
  $node = $vars['node'];

  // define a variable to hold your rendered content
  $newContent = "";

  if($_SESSION['myid'] == '1' && $node->field_field1[0]['value'] != '') {
    $newContent = $node->field_field1[0]['view'];
  } else if($_SESSION['myid'] == '2' && $node->field_field2[0]['value'] != '') {
    $newContent = $node->field_field2[0]['view'];
  } else {
    $newContent = $node->body;
  }
  if (strlen($newContent)) $vars['content'] = $newContent;
}

```

Everything is working fine except I have to click submit twice to reload the page contents or I have to move to another page to see re-loaded content. How can I reload content with just one click?

# Answer
Blocks are rendered in `hook_preprocess_page`. At that time, all implementations of `hook_preprocess_node` have already been executed, so you cannot influence how the node is displayed (apart from messing with the HTML in `$vars['content']`).

If you use Drupal's Form API to implement the select list and the submit button, Drupal will redirect you after submitting the form, so you do not need to reload the page manually. See Post/Redirect/Get for why it is generally a good idea to redirect after a HTTP Post.
> 1 votes

---
Tags: 6, nodes, theming
---


# Question
Title: Programmatically create a block region in Drupal 7
I am stuck with programmatically creating of regions in Drupal 7. I know how to create regions in .info file, but my problem is that I want regions for every node I create, to show a specific block to each and every node differently.

I am interested in Drupal 7 only. If it is possible by creating a module, that is a solution that interests me, too.

# Answer
1. Edit your theme .info file to add the following line:

```
regions[youregionname] = Your Region name

```
2. Edit your template file (e.g. "page.tpl.php"), and add the following lines:

```
<?php if(!empty($page['youregionname'])) : ?> <!--check if region enabled-->
  <div class='my-new-region-class' >   <!--add class to my region-->
    <?php print render($page['youregionname']); ?> <!--print the region-->
  </div>
<?php endif; ?>

```

After editing the files, don't forget to clear the cache.
> 6 votes

# Answer
You still need to create your regions in your theme's `.info` file, as far as I know there's no way around that short of manually adding these new regions to your database. After that get the Node Blocks module which will help you decide which blocks are shown for which nodes, and what regions they are placed in.
> 1 votes

# Answer
As maged adel said, you need to create regions in the .info file and then use these variables in the page.tpl.php file and create blocks from the admin section and then place it on the regions and make it different for different nodes.
> 1 votes

---
Tags: 7, blocks, theming
---


# Question
Title: Adding Ajax to Webforms in Drupal 7 - Ajax Submit
I'm using Webforms 3.x and Drupal 7.x.

I'd like to be able to use Drupal 7's Ajax features to provide a confirmation message via Ajax on submit.

To achieve this, I'm hoping to modify my form using a HOOK\_form\_alter.

The $form array provides the submit element at `$form['actions']['submit']`. If I add an `['#ajax']` attribute here, the action takes effect when submit is actioned by the use, and the callback function specified is called.

It seems that webform initiates two callbacks from

`$form['#submit'][0] = webform_client_form_pages`

`$form['#submit'][1] = webform_client_form_submit`

My question is, how can I initiate the necessary webform callbacks on Ajax submit? I'm not totally familiar with webform, or how it deviates from standard FAPI (or if it does at all).

Any advice appreciated.

# Answer
See this page on drupal.org for info
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: How to provide upload function for users
> **Possible Duplicate:**
> How to allow users upload images to existing nodes?

How might I go about providing a page for authenticated users to upload image files to the server?

# Answer
You have a few options:
> 1 votes

# Answer
use the image module, it will let you attach images to nodes as well as to create image content, you can go to user permissions to assign the image create and image attach privilege to authenticated user role.
> 0 votes

---
Tags: files
---