title: Check contents of order in commerce

text:
# Question
Title: Check contents of order in commerce
So I have a custom module function that checks a cart order for a certain product type

```
global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);

foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $type = $line_item_wrapper->commerce_product->value()->type;
  if($type=='X'){
    //go mental
  }
}

```

This is used within checkout to display certain list items for "checkout progress" depending on whether a product type is in the cart (i.e show the gift aid stage if there is a donation).

The issue with this is it seems that when the order is no longer within the cart, for example when we hit the payment stage, and further go on to checkout complete. So the function `commerce_cart_order_load($user->uid);` no longer works. How would I achieve this same functionality checking the order for product of type 'X' when the order status is updated post-shopping-cart?

I think I can use $order = commerce\_order\_load(); but somehow I need to get the $order\_id?

# Answer
> 2 votes
```
$order_id = arg(1);
$orderLoad = commerce_order_load($order_id);

foreach ($orderLoad->commerce_line_items['und'] as $line) {
    $line_item = commerce_line_item_load($line['line_item_id']);
    $product_id = $line_item->commerce_product['und'][0]['product_id'];
    $product = commerce_product_load($product_id);
    $type = $product->type;

    if($type == 'X'){
      //go mental
    }
}

```

If anyone has any improvements to this code (to make it more efficient etc. then please comment below). Thanks.

---
Tags: 7, commerce
---


# Question
Title: Create a node(filedepot folder) after user registers in site
> **Possible Duplicate:**
> How to create new node programmatically, when a new user is created, in Drupal 7?

I am using Drupal-7 and Filedepot module. In Filedepot module a folder is created when we create node of **filedepot folder** content type.

I want to achieve that when any user registers in the site then one **filedepot folder** should be created.

Initially I used Rules module. And after registration I created a Rule to create a node of **filedepot folder** content type, but problem is that by using Rules I can't set some of the fields of content type. Node creation using Rules only creates node and sets title but it doesn't set the values of other fields.

Now I am planning to achieve it using other way, after user registers I want to create a node programmatically.

How can I customize Rule's **node create** action?

# Answer
This is how I managed it, and there was one problem regarding permission in folder creation. So I just assigned permission to create folder. and here is the code to create folder during user registration

```
function modulealter_user_insert(&$edit, $account, $category) {
    $node = new stdClass();
    $node->type = 'filedepot_folder';
    node_object_prepare($node);
    $node->language = LANGUAGE_NONE;
    $node->uid = $account->uid;
    $node->name = $account->name;
    $node->title = check_plain($account->name);
    $node->filedepot_folder_desc[LANGUAGE_NONE][0]['value'] = 'This is private folder of author user.';
    $node->parentfolder = 4;
    $node->inherit = 0;
    node_save($node);
    watchdog('filedepot',"New folder created @name - new filedepot folder created.", array('@name' => $account->title));
}

```
> 1 votes

---
Tags: 7, users, files
---


# Question
Title: How to add css and js to a views-view-table--viewname.tpl.php
I am theming a particular view "test" so my theme file is "views-view-table--test.tpl.php". Its working fine.

I want to add css and javascript to the "views-view-table--test.tpl.php" file Used the below code to add css and javascript. but its not working:

```
drupal_add_css("themes/bartik/style-test.css", $type = 'file', $media = 'all', $preprocess = FALSE);
drupal_add_js("jquery.min.js", $type = 'file', $media = 'all', $preprocess = FALSE);

```

How to add css and js to views-view-table--viewname.tpl.php file.

# Answer
You could do this by using a process function at theme level...

```
function YOURTHEME_preprocess_views_view(&$vars) {
    if (isset($vars['view']->name) && $vars['view']->name == 'YOURVIEW') {
        drupal_add_css("themes/bartik/style-test.css", $type = 'file', $media = 'all', $preprocess = FALSE);
        drupal_add_js("jquery.min.js", $type = 'file', $media = 'all', $preprocess = FALSE);
    }
}

```
1. Change 'YOURTHEME' to the theme you are using so if 'bartik' then you want bartik\_preprocess\_views\_view().
2. Change 'YOURVIEW' to the name of your view. You can get this by printing $vars\['view'\]-\>name from the function.
3. Clear caches after adding function.
> 4 votes

---
Tags: 7
---


title: block restrict depending on role

text:
# Question
Title: block restrict depending on role
I use this snippet to restrict block visibility from administrator

```
<?php
global $user;
if (user_access('access administration pages') || ($user->uid == 6)) {
  return FALSE;
} else {
  return TRUE;
}
?>

```

I also want to restrict this block from role 6. However, it does not work. Can somebody help?

Thank you

# Answer
```
// Check to see if $user has the administrator role.
  if (in_array('administrator', array_values($user->roles))) {
    // Do something.
  }

```

Replace "administrator" with the role name you want to check.

EDIT:

If you want to check for role id's use below code.

```
global $user;
$role_ids = array_keys($user->roles);
if (in_array(6, $role_ids)) {
  // Do something
}

```

In your case

```
<?php
global $user;
$role_ids = array_keys($user->roles);
if (user_access('access administration pages') || (in_array(6, $role_ids))) {
  return FALSE;
} else {
  return TRUE;
}
?>

```
> 1 votes

# Answer
`$user->uid` is the user ID, which is different from the role ID of the role assigned to the user.

If you want to avoid that users having the role with ID equal to 1 (or 6) see the block, you should use the following code.

```
<?php
  $roles = $GLOBALS['user']->roles;
  return (!isset($roles[1]) && !isset($roles[6]));
?>

```

If with administrator you mean the first user created when Drupal is installed, then you should use the following code, supposing that you are still interesting in avoiding the users with the role #6 see the block.

```
<?php
  global $user;
  return ($user->uid != 1 && !isset($user->roles[6]));
?>

```
> 0 votes

---
Tags: blocks
---


title: Set users password in code?

text:
# Question
Title: Set users password in code?
I would like to be able to change a users password in code.

Since `user_load` returns an object, and `user_save` wants an array, this is non-trivial.

I assume someone has figured out a quick and easy way to do it.

---

My current solution looks like:

```
db_update('users')
  ->fields(array('pass' => user_hash_password('some_password')))
  ->condition('uid', 1)
  ->execute();

```

But I don't like that this bypasses most hooks.

# Answer
You just need to call `user_save()` using code similar to the following one.

```
$edit['pass'] = 'New password';
user_save($account, $edit);

```

`$account` contains the user object for the user account to alter. I get you load it using `user_load()`, but it could also be the user object for the currently logged in user. In the latter case, Drupal will regenerate the session using the following code (part of user\_save()).

```
  // If the password changed, delete all open sessions and recreate
  // the current one.
  if ($account->pass != $account->original->pass) {
    drupal_session_destroy_uid($account->uid);
    if ($account->uid == $GLOBALS['user']->uid) {
      drupal_session_regenerate();
    }
  }

```

The password in `$edit['pass']` is the plain password. `user_save()` will replace it with its hash using the following code (at the beginning of the function).

```
if (!empty($edit['pass'])) {
  // Allow alternate password hashing schemes.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  $edit['pass'] = user_hash_password(trim($edit['pass']));
  // Abort if the hashing failed and returned FALSE.
  if (!$edit['pass']) {
    return FALSE;
  }
}

```

As alternative, you could use drupal\_submit\_form().

```
$form_state = array();
$form_state['user'] = $account;
$form_state['values']['pass']['pass1'] = 'New password';
$form_state['values']['pass']['pass2'] = 'New password';
$form_state['values']['op'] = t('Save');
drupal_form_submit('user_profile_form', $form_state);

```

In this way, if you have any module that, for example, validates the password, its code would be executed, and you would get any error code from form\_get\_errors().
> 19 votes

---
Tags: users
---


title: How cron.php works for watchdog?

text:
# Question
Title: How cron.php works for watchdog?
I want to truncate the table 'watchdog' once a day.

So I heave:

1. to set the maximum rows number from the 'Logging and Alerts' (of Site Configuration) to 1000
2. create a crontab on my system to run the root/cron.php once a day

But I can't understand how the process goes. The crontab calls the cron.php . What is the process next?

I see the file cron.php includes the bootstrap.inc. Why is that?

Where is the actual code with the mysql queries (truncate) inside?

I need to understand the process to make some changes to a site.

I have googled it enough and have not find any information.

# Answer
> 4 votes
cron.php initiates a call to function `drupal_cron_run()` (in common.inc) which will finally make all calls to all cron tasks.

```
/**
 * Executes a cron run when called
 * @return
 * Returns TRUE if ran successfully
 */
function drupal_cron_run() {
.
.
// Iterate through the modules calling their cron handlers (if any):
module_invoke_all('cron'); // This will call all cron functions defined in modules(enabled)
.
.
}

```

`dblog_cron()` will get invoked by `module_invoke_all('cron')` This is responsible for clearing old entries in your watchdog table. If this function does not suit your requirements you can use Ultimate Cron to disable it alone. This is a good admin tool to manage your cron jobs. Then you can write your own cron task in another module and enable it.

```
function dblog_cron() {
  // Cleanup the watchdog table
  $max = db_result(db_query('SELECT MAX(wid) FROM {watchdog}'));
  db_query('DELETE FROM {watchdog} WHERE wid <= %d', $max - variable_get('dblog_row_limit', 1000));
}

```

Note : This is wrt Drupal 6. in D7 module invoke is slightly different

# Answer
> 2 votes
crontab calls cron.php. This file makes a complete Drupal bootsrap and then Drupal starts to call all modules that implements the hook\_cron().

So, if you want to do something when cron is run, write a module that implements hook\_cron().

watchdog table is not truncated, when you set maximum number of entries Drupal deletes old entries.

Anyway, I'm not sure if it's a good practice to truncate watchdog table. You may lose valuable information about errores produced before truncate.

---
Tags: database, cron, log-messages
---


title: Strange Drupal behaviour after update

text:
# Question
Title: Strange Drupal behaviour after update
After updating Drupal from 7.15 to 7.16, I noticed a strange behavior.

If my custom module is enabled, the website design is broken in Internet Explorer. I don't see some parts of website: The front page shows only slideshow, I don't see filters or even the whole pages. If a custom module I am using is disabled, everything is OK. I tried to downgrade again to 7.15, but I still have the same error.

I really don't understand why it happened, as I didn't have any problems with Internet Explorer, and my module before the update.

Can anyone help me with my problem?

This is the code used from my custom module.

