# Question
Title: How to use arguments, defined in a custom event, for an action
I've just defined this event with the two arguments: number and message. I want to use them to verify the message and send a response back to the number. I have an action for that but I don't know how to pass the arguments.

```
function sms_rules_rules_event_info() {
  return array(
      'sms_rules_sms_received' => array(
         'label' => t('SMS received'),
         'module' => 'sms_rules',
         'arguments' => array(
            'number' => array('type' => 'text', 'label' => t('Number from where the message was received.')),
            'message' => array('type' => 'long text', 'label' => t('Contents of message.')),
         ),
      ),
  );
}

```

# Answer
> 2 votes
In your action you might have something like

```
function mymodule_rules_action_info() {
  return array(
    'my_action' => array(
      'label' => t('Label'),
      'module' => t('My module'),
      'arguments' => array(
        'number' => array('type' => 'text', 'label' => t('Number from where the message was received.')),
        'message' => array('type' => 'long text', 'label' => t('Contents of message.')),
      ),
      'base' => 'mymodule_my_action',
    ),
  );
}

```

The `'base'` property indicates the callback for the action. You can also use the key of your action as the callback if you choose not to set a `'base'`. In this case it would be `function my_action()`. The arguments defined in the action will automatically be passed to that function. Now, whether the action is available is dependent upon which arguments your event makes available and which arguments your action requires. So, if I had an event that passes a `'type' => 'user'` and `'type' => 'node'` then only actions that have arguments 'user' and 'node' would be available. This is how Rules 1 works. Alternatively, by using a simple 'text' data type the actions will always be available because the data type is not unique. You can specify your own data types by implementing `hook_rules_data_type_info()`.

Anyways, I got off track. So, with your base being `mymodule_my_action`:

```
function mymodule_my_action($number, $message) {
  // Do stuff here.
  return $number;
}

```

Another addition you can make if necessary is adding a settings form to your action.

```
function mymodule_my_action_form($settings, &$form) {
  $form['settings']['my_options'] = array(
    '#type' => 'select',
    '#title' => t('Select an option'),
    '#options' => array(
      'this' => t('this'),
      'that' => t('that'),
      'also' => t('also'),
    ),
    '#default_value' => $settings['my_options'],
    '#required' => TRUE,
  );
}

```

In this case, you would just add the settings array to your action callback as the last argument:

```
function mymodule_my_action($number, $message, $settings) {
  if ($settings['my_options'] == 'this') {
    // Do stuff.
  }
}

```

Hmm... I don't even know if I answered your question, but I tried to provide as much info as possible. If I completely missed it please give me some guidance. I maintain three Rules modules, so I've been around that module for a while and I'm glad to help.

---
Tags: 6, rules
---


# Question
Title: How to Execute a Specific Part of a Function
I am building a function in a custom module, and I want to be able to execute only a specific part of that function.

I am starting with the hook\_node\_api to see if an event occurs, and if that event occurs, I want to execute a only a specific part of that custom function.

```
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {

    case 'presave'
    if (  $node->type == 'property' ){
        $old = node_load($node->nid);
        if($old->field_realtor_reference[0]['uid'] == NULL && $node->field_realtor_reference[0]['uid'] !== NULL){
               mymodule_tn_complete($node);
        }
      }

      break;
  }
}

function mymodule_tn_complete( $node)
{
  //Do something
  //Do Something Else

}

```

# Answer
I personally might reduce some of the conditionals as in some cases they're just checking one item and can basically be placed into the same conditional statement.

```
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  // Placed the $op and node type checks in the same conditional.
  // There's no particular reason they have to be separated since
  // the rest of the code is dependent upon both being TRUE.
  if ($op == 'presave' && $node->type == 'property') {
    $old = node_load($node->nid);

    if($old->field_usera_ref[0]['uid'] != $node->field_user_ref[0]['uid']){
      // Also, it is not necessary to assign the string to $type. You can
      // just pass the string 'realtor_assign' directly without assigning it.
      // Since your second parameter in the function signature is $type this
      // string will automatically be assigned to it.
      mymodule_tn_complete($node, 'realtor_assign');
    }

    if($old->field_userb_reference[0]['uid'] != $node->field_userb_ref[0]['uid']){
      mymodule_tn_complete($node, 'am_assign');
    }

    if($old->field_userc_ref[0]['uid'] != $node->field_userc_ref[0]['uid']){
      mymodule_tn_complete($node, 'trep_assign');
    }
  }
}

function mymodule_tn_complete($node, $type) {
  switch($type){
    case 'realtor_assign':
      //Do Stuff
      break;

    case 'am_assign':
      //Do other stuff
      break;

    case 'trep_assign':
      // Do different stuff
      break;
  }
}

```

Other than those personal preferences from experience, I don't really see anything wrong with it in principal. It looks good. This function is not making any database calls so it should not be putting must strain on the performance. Implementing the hook should not do that. Even if you're not implementing the hook other modules undoubtedly are.
> 0 votes

# Answer
If I'm reading you right you're asking a basic program flow-control question. In PHP, like most programming languages, you can use flow control statements like `switch` and `if` to only execute certain blocks of code, or move some blocks into separate functions.

Since it's your own function you're calling here it completely up to you how to handle it. As you gain experience you'll learn ways to determine what to separate out into unique functions and what to just use `if` statements to control.

To use an `if` statement, you'll probably need to add a parameter to your function to let you determine which pieces to execute.
> 1 votes

# Answer
Okay - It seems to be working with the code below...can you tell me if this looks okay? Also, is presave heavy on the database resources? The page seems to be running slower now.

```
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {

case 'presave':
if($node->type == 'property'){
$old = node_load($node->nid);

if($old->field_usera_ref[0]['uid'] != $node->field_user_ref[0]['uid']){
mymodule_tn_complete($node, $type = 'realtor_assign');
}

if($old->field_userb_reference[0]['uid'] != $node->field_userb_ref[0]['uid']){
mymodule_tn_complete($node, $type = 'am_assign');
}

if($old->field_userc_ref[0]['uid'] != $node->field_userc_ref[0]['uid']){
mymodule_tn_complete($node, $type ='trep_assign');
 }
break;
  }
 }
}

function mymodule_tn_complete( $node, $type)
{
        switch($type){

        case 'realtor_assign':
        //Do Stuff
        break;

        case 'am_assign':
        //Do other stuff
        break;

        case 'trep_assign':
        // Do different stuff
        break;
        }
}

```
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: How to create a view displaying nodes posted in the logged-in user groups?
I can't figure out how to create a view listing all nodes from the logged-in user groups. This was easy with Drupal 6 version of Organic groups, but with the entity based version, it is not obvious (or maybe not doable without some views data hooks).

Thanks for your help.

# Answer
> 0 votes
I've interpreted this question as asking how to set up a View which displays all content published by the current user in the groups he or she belongs to.

Assuming that you have your group set up correctly and a group content type (content that belongs to the group), you should be able to filter by group membership in the following manner:

1. Create a node View
2. Add a Node group membership relationship
3. Add a Group membership: Node group membership contextual filter (argument in D6)
4. While setting up the contextual filter, select "Provide default value" under the fieldset titled "when the filter value is NOT in the URL."
5. Insert the following code:

```
global $user;
$all_groups = db_query('SELECT gid FROM {og_membership} WHERE etid = :uid', array(':uid'   => $user->uid));
$groups_array = array();
foreach($all_groups as $group){
  $groups_array[] = $group->gid;
}
$groups_string = implode('+', $groups_array);
return $groups_string;

```
6. Make sure that you don't provide a way for users to supply their own contextual filter through the URL, otherwise your default contextual filter won't be used.
7. Under the "Extra" fieldset at the bottom (click to expand), check "Allow Multiple Values." Save the contextual filter.
8. Create a normal filter for "User:Current" to limit results to those authored by the current user.

Something along those lines should do the trick.

# Answer
> 2 votes
In Views you can use `User: Current` under "Filter Criteria" to filter the view results.

---
Tags: views, organic-groups
---


# Question
Title: What is the recommended method for programmatically editing or inserting values into the field_data_* tables?
I'm using Drupal 7.7

I'm working on a module to programmatically add users to an Organic Group. I'm using og\_group() and og\_role\_grant(), but the user is not given full access without also having their group\_audience field set correctly. So, my end goal is really to do just that. I cannot find any OG functions that will perform that function, so I'm asking, generically, if there is any Drupal-approved method of writing data into that table.

I've tried using field\_bundle\_settings(), but I can't get that to work, and I'm pretty sure it won't ever work.

my code is below:

```
<?php

$settings = array(
    'group_audience' => array(
    'entity_id' => $user->uid,
    'group_audience_gid' => $gid,
    'group_audience_state' => '1',
  ),
);
field_bundle_settings("user", "user", $settings);

```

thanks

# Answer
> 0 votes
If you want to create users belonging to a group (able to publish content under the group, see group content), og\_group() should do the trick; I'd check your implementation and make sure it's ok before going too far astray. I'm doing the exact same thing with the following code and it's correctly inserting the group\_audience values into the field\_data\_group\_audience table.

```
og_group($group_id, array('entity' => $account));

```

However, if you're totally stuck and want to try another route, you can always manually insert the data through db\_insert().

---
Tags: 7, entities, database, organic-groups
---


title: Execute PHP on every page?

text:
# Question
Title: Execute PHP on every page?
I'm writing a custom module for Drupal 6, and I need to execute some PHP no matter which page the user accesses.

I see that hook\_init is not run on cached pages, so that's a no-go. hook\_boot doesn't work, either, because it happens too early in the page request to let me use some functions I need.

So I was thinking about specifying a block using hook\_block, but that hook just makes me pull my hair out:

```
function test_block($op='list', $delta=0, $edit=array()) {
  switch ($op) {
  case 'list':
    $block['test_block']['info'] = t('Test block');
    return $block;
  case 'view':
    $block = array();
    switch ($delta) {
    case 'test_block':
      $block_content = '<?php echo \'WTF?\'; ?>';
      $block['subject'] = NULL;
      $block['content'] = $block_content;
      break;
    }
    return $block;
  }
}

```

This renders as:

```
<div class="content">
    <!--?php echo 'WTF?'; ?-->
    <a id="context-block-test-test_block" class="context-block editable edit-global"></a>
</div>

```

