# Question
Title: Factors regarding menu visibility (menu is missing on access denied)
I've built a theme based on Zen starterkit, and recently noticed that my main menu is not rendering on any access denied pages (non-admin role obviously), however, the remaining content is rendered as expected. What are the likely causes & recommended solutions? Is this a Zen thing?

# Answer
So if you're ever missing something in your site, consider these factors when diagnosing:

* check the raw markup itself (HTML) ensure it's not a CSS issue.
* a permissions problem, does the role have access?
* can you narrow the problem to the theme... this will determine further courses of action
> 0 votes

---
Tags: users, routes
---


# Question
Title: Move Drupal site from localhost to remote production server
I want to move my Drupal 7 site to a remote server. I searched the Internet for a solution, but the information I found were cluttered. Can someone care to write step-by-step how-to or provide a link?

# Answer
That would depend a lot on the production server environment, and other factors.

Basically, you just copy the database to the server (along with perms), the Drupal filesystem (perms, etc), and point your web server at the correct directory in the filesystem.

Provide more information for a more detailed reply.
> 1 votes

# Answer
You can follow this steps and move your site to production server:
On your local site

1. Install Backup and migrate, which will take the backup of the database (**admin/config/system/backup\_migrate**).
2. Install Backup and migrate files which will enable you to take a backup of your public files in the directory defined at *admin/config/media/file-system*.

On the production server

1. Install fresh copy of Drupal.
2. Copy the modules and themes from localsite's *sites/all/modules* and *sites/all/themes* to the respective folders on the fresh install of dev server.
3. Enable the Backup and migrate module and backup and migrate files module.
4. Go to **admin/config/system/backup\_migrate/restore** and restore the backed up database and public files which you exported at your local site.
> 2 votes

---
Tags: 7, migrations
---


# Question
Title: Recommend a theme function to modify the 'Submitted by' line for a node?
I would like to theme the 'submitted' by date without editing the node.tpl.php file. In other words, in the template.php file.

I know this has been answered thousands of times before, but for the life of me I cannot find a good solution when searching.

Can someone suggest a theme function that uses `format_date()` or other means to manipulate this however I see fit? Specifically, I simply need to say *Submitted by: admin 2012/10/10* but I would like something to keep in my toolbox as this problem comes up on every single project I do.

# Answer
> 1 votes
You can alter the node info using `template_preprocess_node`

```
function template_preprocess_node(&$variables) {
 // your code
}

```

> The $variables array contains the following arguments:
>
> $node
>
> $view\_mode
>
> $page

**This is the default value**

```
$variables['submitted'] = t('Submitted by !username on !datetime', array('!username' =>
  $variables['name'], '!datetime' => $variables['date']));

```

You can override is as you wish. Give a try.

---
Tags: 7, theming
---


# Question
Title: hide the author information from the non-member
I use Drupal-7.14 and the default theme,Bartik 7.14. I added "my content type" as a new content type. Then I could see a new content foo by the url hostname/content/foo.

The content foo shows the author and the date because I checked

Structure \> Content Types \> my content type \> edit \> Display Settings \> Display author and date information.

Only the date should be shown from logouted users. The author should NOT be shown for logouted users.

How can I hide the author information from the non-member.

# Answer
If you copy the `node.tpl.php` file from the templates directory and create a `node--mycontenttype.tpl.php` file you should see the following around line 91:

```
<?php if ($display_submitted): ?>
  <div class="meta submitted">
    <?php print $user_picture; ?>
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

```

Simply change it to this:

```
<?php if ($display_submitted): ?>
  <div class="meta submitted">
    <?php print $user_picture; ?>
    <?php if ($logged_in == TRUE): ?>
      <?php print $submitted; ?>
    <?php endif; ?>
  </div>
<?php endif; ?>

```

The `$logged_in` variable is a node template variable that has the value of TRUE if a user is logged in.

In this snippet you're just saying if the user is logged in, then display the submitted information.

Don't forget to clear your caches!

**EDIT**

Apologies, I've read the question properly now. The following should do what you want.

```
<?php if ($display_submitted): ?>
  <div class="meta submitted">
    <?php print $user_picture; ?>
    <?php if ($logged_in == TRUE): ?>
      <?php print $submitted; ?>
    <?php else: ?>
      <?php print $date; ?>
    <?php endif; ?>
  </div>
<?php endif; ?>

```

This will display the entire submitted by text for authenticated users, and just the date for anonymous users.
> 3 votes

# Answer
In D7 navigate to *admin/people/permissions*

Find **View user profiles** permissions and grand it as you wish to be.
> -1 votes

---
Tags: 7, theming, nodes
---


title: How to use not in in drupal views 3

text:
# Question
Title: How to use not in in drupal views 3
I'm using Drupal 7 with views 3.

I need a list of students who have due payments in a view. The students who have paid the fees are stored in a new table. Now I want to show the students which are not in other table. How can I have this is views 3

EDIT Better explanation of query

I am using views 3 to get a list of students who have due payments. The students who have paid the fees are stored in a new table. Now I want to show the students which are not in fees paid table. How can I have this is views 3.

My Table structure is:

I have a table structure for fee details as

```
fid
name
description
currency
fee
instalments
created

```

This fee schedule has N no of instalments and storing in a cross ref table as

```
iid
fid
instalment_no
amount
payable_by

```

This fee schedule has associated students and are storing in a cross ref table as

```
fid
uid

```

The table structure for paid students who has paid fees.

```
pid      Payment ID serial
fid      Fees ID details
iid      Instalment No
uid      Student who has paid the fees
paid_on  Payment date

```

Thanks in advance for your help.

# Answer
> 1 votes
**My suggestion:** You could make this a *great* deal easier for yourself if "Has payed" a field on the User entity instead.

**Answer to your question:** You need to expose the custom table to Views, by telling Views that it exists and what type of data there is in it. The canonical way of doing that is with hook\_views\_data, although the Data module claims to be able to do this automatically.

Once you have the data in Views, you create a View based on "User", and add a "Filter" to remove all users in the "Payed" table.

---
Tags: views
---


# Question
Title: What is the equivalent of "WHERE nid IN :nids AND (col1 = 1 OR col2 = 1)" with the SelectQuery class?
How do you build a query with a `WHERE` clause like the following one, with a SelectQuery object?

```
WHERE nid IN :nids AND (col1 = 1 OR col2 = 1)

```

# Answer
With a `SelectQuery` object, you use code similar to the following one.

```
$query = db_select('node', 'n')
  ->fields('n', array(/* The fields you need to obtain */))
  ->condition('n.nid', $array_containing_the_ids)
  ->condition(
    db_or()->condition('n.col1', 1)->condition('n.col2', 1)
  );

```

For that type of query, if you don't need to allow other modules to alter the query being executed, which is possible for the other modules with hook\_query\_alter(), you can use db\_query(). In this case, the code is similar to the following one.

```
$result = db_query("SELECT /* The fields you need to obtain */ WHERE nid IN :nids AND (col1 = 1 OR col2 = 1", array(':nids' => $array_containing_the_ids));

```

With the object returned from `db_select()`, the conditions you add with `$query->condition()` are ANDed together; that is because the constructor of the `SelectQuery` class contains the following code.

```
  $this->where = new DatabaseCondition('AND');
  $this->having = new DatabaseCondition('AND');

```

If you need to OR two conditions, you need to execute code similar to the following one.

```
$query = db_select('node', 'n')
  ->fields('n', array(/* The fields you need to obtain */))
  ->condition(
    db_or()->condition('n.col1', 1)->condition('n.col2', 1)
  );

```

If the value you pass to `condition()` is an array, the method assumes you are using the `IN` operator; there is no need to make it explicit, in the same way the `=` is implicit for integer and string values. See What is the default value for $operator in condition()?

As side note, when querying entities, such as nodes, and users, you can also use the `EntityFieldQuery` class. As far as I can understand, with the `EntityFieldQuery` class you cannot build a query to obtain entities where, for example, property A is equal to X, or property B is equal to Y, and property C is equal to Z.
> 1 votes

---
Tags: database
---


title: Track Browser and set site language

text:
# Question
Title: Track Browser and set site language
I have these modules installed:

cck-6.x-2.9

i18n-6.x-1.10

token-6.x-1.18

views-6.x-2.16

I would like to set the language of the website by checking the language used by the browser and set that as the website language.

Is this something that is possible? Can you show an example of how to do this?

# Answer
> 0 votes
Here is my function i eventually used to sort out this issue. I hope it helps anyone in the future.

```
function setLanguage($page) {
/*Set site language if it is the users first visit*/

global $language;
$currentLang = $language->language;
$browserLang = "";

    //If a different language is chosen by the language dropdown
if (isset($_GET['l'])) {

    setCookieLanguage($currentLang);
    $lang = $currentLang;

}

if ($page == "front") {

    if (!isset($_COOKIE['language'])) {

        $browserLang = getBrowser();
        setCookieLanguage($browserLang);
        redirectLanguage($browserLang);

    } else {

        if ($_COOKIE['language'] != $currentLang) {
            redirectLanguage($_COOKIE['language']);
        }

    }
}

$GLOBALS['lang_name'] = $currentLang;
}

```

# Answer
> 0 votes
If writing code is not an issue you could probably handle this in your custom module's hook\_init() implementation by using sessions (to check if the user has been redirected already) and PHP-s $\_SERVER\['HTTP\_ACCEPT\_LANGUAGE'\] variable. Assuming that your site is using path prefixes to determine the language the code could be something like this:

```
function mymodule_init() {
  // If the user landed on the front page and hasn't been redireced during their session.
  if (!isset($_SESSION['mymodule_redirected']) && drupal_is_front_page()) {
    global $language, $base_url;
    $current_lang = $language->language;
    // Available languages besides the sites main one that is using $base_url as it's path.
    $available_langs = array('en', 'de');
    $langcode = explode(";", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    $langcode = explode(",", $langcode['0']);
    $langcode = explode("-", $langcode['0']);
    $lang = $langcode[0];
    $_SESSION['mymodule_redirected'] = TRUE;
    if (in_array($lang, $available_langs)) {
      if ($lang == 'en' && $current_lang != 'en') drupal_goto($base_url . '/en');
      if ($lang == 'de' && $current_lang != 'de') drupal_goto($base_url . '/de');
    }
  }
}

```