```
/**@file This module provides custom functions    */

/** Unset these form elements from the comment_form using hook_form_alter */

function custom_module_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['name']['#access'] = FALSE;
  return $form;
}

/** Implements hook_block_info(). This hook declares what blocks are provided by the module.*/
function custom_module_block_info() {
  $blocks['contact_block_form'] = array(
    'info' => t('Contact Form'),
  );

  return $blocks;
}

/** Implements hook_block_view(). This hook generates the contents of the blocks themselves. */
function custom_module_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'contact_block_form':
      $block['subject'] = t('');
      // Load contact pages inc as the form definition sits there.
      module_load_include('inc', 'contact', 'contact.pages');
      $block['content'] = drupal_get_form('contact_site_form');
      break;
  }

  return $block;
}

/** Views - Exposed Filter Form Theming  */

function custom_module_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'location') {
    $form['field_location_tag_tid']['#options']['All'] = t('- choose region -');
    $form['field_poselok_tag_tid_option_limit']['#options']['All'] = t('- choose city -');
$form['field_poselok_tag_tid_option_limit']['#states'] = array(
      'disabled' => array('select[id="edit-field-location-tag-tid"]' => array('value' => 'All')),
    );

    $form['type_1']['#options']['All'] = t('- choose gallery type -');
    $form['field_author_tid']['#options']['All'] = t('- choose gallery author -');
    $form['field_author_tid']['#states'] = array(
      'invisible' => array('select[name="type_1"]' => array('value' => 'gallery')),
    );
  }
}

```

# Answer
> 0 votes
I placed `<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">` in and now my website looks fine in IE.

---
Tags: 7, updating
---


title: Approach to create team roster?

text:
# Question
Title: Approach to create team roster?
I'm trying to create a team roster content type. Each team member has first name, last name, tel number, character name and a photo.

Attempt #1: I've installed NameField module which allowed me to add/edit players on the team. The problem with Name field is that i can create unlimited number of players in team roster, but namefield doesn't provide a field to upload a photo to each of them.

Attempt #2: I tried to create a content type called 'Player' with fields for name, photo, and tel number. Then create a View with sorted table. My problem: User needs to constantly click add Player to create more than one player. Is there any way to make it more user-friendly? For example, Just click 'Add one more field' without getting into content creating menu?

Question: Approach to create sorted table view of players name, tel. number, and photo?

# Answer
> 2 votes
Try using the Field Collection module.

Create a collection of fields and then attach it to the content type as one field.

---
Tags: views, entities, nodes
---


title: 24 hour notation for Time Field

text:
# Question
Title: 24 hour notation for Time Field
I'm using Time Field to make a field in my event content type for the begin and endtime in of the event. I know that when you outpout the time field via views, you can output it as 24h notation, which works fine. But I want to output the time using php in a tpl file using the row object. So I have php code in my views tpl file that says:

```
    <?php $uur  = $row->field_field_evenement_uur[0]['rendered']['#time']['value_formatted'];
          $uur .= ' - ';
          $uur .= $row->field_field_evenement_uur[0]['rendered']['#time']['value2_formatted'];
?>

```

First thing that came to mind of course was go to `admin/structure/types/manage/my_content_type/fields/my_time_field` and set the field formatting to 24h notation. It simply looks though like it's not part of the configuration.

Then I debugged my `$row` output in my view to discover this other way to get a rawer sort of value for the time. This way I would write code like:

`$row->field_field_evenement_uur[0]['raw']['value'];`

So that would output the time value like `51600`. I've been looking for some formatter functions that I could wrap around this value and get me a 24hour notation, even from php.net but it's all seeming like it has to do with the `date();` function.

# Answer
> 1 votes
I totally looked past the display fields part of the field configuration of fields ui. That's exactly where you can set it to output 24hr notation.

---
Tags: 7, entities
---


# Question
Title: How to pass arguments based on term filter
I have content type called 'software' and added taxonomy terms to this content type as select list. There are 10 taxonomy terms in that list. And now I have created 10 pages under this 'software' content type with 10 different taxonomy terms selected among them.

```
> Page1 -> Term1
> Page2 -> Term2
> etc.

```

What I need is, If i see www.mysite.com/taxonomy/term/3 in the url, I need to display only the page title of the listed nodes in the view (rather than the title and teaser), for those nodes tagged with taxonomy term(3).

How can I achieve using views arguments and filters?

# Answer
If I understand your question correctly, here are the steps you'd need to take to override the default taxonomy term view with your own customized one.

* Go to the listing of available views on your site at **/admin/structure/views** and at the bottom of the page you'll see grayed out views that are not enabled. One of them will be the Taxonomy term view which is delivered by default with the module. Let's go ahead and clone it, so we can customize to fit our needs.
* Hit '**clone**' next to that view, in the drop-down options and rename it to something like 'Custom Taxonomy term'

* Next, navigate to the 'Page' display and change the Format to display '**Fields**' instead of 'Content: Teaser'

* Add whatever fields you want. It sounds like in your case, you'd want to add the Title field. I would uncheck the label from being displayed (uncheck '**Create label**') when configuring the field.

* Finally, save and navigate to your view again: www.mysite.com/taxonomy/term/3 and see the change! Your new view should be picked up and will replace the old one.

Go ahead and beautify and edit as you please from now on to customize the default terms view. Hope this helps!
> 1 votes

---
Tags: 7, views
---


# Question
Title: After adding new content type, drupal (7) returns to same window without any notification
As in the title, every time I add a new content type Drupal returns to the same page and provides no notifications.

Also, the overlay window is full screen width. Any ideas? No error logs.

# Answer
What do you mean by adding content type? It Is normal that drupal return to the front page after creating a new content type...

Do you mean creating a node?Where does drupal returns?
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Custom module is not showing up for regular user
This is what Drupal returns if URL defined from the module is accessed:

> Access denied
> You are not authorized to access this page.

THe permissions are all checked for authorized, and anonymous users.

The implementation of `hook_menu()` is the following.

```
function qarena_menu() {
  $items = array();

  // This determines the path used to show the form and also makes a menu entry
  // This first path is for the entry form
  $items['qarena'] = array(
    'title' => t('QArena'),
    'page callback' => 'qarena_display_page',
    // drupal_get_form, registers the given form in drupal.
    'access arguments' => array('ask question'),
  );

  return $items;
}

```

# Answer
user\_access(), the access handler used by default from Drupal when no other access handler has been set, returns `TRUE` (the user has access to the menu) only when the permission string is one defined from a module, and the user has that permission.

If "ask question" is not a permission defined from any module with hook\_permission() (Drupal 7 or higher), or hook\_perm() (Drupal 6 or lower), then you will get an access denied error.

Once you are sure a module (including the one you are developing) defines the permission you want to use, be sure the same permission is assigned to any of the roles the currently logged-in user has. For example, if the user has the role of *editor*, then the permission you are using needs to be assigned to the *editor* role, or to the *authenticated user* role.
> 3 votes

---
Tags: 6
---


# Question
Title: More efficient use of function by storing the result?
So I have a custom module that is simply one function that during Commerce checkout goes through the order or cart to create an array saying how many "products" of type 'event','donation' and 'product' there are in the cart.

Now this all works great and I use it to do multiple things such as:

* Change the title page of the checkout if someone is "donating" rather than "purchasing"
* Show or hide certain checkout panes depending on whether a 'donation' or 'event' is in the cart
* Render a checkout progress bar which shows certain checkout pages, again dependent on the product types currently in the cart.

My issue now is that on render of the Checkout Details page I have this one function executing 4 separate time. How would I go about triggering it once for each load of a page and storing the array in a place that can be accessed by multiple modules and template files?

# Answer
Seeing as how the data is not really an item that is cachable sitewide, you could quite easily use the `$_SESSION` variable.

Example:

```
function my_expensive_function($foo, $bar) {
  if (isset($_SESSION['my_really_cool_stuff'])) {
    return $_SESSION['my_really_cool_stuff'];
  }
  else {
    //Do what you would normally do to get everything you need
    //and put it in a $my_really_cool_stuff variable
    $_SESSION['my_really_cool_stuff'] = $my_really_cool_stuff;
    return $my_really_cool_stuff;
  }
}

```

This way, if the data already exists in the user session, it'll return that. If not, then it'll generate it, put it in the session, and then return it.

You can put the `$_SESSION` data into a theme function and make it available to templates as well if you wish, but that's probably a separate question (and you'd have to make sure you had a fallback in case the session data had not been set).
> 1 votes

# Answer
It looks like storing the array in a global or static variable would be a good solution for this use case. For example you could rebuild the function to make use of drupal\_static() similarly to this:

```
function my_module_function() {
  $my_data = &drupal_static('my_static_variable');
  if (!isset($my_data)) {
    // Do your calculations here, and populate $my_data
    // with the correct stuff.
  }
  return $my_data;
}

```

For some more detailed explanations I'd suggest reading A beginner's guide to caching data in Drupal 7 (took the code example from there as well).
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: different templates for print and deafult version of the node
I've faced with a problem of differentiating node templates for print-version (I'm using "print" module) and default node's default template.

I have a `<div>` which should be present in node--node\_type.tpl.php but not in print-version (it contains info that is not required when viewing the page not on the display).

Currently I'm solving this with adding

```
<?php if (arg(0) == 'node'): ?>
<div>.....</div>
<?php endif; ?>

```

But it seems to me that this kind an awkward way.

Can you offer any Drupal-alike and more convenient way to gain that?

Thank you.

# Answer
> 0 votes
Well, I've been inspecting the Print module code for a while and figured out the right solution. ( Mr. jdu's answer is still right too but if I have to build completely different templates for printer-friendly and default versions of nodes, it just won't be enough). So for those who may face this problem:

Print module creates a view mode called 'print'. When you get on /print/%nid page, a special function is fired that renders the node in 'print' view mode. Inspecting the code further we find that in 'print' view mode, in preprocess function, it adds the following theme\_hook\_suggestions:

```
if (($variables['elements']['#view_mode'] == 'print') && isset($variables['elements']['#print_format'])) {
  $type = $variables['elements']['#node']->type;
  $format = $variables['elements']['#print_format'];
  $nid = $variables['elements']['#node']->nid;

  $variables['theme_hook_suggestions'][] = "node__print";
  $variables['theme_hook_suggestions'][] = "node__print__{$format}";
  $variables['theme_hook_suggestions'][] = "node__print__{$format}__node__{$type}";
  $variables['theme_hook_suggestions'][] = "node__print__{$format}__node__{$nid}";
}

```

