# Question
Title: Block showing users of a specific role is only showing up for the administrator
I have a view/block that is shown to all the users who have a specific role (RoleX, member and administrator), and I set the view to a specific page. Whenever I look at the page as an administrator, I can see the block and everything looks great. When I log in as a user with the role RoleX, as authenticated user, or as anonymous user, and I look at the page, the block doesn't appear. I thought that this only happened if I only checked off the administrator when you go to `configure block` and then `roles` yet I left all of the roles unchecked so the block would be visible to all.

Does anyone have any idea how I might go about solving this?

# Answer
My guess is that there is an access check somewhere that is failing. When logged in as user 1, it's impossible for a standard access check to fail, so this would be why you're seeing the block.

To solve this, try granting ALL permissions to RoleX (make sure you do not do this on a live site) and see if the block appears when you log in as the test user who has RoleX. If the block starts showing up, start disabling permissions a few at a time until you find which one is causing the issue.
> 0 votes

---
Tags: 7, views, users
---


# Question
Title: Is there a way to programmatically add new links to the primary links?
Is there a way to add links to the primary links using PHP in Drupal 6? The reason I ask is that I want to add more links in the footer of the web page, which I don't want to put in the top navigation level.

# Answer
> 3 votes
You can either specifiy the menu name in hook\_menu() (look for 'menu\_name') if they are defined with that hook or you can use menu\_link\_save().

Yet another option would be to use http://drupal.org/project/features and export your menu structure as a feature.

# Answer
> 0 votes
I don't know the details of how to do it, but I know you may use `hook_menu_link_alter()` or override the primary links function `theme_links()` in template.php.

---
Tags: navigation
---


# Question
Title: I am not able to traverse from the last step to the first step in a multistep form
I have created a multistep form with five steps using programatically. Is there any way to traverse to first step form the fifth step?
I have created multistep form as given in example module. In the module, each step gives previous and next link only, and I am not able to go to the first step directly from the fifth step.

# Answer
The example module uses a value stored in `$form_state['storage']` to indicate which step the form is in, when it is being built. You could add a button with a custom submit handler that unsets this value or set it to the value needed for the step you want to show. Also remember to set `$form_state['rebuild'] = TRUE;`.

On a side note, if you want to make multi step forms, the ctools multi step form wizard API can help you doing a lot of these things for you.
> 2 votes

---
Tags: 6, forms
---


title: Drush Scripting? Or Batch API?

text:
# Question
Title: Drush Scripting? Or Batch API?
We have an Ubercart website that handles large volumes of orders daily, processes them and runs other tasks like billing, delivery routing, and future order creation.

Some of these tasks are heavy and sometimes cause PHP to timeout. Is there a better way to run these tasks like through Drush or Batch API?

Speed is not necessarily a priority (although nice), but we want to avoid timeouts, which can sometimes cause issues with billing correctly and scheduling daily orders.

Is Drush script the better option, or Batch API? Are there any tutorials to make better use of both?

# Answer
> 13 votes
I would not suggest to use the batch API, simply for the fact that batch operations depend from the browser; if for any reason the browser crashes, or it loses the connection with the server, the batch operations will not terminate, or (worse) they will be hanging. In fact, to avoid PHP timeouts, the batch operations cause the browser to ping the batch page at intervals; that is what happens, whenever JavaScript code is involved, or not (in the later case, Drupal uses the refresh meta tag).

In these cases, Drush is probably a better choice; you can create a custom module that implements specific Drush commands, or simply add a command file in the directory Drush uses for its commands.

# Answer
> 2 votes
Also you may use custom PHP CLI script. Here is a simple example for drupal 7:

```
#!/usr/bin/php
<?php
echo "Ubercart tasks\n===================\n";

$_SERVER['HTTP_HOST']       = 'default';
$_SERVER['PHP_SELF']        = '/index.php';
$_SERVER['REMOTE_ADDR']     = '127.0.0.1';
$_SERVER['SERVER_SOFTWARE'] = NULL;
$_SERVER['REQUEST_METHOD']  = 'GET';
$_SERVER['QUERY_STRING']    = '';
$_SERVER['PHP_SELF']        = $_SERVER['REQUEST_URI'] = '/';
$_SERVER['HTTP_USER_AGENT'] = 'console';

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
//-------------------------------------------

// Place your code here

```

# Answer
> 1 votes
I have a D6 Ubercart site that requires significant back-end processing for 'auto-generated digital products'. I handle this via:

1. Purchase of one of these custom digital products causes a db table entry for 'products that need to be compiled.' In that db entry is a 'status' field.
2. A BASH script is started from within Drupal that runs in the background. This script is 're-entrant', meaning it is aware of being invoked while running and adds the new work to any existing work yet to be completed.
3. This BASH script increments the 'status' field in the Drupal database as a custom digital product is created, and finally an email notice is sent to the user with a download link for their completed custom product.

This is a somewhat similar solution to the one proposed by Xio, with the exception that this does not use a PHP CLI script, but BASH scripts invoked by PHP in Drupal to run in the background. Those BASH scripts access the Drupal database and advance the 'status' values of any products it is compiling and sending to customers. Plus, Drupal is able to see these status values and report back to the custmers where in the 'custom creation process' their purchases happen to be at the moment.

---
Tags: 7, drush, ubercart
---


title: How do I overwrite the text value?

text:
# Question
Title: How do I overwrite the text value?
I want to overwrite the `$link['text']` value in `theme('rate_button', $link['text'], $link['href'], 'rate-btn')`, a theme function defined from the Rate module, under a specific content type in template.php. Is there a way to get that? How can I do that?

```
function rate_preprocess_rate_widget(&$variables) {
  extract($variables);

  $buttons = array();
  foreach ($links as $link) {
    $button = theme('rate_button', $link['text'], $link['href'], 'rate-btn');
    $buttons[] = $button;
  }
  $variables['buttons'] = $buttons;

  $info = array();
  if ($mode == RATE_CLOSED) {
    $info[] = t('Voting is closed.');
  }
  if ($mode != RATE_COMPACT && $mode != RATE_COMPACT_DISABLED) {
    if ($results['user_vote']) {
      $info[] = t('You voted \'@option\'.', array('@option' => t($results['user_vote'])));
    }
  }
  $variables['info'] = implode(' ', $info);
}

```

This is the code of `theme_rate_button()`.

```
function theme_rate_button($text, $href, $class = NULL) {
  static $id = 0;
  $id++;

  $classes = 'rate-button';
  if ($class) {
    $classes .= ' ' . $class;
  }
  if (empty($href)) {
    // Widget is disabled or closed.
    return
      '<span class="' . $classes . '" id="rate-button-' . $id . '">' .
      check_plain($text) .
      '</span>';
  }
  else {
    return
      '<a class="' . $classes . '" id="rate-button-' . $id . '" rel="nofollow" href="' . htmlentities($href) . '">' .
      check_plain($text) .
      '</a>';
  }
}

```

The reason I am asking is that I have installed the **rate** module, and created the emotion vote (only one), which is used in two content types ("story", and "company"). In the "story" content type, the vote button should show two buttons labelled "best" and "bad," but in the "company" content type I want to set the buttons to "up" and "down."

The local variable `$links` used in `rate_preprocess_rate_widget()` contain the data for two buttons, of which I want to change the label basing on the content type of the node where those buttons appear.

# Answer
You will need to implement mytheme\_preprocess\_rate\_widget() and write your own version.

Notice how $variables\['buttons'\] is set halfway down the function in the original question. Since preprocess functions for a particular theme ALL get run, you can't (that I know of) stop the rate module running its preprocess function, but by re-assigning $variables\['buttons'\] in your own mytheme\_preprocess\_rate\_widget() function, you will be able to control the output there. I would suggest something like:

```
function mymodule_preprocess_rate_widget(&$vars) {
  extract($vars);

  $buttons = array();
  foreach ($links as $link) {
    $button = theme('rate_button', 'my custom text here', $link['href'], 'rate-btn');
    $buttons[] = $button;
  }
  $vars['buttons'] = $buttons;
}

```
> 3 votes

# Answer
enjoylife, in the other thread on this topic you asked me to show you how to use hook\_nodeapi in order to create a global variable containing the node type. I should add: this assumes you're displaying a "node page" - or even more specifically, a page with just one node - since if you are loading more than one node, there's no way of telling "which" node you are getting without a bit more programming. You say you already have a knowledge of php for Drupal, so I'll assume some of this basic knowledge - if you don't, you could, e.g., find a tutorial on how to create a basic Drupal module - see http://drupal.org/node/206753. Creation of basic Drupal modules is a very common task - intermediate Drupal web builders commonly create a specialized module for each site they build. I'd also recommend reading a tutorial on using hook\_nodeapi (see http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook\_nodeapi/6 for api) - this is a "cornerstone" of many simple Drupal modules. Learning about hook\_nodeapi is also good, since it is a good introduction to how Drupal's hook mechanism operates - it may sound a bit counter-intuitive at first, but it is easy enough to understand, and it's pretty much the basis of all Drupal modules you'll ever write.

First you create & install a module called mymodule. Then, inside mymodule.module:

```
function mymodule_nodeapi($node, $op) {
  global $nodeType;
  //if next line is uncommented, this will always be set to first node loaded (or other $op)
  //if(isset($nodeType)) return;
  $nodeType = $node->type;
}

```

Inside your voting theme function or preprocess function (as Chris Cohen has provided in his answer):

```
global $nodeType;
// use $nodeType after it's globalized to modify the text

```

I hope this helps. If it doesn't make much sense, it probably will once you've read more about how Drupal hooks work.
> 1 votes

---
Tags: 7, rating
---


title: Creating N fields with N 'subfields'

text:
# Question
Title: Creating N fields with N 'subfields'
I'd like to create a content type "Enterprise" where user can define N services and, for every service, N tasks. I have already created the other fields for this content-type (name, description, ..., easy fields) but I don't know how to start with the services and tasks.

I'd like to be able to create services and tasks in the same form. What would be the best way to do it?