Obviously, that's not what I'm looking for, either. Why does the PHP in that block not render correctly? Even if I end up using something other than a block to solve my problem, this issue really sparks my curiosity.

If I can't use hook\_block, how do I get some PHP to run on every page? I need access to the $user global and to the drupal\_goto() function.

# Answer
I ended up using hook\_init, since pages aren't cached for authenticated users. I only needed this PHP to run for authenticated users. I really wish I could have figured out what was going on with hook\_block, though...
> 0 votes

# Answer
What is wrong with your code is that the code that outputs the content of the block needs to be executed, such as:

```
$block['content'] = test_get_block_content();

```

This code makes sense if the code needs to output something in the page; if the code that needs to be executed doesn't need to output anything in the page, then hook\_exit() is always executed, even on cached pages. The documentation for that hook reports the following text:

> Only use this hook if your code must run even for cached page views. If you have code which must run once on all non cached pages, use `hook_init()` instead.

As for redirecting a user, you can look at what the Redirect module does to redirect a user. The purpose of the module is to redirect a user basing on the currently visited page, and on settings decided from an administrator user. The code that redirects the user is contained in this function, which is the implementation of hook\_init():

```
/**
 * Implements hook_init().
 */
function redirect_init() {
  if (!redirect_can_redirect()) {
    return;
  }

  $current_path = current_path();
  $current_langcode = $GLOBALS['language']->language;
  $current_query = drupal_get_query_parameters();
  if ($redirect = redirect_load_by_source($current_path, $current_langcode, $current_query)) {
    redirect_redirect($redirect);
  }
  // …
}

```

The `redirect_redirect()` function is a wrapper for `redirect_page_cache_clear()`.

```
function redirect_page_cache_clear($redirect = NULL) {
  if (!variable_get('redirect_page_cache', 0)) {
    return;
  }

  if (isset($redirect)) {
    $path = url($redirect->source, array('absolute' => TRUE));
    // Use a wildcard to catch paths with query strings.
    cache_clear_all($path, 'cache_page', TRUE);
  }
  else {
    // Clear the entire page cache.
    cache_clear_all('*', 'cache_page', TRUE);
  }
}

```

If you would implement a way to redirect a user through `drupal_goto()`, you should consider implementing `hook_init()` in a similar way.
> 4 votes

# Answer
You can include files whose functions you need to access in `hook_boot()`

e.g.

```
require_once DRUPAL_ROOT . '/' . 'includes/path.inc';
require_once DRUPAL_ROOT . '/' . 'includes/locale.inc';

```

Obviously this means a bit more digging to determine precisely which files you need to include, but it can be done without too many headaches...
> 1 votes

---
Tags: blocks, hooks
---


# Question
Title: How do I programatically create a node, add a menu item, and add a path alias?
I am using Drupal 6. I have an external database that I need to somehow turn into nodes so that our Drupal site can display the content and search the content with Solr. I currently have a module which displays pages and queries the database directly each time these pages are viewed. This is not an optimal solution because these pages are not found when a user uses our search.

I know that I can iterate through the database items, create a $node object and use node\_save() to create nodes.

1) Can I set a specific NID such as $node-\>nid = 9999999 . $some\_database\_key so that I know these nodes can be referenced later for updating?

**I could not get this to work, but I did figure out this solution:** I created a database table for my module similar to the one in the node\_example module. Using this and a custom content type, I could create nodes. I could not get it to work properly until I used

```
$node = node_submit($node);

```

prior to calling

```
node_save($node);

```

2) How do I create menu items for these new nodes?

**Solution**

```
$link = array();
$link['menu_name'] = 'custom_menu'; // Fill out your menu name or just use navigation
$link['link_title'] = 'Title Here'; // What appears in the menu link
$link['link_path'] = 'node/' . $node->nid; // Or you can use a path alias as well
$link['plid'] = 12; // Optional - if you want it to nest under an item you'll need its mlid (menu id)
menu_link_save($link);

```

See: http://api.drupal.org/api/drupal/includes--menu.inc/function/menu\_link\_save/6

3) How do I create aliases for these nodes such as node/856 goes to programs/some-program-type/some-program-title

**SOLUTION** Similar to the menu solution above, you can use

```
path_set_alias('node/' . $node->nid, 'path/alias/here');

```

Thanks for any suggestions!

# Answer
I understand that you have some external database, and your nodes are in relation with some entities from there. You need node 'downloading' some content from other database; for compatibility with Solr.

1) Instead 'hacking' node number, I think you should use create node type for it. Beside distinguishing downloaded nodes for others; you can create CCK field for storing external database id; and setting content edition permission that nobody can edit it.

2) In your custom module you need to implement hook\_blocks to put in the menu content that you need.

3) With pathauto module you can simply create automatic path. If you create special content type out of the box pathauto functionality should be enough.
> 1 votes

---
Tags: nodes, 6
---


# Question
Title: Various "Undefined" notices on content admin screen
I get these sporadically on the content admin screens. These seem to be referencing fields that I do have in my templates, that are working just fine for those actual screens. I just don't get why this content admin screen would be looking for those values.

Here are the error messages:

```
•   Notice: Undefined property: stdClass::$field_pcast_fname in include() (line 64 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/node.tpl.php).
•   Notice: Undefined variable: messages in include() (line 13 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/comment-wrapper.tpl.php).
•   Notice: Undefined index: field_twithandle in include() (line 14 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/user-profile.tpl.php).
•   Notice: Undefined variable: field_headshot in include() (line 24 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/user-profile.tpl.php).
•   Notice: Undefined offset: 1 in include() (line 94 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/user-profile.tpl.php).
•   Notice: Trying to get property of non-object in include() (line 94 of /mnt/drive2/vhosts/ainonline.com/httpdocs/drupal/sites/all/themes/ain_core/templates/user-profile.tpl.php).

```

And for example, the field\_twithandle code that's in my user-profile.tpl.php:

```
<?php if($user_profile['field_twithandle']) { ?>
    <div class="profile_twitfollow">
        <a href="http://twitter.com/<?php print $field_twithandle[0]['value']; ?>" class="twitter-follow-button" data-show-count="false" data-show-screen-name="false">Follow @<?php print $field_twithandle[0]['value']; ?></a>
        <script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
    </div>
<?php  } ?>

```

# Answer
Try this, check to make sure it's set first:

```
<?php if (isset($field_twithandle[0]['value'])): ?>
<a href="http://twitter.com/<?php print $field_twithandle[0]['value']; ?>" class="twitter-follow-button" data-show-count="false" data-show-screen-name="false">Follow @<?php print $field_twithandle[0]['value']; ?></a>
<?php endif; ?>

```

The problem is that those values aren't set on some pages, which is why you're getting the error. So that's a fix for an undefined index error. You also have things like undefined variable, for which a fix could be like:

```
<?php if (isset($messages)): ?>
  /* Do stuff here with $messages */
<?php endif; ?>

```
> 1 votes

---
Tags: 7
---


# Question
Title: Use contextual filter on no results behavior
I'm creating a view where I'd like to use the node ID of the current node seen on the page on the no results behavior. Is it possible?

# Answer
If you have the PHP input format enabled you can use `arg(1)` in the empty text for the view.
> 1 votes

# Answer
You can also create a content pane and send the argument to panels, and use %1 where you want to use the node title. Pretty much all my views are content panes now so I can use this and similar functionality.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Selling user accounts with Ubercart module
A question regarding the registration process. The project I am currently working on has a 1 step registration form (Drupal default). Upon completion of the form an account is created and the new user is e-mailed with an activation e-mail. At this point they are taken to the payment (ubercart) page to purchase the applicable role for the account.

Issue is, I need the registration form to only be shown either after the account has been paid for OR not to actually create the user until payment has come through.

Is this possible, and if so could you please point me in the right direction?

Thanks!

# Answer
Look into http://www.ubercart.org/docs/user/3366/selling\_site\_access\_role\_promotions
> 2 votes

# Answer
Well, that is a good point.. You could create a special role for the user registration, before buying, create a special page for this state or use the payment page, and assign permissions to only this page. After the payment is done, assign the user new role, with permission to full site and/or your application.

I think this would be even a better solution because you already make a connection between the potential buyer and your product. They can return to the payment stage anytime, if they were not ready to pay when they visited your site for the first time. It is more likely they will come back this way, because they already made the decision to buy, they already own a password. And it is much easier to make this decision when you know you will pay later, when returning.. :)
> 0 votes

---
Tags: users, ubercart
---


title: Archive page for custom content

text:
# Question
Title: Archive page for custom content
I want to create an archive page for a custom content type. Essentially list them all on a single page.

I understand that I need to create a module, and implement `hook_block_info()` and `hook_block_view()`. What I don't know how to do is to retrieve content so I can loop it out. In wordpress there is `query_posts($post_type = mycustomcontenttype)`. Is there an equivalent in Drupal 7?

I do not want to use the Views module for this.

# Answer
> 1 votes
If you're looking to retrieve $node objects and aren't afraid of formatting the info yourself, node\_load\_multiple() probably comes closest to solving your problem. The $conditions parameter is supposed to be deprecated, but you could use it to specify content type. If you want to use node\_load\_multiple() in the manner recommended by the API page, I believe you would just use a simple db\_query() to retrieve the node ids (nids) of all content with a given type:

```
$nids = db_query('SELECT nid FROM {node} WHERE type = my_content_type');

```

Then you could iterate through the results to create an array of nids to pass to node\_load\_multiple().

```
$nid_array = array();
foreach($nids as $nid){
  $nid_array[] = $nid;
}
node_load_multiple($nid_array);

```

From there you're going to have to iterate through the $node objects returned to create your archive page. Depending on whether you're using path aliases, you might have to retrieve the alias for each node.

```
drupal_lookup_path('alias',"node/".$node->nid);

```

All that said, I would do this in Views in a heartbeat.

# Answer
> 0 votes
For such queries, there is the EntityFieldQuery class, and the code to use is similar to the following one:

```
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'mycustomcontenttype')
  ->propertyCondition('status', 1)
  ->execute();

$nodes = entity_load('node', array_keys($entities['node']));
return node_view_multiple($nodes, 'teaser');

```

Instead of `entity_load()` you can use `node_load_multiple()` passing the second argument passed to `entity_load()`.