Therefore, all we need is create, in my case, "node--print--html--node--nbt\_text.tpl.php" (underscores from suggestions turn into dashes, my content type is 'nbt\_text').

# Answer
> 1 votes
load a print only CSS file and "display:none" for that div in it:

---
Tags: theming
---


# Question
Title: Is complex field validation possible with WebForm?
WebForm is a *very* nicely done module, but (at least at first glance) it seems to lack some things that I expect to need.

Specifically, I'd like a way to specify more complex field requirements than just a boolean. For instance, what if I have a form with an e-mail address field and a telephone field, and I want the user to be required to enter at least one of the two. In other words, if they enter an e-mail address, they don't need to enter a phone number; and if they enter a phone number, they don't need to enter an e-mail address.

Is this possible with WebForm?

# Answer
> 1 votes
Try using the WebForm Validation module.

> The following validation rules are currently included:
>
> * Numeric values (optionally specify min and / or max value)
> * Minimum length
> * Maximum length
> * Minimum number of words
> * Maximum number of words
> * Equal values on multiple fields
> * Unique values on multiple fields
> * Specific value
> * ***Require at least one of two fields***
> * ***Require at least one of several fields***
> * Minimum number of selections required
> * Maximum number of selections allowed
> * Exact number of selections required
> * Plain text (disallow tags)
> * Regular expression
> * Must be empty (Anti-Spam: Hide with CSS)
> * Words blacklist
> * Must match a username

# Answer
> 1 votes
If your validation logic is complex it might be better to do that through a custom module.

There are three ways:

1. Regular `hook_form_alter()` and adding your validation callback to the `$form['#validate']` array.
2. Implement `hook_webform_validation_validators()`.
3. Implement `hook_webform_validation_validate()`.

See this article for more information about 2. and 3.

---
Tags: webforms
---


# Question
Title: How can I display Drupal comments on a separate page from hook_node_view()?
I have a custom implementation of `hook_node_view()` that changes the display of comments on every node. I would like to know how I can get the result of this improved `hook_node_view()` to be displayed on a separate page.

Each node should have its own comment page.

I have tried doing this with the Views module, but it seems bypassing `hook_node_view()`, which makes sense. So I'm still brainstorming on a way that can make this possible.

# Answer
> 1 votes
The Talk module shows the comments for a node in a tab added to the node page.

> The talk module removes comments from the node page and puts them on a separate tab. This style of commenting is very popular on Wiki sites (usually called the "discussion" page) and on news websites where the goal is to separate user generated content from editorial content.
>
> When installed this module will add a tab to the set of tabs at the top of a node view page like "View | Edit | Talk" and provides a link at the bottom of the node to go to the talk page and view comments.

If you need to do something similar, but on a completely different page, you can look at the code of the module to write similar code.
In short, apart from implementing `hook_node_view()`, the module implements `hook_node_load()` to set `$node->comment` to 0 (after saving its value in another node property). Then it calls comment\_node\_view() after temporary setting the values of the Drupal variables used from that function.

```
  global $conf;
  $clone = clone($node);
  $clone->comment = _talk_node_comment_value($clone);
  $recover = FALSE;
  if (array_key_exists('comment_form_location_' . $node->type, $conf)) {
    $original_setting = $conf['comment_form_location_' . $node->type];
    $recover = TRUE;
  }
  $conf['comment_form_location_' . $node->type] = COMMENT_FORM_SEPARATE_PAGE;
  comment_node_view($clone, $view_mode, $langcode);
  if ($recover) {
    $conf['comment_form_location_' . $node->type] = $original_setting;
  }
  else {
    unset($conf['comment_form_location_' . $node->type]);
  }

  // Display comment summary
  $addcmnt = ((_talk_node_comment_value($node) == COMMENT_NODE_OPEN) && (($view_mode != "teaser") || variable_get('talk_addcmnt_teaser', TRUE)));
  if ($addcmnt) {
    $links = $clone->content['links']['comment']['#links'];
    $node->content['links']['comment'] = array(
      '#theme' => 'links__node__comment__talk',
      '#attributes' => array(
        'class' => array('links', 'inline'),
      ),
    );

    foreach ($links as $link) {
      if(talk_activated($node->type)) {
        if (isset($link['href']) && $link['href'] == 'node/' . $node->nid) {
          $link['href'] .= '/talk';
        }
      }
      $node->content['links']['comment']['#links'][] = $link;
    }
  }
  // Add the Talk link if user has access and it's not blank
  if (_talk_access($node) && strlen(variable_get('talk_link', '')) > 0) {
    $node->content['links']['comment']['#links'][] = array(
      'href' => 'node/' . $node->nid . '/talk',
      'title' => talk_title($node, 'link'),
    );
  }

```

---
Tags: hooks, nodes
---


title: Custom form in pop-up

text:
# Question
Title: Custom form in pop-up
I need to show a custom feedback form when canceling an event.

I used a jQuery modal form for this purpose, but I want to use any Drupal 6 module, or functionality, to save the feedback for future purposes.

Is there any module I can use?

# Answer
There are two ways of doing this:

1. Using Modal Frame API
2. Using CTools

I've used both to successfully create modal popups with embedded forms. In both cases I first needed to create the form using Drupals form api and then assign an event for either MFA or ctools to bind to.

Overall I found MFA easier to get something up and running but ultimately ctools is more powerful and will give you a better understanding of a module that is now used widely throughout contrib modules.

Both modules documentation is the best place to start, MFA has great documentation pages and ctools has some excellent sample modules in the project itself.
> 1 votes

---
Tags: forms, 6, javascript
---


title: Multisites with subdirs for each site

text:
# Question
Title: Multisites with subdirs for each site
I'm starting with Drupal and I would like to have one instance of Drupal on my dev plateform with each project in a subfolder:

* I don't want to have to change my host (and my customers hosts)
* I need to keep drupal in a subfolder on my domaine (`mydomain.tld/drupal`)

Every website should be accessible like this :

* mydomain.tld/drupal/customer1.com
* mydomain.tld/drupal/customer2.org

I know that I have to add some configuration in sites/sites.php and I tryed:

```
$sites = array(

    'mydomain.tld.drupal.customX.com' => 'customerX.com'

);

```

But it looks like the rule is not used and I have a not found error...

Could you help me with that?

# Answer
> 0 votes
You need to create subfolders like this:

yourdomain.com/drupal/sites/site1.com

yourdomain.com/drupal/sites/site2.net

yourdomain.com/drupal/sites/site3.org

and park domains site1.com , site2.net , site3.org to folder yourdomain.com/drupal/

# Answer
> 0 votes
I don't think you need the "$sites = array" part. I know it says it in the comments, but I just list them in the sites.php file:

$sites\['mydomain.net'\] = 'mydomain.net';

$sites\['otherdomain.net'\] = 'otherdomain.net';

$sites\['thirddomain.net'\] = 'thirddomain.net';

And don't forget the folders like Boris mentioned.

# Answer
> 0 votes
It's really tricky to get this working correctly but the documentation is already on Drupal.org - http://drupal.org/documentation/install/multi-site check the Subdirectory multi-site section. I've also posted a more concise version here which is more to specific needs.

---
Tags: 7, multi-sites
---


title: Boost VS Drupal Cache

text:
# Question
Title: Boost VS Drupal Cache
I'm using Boost and Drupal internal cache on two different websites and i m remarking that the site with internal cache is more quickly than the site with the Boost module .
So I'm asking which between the two methodes are suitable ?
Thank you very much

# Answer
> 6 votes
Boost bypasses execution of Drupal's PHP and serves static files. So unless you have other problems, it should always be much faster than the standard Drupal cache. Be aware that it only works for anonymous users.

View source on your pages when running boost and make sure they have a comment at the end that says cached by boost. Boost puts that comment there by default. If you haven't disabled it, and it's not there, boost isn't working properly. It's usually caused by incorrect or missing .htaccess rules. If you don't see this comment, you won't see an error on the status page. Your site will work normally, but is not being cached.

It looks like this:

```
</body>
</html>
<!-- Page cached by Boost @ 2012-10-30 15:01:23, expires @ 2012-10-31 15:01:23 -->

```

---
Tags: performance, caching
---


# Question
Title: Is there advantage to using Drupal.settings, as opposed to directly passing json-encoded var to javascript function
Inside my custom views template, views-view-myview.tpl.php, I have a variable ("$myvar"), which I need to pass to a custom javascript function. Here is how I am currently doing it:

A. json-encode $myvar

```
<?php
$my_json_var = json_encode($myvar);
?>

```

B. Pass the variable as an argument to my custom function, on page load

```
<script>
Drupal.behaviors.mystuff = function (context) {
  my_js_function(<?php print $my_json_var; ?>);
});
</script>

```

I am noticing that Drupal developers generally pass variables to javascript using Drupal.settings, and I am wondering whether I should switch and use Drupal.settings instead.

Question: Is there any disadvantage of doing things my way, as described above? Is there any reason it would be better to switch to Drupal.settings. Note: $myvar is relatively large, say 100k.

Thanks very much

# Answer
> 4 votes
The advantage of having in Drupal.settings is the values can be globally accessed across the JavaScript functions. In your case the function "my\_js\_function" only can access it because of its scope. It is based on the need and if you feel it is unnecessary to have it in settings then you can go with your method.

But best practice is to use Drupal settings. This method will never fail you.

---
Tags: 8, javascript
---


# Question
Title: How can I send Newsletter in HTML format?
I have installed the following modules simplenews, mailsystem, html mail to send HTML news letter from a Drupal 7 site. Right now, I am just able to send plain text email from send test option. How can I send an HTML email from my site? How can I send a newsletter to registered emails of my site?

# Answer
You can use Mime mail along with your newsletter module to enable HTML in your emails. This module will work on the message mime so it should work with almost any mail module
> 3 votes

---
Tags: emails
---


title: Restricting access to nodes

text:
# Question
Title: Restricting access to nodes
I am new to Drupal and for some time now I am trying to figure out how to control access to nodes. After figuring out that no module will give me what I want and deciding that I will have to get my hands dirty and write my own.

The problem is that nothing works and in no way I can restrict access to nodes.

To make things simple I tried blocking everything to anything in any way I found, but it makes absolutely no difference.

