title: drupal_add_js() issues

text:
# Question
Title: drupal_add_js() issues
I am facing some problems while using drupal\_add\_js() along with drupal\_goto().

I am using `hook_nodeapi()` to capture a node prepare condition; inside the "prepare" case, I am adding the following JavaScript code, which I need to close a Lightbox window):

```
drupal_add_js('$(document).ready(function() {
  window.parent.location = "'.$base_url.'";
  window.parent.Shadowbox.close();
})', 'inline');

```

The problem is that if I add a `drupal_goto()` before or after `drupal_add_js()`, then the JavaScript is not included in my page source.

I hope I am able to explain my problem. Can anyone please point me towards why this happens?

I know I can use JavaScript to implement `drupal_goto()` functionality, but in some cases the `drupal_goto()` comes from the drupal module itself and thus cannot be removed.

# Answer
> 3 votes
`drupal_goto()` alters the header of the page, then calls `exit()`. So if it's placed before the `drupal_add_js()`, the function will never be called, and if it's placed after, the header says "Go some place else," and you will be redirected as soon as possible, not waiting for jQuery to execute.

Why do you need to close the shadowbox in the first place if you are going to redirect the user somewhere else? It sounds like there's a fundamental problem to what you want to do.

# Answer
> 1 votes
@Letharion's answer already explains why `drupal_add_js()` doesn't work together with `drupal_goto()`.

I will add that an implementation of `hook_nodeapi()` is not supposed to redirect the user to a different page. If the user needs to be redirect to a different URL when it access a specific URL, then the menu callback associated with that URL needs to be replaced with another menu callback that verifies some conditions, and then redirects the user to the other URL; if the menu callback is one defined in another module, then you need to alter the menu callback associated with that URL using hook\_menu\_alter().

---
Tags: javascript
---


title: Maintaing Images when switching servers

text:
# Question
Title: Maintaing Images when switching servers
I just changed the server one of my sites is hosted on. In doing so, I lost all the images. The CCK file upload fields show "ghost" data but contain no actual image data as they did before the site transfer. All my data is fine, however.

Is there a way to prevent this so all my images are maintained? Thanks

# Answer
> 1 votes
What module are you using to upload/show images? CCK + ImageField?

Anyways, to troubleshot your problem you need to figure the reason why no images are shown. This can be due to several reasons:

1. Wrong file Permission. When uploading via FTP or CPanel sometimes sometimes file permission gets messed. Try setting permission to 777 recursively to your image folder and see if images appear.
2. different absolute path. Some modules use an absolute path to figure in which folder they should upload images to. one easy way to find out is to create/upload a new image via CKK and using firebug (for instance) compare the URI of old images to the URI of the new image.

Keep us posted

---
Tags: nodes, media
---


# Question
Title: Triggers on node creation of certain content-type
It is a question that always gets answered by "use rules module." Unfortunately, this site depends heavily on a few actions and triggers already, and a migration is not in order.

Are there trigger-addons, tricks or code to make a trigger on creation of a certain node-type only?

# Answer
> 2 votes
Rules and core triggers/actions can co-exist. If it can easily be done in Rules, then why not use both. You then won't have to migrate.

# Answer
> 1 votes
I think the easiest way is to create your own action module:

```
/**
 * Implements hook_action_info().
 */
function mymodule_action_info() {
  return array(
    'mymodule_myaction_action' => array(
      'type' => 'node',
      'description' => t('Does something to a node'),
      'configurable' => FALSE,
      'hooks' => array(
        // When this action is called.
        'nodeapi' => array('presave', 'insert', 'update', 'view'),
        'comment' => array('insert'),
      ),
    ),
  );
}

/**
 * Implements hook_action().
 */
function mymodule_myaction_action($node, $context) {
  // If the node type is different from FAQ, returns and does nothing.
  if ($node->type == 'faq') {
    // Do something here.
  }
}

```

---
Tags: 6, rules
---


# Question
Title: Duplicated content shown in a view using a relationship
I am using a view that has a contextual filter ("Content: Has taxonomy term ID") and a relationship ("Content: Taxonomy terms on node"); for some reason, I keep getting duplicated content. In the view settings I have "Distinct" checked.

Are there any other options I can look into?

# Answer
> 1 votes
Yes. Check if one of your fields have multiple values, like Taxonomy Terms, or Images. Then, you have to group those values with the according option to prevent this.

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


# Question
Title: WSOD after migrating to another site? Troubleshooting a site migration
I'm in the process of migrating from one URL to another, and I've got a WSOD. What I had done is to import the new database from the production server.

* I've copied all the files from another server using SCP;
* I've then SCPed the database from the other server;
* I have imported the database from command line;
* I have changed the settings.php to the correct information.

I have the feeling it's something simple that I haven't ruled out.

Do you have any idea?

# Answer
> 6 votes
Remember to check the PHP version. It's running on PHP 4.

# Answer
> 5 votes
Have a look at Apache error.log which generally contains information regarding the error. Also the Drupal handbook have great tips to debug this error, see: http://drupal.org/node/158043

---
Tags: 6, migrations, wsod
---


title: Run javascript code on Form Submit

text:
# Question
Title: Run javascript code on Form Submit
I want to run JavaScript code upon a form being submitted preceding other default tasks that are carried out on form submission.

May anyone suggest some approaches?

# Answer
Depending on the type of code that you need to run, and from the Drupal version, AHAH and AJAX could be the answer.

On Drupal API, there is example code for AHAH (Drupal 6), and AJAX (Drupal 7 and higher).
> 1 votes

---
Tags: javascript, forms
---


# Question
Title: performant way to load many complete node-objects
I need to load a bunch of node-objects and apply some algorithm to them.
Usually I'd use an iteration and `node_load()` within, but I was wondering if there's a better (speaking of performance) way to load node objects.

I think that being able to cache the algorithm's result on a per-page basis would be sufficient.

# Answer
> 2 votes
`node_load()` is the preferable way to load a node object, especially if the node object is passed to some functions.
Take in mind that, in Drupal 6 the result of `node_load()` is locally cached in a static variable by default; if you are going to load a bunch of nodes, it is better if you call the function as `node_load($id, NULL, TRUE)`. If you are sure that, for some reasons, the code could load the same node in consecutive calls to `node_load()`, then you can consider resetting the static value after X calls to `node_load()`.
The result of `node_load()` is not cached, if the `$revision` parameter passed to the function is not `NULL`.

Caching the value obtained from `node_load()` is possible, and your code could use its own cache for that purpose. The cache should be invalidated when nodes are updated, which includes also the case when a node is reverted to a previous revision. Rather than implementing a cache in your own module, it would be better to use a module that caches the nodes for third-party modules.

In Drupal 7, both `node_load()` and `node_load_multiple()` accept a `$reset` parameter that resets the node cache kept as instance variable from the object of class NodeController that is created from Drupal, which uses the instance variable implemented by DrupalDefaultEntityController, the class that implements the default methods necessary for an entity controller.

# Answer
> 1 votes
There is no other way that I know of in Drupal 6.

Drupal 7 has node\_load\_multiple(), which allows to load multiple nodes in a single query (+ hooks, which can also do single queries for multiple nodes). And additinally, there is the Entity cache project, which allows to cache any loaded entity.

---
Tags: 6, performance
---


# Question
Title: How to close login-popup after successful login
I'm working on a FF-extension, that displays user-specific information on 3rd-party websites. Users need to be logged in to my Drupal-website. I'm checking login state with a cross-domain-proof `jQuery.ajax()`. If a user is not logged in, the FF-extension opens a popup-window (`window.open()`) showing a Drupal login/register/passwordlost page (/user/login).

Now I would like this window to close and the FF-extension to carry on, as soon as the login (registration/password-request) is successful. And now I'm lost. How would I do this?

I know how to close the popup from my FF-addon (`window.close()`), but I don't know how to tell the addon, when to do it. I thought of polling the login-state. But that seems kind of clumsy, no? I have also tried redirecting the drupal-page after successful login (login destination module) to a self-closing page, but in newer browsers `window.close()` works only on windows, that were created with the same script. And then I would still have to find a way to tell the FF-addon to proceed.

How do other people solve this?

# Answer
The user login form is the one returned from user\_login(), or user\_login\_block(). In both the cases, user\_login\_submit() is the form submission handler that is invoked for the login form.

Adding a form submission handler that is executed after `user_login_submit()` would be possible to set a Drupal variable.

```
function mymodule_form_user_login_form(&$form, &$form_state) {
  $form['#submit'][] = 'mymodule_login_submit';
}

function mymodule_login_submit($form, &$form_state) {
  global $user;

  variable_set('mymodule_user_logged_in', (integer) !empty($user));
}

```

The addon could then periodically ping a URL handled from the module, which would return the value of "mymodule\_user\_logged\_in," and close the window when its value is not 0.
The code I wrote here is not optimized, and it serves only as example of what is possible to do.

To allow to the added form submission handler to be called after the submission handler added by user.module, the weight of the module should be changed to a value that is different from the default module weight, in hook\_install() or hook\_update\_N().

```
function mymodule_install() {
  db_update('system')
    ->fields(array('weight' => 10))
    ->condition('name', 'mymodule')
    ->execute();
}

```
> 2 votes

---
Tags: 7, javascript, users
---


title: Question about user email activation

text:
# Question
Title: Question about user email activation
I noticed that the user table has a column for status. Does 1 status mean the account has been email activated? and is this the only thing distinguishing a activated account and unvalidated account? Also, I want to make a module that will do something when a user email activates his account. I'm guessing this would be the user hook but what op code would I use to detect when a user email activates his account?

# Answer
> 1 votes
When users create an account, and the email verification has been set as required, the value of the "status" field is set to 1 right after the users enter the username they want to adopt and their email address, if users are allowed to create an account without the approval of an administrator user; the "access" and "login" fields will be 0, until the users don't log in, which happens also in the case they follow the link reported in the email message sent to verify the email address they reported for their account.

---
Tags: 6, users
---


title: How to theme the user profile page?

text:
# Question
Title: How to theme the user profile page?
What is the file I have to modify in order to get Drupal to output a custom user page.

The default link to the file I need to change is:

```
http://www.example.com/?q=user/xx

```

Where xx is the user id.

This page is not dysplaying correctly and I want to fix it, but how do I know which file is Drupal calling?

