# Question
Title: Views search to find users based on terms
I want to have search inputs for users to search and find other users based on associated terms(I'm using term reference) of their user profile. I'm using Search-API, Views-3, and Profile-2. I created fields on the profile that have terms as check boxes. But, I can't seem to figure out how to make a view with search inputs to find/search users by these terms.

~Then, this is probably a question for a different post. But, could I filter the RESULTS to display only certain aspects of that users profile? I would want the results to render a custom user-teaserprofile.tpl.php or something like that. Thank you.

...the whole approach is somewhat related to a dating search or something like that.

# Answer
> 1 votes
With search API you create an index containing all the info that should be searchable. The easiest thing would probably be to create an index based on the Profile entity and add the reference to the User entity and add the fields you need, like the term reference.

If you only want to let users search on the term reference, you might want to exclude normal search altogether and use facets instead, that would allow users to select terms and get the users displayed. Alternatively you could just use Views alone since Search API in not needed if you don't do fuldtext search.

With or without Search API you can in Views select the fields you want to display, just like any view, and use the template options Views provide to customize the output of the search page.

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


title: Problem with Drupal Beauty tips module

text:
# Question
Title: Problem with Drupal Beauty tips module
I am using Beauty tips module to show AJAX content on hover, But When first time it loads I am getting unexpected look. From second time onward I get correct look.

I have attached an image of the problem.

The code that I am using for this is :

```
$options['bt_drupal_help_page'.$nodeid[$i]] = array(
  'cssSelect' => '#rating_'.$nodeid[$i],
  'ajaxPath' => $base_url.'/average_rating',
  'ajaxData' => array('rating'=>$nodeid[$i]),
 //'ajaxLoading' => '<blink>Wait Until It Loads...</blink>',
  'ajaxType' => 'GET',
  'width' => 'auto',
  'height' => '1000px',
  'ajaxCache' => false,
  //'windowMargin' => 5,
   'cornerRadius' => 15,
  //'cssClass' => 'tooltip-box',
 //'cssStyles' => "padding: 2px",
 //'overlay' => true,
 'shrinkToFit' => false,
 'killTitle' => true,
 //'hoverIntentOpts' => '{interval:300,timeout:500}',
);

beautytips_add_beautytips($options);

```

Please let me know, whether I am doing something wrong?

Thanks in advance for the help.

# Answer
It doesn't look like a problem with beautytips module, but instead a lack of styling that's causing the problem. You should be able to fix this with normal CSS.
> 2 votes

---
Tags: forms
---


# Question
Title: How do I print out a specific node to my page?
I'd just like to print out the body of a specific node (no title or other fields). Am I doing this right?

```
echo node_load(127)->body['und'][0]['value']

```

I can't seem to find the answer in any of the Drupal docs.

# Answer
> 5 votes
Looking with the Devel module to the structure of a loaded node, I notice that "body" contains the following values:

The first array index is the language ID for the language set for the node; it could be also LANGUAGE\_NONE (the string "und") for nodes for which the language is set to "neutral." That array index contains an array with the following indexes:

* "value": the content of the "body" field
* "summary": what set as summary (or teaser) for the node
* "format": the input format associated with the "body" field

In the node I used as example, if you try accessing `$node->body['und'][0]['value']`, you would access an undefined value. You should use `$node->language` to know the language set for the node; you code should be similar to the following one:

```
$node = node_load(127);
$body = $node->body[$node->language][0]['value'];

```

As for printing the body content, the "body" field contains the text before the input filter is applied; you should use code similar to the following one, to print the "body" field:

```
$node = node_load(127);
$language = $node->language;
print check_markup($node->body[$language][0]['value'], $node->body[$language][0]['format'], $language);

```

# Answer
> 4 votes
```
$node = node_load(127);
print $node->body;

```

Please, note, this outputs just the content of the Body textarea as input in the node form.

To output the fully themed node without title and links would require a separate template file, its introduction via a preprocess function, and a call to

```
print theme('node', $node);

```

---
Tags: 7, nodes
---


# Question
Title: Adding metadata to nodes for SOLR search
We have a website using SOLR search and we've run across an issue. For example, we have a page called "Organizational Chart" but if someone searches for "org chart" it will not appear in search results.

Is there a way to add aliases or metadata to nodes so that we can add "might be searched by" data or extra information that may enhance search visibility?

Would simply adding a cck field accomplish something like this? Taxonomy doesn't really apply because these are not categories and would be different across each node.

# Answer
Apache Solr supports synonyms, and you can add them to the solr/conf/synonyms.txt file. The path is relative to where you copied the "example" directory to. This way people searching for "org chart" would find documents containing "Organization Chart" and any other synonyms you wish to add without any modifications to Drupal.
> 1 votes

# Answer
If it's a one-time problem, could you give it a path alias of "org-chart" and have Solr Search include the path in its search fields? I just tried exactly that and my test "Organization Chart" page popped to the top of the results for "org chart."
> 0 votes

---
Tags: search, meta-tags
---


# Question
Title: Can a title of a node not be associated with a url?
I want to create a node with multiple urls. I don't want the title of the main node to be a url. Right now the main node is being pulled up in a list view through taxonomy. When I create multiple nodes for the main node, it shows up multiple times in the taxonomy list as the same item.

I want the main node to show up once in the list with all the "sub-nodes" clickable in the main node's summary view. Hope this makes sense.

# Answer
> When I create multiple nodes for the main node

What exactly are you trying to accomplish here? How do you create multiple nodes of the "main" node, how are they related to each other?

CCK has a node reference field, you should use that to make the relationships explicit and go from there.
> 1 votes

# Answer
What about creating 2 different content types, one "main" for your main node and another for your "link" node.
Then you make CCK node reference between them and in the views you just display "main" nodes.
> 1 votes

---
Tags: nodes, uri
---


# Question
Title: xml feed parser from multiple sources, multiple url-source xml importers
I can't seem to find a good module that does what my title says. Xpath XML Parser is limited to a single source isn't it?

I needed to be able to import xml feeds from different URLs towards the same target (e.g. mapped to a specific content type). Say, my website will publish contents from different client's websites using an xml specification defined by me. My website then will get all contents by importing all those xml sources towards the same content type so my site will list all contents from different 'sources' effectively. Say real estate listings coming from different real estate agencies/agents...

Has anyone done this before?

# Answer
To me this seems like an exact use case for Feeds plus Feeds XPath Parser. It will be possible to map your custom XML spec to various fields and import content from as many sources as you want into nodes of the same content type. I posted an answer to another question which may give guidance on how to use it.

**Feeds:**

> * Import or aggregate data as nodes, users, taxonomy terms or simple database records.
> * One-off imports and periodic aggregation of content
> * Import or aggregate RSS/Atom feeds
> * Import or aggregate CSV files
> * Import or aggregate OPML files
> * PubSubHubbub support
> * Create nodes, users, taxonomy terms or simple database records from import
> * Extensible to import any other kind of content
> * Granular mapping of input elements to Drupal content elements
> * Exportable configurations
> * Batched import for large files

**Feeds XPath Parser:**

> Feeds XPath Parser is a Feeds plugin for parsing XML and HTML documents. It enables site builders to leverage the power of Feeds to easily import data from complex, external data sources. Each element you wish to extract is setup using configurable mapping queries, saving time for developers who would otherwise have to code complex, specific-use modules. It also enables end-users to build web scrapers and other useful tools within Drupal.
> 1 votes

---
Tags: importing-exporting, feeds
---


# Question
Title: PHP contextual filter code in drupal 7 'no query was run'
I am using the contextual filter code in views to filter more options for the view, using this snippet:

```
$uid= $GLOBALS['user']->uid;

$result = db_query('SELECT users_node__field_data_field_agencyname.field_agencyname_nid as agencyid
FROM {field_data_field_agencyname} users_node__field_data_field_agencyname
WHERE users_node__field_data_field_agencyname.entity_id=:uid AND users_node__field_data_field_agencyname.deleted=0 AND users_node__field_data_field_agencyname.entity_type=:user',array(':uid'=>$uid,':user'=>'user'));

return $result->agencyid;

```

but no query is run shows up on the sql pane ?

How come?

# Answer
I would suspect that no query is run because your code snippet isn't returning anything. The thing that jumps out to me is that you are trying to use $result as the first row returned by the query, however it is actually the entire result set. For example, retrieving data from a DB usually look similar to the code below:

```
$result = db_query($sql);

// Iterate over the collection ($result).
foreach ($result as $record) {
  $agency_id = $record->agencyid;
}

```

In the example you posted above, you could use the following code snippet to pull a single field from the first row in the result set:

```
// This would return the agency ID.
return db_query($sql)->fetchField();

```

Take a look at the documentation of fetchField() for more information on how it is used.
> 1 votes

---
Tags: views
---


title: Synchronize with the correct time

text:
# Question
Title: Synchronize with the correct time
This may not be Drupal specific, but does Drupal have a module that can fetch the correct world time from any remote time server, which can help me in keeping the time shown in my Drupal site correct?

I don't want to use my system time which may be inaccurate.

# Answer
> 2 votes
Time is a server job, so you should ensure your system time is correct rather than try to solve this with Drupal.
I'd recommend you to set up a NTP (Network Time Protocol) client on your server and have it synchronizes with a NTP server.
Here is the documentation for Ubuntu: Time Synchronisation with NTP.

PS: I think this question is off topic too ;)

# Answer
> 3 votes
If you are on shared hosting your hosting company should be responsible for keeping the time correct. If that's not happening contact them and ask why. If you are on VPS or your own private server you can set up a NTP client as tostinni recommended.

---
Tags: 7
---


title: Include image in RSS feed Views display

text:
# Question
Title: Include image in RSS feed Views display
I'm creating an RSS feed of a basic Blog using Views. This is being picked up by Facebook's Graffitti module. Everything works fine here, except that the image isn't being added to the RSS feed... I've incuded a screenshot of my views settings... I'm using a Style of RSS Feed and Row Style: Node (this is the only type allowed).

How can I get a link to the image into feed?!

screenshot

# Answer
> 1 votes
If the image is a CCK field, make sure the correct formatter has been selected for the image field and it has not been excluded from the RSS display at `admin/content/node-type/YOUR-TYPE/display/rss`.