When showing a list of nodes to user, always filter the nodes basing on their "status" field, except in the case the user has the permission of viewing unpublished nodes; in any case, you should check if the user has that permission.
As third-party modules could restrict the permission to view a node to specific users, instead of depending from the value of the "status" field, you should use node\_access('view') to verify the user has the permission to see the node, before to visualizing it.

---
Tags: 7, blocks, hooks
---


# Question
Title: Should magic quotes be on/off for Drupal 7?
Should magic quotes be on or off?

# Answer
Off. Currently it's non standard to set them on, and here you have somebody with problems created by magic quotes on.
> 1 votes

---
Tags: 7
---


# Question
Title: How do I add the content type token in the page title?
I have installed the Page Title module. What I want to achieve is to add the content type token as page title. I tried to change the pattern in the configuration of the Page Title module, but the tokens appear as they are: "\[current-page:page-title\], \[field\_glossary\_transliterations\] - \[field\_glossary\_meaning\] | \[site:name\]."

How do I do it?

# Answer
Short answer: Simply insert the \[node:content-type\] token.

Longer answer:

The Page Title module modifies the title that appears in the `<title>` tag (which also displays in your browser's title bar. Just to clarify, this is separate from an individual node's title.

In the module configuration page, you will only see the raw token names displayed. The Page Title module will convert those tokens to human readable values on an actual node or "page". View the source of one of your nodes and check the `<title>` tag to see the actual values.

This module relies on the Token module in order to operate.

You can also get the Entity API module (and enable the Entity Tokens submodule) to get even more tokens that weren't picked up before.

Also: Be aware that the project maintainer has identified an issue with Fusion based themes. If your site falls into that category, temporarily switch to another theme such as Bartik to test out the page title module.
> 1 votes

---
Tags: 7
---


# Question
Title: How to include a form in a listing page?
**I am displaying a content information page. At the end of the content displaying page i need to display a form.**

How shall i do it?

What have I done?

1. Written a menu callback in `hook_menu()`
2. Written a method to collect the information
3. Registered a theme in `hook_theme()`
4. Written hook\_preprocess\_theme() to register variables
5. Created a template and assign the variables

By doing all the above, I am displaying the Content Information.

What do I need to do, to display a form at the end of the content?

I have done these thing.

1. Created a form in a function called `content_form()` (including logic)
2. Wrote a submission function (`content_form_submit()`).

My only todo left is displaying the form at the content information page.

# Answer
The quick and dirty way to print a form defined by hook\_form is to use the drupal\_get\_form function:

```
print render(drupal_get_form('content_form'));

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Does Drupal resave the photo even if it's already the correct size as your Image Style?
Does Drupal still recompress the photo even if the file you uploaded is *already* the same size as your selected Image Style? In the event that it does recompress it, is there a way to prevent it? Image quality is at stake in this case since it saves it in JPG.

# Answer
> 1 votes
I ran some **Md5 tests** and sadly it *does* recompress it again even if it's already the correct dimensions. Is there *some* way to prevent this? Uncool.

---
Tags: 7, media
---


title: Thoughts on YSlow Feedback

text:
# Question
Title: Thoughts on YSlow Feedback
I have read many articles on improving the page load for Drupal and used as many steps as possible to enhance the speed of the site.

I installed the FireFox pluggin YSlow to get feedback on my site. I scored a 91 with an A rating thanks to the changes recommended in the forum.

YSlow is giving me an Grade F on Configure entity tags (ETags) and Grade F on Use cookie-free domains.

Are ETags and Cookie-Free domains, something I should concern myself with?

Even though I have a good rating, I still feel the home page loads slowly. Even going from a page with images to a text only page there is a delay.

Thank you.

# Answer
If your using multiple web servers then ETags need to be configured correctly. Add this to your .htaccess file (at the bottom) if this is the case. If you only have 1 server then you can safely ignore this recommendation.

```
FileETag MTime Size

```

Cookie-free domains offer a slight performance improvement because less data will be traveling over the wire. You need a CDN to get a cookie-free domain setup correctly.
> 2 votes

---
Tags: performance
---


title: drupal generating image-styles

text:
# Question
Title: drupal generating image-styles
I just wanted to know if there is some way to make Drupal 7 re-build all the images for a specific style. The image style is created after the pictures were uploaded. The module using this image style will be color box.
Even though I update, delete, re-create the style, no images are generated in the according folder on the webspace.

Do you have any idea?

# Answer
You can use drush to re-build specific image styles. `drush image-flush thumbnail` will force the refresh of thumbnail styles; you can use `drush image-flush` to get a list of available styles to clear.

You can find more information on the Drush website.
> 3 votes

# Answer
I used to have problems updating images after image styles were changed. Images would remain the same size they were before the style updates. Then I realized the problem was with my template files. I used to have static references to images, in the styles directories, which was wrong.

Then I realized I should use a function to display those images. This is how I do it now:

```
<img src="<?php print image_style_url('large', $node->field_image[$node->language][0]['uri']) ?>" />

```

The 'large' attribute is the image style name, you can use 'medium', 'thumbnail' or whatever custom style you have defined.

This solved the problem for me. When displayed, images appear according to the latest definition I have applied.

I don't know how Colorbox handles images with styles. Anyway, I hope my answer helps you.
> 1 votes

---
Tags: media
---


title: Add your own content to node

text:
# Question
Title: Add your own content to node
I've created a module that adds custom content to a node; I'd like to display this custom content in the node view. I think `hook_node_view()` is the right hook to use, but my content doesn't get displayed.

what I got so far is the following code:

```
function mymodule_node_view($node, $view_mode = 'full', $langcode = NULL) {
$node->content['mymodule']['#items'][0] = array(
    'value' => theme('mymodule_output', array('mymodule_cid' => $node->mymodule_cid)),
    'summary' => '',
    'format' => 'full_html',
    'safe_value' => theme('mymodule_output', array('mymodule_cid' => $node->mymodule_cid)),
    'safe_summary' => '',
);
$node->content['mymodule']['#weight'] = 12;
}

```

Can anybody help?

# Answer
> 19 votes
**TL;DR:** The hook is correct, but `$node->content['mymodule']['#items'][0]` should at least contain one of these array indexes/properties: "#markup" or "#theme"; if you don't use one of them, Drupal will not output anything.

If the array indexes you use are for properties handled by your theme function, then you should use *#* at the beginning; for example "format" would become "#format" (the same is true for the other properties).

Anyway, there is no need to use "format" as you do (whatever meaning it has); the function just output HTML, as done in the example shown in the hook\_node\_view() example.

```
function hook_node_view($node, $view_mode, $langcode) {
  $node->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}

```

If you want some more concrete examples of that hook implementations, you can look at book\_node\_view(), statistics\_node\_view(), and translation\_node\_view().

```
function book_node_view($node, $view_mode) {
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $node->content['book_navigation'] = array(
        '#markup' => theme('book_navigation', array('book_link' => $node->book)),
        '#weight' => 100,
      );
    }
  }

  if ($view_mode != 'rss') {
    book_node_view_link($node, $view_mode);
  }
}

```

As side note, I will add that you should use the *#* character only for properties, or you are going to confuse Drupal, which expects that character to be used only for properties.
In fact, element\_children(), which returns the list of child elements of the element passed as argument, uses the following code:

```
  foreach ($elements as $key => $value) {
    if ($key === '' || $key[0] !== '#') {
      $children[$key] = $value;
      if (is_array($value) && isset($value['#weight'])) {
        $sortable = TRUE;
      }
    }
  }

```

As you see, elements whose key value starts with *#* are not taken to be child elements; differently, Drupal would not be able to handle a case like this one (the code is really implemented by a Drupal module, the Search module):

```
  $form['#action'] = url($action);
  // Record the $action for later use in redirecting.
  $form_state['action'] = $action;
  $form['#attributes']['class'][] = 'search-form';
  $form['module'] = array(
    '#type' => 'value',
    '#value' => $module,
  );
  $form['basic'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['basic']['keys'] = array(
    '#type' => 'textfield',
    '#title' => $prompt,
    '#default_value' => $keys,
    '#size' => $prompt ? 40 : 20,
    '#maxlength' => 255,
  );
  // processed_keys is used to coordinate keyword passing between other forms
  // that hook into the basic search form.
  $form['basic']['processed_keys'] = array(
    '#type' => 'value',
    '#value' => '',
  );
  $form['basic']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );

```

Are `$form['#action']` and `$form['basic']['submit']` child elements?

As another side note, I will add that `hook_view()` is invoked by Drupal only for the modules that implement a content type. In fact, the implementations of that hook are invoked by node\_build\_content() using the following code:

```
  // The 'view' hook can be implemented to overwrite the default function
  // to display nodes.
  if (node_hook($node, 'view')) {
    $node = node_invoke($node, 'view', $view_mode, $langcode);
  }

```

The code for node\_invoke() is the following one:

```
  if (node_hook($node, $hook)) {
    $base = node_type_get_base($node);
    $function = $base . '_' . $hook;
    return ($function($node, $a2, $a3, $a4));
  }

```

The code invokes `$hook` for the module implementing the content type of the node passed as argument.

---
Tags: 7, hooks, nodes
---


# Question
Title: Fetching Views 3 implementation from code
I am using Drupal 7. What I want to do is to fetch the View 3 implementation from code, rather than from database, so that I can export my view, and put it in a function that would be available to all my team members w/o the need of importing the database script.

# Answer
> 1 votes
Take a look at hook\_views\_default\_views().

Remember to implement hook\_views\_api() in mymodule.module file, so that views can find your views stored in code using `hook_views_default_views()`.

# Answer
> 2 votes
There are quite some different ways to achieve this

* Use the ctools bulk export module, this will provide you some example code to use
* use the features module, which gives you a full module

---
Tags: views
---


title: Not too sure about template.php

text:
# Question
Title: Not too sure about template.php
I'm primarily a designer and I've been working on Drupal themes for some time now. At this point, I'm comfortable enough converting my designs to Drupal themes reasonably quickly but I continue to have doubts about how to use the template.php file... I've read up about it quite a bit, but my understanding of its usefulness is theoretical at best.

Clearly it's not a required file since it's never stopped my themes from working in the past, but is it advisable to have one in all cases? Are there functions (or anything else for that matter) one would automatically include in template.php?

# Answer
The template.php file should contain the presentation code; the "logic" code, such as the theme functions, or other code that computes the value of a variable, should be in the template.php file.

To make an example, code similar to the following one should not be in the template file, but it should be put in a function contained in the template.php file, and which return a value to the calling code, which then uses the returned code:

```
  if ($user->uid) {
    $class[] = 'authenticaded-user';

    if (user_access('administer content')) {
      $class[] =  'content-administrator';
    }
  }
  else {
    $class[] = 'anonymous-user';
    $class[] = 'anonymous-' . strtr(ip_address(), '.', '-');
  }

  if (isset($class)) {
    print ' class="' . implode(' ', $class) . '"';
  }

