# Question
Title: How can I print a field from a referenced entity in my theme?
I'm trying to print a field from an entity reference field - but I don't have a clue how to do it!

A bit of background: I've got two content types - master and variation. Variation includes an entity reference field, pulling in fields from the referenced master. But they share an image field. When the variation's image field is empty, I need the master's to display in its place. On the other hand, if the variation's image-field is in use, the masters needs to be hidden. My first thought was to use a display mode, but as you can see I need a little more flexibility than that.

So the details.

A dpm($node) on a variation node gives me:

---

**... (Object) stdClass**

**field\_master\_reference (Array, 1 element)**

**--und (Array, 1 element)**

**----0 (Array, 3 elements)**

------target\_id (String, 2 characters ) 11

**------entity (Object) stdClass**

--------*(list of lots of strings which I'll leave out for concision)*

--------field\_country (Array, 1 element)

--------field\_publisher (Array, 1 element)

--------field\_catalog (Array, 1 element)

**--------field\_main\_image (Array, 1 element)**

----------und (Array, 1 element)

------------0 (Array, 13 elements)

--------------fid (String, 2 characters ) 10

--------------alt (String, 0 characters )

--------------title (String, 0 characters )

--------------width (String, 3 characters ) 518

--------------height (String, 3 characters ) 360

--------------uid (String, 1 characters ) 1

--------------filename (String, 21 characters ) testimage99\_r1\_c1.png

--------------uri (String, 38 characters ) public://masters/testimage99\_r1\_c1.png

--------------filemime (String, 9 characters ) image/png

--------------filesize (String, 4 characters ) 4627

--------------status (String, 1 characters ) 1

--------------timestamp (String, 10 characters ) 1366482521

--------------uuid (String, 36 characters ) 67gf4dbb-0a37-4ee9-893e-6g51e3et33c1

------access (Boolean) TRUE

*(miscellaneous other fields which I leave out)*

---

I've bolded the relevant structure. From it, how do I print field\_main\_image (as a fully rendered image)? Sincere thanks to anyone who can help me with something that has perplexed me since Wednesday.

# Answer
> 6 votes
You could do this using either of these:

* hook\_node\_view() in your own custom module
* hook\_preprocess\_node() in your theme template.php

Here's an example of both of these methods. The idea is the same as what rooby suggested earlier but you need to modify the **content** of the node, not the fields.

Example 1: hook\_node\_view(), can be used in a custom module.

```
    // Implements hook_preprocess_node();
    function mycustommodule_node_view($node, $view_mode, $langcode) {

      $field_name = 'field_main_image';

      // Check that the field exists in our node and that it has no content.
      // Alternatively we could check $node->type.
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {

        // Use entity metadata wrapper to gain easy access to referenced entities.
        // This method is more reliable than digging the field array.
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {

          // Get the referenced node object.
          $master = $node_wrapper->field_master_reference->value();

          // Use field_view_field to get the renderable content of the field.
          // Save this data in $node->content so that node template can output it.
          $node->content[$field_name] = field_view_field('node', $master, $field_name);
        }
      }
    }

```

Example 2: hook\_preprocess\_node(), can be used in theme template.php.

```
    // Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = field_view_field('node', $project, $field_name, array(
          'type' => 'image',
          'settings' => array(
            'image_style' => 'thumbnail',
            'image_link' => 'content',
          ),
        ));
        }
      }
    }

```

# Answer
> 1 votes
This is off the top of my head but does it work?:

```
/**
 * Implements hook_node_view().
 */
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'variation') {
    $img_lang = field_language('node', $node, 'field_main_image');
    // If the image is not set on the variation, use the master image.
    if (!isset($node->field_main_image[$img_lang][0])) {
      $ref_lang = field_language('node', $node, 'field_master_reference');
      if (isset($node->field_master_reference[$ref_lang][0]['entity'])) {
        $ref_img_lang = field_language('node', $node->field_master_reference[$ref_lang][0]['entity'], 'field_main_image');
        if (isset($node->field_master_reference[$ref_lang][0]['entity']->field_main_image[$ref_img_lang][0])) {
          $node->field_main_image[$img_lang][0] = $node->field_master_reference[$ref_lang][0]['entity']->field_main_image[$ref_img_lang][0];
        }
      }
    }
  }
}

```

---
Tags: theming, entities
---


# Question
Title: Background Process Module Limitations and Efficiency?
Drupal's Background Process module has been suggested as an alternative to Cron and Batch when heavy lifting is required. The API documentation on background process is good but does not go into details on how it actually works and its' limitations. Can someone explain how Background Process gets around the PHP timeout issue and keeps tasks alive - and whether it operates efficiently (e.g. vs. Batch).

Thank you!

# Answer
Background Process uses set\_time\_limit() to control the timeout of the subrequest. It defaults to 0 (php script does not time out, i.e. runs indefinitely).

* background\_process\_start\_locked('dontrunconcurrently', 'mymodule\_dosomething', $myvar1, $myvar2);

This should be used when you want to ensure that your background process wont run concurrently with itself. In reality the "dontrunconcurrently" is used as a key for a lock.

Background Process has no internal mechanism per se to control serial execution of background processes.

For serial execution of background processes you could take a look at Background Batch, which allows you to run standard Drupal batch jobs as background processes, or you could maintain a state within your background process function.
> 2 votes

---
Tags: 7
---


# Question
Title: How can I display comments/comment form with a custom module?
I have created a module which returns a render array via page callback in hook\_menu. The render array contains several arrays that render markup and tables (and data from a particualr node: passed in by a wildcard in the submitted URL). At the bottom of the rendered page I would like the comments and the comments form to be displayed. My plan is to get the comments via a database query, put them into an array and add them to the render array. For the comments form I was going to use the following code:

```
    $comment = new stdClass;
    $comment -> nid = $nid;
    $form = drupal_get_form('comment_form', $comment);
    return $form;

```

How do I append this to my page callback function so that my table/markup render arrays and comments/comments form appear on the outputted page?

Thanks. Hope this makes sense. I'm open to changing my plan if you think there's a better approach.

# Answer
**Solution**

To append the comments form, add this to your render array:

```
$foo = array(
    'comments' => drupal_get_form('comment_form', $comment),
),

```

Add this, just above your render array:

```
$comment = new stdClass;
$comment -> nid = $nid;

```
> 2 votes

---
Tags: comments
---


# Question
Title: how to create tabbed blocks for recent comment and recent content?
i want to create a tabbed block with two tabs . One for showing recent content and one for showing recent comments .. how can it be done in drupal 7 using only the modules ??

# Answer
Use the quicktabs module:

http://drupal.org/project/quicktabs

Install it normally, and then 'add quicktabs instance'. In the interface, select the two views you have that you want to display and add them to each of the tabs. Your new block will show up in the block menu to be placed using the blocks menu or other layout solution.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Moving site to another domain, install appears
I move the website to another domain on the same server, by copying all files to the other domain's folder. When I visit the new domain the install.php appears. Trying to navigate to another page like /user/login redirects to the installer as well.

I don't think I need to change database settings because it's on the same server.

Any ideas why?

# Answer
> 2 votes
When install appears on a site that you expect to be fully installed, the problem is usually with the file `settings.php` (in the `sites/default/` directory).

It may be missing in action, not visible to the web server user, or unable to establish the credentials to connect to the site's database.

# Answer
> 2 votes
As Gisle said problem looks with settings.php either it has not been created or your web server has not permissions to read it,check under sites/default directory. If its not there then just copy the default settings.php and change database settings as your current database details. As a gentle reminder ensure you have .htaccess file in your drupal root directory if your server is linux based , this file will be hidden.

---
Tags: 7, migrations
---


# Question
Title: How can I ensure this block is properly cached?
I have been trying to get the some book menus displayed by nice menu, and after asking some questions on stackoverflow 1 and stackoverflow 2 settled on this code. My ultimate intention is to turn it into a module that creates blocks for different sets of books.

I am not sure whether this block will be cached so the queries are not computed every time. What additional code may be required to ensure this?

```
<?php
$master_menu = '';
unset($four_books);
  $four_books_list = "91,323,47,149";
  $four_books = &drupal_static(__FUNCTION__);
  if (!isset($four_books)) {
    $four_books = array();
    $nids = db_query("SELECT DISTINCT(bid) FROM {book} where bid in (91,323,47,149)")->fetchCol();

    if ($nids) {
      $query = db_select('book', 'b', array('fetch' => PDO::FETCH_ASSOC));
      $query->join('node', 'n', 'b.nid = n.nid');
      $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
      $query->addField('n', 'type', 'type');
      $query->addField('n', 'title', 'title');
      $query->fields('b');
      $query->fields('ml');
      $query->condition('n.nid', $nids, 'IN');
      $query->condition('n.status', 1);
      $query->orderBy('ml.weight');
      $query->orderBy('ml.link_title');
      $query->addTag('node_access');
      $result2 = $query->execute();
      foreach ($result2 as $link) {
        $link['href'] = $link['link_path'];
        $link['options'] = unserialize($link['options']);
        $four_books[$link['bid']] = $link;
      }
    }
  }

foreach($four_books as $book_nid=>$book) {
  $menu = theme('nice_menus', array('id' => $book['mlid'], 'direction' => 'right', 'depth' => -1, 'menu_name' => $book['menu_name'], 'menu' => NULL));
  $master_menu .= $menu['content'];
}
print $master_menu;
?>

```

# Answer
Why not cache it yourself? The Cache API in Drupal 7 is fairly easy to implement and it sounds as if your problem might warrant it. I had this issue with a very expensive function that was used to generate relatively static data and did a quick cache implementation to avoid having to constantly rebuild the query.

Let's say your existing function is something like this

```
function myfunction() {

   $output = (my calculations and logic);
   return $output;

}

```

A rough way to wrap this in using cache layer would be

```
function myfunction($reset = FALSE) {

  static $output;

  //some unique idenitifier for your specific record, ex. content type+nid
  $cache_key = (your logic here)

  if (!isset($output) || $reset) {

      // check whether or not output has already been cached and if so, use it
      if (!$reset && ($cache = cache_get($cache_key)) && !empty($cache->data)) {

        $output = unserialize($cache->data);

  } else {

        $output = (my calculations and logic);

        cache_set($cache_key, serialize($output), 'cache', 3600);

        return $output;

    }
}

```

The cache\_set function is the key to this, here's what each of the parameters is doing:

* $cache\_key - your unique identifier for you content
* $output - the output from your function
* 'cache' - the specific cache bin you want to use. Most likely, you'll want to use the default 'cache' bin
* 3600 - the time in seconds that the item should live before being reset. In this case, this content is set to live for one hour. You can also set it to "CACHE\_PERMANENT" to never needing reset or "CACHE\_TEMPORARY" to reset the next time the general cache is clear.
> 2 votes

---
Tags: blocks, caching, nodes
---


# Question
Title: Why isn't my custom form element theme function being called?
In my module I have a function that returns a form:

```
function mymodule_myform($form, &$form_state) {
    $form['fs_refine'] = array('#type' => 'fieldset');
    $form['fs_refine']['refine'] = array(
        '#type' => 'checkboxes',
        '#theme' => 'toggles',
        '#title' => t('Refine results by category:'),
        '#options' => array(
            1 => t('Cat 1'),
            2 => t('Cat 2'),
            3 => t('Cat 3')),
        '#default_value' => array(1, 2, 3)
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit')
    );
    return $form;
}

```

I render the form with:

```
drupal_render(drupal_get_form('mymodule_myform'));

```

I have the following functions in my module:

```
function theme_toggles($vars) {
    die;
}

function mymodule_theme_toggles($vars) {
    die;
}

function mymodule_toggles($vars) {
    die;
}

```

I want to call a theme function for my checkboxes form element so that I can customise the HTML output of each checkbox. My theme functions are obviously not being called, because my page would by dying if one of them was.

How do I fix this and theme my form elements using #theme?

# Answer
OK, so you need several things combined in order for this to work:

1. `#theme => unique_name_for_theme_function` on the form element.
2. In your template.php mytemplate\_theme() function you need to return an array something like: `array( 'unique_name_for_theme_function' => array('function') => 'myfunc') );`. This was the bit I was missing.
3. Then in your template.php you need to add a myfunc. I found it easiest to just google "Drupal theme\_form\_element", "Drupal theme\_checkboxes" or whatever, and then copy paste the code I found in to a mytemplate\_theme\_checkboxes function which I then modified to suit my needs.
4. Then you need to flush cache for Drupal to find your theme function.
> 1 votes

---
Tags: forms
---


title: Displaying titles of collapsed menus

text:
# Question
Title: Displaying titles of collapsed menus
I'm currently converting a mock-up and I need to display four menus in a list, the first two are expanded, and I need to display both the titles and menu items, and the next two are collapsed, so I need to display the titles but not the menu items. It should look something like this:

> Menu 1
>
> * Menu item 1
> * Menu item 2
> * Menu item 3
>
> Menu 2
>
> * Menu item 1
> * Menu item 2
> * Menu item 3
>
> Menu 3
>
> Menu 4

Is there an easy way to do that in Drupal's admin panel?

# Answer
> 0 votes
The "easiest" way to do this in Drupals admin panel is to set the menu titles as parent menu items and use "Show as expanded" settings (admin/structure/menu/item/yourmenuname/edit) and hide the menu-names with the block name settings (set to `<none>`)

---
Tags: 7, routes
---


# Question
Title: Problem with restricted download links (hook_file_download)
On my site I have a bunch of files that require logged-in user for download access. Well that's not about just display access, I also want to avoid passing download links around.

Having read about the performance implications of using private file system, I decided I cannot afford it so I thought I'd write a small module to control the download.

The code looks like the following:

```
/**
 * Implements hook_permission().
 */
function docwatch_permission() {
  return array(
    'docwatch download restricted documents' => array(
      'title'       => t('Download restricted documents.'),
      'description' => t('Download technical documents from secured directory.'),
    ),
  );
}

/**
 * Implements hook_file_download
 */
function docwatch_file_download($uri) {
  if (strpos(file_uri_target($uri), 'secure/docs') !== 0) {
    if (!user_access('docwatch download restricted documents')) {
      // Access to the file is denied.
      return -1;
    }
    else {
      return array('Content-Type' => file_get_mimetype($uri));
    }
  }
}

```

And I'm using this debug code to inspect what Drupal "thinks" of the link to the file it displays:

```
function MYTHEME_file_link(&$variables){
  $file = $variables['file'];
  $uri = $file->uri;

  if (strpos(file_uri_target($uri), 'secure/docs') !== 0) { // <-- part of the secure dir path
    if (!user_access('docwatch download restricted documents')) {
      drupal_add_js("console.log('no access')", 'inline');
      // Access to the file is denied.
      // return -1;
    }
    else {
      drupal_add_js("console.log('ok to download')", 'inline');
      // return array('Content-Type' => file_get_mimetype($uri));
    }
  } else {
    drupal_add_js("console.log('from unsecured')", 'inline');
  }
}

```

I then open a page where the link is displayed in two browsers, one with a logged-in status for that role, and the other - plainly anonymous. The console properly reports that difference, yet - despite that the anonymous browser is permitted to download the direct link to the document.

What am I doing wrong?

# Answer
> Having read about the performance implications of using private file system, I decided I cannot afford it so I thought I'd write a small module to control the download.

The performance hit from using the private file system is minimal.

IMHO, using the private file system to control download access to files is the only *sane* way to do this when using Drupal.

> What am I doing wrong?

You err in not using the private file system .

When you hand the direct link to the browser, it goes *directly* to that link. It does not even *see* the PHP/JavaScript you've put in place to restrict download access.

To prevent unauthorised downloads, you must enforce that the downloads are managed by Drupal, and that this access control cannot be bypassed by requesting direct links served by the browser. This is what the private file system (aka *private download method*) does.

This download method stores the files attached to a node in a directory that is *not accessible* by the browser (preferably above the web-root). The only way to get to these files, are then through Drupal.
> 1 votes

---
Tags: hooks, navigation, files
---


# Question
Title: How to add a field default to bulk user records
I've added a field to the user profile page, and set the default. I can see that when I create a new user, the default is set, however for existing users the field is empty.

Is there a way to apply the default to all existing user records?

I've tried View Bulk Operations, but that didn't seem to have an action to update a field.

I'm about to write the mySQL script to update the field, but surely there is a better way........

# Answer
> 0 votes
Check out the answers to this question: Bulk field update? In particular the answer suggesting "Execute Arbitrary PHP Script".

(Looks like a duplicate.)

---
Tags: entities, users, views
---


title: How to relate two views from same node

text:
# Question
Title: How to relate two views from same node
I have searched through all the questions, but I can't seem to find the information, I need. Accept my apology, if this has already been covered.

On a site for a law firm, I have a content type, called "People" (not the same as User) with multiple fields containing information about each individual. I want to display part of a node in a page view, and other parts (such as image, contact details etc) in a block view. The page and the block view has to be related, obviously. I can only find answers on how to relate nodes/files with each other. Not just from a single node.

I cannot get my head around how to filter it, and how to use the contextual filter function. I understand as much, that the context must be with the NID. I just need a 1,2,3 ...

Drupal version 7.22, Views 3

I'll appreciate any help, thanks

* Christian

EDIT: OK, it's solved. And in the end, it wasn't as complicated. Thanks to Rémy, to steer me in the right direction just using normal node (no need for a Page view here)

Here's what I found:

1) No need to fiddle with PHP templates here. Under Content type, just decide which fields, you want to see on your page. Make the others hidden.