If it's an attached image, check that it is displayed as part of teaser (or full body) and that *Feed content* is set to teaser (or Full text) at `admin/content/rss-publishing`.

---
Tags: views, feeds
---


# Question
Title: Can invite module work for existing users?
I'm using UR and invite module. I'm trying to make it so you can "friend" "existing" users. I don't know why Invite is only set for e-mail address invites for just non-users. I want A FB style "friend" request. Is there a way to fanangle this though these modules? Or, do I have to go in another direction with it?

# Answer
The Invite module serves to invite those who are not yet existing users to become ones. That's why you cannot use it to invite existing users.

Anyway, when using UR, at existing user's public profile, there's a *Become USERNAME's friend* link which you can use to befriend an existing user. This is an equivalent of the Facebook *Add Friend* button.

With the UR's `user_relationship_invites` module enabled, you can give users the option of specifying a relationship when inviting new users, e.g. friend. Together with the Contact Importer this would be an equivalent of the Facebook *Find friends* page.
> 0 votes

---
Tags: 7, users
---


# Question
Title: What is the syntax for l.d.o translations in a drush make file
I have read the Drush Make documentation, and understand you can download translations at the time you use the drush make command, since there is an option. What I don't understand clearly is how to add a translation from localize.drupal.org to your .make file. Any help and/or an example would be amazing. Thanks.

Drush Make documentation: http://drupalcode.org/project/drush\_make.git/blob\_plain/refs/heads/6.x-2.x:/README.txt

# Answer
> 5 votes
The post beta9 dev version of drush\_make also supports downloading drupal core translations with, for example:

```
projects[] = nl

```

Source: http://drupal.org/node/644916. (There's also a documentation patch there.)

---
Tags: i18n-l10n, drush
---


title: Load nodes partially?

text:
# Question
Title: Load nodes partially?
Is there a way to partially load nodes based on the view mode? Say I've got a lot of fields, but for the list view I need only 3 of them ... node\_load fetches them all, which doesn't make sense. Or does it? I think about using computed\_fields, but when it comes to larger lists I'm a little concerned about performance.

# Answer
Check out field\_get\_items(), or to go a bit more advanced (and more 'meta'), use EntityFieldQuery (see examples here).

But, if you're doing this outside of a loop or something, it's often easiest to do a full node\_load(), as you can just grab more fields out of there when you need to (in the future) without having to add a bit more code.

My rule of thumb is this: if I only need to load one or two nodes for a particular operation, and the node doesn't contain more than 10-15 fields, I'll just do node\_load(). Much more convenient when you don't need to worry about the extra 50ms or so... (for smaller node objects, of course. It's different if you have a node with 25 fields attached!).

\[Edit: Just realized field\_get\_items() still requires the node object itself... which defeats the purpose.\]
> 1 votes

# Answer
Do you think you could make use of `node_reference` and split your node type into multiple linked "sub-types"? That would make it possible to simply `node_load()` those parts that you need to work with at any point.
> 0 votes

---
Tags: entities
---


# Question
Title: How to submit webform programmatically with Ajax?
I'm working on an Ajax implementation for the Webform submit on Drupal 7. I was not able to find any good `hook` to alter the Webform submit button and add '#ajax' in the form so i had a look to a Drupal 6 module that implements this functionality from an external script.

So i decided to go with my own module and JavaScript code to fire an Ajax post request to a custom menu callback I have defined in `hook_menu()`, in Drupal 7.

The JavaScript part works fine but I'm having issues trying to submit the Webform programmatically.

Here is my JavaScript code:

```
function formSubmit(event, formId) {

  event.preventDefault();

  var form = jQuery("#" + formId);
  var postData = form.serialize();
  var nodeId = formId.substring(20);
  var msg = '';

  msg += form.find('#edit-submitted-name').attr('value') ? '' : 'Please enter your name';
  console.log(form.find('#edit-submitted-name').attr('value'));
  console.log(form.find('#edit-submitted-e-mail').attr('value'));

  if(msg) {
    alert(msg);
  } else {
    jQuery.ajax({
      url: Drupal.settings.basePath + 'webform_ajax/' + nodeId,
      fid:formId,
      type: 'POST',
      data: postData,
      success: function(ajaxData) {
        console.log(ajaxData);
        console.log('Hello world');
        // can't get here
      }
    });
  }
}

```

And my module code (based on webform\_ajax module):

```
function custom_menu() {
  $items = array();
  $items['webform_ajax/%'] = array(
    'page callback' => '_custom_webform_ajax',
    'page arguments' => array(1,2),
    'access callback' => '_custom_webform_ajax_access',
  );
  return $items;
}

function _custom_webform_ajax($nid, $data) {
  //$sid = $_POST['details']['sid'];

  $local_POST = $_POST;
  $form_build_id = $_POST['form_build_id'];

  $form_id = 'webform_client_form_' . $nid;

  $node = node_load($nid);

  $submission = array();
  $form_state = array();

  $form = form_get_cache($form_build_id, $form_state);
  $form_array = drupal_rebuild_form($form_id, $form_state, array($form_state, $node, $submission), $form_build_id);
  $form_state['clicked_button'] = $form_array['actions']['submit'];

  if (is_array($local_POST['submitted'])) {
    foreach ($local_POST['submitted'] as $submit_index => $submit) {
      $form_state['storage']['submitted'][$submit_index] = $submit;
      $form_state['values']['submitted'][$submit_index] = $submit;
    }
  }

  // Clearing empty values from $form_state
  if (is_array($form_state['values']['submitted'])) {
    foreach ($form_state['values']['submitted'] as $value_index => $value) {
      if (!$value) {
        unset($form_state['values']['submitted'][$value_index]);
      }
    }
  }

  // Executing the pressed button action
  drupal_execute($form_id, $form_state, $node, array());

  // Get the HTML for the error messages
  $error_html = theme('status_messages', 'error');

  // Building the resulting form after the processing of the button
  $form_array = drupal_rebuild_form($form_id, $form_state, array($form_state, $node, $submission), $form_build_id);
  $form = drupal_render_form($form_id, $form_array);

  return drupal_json_output(array(
    'message' => $error_html,
    'status' => 'sent',
  ));

}

function _custom_webform_ajax_access() {
  // Todo: Add webform access conditions
  return true;
}

```

When i submit my form i get 500 server errors.

I guess D6 & D7 form API are quite different and i'm not sure where to start to have this piece of code working. I have tried to debug it but i can't figure out what's generating the 500 errors.

I use webform 3 and the module i took the code also relies on the version 3 of webform but for Drupal 6. But both modules should provide the same functions and same kind of functionalities behind. First workaround: It may come from the values i pass that would not be compatible with D7 form api.

In my log i have :

`Argument 1 passed to drupal_array_nested_key_exists() must be an array, null given, called in D:\wamp\www\productionsite\includes\form.inc on line 1986 and defined in drupal_array_nested_key_exists() (line 6296 of D:\wamp\www\productionsite\includes\common.inc).`

-- EDIT --

I'm debugging line by line now, at the end this piece of code could worth to become a D7 module ;)

I found in D7 documentation that drupal\_rebuild\_form() arguments have changed from D6, and that the `$form_state` can't be empty anymore at this stage, so i updated my code in this way:

```
$form_state = array('submitted' => false, 'values' => array());
$form = form_get_cache($form_build_id, $form_state);
$form_array = drupal_rebuild_form($form_id, $form_state, $form);

```

Now i'm trying to find the equivalent of drupal\_execute(), which doesn't exists anymore in D7.

-- Edit (2) --

I got it working a few days ago and come back to share the solution, and maybe get some advices and improvements suggestions.

```
<?php

function custom_menu() {
  $items = array();
  $items['webform_ajax/%'] = array(
    'page callback' => '_custom_webform_ajax',
    'page arguments' => array(1,2),
    'access callback' => '_custom_webform_ajax_access',
  );
  return $items;
}

function _custom_webform_ajax($nid, $data) {

  $local_POST = $_POST;
  $form_build_id = $_POST['form_build_id'];

  $form_id = 'webform_client_form_' . $nid;

  $node = node_load($nid);

  $submission = array();
  $form_state = array(
    'submitted' => false,
    'values' => array(),
    'build_info' => array(
      'args' => array(
        $node,
        array(),
        FALSE
      )
    )
  );

  $form = form_get_cache($form_build_id, $form_state);
  $form_array = drupal_rebuild_form($form_id, $form_state);

  // Add the clicked button before processing the form
  $form_state['clicked_button'] = $form_array['actions']['submit'];

  if (is_array($local_POST['submitted'])) {
    foreach ($local_POST['submitted'] as $submit_index => $submit) {
      $form_state['values']['submitted'][$submit_index] = $submit;
    }
  }

  // Clearing empty values from $form_state
  if (is_array($form_state['values']['submitted'])) {
    foreach ($form_state['values']['submitted'] as $value_index => $value) {
      if (!$value) {
        unset($form_state['values']['submitted'][$value_index]);
      }
    }
  }

  $form_state['values']['details']['nid'] = $nid;

  // Executing the pressed button action
  drupal_build_form($form_id, $form_state);

  return drupal_json_output(array(
    'message' => t('Your submission has been received. Thank you for contacting us.'),
    'status' => 'sent',
  ));

}

function _custom_webform_ajax_access() {
  // TODO: Add user role / perm check
  return true;
}

```

To go a step further I would like now to get the errors from the processed form so i could send them back with the json object. Any ideas ?

# Answer
I was doing something similar and found E. de Saint Chamas's solution to mostly work for me. However, there were a few things that I needed to add:

First, I had to add this to form\_state array before processing form

```
'method' => 'post',

```

Then, towards the bottom, some adjustments to process the form and return error messages if any:

```
  // Prevent the form from redirecting the request
  $form_state['no_redirect'] = TRUE;
  // Executing the pressed button action
  drupal_build_form($form_id, $form_state);
  // See if the form submitted successfully
  if (!$form_state['executed']) {
    // If the form didn't submit successfully, get the errors
    // which are set bu drupal_set_message
    $messages = drupal_get_messages('error');
    $messages = implode('<br />', $messages['error']);
  }
  else {
    // If form submitted successfully, create a nice message.
    $messages = "Thanks for contacting us! We will let you know when the Beta is live!";
  }
  // drupal_json_output seems to confuse some browsers, who want to save as a file
  print drupal_json_encode(array(
    'message' => $messages,
    'status' => $form_state['executed'],
  ));

```