```

The code in the template file should just print (or render) values, but not compute those values; clearly, it's perfectly fine to use code similar to the following one (the code is taken from a Drupal 7 theme):

```
    <?php if ($logo || $site_title): ?>
      <?php if ($title): ?>
        <div id="branding"><strong><a href="<?php print $front_page ?>">
        <?php if ($logo): ?>
          <img src="<?php print $logo ?>" alt="<?php print $site_name_and_slogan ?>" title="<?php print $site_name_and_slogan ?>" id="logo" />
        <?php endif; ?>
        <?php print $site_html ?>
        </a></strong></div>
      <?php else: /* Use h1 when the content title is empty */ ?>
        <h1 id="branding"><a href="<?php print $front_page ?>">
        <?php if ($logo): ?>
          <img src="<?php print $logo ?>" alt="<?php print $site_name_and_slogan ?>" title="<?php print $site_name_and_slogan ?>" id="logo" />
        <?php endif; ?>
        <?php print $site_html ?>
        </a></h1>
    <?php endif; ?>
    <?php endif; ?>

```

The difference is that, in this case, the code is verifying if the variable contains a useful value, and eventually avoid to output the markup, when it's not necessary.
> 2 votes

---
Tags: 6, theming
---


title: jQuery hotkeys plugin

text:
# Question
Title: jQuery hotkeys plugin
I've found a nice plugin to bind hotkey combinations like Ctrl+A for submit buttons, but I don't understand how I can apply this to my form submit button.

Can anyone put me on the right direction?

# Answer
It looks like what you'll want to do is add it in a separate js file in a module. Use `hook_form_alter()` or `hook_form_FORM_ID_alter()`and identify the form that you want the script run on. Then In `hook_form_alter()` use `drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');` to add the JavaScript file to that page.

Also in `hook_form_alter()`, you'll want to identify the button you want to add this to and add a prefix and suffix markup to it.

```
$form['button']['#prefix'] = array('<div class="my-button-class">');
$form['button']['#suffix'] = array('</div>');

```

In the JavaScript file, where you see div.foo you'll want to enter the name of that div that you created on the button.

```
$('div.my-button-class').unbind('keydown', 'Ctrl+a', fn);

```

Also in hook\_form\_alter() you need to add a class to an input or button or whatever you are using.

```
$form['field']['#attributes'] = array('class' => array('my-other-class'));

```

For this, in the js file you need to replace:

```
$('input.my-other-class').bind('keyup', '$', function(){

```

EDIT: Note the *input*.class. If you're targeting a different type of element this will need to be changed accordingly. Same with *div*. class. I think you can also do IDs like input#my-input-id.
> 3 votes

---
Tags: javascript, forms
---


# Question
Title: Pathauto menu token duplicated for a menu added in hook_node_insert
I have a content type using the following pathauto-token pattern: `[node:menupath]/[node:title]`, I added manually a menu using a hook\_node\_insert (see my previous question: creating a menu in a hook\_node\_insert()).

When the node is saved it doesn't have the `[node:menupath]` token in the URL, just the `[node:title]`. I decided to generate the path using pathauto API and this code:

```
$options = array(
  'language' => isset($node->language) ? $node->language : LANGUAGE_NONE,
);
module_load_include('inc', 'pathauto');
$uri = entity_uri('node', $node);
$path = pathauto_create_alias('node', 'insert', $uri['path'],
  array('node' => $node), $node->type, $options['language']);

```

Doing this lead to duplicates in the `url_alias` table, the `[node:menupath]/[node:title]` alias being created first then the title.

I tried to add a `$node->pathauto_perform_alias = FALSE;` in a presave, but seems to be inefective.

Also I tried to set my new path in the hook\_node\_insert but had no success:

```
$path = pathauto_create_alias('node', 'insert', //...
$node->path = $path;

```

My code doesn't feel right, what would be the normal way to avoid duplicate and getting my pattern to work ?

Thanks

# Answer
> 0 votes
I finally moved the insertion of my menu in `hook_node_presave()` and then pathauto worked normally.

---
Tags: 7, hooks, path-aliases, nodes
---


# Question
Title: Hide local tabs in specific content type
I want to hide the local tabs for a specific content type. How can I do this? I don't want to complete remove it since I want to show them in other content types

# Answer
> 1 votes
Have you tried Tab Tamer ? If you're using D7 a port in on its way.

---
Tags: 7
---


# Question
Title: How do I make an alias appear under taxonomy term
Right now, I am adding the taxonomy-term part manually to the beginning of the URL as:

inspirational-story/just-because-of-one-vowel

'inspirational-story' is a taxonomy-term. What do I do that I don't have to put this term manually in the URL, and I just write 'just-because-of-one-vowel' in URL alias field.

# Answer
You need to use the Pathauto and the Token module to define patterns for your URL aliases. Once installed, it will give you a list of tokens to choose from.

e.g. \[node:field\_YOUR-VOCABULARY\]/\[node:title\]
> 2 votes

---
Tags: path-aliases
---


title: Combining 2 exposed filters

text:
# Question
Title: Combining 2 exposed filters
Using Drupal 6. Views 2.

After googling a bit I found this module which does exactly what I need http://drupal.org/project/views\_or, combine 2 exposed filters into 1 single "search box". However, it doesn't work for Views 2.

Anyone know of any alternatives? I want to allow the user to search for terms, both in the title of the node and the taxonomy tags.

Thanks

# Answer
If I understand you correctly, then I believe the solution I used for a similar task is this - http://drupal.org/node/578620#comment-2750454.

Hope it helps,
Shushu
> 1 votes

---
Tags: views, taxonomy-terms, search
---


# Question
Title: get taxonomy terms of parent node while in block
I'm in drupal 7. Let's say I have a block on a website page. The website page is a node that has taxonomy terms. How do I programatically get the taxonomy terms of the website page node from my block?

# Answer
You should be able to use `menu_get_object()` to get the node object if the block is being displayed on a node page. Then, with the `$node` object you can retrieve terms for the node.

```
if ($node = menu_get_object()) {
  $query = db_select('taxonomy_index', 'r');
  $t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
  $v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
  $query->fields( $t_alias );
  $query->condition("r.nid", $node->nid);
  $result = $query->execute();
  $terms = array();
  foreach ($result as $term) {
    $terms[$term->tid] = $term;
  }
}

```

Just remember that that if caching is enabled in your block it should be per-page caching, otherwise you could get unexpected results.
> 1 votes

---
Tags: 7, nodes, taxonomy-terms, blocks
---


# Question
Title: Adding a taxonomy specific css file to certain pages
Im building a web page with multiple sub-portals, which should all have slightly different css styles. Is it possible to add a certain css file depending on the taxonomy of a node? With `drupal_add_css` maybe? Im using Drupal 6.

Thanks, Max

# Answer
> 1 votes
If you want to load certain CSS files based on taxonomy, maybe you could name your files according to taxonomy vocabularies. Just build the file name based on the vocabulary of a term.

```
$file = 'mymodule_taxonomy_' . $vocabulary . '.css';
drupal_add_css(drupal_get_path('module', 'mymodule') . '/' . $file);

```

If you have a node object you can use `taxonomy_node_get_terms()` to get the terms for a node and use this code to load a proper CSS file. Then, with a vocabulary named `cars` you can name a CSS file `mymodule_taxonomy_cars.css`. That file can be loaded according to a vocabulary.

---
Tags: 6, taxonomy-terms, theming
---


# Question
Title: In Drupal 7, where is the code for the "powered by Drupal" block?
The "powered by Drupal" block used to be a module in Drupal 6. I can not find this module in Drupal 7. Where do I find this module/block? So I can duplicate it, or modify it.

# Answer
> 6 votes
The contents is provided by `theme_system_powered_by()`, which is turned into a block by `system_block_info()` and `system_block_view()`.

# Answer
> -2 votes
The block itself is located in admin/structure/block, where you can disable for the footer if you'd like.

I would say if you want to duplicate/modify it then you can just create a new block with whatever content you'd like

---
Tags: 7, blocks
---


title: How to track IP addresses

text:
# Question
Title: How to track IP addresses
I want to track IP address of visitors in my site using statistics module.

A log of which is attached here( 3 day log). I can't figure out if an IP address is used by a bot or human being. For example when I checked the 2nd and 3rd IP address, they turned out to be that of Google and Microsoft( Bing). But I've no idea about the first ip address with 900 visits in 3 days.

I want to track malicious user ip address for Adsense invalid clicks.

# Answer
> 0 votes
What module are you using to get the list of IPs ? You need a Reverse DNS lookup to integrate with your module, I wasn't able to find such module on drupal.org but there's a lot of sites that provides such service like Domain tools: lookup for 203.153.44.130.

---
Tags: nodes
---


# Question
Title: Where to put a script to provide AJAX/JSON response?
I'm using drupal 7. I want to create a php script that uses Drupals DB abstraction layer to query the database and spit out JSON data. Where would I place such a script? At the moment, I've done it in a round-about way by create a new node, then in the `function theme_process_page()` of my `theme/template.php`, I wrote an IF statement to detect the node id, then run my code, then call a die() statement.

Is there a more appropriate place for me to put this script?

\** additional notes \** This script is to be called every time a person presses "Provide a menu link" when adding/editing a node in the CMS. The script will then automatically select the appropriate `Parent Item` and `weight` based on any other existing translation.

# Answer
The easiest is to use Views datasources if it can solve your problem, in essence this means that if you can use views to display the data you need, you can use this module to return it as JSON.

Another option is to write a custom module and use hook\_menu to define a 'menu' item which you can use from the calling code. To return your data as JSON you can use the standard php functions.

If you need multiple scripts and advanced configuration you can always have a look at Services or
> 2 votes

---
Tags: 7, ajax
---


title: Installing Drupal 7 on VPS CentOS