# Answer
In case of use d6, you can use Flexifield, then after you install you should create a content type that should represent your subfields, and in your main content type you should create a new field, with Flexifield type, and then, define the it's a number of values of the field, and then, in the creation node form of your main content type, you\`ll have a field (kind of group), that will have multiple subfields, and depending of the number of fields defined, you should have multiple "groups of subfields".
> 5 votes

# Answer
In drupal 6.x this used to be accomplished by using cck-3.x which had support for multi-group which is the behavior you're asking for.

In drupal 7.x this can be accomplish by using the field\_collection module (http://drupal.org/project/field\_collection) - THis module also requires the entity module.

Once you have that module set up the UI is a little different than jut adding a field and groups.

You're going to want to go to you "Enterprise" content type and add the new Field Collection field (right now the only display is hidden).

Once you added the field collection field :-). You will now need to go to field collection configuration screen over at admin/structure/field-collections. Here you control the fields within your collection.

So you should now see the new field\_collection field you added, You will need to add the two new fields you want to that collection. In your case is the services and tasks fields.

Now you have a collection with two fields in it.

The weird thing is that in order to add collection right now you can't do it when creating the node. You will need to create the node and then you're provided with a "Add collections" link which allows you to add those "Services and Task".

Is a little wierd but it works. I'm sure in the future they're be more widgets available but for now thats whats available in drupal 7.

Hope this helps.
> 1 votes

---
Tags: 7, entities
---


title: View PDF as "node"/content

text:
# Question
Title: View PDF as "node"/content
I'm working on updating our current intranet to Drupal.

What I need to be able to do is take a PDF and load it in an iframe/node via Adobe Reader (or similar).

I can get something similar using (I think) CCK and FileViewer, but I'd like to remove the fileviewer wrapper and just have a standard PDF in browser.

Assume IE7/8 and Adobe Reader are installed.

**Update:**
Custom Formatter Module: Custom Module
Result of Module: enter image description here

***Update 2*** Using an Object per these instructions gives a more controlled block to build on. Ultimately I'll add a "You need Adobe installed from HERE to view THIS PDF" for the small chance of no pdf-viewer installed.

# Answer
You can do this using an `<iframe>` element within a custom formatter for a *file* field.

Field formatters control the output of a field: it's what lets you choose whether to display a generic link, the file name, etc. What you can do is create one that displays the PDF within an `<iframe>` element.

To do this, you need to (at a minimum) implement two hooks: `hook_field_formatter_info()` and `hook_field_formatter_view()`:

```
/**
 * Implements hook_field_formatter_info().
 */
function sandbox_field_formatter_info() {
  $info = array();
  $info['sandbox_formatter'] = array(
    'label' => t('Inline file'),
    'description' => t('Display the file within an iframe.'),
    'field types' => array('file'),
  );
  return $info;
}

/**
 * Implements hook_field_formatter_view().
 */
function sandbox_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  // Create the proper markup for each item within the field instance
  foreach ($items as $delta => $item) {
    $path = file_create_url($item['uri']);
    $element[$delta] = array(
      '#markup' => '<iframe src="' . $path . '"></iframe>',
    );
  }
  return $element;
}

```

Then you can create a file field, set it to only allow PDF, and choose *Inline file* as the display format. When you view a node with a PDF, you'll see the PDF within an `<iframe>` element.

The above is a very basic, minimal example: for an intermediate example that shows how to implement formatter settings, check out Dan Linn's tutorial. Also be sure to check out the relevant API pages, which includes sample implementations even more advanced than Linn's:

As an aside, it should be noted that there are a couple of related modules:

* Iframe: creates an `<iframe>` element formatter, but it hasn't been ported to Drupal 7 yet.
* Custom formatters: claims to allow the creation of custom formatters without needing to create a custom module
> 2 votes

# Answer
If you want to open the PDF in browser window and Adobe Reader + plugins are installed then just use CCK to implement a FileField and display it as "Generic File". The browser will handle opening it automatically. No Drupal magic or skills required...
> 0 votes

---
Tags: 7, files
---


# Question
Title: How can I collect data on authenticated versus anonymous traffic?
One of the important metrics I miss while planning for performance optimization is the type of traffic my site is receiving. What are the ways for collecting data about the type of traffic? I am mostly interested in anonymous versus authenticated requests.

# Answer
> 3 votes
I think the google analytics module does this out of the box.

---
Tags: 7, performance
---


# Question
Title: How to write a module that provides its own content-type using CCK?
I have to write a module that provides its own content type. In the drupal-documentation there is a guide for that; yet, I would have to deal with the CRUD logic inside of my module. I thought I could use CCK to create my new content-type with its fields inside of `hook_install();`. But I couldn't find any guides on how to do that.

Can anyone give a short example or provide a link to some decent guide? That would be awesome.

# Answer
> 4 votes
CCK includes a module named "Content Copy." Enabling that will give you an export tab in the edit section for each content type. That tab will give you code you can copy into a file within your module. If you save that file to /cck/\[type-name\].cck and set values for $type\_name and $module\_name, you can use this code in your hook\_install() to add the content type:

```
  $path = $_SERVER['DOCUMENT_ROOT'] . base_path() . drupal_get_path('module', $module_name) . '/cck/' . $type_name . '.cck';
  $content_type = file_get_contents($path);

  $form_state = array();
  $form = content_copy_import_form($form_state, $type_name);

  $form_state['values']['type_name'] = '<create>';
  $form_state['values']['macro'] = $content_type;
  $form_state['values']['op'] = t('Import');

  content_copy_import_form_submit($form, $form_state);

```

# Answer
> 5 votes
If you goal it to create your own content type, but don't want to deal with the hassle of CRUD, you could use features. It's designed for doing stuff like this.

CCK doesn't actually handle creating new content types, that is part of the node module (Drupal core). If you want to add a node, as if it was done through the interface and don't want to use features you should use `hook_node_info`:

```
/**
 * Implementation of hook_node_info().
 */
function module_node_info() {
  $items = array(
    'activity' => array(
      'name' => t('Name'),
      'module' => 'node',
      'description' => t('Description.'),
      'has_title' => '1',
      'title_label' => t('Title'),
      'has_body' => '1',
      'body_label' => t('Body'),
      'min_word_count' => '0',
      'help' => '',
    ),
  );
  return $items;
}

```

Setting node to be the owner of the node type lets it handle CRUD etc.

# Answer
> 4 votes
Creating Custom CCK Fields is useful to understand how to create custom CCK fields, widgets, and formatters; the example code should be enough to let you start.
What is the Content Construction Kit? A View from the Database is an introduction about CCK for Drupal 5, but it is still valid for Drupal 6.
Creating a custom compound field for CCK is another interesting article that explain how to create a CCK field that uses more than one form field for its input.
Programatically creating a CCK field in Drupal 6 explains how to create a field from code, for example in the installation code of a module that needs to add a specific field for a content type.

# Answer
> 2 votes
Your best reference will be to take a look at the Examples module.

---
Tags: 7, entities
---


# Question
Title: How to display a table view and an add/edit form on the same page?
I'm trying to build a page in my site where users can create a new project (fill out a few text boxes to give the project a title/description), see a list of all of their projects, and edit any of those projects.

I've created a new content type called "Projects" that includes all the text fields needed for creating a new project. And I've figured out how to use Views to display a list of user projects. I've tried to display these 2 elements together using Panels, but that means I need to create a new Variant for both the Node View and the Node Edit pages, which feels clumsy in terms of development. And the end result on the web site is 3 slightly different pages (one to create a new project, one when you click on a particular project to view it, one when you edit the project). But ideally, it would feel like one slick page.

Am I taking the right approach with using Panels, or is there another module or approach that is better?

# Answer
Hey Erin, certainly a good way to build customized pages is use Context module instead of Panels... (Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context. Link: Context).

In addition of that, you can create a block (be sure to have PHP Filter enabled), and include the following code.

For a existing node edit form:

```
//you should have your nid (May be loaded by a custom arg or even a given GET variable)
$nid = 99;
$node = node_load($nid);
//load needed file from node module
module_load_include('inc','node','node.pages');
//load node edit form
$form = drupal_get_form($new_node->type . '_node_form', $node);
//print the form you have loaded
echo($form);

```

In case you want to load a fresh node add form, instead of loading a node with node\_load, you should create a stdClass object, and give the type name just as bellow:

```
//load the current user info
global $user;
//empty object for node
$new_node = new stdClass();
// your machine name content type
$node->type = 'page';
// set the author for the node to be created
$node->name=  $user->name;
//load needed file from node module
module_load_include('inc','node','node.pages');
//load node edit form
$form = drupal_get_form($node->type . '_node_form', $node);
//print the form you have loaded
echo($form);

```

Actually it may not be the best way to do that, but certainly is a functional method.
> 1 votes

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


title: hook_nodeapi() argument?

text:
# Question
Title: hook_nodeapi() argument?
hook\_nodeapi() only has four arguments, but the function `taxonomy_nodeapi($node, $op, $arg = 0)` can have an additional parameter, `$arg=0`. Why?
`$node` is not passed by reference. Why?

# Answer
I'm not sure how you're counting, but hook\_nodeapi() has 4 arguments, as you said, while taxonomy\_nodeapi() has only 3. How they are named is totally irrelevant, only the amount and order counts. PHP doesn't have named arguments, you could also name them in your hook like this: `yourmodule_nodeapi($wathever, $you, $want = 0)` and it would work. There is however no reason to do it, it only has the potential of confusing someone. :)

The only important part is here is that the third and fourth argument are optional and must have a default value, because they are not passed for every `$op`.