I am not sure if this is the best way to do it, but found it worked for me. Of course, you might want to just go ahead and render the error messages and return a fully rendered error message box, and additionally, you could pluck the "confirmation message" from the $form\_state array so that you can control the success message from the webform UI.
> 4 votes

# Answer
Tell me if I am wrong but since a webform submission is a node, why not directly create the node programatically in your `page callback` (with field validation (or could do before submit using javascript))

It could be something like

```
if(!function_exists("node_object_prepare"))
{
  include_once(drupal_get_path('module', 'node') . '/node.pages.inc');
}
$node = new stdClass();
$node->is_new = TRUE;
$node->type = 'YOUR_NODE_TYPE_HERE';
node_object_prepare($node);

// then all the fields you need

node_validate($node);
$node = node_submit($node);
node_save($node);
$nid = $node->nid;

```

Et voilà ! :)
> -1 votes

---
Tags: ajax, webforms, forms
---


# Question
Title: hook_user_update() is invoked before saving the user account, not after
I created a module that implements `hook_user_update()`.
As far as I understand this method is called once a user has edited his data and this has been saved to the database.

The problem I notice is that it is not what really happens with my code: The code is called before.

```
function mymodule_user_update(&$edit, $account, $category) {
  $username = "username";
  $password = "password";
  $database = "database";

  mysql_connect(localhost,$username,$password);
  @mysql_select_db($database) or die( "Unable to select database");
  $query = "select * from somewhere;";
  $result = mysql_query($query);

  $num = mysql_numrows($result);

  $myFile = "some_file.txt";
  $fh = fopen($myFile, 'w') or die("can't open file");
  $stringData = "now: ".date('Y-m-d H:i:s')." Value is:".mysql_result($result,0);
  fwrite($fh, $stringData);
  fclose($fh);
}

```

When I check the result at this point, the values are still the ones before saving the user account.
I thought it would be some kind of database cache but this is supposed to be deleted once you edit the table.

# Answer
Actually, in Drupal 7 user\_save() first invokes `hook_user_presave()`, then saves the user account in the database, and invokes `hook_user_update()` or `hook_user_insert()`. It is not possible that `hook_user_update()` is called before the user account has been saved.
`hook_entity_update()` and `hook_entity_insert()` are invoked right after `hook_user_update()` and `hook_user_insert()`. Eventual field updates should be executed with those hooks.

```
// Invoke hook_user_presave() for all modules.
user_module_invoke('presave', $edit, $account, $category);

// …

if (is_object($account) && !$account->is_new) {
  // ...
  $success = drupal_write_record('users', $account, 'uid');
  if ($success === FALSE) {
    // The query failed - better to abort the save than risk further
    // data loss.
    return FALSE;
  }

  // …

  user_module_invoke('update', $edit, $account, $category);
  module_invoke_all('entity_update', $account, 'user');
}
else {
  // …

  $success = drupal_write_record('users', $account);
  if ($success === FALSE) {
    // On a failed INSERT some other existing user's uid may be returned.
    // We must abort to avoid overwriting their account.
    return FALSE;
  }

  // …

  user_module_invoke('insert', $edit, $account, $category);
  module_invoke_all('entity_insert', $account, 'user');

  // …
}

// …

```

In Drupal 6, user\_save() invokes `hook_user('update')`, saves the user data in the database, and then invokes `hook_user('afer_update')`; if the user account didn't exist before, it saves the data in the database, and then invokes `hook_user('insert')`.
> 12 votes

---
Tags: hooks, database
---


# Question
Title: How to print id of user whose profile I visit rather than id of  logged in user?
> **Possible Duplicate:**
> How to print id of user whose profile I visit rather than id of logged in user?

I would like to print the id of the user on his profile page? How can I do it in Drupal 7. So far I could only print logged in user id..Any advice appreciated.

# Answer
> 4 votes
You can use `hook_user_view()`. I have small module named nova to customise various aspects of drupal. So if I use the following function in my module, I get the title "Id of the Member" and then the output of uid.

```
function nova_user_view($account) {
  $account->content['myid'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('Id of the Member'),
    '#markup' => $account->uid,
  );
}

```

Please let me know if it works for you or if you need more explanation.

# Answer
> 5 votes
If you add this to the user-profile.tpl.php template, it will show the UID of user account being viewed.

```
<?php echo $account->uid;?>

```

---
Tags: users
---


# Question
Title: Create a node programatically and set its CCK field values
I've tried the technique described here: http://lucasforge.2bopen.org/2010/06/drupal-6-create-a-node-with-cck-fields-programmatically/

and here: http://drupal.org/node/1111514

Neither seem to work. The node gets created, but the CCK field I'm trying to set never gets set.

Both those just describe using "field\_name\[0\]\['value'\] = 'something'" but even if I set the field value through the web form and DSM the result it never has 'value' set, just '#default\_value'.

I tried setting "field\_name\[0\]\['#default\_value'\]\[0\]\['nid'\] = 'mynodeid'" but that didn't work either.

This is the structure of the CCK field I'm trying to set:

```
field_application_discipline_id (Array, 13 elements)

#type (String, 20 characters ) nodereference_select
#default_value (Array, 1 element)
#required (String, 1 characters ) 0
#columns (Array, 1 element)
#title (String, 13 characters ) Discipline ID
#description (String, 0 characters )
#delta (Integer) 0
#field_name (String, 31 characters ) field_application_discipline_id
#type_name (String, 11 characters ) application
#tree (Boolean) TRUE
#weight (String, 2 characters ) 31
#access (Boolean) TRUE
#count (Integer) 9

```

Any idea why this wouldn't be working?

# Answer
For nodereference fields you have to use "nid" instead of "value".

```
//123 is the nid of the node you want to reference
$node->field_application_discipline_id[0]['nid'] = 123;

```

The best way to discover what variable to use is to install Devel module and view the devel tab next to the view/edit tab on the node page.
> 1 votes

---
Tags: 6, entities
---


# Question
Title: If $db_prefix is "assumed to be a string", then does Drupal automatically sort what is a sharable table in the DB?
```
$db_prefix = 'drupal_';

```

I've found many examples of installations which pick through the tables and place these in an array. And then there is the example of the site I am migrating where it only contained the above string. So, does Drupal *sort it all out* in the case of this simple string?

What is the big idea I feel I am missing about multi-sites? (haha the mysteries of the D framework!)

# Answer
> 2 votes
$db\_prefix can either be a string or an array, have a look at the documentation: Share a single database across multiple sites, the db\_prefix\_tables function take care of this job.

---
Tags: 6, migrations, multi-sites
---


# Question
Title: Get node count for each value of a CCK Options Widgets field
Lets say I have a CCK options widget field with 4 options like 1 2 3 4

If I want to get the node count for these values how could I do that?

Also, how would I do it if I would like to put this result in a View and sort on it? Use a computed field?

# Answer
Views Group By is just what you need. It enriches D6 & Views2 functionality with SQL Grouping and Aggregation capabilities. Once installed, configure it roughly along these lines:

**Fields to Group On:** Your Field
**SQL Aggregation Function:** Count
**Fields to Aggregate with the SQL Function:** Node NID
**Fields to Sort Resultset On (after SQL Function is Applied):** Your Field
**Sort Direction:** Descending

Please, note, this will only select those fields that have non-zero number of nodes that they are selected for. To work around that, depending on your scenario you might be able to use a taxonomy vocabulary to replace your options widget and then build a Term View type based on that vocabulary.
> 0 votes

---
Tags: views, entities
---


title: Caching Blocks with Context Module

text:
# Question
Title: Caching Blocks with Context Module
I am using the Context module with the Block module disabled and noticed that blocks are not being stored in the cache. How do I get Context to cache blocks? Does it matter that much that blocks are not being cached?

The block module is turned off because I don't see why it is needed with the Context module enabled. The block module loads every block on every page load. So I imagine that it would be a boost to use Context without it. However, I'm curious if it would make sense to also have the Context module cache each block that it loads and check the cache first before it loads the block.

# Answer
The Context module uses the Block module as an API. Context renders blocks with the Block module function, \_block\_render\_blocks($region\_blocks), which checks the cache. The Cache module looks for the table cache\_block which if the block module has not been activated or has been uninstalled doesn't exist. In the case of the Context module installed and the Block module unistalled the cache\_block table needs to exist to cache blocks.

The solution is to activate and then deactivate the Block module without uninstalling it. One less query and a few less loops on each page load now.
> 1 votes

# Answer
> How do I get Context to cache blocks?

Anyway a lot of block don't use cache by default. You need to use http://drupal.org/project/blockcache\_alter to improve the control of what you want to cache. Sadly block cache alter is not compatible with context but a small glue module make it works :) http://drupal.org/project/context\_blockcache\_alter . But need a port on D7.

So using block cache alter going to do a real performance boost.

To not use block module the answer from Adam S is correct.
> 2 votes

# Answer
This is not a feature that is implemented in the context module, so you have some options.

* Implement the feature yourself and post a patch.
* Create a custom module that does the block caching for you.
* Use panels instead of context which has it's own caching system built in.
* Enable the block module.

Giving the block module a quick look, unsure what you mean when you're saying that the block module loads every block on every page. Have you tested how much overhead the block module do cause on your site? My guess is that it's not worth implementing your own caching to avoid having the block module enabled.

**Update:**

Having the block module enabled will create a little overhead, 1 query and some loops and boolean checks. This wouldn't be the place I'd start to performance optimize my site. Like I said probably not worth the hazzle implementing your own caching, but if you did you would get some performance improvement. Not sure if you could measure it though - I doubt it.
> 0 votes

---
Tags: blocks, caching, 7
---


title: How to use fivestar as sort criteria?

text:
# Question
Title: How to use fivestar as sort criteria?
In Drupal 6, I have added fivestar widget to 'Story' nodes. Now I want to make a view to sort the stories according to their average fivestar ratings. But I don't see Fivestar among the 'Sort criteria', so how can I do the sorting based on Fivestar?