# Answer
> 0 votes
I only have a D7 site here, and don't remember if it's same there, but with locale (a core module, dependency of i18n), you can go to /admin/config/regional/language/configure and just enable the detection method

> Determine the language from the browser's language settings.

---
Tags: 6, i18n-l10n
---


# Question
Title: Is it possible to get a clean url to be used in Views comment counts?
I have a Views view of some news nodes. Each of the news nodes has "Generate automatic URL alias" ticked in the "URL path settings" of the node. This is great and gives me nice clean URL's.

However in my comments field in the view when I go to "REWRITE RESULTS" "Output this field as a link" and set the "Link Path" I am unable to find a token that gives me the same clean url that my title field can have or even my Node: Link field.

Is it possible to use the clean urls for comments and if so what is the token?

# Answer
> 1 votes
I'm not sure this can be done through rewriting, it's quite limited and never has given me what I want. At any rate you could be better off if you used the row-theming technique, which is in turn powerful. Then you could build your own links the way you want, wrapping the URLs in drupal\_get\_path\_alias to get nice-looking addresses.

---
Tags: 7, views, comments, tokens, uri
---


# Question
Title: what is use of $title_prefix and $title_suffix variable inside drupal theme system
i am *intermediate* in php.i start learning drupal 7 theme system. i need to know what is role of $title\_prefix and $title\_suffix variable inside .tpl.php files. what happen if we **not** include these variable inside .tpl.php files. i also read documentation for those variable at drupal.org but documentation is not enough to make it crystal clear.can anybody explain its use in simple words.

# Answer
> 9 votes
I'm not sure how it could be any clearer than on the docs page, but here goes;

* `$title_prefix` is for content that should be displayed directly *before* the title in a template file (node.tpl.php, block.tpl.php, etc).
* `$title_suffix` is for content that should be displayed directly *after* the title in a template file.

There really is nothing more to it than that. If you choose not to include these variables in your template file then they simply won't be rendered.

Since any module/theme in the system has the chance to populate/change the values that are in either of these variables it's impossible to say exactly what will not be rendered in your particular case if you choose not to display them.

As an example, (and if I remember rightly), contextual links for blocks/nodes are contained in the `$title_prefix` variable. So if you don't print `$title_prefix` in your template, you won't get contextual links for that item.

---
Tags: theming
---


# Question
Title: Showing a list of content that only authorised users can see
Most of the site is public however certain nodes need to be only visible to authorised users. I've got this up and running using Content Access but now I want to show a list of content that Anonymous users can't see.

I thought I'd be able to do it using Views and Contextual Filters but I can't seem to get just that content to show.

So, how do I do it?

# Answer
> 0 votes
You can use use Nodeqeue and views module to create a nodeqeue and assign permission using views module.

# Answer
> 0 votes
If your page or block is created with Views, views will allow you to configure said page or block to be viewable only by people with certain permissions. In D7, in the middle column, you have 'Page Settings \> Access (about half way down)'; for blocks, same location. Click access and give this view to whatever role you want to be able to see it. If none of the existing roles suffice, just create a new one in 'People'

Hope that helps

---
Tags: users, views
---


# Question
Title: Character escaping rules for $form_state['redirect']
I'm writing a redirect for the form submit function, the redirect part looks like this

```
$form_state['redirect'] = array(
// $path
'catalog/search',
// $options
array('query' => array("circle_op=<&a%5Bvalue%5D=28&a%5Bl%5D" => $location, 'p' => $keyword,)),
// $http_response_code
    302,
  );

```

The problem is that the `"circle_op=<&a%5Bvalue%5D=28&a%5Bl%5D"` part on redirect transforms into `"%253Ccircle_op%3D<%26a%255Bvalue%255D%3D28%26a%255Bl%255D%3D"` inside URL.

Please explain, how to pass this key value correctly?

Thanks

# Answer
> 1 votes
The rule for query strings is pretty simple; you need a key, and a value. The format for this key/value pair is:

```
key=value

```

Both the key and the value will be URL encoded, so any special characters are escaped.

Take the `=` sign for example. Your sample code above uses:

`circle_op=<&a%5Bvalue%5D=28&a%5Bl%50`

as a key, and a value from the variable `$location` as a value. So without being escaped, your query string looks like this:

```
?circle_op=<&a%5Bvalue%5D=28&a%5Bl%5D=VALUE_OF_LOCATION_VAR

```

Obviously if a browser was to encounter that URL it wouldn't know what to do; there are two equal signs, so it doesn't know what is supposed to be the key, and what is supposed to be the value. It can make a guess but that's not the point.

The URL that you are redirecting to is absolutely the correct one for the input you've given for your redirect URL.

---
Tags: 7, forms, uri
---


title: Icon images with node title

text:
# Question
Title: Icon images with node title
I'm using Drupal 7, and I want to put specific icons close to node titles. How can I do this?

This is how I want the node titles to appear.

# Answer
You can use CSS to theme your `<h1>` tag on the node page to include this image as a background image, similar to the method for custom bullets on a `<li>` element.

If different icons represent different node types, then use Drupal's default CSS selectors to specify which CSS elements you need to target for that page.

For example, 'weather content type' might use the following CSS selectors.

```
body.node-weather #node h1 { my background image }

```
> 0 votes

---
Tags: nodes, media
---


# Question
Title: Why different available updates in Drush to admin/reports/updates?
e.g. in the GUI, I'm told (after running admin/reports/updates/update) that I can update 10 modules. But `drush rf; drush up` tells me that only three updates are available. Specific example: the GUI says I can update to Views 7.x-3.3, but `drush up views` says "no code updates available."

I usually **prefer to use drush** to do the updates since I don't want to pass credentials to my server's user account over the unencrypted web!

But I don't get why drush should report update status differently? Can anyone enlighten me?

# Answer
> 0 votes
Think it was using an old (i.e. Debian Squeeze's) version of Drush. Solution:

Add backports to `sources.list`

```
#
# squeeze backports
#
deb http://backports.debian.org/debian-backports squeeze-backports main contrib non-free

```

Then `apt-get install drush=4.5-2~bpo60+1`

Your version number may vary. Check `apt-cache policy drush` to see what versions are available.

---
Tags: 7, drush, updating, log-messages
---


title: the question of enable "mobile switch"

text:
# Question
Title: the question of enable "mobile switch"
I install the module of "mobile switch" and enable it. But I just only enable this module and set a mobile theme, the error message is showed:

```
Notice: Undefined index: ismobiledevice in mobile_switch_boot() (line 40 of D:\xampp\htdocs\drupal\sites\all\modules\mobile_switch\mobile_switch.module).

```

I don't know how to solve it. Have anyone know what'w happen? Thanks....

# Answer
> 5 votes
You could try an alternative Theme key module rather then using mobile switch module to check for the mobile device.
It provides flexibility for changing the theme not only based on the type of device but also can theme different parts of site based on different conditions.
You can check for a detailed video tutorial by Mustardseed to check this features.

---
Tags: theming
---


title: Change states in hook form alter

text:
# Question
Title: Change states in hook form alter
I am trying to change the states via the the following code:

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  ...
  case 'my_form_node_form': {
    $form['my_file_field']['#states'] = array(
      'visible' => array(':input[id="my_id"]' => array('value' => 'my_value'),
    ),
  );
 }
}

```

but, my file field is not becoming visible after my input id is selected, instead is already visible.

# Answer
If this is a file field attached to an entity, and not (for example) a `managed_file` element type, then the actual `<input>` element is contained further down the render array. At the moment you're probably attaching the JS to the wrong element (a container rather than the input).

Try something like this instead:

```
/**
* Implements hook_form_alter()
*/
function my_module_form_alter(&$form, &$form_state, $form_id) {
  ...
  case 'my_form_node_form': {
    $form['my_file_field'][LANGUAGE_NONE][0]['fid']['#states'] = array(
      'visible' => array(
        ':input[id="my_id"]' => array('value' => 'my_value'),
      ),
    );
  }
}

```
> 4 votes

---
Tags: 7, forms
---


# Question
Title: multistep module to create multistep registration form
I need to use the multistep module to create a multistep registration form in Drupal 6.

In the multistep module you can easily create a multistep form for a content type but I need to use it instead of Drupal normal registration page. How can I do this?

# Answer
> 2 votes
From my experience, **CTools** works great for multistep forms using the CTools form wizard. I've already used it successfully but never tried with user registration.

You can follow a nice tutorial for that case here:
**Multistep registration form in Drupal 6**

Another tutorial:
**Intro to Drupal 6 Multistep Form Domination Using Chaos Tools**

Happy coding :)

# Answer
> 0 votes
You can use the Webform module. For multisteps you can use a field type 'pagebreak' between the steps. It is very easy. Try this once

> Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

---
Tags: users, 6, forms
---


# Question
Title: How do I change the permalinks to #1, #2, #3?
I would like to change the comment/forum links to something like:

TOPIC:

```
#1

#2

#3

```

Do you have any idea on how should I do this?

# Answer
Advanced forum provides what you are looking for out of the box (a #number permalink in the upper left corner of the post) among tons of other useful features for a forum.

You could either simply use that module, or you could look at it's template files to see how it's done. The relevant code seems to be in includes/advanced\_forum\_preprocess\_comment.inc and looks like this.

```
  /* Linked post number */
  if (!isset($post_number)) {
    static $post_number = 1;
  }

  $posts_per_page = variable_get('comment_default_per_page_' . $node->type, 50);

  $page_number = !empty($_GET['page']) ? $_GET['page'] : 0;
  if (!$page_number) {
    $page_number = 0;
  }

  $post_number++;

  $linktext = '#' . (($page_number * $posts_per_page) + $post_number);

  // Permalink
  //  You can erase next 3 lines if you wish to use built-in Permalink.
  //  Template adjusted: $post_link -> $permalink
      $uri = entity_uri('comment', $comment);
  $uri['options'] += array('attributes' => array('class' => 'permalink', 'rel' => 'bookmark'));
  $variables['permalink'] = l($linktext, $uri['path'], $uri['options']);