About `&$node`, that's not so nice, but not a problem. The `&` can be left out, which means that `$node` is not by reference (in PHP4, that is) but it seems that `taxonomy_nodeapi()` doesn't need that. The other way round would be a problem in PHP 5.3 (adding a `&` here when PHP doesn't expect one).
> 6 votes

# Answer
The taxonomy\_nodeapi is a implementation of hook\_nodeapi, so, it's supposed to support all available arguments. If you are implementing this hook in your custom module, be sure to check all supported arguments and its functionality.
> 1 votes

# Answer
On your point about &$node and $node argument - they are not quite the same.

Although they do represent the node itself the presence of the ampersand (&) in the first argument means that it had been passed '**By Reference**', i.e. any changes made to the node object in your module/function will be preserved.

The argument without the ampersand has been passed '**By Value**' so while you can read any of the node values, you can't make any changes to the node itself (well you can but they will not be preserved outside of your module/function)

Also `$arg=0` is a default argument, if you do not provide a value for this then it will default to the value specified - in this case zero.
> 1 votes

---
Tags: 6, hooks
---


title: How do I use hook_nodeapi()?

text:
# Question
Title: How do I use hook_nodeapi()?
I found an example on the Internet: Transform CCK field to body content.

```
function riddle_nodeapi(&$node, $op, $teaser, $page) {
  if ($node->type == "historia") {
    switch ($op) {
      case 'view':
        if ($node->field_svar[0]['value'] != "" AND $page == 1) {
          $svar = '<form><fieldset class="collapsible collapsed">
            <legend>Svar</legend>
            <div>'.$node->field_svar[0]['value'].'</div>
            </fieldset></form>';

          $node->content['riddle'] = array(
            '#value' => $svar,
            '#weight' => 0,
          );

          if (is_array($node->content['field_svar'])) {
            unset($node->content['field_svar']);
          }
        }

        break;
    }
  }
}

```

I don't know what the purpose of the following code is. Why should I use it?

```
 if (is_array($node->content['field_svar'])) {
   unset($node->content['field_svar']);
 }

```

What's the use of the `hook_nodeapi()` arguments `$a3` and `a4`?
If in the case of a view operation, I set the $a3 to true or 1, will the body only effect on the node teaser? Am I right?

# Answer
The following code is used because the module is already rendering the CCK field, and wants to avoid that Drupal renders the content of that field.

```
if (is_array($node->content['field_svar'])) {
  unset($node->content['field_svar']);
}

```

Without using that code, the field content will appear twice: once inside a field set, and once outside that field set.

The last parameters used for `hook_nodeapi()` are described from the documentation as:

> $a3
>
> * For "view", passes in the $teaser parameter from node\_view().
> * For "validate", passes in the $form parameter from node\_validate().
>
> $a4
>
> * For "view", passes in the $page parameter from node\_view().

It means that, when the operation is "view," `$a3` is `TRUE` when Drupal is displaying the teaser (and `FALSE` when Drupal is displaying the full node content), and `$a4` is TRUE when the node is being displayed alone in a page (and `FALSE` when the node is being displayed together other nodes in the same page).
To understand the meaning of the different values given to `$a4`, `$a4` is `TRUE` when Drupal is displaying, for example, the page http://example.com/node/1 (where the same page displays only a node); its value is `FALSE` when Drupal is visualizing the front page and there are more than one node promoted to the front page.
> 4 votes

---
Tags: 6, hooks
---


# Question
Title: How would I get taxonomy info using the taxonomy term ID, in order to theme it?
I need to be able to extract a taxonomy array and use it to create links.

# Answer
taxonomy\_term\_load() looks promising.

> Return the term object matching a term ID.
>
> Parameters
>
> `$tid` A term's ID
>
> Return value
>
> A term object. Results are statically cached.
> 7 votes

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


# Question
Title: Getting WSOD for non-LDAP User with Domain and LDAP modules enabled
I am using Domain and LDAP modules on Drupal 7, and upon login as a non-admin non-LDAP user, e.g., "author01", I get a blank screen. Upon viewing source on said blank screen, I can see the HTML for the "Welcome to your new Acquia Drupal website!" page—it is just not rendered in the browser (Safari, Chrome, FF).

When logged in as admin, I can switch to "author01" using the "Switch User" block of the Devel module without issue and the Welcome page appears without issue.

The LDAP module is enabled using "mixed mode authentication," Drupal first and LDAP second; LDAP user are able to login without issue, while Drupal-only users get this blank screen upon login. The Domain module is enabled, and but I haven't added any new domains.

I suspect this issue first started *after* I installed the domain module *and* "Rebuilt Permissions." Mixed mode authentication was working fine before that.

I've tried various combinations of enabling/disabling and installing/uninstalling the LDAP and Domain modules, clearing cache, rebuilding permissions, and the only time the "author01" user can login is when LDAP authentication is disabled. I've tried enabling error reporting based on Drupal's WSOD page, but the blank pages continue to appear. Apache access and error logs are fine.

Under reports (admin/reports/dblog), I see these log messages (read it bottom up):

```
ldap_authentication 04/22/2011 - 11:01  Error: users found with uid=author01 under dc=gwu...
ldap_authentication 04/22/2011 - 11:01  author01 : Success at connecting to devldap
ldap_authentication 04/22/2011 - 11:01  author01 : Trying server devldap where bind_method = 1
ldap_authentication 04/22/2011 - 11:01  author01 : Exisitng Drupal User Account not found. ...
ldap_authentication 04/22/2011 - 11:01  author01 : Drupal User Account found. Continuing on...
ldap_authentication 04/22/2011 - 11:01  author01 : user_load_by_name(author01)

```

The user "author01" definitely exists in the "user" table, has a role ("Content Author"), and the role has permissions.

So I guess I am stumped here, Do you have any idea on what else I can try to troubleshoot and fix this?

# Answer
Of course, shortly after I post this, I am able to fix it by deleting and recreating the entry for the ldap server. Hope this helps someone else save lots of time (-:
> 1 votes

---
Tags: 7, users, authentication-authorization
---


title: GMap Module issue

text:
# Question
Title: GMap Module issue
I am using the GMap Module for Drupal 7 along with Location, with Node Locations enabled.

I have added a simple location field in my article content type, and enabled the location block to be shown in main content type.

During the creation of an article, when I enter the location values as text fields (e.g. countries, cities) without any latitude and longitudes, the map is not displayed on the article node page.

However, if I do enter some latitude and longitude values, either manually or using Google Maps, then the map is shown in the article node.

Does anybody have any idea why this happens?

# Answer
> 3 votes
I could be wrong but I think this is to do with the Geocoding settings, i.e. resolving the location from an address/postcode.

I played with the modules a week or so ago and found the Geocoding for the UK was not possible.

Try looking in the configuration options for the Location module, in particular the Geocoding tab. You'll see that the United Kingdom has no settings available so in my case I'll have to resort to requiring the user to use the map itself to specify the location.

---
Tags: 7, google-maps
---


# Question
Title: How do I get a node, or a taxonomy term URL knowing the node ID or the taxonomy term ID?
I need to render the full URL from a taxonomy term ID.

# Answer
> 5 votes
The generic way is this:

```
$uri = entity_uri($entity_type, $entity);
$url = $uri['path'];

```

So for a node, `$entity_type` would be 'node', and `$entity` would be the fully loaded node object.

Taxonomy terms are also entities in D7, so the syntax would be similar.

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


# Question
Title: What are the ways/strategies to maintain Drupal sites a over period of 10-15 years?
We have started using Drupal as a PHP programming framework (and not just as a CMS). As result, we have many projects running on Drupal (6 or 7).

Typically, after 2-3 years a project gets over and no further development is done on that project. Then, we put that project into a maintenance or dormant mode.

The problem is that at the end of a project, there is hardly any money left for actively maintaining (e.g updating modules/core for security fixes) that project for over a period of say 10 years. And, there is no way that we can ask for maintenance money for a project (this is a sad fact).

So, we were brainstorming what would be the way to maintain Drupal sites **securely** for say a period of at least 10 years.

Some ideas were:

1. Convert entire Drupal site into bunch of static pages using some tool (I suspect this might break lot of interactive functionality in Drupal)
2. Lock down write access to MySQL database
3. Run dormant Drupal based sites in a Virtual Machine
4. Block all input fields on a Drupal site including login functionality (i.e make all content publicly accessible)

I also expect that in a period of 10 years following things might happen:

* A server's hardware might be upgraded
* A new PHP version might be installed
* A new MySQL database might be installed
* A server's OS might not be supported by a vendor for security updates
* Certain Drupal modules may not be supported or may get deprecated by an other module
* In the worst case, the required PHP or MySQL versions itself may not be supported by the community

What are the ways/strategies to securely maintain (i.e. keep them running) dormant Drupal sites for a very long period?

# Answer
Like you mentioned there are many moving parts about Drupal that can require maintenance, so your strategy should be to **remove** as many dependencies as you can within your requirements.

If it is not a requirement that your Drupal sites continue as dynamic systems where content can be created, updated, or deleted then you should remove MySQL and PHP by generating static files. There is good documentation for creating static archives of a Drupal site at http://drupal.org/node/27882.

Since you mentioned putting the site into a "maintenance or dormant mode" it sounds like a static solution would be the best for you.

If you require the continual functional use of the site you could consider moving the site to a managed solution. Managed hosting providers can take care of the web and database server, but for further management of the Drupal code you could consider a service like http://drupalgardens.com.
> 6 votes

# Answer
This question is a bit absurd. Drupal itself is barely 10 years old--how many Drupal 1 sites are still running? How many sites are there today, running PHP 1.0 (released in 1995, 2.0 in 1997)? What hosting providers running PHP 1.0 in 1996 are still in business today, dutifully serving those abandoned projects on un-upgraded hardware and software to whomever is still interested?

The internet is not static, nor is the technology it runs on. The best bet of finding sites from 1996 that were abandoned, is to use the Internet Archive Wayback Machine on http://web.archive.org.

I would tell you to completely export everything to HTML and keep it static, but even this is no guarantee (the *first* Apache HTTP server was only a year old in 1996).
> 3 votes

# Answer
As for the DB Layer, MySQL should be upgraded to keep pace with current technology.

As a MySQL DBA, I can see MySQL changing as fast as Oracle can push it. MySQL 5.0 has reached EOL and MySQL 5.1 is soon to follow. You would want support for the latest release MySQL to always be there for you. Of course, you have the MySQL Community to lean on. You also have Percona, who makes tight, faster running, and performance-blinding binaries of MySQL. You even have the up-and-rising company SkySQL, who supports everything MySQL back to 3.23.58.

I would continue the upgrade path of MySQL by means of using another dev server to test the functionality of the Drupal against the MySQL upgrade. Once done, upgrade the "production" dormant MySQL for Drupal.
> 1 votes

# Answer
Why not migrate the sites to a cloud server, and then write the entire server+OS+Drupal\_stack+entire\_site to a file. As a cloud server, the entire thing is virtual anyway, so the versions of all your software, OS and everything dependant on everything else is wrapped up in a nice shrink wrapped, forever executable file. 'New users' could have a private instance of the site where they do whatever they want with it, because one can always return to a new instance of the original/official backup. You could have a version of the site with 'original user data' as well as one with 'current user data', which could be interesting depending upon what data the sites hold (after 10-15 years).
> 1 votes

# Answer
Actually, there's not a safe way to do this automatically...

bjeavons had exposed good ways to keep the site static, but if you intend to keep the site fully functional in a usual environment, certainly, the best way, is keeping your environment as is, 'freezed', and you will have your site functional for more than 10 years. Any changes in your server, you must be sure to not impact in your site functionality, and if so, you should have an action plan, and this would only be possible creating another server layer, and you should test everything over there before applying it in production to guarantee its fully functionality.
> 0 votes

---
Tags: security, upgrading, maintenance-mode
---


title: Calendar module

text:
# Question
Title: Calendar module
I have a content type ("events") that has a date field inside it ("field\_e\_date"); I want to show on a page some nodes of this content type in calendar format.

Assuming I create a view of style calendar type, I want to display on http://example.com/user/uid 5 events added by this user.

Which exact arguments do I need to pass to the view?

# Answer
> 4 votes
Download and install FullCalendar. Create a new block view with the Format: FullCalendar, and the Style: FullCalendar (Fields).

Add the date field you want to display, set the pager to only display 5 events. Set the Contextual Filter (argument) to User: ID, provide a default value of "User ID from URL".

Save the view, and place the block on the user page. Should work fine.

---
Tags: 7, views, datetime
---


title: How to show "incoming search terms"

text:
# Question
Title: How to show "incoming search terms"
a lot of blogs have a feature to show the "incoming search terms" - it's great for SEO. I looked up and down drupal.org but couldn't find a module.

Any recommendations on how to tackle this (I'm new to D7 and haven't built a module yet).

# Answer
It looks like the Google Analytics Reports module is very close to what you need, except it's currently only for Drupal 6. There is an issue open about porting it to Drupal 7, but it doesn't look very active.
> 1 votes

---
Tags: search, 7
---


title: Template name for the user login block

text:
# Question
Title: Template name for the user login block
I have been trying to create a template to control the user login block given in Drupal 7. I've referred to the template suggestions documentation page and have tried block--user-login.tpl.php, block--user.tpl.php and am getting no love.
What is the template name for the user login block?.

# Answer
Since I answered this in IRC, I'll rewrite the answer.

block--user--login.tpl.php

The easiest way to find all of the possibilities for naming template files is to put `print_r($variables['theme_hook_suggestions']);` at the end of your theme's `template_preprocess_HOOK()`. Doing so works great for block, node, page...
> 12 votes

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


title: Block on specific pages and node types

text:
# Question
Title: Block on specific pages and node types
I'm trying to make a block display on a specific page and inside a node type; I got this code from drupal.org, but I keep getting this error.

```
Warning: array_flip() [function.array-flip]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 178 of /home/content/45/6861545/html/includes/entity.inc).
Warning: array_flip() [function.array-flip]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet() (line 354 of /home/content/45/6861545/html/includes/entity.inc).

```

This is the code I used.

```
$match = FALSE;
$types = array('middle_content' => 1);
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load(array('nid' => $nid));
  $type = $node->type;
  if (isset($types[$type])) {
    $match = TRUE;
  }
}

if (substr($_SERVER["REQUEST_URI"], 0, 10) == '/test'){
  $match = TRUE;
}

if (substr($_SERVER["REQUEST_URI"], 0) == "/node/add/middle_content") {
  $match = TRUE;
}

return $match;

```

# Answer
> 3 votes
To actually fix that error, see my answer to a stackoverflow question.

However, in that case, your code can be simplified *a lot* using menu\_get\_object():

```
$types = array('middle_content' => 1);
if ($node = menu_get_object()) {
  if (isset($types[$node->type])) {
    return TRUE;
  }
}

```

And anyway, you should avoid PHP in blocks etc (See What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?), check out Context. It allows you to configure your blocks (among other things) for conditions exactly like this without having to write code. It is also much faster.

# Answer
> 0 votes
The actual error is occurring because `node_load()` either takes an integer or a numeric array of nids, not an associative array. `$node = node_load($nid);` is perfectly valid.

That said, Berdir's answer is a better solution.

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


# Question
Title: Two columns on frontpage with a CCK form and a node list
I want to show a simple frontpage that contains a content creation form (cck) on the left side and a list of nodes on the right side. With a head and a footer, the page looks like this:

I have looked into doing this with the Panel module, but it seems like overkill and I don't think it plays well with the grid layout I use.

I have also looked on doing this with the Views module and the Context module, but I don't really understand how I can execute the code for rendering the content creation form with this approach.

A third solution is to override the template for the page-front and hard code the rendering there, but a drawback would be that I then need to maintain multiple page templates.

So what is a good solution for this do you think? I would like to involve as little complexity as possible and my head is already spinning with all these modules for such an apparently simple problem.

Appreciate guidance from someone who is fluent with View, Context, CCK and Panels.

# Answer
Administering panels has a huge overhead, however, since panels are highly cached there is actually a performance boost to use them over plain blocks. It's discussed in this article, Assembling Pages with Drupal.

If this is some type of survey or questionaire you can make the node edit form the front page by using using the site configuration feature assigning the font page path. With Views you then can create two blocks that you use to show on the right column in either the block administration page or the panels administration page. However, for surveys the standard is to use the Webform module.
> 1 votes

# Answer
You could create two block regions in page-front, and add the form and the list of nodes as blocks.
> 0 votes

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


# Question
Title: The Calendar module doesn't recognize fields
I created a content type "events", with a date field and other normal settings.

I am trying to use the Calendar module to create a calendar on my Drupal site, but I am facing an issue.
When I try to edit the basic calendar, and change its argument from `date:node` (node updated time), then in the list of date\_fields it does not show the field that I had created above. It only shows the following fields:

* Node: Last comment time
* Node: Post date
* Node: Updated date
* User: Created date
* User: Last access
* User: Last login

I have tried this again and again by recreating my content type, or by disabling/enabling the Calendar module, but it does not seem to work. I am using Date 7.2.x and Calendar 7.2.x.

# Answer
> 2 votes
I installed Calendar 7.x-2.x-dev, Date 7.x-2.x-dev, and Views 7.x-3.x-dev; then I created a "Test" content type to which I added a date field ("Start date").

When I edited the Calendar view, and added a new argument for the view (view arguments are called "contextual filters," in Views 7.x-3.x-dev), I followed the following steps:

* I filtered out the list of arguments to show only the ones defined from the Date module; between the two argument types, I selected "Date: Date (node)."
* On the settings page that Views shows after I selected the argument type, I selected the date field I added to my content type.

---

If you select "Date: Date (users)," then you will see all the date fields that are associated with users, as in the following screenshot.

Still, the field I added to my content type is visible in the list of fields shown in the settings page for the view argument.

The issue you are seeing is probably caused by compatibily problems between Date, and Views. I would try using Views 7.x-3.x-dev.

---
Tags: 7, views, datetime
---


# Question
Title: db_affected_rows() return "1" when the query is wrong
I have a query like `UPDATE user SET creator = 'creator'"`. The "user" table has not the "creator" column, so `db_affected_rows()` shoud return −1, not 1.

Why?

**Update**: `mysql_affected_rows()` returns -1 for this query. I created a "creator" column (unique); after I update the user table, I get the error "User warning: Duplicate entry," but `db_affected_rows()` still returns 1.

# Answer
> 3 votes
**Edit:** db\_affected\_rows() returns an unexpected value because watchdog is turned on. I watched to see if there was another query after the one I ran and before my db\_affected\_rows() call, and sure enough:

> INSERT INTO watchdog (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (1, 'php', '%message in %file on line %line.', 'a:4:{s:6:\\"%error\\";s:12:\\"user warning\\";s:8:\\"%message\\";s:104:\\"Unknown column 'name2' in 'field list'\nquery: UPDATE users SET name2 = 'a'\\"; \[...\]

So, db\_affected\_rows() is returning 1 because watchdog is logging an error. Thus, the proper way to see if a query had an error or not -- and count the rows affected if it *was* successful -- is:

```
$result = db_query("UPDATE users SET name2 = 'a'");
if ($result) {
  printf("Records affected: %d\n", db_affected_rows());
}
else {
  print "Query not successful";
}

```

Hope this helps!

---

*Original answer for posterity:*

I'd have to see the code around your query. Try running this:

```
<?php
function db_affected_rows() {
  global $link;
  return mysql_affected_rows($link);
}

$link = mysql_connect('localhost', 'root', 'root');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('d6.devl');

/* this should return the correct numbers of deleted records */
mysql_query("UPDATE user SET creator = 'creator'");
printf("Records affected: %d\n", mysql_affected_rows());

printf("Records affected: %d\n", db_affected_rows());

```

I did and it worked alright:

> $ php -f test.php
>
> Records affected: -1
>
> Records affected: -1

# Answer
> 1 votes
Try to reproduce that outside of Drupal with just `mysql_query()`, `mysql_affected_rows()` and so on.

This might be an issue with your PHP version or something like that. Drupal just passes the call forward, it doesn't do anything ony it's own.

---
Tags: 7, database
---


# Question
Title: CCK fields don't appear on the "node add" form for authorized user
I would like to allow logged-in users to create nodes, and I gave them the permission to create "some\_content," but on "add node form" users have only one field, which is for custom node title, without any other CCK fields that this content type have. Could anybody tell me how to add those fields to this form?

# Answer
Most likely you have a module enabled that adds access control for each field. Check your permissions setup.
> 3 votes

# Answer
Check the "Display fields" link on your CCK type. Did you make sure to display them?
> 1 votes

---
Tags: 7, entities, users
---


# Question
Title: How to output all taxonomy field values on a node in views?
How can I display all field values that are on the taxonomy terms that are applied to a given node?

So say I have the following Vocab defined:

Vocab name:Fruit Description:Fruit Categories w/ codes Field: fruit\_code

And I add the following terms:

tname:Apple fruit\_code:appl tname:Orange fruit\_code:orng tname:Pine Apple fruit\_code:pin\_appl

Now.. I can apply a field to my view that will output all the tax termnames associated with the nodes that are returned: ie. "Apple, Orange, Pine Apple"..

But when I add the relationship for tid to the view and then try outputting the fruit\_code field.. I get duplicate nodes returned, one for each term applied to the node. How can I get the fruit\_code to oupt in the same manner as the termnames in my view w/o having duplicate nodes displayed??

# Answer
> 1 votes
You can use the views distinct mode.

Drupal 7: Query Settings \> distinct Drupal 6: Distinct

Either that or hook into the view and do some extra processing through a custom module.

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


title: Tagging separate files

text:
# Question
Title: Tagging separate files
I wonder if, and how, the following would be possible to tag each uploaded file with one or more tags and show these files filtered on their tag(s).
I know it's possible to do this for nodes but have not found a way to tag single files.

The purpose of this would be the creation of an image bank in which the administrator can upload images or files (pdf, zip) and define each image/file as being, for example, 300dpi, print, high resolution, color, black & white, etc.

# Answer
In both Drupal 6 and Drupal 7 files are not used independently. Most often, fields are used through a file field, on either a node (D6 or D&) or an entity (D7).

To do the above, I would suggest using a file field on something, that holds all the info about the file. You could add things like title, teaser text, description in addition to tagging. For Drupal 6 the only option you have is to use nodes, for Drupal 7 you could use nodes or create your own entity in a custom module. The easiest thing will be to use nodes, as you wont need to create a lot of functions for editing, loading, rending... the entity. Nodes are probably also a good match in this case since the files are content on your site.

Another plus doing this, is that you would be able to use the Views module, and create different galleries or list of image files.
> 1 votes

---
Tags: taxonomy-terms, files, media
---


title: Creating sub-fields within a field

text:
# Question
Title: Creating sub-fields within a field
I am using the profile2 module in Drupal 7. I have created a field using the check box/radio widget that has 2 options and both options can be checked. How would I be able to create a sub-field that will show another checkbox/radio widget with options depending on what was checked in the main field?

# Answer
For Drupal 6, there was Conditional Fields.

There is no Drupal 7 version yet, but there is an issue which links to field conditional state which at this point is only a sandbox project but seems to be widely used already.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Is there a module that provides perpetual results on scroll?
Let's say you have a page that is a view, and the view is set to page at 50 items. You have 150 items, so you have three pages. Is there a module that will load additional results, like 30 more, when the user scrolls towards the bottom?

The effect is that you don't need to use the pager, as new results appear automatically.
The effect I want to get is the one used in this site.

Is there a module that will do this for a view?

# Answer
> 3 votes
Found it. There are two (quotes included are from their project pages):

* Views Infinite Scroll (Requires Views 3):

> ... provides pluggable pagers that enables Views infinite scrolling (autopaging, depaging, endless pages ... you name it) by using jquery.autopager plugin. Using this module with views page display will load another page whenever the user reaches bottom of the page.
* Views Infinite Pager:

> ... implements "infinite pager" (earlier called "sliding pager") functionality for Views. Infinite pagers open the next page via Ajax below the current page, each sub-page expanding the page vertically downwards. For a well-known infinite pager example, visit a stream on Twitter.com.

---
Tags: 7, views, ajax
---


title: How can I commit changes to a theme?

text:
# Question
Title: How can I commit changes to a theme?
I worked on Omega-7.x-3.0-alpha1 and added some fixes to fluid style sheets in rtl mode.

How can I commit them to the drupal.org repository?

# Answer
Unless you are one of the maintainers or have been explicitly granted write access to the repository, you will not be able to push your commits to the "official" branches.

The recommended route to contribute is the following:

* Checkout the git repository for the correct branch (instructions here)
* Create patch with your changes (instructions in the above link)
* Search for a relevent issue or create a new one in the project's issue tracker on Drupal.org
* Submit the patch in the issue
> 4 votes

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


# Question
Title: Relationship between node_access gid, roles and workflow
If using workflow, what database table.field does the node\_access.gid map to? Does it represent a role, does it represent a workflow sid (state id), or something else?

Example:

```
+---------+------+-----------------+------------+--------------+--------------+
| nid     | gid  | realm           | grant_view | grant_update | grant_delete |
+---------+------+-----------------+------------+--------------+--------------+
| 1234561 |    4 | workflow_access |          1 |            1 |            1 |
| 1234562 |    5 | workflow_access |          1 |            1 |            1 |
| 1234563 |    6 | workflow_access |          1 |            1 |            1 |
| 1234564 |    7 | workflow_access |          1 |            0 |            0 |
+---------+------+-----------------+------------+--------------+--------------+

```

EDIT: After @Berdir's excellent response I wrote the query below to analyze the relationship between node\_access.gid, workflow\_access.rid, and role.rid:

```
# Establish relationship between workflow, roles, gids, etc.
SELECT
    r.name AS role,
    r.rid AS w_role_rid,
    wa.rid AS and_workflow_access_rid,
    ws.state AS has_access_to_state,
    wa.sid AS with_state_sid,
    IF(ws.status=1,'YES','NO') AS which_is_enabled,
    wa.grant_view, wa.grant_update, wa.grant_delete
FROM workflow_access wa
    LEFT JOIN role r ON wa.rid = r.rid
    LEFT JOIN workflow_states ws ON wa.sid = ws.sid
ORDER BY r.rid, wa.sid

```

If anyone notices any incongruousness with my query please comment so.

# Answer
Looking at the source (the function workflow\_access\_node\_access\_records()), it looks to be the rid, which is the role id. Additionally, it is also defined in workflow\_access\_node\_grants(), which returns the gid's for a given user. And that is the role id's for 'workflow\_access' and the user id for 'workflow\_access\_owner'.

There is also a {workflow\_access} table, that contains information about which role has which permissions for each workflow state. Based on that, the access grants for each node are then built.
> 2 votes

---
Tags: 7, workflows, users
---


# Question
Title: How to achieve a particular layout (view within a view, custom template, or ____)?
Say I had a site with travel destinations and I wanted to display a series of videos associated with each destination on a page below a description of the destination. The destinations and the videos each have their own node type.

Currently, the list of destinations is a view. Each video has a taxonomy term associated with it, that ties it to a particular destination. We use views arguments to pick up the taxonomy term from the URL and have the videos displayed in the side bar. However, we'd like to make it more clear that the videos are associated with a particular destination.

How can we best achieve the following layout?

```
+-----------------------------------------+
| +-------------------------------------+ |
| |                                     | |
| |               node 1                | |
| |                                     | |
| +-------------------------------------+ |
| +----------+ +----------+ +-----------+ |
| | video 1a | | video 1b | | video 1c  | |
| +----------+ +----------+ +-----------+ |
|                                         |
| +-------------------------------------+ |
| |                                     | |
| |               node 2                | |
| |                                     | |
| +-------------------------------------+ |
| +----------+ +----------+ +-----------+ |
| | video 2a | | video 2b | | video 2c  | |
| +----------+ +----------+ +-----------+ |
+-----------------------------------------+

```

p.s. - We're already using the Context module, if that helps at all (and consequently, we'd like to avoid installing Panels, since they serve similar purposes).

# Answer
A simple solution would be to use node reference on the destination node which reference video nodes. Then it's just a matter of theming to convert the node references (node ids) to videos.
> 1 votes

---
Tags: taxonomy-terms, views, theming
---


# Question
Title: Block caching when access-restricted modules are enabled
We have a module that creates a custom navigation block. It runs a metric ton of queries, and it's really affecting performance. (Note that I inherited this site; I did not write this code!)

We want to cache the block, but the built-in block caching (admin/settings/performance) is greyed-out, with a message below that says block caching is inactive when modules defining content access restrictions are enabled. We do have several modules that have access restrictions, and cannot disable those.

Is there any other way to cache the navigation block? I know about the BLOCK\_CACHE\_\* constants, but am assuming that the built-in block caching needs to be turned on, and that those constants modify the default behavior. If we can't turn on the built-in caching, what (if anything) can we do?

# Answer
Assuming that the module that creates the block and is this performance heavy is a custom module, a simple solution would be to cache the output of the block from within the block. Take a look at the `cache_set` and `cache_get` functions on http://api.drupal.org
> 5 votes

---
Tags: blocks, caching
---


title: Changing the registration form

text:
# Question
Title: Changing the registration form
I would like to revise the default new user registration form in Drupal 7. Rather than to requst "username", I want to request "full name" with helper instructions to enter the text "username is your full name as you would normally use it."

There may be some other minor formatting changes I would like to make as well.

I cannot find an admin menu item to access anything relating to this question. And I am unable to locate a file within any director that has any text that would indicate it is the source for the new user registration form.

I realize this is a bit unconventional, however it is useful for our needs. I am aware of a module that allows the input of First Name / Last Name, but in processing it changes the input to first initial/lastname, ie Tom Thumb = username of "tthumb". The module "Realname Registration" would be just what I am looking for if it would only translate the username the same as the input.

That wouldn't necessarily solve the other formatting edits, but I would be very happy just to be able to manually edit the registration form help text under the username field, instructing the new user to register using thier real name.

Thanks for any help that you can provide.

J.M.

# Answer
The easiest way is to create a custom module and use hook\_form\_alter():

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'user_register_form') {
    $form['account']['name']['#title'] = t('Full name');
    // perform other changes here
    // var_dump() or krumo() the contents of $form to see what you can change
  }
}

```

If you prefer you can also a variation of hook\_form\_alter to target the form specifically instead of having to do an if

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['name']['#title'] = t('Full name');
  // perform other changes here
}

```
> 13 votes

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


# Question
Title: What is the fastest/simplest way to add/manipulate PHP on a page?
As a PHP developer familiar with MVC frameworks, I am having some difficulty figuring out Drupal.

I like the block setup. I am looking for some simple step-by-step guide to:

1. Add a block with my own PHP code.
2. Alter the html/php of other blocks.

Failing that, I would like to see some code which does these things.

Here is what I've been trying to do, more specifically:

1. There is a button. When it is clicked a DB query is executed.
2. Hide the "create new account" link on the login dialog. **No account for you!**

# Answer
> 2 votes
You are in fact asking four questions here.

1. As jhedstrom said, you need to use the hook\_block\_info() / hook\_block\_view() hooks. A quick google search pointed to to this example: http://www.summasolutions.net/blogposts/how-create-basic-block-code-new-drupal-7
2. You can use the hook\_block\_view\_alter() or hook\_block\_view\_MODULE\_DELTA\_alter() hooks.
3. You can find detailed information about how to create a form in drupal in the quickstart guide. Note that this is for Drupal 6 but works the same way in Drupal 7 for the most part.
4. This does not require any code at all. In fact, doing this with code is doing it the wrong way. Instead, you can disable account registrations by visitors at Configuration \> Account settings, set "Who can register accounts?" to Administrators only.

---
Tags: 7
---


# Question
Title: Why does not hook_menu_link_alter() work?
i want to expand my theme's primary links, so I put the following code in my custom module.

```
function mymodulename_menu_link_alter(&$item, $menu) {
  if ($item['menu_name'] == 'primary-links') {
    $item['expanded'] = 1;
  }
}

```

In page.tpl.php I used `print theme('links', $primary_links)`, but the primary links didn't expand. Why?

# Answer
Not really a complete answer, but hook\_menu\_link\_alter() is not called when the menu is rendered; it is called when the menu item is saved. Just an FYI.
> 19 votes

# Answer
Try after flushing the menu cache. For that, the Devel module will help you.
> 2 votes

# Answer
Start with simple things first. Use the Menu Example in the Examples Project. The menu\_example\_menu\_link\_alter() changes a link... You can use it there and experiment easily.
> 2 votes

---
Tags: 7, routes
---


# Question
Title: Searching for a general approach for passing custom lists of node IDs as an argument to Views 3.x
I need often to exclude (or limit to) a custom list of nodes from a view. I used to enter the PHP logic directly in the php argument code text area, but this is getting difficult to mantain. I would like to store the logic in a module or template.php.

What I need is a general approach for returning a list of nids (nid1+nid2+nid3...) in the php argument code of the view. I have tried using the approach described **here**, but I can make it work only for block displays, not for page displays.

For example, I have a content type where nodes can arbitrarily be restricted to authenticated users using the Content Access module per-node settings. I need to display in a view only those nodes, excluding the ones that are visible to the anonymous users. Since there is no filter for this in views, I have built a simple function to retrieve the node IDs and store them in a variable (nid1+nid2+nid3...).

I am struggling to find out where to put this logic (`theme_preprocess_views_view()`, custom `theme_preprocess_func()`, `mymodule_preprocess_func()`, etc.) in order to be able to use this variable in any view PHP argument code.

TL;DR: I need a general approach for returning a list of nids (nid1+nid2+nid3...) in the PHP argument code of the view, saving the php logic in a module or theme.

# Answer
What you really want is a an "argument default plugin". There are some availible in views itself, one is the php one, which you use already.

It's really not that hard to write. You need the following hooks for it:

* hook\_views\_api
* hook\_views\_plugins

After this you have to create the plugin and most important write a function called get\_argument() which returns the arguments.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to interpret the code: module_invoke_all('user', 'logout', NULL, $user);?
How to interpret this line of code?

```
module_invoke_all('user', 'logout', NULL, $user);

```

Obviously, it logs out the current user, but how do the four arguments make it happen?

I read through the doc, but I can't find information about the four parameters.

Can anyone explain?

> From Documentation:
> `module_invoke_all()`
> Invoke a hook in all enabled modules that implement it.
> Parameters
> $hook The name of the hook to invoke.
> ... Arguments to pass to the hook.

# Answer
No, they don't log the user out. That is done by the call to `session_destroy()` in user\_logout().

That line only invokes the hook to tell other modules *that* the user was just logged out so they can react based on that.

The passed arguments are simply those that match the executed hook. Note that the Drupal 7 version is different from what you posted above, which is the Drupal 6 version.
> 7 votes

---
Tags: users
---


title: Where is the Administer menu?

text:
# Question
Title: Where is the Administer menu?
I can't find the "Administer" menu or it's members "Content Management" or "Site Building". I've tried disabling and re-enabling the core menu module, but still cannot see these menus. This is what I can see.

Any ideas why? Or a known solution?

# Answer
The menu structure has changed a bit from Drupal 6 to Drupal 7.

* Site building is now called structure, though modules is moved from it into it own top level menu item.
* Content management has been split up a bit and have items in content and structure.
* For administer you probably want the Configuration item.

Anyways try clicking around and I'm sure you'll find what you need.
> 8 votes

# Answer
The administer menu was an artifact of the convoluted menu structure we had in Drupal 6.

What you see in the toolbar is basically the “Administer” menu unfolded, with “Content management” named “Content”, and so on.

The admin menu items have been slightly rearranged, but hopefully the new structure will be more intuitive to new users.
> 6 votes

# Answer
The categories like "content management" and "site building" no longer exist, they have been replaced by the categories you see right there. These changes have been made to make the information architecture more intuitive for everyone and easier to understand for new Drupal users.

I too found myself searching for the familiar menu items when I first started using Drupal 7, but now that I've gotten used to the new structure, I must admit that (IMHO) it's more consistent and user friendly than in Drupal 6.

In other words: there is no "solution", but I'm confident that you can learn to love it.
> 2 votes

---
Tags: 7, routes
---


title: Grouped gallery content with Views

text:
# Question
Title: Grouped gallery content with Views
I have an gallery content type with a title-, image-, and text select list field. This content type is used for a gallery where the select list values works as a kind of category for the gallery(a bit like a taxonomy). Using Views I have gotten all the published values printed out group according to there select list values. However I would like to print out an headline above each of the grouped images. Like this:

headline1

item1, item2, item3...

headline2

item4, item5, item6...

The headline is one of the values from the select list field and the grouped items below is the content where this specific value is chosen from the select list field(during upload). Its easy to get stuff printed out and sorted using Views but it seems to be more difficult to get and headline in there.

Anyone know if this is possible, maybe using preprocess for views or views-view.tpl.php files? I have gotten this to work with the grouping feature for table layout, but would like to have it printed out in unformatted html instead.

# Answer
> 1 votes
This should already be happening. Which version of Views?

If, as you said, the headlines ARE the values of the select list, then they should be showing up above each group automatically.

In Views 3:
Under Fields, add the select\_list\_field and check "Exclude from display"
Under Style settings (unformatted), choose Grouping Field: select\_list\_field

It will group by the select list item, and display that select list item's name (ie, the headline) above the group.

---
Tags: 7, views
---


# Question
Title: I want to allow users to click "share this" on a page with an image, and then email that image as an attachment
I have a site that shows floor plans for houses. I want to allow users to share a floor plan via an email form where they can enter their email address and their friend's email address who they want to share with. Then when they enter their message and submit, the image of the floor plan will be attached to the outbound email from the server.

# Answer
> 1 votes
You can use the Send feature in the Printer, e-mail and PDF versions Module. It will allow your user to send the page as rendered in HTML, attached images, and custom messages.

# Answer
> 2 votes
If you are willing to write your own module, check out the mimemail module. Sending the mail is as easy as this:

```
mimemail($sender, $recipient, $subject, $body, $plaintext = NULL, $headers = array(), $text = NULL, $attachments = array(), $mailkey = '')

```

If you store the picture in a imagefield or filefield inside a node, you can put that field into the attachments array and send it.

---
Tags: webforms
---


title: Adding a CCK field with Rules

text:
# Question
Title: Adding a CCK field with Rules
I'm trying to use Rules to populate a CCK field - a user reference when they flag a node. It basically works, but if there's already a user reference it overwrites it instead of adding another. That's not exactly what I want. I want the rule to add another user reference field to whichever ones are already there, *then* populate it with the user reference.

Do you have any idea?

**Edit** \- What I eventually came up with, without Rules -

```
function bamfmodule_flag($action, $flag, $content_id, $account) {
  if($action == 'flag') {
    if ($flag->name == 'event_bookmark') {
        $node = node_load($content_id);
        array_push($node->field_trainer, $account->uid);
        node_save($node);
    }
  }
}

```

# Answer
Does it need to be a user reference?

Assuming that you are not using a global flag (then you wouldn't have an issue with multiple users), that information should already be stored in the flag tables. You should be able to show that information with a view (which you can attach to the node with http://drupal.org/project/views\_attach). Or if that doesn't work, do a custom query in a hook\_node\_view() implementation in a custom module.

And if it has to be a user reference for some reason, an unlimited multi-value user reference should be easier to handle with Rules than a unlimited number of user reference fields. CCK (nor Fields, for that matter) is just not designed for that. And you can only add fields to content types, not single nodes.
> 2 votes

---
Tags: 7, entities, rules
---


title: Dropdown menu expanded on page load

text:
# Question
Title: Dropdown menu expanded on page load
I have a hierarchical dropdown menu created using Drupal Megamenu module. It works good for my needs, but there is a small issue: when the page loads the whole menu tree looks expanded, and covers the entire page for a while.
It gives a hard look. I would greatly appreciate if you have any suggestions or workarounds to fix this.

# Answer
Problems like this occur when you rely on JavaScript to hide things. It can take some hundred ms before it happens making the items appear upon page load.

A way to solve this, would be to use CSS to hide the expanded menu when the page is loading and once the JavaScript has been run, remove the effect of the CSS.

The easiest way to do that is by adding a class on the HTML produced, that is required in the CSS rule, and remove the class with JavaScript on page load. You could add a class to the body in the `preprocess_page` hook and remove it again in one of your theme's JS files.
> 4 votes

---
Tags: 7, routes
---


title: Getting per-module memory stats?

text:
# Question
Title: Getting per-module memory stats?
I'm hosting Drupal on Dreamhost shared hosting where I have a maximum of 90 MB RAM and a lot of enabled modules.
Is there a way to see how much memory each module is using?

# Answer
> 10 votes
No, unfortunately, this is not possible. The used memory of a module is scattered among many functions, caches, etc.

There are tools which allow you to display the memory usage per function, how much time a function used, and so on; for example, there are XHProf and Xdebug, but both are PHP extensions and you will not be able to install them on a shared host.

You could, however, create a local installation (if you haven't already) and then check these tools out. Devel integrates nicely with XHProf, so you only need to install the extension, and enable the corresponding checkbox in the configuration settings of Devel.

# Answer
> 7 votes
Pounard does have an experimental module for that.

I already talk with him, he knows that this is highly experimental and you really should make a backup of your data before trying this module.

Maybe that could help.

---
Tags: 7
---


title: Translation issue

text:
# Question
Title: Translation issue
I have problem with the i18n translation module; despite I translate a text menu link in the administration string translation section, it doesn't translate on the front end when I navigate the site with the other language and it happens for every translated text.

Am I missing anything?

# Answer
Probably not - i18n is notoriously flaky, I find. All I can suggest is you try a bunch of cache clearing, deleting and re-creating of items and see if you can make something stick. Maybe leave that menu item and create another one and see if it translates ok. I think you're experiencing a sort of known issue that is difficult to track down. I've certainly seen this behaviour before and just had to work around it. =(
> 1 votes

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


# Question
Title: Table 'watchdog' was not locked with LOCK TABLES on custom module
I am creating module that need to lock table:

```
db_query('LOCK TABLES {eventi_list} READ');

$is_booked = _is_booked($uid, $nid);
if (! $is_booked) {
  $is_booked = _is_booked($uid, $nid, 'eventi_waiting_list');
}

if (! $is_booked) {
  $amount = _get_free_amount($nid);
  if ($amount > 0) {
    $insert = db_query("INSERT INTO {eventi_list} (uid, nid) VALUES($uid, $nid)");
  }
  else {
    $time = time();
    $insert = db_query("INSERT INTO {eventi_waiting_list} (uid, nid, created_at) VALUES($uid, $nid, $time)");
  }
  $update = db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");
}
db_query('UNLOCK TABLES');

```

I am getting error (4 similar warnings):

```
Warning: Table 'watchdog' was not locked with LOCK TABLES query:
INSERT INTO watchdog (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (19, 'php', '%message in %file on line %line.', 'a:4:{s:6:"%error";s:12:"user warning";s:8:"%message";s:139:"Table eventi_waits was not locked with LOCK TABLES query: SELECT count(nid) AS count FROM eventi_waits WHERE nid=201 AND uid=19";s:5:"%file";s:95:"D:\tools\xampp\htdocs\drupal\sites\bartenders.localhost.com\modules\\custom\eventi\eventi.module";s:5:"%line";i:115;}', 3, '', 'http://bartenders.localhost.com/bartender/book/201/%3Fdestination%3D/eventi/justin-knows', 'http://bartenders.localhost.com/eventi/justin-knows', '127.0.0.1', 1303900341) in D:\tools\xampp\htdocs\drupal\includes\database.mysqli.inc on line 135

```

What can I do with this, turn off database reporting?

# Answer
> 3 votes
This won't work with the current code. It is not the reporting that is the problem, but the implementation of locking.

From mysql lock tables reference

> A session that requires locks must acquire **all the locks that it needs** in a single LOCK TABLES statement. While the locks thus obtained are held, the session can access only the locked tables.

You are trying to access unlocked tables while holding a lock.

I can't say that I have used it in the wild but there is a Drupal specific locking mechanism that you may want to look at instead.

# Answer
> 3 votes
Additionally to what Jeremy French said:

* If you really want to do a lock, you should use the provided api functions db\_lock\_table()
* You *really* need to pass arguments to your queries properly with placeholders like %d and %s. What you are doing is **insecure** and can lead to SQL Injection. Re-read the documentation of db\_query()

# Answer
> 2 votes
The code is using the wrong lock. This is the description reported by the MySQL 5.0 reference manual:

> READ \[LOCAL\] lock:
>
> The session that holds the lock **can read the table (but not write it)**.
>
> Multiple sessions can acquire a READ lock for the table at the same time.
>
> Other sessions can read the table without explicitly acquiring a READ lock.
>
> The LOCAL modifier enables nonconflicting INSERT statements (concurrent inserts) by other sessions to execute while the lock is held. (See Section 7.7.3, “Concurrent Inserts”.) However, READ LOCAL cannot be used if you are going to manipulate the database using processes external to the server while you hold the lock. For InnoDB tables, READ LOCAL is the same as READ as of MySQL 5.0.13. (Before that, READ LOCAL essentially does nothing: It does not lock the table at all, so for InnoDB tables, the use of READ LOCAL is deprecated because a plain consistent-read SELECT does the same thing, and no locks are needed.)

The code is getting a read lock, but then it is writing in the table.

To notice that the main error is caused by the "event\_list" not being write-locked, and from the fact `watchdog()` is trying to log the error writing to a table that was not write-locked too. As Jeremy French reported, the code should acquire all the locks it needs.

If you look at the code of db\_lock\_table(), which is the function that Bedir correctly suggests to use, you will notice that it is acquiring a write lock.

```
function db_lock_table($table) {
  db_query('LOCK TABLES {' . db_escape_table($table) . '} WRITE');
}

```

---
Tags: 7, database
---


# Question
Title: Aegir / drush alias issue: profiles specified at command line get forgotten
Note: Aegir is an installation / site management tool for drupal sites & platforms. See http://community.aegirproject.org/ for details.

This question may be down to an Aegir issue or a drush one; thoughts from either angle are welcome:

I've managed to create Aegir/drupal platforms via both the command line (see http://lists.aegirproject.org/pipermail/aegir/2011-January/000026.html) and web interface, and I can get sites to install with a selected profile through the web interface, but when I try to install a site via the command line it keeps resetting to the default profile. Can anyone see what I'm doing wrong here?

I create a site alias:

```
drush --uri='demo.c.didev.co.uk' provision-save '@site_demo.c.didev.co.uk' --context_type=site --platform='@platform_dennis_generic_20110316b' --profile='myprofile' --db_server='@server_localhost' --client_email='me@domain.com'

```

and it creates a valid alias file:

```
cat .drush/site_demo.c.didev.co.uk.alias.drushrc.php
<?php $aliases['site_demo.c.didev.co.uk'] = array (
'context_type' => 'site',
'platform' => '@platform_dennis_generic_20110316b',
'server' => '@server_master', 'db_server' => '@server_localhost',
'uri' => 'demo.c.didev.co.uk',
'root' => '/var/aegir/platforms/dennis_generic_20110316b/',
'site_path' => '/var/aegir/platforms/dennis_generic_20110316b//sites/demo.c.didev.co.uk',
'site_enabled' => true,
'language' => 'en',
'client_email' => 'me@domain.com',
'aliases' =>  array ( ),
'redirection' => false,
'profile' => 'myprofile', );

```

However, when I run "drush @hostmaster hosting-import @site\_demo.c.didev.co.uk" it rewrites the alias file to "profile = default" and installs with the default profile!

Now, this is a pain but not a disaster as I can do the initial site creating via the web interface and it'll work, but I get apparently related errors when trying to migrate on the command line (per instructions at http://community.aegirproject.org/node/41) where it appears to not create an array of profiles and crashes (I'll post on that separately later) and wanted to rule out these problems before I tackle those.

So - am I doing something wrong, or is there just a bug?

# Answer
> 3 votes
I tweeted this to Mig - he says:

> probably a bug. Workaround is to not hosting-import the site but re-verify the platform & let it autoimport site by itself

HTH! =)

# Answer
> 0 votes
This shows something akin to what you are doing. One interesting line in it is.

> Be sure to install the 3.3 version of Drush as any newer versions will cause problems with Aegir later (as I found out the hard way)

That may be worth trying.

---
Tags: users, drush, installation, aegir
---


title: Taxonomy & Views

text:
# Question
Title: Taxonomy & Views
How can I take a "Content Type" with a "Taxonomy Term" field... and use views to generate a list of content with that term via URL?

I have a content type that has the basics (Title, Body) as well as Taxonomy Term for a Vocabulary & Weight. I want the user to be able to type:

```
http://myip.org/portals/safety

```

This would theoretically generate

1. HTML list of pages
2. "Menu" to be use in a block with a list of safety (or whatever) pages.

I can't seem to figure out where to get the taxonomy/term to work as variables in the View.

Views has the "Taxonomy Term" default view with

```
taxonomy/term/%
taxonomy/term/%/feed

```

I'd like to remove the /%,/%/feed and auto-magically make a taxonomy/term page/menu.

# Answer
The key to views is to use the filter function to get the correct node relations out in the way you want. I had the same problem where I wanted a node of content type "application" with a taxonomy of "approved", "pending", and "denied". The view should get a with a filter of node: type = "applications", based on my example. That will find the right content. I added a base url of applications for the page view. The arguments section is where the taxonomy can be used to filter based on URL.

portals/safety node type = safety

portals/safety/one node type = safety taxonomy: term = one

portals/safety/two node type = safety taxonomy: term = two

It might be easier if I just export the view and see if it helps point the way along.

```
$view = new view;
$view->name = 'Applications';
$view->description = 'List of all applications';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'node';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Application List', 'default');
$handler->override_option('fields', array(
  'title' => array(
    'label' => 'Application',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 1,
    'exclude' => 0,
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'relationship' => 'none',
    'override' => array(
      'button' => 'Override',
    ),
  ),
  'name' => array(
    'id' => 'name',
    'table' => 'term_data',
    'field' => 'name',
  ),
));
$handler->override_option('arguments', array(
  'name' => array(
    'default_action' => 'ignore',
    'style_plugin' => 'default_summary',
    'style_options' => array(),
    'wildcard' => 'all',
    'wildcard_substitution' => 'All',
    'title' => '%1 Status Application',
    'breadcrumb' => 'Applications',
    'default_argument_type' => 'fixed',
    'default_argument' => '',
    'validate_type' => 'none',
    'validate_fail' => 'not found',
    'glossary' => 0,
    'limit' => '0',
    'case' => 'none',
    'path_case' => 'none',
    'transform_dash' => 0,
    'add_table' => 0,
    'require_value' => 0,
    'id' => 'name',
    'table' => 'term_data',
    'field' => 'name',
    'validate_user_argument_type' => 'uid',
    'validate_user_roles' => array(
      '2' => 0,
      '3' => 0,
      '4' => 0,
    ),
    'relationship' => 'none',
    'default_options_div_prefix' => '',
    'default_argument_fixed' => '',
    'default_argument_user' => 0,
    'default_argument_php' => '',
    'validate_argument_node_type' => array(
      'blog' => 0,
      'poll' => 0,
      'faq' => 0,
      'forum' => 0,
      'application' => 0,
      'page' => 0,
      'story' => 0,
    ),
    'validate_argument_node_access' => 0,
    'validate_argument_nid_type' => 'nid',
    'validate_argument_vocabulary' => array(
      '1' => 0,
      '2' => 0,
      '3' => 0,
      '4' => 0,
    ),
    'validate_argument_type' => 'tid',
    'validate_argument_transform' => 0,
    'validate_user_restrict_roles' => 0,
    'validate_argument_php' => '',
  ),
));
$handler->override_option('filters', array(
  'status' => array(
    'operator' => '=',
    'value' => '1',
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'status',
    'table' => 'node',
    'field' => 'status',
    'relationship' => 'none',
  ),
  'type' => array(
    'operator' => 'in',
    'value' => array(
      'application' => 'application',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'type',
    'table' => 'node',
    'field' => 'type',
    'relationship' => 'none',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
));
$handler->override_option('cache', array(
  'type' => 'time',
  'results_lifespan' => '3600',
  'output_lifespan' => '3600',
));
$handler->override_option('title', 'Applications');
$handler->override_option('style_plugin', 'list');
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->override_option('path', 'applications');
$handler->override_option('menu', array(
  'type' => 'tab',
  'title' => 'Applications',
  'description' => 'Applications',
  'weight' => '0',
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->override_option('block_description', 'Applications');
$handler->override_option('block_caching', -1);

```
> 3 votes

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


title: Ordering archive block

text:
# Question
Title: Ordering archive block
I've upgraded an installation from Drupal 5 to Drupal 6, and now I can't get the archive to be displayed in the right order. I've set the sort criteria of the block to be descending and in the preview I can see it correctly: on top I get the last entry, followed by the one after that, etc. The block displayed in the left-hand column never changes, even after cleaning the cache. I know this is the right block because if I remove it, the archive view on the left column will go away too.

Do you have any suggestions?

# Answer
It must have been some sort of caching issue, because the link above just worked.
> 1 votes

---
Tags: 6, views, blocks
---


title: Change control using CVS

text:
# Question
Title: Change control using CVS
We're looking to manage our install of Drupal 7 with CVS (sadly Git and SVN are out). Do you have any pointer for things to think about when setting up the repositories?

Our lay of the land is as follows:

* Our staff include UI developers, back-end developers , administrators, and DBAs.
* For starting, we're going to install various modules (e.g. Domain, LDAP, Workflow, and Views). We'll write some custom modules down the road. We're also looking for implementing our own look and feel.
* We have Dev, Test/QA, and Production instances of Drupal. The flow of code and configurations will be from Dev to Test/QA to Production (with some looping between Dev and Test).
* We'll have top level domains and several subdomains.
* We're on RedHat Enterprise Linux 5.5, MySQL 5.x and Apache 2.x.

What are the ways of managing changes that have worked for you?

# Answer
Regardless the used VCS, here is what I put in my code repository

* A `.make` file used to download Drupal core, contrib modules and contrib themes and apply patches (if required)
* a `module` folder with only the custom modules
* a `themes` folder with only the custom themes
* A build script to
    + run `drush make` on the `.make` file to download Drupal core and contribs to a (VCS ignored) `dist` folder
    + copy the `modules` folder to `dist/sites/all/modules/custom`
    + copy the `themes` folder to to `dist/sites/all/themes/custom`

This to

* properly track changes to the custom code
* properly track used core and contribs versions (in the `.make` file)
* prevent core or contribs hack
* allow proper patching (Drush Make requires the applied patches to be on publicly accessible)

For the build script, I use Phing but any scripting languages (ant, bash, php, ruby, etc.) could be used. With some additional work, the build script can also be used to run automated test (SimpleTest) and code validation (`php -l` and Coder Review).

I try to have as much configuration as possible exported into code. Mainly by using *exportables* through the Features module and by having a project specific profile to define and update non-exportable configurations through its `hook_install` and `hook_update_N` implementations. See The Development -\> Staging -\> Production Workflow Problem in Drupal and the Code driven development: using Features effectively in Drupal 6 and 7 presentation.
> 6 votes

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


# Question
Title: What is the best way to upload a PDF attachment, that can be attached to multiple nodes?
I want multiple nodes to all have a download link on each node to one, shared PDF file.

What is the best way to upload the PDF file one time, but add it as an attachment to each of the multiple nodes?

This is easy to do for one node:one pdf attachment using the File Upload module, but I'm not sure of the best way to associate one single PDF with multiple nodes.

# Answer
Two approaches spring to mind. Either you keep using a filefield and use something like FileField Sources to select already uploaded files; or you use a file-as-node idea, and create a content type for PDFs, use nodereferences to attach them to nodes, and use something like Nodereference Explorer for browsing.
> 4 votes

---
Tags: 7, nodes, files
---


title: Comment theming question

text:
# Question
Title: Comment theming question
In Drupal 7, when theming the comments in my website (comment.tpl.php), I want to print the comment title without a permalink wrapped around as a link. I want the raw title. This should be simple, it seems, but it seems there is no variable for that. `print $title` will show the title wrapped with the permalink link.

Do I have to mess with template.php to fix that?

I also tried `render($content['subject'])`, but nothing it is printed on the screen.

# Answer
> 4 votes
According to the documentation of comment.tpl.php, you should have access to $comment, so the following should work:

```
<?php print $comment->subject; ?>

```

---
Tags: 7, theming, comments
---


# Question
Title: Custom module menu item declaration leads to error 404
```
function eventi_menu() {
  $items = array();
  $items['eventi/book/%/'] = array(
    'title' => 'Book',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/book_waits/%/'] = array(
    'title' => 'Book Waits',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/unbook/%/'] = array(
    'title' => 'Unbook',
    'page callback' => 'eventi_unbook',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );

  return $items;
}

function eventi_book($nid) {
  echo 'something';
}

```

All worked OK, but suddenly, when I visit (for example) http://example.com/eventi/book/201, I get an error 404. I cleared the cache, but I keep to get the same error. Do you have any clue why it happens?

# Answer
> 1 votes
Remove the ending slash in the paths.

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

  $items['eventi/book/%'] = array(
    'title' => 'Book',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/book_waits/%'] = array(
    'title' => 'Book Waits',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/unbook/%'] = array(
    'title' => 'Unbook',
    'page callback' => 'eventi_unbook',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );

  return $items;
}

```

# Answer
> 4 votes
I would guess that trailing slash on the path is throwing you

```
$items['eventi/book/%'] = array(
  'title' => 'Book',
  'page callback' => 'eventi_book',
  'access arguments' => array('allow booking'),
  'page arguments' => array(2),
  'type' => MENU_CALLBACK
);

```

Also, if you use `%node` for the variable in the path, the menu router will call `node_load()` on the given `nid` from the path and you'll get the full `$node` object in your callback function, like so:

```
$items['eventi/book/%node'] = array(
  'title' => 'Book',
  'page callback' => 'eventi_book',
  'access arguments' => array('allow booking'),
  'page arguments' => array(2),
  'type' => MENU_CALLBACK
);

// ...and so on, until...

function eventi_book($node) {
   return $node->title;
}

```

Also note that your callback function should return a value, not echo it.

---
Tags: 7, routes
---


title: Why is my cron not running as intended?

text:
# Question
Title: Why is my cron not running as intended?
`crontab -e` displays

```
*/5 * * * * /persistent/sitename/scripts/cron-curl.sh
~
~
~
"/tmp/crontab.XXXX1FOZWa" 1L, 51C

```

Why is it not running every 5 minutes?

# Answer
> 2 votes
Did you modify `cron-curl.sh` to use the URL for your site? By default, it tries to load http://example.com/cron.php.

---
Tags: 7, cron
---


# Question
Title: Cron job run, but module updates not checked - how to automate?
I configured a script to run as part of my cron.daily tasks, and tested the script.

My status report says that the cron was correctly run by the script, so I'm happy that that will happen.

However, I went to the available updates page, and it still says that I last checked 17 hours ago - isn't this part of the cron?

Is there a way I can include this in the automated checks and reporting?

# Answer
Looking at the code of update\_cron(), I notice that the function checks for updates if there aren't cached data or if the update interval is past.

```
function update_cron() {
  $frequency = variable_get('update_check_frequency', 1);
  $interval = 60 * 60 * 24 * $frequency;
  // Cron should check for updates if there is no update data cached or if the
  // configured update interval has elapsed.
  if (!_update_cache_get('update_available_releases') || ((time() - variable_get('update_last_check', 0)) > $interval)) {
    update_refresh();
    _update_cron_notify();
  }
}

```

By default, updates are checked once per day; if you want Drupal checks for updates twice per day, you can change the value of the "update\_check\_frequency" variable to 0.5.
As the setting page doesn't allow you to set a value that is lower than 1, you can change the value of that variable with `variable_get('update_check_frequency', 0.5)`. Cron tasks needs to be executed at least twice per day, or the trick doesn't work.
You can also invalidate the cache, and force update.module to check for updates the next time the cron tasks run, by visiting the page that lists all the modules and clicking on the "Save" button; alternatively, you can call update\_invalidate\_cache().
> 2 votes

---
Tags: 7, updating, cron
---