```
function mymodule_node_access_records_alter(&$grants, $node) {
  $grants=array();
}

function mymodule_node_access_records($node) {
  return array();
}

function mymodule_node_access($node, $op, $account) {
  return NODE_ACCESS_DENY;
}

```

The module is loaded by drupal, it is parsed (I get error messages when something is wrong), I tried clearing the cache, tried loading the module on and off, I disabled OG Access Control (I still have OG field access running).

The OG access modules are working more or less correctly (sometimes they block what you want them to block).

I am probably forgetting about something obvious but I feel like I tried everything.

# Answer
> 1 votes
Thank you guys for brief answers.

After a good night sleep I fixed the problem. The problem was with brackets (I had functions declared inside a function :/ ). The strange part was that php server was only sometimes returning error Fatal error: Cannot redeclare mymodule\_......

As for the node access restriction.

```
function mymodule_node_access_records_alter(&$grants, $node) {
  $grants=array();
}
function mymodule_node_access_records($node) {
  return array();
}

```

Does not work. It is a pity because I would prefer to use the more powerful grants engine.

```
function mymodule_node_access($node, $op, $account) {
  return NODE_ACCESS_DENY;
}

```

Works as expected.

A thing to mention is that I have to reinstall my module in Drupal for him to notice the new hook implementation.

# Answer
> 2 votes
In the code you are showing there are some mistakes.

* If you implement `hook_node_access_records_alter()`, you don't implement `hook_node_access_records()` (and viceversa)
* If you implement `hook_access_records()`, then you don't implement `hook_node_access()` (and vice versa).
* If you implement `hook_node_access_records()`, the other hook that need to implement is `hook_node_grants()`.
* Returning an empty array in `hook_node_access_records()` or setting `$grants` to an empty array in `hook_node_access_records_alter()` doesn't mean blocking every users from accessing any node. In fact, the function that invokes `hook_node_access_records()` and `hook_node_access_records_alter()` (`node_access_acquire_grants()`) contains the following code.

```
$grants = module_invoke_all('node_access_records', $node);

// Let modules alter the grants.
drupal_alter('node_access_records', $grants, $node);

// If no grants are set and the node is published, then use the default grant.
if (empty($grants) && !empty($node->status)) {
  $grants[] = array(
    'realm' => 'all',
    'gid' => 0,
    'grant_view' => 1,
    'grant_update' => 0,
    'grant_delete' => 0,
  );
}

```

When `$grants` is empty, it adds the default grant that allows users to see the nodes (if other conditions are met).

Even implementing the right hooks, a module is not able to stop every single user from accessing all the nodes, since:

* Users with the *bypass node access* permission can still access any node; this includes the first user created on a Drupal site
* When viewing a node that is unpublished, the user who created it can still see it, if that user has the *view own unpublished content* permission

See the code in `node_access()`, in particular the following lines.

```
  if (user_access('bypass node access', $account)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }
  if (!user_access('access content', $account)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }

  // We grant access to the node if both of the following conditions are met:
  // - No modules say to deny access.
  // - At least one module says to grant access.
  // If no module specified either allow or deny, we fall back to the
  // node_access table.
  $access = module_invoke_all('node_access', $node, $op, $account);
  if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }
  elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }

```

Assuming you aren't interested in blocking the access to users with the *bypass node access* permission, or avoiding that users with the *view own unpublished content* permission can see their own unpublished nodes, then implementing `hook_node_access()` is the quicker way to avoid some users can see all the nodes, as long as the nodes aren't shown in a list of nodes, for example a view, or the front page, because in that case `hook_node_access()` is not even invoked.
Differently, the following code surely works and avoid some users can see every node.

```
function mymodule_node_access($node, $op, $account) {
  return NODE_ACCESS_DENY;
}

```

If that code doesn't work, then there is an error in the code of the module your wrote, since:

* A single module returning `NODE_ACCESS_DENY` in `hook_node_access()` stops users from seeing a node (but remember the permissions part)
* Drupal core doesn't use `hook_node_access_alter()`, so a module cannot alter the value returned from your module, and change that value from `NODE_ACCESS_DENY` to `NODE_ACCESS_ALLOW` or `NODE_ACCESS_NEUTRAL`

# Answer
> 0 votes
Be sure to check the site as an anonymous/regular user - if you are logged in as a super admin (uid: 1) you will be able to access the nodes no matter the permissions.

---
Tags: nodes, hooks, users
---


# Question
Title: Populate a field with the sum of two fields while content creation
I have a content type named "ABC". Which has three fields

* `field_half`(widget type list(text)),
* `field_full`(widget type list(text)),
* `field_total`(widget type float).

During content creation I want the `field_total` to be populated with the sum of two fields `field_half` and `field_full`.

E.g.

```
`field_total` = `field_half` + `field_full`

```

How can I do this.

# Answer
Sounds liks a job for Computed Field

> Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, **including other fields**, the current user, database tables, you name it.

You should just be able to set the field value literally as in your example (i.e. field = fieldA + fieldB)
> 1 votes

---
Tags: 7
---


# Question
Title: Is it possible not to have $_GET values in views' exposed filters?
I can't seem to find a setting to do this nor am I familiar with any hook to implement this. Is it even possible?

I don't want to use ajax though.

# Answer
> 1 votes
Seems that the $\_GET values are hardcoded into the exposed filters and that apart from using ajax (which In this use case I want to avoid) it can't be done. Will gladly pass the checkmark along if someone proves me wrong :)

# Answer
> 1 votes
You can enable Ajax and extra stuff will not be added to the URL. If the problem is too long URLs, do a google search and see how short the URL is. However you can clean up the URL (that means you will use $\_GET values) by setting a shorter URL parameter identifier.

Click on the exposed filter and expand the exposed filter settings. You will see a text field to enter the parameter string for this filter. Give a meaningful but tiny string.

For example, default URL would be like: path/to/view?field\_my\_weird\_field=drupal

You can change it to: path/to/view?text=drupal

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


# Question
Title: Why computed field is not getting displayed while creating content
I using "computed field" Module. I have installed the 7.x-1.0-beta1 version computed field module. Enabled and save the configuration.

I have created a computed field and just displayed "Hello" in my content type "abc".

**But this "computed field is not getting displayed while content creation.**

Any ideas why this computed field is not getting displayed.

# Answer
Try adding the following JavaScript to your theme or in a module (so it's added on the page you are working on with the fields):

It's pretty rudimentary, but it works! You might want to expand it to work on keypresses rather than `.change()` events.

```
Drupal.behaviors.jqFill = {
    attach: function(){
      $('#edit-field-half-und-0-value, #edit-field-full-und-0-value').change(function(){
        half = parseInt($('#edit-field-half-und-0-value').val());
        full = parseInt(+$('#edit-field-full-und-0-value').val());
        total = half + full;

        if(!isNaN(total)){
          $('#edit-field-total-und-0-value').val(total);
        }
      });
    }
  }

```

**Note** I got the field names from your other question here.
> 0 votes

---
Tags: 7
---


# Question
Title: How can I add custom content to a Drupal 6 menu?
1) Currently I have drop down menus for primary & secondary links. They need to now be *mega-menus*, and need to include the item teaser as well as the link:

```
<li>
  <a href='#'>Link 1</a>
  <p>Teaser for this link</p>
</li>

```

2) We also want to include webforms or any content in a menu list item. I am hearing that blocks are the way to go, but again, am a bit confused.

Can anyone help?

# Answer
Try the megamenu module. I haven't used it, but it appears to be designed to do exactly what you are looking to do. Unfortunately, it appears that the capability to add blocks inside menu items only exists in the version for Drupal 7, but the D6 version supports most of the functionality you need.
> 2 votes

# Answer
If you're using Panels, then the Menu Minipanels module might be of use.

> Megamenus built using (mini) Panels, which provides tremendous flexibility in what can be displayed. New stable releases due soon for both Drupal 6 and 7.

This is pretty good too:

> Click-by-click beginner's tutorial: http://drupal.org/node/984560#comment-3922442
> 1 votes

---
Tags: 6, routes
---


# Question
Title: Extending a year range of a popup calendar
Good day

Is there a way I can extend a year range of a popup calendar in drupal 7?

# Answer
Provided you have a *Date* field, the widget you use is the "Pop-up calendar" *and* there is no data in the field yet, you can edit the field and it holds the settings as shown below. Increment the ending year in the field settings
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How to organise children menu links as tabs in D7?
I'm using Drupal 7 and now I have a regular dropdown menu like this:

Link 1

* sub-link 1
* sub-link 2

Link 2

But I would like to organize my sub-links as tabs where sub-link 1 and sub-link 2 would be a content tabs that contain a block content. I tried to use OM Maximenu Modul, it helps to organise parent links as tabs but not sub-links. Could anybody help me in this question?

# Answer
Instead of OM Maximenu module I used Views Menu module as it easier and I used it only with purpose to attach views block to only one menu link.
> 0 votes

---
Tags: routes
---


title: Imagecache: configure image canvas

text:
# Question
Title: Imagecache: configure image canvas
I'm using Drupal 7 and I'm trying to create an image style, which resizes and crops an image and adds another image as the background. The latter image is the canvas for this image style. I am using the Imagecache module and so far I tried either adding the canvas image as "Underlay (background)" or as "Overlay (watermark)", but with either of these selections the problem is that the background image and the front image are positioned at x:0, y:0, and the result is not what I want, meaning both image are on top of the other.

Is there a way to define an offset for the image I want to be inside the canvas image? Otherwise, is there another way of doing this?

Please let me know if I didn't express my question clearly.

Thank you!

# Answer
I assume you are using imagecache\_actions module. I enabled imagecache\_canvasactions module too that comes with imagecache\_actions module.

Once i enable above mentioned modules, i can able to see offset for X & Y while adding Underlay (Background Effect) . See screenshot below. I set offsets to 50 & 40 see the style in action in second image.
> 0 votes

---
Tags: 7, media
---


title: Nothing displaying for Drupal main menu

text:
# Question
Title: Nothing displaying for Drupal main menu
I'm trying to output the `main_menu` in to a custom theme on the `page.tpl.php` template however nothing is displaying when I add `<?php print theme("links", $main_menu) ?>`

However when I do a `var_dump` on the `$main_menu` I get

`array(2) { ["menu-218"]=> array(2) { ["href"]=> string(7) "" ["title"]=> string(4) "Home" } ["menu-335"]=> array(2) { ["href"]=> string(6) "node/1" ["title"]=> string(4) "Home" } }`