```
> 4 votes

# Answer
First, if the code is in `template_preprocess_comment(&$vars)`, `$node->type` needs to be `$vars['node']->type`. Also, there isn't the need of a comment counter per each page because the Comment module adds an ID starting with 1 for the top comment. Currently this code works correctly for me with comments on several pages.

```
function template_preprocess_comment(&$vars) {
  $posts_per_page = variable_get('comment_default_per_page_' . $vars['node']->type, 50);

  $page_number = !empty($_GET['page']) ? $_GET['page'] : 0;
  if (!$page_number) {
    $page_number = 0;
  }

  $linktext = '#' . (($page_number * $posts_per_page) + $vars['id']);

  $vars['comment']->uri['options'] += array('attributes' => array('class' => 'permalink', 'rel' => 'bookmark'));
  $vars['permalink'] = l($linktext, $vars['comment']->uri['path'], $vars['comment']->uri['options']);
}

```
> 3 votes

# Answer
OK got it to work properly ! In you template.php file (drupal/sites/adress/themes/YOURTHEME/template.php) add:

```
<?php

function YOURTHEME!_preprocess_comment(&$variables){

  /* Easy links to the comment and parent node */
  $comment = $variables['comment'];
  $node = node_load($comment->nid);
  $variables['first_post'] = $node;

  // Set the post ID for theming / targetting
  $variables['post_id'] = "post-$comment->cid";

  /* Linked post number */
  if (!isset($post_number)) {
    static $post_number = 1;
  }

  $posts_per_page = variable_get('comment_default_per_page_' . $node->type, 50);

  $page_number = !empty($_GET['page']) ? $_GET['page'] : 0;
  if (!$page_number) {
    $page_number = 0;
  }

  $post_number++;

  $linktext = '#' . (($page_number * $posts_per_page) + $post_number);

  // Permalink
  //  You can erase next 3 lines if you wish to use built-in Permalink.
  //  Template adjusted: $post_link -> $permalink
  $uri = entity_uri('comment', $comment);
  $uri['options'] += array('attributes' => array('class' => 'permalink', 'rel' => 'bookmark'));
  $variables['permalink'] = l($linktext, $uri['path'], $uri['options']);

}
?>

```
> 2 votes

# Answer
You can type in your css file something like this:

.comment .submitted .permalink{ display: none; }

and no more permalink ;)
> -1 votes

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


# Question
Title: Change default Taxonomy value on form via form alter in D7
I am trying to alter a form with a taxonomy term select drop down field; I want to change the default term selected when the form loads. I'm altering the form array via hook\_form\_alter; however, my changes do not seem to be taking effect. I'm looking for an answer similar to this but for Drupal 7.

I'm expecting :

```
        $form['field_mytax_reference']['#default_value'] = array($taxTermId => $taxTermName);

```

to do the job but the form remains with the default specified when the field was created.

Thanks in advance.

# Answer
This worked:

```
$form['field_mytax_reference']['und']['#default_value'] = array($term_tid);

```

Clive's answer was a helpful point in the right direction.
> 3 votes

# Answer
It'll be something more along the lines of:

```
$form['field_mytax_reference'][LANGUAGE_NONE][0]['#default_value'] = $taxTermId;

```

If the field is a multi-select you would wrap the default value in an array, but there's no need to set a key for it:

```
$form['field_mytax_reference'][LANGUAGE_NONE][0]['#default_value'] = array($taxTermId);

```

Have a look at Why is hook\_form\_alter() so messy? for a bit more info.
> 3 votes

---
Tags: 7, forms
---


title: How to get the value of a node field?

text:
# Question
Title: How to get the value of a node field?
In node.tpl.php I am trying to get the raw value but the problem is that when I use render:

```
<?php print render($content['field_price']);?>

```

it does not just return field\_image value but formats and outputs the whole image.

I need a way to get only the field's raw value. How can I achieve this?

# Answer
> 11 votes
To get the real value and not a themed one...

You can use http://api.drupal.org/api/drupal/modules!field!field.module/function/field\_get\_items/7

```
 $my_field_items = field_get_items('node', $node, 'field_my_field');

```

Or use Entity API module and entity\_metadata\_wrapper

```
 $node_wrapper = entity_metadata_wrapper('node', $node);
 $field_val = $node_wrapper->field_test->value();

```

Take a loot also at http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

# Answer
> 5 votes
In a node template, for raw values you can access the `$node` object.

```
<?php print $node->field_price; ?>

```

If you need to see the structure, can do `<?php print_r($node); ?>`.

Also, if this is for a specific content type you should use a variation of node.tpl.php instead of node.tpl.php itself or else it will try to display fields that are non-existent on other content types.

# Answer
> 3 votes
enable Devel module and in node-{content-type}.tpl.php use

```
<?php print dsm($node); ?>

```

on top of code.

you can see all $node fields in readable format

---
Tags: 7, nodes
---


# Question
Title: Improving template/rendering performance
I'm running a Drupal commerce site and using Views to display up to 30 product node teasers per page. The product display content type has a several fields (image, desc, manufacturer) and I am also using the flag module so that users can mark favorite products. As a result, the query ends up being fairly large with several joins.

Views statistics reveal that despite the complex query, the slow page loads are due to the rendering time it takes...

```
Query build time    21.13 ms
Query execute time  1.67 ms
View render time    4237.2 ms

```

How do I improve my Drupal template/rendering performance to get my pages to load faster?

# Answer
I would check for File IO; what does profiling your site tell you. I had similar issues and created the http://drupal.org/project/imageinfo\_cache module and my views performance improved a lot by reducing file IO.

Seeing that your on shared hosing, checkout this http://kpayne.me/2012/02/04/use-register\_tick\_function-to-profile-your-code/
> 4 votes

# Answer
Here are a couple of the more obvious tips:

1. Enable caching for your Drupal.
2. Optimize your Drupal database. Log in to your Drupal admin area and go to Site Configuration \> Performance. Besides enabling cache, you should also enable Page compression, Optimize CSS files and Optimize JavaScript files.
3. If your Drupal is hosted on a dedicated solution, you can modify the global MySQL settings for better performance.
4. \*More for front-side micro-optimisation, you can check your website using this online tool. It will give you valuable information on what modifications can be made in order to improve its performance.
5. Of course, disable/remove all modules/blocks you are not using.

Now, most of those are pretty basic and usual optimisations. I assume this is where you are now standing.

**Next steps:**

In my (humble) opinion, you would get way better response times if you install APC or Memcache on your server. There is also varnish I have heard lots of good things about, but I have not had the chance yet to play with it, and it looks like it is meant for anonymous sessions and static pages so I am not certain you would gain as much benefits than from other 2 above mentionned modules.

If you want to see benchmarks of a Drupal instance with/without APC caching, see here.

Last but not least, have you tried benchmarking *without the flag module* to see what impact this module has? We had to rewrite some queries of the like in other 3rd party modules a few times, some of the sql Drupal generates is not really optimised as you probably realised by now.

Happy coding, cheers!
> 3 votes

---
Tags: views, theming, commerce, performance
---


# Question
Title: Webform api - using the included hooks to change email destination?
I am looking to have a webform posted to specific destination depending on submitted values.

I thought this could be done through the webform api, webform.api.php line 209 has this hook defined:

```
/**
 * Alter the display of a Webform submission.
 *
 * This function applies to both e-mails sent by Webform and normal display of
 * submissions when viewing through the adminsitrative interface.
 *
 * @param $renderable
 *   The Webform submission in a renderable array, similar to FormAPI's
 *   structure. This variable must be passed in by-reference. Important
 *   properties of this array include #node, #submission, #email, and #format,
 *   which can be used to find the context of the submission that is being
 *   rendered.
 */
function hook_webform_submission_render_alter(&$renderable) {
  // Remove page breaks from sent e-mails.
  if (isset($renderable['#email'])) {
    foreach (element_children($renderable) as $key) {
      if ($renderable[$key]['#component']['type'] == 'pagebreak') {
        unset($renderable[$key]);
      }
    }
  }
}

```

So I set out to use it with the following ina custom module:

```
// Implements hook_webform_submission_render_alter
function formHelper_webform_submission_render_alter(&$renderable) {
  // Just a dump to confirm hook was invoked...
  kpr($renderable);
  dpm($renderable);
}

```

However, it seems the hook is not being called. Am I missing something in here to use webform api? Is this even a regular hook? it seems I could get away with just calling the api's function but I would like to be sure of the Drupal way to go.

# Answer
> 1 votes
Was not sure wether to delete original question or not, but decided on leaving it here since it is listed by google when searching for webform api help.

Turns out the code above does execute the hook. I went for lunch, came back, retried and suddenly the hook is invoked as expected.

To anyone needing to change form values or email info on submission of a webform, this hook is the real deal.

Cheers!

---
Tags: hooks, webforms, forms
---


# Question
Title: Override comment.tpl.php file with theme
**Objective**: Override comment.tpl.php file output in drupal core modules.

**Assumption**: My best guess is that I need to create a comment-\[type\].tpl.php file in my themes folder.

**Requirements**:

* template.php can not be used
* need to replace default comment.tpl.php html output

**Questions**:

* how do i find the so called type of the comment for the tpl file?
* is this the best way to change the html output of the file?
* is there another way to change the output with the type or using template.php?

**Links**: http://drupal.org/node/190815

# Answer
> 8 votes
You should be able to override Drupal's default comment.tpl.php file by copying it from /modules/comment into your theme directory. From there, edit the file as needed. Then clear the cache (on the Admin \> Site configuration \> Performance), so that the theme cache will get rebuilt and your new theme file will get recognized.

You would only need to rename comment.tpl.php to comment-\[type\].tpl.php, if you wanted to override comment theming differently for different node types.

---
Tags: theming
---


# Question
Title: Need example : D7 + XPath parser to import (mediawiki) XML - xpath parser settings?
I've installed XPath/Feeds/D7, but I don't know how to configure XPath parser settings.

Maybe someone can help me to set it right.

I just want to inject `<title>` and `<text xml:space="preserve">` to my node.

I need help to configure my XPath Parser settings : admin/structure/feeds/edit/my\_import/settings/FeedsXPathParserXML

I've the following XML structure :

```
<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.3/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.3/ http://www.mediawiki.org/xml/export-0.3.xsd" version="0.3" xml:lang="fr">
  <siteinfo>
    <sitename>Site Name</sitename>
    <base>http://domain.net/index.php/StartPage</base>
    <generator>MediaWiki 1.15.5-1~bpo50+1</generator>
    <case>first-letter</case>
    <namespaces>
      <namespace key="-2">Media</namespace>
      <namespace key="-1">Special</namespace>
      <namespace key="0" />
      <namespace key="1">Chat</namespace>
      <namespace key="2">user</namespace>
      <namespace key="3">Chat user</namespace>
      <namespace key="4">domain.net</namespace>
      <namespace key="5">Chat domain.net</namespace>
      <namespace key="6">files</namespace>
      <namespace key="7">Chat files</namespace>
      <namespace key="8">MediaWiki</namespace>
      <namespace key="9">Chat MediaWiki</namespace>
      <namespace key="10">Model</namespace>
      <namespace key="11">Chat model</namespace>
      <namespace key="12">help</namespace>
      <namespace key="13">Chat help</namespace>
      <namespace key="14">category</namespace>
      <namespace key="15">Chat category</namespace>
    </namespaces>
  </siteinfo>
  <page>
    <title>Drush</title>
    <id>579</id>
    <revision>
      <id>1637</id>
      <timestamp>2012-05-25T14:51:51Z</timestamp>
      <contributor>
        <username>admin</username>
        <id>1</id>
      </contributor>
      <comment>/* Install Drupal with Drush */</comment>
      <text xml:space="preserve">Drush is a command line utility.