2) In Views, create a block view (in this case), under Advanced - Contextual filters, select Content: NID, select Provide default value - Content ID from URL.

The main source of confusion for me was I 'wanted' it to rely on alias in the path. It doesn't. Views isn't checking for that at all, but only for actual node ID - e.g. 108, 109 ...

# Answer
> 0 votes
for the page view use the normal node, and hide the stuff you want to display in one of the block in your node.tpl.php.

then create a new view showing your contenttype, with the actual node id as contextual filter. make block displays, put the fields you need for your different blocks in each block. add the block in to the page, only showing it for the actual contenttype.

---
Tags: views
---


# Question
Title: Issue in converting a HTML Link to Drupal Link using l() function
I have created a HTML anchor link. Now i need to convert this link to Drupal's link using `l()` function. But i am not getting what i want. I am new to this Drupal environment.

HTML Link :

```
<a href="#" onclick="loadQtiPlayer('.$targetPath.','.$targetWindowHeight.','.$targetWindowWidth.')" id="qtiStatQuiz1">'.START_QTIQUIZ.'</a>

```

What i have tried is,

```
l('Start QTI Quiz', '#', array('','onclick' => "loadQtiPlayer('.$targetPath.','.$targetWindowHeight.','.$targetWindowWidth.')"));

```

This is not working. I am using **Drupal 6.14.**

Can anyone point out where is the issue?

# Answer
```
$current_path = check_url(drupal_get_path_alias($_GET['q']));
$onclick = 'loadQtiPlayer(' . $targetPath . ',' . $targetWindowHeight . ',' . $targetWindowWidth . ')';
print l('Start QTI Quiz', $current_path, array('fragment' => ' ', 'attributes' => array('onclick' => $onclick)));

```
> 3 votes

# Answer
You need to use the `fragment` option to add a fragment to the URL. `l()` makes it pretty difficult to get an empty fragment, but you can get very close to it with a little hack:

```
$link = l('Start QTI Quiz', '', array('fragment' => ' ', 'external' => TRUE)));

```

That'll do the trick for Drupal 6 & 7.
> 2 votes

# Answer
In this case as the href is pointing at any content there's no point in using the l() function at all. You may as well code the A tag directly as it's not really a link.
> 0 votes

---
Tags: navigation
---


title: Content not unpublished

text:
# Question
Title: Content not unpublished
I am trying to unpublish some content by going to admin/content and then checking the chechbox for those content and then in update options i do a Unpublish selected content but then i get an error: The website encountered an unexpected error...I check the logs i get the error:

```
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value:
 '' for column 'field_time_to_finish_countdown_timer' at row 1:
 INSERT INTO {field_data_field_time_to_finish} (entity_type, entity_id,
 revision_id, bundle, delta, language, field_time_to_finish_countdown_timer)
 VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2,
 :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5,
 :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => node
 [:db_insert_placeholder_1] => 135 [:db_insert_placeholder_2] => 174
 [:db_insert_placeholder_3] => challenge [:db_insert_placeholder_4] => 0
 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => ) in
 field_sql_storage_field_storage_write()
 (line 448 of
 /home/qa/ypwb/public_html/modules/field/modules/field_sql_storage/field_sql_storage.module).

```

What is this and how can i rectify that?

# Answer
It seems you added the field `field_time_to_finish_countdown_timer` to your content type `challenge` after you created some content for this type.

The previously created content do not have any value for this field, causing this error. You may define a default value for this field, such as 0 to get rid of this error.
> 2 votes

---
Tags: 7, users, nodes
---


title: How to group fields with select option?

text:
# Question
Title: How to group fields with select option?
I just want to show the user to select any one of the group see the below image.

I am not sure which module i have to use.

Please suggest me how to do this ?

# Answer
> 1 votes
If you are looking to have different fields displaying based on what the user selects for your radio buttons, use the http://drupal.org/project/conditional\_fields module.

There is documentation on how to use the module at http://drupal.org/node/1704126

To split the form into left and right sections you can use the http://drupal.org/project/ds module.

You can use the http://drupal.org/project/field\_group module to group fields together, however to get the fields to indent underneath your radio button like in your image you will probably have to do some custom css and maybe a little custom themeing of the markup.

You should be able to get pretty close to what your image has though without custom work.

---
Tags: 7, entities
---


title: Register a module theme implementations

text:
# Question
Title: Register a module theme implementations
I have created a simple module to display frequently asked questions (FAQ). The output (faq content) can be customize in mymodule-template.tpl.php file located in a module directory.

I'd like to create an additional template file suggestion for the theme directory e.g: sites/all/themes/mytheme/templates/mymodule-template.tpl.php

So, the main goal is to add two template file suggestions.

1. \[my module path\]/mymodule-template.tpl.php
2. \[active theme path\]/templates/mymodule-template.tpl.php

To achieve #1 I have implemented this hook.

```
/**
 * Implements hook_theme()
 * @return
 *  An array with the name of template file and variables
 */
function simple_faq_theme($existing, $type, $theme, $path) {
    // get faq content
    $records     = get_faq_content();   // categories, questions, answers
    $description = get_faq_info('intro');   // faq description

    return array(
        'faq_template'  => array(
          'template'    => 'simple_faq',
          'variables'   => array('records' => $records, 'description' => $description),
        )
    );
}

/**
 * FAQ Page content
 *
 * @return
 *  HTML created by template file
 */
function simple_faq_page() {
    return theme('faq_template');
}

```

It works, but I can't figure out how to create an additional suggestion, which allows users to theme the output without changing anything within module files.

Any idea?

# Answer
Your hook\_theme implementation is not being done in the usual way. It should only have default values for the variables, like this:

```
/**
 * Implements hook_theme()
 * @return
 *  An array with the name of template file and variables
 */
function simple_faq_theme($existing, $type, $theme, $path) {
  return array(
    'faq_template' => array(
      'template' => 'simple_faq',
      'variables' => array('records' => array(), 'description' => ''),
    )
  );
}

```

Then when you call the theme function is where you send the actual values in, like this:

```
/**
 * FAQ Page content
 *
 * @return
 *  HTML created by template file
 */
 function simple_faq_page() {
   // Get faq content.
   // Categories, questions, answers.
   $records = get_faq_content();
   // faq description.
   $description = get_faq_info('intro');
   return theme('faq_template', array('records' => $records, 'description' => $description));
 }

```

As far as I know you can't give 2 values for the template file, however what you want to do should already be possible. All you have to do is tell it where the original template file is in your module, then drupal will automatically find ones that are in any themes (the defining module doesn't have to set up anything for the theme).
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to add a tabbed menu on group main page (panel)?
I managed to get panels working with og 7.x-2.1 following: \- http://modulesunraveled.com/organic-groups/part-3-organic-groups-layout \- http://www.initsix.co.uk/organic-groups-panels-and-views-drupal-7

Now I'd like to add a tabbed menu on the "main og content", where I mainly divide by content-type (documents, agenda, forum, news..).

I tried to follow http://www.austinprogressivecalendar.com/blog/creating-drupal-panels-tabs in order to create tabs, where each tab is a panel. However I don't know how to eventually add what would be my (sub) panel to the main content of the group page, and more in general I wander if there is a less cumber stone way to implement it.

# Answer
> 0 votes
I got a working and straight solution (tabs are panel style) using panels\_tabs.

panels\_ajax\_tab seems more nice (and more clean from a designer point-of-view), but it is also more cumbersome as it only accepts mini-panels as tab elements, and then I'm not sure how to pass the group information down from the main panel to the mini-panel and finally the embedded view panel.

Further panels\_tab load all the page at once and then just hide the unused tabs, so if too many views are loaded the page can take pretty much long time to load !

---
Tags: navigation, panels, organic-groups
---


# Question
Title: How to redirect to l() function link after login?
I'm having a Simplenews newsletter template with a link guiding newsletter readers to a intranet site with more news.

```
<?php print l('hier.', 'node/' . $build['#node']->nid, array('absolute' => TRUE)); ?>

```

My problem now is, that if the user is not logged in, that link only brings him to the login site, where he is then stucked.

What would I have to do or what function would help me to somehow provide a link that redirects the not logged in user to the proper aim after logging in, and which would not affect the already logged in user?

# Answer
You can add a additional destination parameter to the function.

```
<?php
print l(t('Title'), 'url', array('query' => array('destination' => 'destination_url')))
?>

```

This will create :

```
<a href="url?destination=destination_url">Title</a>

```

Hope it helps.
> 5 votes

---
Tags: navigation, redirection, emails
---


# Question
Title: How to get defined display names (id) from selected view?
Getting selected view is simple:

> views\_get\_view('name');

I didn't find and have no idea what do next...

I need to get every defined view page path and add menu item to it.

# Answer
> 4 votes
This will loop through every page display and set a menu item.

```
  $view = views_get_view('VIEW_NAME');
  foreach ($view->display as &$display) {
    if ($display->display_plugin == 'page') {
      // Add an if or switch statement here to check $display->id
      // so you can set different menu items for each display.
      $display->display_options['menu'] = array(
        'type' => 'normal', // Menu item type.
        'title' => t('Menu item title'), // Menu item title
        'description' => '', // Menu item description
        'name' => 'main-menu', // Menu name
        'weight' => 0, // Menu item weight
        'context' => 0, // Not sure off the top of my head what this is for.
      );
    }
  }

```

However this will set the same menu item for each display. You will need to check the $display-\>id for each one so that you can set a different menu item for each display.

Also, that example sets a normal menu item. If you want a local task or default local task it will be slightly different.

...also, why do you need to do this? why not add the menu item via the views UI?

---
Tags: 7, views
---


title: drupal 6 search pdf content

text:
# Question
Title: drupal 6 search pdf content
Is there any way include pdf files in common drupal search. I tried http://drupal.org/project/search\_files module. But it gives the results under a separate tab. Is there any to include them in common drupal search. I merger the result using hook\_preprocess\_search\_results.

```
   $file_results = module_invoke('search_files', 'search', 'search', arg(2));
   $count = count($variables['search_results']);
   $variables['search_results'] = '';
   $f = null;
   $filecount = $count + 1;
   foreach ($file_results as $result) {
      $f[$filecount] = $result;
      $filecount++;
   }
   $variables['results'] = array_merge($variables['results'], $f);

```

But this also is not working. Anybody can suggest a solution? And one more doubt. Is there any way to change search result count.

# Answer
> 2 votes
In my opinion the best thing to use for file search is the http://drupal.org/project/apachesolr module along with the http://drupal.org/project/apachesolr\_attachments module. I probably wouldn't do file searching without solr.

You would then turn off the basic drupal search page and just use the solr one.

It will require a bit of extra setup though and you might not be able to do it if you are on shared hosting.

There is an issue for combining the search files and search pages here - http://drupal.org/node/368195

Unfortunately there isn't a proper patch to use but there is some code in there. You will just have to do a bit of work yourself to get it going.

---
Tags: 7, hooks
---