What might I be doing wrong? I'm new to Drupal so be kind please :D

I do have `features[] = main_menu` in my .info file.

# Answer
> 3 votes
Try adding the following lines to your template file. Works for me.

```
$main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
print drupal_render($main_menu_tree);

```

---
Tags: theming, routes
---


# Question
Title: Conditional Fields module not working when OR operator is used
Using conditional\_fields 7.x-3.x module having two fields "category"(list containing a,b,c,d) and field "total rooms".

I have placed a dependency to show the total rums when category is "a" (OR) category is "c".

```
                      field_category       field_total_rooms is visible when field_category has value "a".
field_total_rooms                     OR
                      field_category       field_total_rooms is visible when field_category has value "c"

```

total rooms is being displayed when category is "a" but total rooms is not getting displayed when category is selected as "c".
Any suggestion

# Answer
The dependency should be like below:

```
 field_total_rooms  field_category     field_total_rooms  is visible when field_category has at least one of the values: a, c.

```
> 3 votes

---
Tags: 7
---


# Question
Title: Move file to specific folder after upload in forum
I am using Drupal 7 with Organic Group and Forum Module.

I have added facility to attach files in Forum posts. Now after forum(node) is submitted, I would like to move the file (which is with forum node) to specific folder.

Actually I would like to move/copy to other folder during node submit only, is is possible with hook\_node\_submit()

# Answer
Here is how I implemented it using hook\_node\_insert() function.

```
function modulealter_node_insert($node) {
    // See if a file has been added
    if ($file_items = field_get_items('node', $node, 'field_file_attachment')) {
        // Get the first file item
        $file_item = array_shift($file_items);

        // Load the file object from the cache/database
        $file = file_load($file_item['fid']);

        // The path to the file is in $file->uri
        //var_dump($node->group_audience['und']['0']['gid']);

        //Set the destination folder where do you want to move it
        $destination = "private://filedepot/filedepot/test/".$file->filename;
        $file = file_copy($file, $destination, FILE_EXISTS_REPLACE);
    }
}

```
> 3 votes

---
Tags: files
---


# Question
Title: Add a limitations to anonymous user for node view
I have to put a limitations on the number of nodes an anonymous user can view. So I have to set a limitations of 5 after that the anonymous user is made to login by redirecting to the login page.

So I have used hook\_nodeapi and under view operation i maintains a counter in cookie for the no of times the user visits the node.So if exceeds the counts it redirects to login page. But some how it doent work and gets redirected randomly..i mean not after 5 but after 7,8,,or some number.Some times it doesnt even increments the counter. So is it because the cache is enabled or is there some other reason to it. below is my code used under hook\_nodeapi:-

```
if($user->uid==0){
  if(isset($_COOKIE['anonymousquizview'])){
    $m = $_COOKIE['anonymousquizview'];
    $m++;
    setcookie("anonymousquizview", $m, 0,"/", "www.example.com");
  }
  else {
    setcookie("anonymousquizview", 1, 0,"/", "www.example.com");}
    if ($_COOKIE['anonymousquizview'] >=5) {
      drupal_set_message("To attend more challenges, kindly login.");
      drupal_goto('user/login');
    }
  }
}

```

# Answer
If cache is enabled `hook_nodeapi()` is not always executed. The first time a node is viewed Drupal renders the page and save it in the cache. During this process, `hook_nodeapi()` will be fired. Next time the same page is viewed, Drupal will find the rendered copy in the cache, serve this copy, and no `hook_nodeapi()` will be fire fired.

You have to do it in hook\_boot. This hook is fired even for cached pages. You must first check if current path is a node path (you may use `arg()` function). Try to add lightweight code as it will be executed in every page petition.

Remember that this protection is easily bypassed clearing the cookies for your domain.

### References
> 0 votes

---
Tags: nodes
---


# Question
Title: WYSIWYG only shows in administration theme
Anyone having this issue where the wysiwyg editor is only showing when you are in admin mode?

# Answer
The issue is that there is a jquery.once file that is getting loaded either in the overlay module or the administration theme module. I added the js file to my html.tpl file to load in this theme

misc/jquery.once.js
> 0 votes

# Answer
This is happening because you have an input format associated with the editor that is only available to your admin users. You need to either make the input format available to other roles on your site or expand the formats that the WYSIWYG editor displays on.
> 1 votes

---
Tags: wysiwyg, users, modal-dialogs
---


title: Setting default content permissions?

text:
# Question
Title: Setting default content permissions?
I've got a Drupal site with a large amount of CCK fields already populated. I'd like to allow non registered users to be able to submit a particular content type, but I don't want all the fields to be available to them.

I can, obviously, use Content Permissions to do this, but I have 100+ fields that I would need to set individual permissions for, and would also need to set permissions every time I added a new field.

Is there a way I can set default permissions for all fields? So, for example, all fields are editable by admin and viewable by all.

# Answer
> 0 votes
OK, so I'm being lazy here, so I just decided to bite the bullet and install the module. However, I have found a shortcut for Chrome users. Here's what I did:

1. Go to admin/user/permissions
2. Open up the Javascript console
3. Assuming your theme already loads jQuery (which it should if you've got the default theme, type $("input\[id\*=edit-3-edit-field-\]").attr('checked','checked'); and press enter to check all the admin permissions boxes to edit
4. To allow unauthenticated users to view all fields type $("input\[id\*=edit-1-view-field-\]").attr('checked','checked'); and press enter
5. Adjust as necessary for the permissions you want.
6. Click 'Save permissions'

I guess this would work for any other browser with a Javascript console too, but I've not tested it.

It doesn't get round the issue of having to add permissions for every single new field, but I guess it's just something I'll have to live with!

# Answer
> 0 votes
I think, the module Field Permissions can solve all of your problems.

---
Tags: entities, users
---


# Question
Title: Is there an Image field that let's users select a file from the server?
I am currently using file field sources to allow users to select images on our server in the Content Type. However, these are rendering as a download link. Is there something that will let a user either upload or select locally and render as an image in both the full and teaser view?

# Answer
It sounds like you already have the solution for selecting the image, you just need to control the output of how it is displayed. Are you using the file field instead of the image field? The file field will output by default as a link to the file, rather than as an IMG tag which is what you want.

If you want to keep the field the same but output it as an image, you have two options: you can use an integrated wysiwyg editor or file browser (IMCE is probably the closest to what you're looking for) to assist the user in displaying the file as an image.

Or - you can theme your node template to take the url of the file field resource and output it as an image. This is a little more involved but you can start here with template suggestions and ask more questions if you get stuck.
> 1 votes

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


# Question
Title: Redirect from "/mynode?language=de" to "/mynode" after storing the language in the cookie
Is it possible to remove the "?language=de" query string after Drupal stores the current language in the session and/or the cookie?

I want this so that if someone who speaks French sends a link to someone who speaks German, they will by default send a link that shows in the target user's preferred language.

# Answer
> 1 votes
You want to send them the language code in the url with the link as http://mysite.com/de/my-url-path and then make sure that you've enabled both session and url as detection methods at admin/config/regional/language/configure

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


# Question
Title: Place a link at top AND bottom of each node
I made some code to put a button/link at the bottom of a node. But it would be nice to place this link also at the top of the node. Would this be possible?

This is the code that places a button at the bottom of each node:

```
function hook_node_view($node, $view_mode, $langcode) {
    $node->content['links']['job'] = array(
        '#links' => array(
            array(
                'title' => t('Apply'),
                'href' => 'jobs/apply',
            ),
        ),
    );
}

```

# Answer
You are placing your link in the links object of the $content array which will generally, unless a template file overrides it, render all it's content in one place.

If the one link you have added visually covers your needs, the other one should be placed within the $content array, with a 'light' #weight property (0 for instance) along with the rest of the array's items (body, fields, etc).

the code could look something like this:

```
$node->content['top_link'] = array(
  '#markup' => '<a href="jobs/apply" class="jobs apply">'.t('Apply').'</a>',
  '#weight' => 0,
   );

```
> 2 votes

---
Tags: 7, nodes
---


title: Alternative to the Regcode module?

text:
# Question
Title: Alternative to the Regcode module?
I'd really like to use the Regcode module, but it is not very well maintained and with the progression of depending modules like VBO it becomes rather unstable imho.

So, i'd be glad if anyone can point me in the right direction to solve these problems:

1. Restrict user registration to "somehow invited" (preferably code-based) people only.
2. Manage the invites in backend.

I'd also like to know if there's maybe a commercial module that fit my needs...

# Answer
I think you'll need to do some custom magic voodoo ;)

I built a similar site earlier this year: The client provided a list of users (with their email addresses) in an Excel spreadsheet. I created a new column with a unique 8 character registration code for each user. I then imported that file, including the code, as new users.

The registration code was saved as a plain-text field in their user profile.

Create a custom user login form that only requires the registration code, mail out the reg codes.
> 1 votes

---
Tags: 7, users
---


title: View Table grouping on Taxonomy terms

text:
# Question
Title: View Table grouping on Taxonomy terms
I am having trouble grouping a view table style on taxonomy terms. It is rendering like

```
TAGS: tall
ITEM        TAGS
One         tall
Two         tall
Four        tall

TAGS: tall, soft
ITEM        TAGS
Three       tall, soft
Three       tall, soft

```

and I would really like it to render

```
TAGS: tall
ITEM        TAGS
One         tall
Two         tall
Three       tall, soft
Four        tall

TAGS: soft
ITEM        TAGS
Three       tall, soft

```

Drupal7, by the way.

# Answer
> 4 votes
I've had this problem before too! Very annoying. ;-) The reason that happens is that, by default, the list of tags are displayed as a comma-separated list when the node is tagged with more than one term. The way you can change that settings in your view is to click on the field that is your term in the **Fields** section of the view and expand the '**Multiple field settings**' which should exist for this field (since it's an input field that accepts multiple values.

In your case, it would be best to select that only the first value is displayed like so:

That should work for you. You'll see that the content type will still appear under all of its categories if it is tagged with multiple tags, but they won't be grouped in long lists with commas. :-)

Let us know if this works!

---
Tags: 7, views
---


title: change the layout of a content type

text:
# Question
Title: change the layout of a content type
I would like to change the layout of my content type. I tried the syntax: page--content-type.tpl.php of Drupal 7. but...I was not able to make the changes appear on the page. When I write the file: page--node--numberNode.tpl.php work, but when I write the file: page--content-type.tpl.php nothing happens.

# Answer
> 2 votes
According to Drupal 7 Template (Theme Hook) Suggestions there is no `page--content-type.tpl.php`, only `node--type.tpl.php` If you have to use a `page-content-type.tpl.php` you must create a template suggestion. This (d6) or this (d7) might help you doing so.

---
Tags: theming, hooks, 7
---


title: File Framework for Drupal 7?

text:
# Question
Title: File Framework for Drupal 7?
File Framework is a collection of modules which allow uploading, converting and displaying different media type files as Drupal nodes.

> Metadata is extracted from uploaded files using EXIF, getID3, pdfinfo and stored as Resource Description Framework (RDF).
>
> A node of type file is created for each uploaded file. This gives a revision control and will integrate with views.
>
> Each file is converted to number of other MIME formats using available open source converters. For example a MS Word file can be automatically converted to PDF, OpenDocument Text (using OpenOffice daemon / LibreOffice + JODConverter), Plain text (using catdoc), Flash video (using SWFTools), JPEG (using GhostScript) and Zip (using gzip). Converted (derived) files are saved in the Bitcache and their metadata is extracted and saved in the RDF along with the relation to the original file. All derived files are listed and can be downloaded.

Unfortunatelly the module is available for Drupal 6 only.

Is there any similar solution available for Drupal 7 ?

Please follow http://drupal.org/node/1827110 if you are interested in File Framework port for Drupal 7.

# Answer
I would suggest using Media as your starting point, and improving it if needed. That's the D7 solution aiming to solve similar problems to the File Framework (and other D6 modules).
> 1 votes

---
Tags: 7, files
---


# Question
Title: How can I use a token to display the node body summary?
I'm trying to use a token to show the body summary of a node on Drupal 7.

The **Replacement Patterns** area gives the following information:

* Body
* \[node:body:?\]
* The main body text of the node. The following properties may be appended to the token: value (Text), summary (Summary), format (Text format)

However, I don't understand what "append" means in this context. I tried \[node:body:summary\] and \[node:body:?summary\], but neither works. What am I supposed to do to get the summary?

# Answer
> 4 votes
Correct tokens are \[node:body\] and \[node:summary\]. Yoy should probably check http://drupal.org/node/1295524 if you experience problems with summary tag

# Answer
> 4 votes
Replace *?* with any of the following:

* value
* summary
* format

The token you use will look like one of the following:

* \[node:body:value\]
* \[node:body:summary\]
* \[node:body:format\]

# Answer
> -2 votes
If using a view you can format the body field using the formatter.

---
Tags: tokens
---


# Question
Title: Not able to add new CCK field to custom content type
Today all of a sudden I found out that I can no longer add custom CCK fields to any of my custom content types. The right most drop down box to select the field type is now disabled!!

When I try to add to the field anyway, I get an error: **Add new field: you need to select a widget.** But I just can't select the widget type. The combobox is disabled.

Any ideas on why is this happening? We are running Drupal 6.22

Thanks!

# Answer
Most likely either JavaSript or AJAX failure is giving you problems. Check your browser Javascript error messages with a tool like Firebug, and check your server log.

Alternatively you can disable the javascipt enabled interface entirely.
> 1 votes

# Answer
I was facing the same issue. I disabled javascript in my browser (firefox), then added the cck fields that I needed and then re-enabled the javascript. Its not a complete solution but a quick one if needed. Obviously, its a javascript issue.

Muhammad.
> 1 votes

---
Tags: entities
---


# Question
Title: Is it safe to delete default image/file styles?
For consistency and usability purposes, we want to set up a default set of image styles which are clearly understood by our editors. This probably means getting rid of default style names like "medium", "large" etc.

The question is, is this likely to break other third party/contrib code that relies on the Styles module? Might we need to patch these (possibly too much of a headache) or just configure them to use the new styles?

Note: styles seem to be defined and displayed to editors purely by their (sometimes auto-capitalised) machine names, so we can't set a friendly name that differs from this.

Also: Is it even possible to remove existing styles? I can only seem to find ways/hooks to add them.

# Answer
You shouldn't remove the default styles (as mentionned), but you can alter them using hook\_image\_styles\_alter

You can remove the options from selected forms using hook\_form\_alter (as mentionned).

I tried to find a generic approach and happily found this page.

This is how I applied the info:

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

  recursiveRemoval($form, 'thumbnail');
  recursiveRemoval($form, 'medium');
  recursiveRemoval($form, 'large');
  recursiveRemoval($form, 'square_thumbnail');

}