text:
# Question
Title: Installing Drupal 7 on VPS CentOS
I am using a Green Geeks VPS (CentOS) at the moment and I am new to it. I have found a tutorial on installing Drupal/Apache/Webadmin etc. http://drupal.org/node/743610

What I am wondering is why not just use something like XAMPP instead of all the separate installs? Is there something more I have to take into account here?

# Answer
> 1 votes
I think it's more a taste/customization vs convenience here.
Using XAMPP can install way more stuff than needed and SysAdmins doesn't like this ;) installing each piece individually allows you to select exactly the pieces you need and also there's less risk to be bothered by some strange library or configuration that XAMPP may set up.

So to sum-up:

* you're **tech-savvy**, you want to manage and configure your VPS and aspire to become a SysA, go for the separate install.
* you **don't want the hassle** of configuring (and eventually debugging) each parts, go for XAMPP.
* if you want **even less troubles**, go for a fully managed/optimized hosting platform like Acquia Dev Cloud.

---
Tags: 7
---


title: improve workflow for multi-lingual site

text:
# Question
Title: improve workflow for multi-lingual site
My client is having a terrible time managing multi-lingual content in drupal 7. I'm using the internationalization module and drupal 7's default capabilities in managing multiple languages. Here's an example workflow my client executes, with bold statements that indicate challenges.

1. Client begins to add new content of content type page. He fills out title and selects language as English.
2. Client clicks on menu settings, and select Provide a menu link. Under Parent item, client selects from the drop down tree About.
3. Client publishes the page.
4. Client clicks on Translate to translate the page.
5. Client clicks on add translation for French to see the add content page.
6. Client notices all the fields **except menu settings is populated. This irritates the client. Client expects the CMS to know that the A Propos menu link is the french equivalent for About menu link, and to have populated accordingly. But instead, client must go through hundreds of link.**

Here's another example workflow that illustrates a big problem.

1. Client wants to re-structure the site map.
2. Client goes to an ENGLISH page in the CMS, goes to menu settings, and changes the Parent item to the Home menu link.
3. Client presses Save.
4. Client goes to FRENCH version of the same page. **Client needs to repeat the process of Parent item but find Accuiel menu link. This irritates the client because client expects the CMS to be smart enough to know Accuiel menu link is the french version of Home menu link, and when the English page was moved from About to Home, then the French page should have moved from A Propos to Accuiel.**

As it stands now, the client feels like he's managing two websites individually. Can anyone suggest a workflow that can reduce the client's workload by about half ? Simply having drupal reflect site map changes in english into french would reduce workload by about half.

# Answer
Ok, I created a hack!!! And a very poorly done hack too. Here's what it does. My hack will put a button above the `CMS>Add Content>Menu Settings>Parent Item`. The button will say "Synchronize Menu Item with Main Language". So for example, if `Awards` move from `Tournaments>Year 2011` to `Achievements>Celebration`, then you can go to C`MS>A Propos>Menu Settings` and click on "Synchronize Menu Item with Main Language" to automatically move `Prix` from `Tournois>Annee 2011` to `Réalisations>Célébration`.

here's my code.....hopefully it's not too buggy...

Add to /themes/seven/seven.info the following line

```
scripts[] = lang.js

```

/themes/seven/lang.js

```
if (typeof jQuery == 'function'){
  jQuery(document).ready(function($) {

        var btn = document.createElement('input');
        btn.value = 'Synchronize Menu with Main Language';
        btn.type = 'button';
        btn.style.padding = '5px 15px';
        btn.style.border = '1px solid #666';
        $(btn).click(mapMenu);

        var loading = document.createElement('span');
        loading.style.display = 'none';
        loading.style.color = 'red';
        loading.id = 'loading-sync';
        loading.innerHTML = 'loading...';

        $('.form-item.form-type-select.form-item-menu-parent').prepend(loading);
        $('.form-item.form-type-select.form-item-menu-parent').prepend(btn);

  });
}

function mapMenu() {
        var sendurl = '/sync-menu/';
        var params = 'menu=main-menu&l='+jQuery('#edit-language').val();

        // translation already exists, so give nid
        if(location.href.match(/^.*node\/\d+.*$/))
        {
                var nid = location.href.replace(/^.*node\//,'').replace(/\/.*/,'');
                params += '&nid='+nid;
        }
        // no translation exists, so give the source nid
        else if(location.href.match(/^.*translation=/))
        {
                var snid = location.href.replace(/^.*translation=/,'').replace(/&.*$/, '');
                params += '&snid='+snid;
        }
        else
        {
                alert('No translation available for this menu');
        }
        jQuery.ajax({ url: sendurl, context: document.body, success: mapMenuCallBack, data:params, type:"GET"});
        jQuery('#loading-sync').css('display','inline');
}

function mapMenuCallBack(responseText)
{
        jQuery('#loading-sync').css('display','none');
        if(!responseText) {alert('No translation available for this menu'); return;}

        eval('var obj = '+responseText);
        if(obj.plid) jQuery('#edit-menu-parent').val('main-menu:'+obj.plid);
        if(obj.weight) jQuery('#edit-menu-weight').val(obj.weight);
}

```

/sync-menu/index.php

```
<?php
// this script is a hack to synchronize multilingual menues.  i don't have time to learn Drupal 7 and the proper way to do things.

include('../sites/default/settings.php');

$cnx = mysql_connect($databases['default']['default']['host'], $databases['default']['default']['username'], $databases['default']['default']['password']);
if(!$cnx) die('failed to connect');

$db = mysql_select_db($databases['default']['default']['database'], $cnx);
if(!$db) die('failed to select db');

$arr_translation = array();
//$menu_name = $_GET['menu'];
$menu_name = 'main-menu';
$lang = substr($_GET['l'],0,2);
$nid = isset($_GET['nid']) ? intval($_GET['nid']) : 0;
$src_nid = isset($_GET['snid']) ? intval($_GET['snid']) : 0;

if($nid)
{
        $sql = "SELECT tnid FROM `node` WHERE nid = $nid";
        $result = mysql_query($sql);
        $row = mysql_fetch_assoc($result);
        if($row)
        {
                $src_nid = $row['tnid'];
        }
}

if($src_nid && $lang && $menu_name)
{
        // find the menu id of source node
        $sql = "SELECT * FROM `menu_links` WHERE menu_name = '$menu_name' AND link_path = 'node/$src_nid'";
        $result = mysql_query($sql);
        $row = mysql_fetch_assoc($result);
        if($row)
        {
                $arr_translation['weight'] = $row['weight'];

                // find the parent menu id of source node
                $sql = "SELECT * FROM `menu_links` WHERE menu_name = '$menu_name' AND mlid = $row[plid]";
                $result= mysql_query($sql);
                $row = mysql_fetch_assoc($result);
                if(!$row) exit;
                // if parent menu item uses a "menu translation"
                if($row['i18n_tsid'])
                {
                        $sql = "SELECT * FROM `menu_links` WHERE i18n_tsid = $row[i18n_tsid] AND language = '$lang' AND i18n_tsid <> 0";
                        $result = mysql_query($sql);
                        $row = mysql_fetch_assoc($result);
                        if($row)
                        {
                                $arr_translation['plid'] = $row['mlid'];
                                print json_encode($arr_translation);
                        }
                }
                // if parent menu item uses a node translation, find the node it links to, get it's translation, get the relevant menu item
                else
                {
                        $src_nid = str_replace('node/','',$row['link_path']);
                        $sql = "SELECT nid FROM `node` WHERE language = '$lang' AND tnid = $src_nid";
                        $result = mysql_query($sql);
                        $row = mysql_fetch_assoc($result);
                        if($row)
                        {
                                $sql = "SELECT mlid FROM `menu_links` WHERE link_path = 'node/$row[nid]'";
                                $result = mysql_query($sql);
                                $row = mysql_fetch_assoc($result);
                                if($row)
                                {
                                        $arr_translation['plid'] = $row['mlid'];
                                        print json_encode($arr_translation);
                                }

                        }
                }
        }
}
?>

```
> 1 votes

# Answer
As far as I can tell this is a problem, the menu items aren't connected so the only thing that links them is through the node they are connected to and their translation sets.

Another possibility, but I never used it like this, is to make the menu items translatable and there's a module inside i18n that redirect links to the right language.
> 1 votes

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


# Question
Title: Set default to empty result with views exposed filters
I am using Views (7.x-3.0-beta3) and I have created a exposed text filter to a view, which work fine.

The problem is the default result value: when the field is empty, is displaying all possible results. But I want to display the empty result by default. If you have a solution please shear it.

# Answer
You can use a views preprocessor to achieve this. The 'empty' element behaves similarly to the "No Results Behavior" option in the Views UI. Place this code in template.php and clear the cache:

```
function mytheme_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'my_view_name') {
    if (empty($vars['view']->exposed_input)) {
      $vars['rows'] = array();
      $vars['empty'] = '';
    }
  }
}

```

Tested using Views 7.x-3.0-rc1.
> 3 votes

---
Tags: 7, views
---


# Question
Title: Using Git to keep Core and modules up to date
I'm looking for a way to use git to pull both core and modules. Let's say for example that I clone Drupal core from the Drupal git, and commit to my own git repo; then, I pull a bunch of modules, and also commit to my own git repo.

Is this even possible? Can I have sub folders within a repository that are checked out from a different repository? Can I still use Drupal to keep my code up to date? Perhaps I'm not really understand some git fundamentals.

# Answer
You can done it easily with Git with the submodules. Every subfolder from yours sites/all/modules (for example) can be a submodule that clone the repo from drupal.org.
> 1 votes

---
Tags: 7, version-control
---


title: Is having 150+ user fields too heavy?