# Answer
> 5 votes
To start with, just enable the `top_content` default view which comes with the *VotingAPI* module. Its *Fivestar* display has the sorting set up as follows:

**Relationship:** Vote results
**Add sort criterion:** Vote results: Value, Relationship: Voting results

---
Tags: 6, views, rating
---


# Question
Title: Drupal 7: hook_menu not working correctly
I've created a custom module (called page\_arg) simply for the purpose of registering a path and having it use a certain template file. I had this working with Drupal 6, but can't get it to work in Drupal 7. Basically, if I leave the page\_arg\_callback() function in the module, I get a 500 Server Error on every page in the site. If I remove it, I'm able to visit the path I'm trying to register, but it isn't using the template file I want it to use.

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

  $items['flashcards'] = array(
    'title' => 'Flashcards',
    'page callback' => 'page_arg_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function page_arg_preprocess_page(&$vars) {
    $url = urlSplit(); //custom function. trust me, this isn't the problem :)
    if($url[0] == 'flashcards'){
        $vars['template_files'][] = 'flashcards';
    }
}

function page_arg_callback($arg){
  return 'howdy';
}

```

As a secondary question, is this the best way to go about simply registering a path and pointing it to a template file? Seems a bit elaborate. Could I implement hook\_menu() in my theme instead?

# Answer
Try this:

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

  $items['flashcards'] = array(
    'title' => 'Flashcards',
    'page callback' => 'page_arg_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function page_arg_callback() {
  // Do stuff
  return theme('page_arg');
}

function page_arg_theme($existing, $type, $theme, $path) {
  return array(
    'page_arg' => array(
      'template' => 'page-arg',
      'path' => drupal_get_path('module', 'page_arg') . '/theme/templates',
    ),
  );
}

```

Create a file *page-arg.tpl.php* and put it in /theme/templates in your module (page\_arg) directory.
> 4 votes

---
Tags: 7, routes, hooks
---


# Question
Title: Body field of some nodes not displayed in teaser view
Some of my nodes have an empty teaser field so when I visit a taxonomy page, you cannot see any of the body content. Only when you click on the node title to view the full node can you see the body. Why does this happen? I fix this by manually editing my database and adding content to the teaser field of the node\_revisions table but it's troublesome to fix nodes this way.

# Answer
This is either a wysiwyg problem or a problem with Drupal teasers counting HTML in the summary character count.

http://drupal.org/node/221257

http://drupal.org/node/823380
> 1 votes

# Answer
This problem might be related to the WYSIWYG editor you're using. Some of them output a lot of redundant code, so you don't get anything or a bunch of white space before content on teasers. Try using the 'Edit summary feature' that comes with Drupal corer to fine-tune teasers (or you could always have a new teaser text field). Most of the WYSIWYG editors come with a Teaser button, so you should use that.
> 1 votes

---
Tags: 6, nodes
---


# Question
Title: What are functions that start with 'hook' used for?
I understand how to use hooks (`mymodule_HOOKNAME()`) but what are functions used for that actually start with hook? Ex: `hook_action_info()`

When I am creating custom hooks I normally just use: `module_invoke('MODULE', 'HOOK_NAME')`.

# Answer
> 3 votes
`hook_action_info` and other functions that begin with `hook_` exist only to document the contract between the caller of the hook and the module that implements it.

# Answer
> 1 votes
First off, there's not a single function in Drupal, that starts with `hook_`.

**hook\_**

Whenever you see a function name starting with `hook_`, it is a symbolic name for a hook function to be implemented by a module or a theme, where `hook_` will be replaced with the module's or theme's actual name.

Within your module, all functions you want to expose to the Drupal's hook system to be called at appropriate times, will start with `mymodule_` as long as the name of your module is actually `mymodule`. That is also the `MODULE` part in

```
module_invoke('MODULE', 'HOOK_NAME')

```

**mymodule\_HOOKNAME**

On the other hand, `mymodule_HOOKNAME()` refers to all or any hook functions implemented by module `mymodule`.

All modules that wish to configure custom actions will have to implement a function which starts with the module name and ends in `_action_info`. Again, that's the `HOOK_NAME` part in

```
module_invoke('MODULE', 'HOOK_NAME')

```

**module\_invoke**

Finally, the `module_invoke('MODULE', 'HOOK_NAME')` just puts these two concepts (module name and hook name) together to build a specific module's hook function name, check if it exists at all and then call it.

To work out the function name to call, `module_invoke` puts together the `MODULE` and `HOOK_NAME` parts, separated by an underscore. And that is why `yourmodule` implementing `hook_action_info()` defines a function `yourmodule_action_info()`.

# Answer
> 1 votes
From the Drupal 7 API:

> Allow modules to interact with the Drupal core.
>
> Drupal's module system is based on the concept of "hooks". A hook is a PHP function that is named foo\_bar(), where "foo" is the name of the module (whose filename is thus foo.module) and "bar" is the name of the hook. Each hook has a defined set of parameters and a specified result type.
>
> To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in all enabled modules that implement it.
>
> The available hooks to implement are explained here in the Hooks section of the developer documentation. The string "hook" is used as a placeholder for the module name in the hook definitions. For example, if the module file is called example.module, then hook\_help() as implemented by that module would be defined as example\_help().
>
> The example functions included are not part of the Drupal core, they are just models that you can modify. Only the hooks implemented within modules are executed when running Drupal.

---
Tags: 7, hooks
---


# Question
Title: Need help configuring new user signup email notification
I am new to Drupal and use Drupal 6 now. I have a site all built up and I want to just send a *new member* email template when he sign-ups. I don't want any other email templates for now.

I installed postFix on the server. I also use FB for Drupal module.

My Question is this: How do I send welcome email?

Please let me know steps, modules I need (if basic modules are not enough) etc.

# Answer
> 1 votes
The workflow for registering users can be configured at `index.php?q=admin/user/settings`. If this does not suit your needs, let us know how your workflow differs from what can be configured on that page.

I suspect you want to check the option **Visitors can create accounts and no administrator approval is required.** and uncheck the option **Require e-mail verification when a visitor creates an account**. The e-mail that are sent can be configured in the fieldset **User e-mail settings** and for some e-mails, you can configure whether to send them at all.

---
Tags: 6, emails, users
---


title: Content type which creates sub contents

text:
# Question
Title: Content type which creates sub contents
I'm new to Drupal and my first project is turning out quite complex, at least it is when I'm trying to do it with Drupal.

I would like a "project" content type, which on creation will be more than just a page. It should be a page with it's own taxonomy term. On this page there should be a view to show recent media posted to that taxonomy term, along with downloads, articles and a couple of other content types. Essentially the new project page pulls all the other content together.

As I am hoping to hand this site over to less technical people (I barely understand Drupal yet nevermind trying to teach all of this to a non-technical person!) and would like this page to just be set up automatically.

I think the process is this: On creation the page should add it's title as a taxonomy term under the current vocab, then set up a view for each content type to pull the newest content posted under it's term.

Does this make sense? If not I'll update it with more information but if anyone has any pointers/tips or actually knows how to do this then I would appreciate the help!

# Answer
> 2 votes
I'd like to regard content types as a template to create entity objects (much like classes in object oriented programming) rather then as a means to create pages.

I do not see a reason for each project to have its own taxonomy term. If there is a 1:1 mapping between terms and projects, you are effectively creating redundancy. This might be done at a later stage to facilitate using specific modules that rely on the taxonomy module.

Nodes of the content type "media" can be linked to nodes of the "Project" content type by adding a "node reference" field to the "Media" content type. In Drupal 6, the "Node reference" module is part of the Content Construction Kit; in Drupal 7, it has been moved into the References module.

You can use the Prepopulate module to create URLs that show the "Media" creation form with the "node reference" field for "Project" already populated. This URL can be linked to using hook\_link() (in Drupal 6) or hook\_node\_view() (in Drupal 7) to create media from the project page.

The list of associated media can be shown on the project page using the Viewfield module. Alternatively, the project page can be overridden using the Panels module. A second alternative is to add the output of the view to the project node using hook\_nodeapi(&$node, $op='view') (in Drupal 6) or hook\_node\_view() (in Drupal 7).

# Answer
> 0 votes
If it is a new project. I would suggest Drupal 7.

In Drupal 7 taxonomy terms can be treated as content. So rather than having a node and a term, you can just have a term.

---
Tags: views, taxonomy-terms, nodes
---


title: Implementing search for a view

text:
# Question
Title: Implementing search for a view
I have a view containing objects of a custom content type. Could anyone please tell me how I could allow my users to search only objects that have certain attributes? Some sort of like "Show me objects that are located in X, have a size of Y and colour Z".

# Answer
Create and expose filter in the view. This is not a full blown search but might be sufficient for your needs. If you need more advanced functionality, try Apache Solr Search Integration.
> 2 votes

---
Tags: views, users, database, search
---


# Question
Title: Add user picture to profile 2/any entity for that matter...
I've disable user pictures in User account and want it displayed in Profile2. I can add a field for Image. But, it's not recognized as the official user picture; so it can be used in comments, node views, etc. How can I do that?

# Answer
> 1 votes
You have two options.

You can use theming to make whatever you want use the profile picture.

Another options would be to add the picture from the profile to the user object on load.

Third option would be to sync the user picture with the profile picture whenever the profile entity is saved.

If you want it to take effect everywhere, you need to use the third options, which adds the headache of having the same data store twice and the problems such a thing can bring,

---
Tags: 7, users
---


# Question
Title: Is it possible to automatically add a taxonomy term for a content type?
How is it possible to automatically add a taxonomy term for a content type?

Is it possible to make the new added terms children of this automatically set term?

I have a content type intended for users, and I would like them to be only able to add terms that are children of a parent term of my wish; in this way, if they choose a term, it will become a child of my default term, but if they don't add a term, then the node will be tagged automatically with my term (the parent term).

# Answer
In Drupal it is possible to associate a vocabulary to a content type: Once you created your vocabulary, and added the taxonomy terms, you go to admin/structure/types, and for the content type to which you want to associate the vocabulary, you click on *manage fields*; in my example, I am going to add a vocabulary to the *Article* content type.

In the *Add new field* column I fill the fields as follows (the value you use for the field name, and to the field title can be what you like better):