Is there a reference guide on Drupal 7 default pages and links?

# Answer
> 4 votes
Here is a brief list of template suggestions for Drupal 7: http://drupal.org/node/1089656

If you are looking to theme the user page, there are multiple templates located in `modules/user` that can be overridden. The template you should probably start with is `user-profile.tpl.php`. Copy that file and paste it in your theme directory then edit it as you like and clear the cache and you should see the changes.

# Answer
> 4 votes
You shouldn't modify an existing file as modifying files in Drupal core or contrib module is not recommended. What you can and should do is overriding the (default) template(s) used on the user page. Usually, you copy the default templates files from the providing module's folder to your theme's folder and apply you change there. If your theme is based on an existing (contrib) theme, consider creating a sub-theme instead of changing files.

Figuring wich templates to override is a bit tricky, usually a page is composed of various elements produced separately using different templates. A template itself usually use bits of markup produced by other templates or theme functions. The Theme developer module can help you there as it provides a on-page overlay to easily view information about the template or theme function used to produce an element on the page. Also, you can't spare learning how Drupal structures the user information (ie. its *data model*) in order to figures how to effectively change the templates.

Keep in mind that templates files (`.tpl.php`) are templates and should notcontains business logic or data access. Data to be laid out by the templates should be provided by modules or preprocess functions in the `template.php` file of your theme.

---
Tags: 7, theming
---


# Question
Title: Adding a "my messages (x)" link in the block template file
I have installed Privatemsg, and I need to output the "My messages (x)" link programmatically in block.tpl.php.

I tried the following code, but it only prints "My Messages", when I need a counter for the new messages:

```
print l('My messages', 'messages');

```

# Answer
> 2 votes
You can use the function privatemsg\_title\_callback() like this:

```
print l(privatemsg_title_callback(), 'messages');

```

And as marcvangend mentioned, Privatemsg already provides a block that informs the user if he has new messages and a block that contains exactly such a link and additionally a link to write a new private message. Why not use one of these instead?

# Answer
> 3 votes
The module already contains a block that does something similar: "New message indication". You can use that block and alter the output if needed by overriding the theme\_privatemsg\_new\_block() function.

---
Tags: theming
---


title: Small site, multiple layouts

text:
# Question
Title: Small site, multiple layouts
So I've been fighting with this for a little bit, and I've been unable to get help from Google, so it's time to ask some experts!

I'm setting up a small business website; we're aiming to create something that's very simple now, and easy to grow as the business grows. Drupal fits the bill nicely, but it's fairly new to us. I'm trying to set up three simple layouts: a basic page (Header, Main Content, Side Bar Menu, Footer), a splash page (Header, Side Bar Content), and a product page (Header, Side Bar Content, and Footer). Nothing overly ambitious, but also not supported by Drupal 7 out of the box (as far as I can see, at least).

I tried experimenting with themes and subthemes, and played around with the Zen theme for a bit to limited success, but no variable layouts. After some digging, I think CTools + Panels is what makes the most sense, and I can get the layouts I want, but I can't figure out how to get the panels to display any actual content.

Is there an easy way to execute this plan with Panels, or should I be investigating a different option?

# Answer
> 1 votes
Panels is definitely the easiest way to create different layouts.

What you have to do is go to Panel Content and on the edge of each panel there is a little gear icon or arrow (if i recall correctly) that opens a drop down menu with many options. one of them is "add content", it will open a modal dialog with options to select from blocks the content you want to display, you can also add custom fields if you want!

# Answer
> 1 votes
Panels might be the better option, but I think you could also simply add conditional blocks (for example with the help of the Context module) that for example only show up when product nodes are displayed.

Then, the corresponding regions (e.g. side bar) should only show up if there are any blocks within them.

There are also modules to display a custom front page: http://drupal.org/project/front

# Answer
> 1 votes
Try checking out Omega theme. Coupled with the delta module and context it allows you to easily modify and setup different layouts based on url etc.

---
Tags: 7, panels
---


# Question
Title: Is there an issue reporting module with these features?
We have 3 departments and we give IT support for all project users. We would like to receive there support request using our drupal 7 site instead of receiving phone call.

* We just need a support request form
* The form sends a notification email to experts
* The submitted issues should be listed by project group; only experts can access the list.
* The form access privilege is only for authenticated users.
* There is no progress status report for the users.

What do you suggest?

# Answer
> 5 votes
The Webform module might do what you want. It lets you create forms using the user interface. You can configure which actions happen when a user submits a form, such as email one or more users and store it in a table.

**Update** about your comment, which looks like so:

> Webform seems good but i drop it by one important reason. that is it doesn't give a privilege form submission only the authenticated user!

Forms created with Webform are just a type of node. If you want to restrict access to the forms you create, you can either not allow anonymous to access any node or you can use more fine grain permissions with another module like Nodeaccess. If this is for an intranet site, the first option might be the best

---
Tags: 7
---


title: Drupal: Multilingual SEO website

text:
# Question
Title: Drupal: Multilingual SEO website
I am trying to build a simple website with a blog. The website needs to have, at least, 4 languages and SEO optimization (Title Description Keywords). Please advise me on which modules to use and if there is any how-to tutorials to do so. Are there any pre-made profiles I can use? In the end I would like to create a profile which I will replicate for feature projects.

# Answer
For a multilingual Drupal 7 site you could enable the Locale and Content translation modules, they are both included in the Drupal Core.

Also, you might want to check the Internationlization module and the Entity translation module.

Basically you start of by adding languages to your site, you can do this in the administration area (/admin/config/regional/language). After that you can allow content types to be translated (/admin/structure/types). When you add a node you will then be able to choose between the enabled languages.

As for SEO: you could check the Drupal SEO Tools, it has a huge list of modules that you can use.
> 2 votes

---
Tags: 7
---


# Question
Title: How to make a custom block visible if and only if there are no other blocks active in given region
The site's header banner is displayed using a custom block containing an image. Is it possible to create a default block which will return visibility = TRUE only in the case that there are no other blocks which are visible in the header region for the page currently being rendered? In other words, can a PHP-code visibility test access the list of blocks which will be rendered in the block's region? If not, how can this functionality be implemented?

# Answer
> 2 votes
There is a function that returns the list of the blocks available in a region, but it cannot be invoked from the PHP code used to establish the visibility of a block as it would probably cause a recursive call.

Looking at the code of block\_list(), you can write the visibility code for your block. What you need to change is the query that obtains the list of all the blocks to exclude the block for which you are writing the visibility code.

The actual query executed by the function is the following:

```
$result = db_query(db_rewrite_sql("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.theme = '%s' AND b.status = 1 AND (r.rid IN (" . db_placeholders($rids) . ") OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), array_merge(array($theme_key), $rids));

```

The function code requires you know the region in which the block is visible; if you move the block in a different region, then you need to change the code used to test the block visibility accordingly.

In Drupal 7, a module can implement hook\_block\_list\_alter() to alter the list of visible blocks.

> Act on blocks prior to rendering.
>
> This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.
>
> You can also set `$block->content` here, which will override the content of the block and prevent `hook_block_view()` from running.

---
Tags: 6, blocks
---


title: Display VAT price on products

text:
# Question
Title: Display VAT price on products
I have added a 20% vat on my products. This is added during checkout. How can I add it to the display price when you view the product?

# Answer
> 1 votes
I'm assuming you're using the VAT module. Ubercart's prices aren't flexible enough to adjust the display price based on the VAT. You should probably enter the prices for each product including the VAT and adjust your uc\_vat so the sell price is inclusive.

---
Tags: 6, ubercart
---


# Question
Title: what's Taxed line items in the ubercart tax module?
does anyone know what is referring to the fields : Taxed line items : Shipping,Empty line,Tax in the tax configuration? i couldn't find an explanation

# Answer
> 1 votes
Line items are the items in an order. They can include products, shipping, and tax. The taxed line items are the line items you apply the tax rate to. Generally that would just be the products.

---
Tags: ubercart
---


# Question
Title: How do I add a customer ID field in Ubercart?
I want to ask for the customer to enter his ID when he buys something. Is it hard to add a new field apart from the default: name, phone, address, etc?

# Answer
> 2 votes
You want to add a field to the checkout process? There are two modules that do that. uc\_webform\_pane allows you to create webform nodes that integrate into the checkout process. uc\_cck\_pane allows you to integrate cck nodes into the checkout process.

---
Tags: 7, ubercart
---


title: Fatal error when running Drush 4.4

text:
# Question
Title: Fatal error when running Drush 4.4
Do you have any idea on what might be causing this error in Drush w/ Drupal 7.2 (worked fine in Drupal 7.0)?

> Fatal error: Undefined class constant 'MYSQL\_ATTR\_USE\_BUFFERED\_QUERY' in /path/to/includes/database/mysql/database.inc on line 42
> Drush command terminated abnormally due to an unrecoverable error. \[error\] Error: Undefined class constant 'MYSQL\_ATTR\_USE\_BUFFERED\_QUERY' in /path/to/includes/database/mysql/database.inc, line 42

Line 42 of database.inc contains the following line:

```
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,

```

I thought this was related to PDO extension missing, but it is indeed installed.

This is the output of `drush -v -d status`.

> Bootstrap to phase 0. \[0.03 sec, 1.28 MB\]
> Drush bootstrap phase : \_drush\_bootstrap\_drush() \[0.03 sec, 1.41 MB\]
> Drush bootstrap phase : \_drush\_bootstrap\_drupal\_root() \[0.07 sec, 3.18 MB\]
> Initialized Drupal 7.2 root directory at /path/to \[0.09 sec, 4.06 MB\]
> Drush bootstrap phase : \_drush\_bootstrap\_drupal\_site() \[0.09 sec, 4.06 MB\]
> Initialized Drupal site default at sites/default \[0.09 sec, 4.06 MB\] \> Drush bootstrap phase : \_drush\_bootstrap\_drupal\_configuration() \[0.09 sec, 4.06 MB\]
>
> Fatal error: Undefined class constant 'MYSQL\_ATTR\_USE\_BUFFERED\_QUERY' in /path/to/includes/database/mysql/database.inc on line 42
> Drush command terminated abnormally due to an unrecoverable error. \> Error: Undefined class constant 'MYSQL\_ATTR\_USE\_BUFFERED\_QUERY' in /path/to/includes/database/mysql/database.inc, line 42 \[0.1 sec, 4.56 MB\]