text:
# Question
Title: Is having 150+ user fields too heavy?
Our user entities have about 5 fields for the public profile, and 5 fields with settings that determine the content of 60 other fields we need for our implementation (I've thought of making this 60 "computed fields"). The last ones can be overridden by the user, so we need another 60 to store the user entered values (without loosing the defaults) and 30 fields to act as a flag that indicates if the default or custom version is used (30 flags are enough because the 60 fields go in pairs, they are 30 pairs).

Let's say that we attach the 150+ fields to user entities: Wouldn't that be too heavy, especially when viewing the user profile page (where all the other fields are not necessary)?

Should we define a custom field that would integrate a pair of the default values, a pair of the custom values, and the flag, so we would only need 30 of those within a user object? Apart from having to define the custom field, we lose the computed field module, I think.

Should we offload user entities by creating a content type to attach the total 60 + 60 +30 fields, and link the user with the content type using the Relation module?

# Answer
thats right, consider creating a new entity and relate it through a user reference field, for these types of references, the "references module" is better than the "relations module".
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Replace a content type name with a different string, in a view
I have a view that appears as the following table:

```
Title            Content type          Published
------------------------------------------------
title1           content type 1          yes
title2           content type 2          no
title3           content type 3          yes

```

I want to be able to use a custom string instead of the content type name. My view should be like the following:

```
Title            Content type          Published
------------------------------------------------
title1           my content1             yes
title2           contents for all        no
title3           other content           yes

```

I don't know is it's possible to do this with Views. I don't want to change the name of content types, I only want change them in the view.

Is it possible?

# Answer
> 0 votes
Override the template file of you 'Content type' field for your particular view, and code in it.

```
switch($output) {
  case 'content type 1':
    print 'my content1';
    break;

  case 'content type 2':
    print 'contents for all';
    break;

  // ...
}

```

---
Tags: views, entities
---


# Question
Title: Check if the page is a node using arguments in D7
In Drupal 6, to check if current page is a node, we use the following snippet:

```
if (arg(0)=='node' && is_numeric(arg(1))) { /* Do stuff. */ }

```

Since this is a frequently used statement, I wonder if there's a shorter way to do this in Drupal 7, such as something similar to the following:

```
if (is_node()) { /* Do stuff. */ }

```

# Answer
> 15 votes
Actually, there is a function that is available in Drupal 6 too: `menu_get_object()`. With the default values, it will return a node object if the URL for the current page starts with *node/\[node ID\]* (where *\[node ID\]* is the node ID), and `FALSE` in the other cases; the function is particularly useful if, after verifying the current page is a node page, you also need to access the node object associated with the page, and the function that is calling `menu_get_object()` doesn't get a node object between its arguments.

In Drupal 7, there is also another function, but its purpose is just to verify if the current viewed page is the full page view of the node passed as argument: `node_is_page()`.

---
Tags: nodes
---


# Question
Title: A block created with Views is not rendered if the page URL contains "page="
I have an odd problem. I'm using Drupal 7 and an Omega subtheme. Within Views, I have a block defined and it works great - appears where it's supposed to all over the site - except when the URL has a "?page=" in it. Some possibly relevant info: clean\_urls and pathauto enabled, Delta and Layout installed but no Deltas defined.

I discovered this when I created a page View (of a different content-type) that features the pager to scroll through the results. When using the pager it appends "?page=1", "?page=2", etc to the URL. I think it does it by default and from what I've read it seems to be difficult to change this. I could probably put up with the non-clean URLs but the bigger issue now is trying to work out why this results in my first view block not being rendered. I've tested it out by navigating to random pages on the site and appending the "?page=" to the URl and it's always the same result - the block view's not displayed.

Do you have any idea, or any pointer to where I should start looking?

# Answer
I think I worked out what the problem was. The way the View selected the content, there could only be one result (the View is to show the current exhibition for an art gallery website, and they only ever have one exhibition at once). Because by design it could only produce one result I didn't even think about the pager, which was to Full by default.

This caused problems when that block was rendered on the same page as another View - one which deliberately has a pager. Maybe there's an issue with multiple pagers on the same webpage?

Anyway, I changed the block View's pager settings to "Display a specified number of items | 1 item" and that fixed everything - now there's only ever one pager on the webpage and now my block view is displayed on every page as it's supposed to.

Edit: Will click this as accepted answer in 2 days when I'm allowed to
> 1 votes

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


# Question
Title: How does one set up aliases per domain on a multi-domain site?
I have a site where there are several domains each with different content:

```
www.domaina.com
www.domainb.com
www.domainc.com

```

I want to make the alias foobar to different paths on each domain

```
www.domaina.com/foobar => page/100/14
www.domainb.com/foobar => page/136/12
www.domainc.com/foobar => page/96/14

```

I would like to be able to create the aliases using tokens and pathauto in my own module. I've considered Domain Access, but I'm not sure this allows you to create different aliases per domain.

Can someone please confirm what the best approach would be?

**UPDATE:**

It looks like I can use Domain Path and Domain Access, but looking at the source code of Domain Path, I'd have to add entries for each alias:

```
$domain = domain_get_domain();
$domain_id = $domain['domain_id'];
$record = array(
    'domain_id' => $domain_id,
    'source' => "node/$node->nid",
    'alias' => $path,
    'language' => isset($node->language) ? $node->language : LANGUAGE_NONE,
    'entity_type' => 'node',
    'entity_id' => $node->nid,
);
drupal_write_record('domain_path', $record);

```

This is drupal 6 code, so I don't understand why there is an entity\_type and an entity\_id. I'm going to be creating aliases to sources that are views with arguments. Does anyone know how I'd create that record?

# Answer
> 2 votes
Domain Access does allow you to have per-domain auto alias settings (but I have never tried this), but I am only seeing one alias on an edit page.

A less than idea option if you are using Panels is to have a panel page for each path, and then create a selection rule for each domain, and then assign the node that way. This would be a lot more work, though.

---
Tags: 6, path-aliases, domain-access
---


# Question
Title: drupal template files in different folders for different content types
I'm trying to get Drupal to scan multiple directories to find template files for pages and nodes. I have a content type called "contest". I have a node with the path of "http://mysite.com/contest/test I'd like to have a folder structure like:

```
templates
    page
        page.tpl.php
        page-front.tpl.php
    node
        node.tpl.php
    contest
        contest.tpl.php
        contest-test.tpl.php

```

Drupal is not finding contest tpl's.

# Answer
> 1 votes
See http://drupal.org/node/1089656 for more information on the possible file names that Drupal will recognize by default.

Drupal will not recognize `contest.tpl.php` as it is not one of the patterns that it recognizes. If `contest.tpl.php` is an override of node.tpl.php then you should name it `node--contest.tpl.php`

If you want to override a page template in the same manner, see this previous post: https://stackoverflow.com/questions/5194109/drupal-7-candidate-page-tpl-name-for-particular-custom-content-type-entry/5194364#5194364

# Answer
> 0 votes
It is not possible to have a different directory for each template file that is specific for a content type, as Drupal will look for those template files in the same directory where the base template file is.
For example, if the template file is one of the suggested files for node.tpl.php, then both node.tpl.php and the suggested template file must be in the same directory.

---
Tags: theming
---


title: Internet Explorer 7 transparency fix

text:
# Question
Title: Internet Explorer 7 transparency fix
I have a menu that has a transparent background with the following CSS:

```
background-color: transparent;
background-color: rgba(113,157,174,0.7);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd)";

```

In IE, it doesn't have any color; it is just white. I used an Internet Explorer fix, in which I used the following code:

```
filter: alpha(Opacity=45);
background-color: #0010A5;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd)";

```

The only thing this did was to make it purple, but it wasn't transparent at all.

```
![screenshot][1]

```

I know it is possible because I've seen it done before. What am I doing wrong? How do I fix it?

# Answer
I found the answer, it was in fact `filter: alpha(Opacity=45);` inside the IE fix, but apparently it needed to be in the `-inner` of the class, instead of the regular class.
> 1 votes

# Answer
Did you try the PNG Fix module? Maybe it can solve the problem.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Optionally redirect a content to another url?
I'm using drupal 7. I have a content type called News Item. On my home page, I have a block+view that lists the most recent news items. What is shown is the title of the news item, a brief description, and a read more link to the news item. When a person clicks on the read more link, it takes them to a page that displays the entire news item.

I want the ability to specify a redirect on some news items. If a news item has a redirect, whenever a person clicks on the read more link in the home page, they will be redirected to a different url, NOT the url of the actual news item. And if a person types in the url of the actual news item, they will be redirected to the different url instead.

How do I implement this kind of functionality?

# Answer
> 0 votes
I added a field called url\_redirect to the relevant content types. Then in my theme\_process\_html() function of template.php, i added the following code:

```
if(isset($variables['node']->field_url_redirect))
{
  if(is_array($variables['node']->field_url_redirect))
  {
    $temp = current($variables['node']->field_url_redirect);
    if(is_array($temp))
    {
      $temp = current($temp);
      if(is_array($temp))
      {
        $url_redirect = $temp['value'];
        if(preg_match('/^\w[\w\d_-]*\./',$url_redirect))
        {
          $url_redirect = 'http://'.$url_redirect;
        }
        else
        {
          $url_redirect = '/'.$url_redirect;
        }
        if(isset($variables['logged_in']))
        {
          $url_redirect = '/redirect?node='.$variables['node']->nid.'&rurl='.urlencode($url_redirect);
          if(isset($variables['node']->current_version_id))
          $url_redirect .= '&v='.$variables['node']->current_version_id;
        }
        header('Location: '.$url_redirect);
        exit;
      }
    }
  }
}

```

# Answer
> 1 votes
I think you could handle this in a views row level template file.

First set up a field for the redirect which is optional. Then add it to your view. Create the appropriate views row template file. In your template file print out the fields individually adding a bit of logic around the read more link:

```
<?php if ($fields['news_url']): ?>
  <?php print $fields['news_url']; ?>
<?php else: ?>
  <?php print $fields['readmore']; ?>
<?php endif; ?>

```

Obviously the field names are wrong but hopefully this gives you the idea.

---
Tags: 7, redirection
---


# Question
Title: How to make a numeric textField in Drupal WebForm?
Can anyone suggest how to make a *numeric only* textfield in WebForm for a mobile number field?

# Answer
> 1 votes
You can use the Webform validation module to create such validation.

# Answer
> 0 votes
The following features of the Webform Validation module will help you

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

---
Tags: 7, webforms
---


# Question
Title: Making it so registered users can't add/edit taxonomy terms to nodes
Is there a way to add a permission so only admins can add/edit taxonomy terms on nodes? I tried http://drupal.org/project/taxonomy\_access but I don't really want full module and while rebuilding my content permissions I got an error so that module might not even work.

# Answer
Found a module that does this: Taxonomy Role
> 1 votes

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


# Question
Title: How to extend or "hook" Drupal Form AJAX?
I'm working with standard admin form, which has `'add_more'` button for one of fields.
My task is to move some fields to jQuery UI Dialog just for usability. When dialog was closed I manually append it's content to form so It sends normally.
The problem appears when some core ajax is sending while some form parts are in the dialog (i.e. outside of `form` tag because jQuery UI Dialog appears in the bottom of `body`). The `'add_more'` button as example. When I click on it, the form serializes for AJAX without some inputs in the dialog.
Оh..
The jQuery Form Plugin (which used by Drupal) has option `beforeSerialize`. I think it can help me but I don't know how I can extend Drupal.ajax.options to set something custom.

If you can recommend other ways to solve my problem or give some links to documentation about Drupal JavaScript, I will be very happy :)