function recursiveRemoval(&$array, $val) {

  if (is_array($array)) {

    foreach($array as $key => &$arrayElement) {

      if(is_array($arrayElement)) {

        recursiveRemoval($arrayElement, $val);

      } else {

        if($arrayElement === $val) {

          unset($array[$key]);

        }

      }
    }
  }

}

```

N.B.: Use at your own discretion.
> 3 votes

# Answer
I don't believe you can delete the default styles and doing so would break modules. The Drupal core module relies on the thumbnail style being present.

If you want to improve the usability for your editors, you could simply hide the style where you normally can select it on editor friendly pages.
> 2 votes

---
Tags: media
---


# Question
Title: How to make a hierarchical categories of a view's nodes?
I want to have hierarchical categories of a view's nodes,where categories will be taxonomy terms of the nodes.How to do that?

# Answer
If you want to display your taxonomy as tree, and insert nodes having given term, into that tree, you'd need Views Tree. This adds a display plugin for Views. You just need to create a node listing view which accepts a term argument.

If you mean to format the term attached to a node, as a hierarchical tree, try Term Reference Tree.
> 1 votes

# Answer
You can use Hierarchical Select
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to hide an empty block with no results
The block is generated by Views and I the only field comes from a relationship and is not accessible in the filters, so I can't set a filter.

I have tried to use another field, rewrite the results but the filter only considers that initial value of the field, not the rewritten one.

I suspect I have to do something with a template file, but a precise how-to would be very helpful.

Thanks in advance!

# Answer
> 0 votes
The solution turned up pretty simple: I had to check the "Require this relationship" option in the relationships settings

# Answer
> 0 votes
try restricting the block's display using "Pages on which this PHP code returns TRUE (experts only)" and checking for the final re-written value there.

---
Tags: views, blocks
---


title: Session variables and page cache

text:
# Question
Title: Session variables and page cache
My drupal site uses normal cache system, as you'll probably know, the cache\_page table is updated using as primary key the REQUEST\_URI. This is great because when an anonymous user requests a page, drupal serves it to the client from the cache\_page, and the best part is that all variables in the GET request are part of the cache id for serving that page.

So for example if I have these URL's

* `http://domain.com/gallery`
* `http://domain.com/gallery?list_mode=thumbs`

Both url's are different in the cache\_page table.

The problem comes here, I want anonymous users to remember the last option that selected as "list\_mode", so the next time they come they'll get one or another list mode by default. So I added list\_mode as a SESSION var. The problem is that accessing

```
http://domain.com/gallery

```

as anonymous, the page is served from cache with the default list\_mode. (whose value is not "thumbs")

I don't want to stop using cache\_page for this url (this was a possible solution), and the ideal thing would be adding some way this SESSION variable to the REQUEST\_URI so the page will be served as it should , in this case would consist of translating:

`http://domain.com/gallery` TO `http://domain.com/gallery?list_mode=thumbs`

before checking the cache, so the user gets the second URL served instead of the first.

`hook_boot` would be a good place to do that, but I don't think that hacking the request\_uri is a good idea, so, is there any other way to do this approach ?

Thanks for your help.

PS: I found a similar issue, the user makes use of the RewriteCond to achieve what he wants, and asks for a better solution, but the only answer advises to disable caching for that pages: Cache page based on cookie value and URL

# Answer
> 1 votes
On the other answer, the page cache is bypassed on the first hit. Subsequent hits do hit the page cache because the cookie will be set then.

To answer your question, have some client side javascript that sets a cookie called gallery\_list\_mode. If no selection is made, set it to 0 or delete it. If user selected `thumbs`, have the javascript set the gallery\_list\_mode cookie to `thumbs`. Then inside of your settings.php drop this in

```
<?php
// Check if cookie is set and user is on a gallery page.
if (!empty($_COOKIE['gallery_list_mode']) && $_SERVER['REQUEST_URI'] == '/gallery') {
  $ok_list = array(
    'thumbs',
  );
  if (in_array($_COOKIE['gallery_list_mode', $ok_list)) {
    // Add cookie value to page cache id.
    $_SERVER['REQUEST_URI'] .= '?list_mode=' . $_COOKIE['gallery_list_mode'];

    // This line might be needed.
    //$_GET['q'] .= '?list_mode=' . $_COOKIE['gallery_list_mode'];
  }
}
?>

```

This will make http://domain.com/gallery point to the cache entry for http://domain.com/gallery?list\_mode=thumbs if the gallery\_list\_mode cookie is set to thumbs.

As a security feature you should make sure to only accept values for gallery\_list\_mode that you want. That is what the `$ok_list` array is for.

---
Tags: caching, uri, sessions, cookies
---


# Question
Title: Why do I get a redirect loop (302) when using path-auto patterns on taxonomy terms?
I am using pathauto to set up my URL's at the moment and they are working fine for nodes.
However when I set up a rule for taxonomy terms using \[term:name\] as the pattern I end up with redirect loops.

Can anyone explain why this is and how to remedy.

Thanks for any help.

# Answer
> 1 votes
It seems to have been due to caching and the rebuilding of the alias table.

Once I left it for a while and cleared caches it was working as expected.

---
Tags: 7, taxonomy-terms, redirection, path-aliases
---


title: how to cache my site background image?

text:
# Question
Title: how to cache my site background image?
I am using an image as my site background that is of size 2.7MB. Because of its image size alone it takes 7+ seconds for the page to load.

Question: Can/How do I cache this background image at user's browser caches that it is not downloaded every single time?

Basically, i understand that first load will be slow but if cached - subsequent loads would be faster then.

# Answer
> 2 votes
The default drupal .htaccess settings should have your browser cache this image for 2 weeks. If this is not working I recommend installing the mod\_expires module & the mod\_headers module on your server. If 2 weeks is not long enough, you will need to modify your .htaccess file to set the expires & cache control headers for this file. An example of that below:

```
<FilesMatch "my-big-image\.jpg$">
  <IfModule mod_expires.c>
    # Enable expiration.
    ExpiresActive On

    # Cache this file for 1 year after access (A).
    ExpiresDefault A31556926
  </IfModule>
  <IfModule mod_headers.c>
    # Make this file publicly cacheable.
    Header append Cache-Control "public"
  </IfModule>
</FilesMatch>

```

At a bare minimum, you can try adding this line to the bottom of your .htaccess file. This doesn't require any apache modules to be installed and it should have your sever send back a small 304 instead of a large 200.

```
FileETag MTime Size

```

# Answer
> 1 votes
First of all a 2.7MB background image doesn't do any good for anyone (especially for mobiles). So you really need to compress this. Have a look at "save for the web" in Photoshop or similar applications.

To make clients cache this you need to configure the expires headers. Have a look at "Expires or a Cache-Control Header" of http://developer.yahoo.com/performance/rules.html

---
Tags: theming, caching, performance
---


# Question
Title: How do I NOT clear memcache or other cache tables?
All of us who love Drupal know the pain of building those cache tables for the first time.

I have a site whose activity is high during a certain part of the day and then non existant at others. I have over 25,000 items of content on the site, and that grows daily. I have Memcache, APC (etc) installed for performance. When the site is active, it flies. I am very happy with the speed and performance.

However, if you are part of the lucky few who get to access the site when the cache tables are being rebuilt, you have a good 10 min to sit there and wait.

What can I do to prevent this? Can I have memcache keep all cached files in memory until new versions of pages are requested? I thought about writing a spider to access the site every 15 min to half hour or so (somewhat like boost module does), but wanted to see if any of my caching options could be simply configured before diving into that. If so what configuration options would you recommend?

# Answer
One setting you can play around with is the minimum cache lifetime setting. It will help, but it won't solve the issue.

The standard Drupal cache doesn't allow for what you are describing. One can do some exotic stuff to update caches in the background but unless you have a large developer budget to make this work I would move on. Note: The 6.x version of boost is the only thing I know of that allows for the cache to be updated in the background.

If you are looking to build a spider, http://drupal.org/project/httprl/ is the way to go. I hope to be developing with this more in the future.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: Why Drupal 7 takes too time in connecting to mysql db? - measured with xdebugger
i have drupal 7 on localhost (core i7 - 12gb ram etc) on Nginx with APC and mySql on windows7.

standard installation with standard theme and a bounch of new modules. about NO content.

The problem is that the homepage take ever 1,5 sec to load (without APC 3 secs). i installed XDEBUGGER and with winCacheGrind i discovered that 75% of the time is lost in DB connections. Self: 2ms, Cumulative:1007ms

i tried almost anything i found on google... also i ported db engine to MyISAM... mySql is configured with my-HUGE.ini file... so it can take any resource from the computer.

How could i solve this?

1,5sec for any loggedin user is too much time... on the hosting this time will be greater as i won't have a so big dedicated server...

# Answer
This is a good group for you to join on groups.drupal.org
http://groups.drupal.org/drupal-windows

Looking at this post it sounds like the issue you are describing: http://groups.drupal.org/node/242443.

> Make sure that your Drupal settings.php connection string uses the IP address of your MySQL server (e.g. 127.0.0.1 for your local Windows machine), not 'localhost'.
> 1 votes

---
Tags: performance, database
---


# Question
Title: Looking for suggestions on AJAX-base update to view
I have a requirement that I'm not sure how to go about implementing. The flow goes something like this:

1. User clicks button: share your update
2. Popup window opens
3. User fills in form and clicks Save
4. View is updated immediately to reflect update

I'm thinking I'll need a new content type for updates since the view being updated is for node content, not comments.

Anyway, I think I'll need to AJAX-load the node/add form, then somehow trigger the view to update upon saving the node. Perhaps it will work by using the Overlay module? (Note: I would only want the Overlay to be used in this one specific case.)

Anyone done this that can provide some pointers and/or some links?

Thanks,

Dan

# Answer
Wow this was not all that difficult after all.

The following forces the overlay to only be used for my desired node type and admin pages:

```
<?php
  function yourmodule_admin_paths_alter(&$paths) {
  $paths['node/add/user-update'] = TRUE;
  $paths['user'] = FALSE;
  $paths['user/*'] = FALSE;
  $paths['users/*'] = FALSE;
  $paths['node/*/edit'] = FALSE;
  // Add this for each content type you don't want the overlay to be used for.
  $paths['node/add/other-types'] = FALSE;
?>

```

Then I needed a rule to redirect to my view (home page in this case) after the content was added:

```
{ "rules_redirect" : {
"LABEL" : "Redirect to home page",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "node_insert" ],
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "user_update" : "user_update" } }
    }
  }
],
"DO" : [ { "redirect" : { "url" : "\/" } } ]
  }
}

```

The combination of the two makes it appear as if the user is adding a "quick update".
> 2 votes

---
Tags: 7, views, ajax, modal-dialogs
---


# Question
Title: Image Gallery not loading random thumbnails
This has been happening for... perhaps for years.

I have an image gallery here http://windwanderer.com/image

When I load any page of this gallery, only SOME of the thumbnails are loaded and the rest show the default text.

Which thumbnails load and which do not changes with each load. Try it, go to the link above and see which images are shown (you may need to scroll down) then click "reload" on your browser. Some of those that looked to be unavailable will be loaded and some of those that loaded correctly the first time will now appear as thought the image can't be found.

The error occurs in Firefox, Midori, and even Dolphin browser running on Android phone!! Haven't tested it with iexplorer.

I believe this problem may have persisted over an upgrade from Drupal 5.x to 6.x

My guess was that it had something to do with the cache. Here is what I have done:

* I've emptied it
* turned off page caching
* rebuilt the derivative images multiple times

... yet the problem persists.

I would really appreciate any help. Please be patient, though, as I don't sit at my computer every day and it may take me time to test solutions.

Cheers Jesse

> SITE STATS: Drupal Version: 6.x-2.9 Image Gallery Version: 6.x-1.1 Was using acidfree albums in 5.x but changed to image gallery (views) when upgraded to 6.x The view states "Overridden Node view: image\_gallery" Views Version: 6.x-2.16 Was using image toolkit: "GD2 image manipulation toolkit" but have just changed to "ImageMagick Toolkit" in attempts to solve this problem.

# Answer
> 0 votes
I just checked out your site and all images showed up. It took some time, but all images did show up. Looking at it further, it appears that you have your file system set to private. Go to admin/settings/file-system/settings and change the Download method to public. If this is not an option, then I would look at implementing xsend in apache and installing the drupal module http://drupal.org/project/xsend

Unless you have some VERY good reasons to set your file system to private, I highly recommend using a public file system.

---
Tags: caching, media
---


# Question
Title: Update the number of comments without refreshing the cache
I am running a local installation of Drupal 7 with the Disqus module installed.

I have created a view with a list of "blog" nodes, and the number of comments displaying through the view. The number of comments in my view does not refresh/update without clearing the cache in Drupal.

Is there a specific way to do this for Disqus, or automatically refresh the Drupal cache?

# Answer
Long story short, you need ESI or AJAX to do what you want.

This will help you get there, but I don't believe any of the below modules will do exactly what you're looking for.
http://drupal.org/project/esi
http://drupal.org/project/ajaxblocks
> 1 votes

---
Tags: 7, caching, comments
---


# Question
Title: Hide the block on the "node/add/my_content_type" page
I created a content type. I want to show a block on all nodes of this content type except "node/add/my\_content\_type". I used the following PHP code:

```
global $node;
$arg1 = arg(1);
if ( $node->type == 'my_content_type') && arg(0) == 'node' && is_numeric($arg1) ) {
  return TRUE;
}
return FALSE;  //default

```

Result: the block does show on all nodes of this content type, but also show on "node/add/my\_content\_type".

What I did wrong? Thanks for any help.

# Answer
> 0 votes
Try this

```
$node = menu_get_object();
return isset($node) && $node->type == 'your_content_type' && arg(2) == '';

```

Edit: forgot about the third parameter

# Answer
> 0 votes
```
<?php
if (arg(0) == "node" && is_numeric(arg(1)) && arg(2) == "") {
  $node = node_load(arg(1));
  if ($node->type == "your_content_type") {
    return TRUE;
  }
  return FALSE;
}
else {
  return FALSE;
}
?>

```

Above code will show your block in all node pages of type "your\_content\_type"

# Answer
> 0 votes
There isn't a global `$node` variable. If you want to get the node object for the node currently being viewed, you should call menu\_get\_object().

I would rather use the following code.

```
$node = menu_get_object();
return (!empty($node) && $node->type == 'your_content_type');

```

---
Tags: blocks
---


# Question
Title: Can custom module function names contain characters between 7F and FF?
PHP defines valid function names as \[a-zA-Z\_\x7f-\xff\]\[a-zA-Z0-9\_\x7f-\xff\]\*.

I have already been bitten by Drupal name conflicts when using hook\_form\_alter clashing with my module name when it contained common words separated by an underscore "\_" ("isys\_helper\_form\_alter").