# Question
Title: Contextual Filter (Author's Username) Multiple usernames
I'm setting up a custom Views RSS Feed that looks something like this.

The problem is, when I add one user name as a filter, it works but anything after it, the view will not show the post of the other user. Ex: If my name is X and I put X in for the filter, it shows X's post but if I put in X/Y, only X's posts will show.

# Answer
> 1 votes
You have to have the "Allow multiple values" option of the contextual filter set (it is in the "MORE" collapsible fieldset).

Then you have to separate the names with a plus symbol (+) or a comma (,).

If you separate with a slash views will treat it as 2 separate arguments and your view only has one argument.

---
Tags: feeds, views
---


# Question
Title: Is there a hook I can use to alter the way comments are rendered?
Is there a hook I can use to alter the way comments are rendered? Not for altering the comments form, but the listed comments themselves. Obviously, I can target with CSS, but I was wondering if I can hook into core and change the way they are displayed from there?

Thanks

# Answer
> 2 votes
You can use `hook_comment_view()`:

> The comment is being viewed. This hook can be used to add additional data to the comment before theming.

e.g.

```
function hook_comment_view($comment, $view_mode, $langcode) {
  // how old is the comment
  $comment->time_ago = time() - $comment->changed;
}

```

Or use a standard theme preprocess hook

```
function MYTHEME_preprocess_comment(&$vars) {
  // Make changes to $vars that will be available in comment.tpl.php
}

```

You can also override the standard comment.tpl.php file in your theme to have full control over the markup.

---
Tags: comments
---


# Question
Title: Target Bundle with hook_element_info_alter
Using the following hook you can alter form elements

```
function EXAMPLE_element_info_alter(&$type){
  // Increase the default weight range
  if (isset($type['weight']['#delta'])) {
    $type['weight']['#delta'] = 120;
  }
}

```

How can I target a bundle with this hook?

# Answer
> 2 votes
Bundles are defined in `hook_entity_info()`, so the complementary alter hook is `hook_entity_info_alter()`

> Alter the entity info.
>
> Modules may implement this hook to alter the information that defines an entity. All properties that are available in hook\_entity\_info() can be altered here.

`hook_element_info_alter()` is for altering form elements (which a bundle is not), so it can't be used in that context.

---
Tags: hooks
---


# Question
Title: Ubercart 3.x catalog page (terms categories) theme?
How to change output theme for categories page in Ubercart 3 for Drupal 7?

# Answer
I not sure if you are referring to a taxonomy term page. In case if you are then please follow below mentioned steps:

1. Go to: admin/structure/views
2. Find a view called: Taxonomy term
3. Edit this view and add the fields as you wish
4. Under 'FORMAT' change to table, etc will change the overview of the taxonomy term page.

By modifying this view you will be able to change the layout, and the add more fields to the page.

Note: changing this view will change all the taxonomy term pages.
> 3 votes

---
Tags: views, ubercart
---


title: Multiple FAQ pages using FAQ module

text:
# Question
Title: Multiple FAQ pages using FAQ module
I am using the FAQ module in drupal7. My website has many pages which should have a FAQ of their own. So adding FAQ from "Add Content" adds and lists all the FAQs in different categories in the "faq-page". For example, I have two applications so i need dedicated faq page for application 1 and 2.

Is this possible using the FAQ module ?

# Answer
> 3 votes
Yes, the FAQ module provides the ability to have separate categories of FAQ via the taxonomy module as per the project page:

> "In addition, if the 'Taxonomy' module is enabled, it is possible to put the questions into different categories when editing. Users will need the 'view faq page' permission to view the built-in 'faq' page and will need the 'administer faq' permission to configure the layout, etc."

To use the individual faq categories, use the urls: faq-page/\[tid\] - where the \[tid\] is the term ID of the category you want.

You can also use views to make additional faq pages for specific categories if you like.

---
Tags: views, 7
---


title: entity translation of menu

text:
# Question
Title: entity translation of menu
i have set up entity translation and everything is working. except for menus. I have a translation set defined for a menu item in "main-menu" and have 2 languages set up for a menu item. However, now both show up in the main menu regardless of which language i am in.

any clues?

its possible my custom menu tree may have something to do with it?

in page.tpl \>

```
$pid = variable_get('menu_main_links_source', 'main-menu');
$tree = menu_tree($pid);
$tree = str_replace(' class="menu"', '', $tree);
$main_menu = drupal_render($tree);
print $main_menu;

```

# Answer
Fixed with i18n\_menu\_translated\_tree

`$tree = i18n_menu_translated_tree($pid);`

as an alert for the next guy, there is some development to move towards i18n\_menu\_translated\_menu\_link\_alter() http://drupal.org/node/1693074
> 1 votes

# Answer
1) Show menu as tree:

just edit each menu link that must be expanded and check `Show as expanded`. Than you can enable your menu block.

2) Menu translation:

Each menu title is translatable via standart Drupal form at `admin/config/regional/translate/translate`
> 0 votes

---
Tags: routes, i18n-l10n
---


# Question
Title: Add Menu Block (module) Menu To Page tpl
Hello i am trying to avoid using the block system with drupal. Im using panels and i dont like having to add the main content if i use any block in a region. anyhow.... i was hoping to add a menu block i have to my page.tpl

The block i want to add has this url to it when i edit it- block/manage/menu\_block/2/configure

The code im using to add another block is

```
    <?php
      $block = module_invoke('md_megamenu', 'block_view', '1');
      print $block['content'];
    ?>

```

Ive tried a few things with not much success. If i was to choose my best effort it would be-

```
   <?php
             $block = module_invoke('menu_block', 'block_view', '2');
          print $block['content'];
        ?>

```

this just shows 'array' though.

could anyone suggest anything i should try?

Thanks

# Answer
> 5 votes
It seems like you're mixing the Drupal 6 and Drupal 7 api a little bit.

If you're on Drupal 7, you should print out your block like this:

```
<?php
$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);
?>

```

Note the '**print render**'. (You're missing the 'render' part if you're on Drupal 7.

The only things you need to change are to put '**menu\_block**' for the 'module\_name' and your **block's machine name** for 'block\_delta'.

More info and examples are on drupal.org: http://drupal.org/node/26502

Does that work for you?

============ Edit ==============

On the other hand, if you're on Drupal 6, your call should look something like this:

```
<?php
$block = module_invoke('module_name', 'block', 'view', 'block_delta');
print $block['content'];
?>

```

In this case, you're fine with the just 'print $block\['content'\]', but your arguments are a little off. From what you're saying though, it sounds like you're on Drupal 7, and are just returning the array without rendering it!!! :-)

---
Tags: theming, blocks
---


# Question
Title: How to show a menu for everybody but one role?
I'd like to add, in a custom module, a hook menu that adds a menu only if

* the user is logged in
* the user has the role "immat"

I'm trying to use the hook\_menu() hook but it's never called when the page displays the "Navigation" menu. Where should I look / which hook should I use?

Thank you very much!

# Answer
hook\_menu is not called on every page load, because that make Drupal really slow. It is only called when the menu is being (re)built, and the resulting menu structure is cached.

In hook\_menu, you can tell Drupal how to determine which users have access. Access is not granted by role, but by permission. That way, you can easily grant the same permission to other roles when needed.

You will need to:

* Define a new permission using hook\_permission
* Add the new permission to the role you want to give access
* Restrict your menu item to users with that permission by adding `'access arguments' => array('[name of your permission]'),` to your menu item

For an example, see the menu\_example module at api.drupal.org. More specifically, see how menu\_example\_permission defines a new permission and how menu\_example\_menu specifies that permission as access arguments for the `$items['menu_example/permissioned/controlled']` item.
> 4 votes

# Answer
It may be done without any programming: simply add the Menu by Role module or the Menu Item Visibility module and you will have the option to select for which roles the menu item is enabled. I've tried both of them and ended up working with the first one.
> 0 votes

---
Tags: hooks
---


# Question
Title: Get page title of view and panel page via url
Is there any way to get page title of view and panel page using url. I tried

```
$normal_path = drupal_get_normal_path($path);
$item = menu_get_item($normal_path);
$title = $item['title'];

```

and it is giving empty title while it is working well for normal node.

Please suggest.

# Answer
> 1 votes
For pannel you can pass the page title in url let say xyz/page\_title then add content to panel and choose New custom content in the body field your code will somewhat look like

```
<?php
  $title = arg(1);
  drupal_set_title($title);
?>

```

check screenhot for better understanding:

For views its a simple 2 step process step1: Set the view path to take the title as wildcard i.e. your view path will be view\_path/%

step2: now change the title field on views to use the title wildcard by changing it to %1 as this is the first argument in the url

hope it helps you :)

---
Tags: views, panels, uri, 7
---


title: 2 submits with same validation?

text:
# Question
Title: 2 submits with same validation?
I am modifying user\_pass so that it also has an option to resend a user's activation email.

```
if($form_id=='user_pass'){
    $form['name']['#title'] = 'Email Address';
    $form['actions']['submit'] = array();
    $form['actions']['submit_reset'] = array(
        '#value' => t('Reset Password'),
        '#type' => 'submit',
        '#attributes' => array('class' => array('btn-primary', 'btn'))

    );

    //resend button
     $form['actions']['submit_resend'] = array (
        '#value' => t('Resend Activation Email'),
        '#type' => 'submit',
        '#submit' => '_mymodule_resend_activation', //gives invalid argument on foreach
        '#attributes' => array('class' => array('btn-primary', 'btn'))
    );
}

```

This doesn't seem to work bc I get an invalid argument for a foreach when I set the submit property for the resend button. But the reset functionality is exactly as I want it. Is there a way I can use the same validation for both submits and have a custom handler for the second one?

# Answer
`#submit` and `#validate` each need to be an array:

```
$form['actions']['submit_resend'] = array (
  '#value' => t('Resend Activation Email'),
  '#type' => 'submit',
  '#submit' => array('_mymodule_resend_activation'),
  '#validate' => array('_mymodule_form_validate'),
  '#attributes' => array('class' => array('btn-primary', 'btn'))
);

```

As far as I know there aren't any limits on the number of elements that can share the same validation callback.
> 3 votes

---
Tags: users, forms
---


# Question
Title: menu_navigation_links() generate a error
I'm try listing a menu navigation links with menu\_navigation\_links() function, but is generate a follow error:

> Notice: Undefined index: localized\_options in menu\_navigation\_links() (line 1860 of /home3/xptoboxc/public\_html/drupal/includes/menu.inc).

**My code:**

```
$html .='<ul id="navigation" class="arrow-list">';
foreach (menu_navigation_links('navigation') as $menu => $link) {
    if(!empty($link['title']))
        $html .= '<li><a href="' . url($link['href']) . '" title="' . $link['title'] . '">' . $link['title'] . '</a></li>';
}
$html .= '</ul>';

```

# Answer
Are you using the navigation menu as the secondary menu for the site?

The cause could be a bug in drupal core. See http://drupal.org/node/1018614

There is a patch in #83, which I think is for drupal 8 but the fix should be the same for drupal 7.
> 2 votes

# Answer
try this code:

```
$html .='<ul id="navigation" class="arrow-list">';
foreach (menu_navigation_links('navigation') as $menu => $link) {
    if(!empty($link['title']))
        $linkt = t($link['title']);
        $html .= '<li><a href="' . url($link['href']) . '" title="' . $link['title'] . '">' . $linkt . '</a></li>';
}
$html .= '</ul>';

```
> 0 votes

---
Tags: 7, routes
---


title: Assigning Template for Parts of Pages

text:
# Question
Title: Assigning Template for Parts of Pages
I'm new to drupal and coding so I'll try and explain best I can the issue I'm having.

I'm on Drupal 7, using Zen Sub Theme

I have a site which is essentially a database of gadgets. 'gadget' is a custom content type with custom fields such as 'year of manufacture', 'manufacturer', 'image' and 'description'.