>

When you click on *Save*, you get the following page. (The shown error is just because I am creating a patch for Drupal 7; it's not something you should see.)

>

Select the vocabulary you want to associate with the content type, and click *Save field settings*. In the next page, you can select the default value for the taxonomy term, which by default is *\- None -*; you can select the one that is automatically set. If the user doesn't change it, it will be the value associated with the node.

>

When a user will create a node of that content type, they will see something similar to what shown in the following screenshot:

>

In my case, I selected *Overview* as default taxonomy term.

When you create your vocabulary, you can set a taxonomy term that is the parent of all the other taxonomy terms, and select it as default value for the content type.

>

In this case, *Golden apple* is child of *Apple*, which is child of *Fruits*; *Kaiser pear* is child of *Pear*, which is child of *Fruit*.
As side note, the hierarchy of taxonomy terms that are shown in the node edit form is the one defined in the vocabulary you associated with the content type; this means that, if *Apple* is not child of *Fruit* in the vocabulary I am using, then it will not be shown as child, in the node edit form. The taxonomy term widget doesn't alter the vocabulary structure.
> 7 votes

# Answer
Yes it is.

You can either do this with a custom module that implements hook\_form\_alter or by using a module that does this for you.

I can suggest looking at http://drupal.org/project/prepopulate \- which may give you some clues on how to achieve this
> 3 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: How can I display a user avatar in Drupal 7?
I'd like to know how to display a user avatar in Drupal 7. I want to display the avatar in full size, and as thumbnail.

# Answer
> 3 votes
The code used from user\_user\_view() is the following one:

```
$account->content['user_picture'] = array(
  '#markup' => theme('user_picture', array('account' => $account)),
  '#weight' => -10,
);

```

For example, if you want to output the HTML code to show the picture associated with the currently logged-in user in a form, you could use code similar to the following one:

```
$form['user_picture'] = array(
  '#theme' => 'user_picture',
  '#account' => $GLOBALS['user'],
);

```

This is similar to the following code used in node\_admin\_nodes(), which uses a different theme function.

```
$form['nodes'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $options,
  '#empty' => t('No content available.'),
);

```

The content of "#header," "#rows," and "#empty" are used to populate the content of the `$variables` array that is passed to the theme function ("#header" becomes "header," etc).

`theme('user_picture')` works even when the Image module (the one that defines `theme_image_style()`) is not enabled; in that case, it uses `theme_image()` instead. When the Image module is enabled, it uses the default style as contained in the Drupal variable "user\_picture\_style." In both the cases, the user image is a link to the user profile.

As the theme function is using a template (user-picture.tpl.php), the relevant code is in template\_preprocess\_user\_picture(); if you look at the code for theme\_user\_picture(), you would see there is no code.

# Answer
> 2 votes
A user's profile picture is available on the loaded user object. You can use image\_style theme function to render an image in the size of your choosing.

---
Tags: 7, users, media
---


title: Adding a background image to the header

text:
# Question
Title: Adding a background image to the header
I'm trying to display a photo as background image for a Drupal 7.7 website.

After reading a doc on subthemes, I have created a directory called "pasture" in the same directory where "bartik" resides (i.e. in ~/public\_html/drupal/themes/pasture).

* I have created the pasture.info file.

```
name = pasture
base theme = Bartik
stylesheets[all][] = pasture.css
files[] = pasture.jpg
core = 7.x

```
* I have created the pasture.css file.

```
#header {
        background:url(/drupal/themes/pasture/pasture.jpg) top left no-repeat;
}

```
* I have saved a public domain image as pasture.jpg. The image is the following one.

Unfortunately, my site appears completely broken, after I activate that theme, and I see numerous warnings:

> Notice: Undefined index: Bartik in method drupal\_theme\_initialize() (line 98 inf file /usr/www/users/simplex/drupal/includes/theme.inc). Notice: Trying to get property of non-object in method phptemplate\_init() (line 12 in file /usr/www/users/simplex/drupal/themes/engines/phptemplate/phptemplate.engine).

# Answer
> 1 votes
I cannot comment, but some remarks

1. remove the files\[\] = pasture.jpg line, it isn't needed
2. you may enable your base theme, but it isn't necessary
3. put your own themes (modules) under /sites/all/themes or /sites/default/themes, don not put them inside /themes (/modules), if this directory doesn't exist, just create them

Question, does your site works when using the Bartik theme?

---
Tags: 7, theming
---


# Question
Title: Find out if you're viewing a taxonomy page
Clicking on a Taxonomy term generally takes you to a page showing several nodes which use that term. Is there a way to find out if you're viewing a specific vocabulary and save it to a variable? That way you can change the layout at will:

```
<?php if( $is_vocabulary_fruits ) : ?>
    Load this layout
<?php if( $is_vocabulary_cars ) : ?>
    Another layout different from the first
<?php else : ?>
    Nope, use this layout instead
<?php endif; ?>

```

I'm looking to place this in `page.tpl.php`. This means that the markup outside of the `node.tpl.php` is changed when viewing a taxonomy and not the node itself. How is this done in my template.php file?

# Answer
> 2 votes
When a taxonomy page is rendered, the template file used is taxonomy-term.tpl.php that receives, among other variables, the `$term` variable, which contains the term object for the taxonomy term associated to those nodes.
Basing on the vocabulary that owns that taxonomy term, you can change the layout of the page.

If you want to find out in page.tpl.php the taxonomy term associated with the nodes shown in the page (where the page's URL is example.com/taxonomy/term/\[tid\]), then you can use the following code:

```
$term = menu_get_object('taxonomy_term', 2);

```

If the page's URL is not example.com/taxonomy/term/\[tid\], then the function returns `FALSE`. The code can also be executed in a preprocess function, such as `hook_preprocess_page()`.

# Answer
> 1 votes
I can think of a couple of ways to have different layouts based on vocabulary. One is through template suggestions: http://drupal.org/node/1089656. You would need to do your own template suggestion for your vocabularies and you can have different markup or classes.

Another way would be to add a vocabulary body class based on the taxonomy and you change the layout that way like:

```
.vocabulary-fruits #main {width:600px; float:right}

```

Look at: http://drupal.org/node/1072806

---
Tags: 7, taxonomy-terms
---


# Question
Title: Activate an existing menu item through code
I need to activate an existing menu item through a hook when I'm on a certain page. To give some context, I have a primary navigation bar which is visible on all pages, and when I'm on a user profile page I want to activate the People menu item. The path to people is /people. Any help is appreciated.

Cheers.

# Answer
> 5 votes
I would recommend using the Context module. You can setup rules for when a menu item is active such as content type or menu path which will save you from writing related code.

This might make it easier to understand as well for someone inheriting your site.

# Answer
> 0 votes
While not a hook maybe this will help.

If you are using a menu block you can just Show block on specific pages (in Home » Administration » Structure » Blocks). Select "Only the listed pages," and enter "people" "people/\*" (for pages such as people/joe, people/amy).
This is for if you aren't using Context or Panels which are much more flexible.

Check out also hook\_block\_info().

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


title: Multiple node reference on same node

text:
# Question
Title: Multiple node reference on same node
In Drupal 6, I have the "Player" content type that has a field reference to the "Team" content type.
I want to make content type for sports match.

It has two referencing field for teams:

* field\_host\_team
* field\_guest\_team

I want to make a relationship for players that played, but I want the users to be able to choose only players that have a reference to the selected (home/guest) team such as:

* field\_host\_players (only players from team selected in field\_host\_team)
* field\_guest\_players (only players from team selected in field\_guest\_team)

Do you have any idea on how to do this?

# Answer
> 2 votes
You can have a node reference for players. In node reference you can limit the list of options to a view. You can make a view that has a custom argument that looks up players from the home and away teams already attached to the node.

You might get a better answer for this, but throwing this one out there in the few mins I have.

---
Tags: entities, nodes
---


title: Why is my webform not displaying?

text:
# Question
Title: Why is my webform not displaying?
I have a webform. If I go into the backend "content management =\> content" area and click "edit" for the form and then "preview", the form preview displays fine.

However, if I view that same webform on the frontend, I see either:

1. "Published by admin on Tue, 07/19/2011 - 15:15" if I am logged in as a new user
2. "Published by admin..." and in my $messages "You have already submitted this form. View your previous submissions." if I am logged in as a user who has submitted the form before.

This form was displaying fine at some point. Obviously someone working on the project (quite likely me) has broken it since then.

The form is published. The submission limit is set to "unlimited". The "status of this form" is set to "open". The "submission access" settings allow any "authenticated user" to submit the form.

What are some reasons for why my form might not be displaying? Do I need to add something in my page.tpl.php to have it display? What's the quickest way for me to debug this?

# Answer
This sounds like something you could have done in the node template in your theme. You can try to change your theme. If that fixes then your theme is the root cause.
> 3 votes

# Answer
Turned out to be a silly mistake in node.tpl.php — someone removed the `print $content;` from that file.
> 2 votes

---
Tags: 6, webforms
---


# Question
Title: Only show the amount of views in Advanced Forum
I am using the 'Advanced Forum' module in Drupal 7 and I want to have a 'Views' column in the topic list. I have managed to do this using the Statistics module, but now at the bottom of every node it says '## reads', much to my dislike. Therefore, I would like to remove every visible view count; only leaving the views column in the 'Advanced Forum'.

Is this possible? If it is possible, how can I do it?

# Answer
You can remove it through `template_preprocess_node()`. For instance:

```
function YOURTHEMENAME_preprocess_node(&$variables) {
  unset($variables['content']['links']['statistics']);
}

```

Or you may be able to do this with simple CSS as well:

```
li.statistics_counter {
  display: none;
}

```
> 1 votes

# Answer
Also, the view count on nodes is permission based, so you can deny the view permission to everyone and then it will only show for UID 1.
> 2 votes

---
Tags: 7, nodes
---


title: Change Node Owner On Node Submit

text:
# Question
Title: Change Node Owner On Node Submit
How can I change the owner of an anonymously submitted node upon the initial node creation?

Goal:

1. Anonymous user completes form.
2. Node owner is changed to a specific user id.
3. Node is inserted into DB.

Can this be done with `hook_form_FORM_ID_alter();`

# Answer
hook\_form\_FORM\_ID\_alter is used to alter the form before it is rendered, if you want to alter the form after being submitted and before being save, you have to use hook\_node\_presave.
Put this code in a `custom.module`:

```
function custom_node_presave($node) {
  if ($node->uid == 0) {
    // Change anonymous node author to uid: 2
    $node->uid = 2;
  }
}

```
> 2 votes

---
Tags: nodes, forms
---


# Question
Title: Change Form Single Select element to Multi Select for JS enabled users
I would like to have an exposed filter that shows single select by default, but for JS users is able to be altered to a multi-select.

The reason for this is that I want to apply the JQuery plugin Chosen onto my multi-select elements. However showing the pure multi-select element in the same block space on the page will be both unsightly and unwieldy for non-JS users, so I'd prefer they fell back to a single-select drop down menu.

I guess I can easily change a single select to a multi-select using JQuery, however is this going to prevent Drupal from accepting multiple values since the form element will only be expecting a single value for that single-select element?

Thank!

# Answer
> 2 votes
Looks like someone made a module for this: http://drupal.org/project/chosen, maybe he can provides some support for views.

Some details from the module's project page:

> Chosen uses the Chosen jQuery plugin to make your `<select>` elements more user-friendly.

---
Tags: forms, javascript, views
---


# Question
Title: How to find out what views page you're looking at
I have the `$is_portfolio` variable in my "template.php" file that lets me easily check what content type is being displayed, so I can do freaky and awesome stuff with it:

```
function mycooltheme_preprocess(&$variables, $hook) {
  if ($hook == 'page' ) {
    if ($variables['node']->type == 'portfolio') {
      $variables['is_portfolio'] = TRUE;
    }
    else {
      $variables['is_portfolio'] = FALSE;
    }
  }
}

```

In my "page.tpl.php" file, I use it through a conditional which lets me change the markup depending on the content type:

```
<?php if ($is_portfolio) : ?>
  // Use this layout
<?php elseif (!$is_portfolio) : ?>
  // Boo, use this layout instead :-(
<?php endif; ?>

```

How can my code in "template.php" be customized so it can also check which **Views page** is being displayed, so I can target those as well?

# Answer
> 2 votes
Use menu\_get\_item() to retrieve the page callback for the currently shown path, and check it correponds to 'views\_page', which means you are in a view.

```
function mycooltheme_preprocess_page(&$vars) {
  $menu_item = menu_get_item($_GET['q']);

  if ($menu_item['page_callback'] == 'views_page') {
    $vars['is_portfolio'] = ($menu_item['page_arguments'][0] == 'path_of_your_view');
  }
}

```

You can also use current\_path() directly, but I found interesting to know that you're on a Views page using `menu_get_item()`.

# Answer
> 1 votes
Alternative you can use

```
$view = views_get_page_view();
$name = $view->name;

```

---
Tags: 7, views
---


title: Per-group/node RSS feed aggregation?

text:
# Question
Title: Per-group/node RSS feed aggregation?
I am in the process of building out a community site where each 'network' (like an OG group) can set up it's own RSS feed (simply by pasting the URL into their network node's 'network\_feed' field).

I am in the early stages of figuring out how to build and implement a system whereby I can run through all those feeds (for networks that have them) and aggregate them, posting new nodes that contain node references back to the main network for each new item in the feeds.

I have had some limited experience with the Feeds module, and it seems the best candidate for this (Aggregator in D7 core seems a bit less hardy), but I didn't know if there was something I was missing that would make this much easier.

I'm thinking, right now, that I'll build some sort of system that queues up all the URLs contained in 'network\_feed' fields, then maybe hook into some of the feeds.module's methods to retrieve and parse the nodes. Instead of doing this manually, does anyone know if there's something prewritten for Feeds, Aggregator, or another solution that does this kind of thing?

# Answer
> 0 votes
I eventually wrote an entire module for this purpose. Basically, I have a 'feed' field for the group-type content type, and my module tracks that field and any changes through core hook\_node\_update, \_delete, \_insert, etc. hooks. Then I have a cron-based queue consumer that grabs the 5 feeds that were updated furthest in the past and checks for new content, then posts it into nodes under the feed's group.

I used SimplePie to help with the parsing, because even SimpleXML is somewhat of a pain. Anyways, I might try to make this functionality more formalized and port it to work with something like Organic Groups, but it's really purpose-built. If anyone would like some help doing something similar, give me a shout.

---
Tags: feeds
---


# Question
Title: View list of teasers wrapped in <li> instead of <div>
How can I view my teasers in `<li>` instead of in the default `<div>`? I find that changing the `<div>` to `<li>` in `node.tpl.php` doesn't work since `<li>` needs to be wrapped in a `<ul>` tag.

# Answer
I agree you should use Views for this. You can replicate Drupal's default front page, just by enabling the default front page view that comes with views. You can use the regular View style plugins to create lists, tables, etc. Using things like Semantic Views in Drupal 6 and by configuring the styles in Views 3 you can have clean markup and have more exotic things like definition lists.

To understand how Views outputs its markup you should have a look at the templates views comes with in the themes folder, if you want to see how views outputs lists for example check out views-view-list.tpl.php.
> 1 votes

# Answer
You could use the Views module to output an unordered list of teasers. You can use the **HTML List** display type, along with a **Node: Teaser** field.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Using the PHP include in your template: Naming the file .php or .inc?
I'm able to load static PHP files for my theme without any problems but do I name the file as `file.php` or `file.inc`? I found out that either way works fine so which one is better?

```
<?php include ".." . base_path() . path_to_theme() . "/includes_folder/file.php"; ?>
<?php include ".." . base_path() . path_to_theme() . "/includes_folder/file.inc"; ?>

```

Remember that the files are saved in my theme folder since I'm not making a module. It's just static content.

# Answer
The extension ".php" is used for template files, whose extension is really ".tpl.php" files that are included from other files, such as module files, should use the ".inc" extension.

Drupal 8 uses .php (not ,tpl.php) for templates and PHP files containing classes, but still uses .inc for files loaded from modules, such as path.inc.
> 6 votes

# Answer
The Drupal 7 coding standards (#includes) seem to use ".inc" over ".php". If you browse the Drupal Core you see ".inc" is used everywhere. I suggest you stick to ".inc".
> 8 votes

# Answer
As others have answered I suggest you stick with the coding standards set out by Drupal.

Make sure to protect your files though: .inc files called directly from the browser may not be pre-process by php and therefore your source code will passed straight to the user. This may already be done for you by Drupal at a high level, or may not be required due to webserver configuration.

Lastly consider checking inside each of your .inc files that they are *not* the entry point, devious users might cause unexpected behaviour.
> 1 votes

---
Tags: 7, theming
---


title: Having a views result in raw output

text:
# Question
Title: Having a views result in raw output
I already found Get "Raw" views data (with no or little markup), but it wasn't, what I was looking for. I really do need the raw fields for having them differently styled in a module. Because the view itself should just be styled like it is, when navigating to it as page. But my module should be able to read the fields in raw-style. Or do I have to clone a view in order to be able to read the raw format?

# Answer
> 2 votes
Your module can load and execute the view itself. You can get the results from the view without changing the display.

```
// Load the view
$myview = views_get_view('my_view');
// Set arguments if you need to
$myview->set_arguments(array($code));
// Execute the query
$myview->execute();
// Loop over the results
foreach ($myview->result as $row) {
  // The fields are properties of the row
  $x = $row->my_field;
}

```

---
Tags: views, 7
---


# Question
Title: drush devel-reinstall does not rebuild tables
For some reason if a module is a dependency other another module, and I run 'drush devel-reinstall' on it, it does not delete and then rebuild the tables for that module. Does anyone know why?

# Answer
> 1 votes
Apparently because the module can't be uninstalled because another one is dependent on it.

---
Tags: 7, drush
---


title: Hide Breadcrumb on Taxonomy Term View

text:
# Question
Title: Hide Breadcrumb on Taxonomy Term View
Hello i asked this on stackoverflow and was refered to here. I hope you dont mind me copying and pasting it. thanks

Hello i don't really know where to ask this on drupal so i hope you all don't mind me asking it here on your fine site. Everything ive asked before has been resolved by your good selves so i thought i'd give you a try on this. Thanks.

I was hoping to just hide my breadcrumb when viewing the taxonomy term view created by Views. I do use Custom Breadcrumbs module but from what ive read that just edits the output and not the breadcrumb appearing or not. Here's an example of my view- http://onlinebanter.com/general-chat

As you can see it's pushing the centre of my page down so as it isnt lined up with the sidebar. I dont really need it in these views. All help appreciate from your vast combined knowledgebase.

Thanks

Reg

# Answer
This is easily done with a little bit of theming. Based on the page being displayed, you can unset the `$breadcrumb` template variable to suppress output of the breadcrumbs on that particular page.

Pop a function like this simple example into YOUR\_MODULE's `template.php`:

```
function YOUR_MODULE_preprocess_page(&$vars) {
  if ($_GET['q'] == 'general-chat') {
    unset($vars['breadcrumb']);
  }
}

```
> 0 votes

---
Tags: breadcrumbs
---


# Question
Title: Restrict taxonomy terms when users edit content?
I've implemented my site's structure by creating a taxonomy for "areas" and making a term for each area I want in my site (guest info, newbie, facilities, news, and admin). I've let the main menu show these terms as menu items, so that each item shows the content of the corresponding area. When I add content, I specify which area it's for, and this works quite well.

Now, though, I would like to introduce a content type for users to create (for a "user-to-user" area) and I want to hard-code this content type to a specific taxonomy term.

* If I leave out the field for this taxonomy, no term will be assigned. :-/
* If I include the field for this taxonomy, the user can choose a term (and put the page in any area). :-/
* It doesn't look like term assignment is something that can be done with Actions and Triggers. :-/

Is there perhaps a module that provides control over what terms are available for a given situation (user/role/content type)? I've googled, but all I can find is acces control modules for users and nodes, not taxonomy terms.

Edit: *To be clear, I'd like to EITHER programmatically set a particular term of a particular vocabulary every time a user of a particular role saves a node of a particular type (but without me having to do PHP programming); OR allow users of a particular role access to only a subset of a particular vocabulary.*

Help! :-)

# Answer
Taxonomy Access Control will let you set up the permissions at the term level.

> Access control for user roles based on taxonomy categories (vocabulary, terms).
>
> * Automatically controls access to nodes (based on their taxonomy
> terms).
> * Configuration page for each user role.
> * Three node access permission types: View, Update, Delete.
> * Two term access types: View tag, Add tag.
> 6 votes

# Answer
I'm not aware of any modules that provide this functionality. However, you could write a pretty simple module yourself that automatically assigns the correct taxonomy term. This can be done by adding the field for taxonomy to the content type in question, but not giving users permission to edit the taxonomy terms. It sounds like only the administrator (you) is using this taxonomy vocabulary. Another option would be to simply hide the field (using CSS or other means) on the form.

Either way, use `hook_nodeapi()` (or `hook_node_insert` in Drupal 7) to set the value of the taxonomy field automatically when the new node gets created. This way you're guaranteed that each user created node has the correct taxonomy terms.
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: Upgrading to  Drupal 7.7 produces a fatal error: What can I do?
I have upgraded my local site to Drupal 7.7 from Drupal 7.4, following the instructions in How to upgrade Drupal 7 to Drupal 7.2.

Before I could use update.php, visiting my site got me this message on every page of the site:

> Fatal error: Class 'DatabaseConnection' not found in C:\Users\Developer\Documents\Sites\accountablog\includes\database\database.inc on line 17

Doing a database restore did nothing to alleviate the problem.
What can I do to fix the problem?

# Answer
The database.inc file does contain the definition of the class `DatabaseConnection`.

```
/**
 * Base Database API class.
 *
 * This class provides a Drupal-specific extension of the PDO database
 * abstraction class in PHP. Every database driver implementation must provide a
 * concrete implementation of it to support special handling required by that
 * database.
 *
 * @see http://php.net/manual/en/book.pdo.php
 */
abstract class DatabaseConnection extends PDO {
  // …
}

```

It is probable the file was not correctly copied, or has been corrupted during the copy; that would explain why the class has not been found, but the class is effectively present in the file that comes with Drupal 7.
> 3 votes

---
Tags: 7, updating
---


# Question
Title: Do page arguments in hook_menu get sanitized?
The title pretty much says it all.

If a callback is defined in a hook\_menu, such as

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

    $items["mymodule/foo/%"] = array(
        "page callback" => "mymodule_foo",
        "page arguments" => array(2),
        "access arguments" => array("mymodule permission"),
        "type" => MENU_CALLBACK,
    );

    return $items;
}