`phpinfo()` indicates that PDO and PDO MySQL are all installed. However, when I run `pecl remote-info pdo` (and `pdo-mysql`), I get * Installed - no -\*.

So it appears that via the web requests, the extensions appear as installed, but not from the command line (same instance of PHP 5.3). Is there a way to tell PECL what `phpinfo()` already knows?

# Answer
Ok, another one for the "learning experience" column:

I specified

```
DRUSH_PHP=/path/to/php

```

right before this line in drush wrapper script:

```
if [ ! -z "$DRUSH_PHP" ] ; then

```

Works now.

Thanks @kiamlaluno & @Berdir for your time and input. Hopefully this helps others.

KM
> 4 votes

# Answer
You are most likely missing the pdo\_mysql extension, which you also not, not only pdo and mysql/mysqli (that one is actually not necessary for *Drupal 7*, but is if you're also using Drupal 6 or other projects which use it).

You can see the enabled modules with:

```
php -m

```

Make sure it lists both PDO and PDO\_mysql and if not, enable/install that.
> 3 votes

# Answer
There is an issue report on Drupal.org, Fatal error in D7 HEAD while running 'drush update', where the OP reports a similar error.
One user reports the error can be fixed when the php\_pdo\_mysql extension is installed; another user reports it is necessary to install php5-mysql, under Ubuntu 10.10.
> 1 votes

---
Tags: drush
---


title: Select the fields of a node using code

text:
# Question
Title: Select the fields of a node using code
I'm new to Drupal, and I have some problems.
I need to select some fields from a node (via code), and then process the data.

\[Full-size image\]

Basically, I want to show the total of column "value", grouped by "category", but as each field's content type is a table, I do not know how to do it.

# Answer
> 1 votes
To get the data from a field in an entity be it a node or something else is pretty straight forward.

It can usually be done doing something like this.

```
$data = $node->field_name['und'][0]['value']

```

But it depends on which field type you are using ect. A more convenient way is to use the entity module. With that installed you can do:

```
$node_wrapper = entity_metadata_wrapper('node', $node);
$data = $node_wrapper->field_name->value();

```

This giv give you the value, for reference fields like term reference, you will get the actual loaded term instead of the raw id which is pretty handy and allows chaining.

---
Tags: 7, entities, nodes
---


title: Modules and performance

text:
# Question
Title: Modules and performance
I know that disabled modules do not effect performance. I also know that typically the number of modules you have enabled will effect the speed of you site. One individual on Drupal.org said you should never have more than 40 modules enabled. I found this strange because I would assume some modules are more intensive than others.

Is it simply the number of modules that somehow effect performance, (because the hook is always called), or is it really dependent on what you are doing in the module?

# Answer
It depends on the module.

You can create a module which has a simple info file and a blank module file, compare that to views which has loads of file and implement lots of hooks and create it's own as well. Obviously this requires more memory than a blank module.

Performance depends on a lot of factors. A module can use a lot of memory but not slow the side down much while the reversed can be true as well. Usually the bottleneck is r/w to the database. A single bad query can take seconds to perform, most tasks in code is not that slow. Iterating over a lot of objects and munching data can, however, take a lot of time.

So it's hard to say how a module will effect performance, but it's always a good idea to limit the amount of modules used when possible. I haven't heard of a thumb rule though and to be able to make one, you would need to know the hosting environment.
> 9 votes

---
Tags: 7, hooks, performance
---


# Question
Title: Enable / Disable comment form in a module?
I would like to set a given node's comment flag to 1 or 2 (to either show or hide the comment form) via my custom module, depending on certain conditions.

I have tried using hook\_node\_view, but this approach seems not to have worked:

```
function custom_node_view($node, $view_mode, $langcode) {
  $node->comment = 1;
}

```

Even if I explicitly set the comment flag to 1, it will remain 2 for a given node. If I `dpm($node);` just after setting the flag, the correct value will show in the devel information, but the comment form will still show...

According to comment.module, the values are such:

```
/**
 * Comments for this node are closed.
 */
define('COMMENT_NODE_CLOSED', 1);

/**
 * Comments for this node are open.
 */
define('COMMENT_NODE_OPEN', 2);

```

Is there a different hook I should be using to show/hide the comment form programmatically?

# Answer
> 4 votes
It looks like I can set the comment display correctly within hook\_node\_load(). I guess that runs a bit earlier in the process, and tells comment.module to not display the form for a given node.

Here's an example of what I ended up implementing:

```
<?php
/**
 * Implements hook_node_load().
 */
function custom_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->comment = COMMENT_NODE_CLOSED; // to close comments
  }
}
?>

```

---
Tags: 7, hooks, comments
---


# Question
Title: What are the limitations of the theming system?
* Can every theme function in include/theme.inc be overridden by a template (\*.tpl) file?
* Can preprocess functions be used to add variables to any theme function?

# Answer
Theming hooks (templates and *theme functions*) defined in `hook_theme()` implementations are always overridable. But they have to be used properly, always use `theme('foo', $bar)`, never `theme_foo($bar)`.

In Drupal 6, (pre)process functions are only available for templates, not *theme functions*. Also, the templates must be be overriden in the theme otherwise the preprocess function from the theme is not used. So to have your `THEME_preprocess_node(&$variables)` function used, you need to have the `node.tpl.php` in your theme folder.

Another limitation (actually a bug) is that for a template to be overridable in a theme, the file name (without the `.tpl.ph`p extension) must be exactly the same as the theming hook name except for the `_` that are replaced by `-`:

```
function MODULE_theme() {
  return array(
    'overridable_template' => array(
      'template' => 'overridable-template',
    ),
    'non_overridable_template' => array(
      'template' => 'nonoverridable-template',
    )
  );
}

```
> 2 votes

# Answer
1. Yes, but you have to register the template file by implementing hook\_theme.
2. No, according to http://drupal.org/node/223430, "Preprocess functions only apply to theming hooks implemented as templates".
> 1 votes

# Answer
1) Yes.

2) In Drupal 7, there is the new `hook_preprocess()`, which can be used for any theme or template function. For example, `theme_checkbox()` can be preprocessed by `YOURTHEME_preprocess_checkbox()`.
> 1 votes

# Answer
* Yes, they can. As with any theme function defined from other modules, you can override them with a template file if you implement hook\_theme\_registry\_alter().
* As reported in the documentation for theme()
> If the implementation is a template file, several functions are called before the template file is invoked, to modify the `$variables` array. These fall into the "preprocessing" phase and the "processing" phase, and are executed (if they exist), in the following order (note that in the following list, HOOK indicates the theme hook name, MODULE indicates a module name, THEME indicates a theme name, and ENGINE indicates a theme engine name):
> 0 votes

---
Tags: theming
---


# Question
Title: Breadcrumbs for a view page with arguments
How do I set the breadcrumbs for a view page with arguments? I've used the "User: username" argument, and the following PHP Code as default argument, but it doesn't work:

```
$breadcrumb[] = l('Home', NULL);
$breadcrumb[] .= l('Our Team', 'team');
drupal_set_breadcrumb($breadcrumb);

```

# Answer
I believe when you are creating a view that has an argument you can the opportunity to set a breadcrumb from within views itself.

Substitutions will also be available based on the arguments present.

For example, if you view is

```
/blogs/2011

```

Where blogs is the path to the page, and 2011 is the argument, you could set the breadcrumb of the page with the argument to be:

```
%1

```

This would leave breadcrumbs that would look like:

```
Blogs > 2011

```
> 1 votes

---
Tags: views
---


title: Theming the user registration form

text:
# Question
Title: Theming the user registration form
I want to theme the user registration form in Drupal 7 by adding new markup, etc. I cannot seem to figure out how to do it.

I've followed a few tutorials which suggested that you could simply invoke hook\_theme in template.php, and use a corresponding theme function:

```
function mytheme_theme(){
  return array(
    'user_register' => array(
      'arguments' => array('form' => NULL),
    ),
  );
}

function mytheme_user_register($form) {
  // print, die, etc
}

```

But this is not doing anything, regardless of what I do in the `theme_user_register()` function, or how many times I clear the caches.

Any thoughts about how to do this in D7?

# Answer
It turns out that I need a combination of changes:

I had to implement `hook_form_alter()`in a module and set the form's `#theme` property:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'user_register';
}

```

And then in template.php:

```
function mytheme_theme($existing, $type, $theme, $path){
  return array(
    'user_register' => array(
      'render element' => 'form',
      'template' => 'templates/user-register',
    ),
  );
}

function mytheme_preprocess_user_register(&$variables) {
  $variables['rendered'] = drupal_render_children($variables['form']);
}

```

And then I added user-register.tpl.php with my desired markup, and

```
<?php echo $rendered; ?>

```

to print the form.
> 9 votes

# Answer
The definition of the theme function given from the implementation of hook\_theme() is wrong:

* In Drupal 7, the array index "arguments" is not used anymore; you should use "render element" (as in this case), or "variables."
* The theme function receive a different argument, in Drupal 7, which is `&$variables`; in your case, you should use `$form = $variables['form']`, once you defined the theme function using the array index I reported in the previous point. See what done in theme\_locale\_date\_format\_form() (the theme function used for the form defined by locale\_date\_format\_form(), which is defined in locale\_theme(), or in theme\_status\_report(), which is defined in system\_theme().
> 3 votes

# Answer
You can use `hook_form_alter` to alter the form elements and add custom markup by adding markup form elements. It's also possible to set which theme function to use which could be your own custom theme function.

See the FAPI for more details.
> 2 votes

# Answer
I think this is possible without having to do any modules. There is a built-in theme suggestion for the user registration page and it is page--user--register.tpl.php
> 2 votes

# Answer
Here is the exact function:

@see hook\_form\_FORM\_ID\_alter

```
function hook_form_user_login_alter(&$form, &$form_state, $form_id) {
  // Modification for the form with the given BASE_FORM_ID goes here. For
  // example, if BASE_FORM_ID is "node_form", this code would run on every
  // node form, regardless of node type.

  // Add a checkbox to the node form about agreeing to terms of use.
  $form['terms_of_use'] = array(
    '#type' => 'checkbox',
    '#title' => t("I agree with the website's terms and conditions."),
    '#required' => TRUE,
  );
}

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How should I name  the node template files for my theme?
I'm a bit confused about how to name my template files. It's the first time I started to mess with templates in drupal 7 and somehow I don't get it.