I work out of 'page.tpl.php' to control the look of my homepage. I find this to be very easy to use, as far as creating/formatting regions. Essentially formatting the building blocks of my template. On the homepage I have list of links (created via views) to the most recent gadgets. When I click on a gadget it takes me to the 'Gadget' page displaying all the fields I mentioned above.

Now to the issue I'm having:

I can't figure out for the sake of me how I can have a tpl file for the custom content type (ie. the gadget). I have so far formatted the page with CSS but it would be nice if I can have (I prefer to work through editing the tpl files) a TPL file for the page elements (ie. header, footer) and a TPL file for the region its showing my gadget node.

I've attached a picture of what I'm trying to do:

---

The home page templating

http://imageshack.us/photo/my-images/402/homepagem.png/

---

The gadget page templating

http://imageshack.us/photo/my-images/560/pageinside.png/

---

What I've tried:

1) Formatting the gadget page with CSS : This works fine, but I would prefer to have control over tpl file.

2) In the templates folder I added node--gadget.tpl.php and cleared cache (doesnt work). node.tpl.php on the other hand does get pulled up by static pages in the site (like the 'about us' page) but not on custom content type (gadget).

3) I added the code below to confirm that content '\[type\] =\> gadget':

```
    <?php
function gadgettheme_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $vid = db_query("SELECT vid FROM {taxonomy_term_data} WHERE tid = :tid", array(':tid' => $tid))->fetchField();
    $vars['theme_hook_suggestions'][] = 'page__vocabulary__' . $vid;
  }
}
?>

```

4) Finally I put in the code below and create a page--gadget.tpl.php. This worked but the problem is its page--gadget controls the whole content which means I would need to copy over the template from the page.tpl.php to control the header and footer. I want these elements to be controlled solely from page.tpl.php and have another node--gadget.tpl.php.

```
function gadgettheme_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

?>

```

Your help is appreciated in advance,

Cheers,

# Answer
I've managed to solve this issue.

I was using display suite to format my node and without realising I was using the Display Suite's theming file. Once I renamed my node--gadget.tpl.php to the Display Suites theme name ds-1col--node--gadget.tpl.php it worked!

Cheers,
> 2 votes

# Answer
Since you say you're new to drupal, I hope you don't mind some simple questions?

1. IF the machine name of your content type is "gadget" then your point #2 should work. The fact it isn't begs my questions about your presumptions about drupal subthemes. SO:
2. Where does you subtheme directory exist?
3. What is the name of your subdirectory?
4. where is your "templates" subdirectory?

NOW with THAT out of the way, I strongly suggest you check out "Display Suite" which gives you enough output customization to make any themer happy. http://drupal.org/project/ds You can customize your node output within the Drupal UI and with a bevy of handy options for full node view, teaser view, and any custom view you'd like to create.

Regardless, let's make certain your subtheme is correctly established.
> 0 votes

---
Tags: theming
---


title: boost and nginx compatible?

text:
# Question
Title: boost and nginx compatible?
Is the boost module compatible with nginx ? Or does boost support nginx integration? If so where can one find the default nginx rules for installing boost?

The module requires installation using htaccess but nginx doesn't use htaccess it utilizes virtualhosts directives to manage the site.

I was able to find this resource but it's from 2008 and it's for drupal 6. I know the rewriting rules have changed only slightly.

# Answer
> 2 votes
Found my answer. Boost and nginx are compatible.

Perusio provides a pretty detailed configuration setup for boost.

---
Tags: 7, caching
---


# Question
Title: Trying to Understand Where I am Going Wrong Modifying User Registration Form
I am working with Drupal as part of a student project. As background, I work professionally doing front end development and I've taught myself at least the basics of the back end.

Here's my problem, I have the form set up as expected, it validates upon hitting the submit button, and the user is created. However, none of the custom fields populate the db. I've tried so many different approaches/tutorials and nothing actually works. Without writing a rant this has been very frustrating because it would be simple to do this task in straight PHP. Anyways, here is my code, any help would be vastly appreciated.

```
function user_creation_form_user_register_form_alter(&$form, &$form_state, &$form_id){

// Adds form validation
$form['#validate'][] = 'user_creation_user_form_validate';

$form['account']['confirm_email'] = array(
    '#type' => 'textfield',
    '#title' => 'Confirm your email:',
    '#required' => TRUE,
);

$form['account']['password_confirm'] = array(
    '#type' => 'password_confirm',
    '#required' => TRUE,
);

$form['account']['password_hint_question'] = array(
    '#type' => 'select',
    '#title' => 'Password Hint:',
    '#required' => TRUE,
    '#options' => array(
        t('What was your first car?'),
        t('What was the name of your first pet?'),
        t('What was the name of your high school?'),
        t('What is the name of your favorite sports team?'),
    ),
);

$form['account']['password_hint_answer'] = array(
    '#type' => 'textfield',
    '#title' => 'Password Hint Answer:',
    '#required' => TRUE,
);

$form['account']['first_name'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name:',
);

$form['account']['last_name'] = array(
    '#type' => 'textfield',
    '#title' => 'Last Name:',
);

$form['account']['user_icon'] = array(
    '#type' => 'file',
    '#title' => 'User Icon:',
);

$form['account']['location'] = array(
    '#type' => 'textfield',
    '#title' => 'Location:',
);

// Adds the year began drop down
$form['account']['year_began'] = array(
    '#type' => 'select',
    '#title' => 'Began Playing in Year:',
    '#options' => year_array(),
    '#description' => t('Select the year you began playing.'),
);

$form['extra_info']['about_me'] = array(
    '#type' => 'textarea',
    '#title' => 'Tell us about yourself',
);

$form['approve']['read_rules'] = array(
    '#type' => 'fieldset',
    '#title' => t('Rules Agreement'),
);

$form['approve']['read_rules']['rules'] = array(
    '#markup' => '<div class="agreement">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam tempus velit ante. Nullam semper pellentesque est, sit amet ultrices ante scelerisque vel. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer accumsan vulputate arcu in pharetra. Etiam nec dolor quis magna scelerisque pretium. In hac habitasse platea dictumst. Aliquam dictum condimentum viverra. Nullam rutrum, magna eu semper vehicula, nisl leo bibendum dui, ac scelerisque velit nisl et sem. Proin lobortis tellus vel lacus ultrices vel ultricies purus convallis. In hac habitasse platea dictumst. Quisque a blandit neque.</p>

    <p>Mauris faucibus placerat ipsum non ultricies. Suspendisse vel est a velit dignissim molestie. Maecenas mollis porttitor lorem, a facilisis mauris lobortis quis. Nunc non felis sit amet justo scelerisque pulvinar in vitae quam. Nullam vulputate lectus sit amet quam pulvinar euismod. Maecenas bibendum tortor nec lorem fermentum ornare. Quisque suscipit, velit id consectetur consequat, velit mauris condimentum purus, a pretium lorem lorem eu risus. Nullam id ante neque, at convallis quam. Morbi varius turpis et lacus scelerisque eleifend. Nullam nisl sem, porttitor a venenatis id, fermentum eget leo.</p>
    </div>',
);

$form['approve']['read_rules']['decision'] = array(
    '#type' => 'radios',
    '#description' => t('By clicking yes you agree to abide by the rules of BGRA.net stated above.'),
    '#default_value' => 1,
    '#options' => array(t('I agree'), t('I disagree')),
);
}

function year_array(){
$years = array();
array_push($years, t(' '));

for($i = date('Y'); $i >= 1950; $i--){
    array_push($years, t($i));
}

return $years;
}
/**
* Implements hook_user_form_validate
*/
function user_creation_user_form_validate($form, &$form_state){
global $user;
// Do emails match
if ($form_state['input']['mail'] <> $form_state['input']['confirm_email']){
        form_set_error('confirm_email', t('Your original email and confirmation email must match.'));
}

// Did user agree?
if ($form_state['input']['decision'] <> 0) {
    form_set_error('decision', t('You must agree to the Rules Agreement before registration can be completed.'));
}
}
/**
 * Implements hook_form_submit
 */
function user_creation_form_submit_handler($form, &$form_state){
    $edit = array(
    'name' => $form_state['values']['name'],
    'pass' => user_password(),
    'mail' => $form_state['values']['mail'],
    'init' => $form_state['values']['mail'],
    'status' => 1,
    'access' => REQUEST_TIME,
    'first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['first_name']))),
    'last_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['last_name']))),
    'password_hint_question' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['password_hint_question']))),
    'password_hint_answer' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['password_hint_answer']))),
    'user_icon' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['user_icon']))),
    'year_began' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['year_began']))),
    'location' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['location']))),
    'about_me' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['about_me']))),
);
user_save(drupal_anonymous_user(), $edit);
}

```

As a separate and non-essential issue, I couldn't figure out how to get the .install file to alter the schema for the users table w/o errors, so I manually made an ALTER TABLE call in phpmyadmin. I know this would probably be a problem when the Drupal version is updated and likely overrides the users table. But again, this is a student project - so while I'm curious as to how to do it properly it's not essential.

# Answer
> 2 votes
You can add custom fields to the User Account at the page `admin/config/people/accounts/fields`. This page uses the Field UI.

You can export these fields to PHP code and install them via a custom modules `hook_install()` function call by following the sample directions here a blog post on how to export the Field definition array structure from Drupal. Your entity\_type would be `user` as would the bundle i believe. An excerpt from this blog is:

```
$entity_type = '';
$field_name = 'field_';
$bundle_name = '';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">" . $output . '</textarea>');

```

You would then take the outputted code, and place it into your modules `hook_install()` function. Then when your module is enabled the fields are created.

You can then save custom Drupal Fields you've made on form submit rather easily along with the default User values as this example code shows I've yoinked from code I have laying around:

```
$userinfo = array(
  'name' => $name,
  'pass' => user_password(),
  'init' => $name,
  'status' => 1,
  'access' => REQUEST_TIME,
  // This is where we are different from the default function.
  'roles'        => $provisioned_roles,
  'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['first_name']))),
  'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['last_name']))),
  'field_perm_number'  => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['perm_number']))),
  'field_school_employee_id'  => array(LANGUAGE_NONE => array( 0 => array('value' => @ldap_details['employee_number']))),
  'mail' => $ldap_details['mail'],
);
$account = user_save(drupal_anonymous_user(), $userinfo);

```