=Install Drupal with Drush=
To install drupal with drush :
 drush site-install standard --db-url=mysql://username:pass@localhost/databasename

[[category:Drupal]]</text>
    </revision>
  </page>
  <page>
    <title>Memcache</title>
    <id>586</id>
    <revision>
      <id>1287</id>
      <timestamp>2012-02-12T17:43:32Z</timestamp>
      <contributor>
        <username>admin</username>
        <id>1</id>
      </contributor>
      <comment>Do it under Debian</comment>
      <text xml:space="preserve">=Install=
==Debian==
===Memcache Server===
To install :
 aptitude install memcached

Read and change ''/etc/memcached.conf''.
===PHP5 / PECL===
Install memcache PECL :
 php5-memcache
or
 pecl install memcache

Restart Apache.

===Drupal===
* InstallMemcache module in Drupal.
* Change ''settings.php'' :
<source lang="php">
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['memcache_key_prefix'] = 'site_prefix';
</source>

Read : http://drupal.org/node/1131458

[[category:Linux]]

[[category:Drupal]]</text>
    </revision>
  </page>
</mediawiki>

```

**Optional task :** How can I convert "=" to `<h1>`, "==" to `<h2>`, space before start of line to `<pre>`, \[\[category:xyz\]\] to Tags, etc ... ?

# Answer
> 7 votes
Context should be : `//Mediawiki/page`, Title field should be `title` and Text should be `revision/text`.

---
Tags: 7, feeds
---


# Question
Title: Main menu links not operational on front page when anonymous
I have two links to 'published content' in main menu. This menu is displayed on all pages, including front page.

When I am logged in as admin, those links work well, but when I am logged out (=anonymous), those links are displayed, but not operational. It is as if they were plain text only.

Yet, when I access content directly with the proper URL as anonymous, those links do work properly in the corresponding page.

So, why don't they work on the front page when using anonymous mode? I have checked page source and the code is the same. I have checked permission and View published content is allowed for anonymous users.

Want could be the cause of this issue?

**Update**

For the records, I have also asked a question here. I tried to solve this issue with a Drupal Navigation Menu, but only the Home link works, not the other link.

To solve this issue, I have created my own menu manually. It works, but...

**Update II**

I am using a simple plain vanilla system with panels everywhere. The theme is Versatile. I have header, footer, left, right mini-panels + central content in a default page variant. The right mini-panel just displays an instance of Main Menu. In fact, I have not created users. The site is meant to be used by anonymous people.

**Update III**

The issue only happens when the following CSS is applied:

```
.NCK_Menu {

    font-size: 103%;
    height: 240px;
    width: 120px;
    background-color: #5E88D0;
    margin: 10px 9px 10px 7px;
    padding: 7px;
    border:none;
    -webkit-border-radius: 1px;
    -moz-border-radius: 1px;
    border-radius: 1px;

}

```

It does not make sense !!!

# Answer
> 1 votes
The most often reason when you can\`t see any kind of links in menu - are permissions for users. So please double check whether all of ones connected to your links (maybe modules/content types or whatever) are enabled for anonymous user.

---
Tags: 7, routes
---


# Question
Title: how to add taxonomy terms to admin/config/people/accounts/fields programmatically?
I know I can use the UI at `admin/config/people/accounts/fields` to add existing taxonomy fields.

But I want to create them automatically using my module.

I know I can use `hook_enable()` or `hook_install()` for this but I don't know which hook or function I need to use to make the field show up in `admin/config/people/accounts/fields` ( and on the user edit / registration page )

I've read somewhere something about a bundle but I'm not sure if I'm looking in the right direction there.

# Answer
> 1 votes
You need to create an instance of the field, and then attach it to your content type. This is done using the `field_create_instance()` function.

There's a nice example in the standard profile of attaching the 'Tags' vocabulary to the article content type upon install:

```
$instance = array(
  'field_name' => 'field_' . $vocabulary->machine_name,
  'entity_type' => 'node',
  'label' => 'Tags',
  'bundle' => 'article',
  'description' => $vocabulary->help,
  'widget' => array(
    'type' => 'taxonomy_autocomplete',
    'weight' => -4,
  ),
  'display' => array(
    'default' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
    'teaser' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
  ),
);
field_create_instance($instance);

```

The documentation page has a full list of all the available properties for your field instance, but the above code is an excellent place to start.

I also have this piece of code in my arsenal which dumps the field/instance definitions of an existing field so I can inspect it and just chop and change what I need to:

```
$entity_type = 'node';
$field_name = 'field_FIELDNAME';
$bundle_name = 'BUNDLE_NAME';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

```

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


# Question
Title: Two different front pages with different themes
So I have the following problem. I created an entry page with module front that has two links. To categoryA and categoryB. Now I want these two categories to have different front pages with different themes.

Any ideas on how I can achieve that?

# Answer
Have you tried the ThemeKey module?

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.
> 2 votes

---
Tags: 7
---


# Question
Title: Drupal 7 - When to use template suggestions?
I always found it difficult to work with template suggestions in Drupal. I'm trying to override those files (html.tpl.php, page.tpl.php, region.tpl.php) for a given url (mysite.com/user-export). So I found this function:

```
function MYTHEMENAME_process_page(&$variables) {
if (module_exists('path')) {
    $alias = drupal_get_path_alias(str_replace('/edit', '', $_GET['q']));
    if ($alias != $_GET['q']) {
        $template_filename = 'page';
        foreach (explode('/', $alias) as $path_part) {
            $template_filename = $template_filename . '__' . $path_part;
        }
        $vars['theme_hook_suggestions'][] = $template_filename;
    }
}
}

```

That seemed to work pretty well, I created a file named page--user-export.tpl.php to override the page.tpl.php file and it worked. However, at some point I removed that function, and the template overriding was still working! So I guess in some cases we need to create a function in template.php, and in some other cases, the overriding is done automatically without having to create a function.

So my question is: **When to use template suggestions ?**

Thanks in advance!

# Answer
> 3 votes
page--*internal-path* is already defined by Drupal core as a theme hook suggestion, so adding your own version of it won't really have any effect (just as then removing that version won't have any effect).

You can see a full list of the core-implemented hook suggestions on the Drupal 7 Theme Hook Suggestions page.

The simple answer to the question is that you need to provide your own template suggestions when you require that functionality, and Drupal's core system, or a contributed module, haven't already provided the overrides for you.

---
Tags: theming
---


title: How to use Entity Reference and Views

text:
# Question
Title: How to use Entity Reference and Views
Been reading a lot of questions and playing around alot and I haven't been able to figure this out.

I have a node with a field for entity references. I'm trying to make a view that I can put on the node page that will grab the fields I want from the referenced entities but I haven't been able to make this happen.

I've created a view that that gets the current NID and I've set up relationships to the entity reference field on the node. I've also created a node with a the reference field filled out and in the views preview I'm passing that NID, but nothing is returned.

Does anyone have an idea why the view isn't returning the referenced entities that I've defined on the specific node?

Thanks, Paul

# Answer
Turns out I needed to use the relationship on the filters as well.
> 7 votes

---
Tags: entities, views
---


# Question
Title: How can I allow a user to send private messages but prevent other users from sending that user a private message?
I have a "system" user that sends "Welcome to the website" private messages as well as announcements to users. I am able to send these messages via rules; however, I don't want users to be able to reply to these messages.

I tried disabling private messages for the system user but that option disables both the receiving and sending of private messages (I checked-- if private messages are disabled for a user, no private message can be mailed from that user using rules).

I don't need a solution that is bulletproof; hiding the reply form on the private message view screen is sufficient. However, I dug through the private message module code and was unable to find any way to do that.

# Answer
> 3 votes
There are two ways to do this.

1. The pm\_block\_user module has settings that allow for role-based configurations for who is allowed to write whom. However, it is only possible to add positive rules. Meaning, you wold need to add all your users into a normal role that the system user is not part of and then allow users of that role to write users of that role.
2. Implement hook\_privatemsg\_block\_message() and block the system user id.

You're welcome to provide option two as a patch in the main module (e.g. allow to choose a system user whom you can't write/reply and is maybe also themed differently). This is an often requested feature.

---
Tags: privatemsg
---


title: Update a cck field value of a node

text:
# Question
Title: Update a cck field value of a node
I have a cck field in a node. I bring this value out in some other form and alter its value, But i am unable to save it back to DB. How should i write it back to table such that node changed date also gets changed. please show some code for this.

# Answer
You can use `node_save()` to do this; CCK will automatically hook into it and update the field values in the database for you:

```
// Load a node
$node = node_load(1);

// Update the field value
$node->field_field_name = array(0 => array('value' => 'A value'));

// Save the node. Field values are also saved, and the node modified time is updated.
node_save($node);