function mymodule_foo ($parameter)
{
    // do stuff
}
```

When the callback gets called, has `$parameter` been sanitized, or is this the responsibility of the module?

I always sanitize in the module, but have never seen this stated either way and haven't found where callbacks get called from core.

# Answer
**In D6**

menu\_execute\_active\_handler() calls the callback. However it gets it's arguments from menu\_get\_item(), which uses arg.

I can't see any sanitizing in any of that. So it looks like the answer is no.

In any case extra sanitizing can't hurt.
> 3 votes

---
Tags: routes, hooks
---


title: Override User Registration Page

text:
# Question
Title: Override User Registration Page
I want to override the user registration page, but my code is not working like it used to for Drupal 6.

```
function mytheme_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   $hooks['user_login'] = array(
     'template' => 'templates/user-login',
     'render element' => 'form',
   );
   $hooks['user_register'] = array(
     'template' => 'templates/user-register',
     'render element' => 'form',
   );

   return $hooks;
 }

```

Only the login block hook seems to work.

```
function mytheme_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

function mytheme_preprocess_user_register(&$vars) {
  exit;
}

```

I need this to be a preprocess function so I can change/add variables to put into the template. The second function is never called.

# Answer
I got it: The theme ID should be `user_register_form`, not `user_register`. Now it works.
> 2 votes

---
Tags: 7, forms, theming
---


title: Form alter in a custom module

text:
# Question
Title: Form alter in a custom module
I am trying to modify a form with a hook\_form\_FORM\_ID\_alter within a module though it doesn t seem to have any effect at all when called from within my module.

My code looks like something like this:

```
function fb_reg_form_user_register_form_alter(&$form, &$form_state, $form_id ){
    $form['field_lang_list']['#prefix'] = '<div style="display:none;">';
    $form['field_lang_list']['#suffix'] = '</div>';

   $fbu = fb_facebook_user();
   if ($fbu || is_numeric($fbu)){
   $fb_account = fb_api($fbu);

   krumo($fb_account);
   $form['account']['mail']['#prefix']= '<fb:profile-pic uid="'.$fbu.'" linked="false"></fb:profile-pic>';
    $form['account']['mail']['#default_value'] = $fb_account['email'];
    $form['account']['name']['#default_value'] = $fb_account['name'];
    //$form['account']['name']['#default_value'] = $fb_account['name'];
   }
}