In general, these questions have been answered before, but sometimes finding the answers here can be tough. There is a great Examples project for developers, also the Core modules found in `/modules` all do alot of this same application logic as well (such as user\_external\_login\_register())

# Answer
> 0 votes
You must implement hook\_schema\_alter() in your module. Look how I added custom field to node table i mymodule.install file:

```
/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Add the new field to the node table
  $field = array(
    'description' => 'Stores the last activity on node',
    'type' => 'int',
    'unsigned' => TRUE
  );

  db_add_field('node', 'activity', $field);
  db_add_index('node', 'activity', array('activity'));
}

```

and in mymodule.module file:

```
/**
 * Implements hook_schema_alter().
 */
function MYMODULE_schema_alter(&$schema) {
  // Add the new field to the schema cache
  $schema['node']['fields']['activity'] = array(
    'description' => 'Stores the last activity on node',
    'type' => 'int',
    'unsigned' => TRUE
  );
}

```

To access this custom field in views, implement hook\_views\_data\_alter()

```
/**
 * Implements hook_views_data_alter().
 */
function MYMODULE_views_data_alter(&$data) {

  $data['node']['activity'] = array(
    'title' => t('Node activity'),
    'help' => t('Last activity on node'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );
}

```

---
Tags: database, forms
---


title: path template page--path.tpl.php

text:
# Question
Title: path template page--path.tpl.php
I am using one shared template - page.tpl.php for basic pages such as about us, contact us,etc. However, there are rental properties that share a different template, so i have created Content type - property page, and i would like to share a separate template for all pages of content type - property page. How to do it?

I tried to add path 'rentals/property1-3' and use page--rentals.tpl.php but it doesn't work

Any help appreciated.

Thanks

# Answer
You need to use this format for drupal to recognize the template for that content type.

```
page--machine_name.tpl.php

```

The machine name should be displayed on your YOUR\_SITE\_NAME.com/admin/structure/types page.
> 1 votes

# Answer
For Drupal 6 :

If you want template file of each node use `page-node-[nid].tpl.php`.

If you want template file of content type use `page-content_type_name.tpl.php`
> 0 votes

# Answer
I found the solution from the following Drupal article: http://drupal.org/node/1430110

In short, by adding the following preprocessor at \[..\]all/themes/themeName/template.php

```
<?php
function minnehaha_preprocess_page(&$vars, $hook) {
    if (isset($vars['node'])) {
        $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
    }
}

```

Now, it overrides any content type with following pattern 'page--machine\_name.tpl.php' where machine name is the content type name
> 0 votes

---
Tags: theming
---


title: Add an action to user register form

text:
# Question
Title: Add an action to user register form
On registration I want to get the value of the user's email and forward them to a page that has an option to resend their activation email. I have the page with the form they're forwarded to, but I need some place to add the user's email address to a $session variable when user\_register is being submitted. Apparently there is no submit\_hook for that form without overriding it entirely (which I would rather not do).

This is the code I have so far:

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
    global $user;

    if($form_id=='user_register_form' && $user->uid != 1 && !in_array('manager', array_values($user->roles)))
    {
        $form['actions']['submit']['#value'] = 'Create Account';
        $form['account']['mail']['#description'] = "Please use a valid email address as you will need to verify it.";
        $form['account']['mail']['#attributes'] = array('placeholder' => 'email@address.com');
        $form['account']['mail']['#title'] = 'Email Address';
        $form['account']['name']['#description'] = "";

        $form['#action'] .= '?destination=node/'.variable_get('checkemailpage', 6);

    }
}

```

# Answer
You can add additional submit callback function to the registration form, then assign user's email to a session so you can call it on the destination page.

Add the following line after `$form['#action']`

`$form['#submit'][] = 'custom_user_register_submit';`

Then add this function to your custom module

```
function custom_user_register_submit(&$form, &$form_state) {

  $_SESSION['custom_user_mail'] = $form_state['values']['mail'];
}

```

Then call `$_SESSION['custom_user_mail']` on any page you want.
> 3 votes

---
Tags: users, forms
---


# Question
Title: How can I update multiple drupal 7 sites on my server, using drush
I just installed drush in my ssh home directory. Is there a drush command for updating all sites inside home directory that have drupal 7?

There is to mention that i have also non drupal sites and i would not like drush to mess with these.

Thanks

# Answer
You can simply create a Bash script, and feed in all the folder names in the sites/dir into Drush.

See this script for updating a Drupal site; modify it according your needs-

Remember that testing is a very important part of every site upgrade. You should include a manual testing phase after the pm-update, and then push each tested site back to the live site as they are found to be working.
> 3 votes

# Answer
Here's another script for updating multiple Drupal sites:

https://github.com/greg-1-anderson/utiliscripts/blob/master/drupal-backup-all

Make an alias for each site to be backed up. This script will first make a remote copy, then it will copy the site again and update it. You'll end up with two sites for each one you start with - a backup, and an update site ready for testing. Push the code from the update site back to the live site after testing.
> 2 votes

# Answer
Not long ago I had the same issue with a client server where he had a couple of Drupal sites and I found my self repeating the same commands over and over for each site. I wrote and small PHP code and I added a shortcut to my shell, now I just run "msu-drush" and all sites get updated even the unwanted text files like LICENSE.txt and COPYRIGHT.txt get removed. It worked for me so there is a big change it can work for you too.

See the PHP code in Drupal.org: http://drupal.org/node/1926484
> 0 votes

---
Tags: 7, drush
---


# Question
Title: Omega - Debugging blocks only for specified role
Is it possible to see debugging blocks only for specified role?

**IDEA** I made special role "*theme developer*" to see debugging blocks of Omega only for this role. When I check in \*admin/appearance/settings/my\_subtheme -\> Debbugging\* options:

* *Enable the debugging (placeholder) blocks for the selected roles.*
* *Enable the grid overlay for the selected roles.*

and select "*theme developer*" role debugging blocks will be seen by granted users only.

**PROBLEM** If I am an administrator I can see debugging blocks even if I'm not in "theme developer" role. Why?

After documentation http://drupal.org/node/1298690 it should work as I wrote in idea but it is not.

# Answer
If you're user uid=1 (administrator), you'll see everything regardless of role. You may be confusing it with the "administrator" role, which is not the same as the admin user.
> 0 votes

---
Tags: 7, blocks, users, theming, debugging
---


# Question
Title: Drupal 7 - Add two menu items with the same path but different query string
On Drupal 7, there is a difficulty adding two or more items to a menu which are having the same URL but a different query string.

For example, when I add two similar paths:

1. node/add/alert?kind=regular
2. node/add/alert?kind=news

Only one of the links is randomly displayed. So frustrating...

Any ideas of how to by bypass this issue?

# Answer
What I did is add the redirect module.

Then I created custom redirects for those menu items, e.g. "node/add/alert/kind/regular" goes to "node/add/alert?kind=regular".

No need for custom hook\_menu programming. It worked! But why doesn't drupal provide it work out of the box???
> 3 votes

# Answer
Another option would have been to make a custom Block in Drupal with your 2 links as simply an HTML list.

So far as I know `/node/add/alert` is 1 page in Drupal, Pylons, Joomla whatever .... its 1 page path to Apache or Nginx. The querystring is simply key-value pairs of arguments you are passing to the page.

The default Menu system in drupal doesnt allow for a single page to exist in more than 1 spot of your site (see NodeSymlink for a module that allows an alias of a page to live in different places of your site, but only 1 master location for the content).

I believe what you're seeing here is an example of drupal's 1 piece of content, lives only 1 place in drupal; so disallow multiple links to the same thing for SEO purposes.
> 2 votes

# Answer
Not quite with Drupal, but you can add a bit of jquery to target the menu item id.

In your menu item, set the path to "" as a placeholder.

Then add this bit of jquery:

$("a#specificLink1").attr('href','/node/add/alert?kind=regular'); $("a#specificLink2").attr('href','/node/add/alert?kind= news');
> 0 votes

---
Tags: nodes
---


# Question
Title: How to retain <noscript> tag in HTML output when added in a Views Fields?
I need to re-write some fields in my Views to output certain format for my `<img>` tag. Since the new format that needs to be written isn't actually accessible, I would need to include `<noscript>` tag for the original `<img>` tag.

### Example

**Accessible, original format**

```
<img src="/images/myimage.jpg">

```

**Non-Accessible, new format**

```
<img src="/images/placeholder.jpg" data-original="/images/myimage.jpg">
<noscript><img src="/images/myimage.jpg"</noscript>

```

## Question

How to make it so that the `<noscript>` tag is retained and not stripped?

Please kindly share your detailed solutions in a way that a Drupal beginner like me can understand. Thank you!

# Answer
Had to use Views PHP module for the `<noscript>` tag to be retained. Even so, had to do some workaround to make it work \>.\<
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to print CCK field on a custom node template? Drupal 7, Omega Theme base
I've been trying to print out CCK fields (Devel screenshot) in my custom node template using this code below which I found from a number of different sources (eg. src1, src2, src3) but with no result.

```
<?php print render($content['field_client_name']); ?>
<?php print render($content['field_bts_desc']); ?>

```

The code above seems to work for most people, if not all. I'm quite baffled as to why it doesn't work for me = /

Could it be something to do with Omega theme that I'm using as a base theme? I've also tried looking for Omega related issue with cck fields but still no result.

Please share your solutions with clear explanation, preferably like a step-by-step guide/explanation as I'm quite new to Drupal. Thank you!

# Answer
> 0 votes
Still had no idea what went wrong. I decided to build my own theme from scratch and the usual way of printing the CCK fields (refer below) finally works for me as well. Thanks again!

```
<?php print render($content['field_client_name']); ?>
<?php print render($content['field_bts_desc']); ?>

```

# Answer
> 0 votes
Go to you content type's manage display fields tab and check weather field is visible or not?

# Answer
> 0 votes
I'd just start troubleshooting to see whether there's some part of the content that's problematic and breaking the output. Start by trying to print something out by going directly to the content.... doing statements like:

```
<?php print $content['field_bts_desc']['und'][0]['value']); ?>