Thanks.

# Answer
Thank you, **@yvan**, for answer. Links you added are good.
But there are better documentation in source code comments. If you want to understand how it works you should look through files `includes/ajax.inc` and `misc/ajax.js`.
My problem was solved like this:

```
(function($) {
Drupal.behaviors.MyModule = {
    attach: function (context, settings) {

        // Overwrite beforeSubmit
        Drupal.ajax['some_element'].options.beforeSubmit = function (form_values, element, options) {
            // ... Some staff added to form_values
            // return false; // to prevent AJAX call if needed.
        }
        //Or you can overwrite beforeSubmit
        Drupal.ajax['some_element'].options.beforeSerialize = function (element, options) {

            // ... Some staff added to options.data
            // Also call parent function
            Drupal.ajax.prototype.beforeSerialize(element, options);
        }

                    //...

```

These functions are calling in jQuery Form Plugin.
> 9 votes

# Answer
It's a little bit sad, but the JavaScript Documentation for Drupal 7 is really poor but still better than Drupal 6 :)

Well, I understand your problem and I haven't found a solution, I just can send you to some interesting pages that can help you.

First, about Ajax Forms in Drupal 7 who send you also to Ajax Framework and finally look into Example Ajax Module, maybe you'll find something that can help you.
> 0 votes

---
Tags: 7, forms, javascript, ajax
---


title: Implement hook_block_configure on theme

text:
# Question
Title: Implement hook_block_configure on theme
Is it possible to implement a hook\_block\_configure inside a theme? I would like to have a configuration that is related to my theme in each block but don't want to implement this in a module because I'd generate a dependency from the theme to the module.

# Answer
> 0 votes
Unfortunately no, I must use a module for that, only because of module\_invoke use to call the hook.

Also, I was thinking that you could just add your functions on template.php, but this file is only included in the theme function, that doesn't allow you add some stuff, expect throw theme override.

---
Tags: 7, theming
---


# Question
Title: Is there anyway to get the $form_state inside a hook_block_configure?
Is there any way to get the `$form_state` inside a `hook_block_configure()`? I'm trying to do that to make `#ajax` work on `hook_block_configure()`.

# Answer
You don't have this information, but you can access to it with hook\_form\_alter. But to access to this form (that call block\_configure) you have two form\_id block\_admin\_configure and block\_add\_block\_form.
> 2 votes

---
Tags: 7, forms, blocks
---


# Question
Title: How does contextual menus work in Drupal 7?
I've been trying to understand this for a while now, but I find the documentation either to lacking, or maybe I just don't understand what I'm looking for. Could anyone enlighten me on how to implement them?

One thing I'm trying to do is to be able to have `contextual menus` for each node in a list of nodes (loaded using `node_load_multiple`) that I'm sending along to a `theme()` function and looping through inside the `.tpl.php`

# Answer
I'll put my temporary solution here for now anyway in case it will help someone.

What I did was just creating a new theme function (?) in my module

```
$themes['contextual'] = array(
    'template' => 'contextual',
    'variables' => array('links' => array(), 'destination' => null)
);

```

Then I defined my `contextual.tpl.php`

```
<div class="contextual-links-wrapper">
    <ul class="contextual-links">
        <?php foreach($links as $url => $title): ?>
        <li>
            <?php echo l($title, $url,
                array('query' => array('destination' => $destination))) ?>
        </li>
        <?php endforeach; ?>
    </ul>
</div>

```

Finally, to use it, wherever there is a need for a contextual menu, add the class `contextual-links-region` to the container div of the node (or whatever), and inside the div I use my function, for example:

```
<?php echo theme('contextual', array('destination' => 'node/'.arg(1),
    'links' => array('node/'.$somenode->nid.'/edit', t('Edit node')))); ?>

```
> 3 votes

---
Tags: 7
---


# Question
Title: Drupal 6 to Pressflow migration: MyISAM to InnoDB?
I will soon be migrating from Drupal 6 to Pressflow. As Pressflow encourages InnoDB for certain tables, how can I promote these recommendations when migrating an existing site?

Is this something which update.php handles?

In addition, as my Drupal site is not the latest Drupal core version, should I update to latest core first, and then sideways to the corresponding Pressflow version, or can I go straight from 6.19 to Pressflow 6.22?

# Answer
You should be fine going from Drupal 6.19 to Pressflow 6.22 but make sure you backup files and database just in case.
As for converting the tables your best doing that either through mysql cli, or phpmyadmin.

I would treat these as two separate jobs: First, migrate to Pressflow and confirm the site is working; then, secondly, start moving tables.
> 3 votes

# Answer
For converting from MyISAM to InnoDB, there are a few different methods.

You can use the DB Tuner module to do this straight from Drupal.

You can also take a backup (say with Backup and Migrate), change all of the `CREATE` statements, and then do a restore.

If you poke around on the main SO site, there are some methods to do this with the mysql CLI tool.

As for Pressflow, you should be able to copy your `sites/` directory into a Pressflow install, run the `update.php` script, and have everything turn out OK.

Personally, I would migrate to InnoDB, update to Drupal 6.22, and then migrate to Pressflow, but I am not sure how critical this is.
> 1 votes

---
Tags: 6
---


# Question
Title: option to promote to top of list in drupal
I have a site that shows top music in a list, I have created a content type called "topMusic" and a view that will show all topMusic content types.

this View shows topMusic content in a row, first content created will get on top of the list, anything added after that will show below it.

I want to add a new button or trigger to the content type, that when its "on", this content gets on the top of the list.

Any idea's will be greatly appreciated.

# Answer
By default, you will find a checkbox on every node-edit form called "Sticky at top of lists". It's under the "Publishing options". If you use that to identify the top content, you can add a sort criterion "Node: Sticky" (descending) to your view to make the selected nodes appear on top.

If you need even more control (ie. you want to specify the exact order) use a module like Draggable Views or Nodequeue.
> 11 votes

# Answer
Not too sure what you mean, but You can use view's built-in filter system to change the order of the display. The default is creation time hence you got "first content created will get on top of the list, anything added after that will show below it."
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Views 2 filter: field x = current user's ID
So I have a view and a filter with field x. I want this field x to be equal to the user ID of the current user.

When adding the filter I'm asked to insert a value, if I insert the value by hand, e.g. 1, the right content is displayed for that user. However, I wanna automate this system for the rest of the users.

I tried things like %uid in the value box but this doesn't seem to work.

any ideas?

I'm using Drupal 6 and Views 2.

# Answer
> 1 votes
There is a filter called `User: Current` which will "Filter the view to the currently logged in user."

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


# Question
Title: Advertisement view sorted by Nodequeue relationship
I have a Advertisement type of View listing Ads by taxonomy but I need to order them by Nodequeue and I don't see it available in the Relationships area. Is there a hack for this anywhere?

thanks

# Answer
I figured it out. You need to tell the view to have a relation from Advertisement to Node (Ad: Aid). Do this by going to Relationships and adding a relationship based upon "Ad: Aid". You'll then see under Fields all of the Node fields such as Title and Body available. Then add another relationship "(Node) Nodequeue: Queue".
> 1 votes

---
Tags: views
---


# Question
Title: Best module where you create a block and select a node from drop-down to render?
It's been a short while since I played with Drupal 6 and now I'm getting my feet wet in Drupal 7.7.

I need to be able to create a simple block and in that block 'configure' area I want to be able to simply choose a node in the system from a drop-down list. When that block renders on XXXX page, it will then render the teaser for that node along with any other variables set.

I thought I could do this with Views 3.x by just creating a block view which only renders one result and takes a node title as an argument. The new Views 3.x interface has me a little confused though. Not quite sure how to set it so the node title argument is configured in the block admin area and that argument is then always passed with the block view renders.

I guess what I sort of was looking for was an exposed filter in the block admin edit page where the value is saved but that doesn't seem possible. Anyone have any module suggestions?

# Answer
> 0 votes
The Nodes In Block module seems to give you the desired outcome - albeit a different workflow to what you described. Here is an excerpt about it from the module's project page:

> ... makes it possible to add nodes into a block. A number of configurable blocks are generated which you can assign to a region. Visibility settings of this block are automatically set to 'Show on only the listed pages'. On the node content form, you define the weight and visibility per node thus making it easier for content administration as all your content is now in the same place. With this module, you don't have to explain your customers how blocks work but is still able to decide on which pages content must be rendered.

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


# Question
Title: Rules: Steps to trigger a rule when a field is updated
I am using the rules module to send an email when a particular CCK field `field_test` is changed. These are the steps I performed:

```
Event: After updating existing content
Condition: Field has changed

```

Under Field I chose `field_test`. Under DO I chose the action as email.

My issue is that even if any other field is updated under that content type, it still triggers my rule, under debugging it shows Condition `Updated content's field 'field_test' has been changed` evaluated to TRUE.

I'd appreciate any help on this.

Thanks.

# Answer
I figured what my issue was. I had an earlier version of the CCK module (6.x-2.1) and once upgraded to the latest version (6.x-2.9) the rule behaves as expected.

Thanks to jordojuice for pointing me in the right direction.
> 1 votes

---
Tags: 6, rules
---


# Question
Title: Is it okay to use drupal_goto() from within a node?
I implemented a node that automatically adds a product to a cart using this function `uc_cart_add_item(33);`