```

The thing i don't understand is that this works as expected when the hook is called from within the template.php but when in the module it self i can't seem to get it work.

Would anyone have any idea on what s going on?

**EDIT: Could this have something to do module weight ?**

Many thanks,

# Answer
If the part of the form you're altering doesn't exist when you're altering it (if it's put there by some other form-altering module) OR if some other module is altering the form after you and wiping out what you're doing then you can indeed have a module weight problem. The way to find out is to put a dsm() (see devel module) in your code and see what the form looks like before your alter. Or use a debugger of course (recommended!)
> 2 votes

# Answer
If you use form id in function name, you don't need $form\_id param.

IMO function name should be

> mymodule\_form\_user\_register\_alter
> 0 votes

---
Tags: 7, hooks, forms
---


title: Entities and Views integration problems

text:
# Question
Title: Entities and Views integration problems
I can't figure this out despite hours (maybe 12hrs) of Googling and experimentation. I'm trying to integrate my custom entity with views. I am using Entity API. I don't normally dump a lot of code in these posts, but I'm not sure where to start with this one. I'm hoping someone can point me in the right direction.

@googletorp - I tried to follow your tutorial but must be missing something because I just can't get it to work.

Below are the following: 1) Entity Declarations 2) Schema 3) Screenshot of what's showing up in Views

Entity Declarations

```
    function bse_entity_info()
    {
        $items['bse_type'] = array(
            'label' => t('Basic Storage Entity'),
            'controller class' => 'EntityAPIController',
            'entity class' => 'Entity',
            'base table' => 'bse_type',
            'fieldable' => TRUE,
            'entity keys' => array(
                'id' => 'id',
                'label' => 'label',
                'name' => 'type',
            ),
            'exportable' => FALSE,
            'bundle of' => 'bse',
            'module' => 'bse',
            'access callback' => TRUE,
        );

        $items['bse'] = array(
            'label' => t('Basic Storage Entity'),
            'controller class' => 'EntityAPIController',
            'views controller class' => 'EntityDefaultViewsController',
            'entity class' => 'Entity',
            'base table' => 'bse',
            'fieldable' => TRUE,
            'access callback' => TRUE,
            'entity keys' => array(
                'id' => 'bid',
                'bundle' => 'type',
            ),
        'label callback' => 'entity_class_label',
            'bundles' => array(),
            'bundle keys' => array(
                'bundle' => 'type',
            ),
            'view modes' => array(
                'full' => array(
                    'label' => t('Full'),
                    'custom settings' => FALSE,
                ),
            ),
            'module' => 'bse',
        );
        return $items;
    }

    function bse_entity_info_alter(&$entity_info)
    {
     $bundles = entity_load('bse_type');
        foreach ($bundles as $type_name => $type) {
          $entity_info['bse']['bundles'][$type_name] = array(
           'label' => $type->label,
        );
        }
       }

```

Schema

```
function bse_schema()
{
    $schema['bse'] = array(
        'description' => 'BSE Table',
        'fields' => array(
            'bid' => array(
                'type' => 'serial',
                'not null' => TRUE,
                'description' => 'Primary Key: Unique entry ID.',
            ),
            'type' => array(
                'description' => 'BSE content type.',
                'type' => 'varchar',
                'length' => 32,
                'not null' => TRUE,
                'default' => '',
            ),
            'uid' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
                'description' => "The {users}.uid of the associated user.",
            ),
            'created' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
                'description' => "Timestamp for when this entry was created.",
            ),
            'status' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
                'description' => "Status of content.",
            ),
        ),
        'foreign keys' => array(
            'uid' => array(
                'table' => 'users',
                'columns' => array('uid' => 'uid'),
            ),
            'type' => array(
                'table' => 'bse_type',
                'columns' => array('type' => 'type'),
            ),
        ),
        'primary key' => array('bid'),
    );

    $schema['bse_type'] = array(
        'description' => 'BSE Type Table',
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'not null' => TRUE,
                'description' => 'Primary Key: Unique ID.',
            ),
            'type' => array(
                'description' => 'BSE type machine name.',
                'type' => 'varchar',
                'length' => 32,
                'not null' => TRUE,
            ),
            'label' => array(
                'description' => 'The human-readable name of this bse type.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
            ),
            'module' => array(
                'description' => 'Name of the module that defined this type.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
            ),
            'disable' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
                'description' => "1 = disabled. 0 = enabled.",
            ),
        ),
        'primary key' => array('id'),
        'unique keys' => array('type' => array('type')),
    );

    return $schema;
}

```

Views

# Answer
The entities in Commerce might be useful to you. They use Entity module's wrappers, but have full views support. The GPL programmer's motto: When in doubt, steal code.
> 2 votes

---
Tags: 7, views, entities
---


# Question
Title: Drush missing the "provision" and "Hostmaster" commands
One of our boxes is missing these Aegir-Drush commands (from `drush help`):

```
All commands in provision: (provision)
 backend-parse         Parse the output of --backend commands to a human readable form
 hostmaster-install    Install and verify the Hostmaster frontend.
 hostmaster-migrate    Migrate an instance of the Hostmaster front end to a new platform
 provision-backup      Generate a back up for the site.
 provision-backup_del  Delete a backup file.
 ete
 provision-clone       Clone a site between platforms.
 provision-delete      Delete a site.
 provision-deploy      Deploy an existing backup to a new url.
 provision-disable     Disable a site.
 provision-enable      Enable a disabled site.
 provision-import      Turn an already running site into a provisioned site.
 provision-install     Provision a new site using the provided data.
 provision-lock        Lock a platform from having any other sites provisioned on it.
 provision-login_rese  Generate a one-time login reset URL.
 t
 provision-migrate     Migrate a site between platforms.
 provision-restore     Restore the site to a previous backup. This will also generate a backup of the site as it was.
 provision-save        Save Drush alias
 provision-unlock      Unlock a platform so that sites can be provisioned on it.
 provision-verify      Verify that the provisioning framework is correctly installed.