```
> 1 votes

# Answer
You should try with hook\_nodeapi(&$node, $op, ...) with `$op='presave'`.
> 0 votes

---
Tags: 6
---


# Question
Title: How to use Taxonomy Facets together with Apache Solr Multisite Search ?
This regards http://drupal.org/project/apachesolr\_multisitesearch I'm trying to enable Multisite Search Facets (based on Taxonomies) for a few sites. The 'normal' multisite facets such as 'filter by site', 'current search' etc appear fine but facets based on Taxonomies do not appear not matter what I do. The facets are enabled and the blocks added to regions, caches cleared etc.

Tested in Drupal Core 6.20 with the latest stable version of Apache Solr & Apache Solr Multisite Search

Has anyone else successfully enabled this functionality?

Any help greatly appreciated

# Answer
A little patch that solve the issue

```
Index: apachesolr_multisitesearch.module
===================================================================
--- apachesolr_multisitesearch.module   (révision 32470)
+++ apachesolr_multisitesearch.module   (copie de travail)
@@ -331,6 +331,10 @@
             return apachesolr_date_facet_block($response, $query, 'apachesolr_multisitesearch', $delta, $delta, t('Filter by post date'));
           case 'hash':
             return apachesolr_facet_block($response, $query, 'apachesolr_multisitesearch', $delta, $delta, t('Filter by site'), 'theme_apachesolr_breadcrumb_hash');
+
+           //syg on ajoute un retour pours toutes les autres facets
+          default:
+            return apachesolr_facet_block($response, $query, 'apachesolr_multisitesearch', $delta, $delta, t('Filter by %field', array('%field'=> $delta)));
         }
       }
       break;

```
> 1 votes

---
Tags: 6, taxonomy-terms, search, multi-sites
---


# Question
Title: hook_query_alter, AJAX, views_get_view : have to submit twice
A view is embedded in a page template via this code. It's AJAX enabled and uses exposed filters which I have to mess around with for business purposes :

```
$view = views_get_view('rechercher', $reset);
$view->set_display('default');
$view->set_use_ajax(TRUE);

$set_exposed_input  = array();
if (isset($_GET['commune'])) {
  $set_exposed_input['field_commune_value'] = filter_xss($_GET['commune']);
}
if (arg(1) == 646 && ! isset($_GET['raz'])) {
  $set_exposed_input['field_type_vente_value'] = 'LOCA';
} elseif (arg(1) == 645 &&  ! isset($_GET['raz'])) {
  $set_exposed_input['field_type_vente_value'] = 'VENT';
}
if ($set_exposed_input) {
  $view->set_exposed_input($set_exposed_input);
}
$view->execute();
print $view->render();

```

It works perfectly.

Now the query must be altered via hook\_query\_alter :

```
function my_module_views_query_alter(&$view, &$query) {

  // Unrelevant stuff here

  if ($view->name == 'rechercher') {
    $view->query->add_table('field_data_field_cp');
    $view->query->add_where(1, 'field_data_field_cp.field_cp_value', '%' . $_SESSION['filtres']['field_commune_value'] . '%', 'LIKE');
  }

```

As soon as I uncomment this code, I have to submit the view twice to have the results refreshed.

Except for this, the view behaves as expected (query returns the right data, etc.).

I guess it's some kind of cache and/or form caching issue but can't figure what exactly.

Any help would be appreciated.

---

EDIT : Some more details

Please forget AJAX : it has nothing to do with it, as the behaviour is exactly the same without it.

One more info : the query is correctly altered on the first filters form submission. Dumping proves it.

So it boils down to something that happens AFTER query altering. The mistery remains as to what and when.

# Answer
It was some kind of mess with the $\_SESSION variable, which I used for independant reasons.

I corrected my code this way :

```
  if ($view->name == 'rechercher') {
    $view->query->add_table('field_data_field_cp');

// Old code
// $view->query->add_where(1, 'field_data_field_cp.field_cp_value', '%' .
// $_SESSION['filtres']['field_commune_value'] . '%', 'LIKE');

// New code
    $view->query->add_where(1, 'field_data_field_cp.field_cp_value', '%' . $view->exposed_data['field_commune_value'] . '%', 'LIKE');
  }

```

... and everything seems to be fine, AJAX and all.

Thanks to Clive for the help.
> 1 votes

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


title: Put file download image

text:
# Question
Title: Put file download image
I'm using Drupal 7 and i've got 3 file field in content. I don't want see generic file, url file etc... I want spesific bg image on all my file field. How can i do this?

# Answer
You can modify your theme's CSS to give every File Field a specific background image. You would add this to your theme's stylesheet, looking for a "style.css" file in your theme folder. The generic code for the background image would be:

```
.node-your-node-type .field-type-file {
  background: url("/sites/all/themes/yourtheme/yourbackgroundimage.png") no-repeat scroll 0 0 transparent;
}

```
> 0 votes

---
Tags: 7, files
---


# Question
Title: Why is arg() failing to get the router object on pages with aliased URLs?
So I posted this question about how to get NID of current node and I'm assured that arg() should work to return the router item for the current page, regardless of aliasing. However, it doesn't work.

The relevant snippet is

```
if(arg(0)=='node' && is_numeric(arg(1))){
   $nid = arg(1);
   dsm($nid);
}

```

I've also tried

```
$load = node_load();
$dsm($load);

```

and

```
$item = menu_get_item();
dsm ($item);

```

and

```
$node = menu_get_object();
dsm($node);

```

For all of these methods, they work when I edit the page (and thus make the URL displayed become `/node/%/edit`) and when I just navigate to `/node/%` (where `%` is the NID) but they display either nothing or (in the case of `arg()`) only the alias (e.g. "about-our-company for the path alias `/about-our-company`).

How can I reliably get the NID of the current node?

# Answer
Your code is failing because you're putting it directly in the module file, and not using the hook system. I won't go into exactly why this won't work, if you read the Module Developer's Guide it'll make sense.

It's a bit tricky to advise what hook your code should be going in as you don't mention what you want to do with it. As an example, though, lets say you want to extract the `nid` from the current page and pass it to an external service somewhere outside of Drupal.

There are several different ways to do it; at the most basic level, you could use `hook_init()`, which is called on every page load. Using this method your calls to `menu_get_object()` and `arg()` will yield the result you're expecting:

```
function MODULENAME_init() {
  $node = menu_get_object();

  if (isset($node->nid)) {
    send_data_to_external_service($node->nid);
  }
}

```

That's all fine, but let's say you want to change the content of a node based on it's `nid`. `hook_init()` will be no good for this, as it has no node available to manipulate in the current context.

Instead, Drupal actually provides a hook that is called when any node in the system is prepared for view, allowing you to manipulate the content. This hook is called `hook_node_view()`, and can be used like this:

```
function MODULENAME_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full') { // Node is being viewed on it's full node page
    $node->content['my_additional_field'] = array(
      '#markup' => $additional_field,
      '#weight' => 10,
      '#theme' => 'mymodule_my_additional_field',
    );
  }
}

```

Notice that one of the arguments that's passed to the function is the `$node` object, which contains the `nid` as a property. As you have this object in the current context, there's no need to query `menu_get_object()` or `arg()` to get the `nid`.

There are dozens of different hooks in Drupal that respond to different system events, and allow your custom modules to have a say in how a page is displayed/how data is saved/etc. It might be a good exercise to read through that list and see which hooks would help with the development of your own module.
> 3 votes

# Answer
arg() is intended to work with system paths. if you are viewing you node page with system path (node/#) or by alias then arg(1) must return nid of the node.

How are you defining your alias? Are you using path module interface?
Perhaps the alias is a result of a custom menu hook by some module, rendering a node by some arbitrary logic.

I would also like to share a hack to overcome this issue if you get alias in arg() and this alias is truly defined by path module directly on node then drupal\_lookup\_path('source', 'your/node/alias') will return the system path of your node e.g. `node/#`
> 3 votes

---
Tags: nodes, path-aliases
---


# Question
Title: Uninstalling modules, specificially ANSWERS
I have uinstalled and reinstalled this module MANY times, all of the fields i have created and settings, and ADD question content are there no matter what i do.

here's the order i did

unchecked in modules section then uninstalled, then deleted via ftp then clear cache

everything is still there, any help is appreciated, thanks!!

signed--newbie

# Answer
If a module doesn't delete its tables or content in hook\_uninstall, then the content is not automatically removed when you disable the module.

You can see here that answers *does not* clean up after itself when it is uninstalled, probably for good reason.

If you want to purge everything, you will need to delete the nodes, fields, and bundles manually at admin/content and admin/structure/types or by writing some code that uses field\_delete\_field() or field\_attach\_delete\_bundle().
> 4 votes

---
Tags: 7
---


# Question
Title: How do I add the "cancel" button to a managed file
I made a new component for webform that adds a file upload component. It has a "choose file" button, and an "upload" button. You can also choose to use a progress bar during the upload.

Now I want to include a "cancel" button to interrupt the upload process. How can I do this?

# Answer
> 1 votes
if you redirect your browser I'm 99.9% sure it will cancel the upload.

how you handle that redirection is up to you. I'd probably just show a hidden div when the upload starts with a Cancel upload

hopefully what I wrote above helps, but I'd like to mention the other alternative:

don't put a cancel button in. I would say that this is a useless "feature" and really why add things to your UI when you don't have to?

the user has to step through quite a few things, it'd be pretty odd if they selected the wrong file.

---
Tags: files
---


# Question
Title: CDN module - serving files from subdomain - setup
Can plaease somebody point me to correct setup if I want my files to be served from subdomain?

As I understood I should choose origin pull mode. Then create a subdomain. Copy all files inside same structure to new subdomain. In config details of CDN module add new subdomain

Should I add some rules inside htaccess of new subdomain? Thank you very much for help.

# Answer
> 1 votes
If you are using the Amazon Cloudfront - You are using origin pull cdn in which case you can:

1. Create an custom origin in there service http://aws.typepad.com/aws/2010/11/amazon-cloudfront-support-for-custom-origins.html
2. Point that url that you get from cloudfront to a cname in your dns info in you admin panel in hosting setup
3. Install the cdn module enable it select origin pull and add the mapping the for files

Then save and you should be good to go

If you wanted to make an attempt at file conveyor that can be found here

http://fileconveyor.org/

---
Tags: cdn
---


title: Override theme css with custom styles

text:
# Question
Title: Override theme css with custom styles
I built a site with the theme Corporate Clean. I wanted to add some custom CSS (override some colors, fonts etc.) so I added this to the files in the folder /sites/all/themes/corporateclean/...). Now an update for the theme became available and I lost all my custom styles (I have them in source control so no panic).

What is the best way to add custom css that doesn't disappear when a new theme version is published? I prefer file based. I've seen CSS Injector but that CSS would also be gone if I start from a new database.

# Answer
What you want to do is create a sub-theme so that updating your contributed theme does not overwrite custom changes you've made.
> 2 votes

---
Tags: theming
---