I want a template file that changes the behavior of my blog posts which are on my front page. In Drupal 6 a file named node-blog.tpl.php was all I needed to mess with my blog posts.

I tried the same with Drupal 7, but it didn't work. I searched for an answer and read that the following function should be relevant for choosing the template files.

```
function template_preprocess_node(&$variables) {
  ...
// Clean up name so there are no underscores.
  $variables['theme_hook_suggestions'][] = 'node__' . $node->type;
  $variables['theme_hook_suggestions'][] = 'node__' . $node->nid;
}

```

I also read about some conversion between '-' and '\_' because '-' could not be used in function names. So I tried a few variants.

```
node__blog.tpl.php
node--blog.tpl.php
node-blog.tpl.php
node_blog.tpl.php

```

None of them is recognised by Drupal. What am I doing wrong?

# Answer
The following should work:

```
node--blog.tpl.php

```

Make sure that you also have a node.tpl.php in your theme folder and that you cleared the cache.

See also Page template suggestions are not working for more information.
> 1 votes

# Answer
Glad you got away from adding custom suggestions!

Only time that's a good thing is if you want to run several node types through the same alternate node template.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Rewrite CCK field output without using templates
The Views module has the nice option to rewrite the output of a field. This allows to adapt the output of CCK fields using Tokens without having to create a template for that view.

Is there a module that would allow a similar functionality for the "Display Fields" tab of a content type? I need to slightly modify the field output for teaser and body, but don't want to create a full template.

I'm currently using Contemplate for that, but that is more complicated than I need and unnecessary difficult if you're not familiar with the Drupal PHP API. It is also annoying that I need to modify the template every time I add an additional field to the content type, I really only need to rewrite a few fields, not the whole body or teaser.

So, what I would like to have is a simple way to rewrite each CCK field output using any token available for that content type. Does something like that exist?

# Answer
> 5 votes
Sounds like you're looking for the Custom Formatters module, very similar to Contemplate, but specifically for create Field Formatters to be used via the Display Settings page or Views.

Custom Formatters can be built with both Tokens or pure PHP code.

Additionally, Custom Formatters can be exported as native Drupal Hooks or in a custom Features exportable format.

# Answer
> 4 votes
If you're just looking to tweak the markup, Semantic CCK is worth a try.

> Semantic CCK was created to give users the means of customizing the HTML output of CCK fields. It was inspired in part by the highly recommended module Semantic Views which provides the same functionality for Views.
>
> ### Drupal 7
>
> A Drupal 7 version of Semantic CCK is currently under development: Semantic Fields.

# Answer
> 2 votes
Using the Contemplate module is not recommended, since it puts PHP code into the database, which is generally considered a security vulnerability and non-performant.
You may consider defining your own field formatters using `hook_field_formatter_info()`. This allows you to define custom callbacks that can handle each field. Browse other modules' implementation of `hook_field_formatter_info()` to see how it works. In Drupal 6, it ties in directly with `hook_theme()` while Drupal 7 uses `hook_field_formatter_view()`.

# Answer
> 0 votes
I've been fighting with this same issue for some time now too.

I can't / don't want to use...

1. Contemplate for mediocre architecture reasons.
2. Display Suite, which is awesome but overkill and doesn't actually allow simple alterations to fields.
3. Custom formatters, as it again ends up with PHP in the database for multiple value fields.
4. Field template because I'm just adding a line of text with the item.
5. Semantic CCK because that only alters the elements and classes.
6. hook\_preprocess or another code based solutions because I need it configurable.

It's a real bummer, when **all I need to do is add a CCK field description to display output.** This should actually be rather simple.

Sounds like you needed Custom Formatters.

---
Tags: entities, theming, tokens
---


title: Fork currect Drupal installation

text:
# Question
Title: Fork currect Drupal installation
Is it possible to fork current Drupal installation for experiments and have two versions of Drupal with one installation of Apache, PHP and MySQL on Ubuntu?

thank you

# Answer
> 2 votes
Yes; See the handbook page on drupal.org: Installing virtual hosts for Drupal sites and subsites.

# Answer
> 1 votes
You can install two instances of Drupal in different sub-directories of the Server root directory; when you install them, you need to use different databases, or a different prefix for the tables used from each Drupal installation.

Doing so, I was able to have an instance of Drupal 5, two instances of Drupal 6, and two instances of Drupal 7 in my test computer.

# Answer
> 0 votes
It depends on exactly what you want to do. You could obviously just have two folders with the two different versions in it, and give the database tables different prefixes on install.

---
Tags: 7, installation
---


# Question
Title: How to create different Views pages for different taxonomy vocabularies?
I have two vocabularies that require two different taxonomy view pages. For example, I have vertebrates with terms fish, cats and snakes and invertebrates with sea cucumbers, spiders and snails. I would like to create a different view for each. Can I configure Path Auto to create separate URLs passing the vocabulary term ID as an argument? If so then how do I change the link of the Term found in the Term Reference field of the node view to point to these pages? I'm thinking about installing the Taxonomy Views Integrator but would rather leave out an extra module if it's just a matter of configuring a Views argument correctly.

# Answer
> 1 votes
The Taxonomy Views Switcher does the trick. It does something clever. If the default view page path is 'taxonomy/term/%' it will walk through the paths of the. If the vid of the term is 3 it will associate the term with the view that has vid/3 in the path and will when taxonomy/term/% is called pass it -- the second view -- the argument of the term ID. Since this is a separate view it can have any field, sort, filter or display plugin.

Now I need to trigger contexts based on views that are triggered.

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


# Question
Title: How to detect if a user is in a specific directory/accessing a specific path?
For example I need to know if a user is in this directory http://example.com/directory; the value should return true if the use is on any of the following pages:

# Answer
> For example I need to know if a user is in this directory http://example.com/directory

If "directory" is a filesystem directory, then it's not possible for a Drupal function to know when a user is visiting that directory, for the simple fact Drupal is not invoked to serve the content of a directory. One of the Rewrite directives present in the .htaccess file that comes with Drupal is the following one:

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

If "directory" is the path for which a module defines a menu callback, and there isn't a directory with that name, then it is possible for a function to return `TRUE` when the user is visiting a specific path.

```
function check_path(array $directories) {
  $path = $_GET['q'];

  foreach ($directories as $dir) {
    if ($dir == $path) {
      return TRUE;
    }
  }

  return FALSE;
}

```

This function doesn't consider the path aliases. If http://example.com/path-alias is the path alias for http://example.com/real-path, `$_GET['q']` will contain real-path when the user visits http://example.com/path-alias; the same is true for `arg()`, which will return an array containing real-path.
If the function needs to consider also the path aliases, then it needs to be rewritten as:

```
function check_path(array $directories) {
  $path = $_GET['q'];

  foreach ($directories as $dir) {
    if (drupal_get_normal_path($dir) == $path) {
      return TRUE;
    }
  }

  return FALSE;
}

```
> 5 votes

# Answer
Are you looking for http://api.drupal.org/api/drupal/includes--path.inc/function/arg ?

```
arg(0); // should be 'directory'

```

That's if you're referring to path components (eg "node" and "1" in "node/1") rather than actual directories, which are a filesystem component as kiamlaluno says. But if those were actual directories, then this wouldn't be a Drupal question :)
> 3 votes

---
Tags: uri
---


# Question
Title: A module to add a field for display as a column in the administration area
I would like to display a column with the email address to the listing of users in my site's administration area. does anyone know of a module that does this?

# Answer
You can't easily extend that list directly.

The easiest way is to replace the default user list using Views and probably VBO.

See also Creating a userlist in Views (including custom user fields).
> 0 votes

---
Tags: theming
---


# Question
Title: Using "Add another" field widget on non-fields (extra_fields or Entity API properties)
I would like to have a multiple-value property attached to an entity.

Currently, all of the properties are handled with field\_extra\_field and then stored in a single database table so we don't add the overhead of lots more tables. We don't need all of the neat features of Field API like versioning, so this works.

However, we do need one feature, the multiple value handling. Is there any way to get this without making a real field?

# Answer
> 1 votes
The Examples project has an "ajax example" submodule that shows how such a thing can be done with #ajax in a form. Should get you far.

# Answer
> 0 votes
I don't really get why you don't want to use the fields API. A field only creates two tables with the default field storage module, the data and the revision table. And the revision table is only used when the entity it is attached to uses revisioning. And you can attach the same field to multiple entities. So I'm not sure what you mean with "lots more tables".

Creating a field is pretty simple, all you need to do is define the schema for your database table, the widget form and the formatter for displaying it. See http://api.drupal.org/api/examples/field\_example--field\_example.module/7.

That said, you can of course replicate the multiple value handling yourself (you can even do that and still use the field API), field\_multiple\_value\_form() is the function that contains the generic implementation for fields, which you can adapt. It basically comes down to keep track of the number of "rows" you currently have and add that amount of form elements + a button do add one more.

Image/File fields for example implement their own multiple value handling (currently totally broken in D7 when you have multiple fields) and so does my own Dynamic Properties module.

---
Tags: entities
---


# Question
Title: Is it correct to use taxonomy_term_is_page() in this code?
I am trying to get some content to show up when some conditions are verified: if I am on a certain page, the content will be shown; differently, the content is blank.
Everything looks correct; I just don't know if I am not using the correct function or something else is wrong.

```
<?php if (!taxonomy_term_is_page('18')): ?>
  <h5><a href="home/news">blah 1 News</a></h5>
<?php elseif (!taxonomy_term_is_page('28')): ?>
  <h5><a href="home/news">blah 2 News</a></h5>
<?php elseif (!taxonomy_term_is_page('29')): ?>
  <h5><a href="home/news">blah 3 News</a></h5>
<?php elseif (!taxonomy_term_is_page('30')): ?>
  <h5><a href="home/news">blah 4 News</a></h5>
<?php elseif (!taxonomy_term_is_page('81')): ?>
  <h5><a href="home/news">blah 5 News</a></h5>
<?php endif; ?>

```

This displays the results; however, when I am on one of the other terms the output doesn't change: it stays the same as the output for the taxonomy term with ID equal to 18.