but I want it to then redirect the visitor to the check out page. I saw that drupal has a drupal\_goto() function however this is essentially just a php Header(location: http://mysite.com/cart/checkout) which usually shouldn't work if it is not done so before any content is spit out.

Now I got this to work and everything but I never liked the idea of just getting it to work, I'd like to get it right. I thought of a script outside of the drupal environment but wasnt sure if I could use the ubercarts functions. Does anyone have any ideas on a better way or is the using drupal\_goto() within a node okay?

Just to say and I saw someone else who had a similar problem was that this did work, however the cron job time exceeded the time limit after I implemented this. SO maybe not a good option like i thought.

# Answer
> 3 votes
It is a bad idea and I wouldn't recommend doing it. The cron error you see is most likely due to the Search module. During cron while the Search module is trying to index content, if it reaches a node containing a `drupal_goto()` it will hang and cron will error which could lead to more problems

# Answer
> 2 votes
It's a bad idea to use it in the nodeapi. Drupal uses the decorator pattern in this API and interrupting that with a redirect won't give the other modules a chance to operate on the node.

Assuming you're submitting a form: The form API (which also uses the same pattern) will let you redirect with $form\['#redirect'\]. But be sure to use the global $base\_url in your path. It's a caveat in the form API.

Something like:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $base_url;
  $form['#redirect'] = $base_url .'/path';
}

```

You'd probably want to avoid hard coding the path but that should point you in the right direction...

# Answer
> 2 votes
This is what I used when we really needed `drupal_goto()` without creating modules to do it (D6)

```
//normally script name is index.php, but is cron.php if it's loaded via cron
//do not execute the drupal_goto if script name is cron.php,
// or if the node is loaded for anything other than being viewed

$script_name= str_replace(base_path(), '', $_SERVER['SCRIPT_NAME']);

$arg0 = arg(0);
$arg2 = arg(2);

if($script_name != 'cron.php'
   && $_SERVER['REQUEST_URI'] != '/admin/reports/status/run-cron'
   && $_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR']
   && !($arg0 == 'node' && !empty($arg2)))
{
  drupal_goto('node/123');
}

?>

```

# Answer
> 1 votes
Assuming that *within a node* means *when viewing a node page*, it is possible to safely call `drupal_goto()`. In a `hook_nodeapi()` when `$op == 'view'` (Drupal 6) or `hook_node_view()` (Drupal 7) implementation, you should take care to call `drupal_goto()` only if the node is actually viewed as a full page. This will prevent other modules' hooks to run, but as they should only add content to display to `$node->content`, this shouldn't be an issue.

In Drupal 6, something like

```
function MODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'view' && $a3 === FALSE && $a4 == TRUE) {
    $page_node = menu_get_object();
    if (!empty($page_node) && $page_node->nid == $node->nid) {
      //It is safe to call drupal_goto() from here
    }
  }
}

```

In Drupal 7, something like

```
function MODULE_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    //It is safe to call drupal_goto() from here
  }
}

```

It is unsafe to call `drupal_goto()` for all the other values of `$op` or from other `hook_node_*` implementations. `drupal_goto()` will end the request processing and prevent hooks from other module to run.

---
Tags: nodes
---


# Question
Title: Using a custom view for a taxonomy term page
Using Drupal 7 and Views 7.x-3.0-beta3, what is the best way to have a taxonomy page use a custom view?

For example, in Path Auto I have a rule that points the URL alias countries/england towards taxonomy/term/44.

When a user visits countries/england I want to display a page created with Views, not the default taxonomy page.

I am populating the menu using Taxonomy Menu which doesn't yet support custom paths in Drupal 7.

# Answer
Maybe I am misunderstanding what you are saying, but Views comes with a view for taxonomy/term/%tid. Once enabled, when you visit http://example.com/taxonomy/term/44, Views will show its own page, and not the default page output from Drupal.
> 6 votes

# Answer
There are two modules that can pull this off for you. Either tvi or taxonomy display. Both are quite buggy in Drupal 7 at the moment so it will take some tweaking to get them working properly.

I have a site using your setup with tvi but I had to manually enter the values into the tvi table to get it working and could not use taxonomy/term/% for the path of the views. I had to use pathalias\_i\_set\_for\_the\_term/%. I tried out taxonomy display as it is in alpha but it had some errors with my setup and tvi was already hacked and working for me. I would suggest trying out taxonomy display first as it appears like it will be the better option moving forward.
> 4 votes

# Answer
As kiamlaluno said, I think that you can do this out-of-the-box in views 7.x-3.0-beta3: you can add taxonomy name/id to "Filter Criteria" or "Contextual filter" to a basic new unformated view, then you can add a path to that display/view.
> 0 votes

# Answer
Try this module: Taxonomy Views Integrator It allows you to theme every vocabulary or term with it's own view. Worked wonders for me. Also see this page: http://drupal.org/node/424168
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to update the blocks db-table correctly
I wrote a module that comes with a default\_view (a block view). The corresponding block is not automatically listed inside the blocks db-table, even after a cache clearing, but it is shown after I visit `admin/build/block`. My problem is that I have a `hook_update_N()`, which is going to update the blocks table (the configuration of this specific block); if it's not there, it can't be updated.

When I use \_block\_rehash('MYTHEME') the table is updated, not only for MYTHEME (ZEN-subtheme) but also for the Minelli theme. Is there another way of "updating" the blocks-table? What exactly is going on, when `admin/build/block` is visited?

**Edit**: I just noticed that Pro Drupal Devel (2. Ed.) states, at page 218, to use a `Insert INTO` query and do it "by hand." I think thats what I'm going to do now.

# Answer
Use `INSERT INTO`. I've spent hours and hours using block\_rehash and variants to no effect.
> 1 votes

---
Tags: 6, blocks, updating
---


# Question
Title: If I use node_save() to create a new node, do I need to manually escape user input?
I am writing a custom module for Drupal 6 that programmatically creates a node using node\_save().

The various custom node fields come from user input - is it necessary to manually escape these fields, or will node\_save() take care of that for me?

# Answer
If by escaping you mean using `check_plain()` or similar functions, then no; escaping is done when outputting something, not when saving it in the database, or in Drupal persistent variables.

Imagine what would happen if you call `check_plain()` on a node containing "&"; that character would be escaped to "`&`" that it would be converted in `&amp;` when Drupal would show the node content. The result is that "&" would be shown as "&" and that is not what it would be expected.

In Writing secure code, you can read the following text:

> Use check functions on output to prevent cross site scripting attacks
>
> No piece of user-submitted content should ever be placed as-is into HTML.
>
> * Use `check_plain()` or `theme('placeholder')` for plain text.
> * Use `check_markup()` or `filter_xss()` for markup containing text.
> * Use the `t()` function with "@" or "%" placeholders to construct safe, translatable strings.
>
> See how to handle text in a secure fashion for more details.

As you see, the page about writing secure code doesn't say to escape the text being saved, but only text being output, when the text has been entered from users, in a way or in another. An example of text entered from a user is the username or the signature associated to user accounts, the node title, or the node body.

About SQL injection, you just need to use placeholders in you queries; Drupal database functions escapes the content of the placeholders, which would not be possible if you write a query like the following one, for example:

```
$query = db_query("SELECT * FROM {node} WHERE title = '$title'");

```

The "Writing secure code" reports:

> Use the database layer correctly. For example, never concatenate data directly into SQL queries, like this:
>
> ```
> <?php
>  db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);
> ?>
>
> ```
>
> Instead, use proper argument substitution with db\_query:
>
> ```
> <?php
>  db_query("SELECT foo FROM {table} t WHERE t.name = '%s' ", $_GET['user']);
> ?>
>
> ```
>
> If you have to accommodate a variable number of arguments in your SQL, create an array of placeholders. Don't do this:
>
> ```
> <?php
>  db_query("SELECT t.s FROM {table} t WHERE t.field IN (%s)", $from_user);
> ?>
>
> ```
>
> Instead, do this:
>
> ```
> <?php
>  $placeholders = implode(',', array_fill(0, count($from_user), "%d"));
>  db_query("SELECT t.s FROM {table} t WHERE t.field IN ($placeholders)", $from_user);
> ?>
>
> ```
> 5 votes

# Answer
I quickly glanced through node\_save and there is no escaping done on the $node object before drupal\_write\_record, drupal\_write\_record does no escaping either so even if I've overlooked something your best bet is to escape. Better safe than sorry!
> 0 votes

---
Tags: 6, security
---


title: How to build a field list in a node?

text:
# Question
Title: How to build a field list in a node?
I have two content types: 'artist' and 'venue'.

When an artist node is viewed, it needs to display a list of venues and dates. Venue name will link to the venue node eg:

```
Artist
--------------------
Venue1 | 1-Jan 20:00
Venue2 | 2-Jan 17:00
Venue3 | 4-Jan 20:00

```

The possible solutions are:

1. Create a 'performance' content type that links (using the References module) to artist and venue, and has a date field. Then attach the list using Views. This seems like a lot of extra work for the editor.
2. Add two unlimited value fields to artist node: reference to venue and date field. It is difficult to keep them in sync and clunky.
3. Would this be a good use of the entity API? I don't know enough about entities yet, but have a feeling that would be overkill for something so simple?

# Answer
Are you looking for Field Collection?
You can create collection with Node Reference field and Date field. Then Field Collection Table will help you with outputting. This exactly works with Entity API.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How to determine if request will result in a successful HTTP request?
Two part question here.

What is the proper way in a module to determine if a page request is resulting in a HTTP 200 OK? Looking through `static $stored_headers` for a 30x/40x/50x seems wrong.

What is the earliest hook that you can reliably do this from?

# Answer
When I was developing the code for Nodewords, I used the following code, to verify if Drupal was serving an error page:

```
  $headers = drupal_get_headers();

  if (preg_match('@HTTP/1\.[01]\x20+403@', $headers)) {
    return array('type' => NODEWORDS_TYPE_ERRORPAGE, 'id' => 403);
  }

  if (preg_match('@HTTP/1\.[01]\x20+404@', $headers)) {
    return array('type' => NODEWORDS_TYPE_ERRORPAGE, 'id' => 404);
  }

```

The function containing that code is called from `nodewords_preprocess_page()`, the implementation of `hook_preprocess_page()`.
> 1 votes

---
Tags: 6, hooks
---


# Question
Title: What theme function outputs the administrative overlay in D7?
What theming function generates the output for the admin overlay in d7?

# Answer
> 3 votes
To output the overlay, Drupal uses a template file, overlay.tpl.php. To use that template file, the Overlay module implements hook\_page\_alter(), which contains the following code:

```
  $mode = overlay_get_mode();
  if ($mode == 'child') {
    // Add the overlay wrapper before the html wrapper.
    array_unshift($page['#theme_wrappers'], 'overlay');
  }

```

The Overlay module has also a preprocess function for that template file: template\_preprocess\_overlay().

---
Tags: 7, theming
---