# Question
Title: How to programatically create an address field
I would like to use the address field module in my module. How do I create an address field and an instance for that field. I haven't found any code in the module that defines what the array structure should look like.

I found this code in the commerce module (under modules/customer/commerce\_customer.module):

```
if (empty($field)) {
  $field = array(
    'field_name' => $field_name,
    'type' => 'addressfield',
    'cardinality' => 1,
    'entity_types' => array('commerce_customer_profile'),
    'translatable' => FALSE,
  );

  $field = field_create_field($field);
}

if (empty($instance)) {
  $instance = array(
    'field_name' => $field_name,
    'entity_type' => 'commerce_customer_profile',
    'bundle' => $profile_type['type'],
    'label' => t('Address'),
    'required' => TRUE,
    'widget' => array(
      'type' => 'addressfield_standard',
      'weight' => -10,
      'settings' => array(
        'format_handlers' => array('address', 'name-oneline'),
      ),
    ),
    'display' => array(),
  );

```

I can modify that to meet my needs, if someone is familiar with this module and could point out some attributes that may be missing, I'll accept their response as an answer to this question.

**Update** The address that I'm importing may contain up to 6 lines for the street address (all for one location) as defined by RETS. Is it possible to store a street address this long in an address field? If not I can concatenate the extra addresses into the second address line.

# Answer
I had a similar question these days, and I tried to see if the Features module could help. Features worked to me.

You can create the field by the UI and then export a feature with the address field already created.
After that you can move the inc files for your custom module and add an include on your .module file:

```
include_once('[your_module].features.inc');

```

Then, you will need to add the some lines on your .info from the info file of the exported feature.

Your info file will need something like this:

```
dependencies[] = "features"
dependencies[] = "text"

features[field][] = "node-article-field_address"

```

This question may help you too: Develop a module that adds a new content type with custom fields.
> 1 votes

# Answer
This is also a useful link for creating just address field form values: http://drupal.org/node/970048
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Is there a way to make aliases as short as possible?
For instance, if you have three tokens, let's say \[city\], \[state\], and \[country\] is there a way to do this:

/\[city\]-\[state\]-\[country\]

and then let's say there are three cities, Venice, in different places the first, Venice, Florida, United States would get this url

/venice

the second, Venice, California, United States would get this url

/venice-california

the third, Venice, Italy would get this url:

/venice-italy

Notice that it does not cut an individual token, only cuts off the extra tokens as they are not needed (in the case of Italy, there is no state so pauthauto automatically skips this token). From reading the documention, it looks like Pathauto's default behavior is to do this:

/venice

/venice-1

/venice-2

and so on... when what I want to do is make the first one the "venice" and any additinal ones get additial tokens as needed, so if Venice, Italy is first then they will get /venice

If there's a way to do this with pathauto, how would you do it? If not, what's the best way to make a module that does this? Can a module modify how pauthauto works without modifying pathauto itself?

thanks!

# Answer
> 1 votes
`hook_pathauto_alias_alter()` is nearest to your query.

First parameter `$alias` will be newly created alias by the Pathauto module. You would have to analyze it with some regex pattern for undesired pattern generation.

The second parameter will give you contextual picture of item in associated array.

`module` definitely be `taxonomy_term`
`source` system path of taxonomy e.g. `taxonomy/term/<tid>`

I think you will have pretty much to analyze the term and get its hierarchical info to update `$alias` variable.

# Answer
> 0 votes
What about `path_save()` called X number of times with whatever tokens you want in the URL fragment?

What you're asking isn't really a Pathauto question I think, as the uniqueness you describe is pretty subjective.

You could keep a one-to-many database table of node IDs for the allowed aliases you want per city.

---
Tags: 7, path-aliases
---


# Question
Title: Can I access public:// from inside a module?
I need to load an image that's uploaded to the public folder from within a module

In the module itself:

```
function mymodule_dashboard() {
   GLOBAL $user;
   $profile = profile2_load_by_user($user->uid, 'personal_information');
   $data['avatar'] = $profile->field_picture['und'][0]['uri'];

```

In my dashboard.tpl.php:

```
<img src="<?php echo $data['avatar']; ?>" />

```

The rendered content:

```
<img src="public://image.jpg">

```

I can pull the image name and build the path myself, but I'm looking for a way to actually take advantage of this public folder business

# Answer
> 10 votes
You're looking for the `file_create_url()` function:

> Creates a web-accessible URL for a stream to an external or local file.

e.g.

```
$data['avatar'] = file_create_url($profile->field_picture['und'][0]['uri']);

```

---
Tags: 7, uri
---


title: eu cookie compliance

text:
# Question
Title: eu cookie compliance
With the new EU cookie compliance law coming into force Friday (26/05/12), does anyone have any suitable advice for those of us who not only develop in Drupal and other frameworks? I myself have a degree in Business (and use to teach Business at FE level and had numerous limited companies), the ICO website is not helpful for those who developing, but those who have 'netpreneur' aspirations, may have second thoughts now the full weight of the ICO is behind the EU law. Personally, I would be quite happy to see the cookies option removed from all visitors on my future portal developments.

Would anyone care to shed some light on this in how we can ensure end users perceptions of 'privacy' theft are reduced to the lowest possible point. I don't believe the answer is merely to 'seek professional advice' as some Drupal developers simply cannot when starting out, even though I would argue that that should always be the case from a organsizational legal standpoint.

What would be the simplest answer to ensure compliance across Drupal?

# Answer
> 10 votes
The simplest way to ensure compliance for Drupal is to install the Cookie Control module, which has been created for exactly this purpose:

> On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.
>
> Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.

There's also the EU Cookie Compliance module:

> This module intends to deal with the EU Directive on Privacy and Electronic Communications that comes into effect in the UK on 26th May 2012.

This second one does a better job in my opinion.

# Answer
> 3 votes
It depends on which country in the EU you are in, as countries are interpreting it differently. Some are ignoring it. Some are enforcing it. The UK, for example, is enforcing it and website owners were supposed to ask for consent, or at least let users know that cookie will be stored and that the user can change the settings if they want. See http://www.bbc.co.uk for an example of this.

However, at the 11th hour, the Information Commissioner changed the law to implied consent. So website owners can assume that users have consented to cookies being stored on their machines.

---
Tags: cookies
---


# Question
Title: Roles are not correct while getting it in hook_user
I have added a new role called pre-auth i.e. if a user is registered and has not clicked the confirmation link(using LoginToboggan module) from the mail and the other is authenticated role its the normal authenticated role. I have a hook\_user to check the role but it gives me as "authenticated user " always but in `admin/user/user/` it shows the role as "pre-auth"

```
function mynewmod_user($op, &$edit, &$account, $category = NULL){
  switch ($op){
  case 'insert':
  case 'after_update':
    $user_details = user_load($account->uid);
    drupal_set_message('<pre>'. print_r($user_details->roles, true) .'</pre>');
}

```

Can any one tell me how can I get the exact role.

# Answer
> 1 votes
The variable $account already has the loaded user object. Calling $account-\>roles will give you an array of roles.

---
Tags: hooks
---


# Question
Title: Let users create / list their own restaurant menu
I am building a site where a restaurants visitors could register. Now, I have created a content type where the restaurant owners could list up there restaurant. I have to also allow them to add there restaurant menu based on categories like 'starters', 'mains' etc.

Is there any module which could help me achieve this?

# Answer
> 2 votes
Not totally sure what you're looking for. I'm going to assume that you're looking for a particular form to create a restaurant menu from the backend.

Drupal allows you to create this functionality OOTB (out of the box):

* Fields (formerly cck pre Drupal 7)
* User Roles
* User Permissions

You're probably going to need to output this in a pretty fashion so your best bet are some standard contrib modules:

Nonethless, these modules are standard fare for every Drupal project (except maybe Fields Collections).

Oh i googled and there are possibly similar questions out there on SO:

---
Tags: 7, nodes
---


# Question
Title: Do Drupal websites have bad performance or are heavy?
I'm facing a lot of problems with my shared hosting company regarding the performance of my website.

My website is not complicated at all, just text pages, and also some pages using the Views module, I'm not using Panels, and I aggregate my css and js, and also I have 7 image styles (thumbnail,large etc...).

But even so my hosting company told me that I exceeded the memory limit and I have to optimize the website.

I have also another site in a different hosting company .... another problem appears in the database and this is the error message:

> **PDOException: SQLSTATE\[00000\] \[1129\] Host '...' is blocked because of many connection errors;**

I don't know if the problem is because of Drupal or something else.

# Answer
What's your hosts memory limit?

For MySQL Run this MySQL command

```
SHOW VARIABLES LIKE 'innodb_buffer_pool_size'

```

If it's at the default I would see if you can increase it to at least the same size as your database. If you can not, I would look at converting some of your tables to MyISAM. http://www.mysqlperformanceblog.com/2007/11/03/choosing-innodb\_buffer\_pool\_size/
> 4 votes

---
Tags: 7, performance
---


# Question
Title: after updating 7.12 to 7.14 can't update modules
I guess I should have updated the CKEditor (currently 7.x-1.8), Date (7.x-2.3) & Webform (7.x-3.17) modules before updating Drupal 7 core. Now, I am unable to update the three modules. When I go to Home » Administration » Reports » Available updates, and then check any one or all three modules, I click Download the Update. Then, I see "Ready to update" and then after clicking "Continue", the site goes directly back to the home page. Any suggestions of how I might be able to update my three modules?

# Answer
This is probably a problem with folder/file permissions. You can try changing the permissions of the sites/all/modules folder, and of the problematic modules' folders. You can read more about changing permissions here (follow the links there to see what's recommended; basically 755 should do). Possibly these modules cannot be removed by Drupal because of the ownership settings of the files/folders in question.

You can also do a manual update, as explained in the answers to this question.
> 1 votes

---
Tags: 7, webforms, datetime, updating, wysiwyg
---


# Question
Title: My view's 'more' link needs to go to a page with exposed filters already selected
I have a view that is a list of a certain content. The more link for the view needs to link to a page I have set up that has exposed filters for sorting the content.

So let's say the view I have is of baseball-related content. The more link will go to another page that contains all sports, but in this case it will link there but already have the baseball filter selected. Confused?

What I had been trying was to use the Custom URL field in the view, but no tokens can be used. Maybe this isn't even the right way to go about it. I'd love to know what is.

Any ideas?