My description for what I was trying to achieve has been changed; I am not trying to get anything shown based on any conditions. To put it in better words, I am trying to have the content shown; if I am on taxonomy/term/18, the content would show the else nothing would shown if I am on taxonomy/term/28 content shows and so on. It's simular to is\_front\_page function and you have content shown if you are on the front page, except these are taxonomy terms.

# Answer
Basing on the documentation of taxonomy\_term\_is\_page(), the function just checks if the current page is the page of the passed-in term. Looking at the code, the function verifies the path of the current page is "taxonomy/term/%term-id", and "%term-id" is the term ID of the taxonomy term passed as argument.

```
function taxonomy_term_is_page($term) {
  $page_term = menu_get_object('taxonomy_term', 2);
  return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
}

```

You are passing to the function the wrong parameters; you should pass it a taxonomy term object.
The code you reported is calling the function as `taxonomy_term_is_page('28')`.

If you know the term ID for the taxonomy term, then you can use the following code:

```
<?php
  $page_term = menu_get_object('taxonomy_term', 2);
?>
<?php if (!empty($page_term)): ?>
  <?php if ($page_term->tid != 18): ?>
    <h5><a href="home/news">blah 1 News</a></h5>
  <?php elseif ($page_term->tid != 28): ?>
    <h5><a href="home/news">blah 2 News</a></h5>
  <?php elseif ($page_term->tid != 29)): ?>
    <h5><a href="home/news">blah 3 News</a></h5>
  <?php elseif ($page_term->tid != 30): ?>
    <h5><a href="home/news">blah 4 News</a></h5>
  <?php elseif ($page_term->tid != 81): ?>
    <h5><a href="home/news">blah 5 News</a></h5>
  <?php endif; ?>
<?php endif; ?>

```
> 2 votes

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


# Question
Title: How to alter country dropdown in location module?
I have been researching a way to limit the available countries in the drop-down that comes with the contributed locations module. I think `hook_form_alter()` is the way to handle just showing certain countries, but starting a `hook_form_alter()` snippet from hand is not something that I have the ability to achieve. After much googling I have not been able to find a code snippet to get me started.

A project I am working on now only allows registrations from the US and Canada, so I want to limit that drop-down to just those 2 countries. The function that calls the country list is `location_get_iso3166_list()` and the array is `$countries`. The location module is being used to populate pieces in the Content Profile module.

I have found a couple posts online that suggest just commenting out the countries that are not needed in the .inc file; this is not an option for this project as we are on a multi-site set-up, so changing it in the module will affect other sites. I think I need to add a `hook_form_alter()` snippet to the template.php.

# Answer
> 3 votes
You are correct, hook\_form\_alter() is a good start. If you are looking to alter a content type form (and the CCK Location field), one method I have used is to create a really small and simple custom module implementing hook\_form\_alter(). Details/instructions on creating this module can be found below (for Drupal 6, should be similar if not the same for 7).

As an example, I am calling this module 'custom\_countries', if you want to change the name, you can always rename the files and do a search and replace in them later.

First you need to create a new folder in your modules folder (`sites/all/modules`, etc). (All files created from now on should be placed in this folder). Next, create a new file called `custom_countries.info` and put the following inside and save:

```
name = "Custom Countries"
description = "Changes the list of countries available from Location module for certain content types"
core = 6.x

```

Next, create another file called `custom_countries.module`, place the following code inside and save the file:

```
<?php
/**
 * @file custom_countries.module
 * Module to change the countries options of location module
 * for certain content type(s)
 */

/**
 * Implementation of hook_form_alter()
 */
function custom_countries_form_alter(&$form, $form_state, $form_id) {
  // Replace "YOUR_CONTENT_TYPE with the name of the content type desired
  if ($form_id == 'YOUR_CONTENT_TYPE_node_form') {
    $form['#after_build'][] = 'custom_countries_after_build';
  }
}

/**
 * Make changes to countries field after all fields are rendered
 */
function custom_countries_after_build($form_element, &$form_state) {
  // Replace FIELD_NAME with the machine name of the location field for your content type
  $form_element[FIELD_NAME][0]['country']['#options'] = array(
    'ca' => 'Canada',
    'us' => 'United States',
  );
  return $form_element;
}

```

**Important:** be sure to read the comments and change 'YOUR\_CONTENT\_TYPE' to the machine name of the content type your location field is in (possibly just 'profile' if using default content\_profile settings). Also, change 'FIELD\_NAME' to the machine name of the location field.

Finally, enable the module at `admin/build/modules`.

Now when you are creating/editing the content type you specified, you will only see 2 options in the countries list. Using this method, you can now easily make changes to other forms as well.

The idea for this came from Make Location form fields available to hook\_form\_alter(). If in the future you decide to add other countries, the complete list of key/value pairs can be found at http://api.lullabot.com/location\_get\_iso3166\_list/5

---
Tags: hooks, location, users
---


# Question
Title: Redirect users from authentication URLs to signup page
I'm using Drupal 6.

I want to redirect users from /user/login, /user/register, /user to /sign-up if the user is the anonymous user. This page would show both login and register forms together.

The only page left would be /user/password, which form I don't want to have on /sign-up.
I'm comfortable with PHP, but I'm not sure about which hooks should I use to achieve this.

PS. I already know how to print those forms on my own. My doubt is just about the URLs.

# Answer
There is no dedicated hook for things like this, but you can implement hook\_init() and then do the redirect there. Something like this:

```
function yourmodule_init() {
  global $user;
  if (in_array($_GET['q'], array('user', 'user/login', 'user/register') && !$user->uid) {
    drupal_goto('sign-up');
  }
}

```
> 1 votes

# Answer
The easy way, you can just enable Path module, and create URL aliases for the paths you want.

Go to admin/build/path/add and create the aliases. But this will keep the same page, if you want a more custom page, and you have already the form by your own, create a hook\_menu, and place the form on it.
> 0 votes

---
Tags: 6, users, redirection
---


# Question
Title: Changing a field settings on a live site in Drupal7
In the middle of entering content I discovered the length of 15 characters of a particular field I set earlier is not enough.

In Drupal6 I could change the settings of a cck field. It could be potentially dangerous, but in my case it's a lossless transform, I just want to make a maximum size of a field a little longer.

But in Drupal7 I get the message saying it's impossible to change the field settings because there is some content stored in that field in database.

This restriction seems too strict to me. A warning message seems to be enough.

So my question is what's the reasons for this behavior and what can be done in my case? Manual deleting and recreating the content is not the option.

# Answer
> 6 votes
Unlike in Drupal 6 where setting the max length of a text field didn't have any influence on the database, but merely added a validation check, Drupal 7 will actual create a column that can only hold the selected number of chars.

You can get around this, but not though the UI, as you need to alter the table in the database.

What you need to do is alter the max length of the value column in the field tables named:

* field\_data\_\[FIELD NAME\]
* field\_revision\_\[FIELD NAME\]

The column you need to change should be called \[FIELD\_NAME\]\_value

Then you need to alter the configuration, which is serialized data in the data column in the field\_config table for the field. You can either edit it directly if you are familiar with PHP serialized data or can do it with drupal\_write\_record. I believe the usual API function `field_update_field` wont work, as it should throw an exception not allowing the field to be saved, you can however use `field_info_field` to get the field data as it is stored in the database.

So in short, it can be done, but requires some custom hacking on the DB not using proper APIs.

An alternative solution would be to create a new field and migrate the data and then delete the old field.