```

We're able to log into Aegir via the web interface, but none of the commands work. The best we could tell, the install went fine. I think it might be related to these commands missing from our server.

How do I get these commands back? We were able to verify the Hostmaster platform with no problem.

# Answer
> 3 votes
Have had similar issues with this in the past,

How many instances of drush is there on your server? In my case I had a drush 3.3 version in `/usr/share/drush` and the aegir 4.4 version (with provision and hostmaster commands) in `/var/aegir/.drush`

In order to get drush to work, I had to alter the path for the aegir user to include `/var/aegir/.drush` first

You can always tell which version of drush you are using by running the command

`which drush`

---
Tags: drush, aegir
---


# Question
Title: Replace the drop-down in Views with an image map
I am looking for a way to replace one of the exposed filters used in the Views module with an Image Map (e.g. a map of the country).

Is there a way for doing this?

# Answer
Strictly off the top of my head here...

You should be able to point the theming of an exposed filter to a custom theme function. Take a look at Better Exposed Filters for how to do so -- it's different between Views 2 and 3 and a little different between D6 and D7. The key will be to build the image map such that the URLs it redirects to are the same format that Views is expecting. Eg: test?field\_animals\_value\[\]=Dog

'Course you won't be able to use this solution with any filter on changing content without updating the image map....
> 2 votes

---
Tags: views
---


# Question
Title: Making sort links on views better exposed filters toggle
I was able to create sort links on views using better exposed filters. I configured the sort filter sin such a way so I have one link that is ascending and another one descending, based on post date. This works very well. What would be amazing is if I could have one link that toggles achieving the behavior of the previously explained sort links. So for example when I'm first looking at the view sorted by ascending date I would get one exposed sort link that would sort by descending (most recent ↓). Then when I would be looking at the view sorted by descending date I would only get one exposed sort link that would sort by ascending (most recent ↑).

So in conclusion I want to combine the two views sort links that I have: **most recent asc** and **most recent desc** into one link that toggles between **most recent ↑** and **most recent ↓**

Is there a way to do this with jQuery for example?

# Answer
> 2 votes
Right now, BEF doesn't have a lot of extra classes or IDs that would facilitate this. You could post a feature request in the BEF issue queue requesting the necessary additional markup that would make this fairly simple using jQuery.

At a minimum, you'd need some sort of "active" designation so you knew which link reflected the current sort options. Currently the active sort option is displayed as plain text (rather than a link) but there's an issue requesting the active sort be displayed as a link.

However, I should point out that I'll be out of town most of Aug and wont' be on the issue queue much... (I'm the BEF maintainer).

I'm always open to bounties! :)

---
Tags: views
---


# Question
Title: Hiding submenu items of a page in Drupal 6
Is there a way, in Drupal 6, to automatically hide all submenu pages? For example, suppose I have the following menu structure:

* Sport
    + football
    + cricket

Is there a way I can enforce "football" and "cricket" to never be seen?

# Answer
> 2 votes
You can use Menu Block module to only show the top level items: http://drupal.org/project/menu\_block

Make a normal menu, create a menu block using that menu and set the depth to '1' .

# Answer
> 0 votes
If you're using the default block created by the Menu system, you can control visibility at a global level under Site Building -\> Menus -\> List Menus -\> \[the menu in question\], then either choosing to disable the particular link, or by disabling the 'Expanded' checkbox for the parent menu item.

---
Tags: 6, routes
---


title: Perfomance problem when posting

text:
# Question
Title: Perfomance problem when posting
Sometimes when I submit a new post (story node) or update one, it take 10-15 minutes for the page to finish loading. I figured it was some problem with the database so I did a SHOW FULL PROCESSLIST the next time I noticed it happening. It was stuck deleting from the boost\_cache\_relationships table. Why is this taking so long and what can I do to fix this?

Here's part of the output from SHOW FULL PROCESSLIST showing the problem query:

```
+---------+---------+-----------+-----------------+---------+------+----------------+------------------------------------------------------------------------------------------------------+
| Id      | User    | Host      | db              | Command | Time | State          | Info                                                                                |
+---------+---------+-----------+-----------------+---------+------+----------------+------------------------------------------------------------------------------------------------------+
| 2208461 | upgrade | localhost | dane101_upgrade | Query   |   28 | Sending data   | SELECT SUM(score) FROM search_index WHERE word = 'when'                                              |
| 2208478 | upgrade | localhost | dane101_upgrade | Query   | *1088* | updating       | **DELETE FROM boost_cache_relationships WHERE base_dir = 'cache/normal/www.dane101.com' AND page_callb**  |
|

```

# Answer
> 3 votes
It appears you may be having the same issue as this person - http://drupal.org/node/1136822

May I suggest you apply the tweaks mentioned in the issue, and if it improves your performance, perhaps consider writing a patch to place back in the issue queue.

I have cross linked the drupal.org issue with this, so that everything is visible

# Answer
> 1 votes
Boost db usage is (currently) not suitable for site using Views and has large number of nodes. Check this issue http://drupal.org/node/715450 and the suggestion in #6

# Answer
> 0 votes
Try to make an `EXPLAIN` on the DELETE query to see if it's using the index in a correct way.
Andrew Berry wrote an interesting post regarding this matter on Lullabot's blog: Slow Queries? Check the Cardinality of Your MySQL Indexes.

# Answer
> 0 votes
Generically & correctly handling views logic in terms of cache expiration is tricky to say the least. There's a reason that by default drupal does a clear\_cache\_all on node\_save; makes worrying about old cached content showing up a thing of the past. I figured one could do better, and for my use case, boost's expiration logic works great with views and panels. For other peoples use cases it might not work as well. If your not using the latest dev, I recommend giving it a shot as it works better in this aspect.

Due to where I work, I have a fairly good idea in terms of what needs to happen to make this a better setup; yes we use boost, but mainly for the relational data it generates (the part your complaining about). Time is the issue. Been busy with more pressing issues; I've sunk the last 6 months into the Advanced CSS/JS Aggregation module and there is still a little bit more dev work to do on it.

The big plan is to move the complicated views/panels relational logic into sub-modules of the expire module, but thats still a long ways off. Getting one of the async js loaders working 100% with panels, wysiwyg & chrome (LABjs, HeadJS) will give us more bang for the buck from our perspective. AdvAgg is laying the foundation for better front end performance; & HeadJS is starting to take full advantage of that.

Long story short, I'm aware of the issues; but they are not affecting us at work thus I can't allocate much time to fixing them. Boost is a very critical bit of our infrastructure (controls varnish & other systems), so things will eventually happen; just don't hold your breath. BTW we are up to 600k nodes on one of our 70 databases so it really is a case of your mileage may vary.

---
Tags: database, performance, caching
---


# Question
Title: Is there anything wrong w giving a node a status other than 0 or 1?
Is there anything wrong w giving a node a status other than 0 or 1? I want to have several different statuses for a content type im working with.

# Answer
I would keep `$node->status` to 0 or 1 doing a grep in a couple of installs there are some explicit checks for it. (not in core but in contrib). While there is nothing to stop you, you won't guarantee that things will work with it.

You can create your own field which represents another status and use that for your own needs.
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: Give users a stripped down version of add node page and then require admin approval
I want to give my users stripped down versions of the 'add node' pages to create nodes of various content types. Once they fill out the stripped down version (less fields and options) an admin/editor can then approve each node manually and fill in fields not in the stripped form. What method or modules can I use to achieve this?

For example, a user would fill in the title, body, tags and the admin would fill in custom fields such as the imagefield, filefield etc.

# Answer
You can assign permissions to fields, the content permissions module should give you what you want. Look in the permissions pages and you can see what rolls have access to which fields.

A simple way to set up the workflow you suggested is to set the default node status to unpublished (look under workflow settings on the edit content type page). Then make sure only your admin role has the *administer nodes* permission.
> 2 votes

---
Tags: 6, nodes, forms
---


# Question
Title: db_fetch_array() fetches only one row from data table, even though I am expecting multiple results
I'm trying to create an array with all the group node' IDs, and from outside group context. I currently have two group nodes defined, and I can see them in my OG table.

However I only get back one result, using the following code. I've tried using only `db_query()` without `db_fetch_array()` and I still get a single result.

```
$group_node_nids = db_fetch_array(db_query("SELECT nid from {og}"));

```

What am I missing here?

# Answer
The code you are using is wrong; you should use the following one:

```
$query = db_query("SELECT nid FROM {og}");

while ($group = db_fetch_array($query)) {
  // Do something with $group['nid'], such as storing it in an array,
  // or directly using it.
}

```

db\_fetch\_array() doesn't return an array containing all the rows matching the query; it returns only one row. If you want to get all the results, you need to keep calling that function.

In this specific case, as you are just fetching a field, you should use db\_result().

```
$query = db_query("SELECT nid FROM {og}");

while ($nid = db_result($query)) {
  // Do something with $nid, which is the node ID for the group.
}

```

`db_result()` should be used also in cases similar to the following one, where the query is returning a single value:

```
$max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $edit['nid']));

```

Instead of `MAX(thread)` you could also use `COUNT(*)` as in the following code, which returns the number of groups present in the site:

```
$number_of_groups = db_select(db_query("SELECT COUNT(*) FROM {og}"));

```
> 1 votes

# Answer
Every time I have to take results outs of a database query result resource I'm scratching my head wondering why we don't have a way to return all rows without having to iterate over the object. Perhaps there's a method out there in cTools or Drupal 7 but until a better answer is presented:

```
$results = db_query("SELECT nid from {og}");
while($row = db_fetch_array($results)) {
  $group_node_nids[] = $row['nid'];
}

```
> 2 votes

---
Tags: organic-groups, database
---