So I thought about using the broken pipe character instead like I have done in other PHP projects ("¦", char #A6, "isys¦helper\_form\_alter").

Unfortunately, Drupal does not seem to find any functions I name using characters in the 7F to FF range.

Is this a documented difference with Drupal vs. PHP?

Searching the documentation online did not state any such difference, but I could have missed it.

# Answer
That's a bad idea. Please refer to Drupals Coding Standards under the section Naming Conventions.

In my opinion function/class/var names shouldn't contain anything else than `A-Za-z0-9_`.

If you don't want `isys_helper_form_alter` to be picked up by Drupal, you can always prefix it with an underscore: `_isys_helper_form_alter`.

**Update**

Here's another topic on why other characters are bad: https://stackoverflow.com/questions/6362241/php-variable-function-class-names-using-special-characters. And even if you remember to save it in the right encoding, other people who needs to maintain your code later on might not do that.
> 5 votes

# Answer
Drupal allows you to use those characters in a function name. In fact the DRUPAL\_PHP\_FUNCTION\_PATTERN constant is defined as follows.

```
define('DRUPAL_PHP_FUNCTION_PATTERN', '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*')

```

In your case, the problem is that the short name of the module would not match with initial part of the function name. If the short name of the module is isys\_helper, then every hook implemented by that module must have a name that starts with isys\_helper\_. You cannot have a module called isys\_helper for which the hook is called `isys¦helper_form_alter()`.

The name collision happens when Drupal is not able to understand for which module the function is a hook implementation, and for which hook.
Suppose you create a module called user\_node.module that defines a new content type, for which it implements `hook_view()`. The function implementing that hook for that module would be called `user_node_view()`, but that would be also the name for `hook_node_view()` implemented from the User module. This means that the following code would invoke `user_node_view()` twice, provided that both user\_node.module, and user.module are enabled.

```
// Call any implementation of hook_view().
$node = module_invoke_all('view', $node, $view_mode);

// Call any implementation of hook_node_view().
module_invoke_all('node_view', $node, $view_mode, $langcode);

```

Surely using underscores in the short name of a module doesn't help, but the solution is not to prefix the name of a hook with a string that is different from the one Drupal is expecting.

Solutions have been proposed to avoid issues, such as using two underscores to separate the module name from the hook name. In the example I made the implementation of `hook_node_view()` made from the User module would be called `user__node_view()` while the implementation of `hook_view()` for the other module would be `user_node__view()`. In this way, the ambiguity would be avoided.
Another proposal has been to use PHP 5.3 namespaces, but it is probable that even with Drupal 8 the hook names will follow the same schema used in other Drupal versions.
> 0 votes

---
Tags: coding-standards
---


title: Selective caching - by user

text:
# Question
Title: Selective caching - by user
Is it even possible to do this?

The goal is to group our visitors:

```
Group A sees Theme A
Group B sees Theme B

```

I am able to achieve this goal through cookies. But when caching is enabled (i.e. Site config \> Performance \> On), things are messed up. This is what happens:

1) Group A visits Page-1
-- Page-1 is not cached yet.
-- Cookies are properly checked.
-- Page-1 is displayed using Theme A

2) Group B visits Page-2
-- Page-2 is not yet cached.
-- Cookies are properly checked.
-- Page-2 is displayed using Theme B

3) Group A visits Page-2
-- Page-2 is already cached.
-- Cookies are ignored
-- Page-2 is displayed using Theme B (when it should be displayed using Theme A)

So now what I am thinking is, instead of using cookies, I'll use separate cache for each group.

Is this even possible? :S If not, any recommendations are welcome.

Inputs will be highly appreciated. Thanks!

# Answer
> 0 votes
Ok so here's what I did.

I extended drupal's cache.inc by including this line on settings.php

```
$conf['cache_inc'] = sites/all/modules/mycustom_module/my_custom_cache.inc';

```

I basically copied drupal's cache.inc and pasted it in my module's folder, renamed it, and then added a few lines of code where I altered how $cid's are generated. This way I am able to create $cid variants of cache depending on the theme

# Answer
> 0 votes
Checkout Cache page based on cookie value and URL

Long story short what you want can be done. Depends on how you want to do it :)

---
Tags: theming, caching
---


# Question
Title: how should I hide the menu and url setting in from alter?
I have a node/add/blog form, there are some things I don't want show it. I give the elements

```
$form['author']['#access'] = FALSE;
$form['options']['#access'] = FALSE;
$form['comment_settings']['#access'] = FALSE;

```

but I cann't find what's the element name for **menu** and **url setting** in message of dpm($form);

# Answer
> 1 votes
As explained in hook\_form\_alter

> The call order is as follows: all existing form alter functions are called for module A, then all for module B, etc., followed by all for any base theme(s), and finally for the theme itself. The module order is determined by system weight, then by module name.
>
> Within each module, form alter hooks are called in the following order: first, hook\_form\_alter(); second, hook\_form\_BASE\_FORM\_ID\_alter(); third, hook\_form\_FORM\_ID\_alter(). So, for each module, the more general hooks are called first followed by the more specific.

So, your module hook\_form\_alter is called before path module or menu module which adds those elements. That's the reason you can able to see those elements when you print form in your custom module.

Try using same form alter hook in your theme template.php it should work. It worked for me ! I can able to see path settings and menu setting. See for Seven Administration theme below.

```
function seven_form_alter(&$form, &$from_state, $form_id) {
  drupal_set_message("<pre>" . print_r($form, 1) . "</pre>");
}

```

Else, you need to alter your module weights !!

---
Tags: forms
---


title: CKeditor cannot find ckeditor.js

text:
# Question
Title: CKeditor cannot find ckeditor.js
I am in the process of upgrading a Drupal install from 6 to 7. Drupal 6 uses the ckeditor module without any difficulties.

As I upgraded to Drupal 7 and the latest version of ckeditor, the module no longer works.

Firebug gives me an error message:

```
Failed to load resource: the server responded with a status of 404 (Not Found) http://mysite/ckeditor.js?mcqjp7

```

I'm not sure why ckeditor is looking in the site room for that file.

It has no trouble finding the css file

```
<style type="text/css" media="all">@import url("http://mysite/cms/sites/all/modules/ckeditor/ckeditor.css?mcqjp7");

```

So why can it find the CSS file but not the JS file?

# Answer
> 3 votes
---

You have to check the libraries for ckeditor in your drupal site.

```
sites/all/libraries/ckeditor

```

In D7 the CKEditor contain the libraries for editor. if you don't have then download the module and library from http://ckeditor.com/download

---
Tags: wysiwyg
---


title: What are the risks not upgrading to 7?

text:
# Question
Title: What are the risks not upgrading to 7?
> **Possible Duplicate:**
> Drupal 6 end of life

what are the risks if Drupal 8 comes out and Drupal 6 is not supported any more, but you will upgrade from 6 to 7 later ie 6 months after Drupal 8 has come out?

Thanks!

# Answer
Only risk is that you will stop receiving updates(including security) once stable version of Drupal 8 is out. You can still keep running on Drupal 6 as long as security issues does not affect your sites. Drupal 6 will suffer same fate as Drupal 5 did.

> Release notes from last supported Drupal 5 release.
>
> The twenty-third maintenance and security release of the Drupal 5 series. Only fixes for security vulnerabilities and other bugs have been committed. New features are only being added to the forthcoming Drupal 7.0 release.
>
> This release fixes security vulnerabilities. Sites are urged to upgrade immediately
> -1 votes

---
Tags: 7, upgrading
---


# Question
Title: Safely enter PHP code in block to prevent site crash?
When I enter a php snippet into a block (or story or page), it can crash the site.

Two questions:
1) How can the chances of this be reduced? For example, I just crashed a fresh installation because a function name was not recognized. Would placing the code in a try/catch block been likely to prevent that crash?
2) If/when I do crash the site due to malformed php code, how can I recover the site?

# Answer
> 4 votes
Two common errors occur while entering PHP code, syntax error & function not defined error. To avoid syntax errors, write your code in any IDEs which supports syntax checking. And always use `if(function_exists())` when calling any custom functions. Once you have both these checked move it to dev, test and move it to live site.

As indicated by others there are loopholes entering PHP codes but when you cannot avoid above two points might help you.

# Answer
> 5 votes
The usual way to avoid problems with your production site is to try out everything first on a dev or staging site, and then push it to production after it is tested. There are two main problems with php in blocks: one is that block data is stored in the database. If you push the database from dev to production, you will lose new content on your live site -- no good. The solution to this problem is to use the features module to export your database configuration to your code files, which allows you to push your config-in-code from dev to live & then re-import on the live site.

The other problem with putting php in blocks, though, is that it opens up a security hole in your site, as anyone who has the right to configure blocks can now run code on your server. This means that your site is one guessed password away from compromise at all times. It is therefore better to write your blocks in code using a custom Drupal module rather than put php in the database.

If you do have a site with malformed code in a block, you can disable the block using the drush block-disable command from the drush\_extras project.

# Answer
> 2 votes
I suggest you read Develop for Drupal documentation first.

Read about The White Screen of Death (Completely Blank Page) too.

You can find more about Drupal code debugging here.

Follow Drupal's Standards, security and best practices for writing code and maintaining Drupal's security. This documentation also provides a number of best practices that will help you optimize the speed and performance of your application.

Avoid storing php code in the database. It is more secure to create a custom module instead of using php-enabled fields.

Set up your testing strategy appropriate to your use case: at least test your code on your development (or local) environment before it is used in the production (live) environment.

# Answer
> 1 votes
In case you are stuck because of bad code in the php-enabled field or node, here is how I usually recover.

1. Remove the "php" folder from modules folder.
2. See if the site now works without any White Screen Of Deaths.
3. If the site shows "failed opening .."as a fatal error, set 0 to status for php module in system table.
4. Or if the site is working now, go to the node edit and remove that bad code.
5. Place the code in place after fixing that.

However, it's **NEVER** a good idea to use PHP in nodes. Only places I would suggest using raw php in database-stored values are some Rules module's configuration and Views arguments.

For blocks or pages, it's much easier to make a module with necessary menu hooks and block hooks.

Good luck!

---
Tags: blocks
---


title: How to remove user picture on the nodes

text:
# Question
Title: How to remove user picture on the nodes
Is there a way to remove a user's picture from the node, or the teaser without any CSS modification, but just doing it from the GUI?

# Answer
> 2 votes
Look at the settings for your theme. There is a check mark to include the user pictures or not. There are settings for the individual theme, and generic settings.

---
Tags: users, media
---


# Question
Title: Dynamically enabling checkout panes based on cart contents?
I am working on a service booking website and below is a customer scenario:

i) A customer arrives at the site, views the various services and clicks the "make a booking link" for a particular service.

ii) They are redirected, a view of all available services of that type (product with time/date field & service\_type\_id) is then generated.

iii) The customer selects the timeslot suited and clicks on a "Book now" button (overidden "Add to Cart"), the Review page is skipped and they are redirected to the checkout page

On the checkout page I am trying to dynamically add suggested services that compliment their current selection. The problem I am having is how to dynamically add this checkout pane?

Currently I am using rules to detect what service has been added to cart, using entity has the field (service\_type\_id) & a data comparison to allow me to know what added service type I should suggest. I am trying to use commerce extra panes to create and display the content.

I am just wondering what is the best way to go about dynamically adding panes based on the contents of the cart?

I imagine I will have to write a series of rules that enable/disable checkout panes based on the carts contents but am hoping there is a simpler way to get the functionality I am looking for?

Allowing for the display of extra panes to be integrated with conditionals derived from rules would be a very handy feature for a variety of uses.

Any thoughts/help appreciated.

Kind regards, Ruairi

# Answer
You may want to follow this issue: http://drupal.org/node/1122386

it develops Rules based pane visibility.
> 2 votes

---
Tags: commerce
---