# Answer
> 1 votes
In most cases, especially during development or testing (when I don't need the data in the field already), I would just delete the field altogether and recreate it from scratch. If you need to keep data from the field, I'd consider doing the manual process outlined by googletorp.

The new way the Field API handles explicit-length text fields may be a pain, but it can greatly speed up requests in some cases, meaning I'm okay with the configuration tradeoff. Just always try to think ahead a digit or two ;-)

---
Tags: 7, entities
---


# Question
Title: How to add CSS and JS files on node pages from theme's template.php
I am trying to add JavaScript and CSS files to one node type page from my template.php file but it is not working. Here is my template.php code:

```
<?php
// $Id: template.php,v 1.13 2010/12/14 01:04:27 dries Exp $

function mttheme_preprocess_html(&$variables) {
  $node = node_load(arg(1));
  if ($node->type = 'sales_team_page') {
    drupal_add_css('misc/jquery.fancybox-1.3.4.css');
    drupal_add_js('misc/jquery.mousewheel-3.0.4.pack.js',
      array('type' => 'file', 'scope' => 'header')
    );
    drupal_add_js('misc/jquery.fancybox-1.3.4.pack.js',
      array('type' => 'file', 'scope' => 'header')
    );
    drupal_add_js('misc/jquery.fancybox-calls.js',
      array('type' => 'file', 'scope' => 'header')
    );
  }
}

```

Does anyone know why it is not working?

# Answer
Since you want your CSS and JavaScript when displaying a node, you can add the files it in the preprocess function for the node template. Also, as stated in their documentation, when adding a file, the first argument for `drupal_add_css()` and `drupal_add_js()` is the path the CSS/JavaScript file **relative to the base\_path()**. You can use `drupal_get_path('theme', 'THEME')` to get the path of your theme relative to the base path.

```
function THEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full') {
    $node =& $variables['node'];
    if ($node->type == 'sales_team_page') {
      $path = drupal_get_path('theme', 'THEME');
      drupal_add_css($path . '/misc/jquery.fancybox-1.3.4.css');
      drupal_add_js($path . '/misc/jquery.mousewheel-3.0.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-1.3.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-calls.js', array('type' => 'file', 'scope' => 'header'));
    }
  }
}

```

Also, doing `$node = node_load(arg(1));` to load the currently viewed node is unsafe and wrong. If you have a *non node* page at `whatever/42` but have an existing `sales_team_page` node with nid = 42, you will load this node and add your CSS and JavaScript files even if the user is not viewing the node.
> 7 votes

# Answer
Probably because you dont get the node type correctly. Use preprocess node in order to capture the node type correctly.

```
function mttheme_preprocess_node(&$variables) {
 if ($variables['type'] == "sales_team_page"){
   drupal_add_css(drupal_get_path('theme', 'mttheme') . 'misc/jquery.fancybox-1.3.4.css');
   //add js in the same way using drupal_get_path()
 }
}

```

You can also add them through your .info file of your theme :

```
name = Your theme
core = 7.x
engine = phptemplate

scripts[] = my_js.js

```
> 1 votes

---
Tags: javascript, theming
---


# Question
Title: Clearing the cache changes the nice menu every time
Maybe this isn't a cache problem, but I am using Drupal 6, I have cache disable and I am editing a custom nice menu CSS file.

I didn't see changes right away to my nice menus, so I cleared the cache in the performance page, and the menu would revert back to old changes. When I cleared the cache again, it randomly found new settings for Nice Menu.
I then installed Devel, and cleared the cache, but it didn't help. Clearing the browser cache didn't help either.

Do you have any idea?

# Answer
If you have turned CSS file aggregation off, changes take effect immediately unless you have an external cache like Varnish of the css file. If you are not seeing changes after checking this, maybe your CSS file is not included or the rules implemented is overridden by other CSS rules.
> 1 votes

---
Tags: caching, theming, navigation
---


title: Updating a block inside an update hook

text:
# Question
Title: Updating a block inside an update hook
I want to update the configuration (weight, pages, region) of some blocks within an update function. I know I could do this directly inside the database. Is there a better way of doing this? I scanned http://api.drupal.org, but I didn't find anything like `block_load()` and `block_save()`.

Do you have any idea?

# Answer
> 1 votes
No, there is no such thing.

One of the typical update block configuration tasks was changing the cache flag (before 6.22, that is). You can find updates that mess with the {block} table directly in many projects, including mine: privatemsg\_update\_6002().

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


title: Can you bulk enable comments?

text:
# Question
Title: Can you bulk enable comments?
I have a whole bunch of nodes (all the same type), and I'd like to turn comments on for all of them (the client changed their mind about commenting after all of the data was added).

I've found notes that suggest that if I do something like:

```
update node set comment = 2 where type = 'foo'

```

then it should turn commenting on for all the nodes of type foo. However, this doesn't seem to work in Drupal 7, and the notes on drupal's site only specify 5 and 6.

I tried flushing caches and bouncing apache after making the change, and still can't see comments coming back on. Did this change in Drupal 7?

# Answer
> 7 votes
That will work; don't forget node\_revision.

```
UPDATE NODE SET comment = 2 WHERE type = 'foo'
UPDATE node_revision SET comment = 2 WHERE nid IN (SELECT nid FROM node WHERE type = 'foo')

```

# Answer
> 12 votes
I'd also recommend Views Bulk Operations. You could create a view with a filter of that content type and add enable comments as an action. Then it offers you to select all.

Quite the useful admin tool.

---
Tags: 7, database, comments
---


# Question
Title: Module to upload a file for attachment to many nodes as a bulk operation
I have a large number of nodes created with a large subset for a specific term that I would like to add one file to all of these nodes at one time.

For a single case, I have a CCK field for uploading a file. If I had to do this one by one for every node, it would take a long time.

At this time, I am planning on writing code to do this work using code to query the db for all nodes for the term, and loop over each of those attaching the file to the CCK field of each node.

There's one file on the server, I want to attach it to many nodes as a bulk operation, rather than attach the file to each node, one by one. This seems like a problem that would have been run into before. Is there any suggestions on modules that might already do what I want?

# Answer
If you want to do it a little easier, Views Bulk Operations *might* be helpful. But otherwise, adding the file to one node, then adding a reference to the file from all the other nodes is the best solution (this way the file isn't independently added to hundreds of nodes, creating hundreds of duplicate files).

You should also check out how FileField Sources adds references to existing files for inspiration.
> 1 votes

# Answer
If I should do that without thinking to a better solution, I would create a batch in a module and add the file to the node. Creating batches is really simple, you'll find tutorial.

Another solution, would be, if you have to copy the SAME file to every node, is to make a node reference to the node containing the file.

This way, you can easily create a batch and set the nid to the right field

```
$node->field_file_reference[0]['nid'] = THE_NID_OF_THE_NODE_CONTAINING_THE_FILE;

```

I hope this helps...
> 0 votes

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


# Question
Title: How do I set the active menu item dynamically for a view?
How do I change the active menu item when showing a view? How do I dynamically set the active menu item? shows how to do for nodes (using `hook_nodeapi()`), but how can I achieve the same for a view?

I tried `hook_views_pre_view()`, but that doesn't work.

# Answer
You could use Context and set condition to be your view and reaction to be menu link.
> 1 votes

# Answer
One thing you could try is to use the Menu position module, it lets you make rules for when and what menu item is selected. Also Menu trails is something you could check out.
> 0 votes

---
Tags: views, 6, navigation
---


# Question
Title: Problem while using the user_reference field in my bundle
I am creating an entity for my D7 Module and trying to include a user\_reference auto-complete field in it. The autocomplete-field shows up correctly with the add-more option since I have set cardinality to unlimited.

However, nothing shows up in auto-complete suggestions and it doesn't accept any of the user-instances.

Even more annoying is that when I go and check the field settings in Home » Administration » Structure » Content types » » Manage fields and click on Save without making any changes, the suggestions start appearing correctly as they should.

I have written down the following settings for the field and the instance.

field :

```
'vocabulary_authors' => array(
      'field_name' => 'vocabulary_authors',
      'type'        => 'user_reference',
      'settings' => array(
        'referenceable_roles' => array('2','3'),  // for authenticated user + administrator
        'referenceable_status' => array('1'),    // for active
      ),
      'default_widget' => 'user_reference_autocomplete',
      'default_formatter' => 'user_reference_default',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ),

```

instance :

```
'vocabulary_authors' => array(
      'field_name'  => 'vocabulary_authors',
      'label'       => $t(' Authors'),
      'bundle' => 'vocabulary',
      'entity_type' => 'node',
      'description' => '',
      'required'    => FALSE,
      'widget' => array(
        'type'    => 'user_reference_autocomplete',
        'settings' => array(
         'autocomplete_match' => 'starts_with',
        ),
      ),

```

Please help me out here. I think I am I missing out on some required settings.

# Answer
> 1 votes
You are missing the `module` definition, though I'm not sure it's required.

The easiest thing to do it so use `field_info_field` and `field_info_instance` for the field to see what info Drupal provides and fill in the blanks until every works.

---
Tags: 7, entities
---


# Question
Title: Help with adding different stylesheet to one specific page in Drupal 7 using the template.php
I am trying to apply a CSS style (games.css) to page--type--games.tpl.php. I am using Drupal 7, and I have created a new content type called "games."

So far, my code works for pulling up the page--type--games.tpl.php, but it has been unsuccessful in applying the CSS stylesheet. This is my current version of the code.

```
/**
 * Add javascript files for front-page jquery slideshow.
 */
if (drupal_is_front_page()) {
  drupal_add_js(drupal_get_path('theme', 'bluemasters') . '/js/bluemasters.js');
}

function bluemasters_preprocess_page(&$variables, $hook) {
  //some other stuff
  if (isset($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__type__'. $variables['node']->type;
    $variables['theme_hook_suggestions'][] = "page__node__" . $variables['node']->nid;
  }

  if (drupal_get_path_alias("node/{$variables['#node']->nid}") == 'games') {
    drupal_add_css(drupal_get_path('theme', 'bluemasters') . "/games.css");
  }
}

```

# Answer
`drupal_get_path_alias("node/{$variables['#node']->nid}")` will be equal to "games" only in the case "games" is the path alias for the node being shown.

If you just want to verify the content type of the node being shown is "games," then you need to use code similar to the following one:

```
if ($variables['node']->type == 'games') {
  drupal_add_css(drupal_get_path('theme', 'bluemasters') . "/games.css");
}

```

To notice that a page preprocess function is called also for pages that are not associated to nodes; the function should first verify if it gets a node object, before to access it.
The complete code of the preprocess function should be like the following:

```
function bluemasters_preprocess_page(&$variables, $hook) {
  if (!empty($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__type__'. $variables['node']->type;
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->nid;

    if ($variables['node']->type == 'games') {
      drupal_add_css(drupal_get_path('theme', 'bluemasters') . "/games.css");
    }
  }
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: How to pass an array or an object from a module to a theme
I have used hook\_menu() with a page callback as follows:

```
function profilecb_menu() {
  $items['profilecb'] = array(
    'title' => 'Profile CB',
    'page callback' => 'pcb_exe',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

The callback code is the following:

```
function pcb_exe($id) {
  $ar = array('arg1'=> 'value1', 'arg2'=> $id);

  return $ar;
}

```

I have been able to make the callback function return a single string; when I try to return an array, I get an error.

All I need to do is to make the callback function do some tasks, like connecting to the database, and return to a template a complex array of useful information.

How can I do that?

# Answer
In Drupal 6, a menu callback needs to return a string that contains the HTML to output together the output of other modules; alternatively, it can print the output and call `exit()`.

If you need to pass an array to a theme function, then the output returned from the menu callback should be output from a theme function to which the menu callback passes an array.

```
function pcb_exe($id) {
  $ar = array('arg1'=> 'value1', 'arg2'=> $id);
  return theme('pcb_exe_output', $ar);
}

```

In Drupal 7 (and higher versions), the output of a menu callback is normally an array that has the format used by drupal\_render().
It still possible to pass an array to a theme function, but the parameters passed to a theme function changed.

```
function pcb_exe($id) {
  $ar = array('arg1'=> 'value1', 'arg2'=> $id);
  return theme('pcb_exe_output', $ar);
}

```

In this case, there is no noticeable difference, as the parameter passed to the theme function was already an array. The parameter passed to a theme function since Drupal 7 is an array containing all the values required from the theme function. See the code of theme\_vertical\_tabs() as example:

```
function theme_vertical_tabs($variables) {
  $element = $variables['element'];
  // Add required JavaScript and Stylesheet.
  drupal_add_library('system', 'drupal.vertical-tabs');

  $output = '<h2 class="element-invisible">' . t('Vertical Tabs') . '</h2>';
  $output .= '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
  return $output;
}

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Why isn't code for $op == 'presave' being executed in hook_nodeapi?
I want the administrator users can publish nodes of the story content type; the other roles can unpublish. The following is the code I am using, but it doesn't work. I unchecked the box "published", which is in the "story" content type.

```
   function mymodulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
     global $user;

     if ($op== 'presave' && $node->type == 'story') {
       if (in_array('administrator',array_values($user->roles))) {
         $node->status = 1;
       }
     }
   }

```

I am using `echo 'test'` above on the `if ($op....)`, the page outputs "test." When I put the `echo 'test'` into `if` body, the page doesn't output "test." but When I delete `$op == 'presave'`， it can output "test."

# Answer
> 1 votes
Regarding your problem, you're editing the node right ? Because `presave` acts during saving.

On a site I use this module which is quite handy, maybe it can help you: Publish Content

---
Tags: 6, nodes, hooks
---


title: Adding a Space Context Condition

text:
# Question
Title: Adding a Space Context Condition
I want to add a condition of what type of space is currently active on the site. Does anyone know of a module that supports this?

I notice that spaces is setting a context for us, but I cannot find the relevant plugin or set the condition up in Context UI.

```
function spaces_set_space($space = NULL) {
  static $active_space;
  if (isset($space)) {
    $active_space = $space;
    if (module_exists('context') &&
        $plugin = context_get_plugin('condition','spaces_type')
        ) {
        $plugin->execute($space);
    }
  }
  return isset($active_space) ? $active_space : FALSE;
}

```

# Answer
If you can figure out the name of the contexts made available from spaces, you can use the condition that is triggered by other active contexts. I personally have not heard of spaces creating context on their own however. You may also consider writing your own plugin/module as this is relatively simple to do. I myself used the path condition files to create the context keywords module(http://drupal.org/project/context\_keywords). You could honestly probably reuse 90% of the code from mine, and just change the part that returns true or false.
> 1 votes

# Answer
That code you posted looks like it would do what you wanted? Maybe you'd be better off filing an issue in the Spaces issue queue rather than here?
> 1 votes

---
Tags: 7
---


# Question
Title: How do I return the output from a callback function unthemed?
I have a custom module with a `hook_menu()` "page callback" function, a custom theme function and a `hook_theme()` implementation. This module is working fine and the final output of the module is passed to the template of my site.

However, what I would like to do is to have the output of the module to be displayed on its very own - nothing else. That is:

what it does now:

```
hook_menu --> page callback function --> custom theme function --> hook_theme implementation --> .tpl.php template file

```

what I would like it to do:

```
hook_menu --> page callback function --> return a <div> to be displayed on its own

```

Can anyone help?

# Answer
> 4 votes
This is really easy: instead of returning the output in the page callback, just print it and exit.

### Drupal 6

```
function foo_callback() {
  print theme('foo');
  exit();
}

```

One thing to keep in mind when doing this is that `hook_exit()` will not be invoked, as you'll be ending the script before Drupal reaches that point, so make sure you don't need it. If you do, you can invoke it yourself before calling `exit()`:

```
function foo_callback() {
  print theme('foo');
  module_invoke_all('exit');
  exit();
}

```

### Drupal 7

`drupal_exit()` was added for this use-case, and will call all the shutdown stuff before exiting. So you just need:

```
function foo_callback() {
  print theme('foo');
  drupal_exit();
}

```

---
Tags: 7, theming
---


# Question
Title: How do I import an RSS feeds into nodes?
I'm looking for a way to import an RSS feeds into nodes.

This is an example of RSS feeds that I'm trying to import:

```
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
  <title>List of changes (3244034544-3243867643)</title>
  <link>http://matt.dev.openstreetmap.org/owl_viewer</link>
  <description>Changes for range 3244034544-3243867643</description>
    <item>
    <title>Changeset 7989922 by Drupol</title>
    <description>
      <![CDATA[<p>By <a href="http://www.openstreetmap.org/user/Drupol">Drupol</a> covering 6 tiles, with comment "Colfontaine et alentours", using "JOSM/1.5 (4021 en)". View changeset on <a href="http://www.openstreetmap.org/browse/changeset/7989922">main OSM site</a>.</p>]]>
    </description>
    <pubDate>Wed, 27 Apr 2011 23:19:19 +0100</pubDate>
    <link>http://matt.dev.openstreetmap.org/owl_viewer/tiles/7989922</link>
    <guid>http://matt.dev.openstreetmap.org/owl_viewer/tiles/7989922</guid>
  </item>
  <item>
    <title>Changeset 7989942 by Drupol</title>
    <description>
      <![CDATA[<p>By <a href="http://www.openstreetmap.org/user/Drupol">Drupol</a> covering 1 tiles, with comment "Colfontaine et alentours", using "JOSM/1.5 (4021 en)". View changeset on <a href="http://www.openstreetmap.org/browse/changeset/7989942">main OSM site</a>.</p>]]>
    </description>
    <pubDate>Wed, 27 Apr 2011 23:19:19 +0100</pubDate>
    <link>http://matt.dev.openstreetmap.org/owl_viewer/tiles/7989942</link>
    <guid>http://matt.dev.openstreetmap.org/owl_viewer/tiles/7989942</guid>
  </item>
  .
  .
  .

```

I use the module Feeds and a simple importer to import the data.

What I would like to do is importing the Changeset ID, Username and Comments into CCK fields.
I've created my node 'OSMLOG' and the 3 custom fields.

Back in Feeds, I map the title to the $node-\>"OSM Chanseget Field", again title to $node-\>"OSM Username", and software to $node-\>"OSM Software".
Then I create my own module to work on data before assigning them:

```
/**
 * Implementation of hook_feeds_node_processor_targets_alter().
 */
function mymodule_feeds_node_processor_targets_alter(&$targets, $content_type) {

  dpm($content_type);

  if ($content_type == 'osmlog') {
    $targets['field_osmlog_software'] = array(
      'name' => t('OSM Log Software'),
      'description' => t('OSM Log Software'),
      'callback' => 'mymodule_set_target'
    );
    $targets['field_osmlog_changeset'] = array(
      'name' => t('OSM Log Changeset ID'),
      'description' => t('OSM Log Changeset ID'),
      'callback' => 'mymodule_set_target'
    );
    $targets['field_osmlog_user'] = array(
      'name' => t('OSM Log User'),
      'description' => t('OSM Log User'),
      'callback' => 'mymodule_set_target'
    );
  }
}

/**
 * Mapping callback.
 */
function mymodule_set_target($node, $target, $value) {
  $node->$target = "Testing";
}

```

If I do that, nothing is working, it seems that is never goes into the callback. I'm pretty sure that it goes into the hook\_feeds\_node\_processor\_targets\_alter() but not in the callback. Is there a good documentation on how to setup such things with Feeds ?

# Answer
Since you're trying to parse XML, you can avoid having to create your own Feeds parser. Instead, use Feeds XPath Parser.

What it'll do is expose a couple of new parsers including *XPath XML Parser*. You can then map arbitrary XPath queries to fields.

So you'd map `xpathparser:0`, `xpathparser:1`, `xpathparser:2` to your CCK fields for Changeset ID, Username, and Comments, respectively.

Then, in the parser settings, you'd use the following XPath queries:

* **Context:** `//item`
* **`xpathparser:0`:** `substring-after(substring-before(title, ' by'), 'Changeset ')`
* **`xpathparser:1`:** `substring-after(title, ' by ')`
* **`xpathparser:2`:** `description:text()`

*(Note: I couldn't figure out what you were referring to when you said "comments", so I guessed it was the `<description>` element. Modify to your needs if it's another element.)*

If you need to provide this importer programmatically, Feeds is Features aware, and the importer can be easily exported and provided as a custom Features module.
> 1 votes

---
Tags: 6, feeds
---


# Question
Title: Passing an extra element to $edit array when creating an account
I added an extra user registration validation critera in my custom module by implementing hook\_user

```
if ('validate' == $op && 'user_register' == $edit['form_id'] && 'account' == $category && !$edit['remote_create_user']) {

    // Is the mail address OK?
    if ($email_in_use) {
    // No, set error on mail form field
    form_set_error('mail', t('Your email address is already associated with a account.'));
    }

```

I added the `!$edit['remote_save']` because I don't want this extra validation if I am creating accounts programmatically. The code I am using to create accounts is

```
 $form_state['values'] = $account;
    $form_state['values']['pass'] = array(
      'pass1' => $account['pass'],
      'pass2' => $account['pass'],
    );
    $form_state['values']['op'] = t('Create new account');
    $form_state['values']['remote_create_user'] = TRUE;
    $ret = drupal_execute('user_register', $form_state);

```

As you can see, I tried to add an extra form element called 'remote\_save' `$form_state['values']['remote_save'] = TRUE;`. However, in the hook code above $edit\['remote\_save'\] is empty so I can't use it to stop the extra validation. How can I pass a value from $form\_state to the $edit array? Or is there a better way to do this?

EDIT: So I tried to use hook\_form\_alter with the code below

```
function module_form_alter(&$form, &$form_state, $form_id)  {
  if ($form_id == 'user_register') {
    $form['remote_create_user'] = array('#type' => 'value', '#value' => FALSE);
  }
}

```

However this code `$form_state['values']['remote_create_user'] = TRUE;` which is in a separate module, does not set the value of $edit\['remote\_create\_user'\]. The value of $edit\['remote\_create\_user'\] is still false.

# Answer
If you are actually trying to prevent a user from registering with an email that is in use, Drupal already has that built in. It also has a check that prevents users with an IP in the blocked IP address list to create an account.

**Solution**

Your flaw in the above code is that `drupal_execute` calls `drupal_process_form` which will rebuild the `$form_state['values']`. A solution could be to add a hidden/value form element to the user\_register form with `hook_form_alter`. Doing that should allow you to send your custom value through `drupal_execute`.
> 1 votes

---
Tags: forms, 6, hooks
---


title: Feeds Import csv - inline images

text:
# Question
Title: Feeds Import csv - inline images
I'm using the feeds module to import thousands of nodes into my Drupal 6 site (the source is a Drupal 5 site) and after figuring a few things out, it actually works really nicely! I just have one problem though, most of these nodes are supposed to contain inline images, and I'm wondering how to recover them as they don't come with the import...?

Thanks!

# Answer
Under the settings of the importer (Feeds -\> (Importer name -\>) Processor -\> Node processor -\> Settings) is the Input format set to default? If so, is the default Filtered HTML? That might remove the images. You could you try changing this to Full HTML...
> 1 votes

# Answer
If the enable full html does not work try using Feeds Image Grabber
> 3 votes

---
Tags: 6, media, feeds
---


# Question
Title: I need to bring a site to version control, and set up the continuous Integration environment
I am an entrepreneur with a Drupal 6x project that started small enough to not need version control (per developers), but now I am convinced there is no way without it. There's extensive documentation on JIRA, complete with well-written User Stories covering everything. I read up a bit about how this could be done and came up with the following plan -

1. Separate site code from database using modules
    1. Context
    2. Features
    3. Strongarm
    4. Profiler
2. Put the code in a SVN repository and create a staging site
3. Create a mirror of the staging server on EC2 production server
4. Create Selenium tests, and run them on the cloud using Saucelabs
5. Create a build workflow in JIRA Studio using Elastic Bamboo to run automatic updates
6. Update and install profiles using Drush Make
7. Run updates on production server (I am not sure how)

To begin with, I have made a list of about 50 "Features", each with its components (views, content types, modules etc). This will no doubt be challenging as the site contains about a dozen custom modules and web services, not to mention another dozen instances of content type "application" containing custom code (most of which I would like to have converted to upgradable views or modules). The good thing is that the site is not yet in production so the risk is still limited.

Does anyone have any experience in doing something similar? What pitfalls and limitations should I expect to encounter? I would greatly appreciate any suggestions for improving/correcting the above plan, or any insight or advice that you experts out there might have for me.

# Answer
> 23 votes
Ok, I'll give this a try :) I won't be able to fully answer your question, but maybe give you have few interesting hints. Note that my numbering is not in direct response to yours :)

1. As I already mentioned in the comment, no project is too small for version control. I personally recommend Git. Reasons are the plain awesome speed of it (wait time in git is measured in milliseconds, not seconds) and the huge amount of features. It can be a bit hard to pick up, because of weird names and arguments but the following documentation explains many of them *really* good: http://www.eecs.harvard.edu/~cduan/technical/git/. Another reason is that it is now used by drupal.org, so knowing git will help you when you want to contribute back (providing patches, testing patches, release modules, ...)
2. That said, if you'd like to use SVN for some reason (like integration with services you plan to use), then go for it. SVN works reasonable well too and is much better than no source control. (Unless you ask Linus Torvalds..). Also, there are often ways to migrate from one VCS to another if you change your mind. SVN -\> Git works well, for example.
3. Third, approach this step by step. Don't try to do everything at once. Give you (and your developers) the time to learn the new tools.
4. Switching from Drupal 6 to Drupal 7 is not a trivial thing. Especially with a lot custom code. Note only are there tons of API changes and new concepts (like the entity/field system), there is also the point that many contributed modules aren't fully ready yet.
5. Deployment management *is* one of the weak points of Drupal, that also hasn't changed that much in Drupal 7. We are aware of the problem and people are working hard to resolve this for Drupal 8: http://groups.drupal.org/build-systems-change-management/cmi. Features etc. helps, but it's not a silver bullet. Not everything can be exported as a feature.
6. There are also a few Drupal-specifc options for deploying staging/production sites. Pantheon (still in beta) and Acquia Dev Cloud might be worth checking out.
7. Continuous integration, automated testing is important and really useful *but* also require time to set up, write the tests and so on. Time you might or might not have at this point. But especially automated tests is an area where it is easy to do incremental improvements. Once you have a environment set up to run them, you can write more and more tests as time permits.

So, here is my *recommendation* for the updated question in the comment:

Finish and release as is, *but* start using a VCS (version control system) for Drupal 6 now. Create a staging environment for your site. Look at what (contributed) modules you are using and check if a port to Drupal 7 is feasable at that point. Don't underestimate the time that will take. Also start to improve the testing/deployment process, starting with what you think will bring you the most benefits/cost.

You can also create more specific follow-up questions or look those which already exist. As you can see, even only giving a few hints to a question like this can get huge and take quite a bit of time.

---
Tags: features, 7, version-control, drush
---


title: How to use theme_hook_suggestions()

text:
# Question
Title: How to use theme_hook_suggestions()
I'm on page of my website and I'm viewing it with the theme developer module, which gives me a lot of information. It gives me some theme suggestions based on theme\_hook\_suggestions() which are:

```
html__profile_personal
html__profile_personal__%
html__profile_personal__113
html__profile_personal__edit

```

How can I create a new theme for this page? What naming convention should I use, given the info above?

# Answer
> 1 votes
Replace the underscore with a hyphen, and you get the name for the template file.

If the suggestions you are getting are the ones reported by theme\_get\_suggestions(), then they are the ones returned from template\_preprocess\_html() for a page at /profile\_personal/113/edit.

The first suggestion would be applied for all the pages with a path starting with /profile\_personal/; the last suggestion would be applied also for a page with path /profile\_personal/edit, and the one before the last would be applied also for /profile\_personal/113/revisions.

Whichever you choose, you should always check the path of the currently show page, via arg().

---
Tags: 7, theming
---


# Question
Title: How do I retrieve the field data  associated with an entity, using EntityFieldQuery?
I'm still confused about the entity concept in Drupal 7. I have a node type audio with an MP3 field. I'm able to use `EntityFieldQuery` to find all the audio nodes, but I need the URL of the MP3, which is stored in the "file\_managed" table, and I don't find a way to retrieve it.

This is what I have:

```
// Query audio nodes
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'audio')
  ->propertyCondition('status', 1);
$result = $query->execute();

```

There is no URL in the `$result` array. At least I can't find it there; I only get the fid.

# Answer
When EntityFieldQuery::count() is not invoked, what returned from EntityFieldQuery::execute() is an array having the following structure:

```
[entity type] => array([entities])

```

```
[entity] => array([relevant ID] => [entity object])

```

The relevant ID is normally the entity ID, as in the query you reported. See entity\_create\_stub\_entity(), and entity\_get\_info() to understand what information the entity object contains.

To get all the fields associated with the entity you are querying, you just need to execute the following code.

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

if (!empty($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']);
}

```
> 3 votes

# Answer
`EntityFieldQuery` doesn't allow for adding addition field data to the query result. You can load the entities afterwards. From the documentation:

```
$result = $query->execute();
$entities = entity_load($my_type, array_keys($result[$my_type]));

```

In the above example, `$mt_type` is your entity type (node).
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Can Drupal be configured to find modules in other locations?
I put my modules in sites/all/modules. Is there a way to configure Drupal to find more modules in other locations as well?

---

Edited

I use Virtual Hosts often but not in the way you described. The format I'm familiar with looks like this, and it helps me put the entire work project somewhere else not inside www.

```
<VirtualHost *:80>
    ServerName testdrupal.com
    DocumentRoot "C:/proj/testdrupal"
    ServerAlias testdrupal.com

   <Directory "C:/proj/testdrupal/">
       Options Indexes MultiViews FollowSymLinks
       AllowOverride All
       Order allow,deny
       Allow from all
   </Directory>
</VirtualHost>

```

I think what you're describing is something different, right? I'm trying to leave the drupal folder inside www as usual, but move only the sites/all/modules to another location, but I still can't figure out how the VHost entry will look like in this case. Let's say I want to move it to C:/proj/testdrupal. I hope I didn't completely misunderstand you.

# Answer
Before answering, it's helpful to have a little background about how Drupal finds modules. Drupal uses a list of suggestions from the Drupal root to figure out where to find modules. In order of priority:

1. `sites/$SITENAME/modules`
2. `sites/all/modules`
3. `profiles/$INSTALLPROFILE/modules`
4. `modules`

If Drupal doesn't find a module in **(1)**, it checks **(2)**. If it's not there, it checks **(3)**, and so on.

For **(1)**, if you're just using a basic, single-site install of Drupal, `$SITENAME` is `default`. Otherwise:

* In Drupal 6, `$SITENAME` is the host name of the site. If your site is located at `example.com`, `$SITENAME` would be `example.com`.
* In Drupal 7, `$SITENAME` is defined in `sites/sites.php`. If you look at `example.sites.php`, you can see how to define it. It's also important to note that any module listed there will only be usable for that specific sites, not all sites.

In **(2)**, any module found there will be usable on any site in the Drupal installation. It will also be left untouched when you upgrade the core installation. This is, of course, the recommended place to put modules and likely all documentation you've read have told you to put your modules here.

**(3)** is used for installation profiles that require a specific module. Installation profiles are essentially a way to define a custom initial state for a Drupal site. For example, Drupal comes with two installation profiles built in: Standard, which includes most-used features, and Minimal, which only includes the bare minimum needed for a Drupal site to function.

**(4)** is used by Drupal core. While you can technically add modules here and they will be available for all sites, **you shouldn't. Seriously.** The `modules` folder is touched when Drupal core is updated, and will cause problems down the line if you're sticking modules you need for your site to function there.

---

Now that the background is out of the way, you can use file system tricks to have your modules housed outside of where Drupal looks.

For example, you could set up a symbolic link from `sites/all/modules` to another directory outside of the Drupal installation:

* In Unix/Linux/BSD-based systems: `ln -s /path/to/modules/folder /path/to/drupal/sites/all/modules`
* On Windows Vista/Server 2008/7 and higher: `mklink C:\path\to\drupal\sites\all\modules C:\path\to\custom\modules\folder`

As far as I'm aware, there's not much you can do in earlier versions of Windows that don't have mklink.
> 14 votes

# Answer
In Drupal 7, the directories where Drupal looks for modules are the following:

* modules
* profiles/$profile/modules
* $config/modules

$profile is the value returned from drupal\_get\_profile(); $config is the value returned from conf\_path().
The function that searches for system object files (modules, themes, etc) is drupal\_system\_listing().

The same directories are looked for, in Drupal 6. The only difference is that $profile is a global variable; when the global variable is not set, the function gets the value of the "install\_profile" persistent variable, which has the default value of "default."
> 3 votes

# Answer
You can place them either in sites/all/modules, then they will be available to all sites (if you have a multi-site configuration), in sites/default/modules for the default site or sites/site.com/modules if you have that. For the latter directories, this means that they will only be available to that specific site.

Additionally, you can organize them as you want below those folders, meaning, you can create whatever sub-folders in there. A typical thing to do is creating a contrib folder and then place modules downloaded from d.o there while keeping self-written modules for that site in a custom folder.
> 2 votes

# Answer
Not sure what you mean, but we use a somewhat common convention of seperatating in-house modules from 3rd party modules.

'Home-made' custom modules would be in:

> sites/all/modules/custom

3rd party modules would be in:

> sites/all/modules/vendor

If having subdirectories does not match your needs, I believe you could easily symlink your /obscure/path/to/module directory into your drupal's module directory.
> 1 votes

---
Tags: files
---