```

and see if that prints out or gives you problems. That way you can get to the content more directly and can see whether it's the content vs. something strange about the render function that's breaking things.

Do the same with other fields -- you know how to use print\_r to see the arrays/objects' structure to find any trends.

Some follow-ups: 1. Does

```
 <?php print render($content['body']); ?>

```

give you any trouble?

1. Also, do you have any log messages under 'admin/reports/dblog' after viewing a page that breaks with one of these print render statements that may give you some additional info?

(sorry I couldn't fit the above in a comment)

---
Tags: 7, entities, theming
---


# Question
Title: Can I make a subdirectory in public:// viewable in Media module's UI?
In Drupal 7 Media module (admin/content/media) is it possible to view subdirectories in my public:// domain? I have images and files from legacy site that were uploaded in a variety of subdirectories, i.e.

sites/default/files/presentations

sites/default/files/sponsors

etc.

My Media module browser lists all the files that exist in the main public:// directory, but doesn't show any of the subdirectories, even though I confirmed via FTP the subdirectories exist. Thanks!

# Answer
> 0 votes
I guess you can five a try to filedepot module if it helps you. Here is a quote about it (from the module's project page):

> ... full featured Document Management module that has a google docs like feel. It fulfills the need for an integrated file management module supporting role and user based security. Documents can be saved outside the Drupal public directory to protect documents for safe access and distribution.

---
Tags: 7, files, media
---


title: iPaper like module recommendation

text:
# Question
Title: iPaper like module recommendation
I am looking for a module that will enable me to upload and preview pdf files, word docs etc on the site. Something along the lines of http://drupal.org/files/images/screenshot\_2.jpg. I would like it to be indexable and searchable on the site.

Any recommendations for the module that will allow me to achieve this would be greatly appreciated.

# Answer
You can try Embedded Google Docs Viewer and check whether your requirements are fulfilled or not. Here is the demo of the module.

The Embedded Google Docs Viewer module adds a new formatter to the File field using the Field API. This formatter displays PDFs, Microsft Word documents, Powerpoint presentations, or Excel spreadsheets directly within a Drupal node.
> 1 votes

---
Tags: 7
---


# Question
Title: LESS could not create a directory in public:
I am creating a site with drupal 7.15 with bootstrap and using less. But when i reload the page i found the following errors. (dope is my sub-theme name)

```
LESS could not create a directory in public://less/51761ea74e5068.61766466/sites/all/themes/dope/less
Warning: Invalid argument supplied for foreach() in drupal_pre_render_styles() (line 3311 of /home/seat3/public_html/DOPE/drupal/includes/common.inc).
Warning: Invalid argument supplied for foreach() in element_children() (line 6300 of /home/seat3/public_html/DOPE/drupal/includes/common.inc).

```

# Answer
> 4 votes
Your drupal site `files` directory has to be writable by your webserver.

---
Tags: theming
---


title: multilingual while adding content

text:
# Question
Title: multilingual while adding content
I have enabled the i18n module and created a taxonomy vocabulary with translated terms. In addition I have created a CT (content type) in which I've added a term reference field of this taxonomy vocabulary.

Is there a way while I'm authoring a new content of this CT to have to choose only among the user's current language terms? At this point I'm seeing a list of 10x3 (30) terms 'cause I got 3 languages, and that's a bit of chaos for the authors.

Thanks in advanced, I hope I've been clear

# Answer
> 0 votes
You can create a node reference view. Check this answer for more information: Display language in entity reference field

You can either limit your entries in the reference field or show the language in every entry.

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


# Question
Title: how to send muliple emails in drupal in same time
in my site when user submit a dination i want to send email to donor,charity and delivery service at same time(three different emails) in code and i want to kown how can i achieve that,below is the my mail seding function,i already tried call email function with 3 times with different keys for `$key` but that time emails are sending with out body content

```
 function zgRequestsdonor2_mail ($key, &$message, $params) {
  switch ($key) {
  case 'aftersubmit_donor':
    // Set headers etc

    $message['subject'] = t('email to donor');
    //$message['body'][] = t('Hello @username,', array('@username' => $params['username']));
    $message['body'][] = 'tyrtyrtyrtyty';
    break;
  }
}

```

calling it at

```
function zgRequestsdonor2_form_submit($form, &$form_state) {
  drupal_mail('zgRequestsdonor2','aftersubmit_donor',$donoremail, $language, $params = array(), $from = NULL, $send = TRUE);
}

```

# Answer
If you want to send same mail to donor, charity and delivery service, then you can use CC feature of the mail.

```
$message['headers']['CC'] = "myemail@me.com";

```
> 1 votes

---
Tags: 7, forms, emails
---


title: how to get total orders of a user?

text:
# Question
Title: how to get total orders of a user?
how can I get total price of all orders which owned by a single user? I want to assign different type of discounts by finding about total amount of their orders. I'm using

> hook\_rules\_action\_info

. should I use **commerce\_order\_load\_multiple()** ?

# Answer
I had a different approach to a similar scenario.

I created a field in the user profile that would store the total amount of orders so far. This field would be increased every time a new order was placed. Also created 3 different roles (silver, gold, platinum) Each role was entitled to different discounts. When the total order would pass the threshold value for the group, the user will be given that role.
> 2 votes

# Answer
Try this

```
$orders = commerce_order_load_multiple(array(), array('uid' => $user_id));

```

You can use the conditions parameter of commerce\_order\_load\_multiple.
> 4 votes

---
Tags: commerce
---


title: Cron job and Access Denied function

text:
# Question
Title: Cron job and Access Denied function
I have a custom module which implements  `hook_node_view()` and checks certain conditions to decide whether a user can view the content or not. The code snippet is:

```
    if( ! user_is_logged_in() && $node->type == "abc") {
        drupal_access_denied();
        module_invoke_all('exit');
        exit();
    }
    else {
        //do nothing
    }
}

```

The code works fine for me but the problem occurs when drupal's cron runs as `Anonymous` user. The only message I get is `Attempting to re-run cron while it is already running.` Could you please give me your suggestion to handle this.

# Answer
> 2 votes
`hook_node_view()` shouldn't be used for access checks, there's `hook_node_access()` for that sort of situation:

```
function MYMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;
  if ($type == 'abc' && $op == 'view') {
    return $account->uid > 0;
  }
}

```

That'll handle the access check for the node gracefully, and shouldn't stop cron running halfway through.

---
Tags: users, cron
---


# Question
Title: Create a rule at the event of "Cron maintenance tasks are performed"?
I created a rule to be fired when "Cron maintenance tasks are performed".

Now I need an action to check delete all nodes of the content type: "Question" that have the field "Delete" set to "yes"

How can I do this?

# Answer
you could use hook\_cron\_queue\_info to create a task that sits in a queue and happens on a timer. This would account for the potentially long duration of the task you mention.
> 0 votes

---
Tags: rules, cron
---


# Question
Title: Form API Select List will not show empty option
I am trying to add a form that forces you to select an option from a dropdown. The documentation says:

> If #required is TRUE and there is no #default\_value, an empty option is added to the select control to force the user to make an active choice.

http://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7#empty\_value

OK that sounds great. That is what I want. So I have the following code to add the select list to my form.

```
$form['test'] = array(
    '#type' => 'select',
    '#options' => array (
      1 => 'Very poor',
      2 => 'Not that bad',
      3 => 'Average',
      4 => 'Good',
      5 => 'Perfect',
    ),
    '#required' => TRUE,
    '#title' => 'Rating',
  );

```

It is a select list, it is required and there is no default value. I however do not see a empty option...

What am I doing wrong?

**Updated**

The element above is now the only thing going into my array. When I `dpm()` the `$form` I get the following back:

**Update 2**

Below is what theme developer is seeing:

**Update 3**

I have set up a clean instance of drupal 7.22 and installed my custom code and the same thing is happening. I used the minimal profile. Must be something I am doing wrong else where...

**Update 4**

I have tested the full code on a different environment (7.19) and the same thing is happening. So it looks like there is something fundamentally wrong with the modules themselves. Will try and anonymize the problem so I can post here.

**Update 5**

I have the following two files in my module.

stack\_test.module

```
<?php

function stack_test_menu(){
  $items['stacktest'] = array(
    'title' => 'Stack Test',
    'page callback' => 'stack_test_form',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );
  return $items;
}

function  stack_test_form(){
  $countryList = array (
    1 => t('Very poor'),
    2 => t('Not that bad'),
    3 => t('Average'),
    4 => t('Good'),
    5 => t('Perfect'),
  );
  $form['test'] = array(
    '#type' => 'select',
    '#options' => $countryList,
    '#required' => TRUE,
    '#title' => 'Rating',
  );
  return $form;
}

```

Then I have my stack\_test.info file:

```
name = Stack Test
description = Test Module
package = Stack Exchange
core = 7.x

files[] = stack_test.module