# Answer
> 0 votes
My coworker came up with this. Works flawless. It was put in the file views\_and\_panels.module file created by one of our features.

```
 /**
 * Implement hook_panels_pane_content_alter().
 *
 * Add more links to the appropriate panels.
 */
function module-name_views_and_panels_panels_pane_content_alter($content, $pane, $args, $context) {
  if($pane->subtype == 'node:field_related_products') {
    if($context['argument_entity_id:node_1']->data) {
      $values = field_get_items('node', $context['argument_entity_id:node_1']->data, 'field_catalog');
      $tids = array();
      if($values) {
        foreach($values as $value) {
          $tids[]  = $value['tid'];
        }
      }
      $content->more = array(
        'href' => 'catalog/all_products-tax-term',
        'title' => 'See All',
        'query' => array(
          'field_catalog_tid' => $tids,
        )
      );
    }

  }

  if ($pane->subtype == 'view-name_featured_resources_and') {
    if ($content->delta == 'view-name_featured_resources_and-block_2') {
      if ($context['argument_term_1']->data) {
        $tids = array();
        $tids[] = $context['argument_term_1']->data->tid;
        $content->more = array(
          'href' => 'catalog/all_products-tax-term',
          'title' => 'See All',
          'query' => array(
            'field_catalog_tid' => $tids,
          )
        );
      }
    }
  }

```