```

**Update 6**

Creating a select list in a content type with validation required works as expected and '- Select a value -' is displayed at the top of the list.

**Update 7**

The code in Update 5 should work now. I have created a mini module just with that in and I get the same results.

# Answer
> 7 votes
It looks like you're not running your form through `drupal_get_form()`...that would account for the additional form processing functions not running, but you'll still get a rendered HTML element out at the other end so it could be difficult to tell the difference.

Just change the `page callback` for your router item, and add the form as arguments:

```
function stack_test_menu(){
  $items['stacktest'] = array(
    'title' => 'Stack Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('stack_test_form'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );
  return $items;
}

```

Clear the caches and give your test page another try.

The same goes for your original problem - A form is essentially just a render array, and when you return that directly from a page callback it's run through `drupal_render()`. That function will do what it can to render the form element, and it knows how to do it to a certain degree, but the form processing functions add a lot of extra stuff in there, which `drupal_render()` won't do.

Moral of the story - always use `drupal_get_form()` to build the output for a form :)

# Answer
> 2 votes
You need to add "#empty\_option" property to the select box to set your default empty option for selectbox. It will add the first option for the select box.

```
    $form['test'] = array(
    '#type' => 'select',
    '#options' => array (
      1 => 'Very poor',
      2 => 'Not that bad',
      3 => 'Average',
      4 => 'Good',
      5 => 'Perfect',
    ),
    '#required' => TRUE,
    '#title' => 'Rating',
    '#empty_option' => '--Test--',
  );

```

# Answer
> 1 votes
I copied your code to my own module and it works.

The default (none) value of the field is "- Select -".

Do you have any other code that could be interfering?

Also, tet that it printed to the screen generally should run through the translate function t().

Like this:

```
$form['test'] = array(
  '#type' => 'select',
  '#title' => t('Rating'),
  '#options' => array(
    1 => t('Very poor'),
    2 => t('Not that bad'),
    3 => t('Average'),
    4 => t('Good'),
    5 => t('Perfect'),
  ),
  '#required' => TRUE,
);

```

---
Tags: 7, forms
---


# Question
Title: Link menu item to an element ID on the same page
I want to link my menu items not to a page, but to a specific ID of a div tag on the same page, so if anyone click on it would go to the div section. basically its because I want to make a list of some items in my page.

I appreciate any guidance, thanks.

# Answer
well I just figured that out, I can simply link it like: node/515#node-2 so it wont refresh the page and goes straight to the div.

node/515 (same page that my menu are in), but the thing is it doesnt work with url alias so better stick to the classic node url's
> 1 votes

---
Tags: 6, routes
---


# Question
Title: How can I alter the 'submitted by username' for a comment?
I am rendering comments on my site. I am using the Zen theme. If I remark out `<?php print $submitted; ?>` in `comment.tpl.php` the 'username replied on' part is no longer rendered. But I don't want to remove the whole thing - just the 'replied on' text. I can't work out how to alter this bit. Thanks

In Zen comment.tpl.php it reads: '$submitted: Submission information created from $author and $created during template\_preprocess\_comment()'. Presumably, somewhere there will be: $author . 'replied on' - and this is what I need to alter.

# Answer
> 3 votes
**Solution**

A solution is to not use $submitted, but to use $author and $created separately in comment.tpl.php.

# Answer
> 2 votes
you could override theme\_comment\_submitted()

```
    function yourtheme_comment_submitted($comment) {
  return t('Posted by !username on @date at about @time.', array(
    '!username' => theme('username', $comment),
    '@date' => format_date($comment->timestamp, 'custom', 'd M Y'),
    '@time' => format_date($comment->timestamp, 'custom', 'H:i')
  ));
}

```

but the way I prefer is instead of using `$submitted` try using `$author` and $created along some words you rather to use.

on the other hand the easiest and not recommended way to do this is to use locale module, and then translate it to the same language you have but with the words you want!

---
Tags: comments, theming
---


# Question
Title: How to create a View showing subscribed content?
I want to create a view which will display all the posts user has subscribed to (very much like the Facebook homepage).

I have used the Subscriptions module for allowing the user to subscribe to posts, but I am unable to configure the Views.

Any help will be appreciated.

# Answer
> 1 votes
Subscriptions does not currently have views support.

There is an issue for it here - http://drupal.org/node/269472 \- with a patch, however it is missing some parts and the author has not yet responded with the missing code.

I need it so I will be finishing the patch sometime in the next week unless someone beats me to it.

Until then, unless you want to code the views support yourself there is no views/subscriptions solution.

---
Tags: 7, views, notifications
---


title: Hiding link from anonymous users

text:
# Question
Title: Hiding link from anonymous users
How can I hide a particular link in the main menu from anonymous users without making the whole menu invisible?

# Answer
> 5 votes
You don't so much configure the visibility of links directly, but rather you configure the permissions of specific content types, and any link to content of a particular type will either be visible or invisible depending on the permissions of the content the link points to.

You can configure the permissions on any given piece of content by going into the Permissions section in Administration and finding the content type you want to restrict permissions on, and configure those permissions (check boxes for view, create, edit, etc..) based on role appropriately.

If you need to configure access to specific nodes/content, then you might have a look at Content Access.

# Answer
> 5 votes
You can do this easily *with a little bit of elbow grease!*

There are two hooks for this depending on if your menu is generated by a module or by Drupal itself. In a custom module you would use either hook\_menu or hook\_menu\_alter.

These two hooks have a parameter, `access callback` where you can give it a function that returns a BOOL. If the function returns TRUE, access is allowed and menu link is shown. If FALSE is returned, access is not allowed and menu link not displayed.

```
//Small example
function <your_module>_menu_alter(&$items) {
  // Example - disallow access for anonymous to node 15 from custom module
  $items['node/15']['access callback'] = '_accessCheck';
}

```

Then, further down you define the callback:

```
function _acccessCheck(){
  global $user;
  if ($user->uid) { // user is logged in
    return TRUE;
  } // Anonymous
    return FALSE;
}

```

Hope this helps, happy coding!

# Answer
> 3 votes
you could restrict users to see some of the menu links by using Menu per role module.
It allows you to restrict access to menu items based on user roles. So you could hide a particular menu link from a particular role and show it to others.

# Answer
> 2 votes
You can do it manually. Maybe, it isn't the best form, but it may fix you problem temporarily.
You can add a JavaScript file to you main `.tpl.php`. In this file you can play with the parent and children elements of you code (http://api.jquery.com/parent), by JavaScript methods. So, first you have to get your element, by something like `#idelement` (it may be positioned in the menu code between all the leafs of the menu) and then hide the element by `.hide()`. Also, you have to add to your code that the JavaScript file added to the `.tpl.php` only if the user is logged in. Like:

```
if(user_is_logged_in()){
   drupal_add_js(yourjSFile);
}

```

I repeat that is a temporary solution.
If you modified your code or element in the menu, this solution also must be modified.
This will only hide a menu item, and not the content types.

# Answer
> 0 votes
http://drupal.org/project/content\_access works really well for me with Drupal 7.22.

It even hides the main menu links pointing to restricted content.

---
Tags: 7, routes, navigation
---


# Question
Title: Field Collection : Query to get the node id by sending a value of a field collection field value
* I am having a field collection in a content type called 'client'. There are,

1. Client name
    2. Email
    3. Mobile
    4. Address 1
    5. Address 2
    6. Address 3
    7. etc.. as fields. That's it in the client content type.
* I am having another content type which basically has a textfield and a dropdown list
* The texfield allows to enter a client's name
* Once the client's name is filled in the textfield the dropdown list should be filled with client's addresses
* So what I am trying to do here is, programmatically generate the dropdown options by sending the client's name and getting their relevant addresses which was saved using the client content type.
* I'm quite confused with DB structure for field collection values.

Would be great if you can help ASAP

Thank you.

# Answer
You could try Field Collection Values

As it says, try

> To get the values of the individual field items call the entity\_load function:

```
<?php
  $node25 = node_load(25);
  $track_1 = entity_load('field_collection_item', array($node25->field_track[LANGUAGE_NONE][0]['value']));
  $track_2 = entity_load('field_collection_item', array($node25->field_track[LANGUAGE_NONE][1]['value']));
?>

```
> 1 votes

# Answer
This is not a complete working example you can just copy and paste but it has the elements you need (I can't do it exact as I don't know all your field names etc.).

```
// This should be set to the client name that has been entered into the client name field.
$client_name = 'John Doe';
// Get field collection items with the given client name.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'field_collection_item')
  ->entityCondition('bundle', 'FIELD_COLLECTION_NAME')
  ->fieldCondition('CLIENT_NAME_FIELD_ID', 'value', $client_name);

$result = $query->execute();

$field_collection_items = array();
if (isset($result['field_collection_item'])) {
  $field_collection_item_ids = array_keys($result['field_collection_item']);
  $field_collection_items = field_collection_item_load_multiple($field_collection_item_ids);
}

// If you expect there to only ever be one field collection item for each name, do this:
// From your description it seems like you only want to deal with a single one.
// This will be your client field collection item.
$client_field_collection_item = reset($field_collection_items);

// Otherwise, loop through the items that match the name and do something with each one.
// However, based on your question I will stick with the above single item.
foreach ($field_collection_items as $field_collection_item) {
  // Do something with each $field_collection_item here.
}

// To get the value of one of the fields of the field collection item, do this:
$lang = field_language('field_collection_item', $client_field_collection_item, 'FIELD_NAME');
$address1 = '';
if (!empty($client_field_collection_item[$lang][0])) {
  $address1 = $client_field_collection_item[$lang][0]['value'];
}

```
> 1 votes

---
Tags: nodes, entities
---


title: When should I use user_load($user->uid)

text:
# Question
Title: When should I use user_load($user->uid)
when do we need to load user using user\_load($user-\>uid) after global $user. Why do we need to load a user because we can access user data after declaring it global. I am adding a commerce customer to his billing and shipping profiles, should I use user\_load?

# Answer
> 7 votes
The global `$user` object is just the bare data received from the `users` table for the associated user. It doesn't have any field, or other module-added data, attached to it by default.

For example, if you have a field attached to your user accounts called 'field\_nickname', and you want to inspect the value of that field for the current user in code, you would need to call `user_load()` for the data to be available.

```
// Might work, but it's not guaranteed - depends on the modules
// you have installed and what's happened in the page build so far
$account = $GLOBALS['user'];
if ($items = field_get_items('user', $account, 'field_nickname')) {
  // ...
}

// Will always work.
$account = user_load($GLOBALS['user']->uid);
if ($items = field_get_items('user', $account, 'field_nickname')) {
  // ...
}

```

There are situations when other modules will load the field and other module data onto the global `$user` object, so depending on what modules you have installed you call to `user_load()` might not strictly be necessary.

However, it's good practice to make sure you load the object yourself; if another module has already run it for the current user then that data is statically cached, so you don't get a performance hit.

# Answer
> -1 votes
You don't need to do user\_load() on global $user.

global $user is already a loaded user (the current user).

use user\_load() when you want to load users other than the current user. for example, if you have a uid for the author of a node or comment, or a uid from a commerce order, then you use user\_load() to load the user object.

Unless (as Clive mentioned), you need to access fields attached to the user, in which case you should load it.

Also, if you want profile2 fields you will need to do

```
$profile = profile2_load_by_user($user, 'PROFILE_NAME');

```

---
Tags: commerce, users
---