# Answer
> 2 votes
I believe you want to use Contextual Filters (or, the functionality formerly known as Arguments").

Expand the "advanced" fieldset on the right side of your View's admin panel.

If, for example, I select "Content:Type" as a contextual filter, and my main page output of the view has a path of "/testview" then I can go to "/testview/Page" and see all content of type "Page". Same with my other content types, which happen to be "Story", "Product", and "Slide". You can do this with features besides content type. It sounds like using taxonomy terms would meet your needs.

---
Tags: tokens, views
---


title: Time Optional using the date_popup type

text:
# Question
Title: Time Optional using the date_popup type
Is there a way to have date/time fields with the date\_popup type, but have the time field be something optional for the user to fill in?

I have the UI with both a Date and Time field with the following code:

```
$form['mygsb_settings']["publish_on_start_date"] = array(
    '#type' => 'date_popup',
    '#title' => "Publish Start Date",
);

```

But when a user doesn't enter the start time, I get back the following validation error from drupal.

The value input for field Publish Start Date is invalid: The value 2012-03-14 does not match the expected format.

Is there any way to avoid this validation error? Basically, I want to make the time field optional.

Greg

# Answer
I needed to allow users to give either a datetime or just a date, so I needed to override the default date\_popup behaviour. NOTE: I am not using the date fields provided with the date uri, just the date\_popup form element.

You can override the default date\_popup validation. The data\_popup module applies the validation function during the `date_popup_element_process` function.

I used a `hook_element_info_alter` function to append a custom process function AFTER the `date_popup_element_process` and applied my own validation function. Like so:

```
function hook_element_info_alter(&$type) {
    $type['date_popup']['#process'][] = 'my_popup_date_process';
}

function my_popup_date_process($element, &$form_state, $form) {
    $element['#element_validate'] = array('my_popup_date_validate');
    return $element;
}

function my_popup_date_validate() {
    if (isset($form_state['values'][$element['#field_name']])) {
        if (trim($form_state['values'][$element['#field_name']][$element['#language']][0]['time']) == '') {
            list($date_format, $time_format) = explode(" ", $element['#date_format']);
            $element['#date_format'] = trim($date_format);
        }
    }
    date_popup_validate($element, $form_state);
}

```

Removed unneeded code for brevity. Updated validation funciton with an example showing how this could be achieved. This example assumes that there is a space between the data and time formats (ie "d/m/Y H:i:s") and that the date format is first.
> 1 votes

# Answer
adding

```
'#required' => FALSE,

```

could help .. see forms API
> 0 votes

---
Tags: forms
---


# Question
Title: Redirecting from example.com to example.com/drupal
I have Drupal 7 installed in a ./drupal directory in my web server (shared host).

I would like www.mysite.net to be redirect to www.mysite.net/drupal in a transparent way for visitors. They should see in their navigation bar www.mysite.net instead of www.mysite.net/drupal.

I also want clean URLs to work. To make clean URLs work, I have edited my drupal/.htaccess file and uncomment this line:

```
RewriteBase /drupal

```

I read a lot of posts about having Drupal in a subdirectory, but the suggested solutions don't work (they cause an internal server error, or problems with CSS and images). Most of these tutorials are based in 2 htaccess file, one in the root directory and one in the directory where Drupal is installed. They also required to change `$base_url` in settings.php.

# Answer
Try in .htaccess and make sure `RewriteEngine On`

```
RewriteRule !^drupal/ drupal/%{REQUEST_URI}

```

Then try `example.com` if this maps to `example.com/drupal/`

I think `RewriteBase /drupal` will not produce the result.

It should be either `RewriteBase /` or commented in the case above.

---

I have gone through this issues deeply and fixed on my end.

Put following rule to your .htaccess on root.

```
RewriteEngine On
RewriteRule !^drupal/ drupal/index.php?q=%{REQUEST_URI}

```

The default .htaccess of Drupal is restored to original.

After this setup css and image will fail those are depending on `$base_path`. I then override `$base_path` value from `/drupal/` to `/` using `hook_init()`

```
function my_custom_module_init(){
   global $base_path;
   $base_path = '/';
}

```

And this is fixed.
> 2 votes

# Answer
The following worked for me, but keep in mind that the issue is still in the form of several bugs, that were not yet addressed as of v. 7.14. It involves something with bootstrap.inc, and updated .htaccess between v. 6 and v. 7. I do not fully grasp modRewrite syntax, so particular instructions could be not as efficient. I just used what worked for me (at godaddy.com hosting).

1. Place Drupal installation in `/drupal/` directory (or whichever, adjust accordingly).
2. Set `$base_url` in `settings.php` to your domain (`$base_url = 'http://example.net';`).
3. Create `.htaccess` file in the root directory and place following in it:

```
# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

ReWriteEngine On
ReWriteBase /

# Exclude other directories from rewrite rules
RewriteRule ^(exclude1|exclude2) - [L]

RewriteCond %{HTTP_HOST} ^example\.net$ [NC]
ReWriteRule !^drupal/   - [C]
ReWriteRule ^(.*)  drupal/$1  [L]

```

**Note:** Up to this point, instructions work the same for Drupal 6 (it would be complete now).
4. In the `/drupal/.htaccess` file find the section starting with following comments:

```
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().

```

Comment out this string (to keep it in case the issue shall be fixed):

```
RewriteRule ^ index.php [L]

```

And add following line (from drupal 6):

```
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```
> 2 votes

---
Tags: redirection
---


# Question
Title: Creating a related content block in Drupal 7 using OpenCalais
How do I use OpenCalais to display related content in Drupal 7?

I would think I have to create a view, or something. I have nearly all the OpenCalais categories enabled (I'm creating a site for a newspaper), so it seems somewhat impractical to use them all as filters. I think you're supposed to use the More Like This module, but it doesn't have a Drupal 7 release. I am genuinely confused.

# Answer
Open Calais will take your content and through their web service create metadata for it which the opencalais module can use to create an amazingly diverse variety of taxonomy terms that are applied to your nodes. It is a really cool service.

Once your content had the tags added by OpenCalais you could use one of the modules that provide a "Similar Content" block: http://drupal.org/node/323329 . Most of them are based on taxonomy terms. The More Like This module doesn't look like it has a D7 release but looks like it also uses taxonomy terms.

The simplest method for making a "More Like This" block might be to use Search API Solr or ApacheSolr. If you have full access to your server it is not that difficult to install. Solr's version of More Like This uses Solr's search engine to determine similar content on your site. Also a very very cool technology.
> 1 votes

---
Tags: 7
---


# Question
Title: Implementations suggestions for content on front page
My front page needs to look like the following:

The header, navigation, and white content areas are part of my page.tpl.php, and show up on all pages.

I'm assuming I can power the blue Image Carousel by creating a content type that contains an image and caption, then create a view that pulls those images out of the database.

Below that are 3 areas which contain different stuff.

"1" is an image that is a link. The image and link need to be controllable by the admin. "2" is a Facebook social plugin. I'm assuming I can just create a content block and paste the HTML from Facebook into that and assign that block to show up on the front page, somehow. "3" is another, smaller, image carousel, but will most likely use a different content type (assuming I should be using content types for this at all).

What is the best way to put this page together?
It doesn't need to be completely flexible from the admin screens. I'm OK with building a front page template.

How would you build this page? I'm getting to the point where I can get things to work, but I don't think I'm doing them in the most efficient and/or Drupalish way.

# Answer
I'd use Panels to handle the layout. Panels will allow you to create a customized front page without using any templates from within the Panels interface. I can't describe in detail how to use Panels here but Node One has an excellent series of screencasts on Page Manager and Panels.

Using Panels will allow you to easily give the front page a unique look which you can change at any time by simply logging in to the site (as an admin) and opening up the Panels interface.

For the slideshow, try the Views Slideshow module. It is well-documented (links on the module page) so you shouldn't have too hard of a time setting it up, and it is widely used (more than 100,000 sites).
> 1 votes

# Answer
Panels is very weighty module and views is also. So i would not advice you panels for such simple thing as that.

You could use views to generate your carousel (Nivo Slider, Views Slideshow or etc) or you can implement any kind of other slideshow/carousel script. If you want other you would have to edit a view template by your means.

Then i would create a page--front.tpl.php (just copy your page.tpl and rename - it assumes that you already have those blocks, header and navigation, you could use any of useful for your theme, Framework for example. More info about theme hook suggestions.

After you could embed your view with a block in this page directly where it needs to be.

```
<?php print views_embed_view('slider', 'block'); ?>

```

Where slider is the machine name of the view and block is the id of your block.

Or you can simply put a block to a region created for that or if it exists for another content.

With blocks it\`s rather simple just create it and put there anything you want, edit your blocks in that region with css to display proper. 1st and 3rd block can be simply build with views. Try to learn some from views tutorials, this one for example.

Hope it will help. Good luck
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Add JavaScript into a specific content type
I would like to know what is the best way to add a JavaScript file into a specific page basing on the content type. For example, I want to add this:

```
<script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script>

```

So far, what I have done is using this way to add into my specific content type. For the map\_page content type, I adde the below two line of code in page--map\_page.tpl.php.

```
drupal_add_js("http://maps.google.com/maps/api/js?sensor=false", 'external');
$scripts = drupal_get_js();

```

Is there any other better way? if possible can give some example, currently not really understand well...

# Answer
> 6 votes
I can't comment on the proper Drupal 7 equivalent, but in Drupal 6 sites I do this in a template\_preprocess\_page.

I will have some logic to make the decision (either based on `arg()` or `page_manager_get_current_page()` from panels), and then prepend `$vars["scripts"]` with the external script. I prepend so that I don't run into dependency trouble with any local scripts.

I will also sometimes set up a new region called `$global_scripts` for thinks like Google API and SWFObject that I want to load from a CDN, and this gets printed out before `$scripts` in the page template.

To be honest, though I normally have all JS on all pages so that the files get cached.

# Answer
> 6 votes
Since Drupal won't let you redefine `template_preprocess_node` (because it's already defined in node.module), I added a preprocessor function in my custom module:

```
function mymodule_preprocess_node(&$vars) {
  if ($vars['type'] == 'my-node-type') {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/myjs.js');
  }
}

```

I used `preprocess_node` rather than `preprocess_page` because it's easier to get to the node type. If you actually reference a javascript file, then it will be automatically cached (see Parameters section).

# Answer
> 2 votes
you could also use hook\_node\_view check for the content type and then add the js in the way you are doing already.

OR

If you have a field which outputs the information which will use the JS use a preprocessor there to add the js, so the js include is dependent on the field displaying the map rather than the content type.

# Answer
> 0 votes
A simple solution is to just place the add\_js:

```
  drupal_add_js('drupal_get_path('module', 'mymodule') . '/myjs.js');

```

in the page/node template.php.

---
Tags: 7, javascript
---


# Question
Title: Admin denied access to Ubercart Store when running Ubercart SSL
I am running the Ubercart SSL module (not Secure Pages) for my Drupal 7.12 site. I am unable to checkout an order as admin, and I get an access denied message when I try access my store.

Ideas?

# Answer
I would go with the Secure Pages module http://drupal.org/project/securepages and I've create a small write up on how to set up Secure Pages with UC http://drupal.org/node/1586258
> 0 votes

---
Tags: ubercart, ssl
---


title: jQuery integration problem

text:
# Question
Title: jQuery integration problem
I have an problem to get my jQuery code working with D7. In HTML it works fine but with D7 it doesn't work at all...

the code:

```
(function ($) {

Drupal.behaviors.exampleModule = {
attach: function(context, settings) {

    var thumbstart = $("ul li img");

    for (var i = 0, ii = thumbstart.length; i < ii; i++){
        if (thumbstart[i].title && thumbstart[i].title.length > 0)
        {
            var imgtitle = thumbstart[i].title;
            $(thumbstart[i]).wrap('<div class="wrapper" />').
            after('<div class=\'inner\'><span class=\'caption\'>' + imgtitle + '</span></div>').
            removeAttr('title');

        }
    };
// At here the code works fine...
$('.wrapper').find('img').css({opacity: ".8"});
$('.teaser').find('.caption').css({top:"107px"});
$('.test2').find('.caption').css({top:"165px"});

$('.teaser').hover(
    function(){
        $(this).find('img').animate({opacity: "1.0"}, 300);
        $(this).find('.caption').animate({top:"160px"}, 300);
    },
    function(){
        $(this).find('img').animate({opacity: ".8"}, 300);
        $(this).find('.caption').animate({top:"107px"}, 300);
    }
    );

}
};

})(jQuery);

```

the problem is that the top of part is not working (begins at: var thumbstart...) is there anything that I can do? Does D7 need extra library/modules?

# Answer
Far from needing extra libraries, Drupal needs *less* libraries then you're giving it.

Drupal 7 ships with jQuery 1.4, and can be updated to 1.5.2 with the jQuery Update module. Updating to v1.7 is not really feasible at the moment (see How do I update jQuery to the latest version I can download?, and search the site for 'latest jquery' for more information on that).

Even if the core/contrib Drupal JS worked well with v1.7, you can't just add it to the page and expect it to work, it will conflict with the core jQuery libraries added by Drupal (see `jQuery.noConflict()` for background).

That said, I can't see anything in your code that would necessitate using jQuery 1.7, so just remove the erroneous line from your .info file, clear the caches, and move on :)

To address the problems with your code now that the correct jQuery files are being included:

Your JS looks like this:

```
if (thumbstart[i].title && thumbstart[i].title.length > 0)

```

So the wrapper won't be added unless the `<img>` has a title. If you look at the source code of http://icon-guideline.fanlobby.net/ you'll see that the markup is as such:

```
<ul><li>
    <a href="http://icon-guideline.fanlobby.net/design-kriterien"><img alt="" src="/sites/default/files/images/Android.png" /></a></li>
<li>
    <a href="http://icon-guideline.fanlobby.net/design-kriterien"><img alt="" src="/sites/default/files/images/iPhone.png" /></a></li>
<li>
    <a href="http://icon-guideline.fanlobby.net/design-kriterien"><img alt="" src="/sites/default/files/images/WindowsPhone.png" /></a></li>
<li>
    <a href="http://icon-guideline.fanlobby.net/design-kriterien"><img alt="" src="/sites/default/files/images/BlackBerry.png" /></a></li>

```

As you can see, there's no title on any of the images, so your JS condition will never resolve to `true`, and the wrapper will never be added.
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: How to put a Token in a path in a view Path setting?
I have a view page display to show some content and I added a contextual filter to filter by user id \[uid\]. It works fine.

I need to create the path to be shown in the **Main Menu** including the token for user id at the end of the path. Something like `/tus-lotes/[uid]`

If I try with: `/tus-lotes/%` I get this error message:

```
Views cannot create normal menu items for paths with a % in them.

```

But I see that the path doesn't accept token. How can I accomplish this?

Please look the capture:

# Answer
In the contextual filter settings: **When the filter value is NOT available** -\> provide default value -\>User ID from url

and edit link of the view just without the argument/token
> 2 votes

---
Tags: views, tokens
---


# Question
Title: Why cannot I print $form in my template file?
I have a "video" content type. I want to customize the template file for edit form, page--node--add--video.tpl.php, but when I render (or print) `$form`, it returns `NULL`.

What is the problem?

# Answer
There's no `$form` variable available in page.tpl.php (see the docs for a full list of available vars).

If you're trying to output the page content it's done like so:

```
<?php echo render($page['content']); ?>

```
> 4 votes

---
Tags: forms, theming
---


# Question
Title: node_type_get_type() and hook_uninstall()
I have a job\_post module, which defines the "job\_post" content type.

In this module I have `hook_unistall()` which calls node\_type\_delete() to remove that content type.

After uninstalling, I have the following error from the Comment module:

> Notice: Trying to get property of non-object in comment\_node\_type\_delete() (line 343 of ....\comment.module).

I have this error because the `$info` variable in `node_type_delete()` is set to `FALSE`.

Why when my module is installed and when I am printing `var_dump(node_type_get_type('job_post'))` on any page, I have an object, but when I'm trying to print the same code in my unistall function I get `FALSE` and this error?

### job\_post.install

```
/**
 * Implements hook_install().
 */
function job_post_install() {
  node_types_rebuild();

  $types = node_type_get_types();
  node_add_body_field($types['job_post']);

  $body_instance = field_info_instance('node', 'body', 'job_post');
  $body_instance['type'] = 'text_summary_or_trimmed';

  field_update_instance($body_instance);
}

/**
 * Implements hook_uninstall().
 */
function job_post_uninstall() {
  $instances = field_info_instances('node', 'job_post');
  foreach ($instances as $instance_name => $instance) {
    field_delete_instance($instance);
  }

  // Force rebuild of the node type cache
  // as Clive suggested didn't help
  // _node_types_build(TRUE);

  node_type_delete('job_post');

  field_purge_batch(1000);
}

```

### job\_post.module

```
/**
 * Implements hook_node_info() to provide our job_post type.
 */
function job_post_node_info() {
  return array(
    'job_post' => array(
      'name' => t('Job Post'),
      'base' => 'job_post',
      'description' => t('Use this content type to post a job.'),
      'has_title' => TRUE,
      'title_label' => t('Job Title'),
      'help' => t('Enter the job title and job description')
    )
  );
}

/**
 * Implement hook_form() with the standard default form.
 */
function job_post_form($node, $form_state) {
  return node_content_form($node, $form_state);
}

```

# Answer
If you look at the code that the Forum module executes in forum\_uninstall(), you will notice that it just deletes the field it defines, but it doesn't delete the content type it defines.

```
function forum_uninstall() {
  // Load the dependent Taxonomy module, in case it has been disabled.
  drupal_load('module', 'taxonomy');

  variable_del('forum_containers');
  variable_del('forum_hot_topic');
  variable_del('forum_per_page');
  variable_del('forum_order');
  variable_del('forum_block_num_active');
  variable_del('forum_block_num_new');
  variable_del('node_options_forum');

  field_delete_field('taxonomy_forums');
  // Purge field data now to allow taxonomy module to be uninstalled
  // if this is the only field remaining.
  field_purge_batch(10);
}

```

Your module should do the same, and avoid deleting the fields defined for the content type (if they are not defined from the module), or the content type itself.
> 1 votes

# Answer
`node_type_get_type()` calls `_node_types_build()`, which contains the following comment.

```
// Check for node types from disabled modules and mark their types for removal.
// Types defined by the node module in the database (rather than by a separate
// module using hook_node_info) have a base value of 'node_content'. The isset()
// check prevents errors on old (pre-Drupal 7) databases.

```

Apparently, `_node_types_build()` is not intended to return content types from disabled modules.
> 0 votes

---
Tags: 7, hooks
---


title: FAQ display using Views

text:
# Question
Title: FAQ display using Views
I would like to set up a FAQ system using a custom content type and views. I would like to display the FAQs one of two common ways:

* Each question is a link that hides/displays the answer below it when the link is clicked, or
* Each question is a link that jumps down to a corresponding anchor on the page with the answer.

Are either of those possible in Views? I'm new to Drupal and learning as I go. Thanks.

# Answer
There is a module that will do exactly that, called FAQ.

And it also integrates with Views should you need to extend it. But out of the box, it should do the two things you need (I have used it and did both things).
> 1 votes

---
Tags: 7, views
---