# Question
Title: How to color cards (hearts and diamonds) red in Drupal 7 comments?
I run a Drupal 7 website with Forum, Blog, Comment core modules enabled and a custom module (generates a block with Flash game and blocks with player rating) written by me.

The website is dedicated to a Russian card game and users often mention card colors in their comments when discussing some card riddle or a game:

Most users are older folks, who don't understand anything like HTML tags, so I have only enabled plain text comments for them.

**My quesion is:** in the plain text Comments - how to recognize the strings like K♥ or 7♦ and color them red?

The PHP code would be something like:

```
preg_replace(/(1?[0789JQKA][♥♦])/, '<font color="red">\1</font>', $str);

```

(I can improve the regex later) - but where/how to apply it in Drupal 7?

# Answer
What you are looking for seems to be Text filters and Input Formats.

> Processing textual content for output in a browser is one of Drupal's most critical tasks. Without such processing we would all have to become masters at typing in HTML text! This section of the handbook explains what filters and input formats are, why they are important, how they are used, and why they impact site security.

Or you can just dump regex in template.php or comment.tpl.php - it's way simpler and way less clean, but works.
> 4 votes

# Answer
If you need it to be configurable/re-usable then a custom filter is the way to go as Mołot said. The idea is that the raw data is always stored, and the filter is applied upon display. This is all well and good, but if you don't ever *need* the original text I find this method to be an unnecessary performance overhead (especially when you involve regexs, as most filters do).

The other way is to intercept the comment body before it's saved, and apply your filter then. For this you can use `hook_comment_presave()`:

```
function MYMODULE_comment_presave($comment) {
  $comment->comment_body[$comment->language][0]['value'] = string_replacement_function($comment->comment_body[$comment->language][0]['value']);
}

```

I know this method is 'frowned upon' (heaven forbid we alter someone's input, even if we *want* to control what goes in the database!), and I can think of at least 2 people who will downvote this if/when they see it.

I think the benefits/drawbacks of both methods are pretty clear, though, so I'd advise you make a decision based on *your use-case*. If the module you implement to do this isn't being released back into the wild, I see no benefit in taking the extra performance hit here.

But if you think you'll ever want to use this method to filter text elsewhere on the site (e.g. in node bodies), a custom filter would make more sense.
> 5 votes

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


title: multi query execution

text:
# Question
Title: multi query execution
i want to implement store procedure in drupal 6, i need database(mysql) connection to execute `$mysqli->multi_query($query)` currently i am creating new connection every time when my function called.
Here in my function for this,

```
function test($journal_id, $ebook_id, $table_name)
{
$mysqli = new mysqli('localhost','root','root','sanjay');
$query = "CALL GetFreeOpenAccessVolumeList1($journal_id, $ebook_id,'$table_name')"; #     if ($mysqli->multi_query($query)) {

if ($result = $mysqli->store_result()) {
     while ($row = $result->fetch_object())
     {

        $arr[] = $row->content_type_id;
     }
    $result->free();
    $mysqli->next_result();
  }
}
else
{
  drupal_set_message("An error ocurred in your module while calling the
   sp_yourstoredprocedure stored procedure. MySQL error: ".mysqli_error(), 'warning');
}

return $arr;
}

```

# Answer
You can get the current connection object through the `$active_db` global.

It's been a million years since I used old-school mysql(i) methods and I can't remember if you can instantiate a new `MySQLi` object from that connection object; Drupal uses the procedural method itself (see `_db_query()`), as in this example:

```
global $active_db;
$query = "CALL GetFreeOpenAccessVolumeList1($journal_id, $ebook_id,'$table_name')";
$result = mysqli_query($active_db, $query);

```

Someone has implemented a `db_query_call()` function which will probably give you everything you need to call stored procedures:

http://drupal.org/node/119781#comment-2904142

Altering it to use the current instantiated connection should be trivial.
> 0 votes

---
Tags: database
---


# Question
Title: Custom rendering exposed filters in Views
I'm sorry if this is dumb question, but I'm creating a search page for a content type using Views in Drupal 7. I am developing multiple exposed filters to achieve this, however, when the filters are rendered, they are done so side by side. I would like them to stack on top of each other with the "Search" button at the bottom.

Is there something obviously simple I am missing or does anyone know how to do this?

# Answer
Copy the views-exposed-form.tpl.php which is located at `<drupalroot>/sites/all/modules/views/theme` to your own theme folder. And it should be easier for you to style it. Here is a tutorial you can follow
> 1 votes

---
Tags: views
---


# Question
Title: By default, Shipping information fields should be shown
In Drupal commerce kickstart Checkout page, by default Shipping information fields should show and the checkbox should uncheck. I tried JavaScript, but it is not working. How do I do this?

# Answer
1) Go to Store Settings -\> Checkout settings 2) Click the configure link for "Shipping information" 3) On the configure page, uncheck the "Make copying information from this profile the default action, requiring users to uncheck a box on the checkout pane to enter a different address." checkbox.
> 1 votes

---
Tags: commerce
---


# Question
Title: Page template suggestions are not working
I've created a theme and have my template files in this structure

* /templates/page/page.tpl.php
* /templates/page/page--node-type.tpl.php

I've created a custom page template but for some reason it's not being picked up by Drupal. I've cleared my cache and also tried adding this preprocessor function in the theme template.php file but it's still not working.

```
if (isset($vars['node']))
  {
    // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $vars['node']->type);
  }

```

Any help would be appreciated.

# Answer
> 14 votes
As reported in Drupal 7 Template Suggestions, the template suggestion used by default from Drupal 7 for pages is page--\[front|internal/path\].tpl.php.

For a page visible at http://www.example.com/node/1/edit, Drupal would look for the following template files:

* page--node--edit.tpl.php
* page--node--1.tpl.php
* page--node.tpl.php
* page.tpl.php

To add extra suggestions, your theme should implement template\_preprocess\_page() and add new suggestions in `$variables['theme_hook_suggestions']` (`$variables` is the variable passed by reference to the function).

If you did that, then the only reason the suggested template file is not being used is because the file is not correctly named: in the case the page shows a book page, for example, the template file should be page--book.tpl.php. You could change the code for your theme, and let it use the page--node-type.tpl.php template, if it doesn't find a template like page--book.tpl.php.

To notice also that, in theme\_get\_suggestions() (which is the function called by template\_preprocess\_page()) hyphens are replaced by `_`, and not vice versa. The reason that is done is explained in a comment reported in the function code.

```
// When we discover templates in drupal_find_theme_templates(),
// hyphens (-) are converted to underscores (_) before the theme hook
// is registered. We do this because the hyphens used for delimiters
// in hook suggestions cannot be used in the function names of the
// associated preprocess functions. Any page templates designed to be used
// on paths that contain a hyphen are also registered with these hyphens
// converted to underscores so here we must convert any hyphens in path
// arguments to underscores here before fetching theme hook suggestions
// to ensure the templates are appropriately recognized.
$arg = str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $arg);

```

# Answer
> 5 votes
I'm using Drupal 7.4, and I had the same problem and the only thing that helped was this post: How to add a custom page.tpl based on content types

From the post:

```
<?php
/**
* Variables preprocess function for the "page" theming hook.
*/
function THEME_NAME_preprocess_page(&$vars) {

  // Do we have a node?
  if (isset($vars['node'])) {

    // Ref suggestions cuz it's stupid long.
    $suggests = &$vars['theme_hook_suggestions'];

    // Get path arguments.
    $args = arg();
    // Remove first argument of "node".
    unset($args[0]);

    // Set type.
    $type = "page__type_{$vars['node']->type}";

    // Bring it all together.
    $suggests = array_merge(
      $suggests,
      array($type),
      theme_get_suggestions($args, $type)
    );

    // if the url is: 'http://domain.com/node/123/edit'
    // and node type is 'blog'..
    //
    // This will be the suggestions:
    //
    // - page__node
    // - page__node__%
    // - page__node__123
    // - page__node__edit
    // - page__type_blog
    // - page__type_blog__%
    // - page__type_blog__123
    // - page__type_blog__edit
    //
    // Which connects to these templates:
    //
    // - page--node.tpl.php
    // - page--node--%.tpl.php
    // - page--node--123.tpl.php
    // - page--node--edit.tpl.php
    // - page--type-blog.tpl.php          << this is what you want.
    // - page--type-blog--%.tpl.php
    // - page--type-blog--123.tpl.php
    // - page--type-blog--edit.tpl.php
    //
    // Latter items take precedence.
  }
}
?>

```

# Answer
> 2 votes
I have spent too long trying to follow the example above using string replace in Drupal 7.22. This does not seem to work for me. Interestingly some content types seem to be suggested automatically, while others do not. This is the code that worked for me in the end.

```
if (isset($variables['node'])) {
   // $variables['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $variables['node']->type);
   //cannot get above working for some reason?
     $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
  }

```

so the template suggestion for a front\_page content type this would then be:

page--front\_cover.tpl.php

Interestingly the code template suggestion for 'issue' content type comes through for as page--issue.tpl.php without any need for a preprocessor script!? This for my purposes seems to override the view template that uses a similar path.

i.e.

view path = /issue/# template suggestion based on content type i.e. /issue/#/front\_cover

---
Tags: 7, theming
---


# Question
Title: How to add classes to a specific bean w/ display suite template
On the website home page that I'm working on, we have 4 call-to-actions.

Below is the DS template file which is used when rendering each of them:

```
<?php

/**
* @file
* Display Suite 2 column template.
*/
?>

<<?php print $layout_wrapper; print $layout_attributes; ?> class="ds-2col <?php print $classes;?> cta-body clearfix" style="background: #<?php print $field_bg_colour[0]['value'] ?>">

<?php if (isset($title_suffix['contextual_links'])): ?>
<?php print render($title_suffix['contextual_links']); ?>
<?php endif; ?>

<!-- If there's a more link, add a link -->
<?php if (isset($field_more_link)): ?>
  <a href="<?php print $field_more_link[0]['url']; ?>">
<?php endif; ?>

  <<?php print $left_wrapper ?> class="group-left<?php print $left_classes; ?>">
    <?php print $left; ?>
  </<?php print $left_wrapper ?>>

  <<?php print $right_wrapper ?> class="group-right<?php print $right_classes; ?>">
    <h2 class="title"><?php print $title ?></h2>
    <span class="cta-text">
      <?php print $right; ?>
    </span>
  </<?php print $right_wrapper ?>>

  <div class="clear"></div>

<!-- And close the link -->
<?php if (isset($field_more_link)): ?>
  </a>
<?php endif; ?>

</<?php print $layout_wrapper ?>>

<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

```

Currently I'm adding a margin-right to each of these, but would like to remove the margin-right on the even number call-to-actions - so my layout works.

Is there any way I can add an odd/even zebra class or a better way to do this?

Many thanks

# Answer
A friend helped me solve this one. All I needed was the following PHP as a container class.

```
<?php print $zebra; ?>

```

I can now style the .odd containers!

Thanks all
> 2 votes

---
Tags: display-suite, theming, blocks
---


# Question
Title: Accessing sub-array data from theme_field__custom_content_type($variables)
This is a mix of a PHP and a Drupal question.

I created a custom function...

```
theme_field__custom_content_type($variables)

```

I have the DEVEL module installed and have been using it profusely. I'm trying to modify the layout/look of a custom content through a childtheme I'm developing. I'm running into an issues that is leaving me scratching my head.

I have a custom content type \[netrunner\_card\] and it has several fields that are taxonomy references. One field in particular is \[field\_card\_subtype\]. A card can have multiple subtypes... "Location," "Seedy," "Cloud," etc. What I want to do is to take those subtypes and place them next to another field like so:

```
field_card_type : field_card_subtype[0] - field_card_subtype[1] - etc

```

So that you would see output like:

Operation : Location - Seedy

ICE : AP - Trap

etc.

What I am doing is the following... Yes, I am creating custom variables for this as it helps to collect everything in an easy to use package.

```
$blinksFieldName = $variables['element']['#field_name'];
switch( $blinksFieldName )
{
    case 'field_unique_card':
        $variables['card_is_unique'] = $variables['element']['#items'][0]['value'];
        break;
    case 'field_card_subtype':
        $variables['card_subtype_list'] = implode( " - ", $variables['element']['#items']);
        break;
    ...
}

```

When I kpr( $variables\['card\_subtype\_list'\] ) I get a string of the word 'Array'. I think that's because the breakdown of the variable in question is more like:

```
$variables['element']['#items'][0]['#title']

```

I'm very confused how you reach that level of the array when one of the placeholders is the array index... I had thought to do a for-next but I can't figure out how I would word it? Any help would be greatly appreciated.

# Answer
I think I get what you're doing...you won't be able to straight implode the items array if it's a sequential set that you're using to build up a list of key/value pairs...

There are probably a few different ways to do that loop, I'd try something like this:

```
$keys = $values = array();
$count = 1;
foreach ($variables['element']['#items'] as $item) {
  if ($count++ % 2 == 1) {
    $keys[] = $item['#title'];
  }
  else {
    $values[] = $item['#title'];
  }
}

$output = '';
for ($i = 0; $i < count($keys); $i++) {
  $output .= $keys[$i] . ' - ' . $values[$i] . '<br />';
}
$variables['card_subtype_list'] = $output;

```

Hopefully someone will propose a better solution, that's not exactly elegant. Apologies if I've misunderstood.
> 1 votes

# Answer
What I did to make this work is as follows. Inside template.php, in the following function:

```
function blinks_responsive_field__netrunner_card($variables)

```

I checked the $delta in the foreach for which subtype I was on.

```
$subTypeSpacer = '';
if( $blinksFieldName == 'field_card_subtype' ){ if( $delta > 0 ){ $subTypeSpacer = ' - '; } }

```

So if we were on subtype #0 (the first one) then don't add the hyphen. Otherwise add it. Then to insert the subTypeSpacer into our output I did the following:

```
$output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . $subTypeSpacer . drupal_render($item) . '</div>';

```

This put everything together in our $variables. Now we have to call them. So we move ahead to node--netrunner-card--Operation--full.tpl.php

In here, we are custom styling the output for an Operation card. Jump down to where render( $content ) used to go, and we see this:

```
<div class="field-card-type"><?php print render( $content['field_card_type']); ?> : <?php print render( $content['field_card_subtype'] ); ?></div>

```

So, now we have all of the elements together, but they sure don't look pretty. These divs are treated like block elements, so they each get their own line. Not acceptable. So let's jump to style.css and do this...

```
div.field-card-type div
{
    display: inline;
}

```

Done.

If you'd like to see a sample here is what it looks like: A single operation card with the card subtypes styled like desired.
> 0 votes

---
Tags: theming
---


# Question
Title: Looking for a module to hit a tokenized URL when certain actions happen
I'm working with an API from another software product. And the way to create/update records there is by hitting a specifically crafter URL.

Ex. https://sample.nodeurl.tld/save?xml&object=supporter&Email=mytest@email.com

Is there any way to do this with rules or via another module? Or does this have to be done through a custom coded module?

# Answer
> 1 votes
The Rules HTTP Client module (+ Rules itself) will handle that:

> This module adds an action wrapping of drupal\_http\_request to use Rules for making http requests. It has many general uses, because the Hypertext Transfer Protocol is the foundation of web data communication.

---
Tags: 7
---


title: Translate logo and favicon?

text:
# Question
Title: Translate logo and favicon?
I am wondering if there is a method to translate the appearance settings section for each theme, for example the logo URL.

# Answer
> 1 votes
This "Variable Translation" module should help you out: http://drupal.org/node/1113374

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


# Question
Title: Upload a file to Drupal server from an outside URL
I am trying to cache in the server the profile images provided by the Facebook Graph API. So far what I did unsuccessfully was getting the path of the image then calling:

```
$file = file_save_upload($big_pic_url, array(), $dest, FILE_EXISTS_RENAME);

```

This returns `NULL` every time. I tried several syntax for the destination path, and also for the Pic URL path, nothing seems to work.

I am doing this the right way? Can `file_save_upload()` take an external link as part of its argument?

# Answer
Here is a solution I've used recently for a Facebook module. Set the image path to `$path` variable (ie. http://graph.facebook.com/username/picture). Then do the following to store it via Drupal's managed file system:

```
$image = file_get_contents($path); // this is a PHP function to get a string representation of the image file

$destination = 'public://path/to/store/this/image/name.jpg'; // a stream wrapper path where you want this image to reside on your file system including the desired filename

$file = file_save_data($image, $destination, FILE_EXISTS_REPLACE);

if (is_object($file)) { // if you get back a Drupal $file object, everything went as expected so make the status permenant
   $file->status = 1;
   $file = file_save($file);
}

```
> 5 votes

# Answer
This is the function I am using and that works.

```
function get_external_image($url) {
    $external_image = file_get_contents($url);
    $parsed_url = parse_url($url);
    $name_dest = rand(1000,9999)."_". basename($parsed_url["path"]);
    $file = file_save_data($external_image, 'public://'.$name_dest , FILE_EXISTS_REPLACE);
    if (is_object($file) && file_exists($file->uri)) {
        $file->status = 1;
        $file = file_save($file);
        drupal_write_record('file_usage', $file);
        return (array) $file;
    }
    return null;
}

```

This is an example on how to use it.

```
// Load your node.
$node = node_load("9999");
// Assign your image.
$node->field_image[$node->language]['0'] = get_external_image("http://cdn.sstatic.net/drupal/img/logo.png");
// Save your node.
node_save($node);

```
> 1 votes

---
Tags: 7, files
---


# Question
Title: How do I display inline content with the Colorbox Module?
I understand that I need to add the class "colorbox-inline" to the link and build the url like 119 this "?width=500&height=500&inline=true#id-of-content"... but how do I do that? Do I need to edit a .tpl file?

# Answer
> 5 votes
No PHP, this is done with HTML and JavaScript

1. CSS style the inline-content you want to display with "display: none;"
2. for colorbox: in "configuration", "Media", "Colorbox" --\> advanced settings, activate "Enable Colorbox inline"
3. add this as the html code for opening the colorbox webform link: `<a class="colorbox-inline" href="?width=310&height=460&inline=true#name-of-your-inline-content">`
4. If this is not working try some additionally jQuery-Magic: `$('#name-of-your-inline-content').colorbox();`

---
Tags: javascript
---


# Question
Title: Understanding database structure for auto-migration
I am trying to come up with a good way to get this handed down Drupal project to work as smooth as possible. Ideally, my goal is to do changes local, and when that looks okay, I should be able to `git push` this to the server. Earlier I've made myself able to push structure changes through git `hooks/post-receive`, `CodeIgniter Migrate` and some bash scripts. This was worked out really neat, and I'm interested in similiar solutions for my Drupal project.

Ideally, I would like to upon `git push` have my php script generate a `.sql` file, send it to the server and let the server execute it so that it replaces live tables as ideal. Since our main page will handle products, orders and such that can't be overwritten, I can't simply just clone the database.

The thing I'm mostly puzzled out is, how do I tell what tables do what in my Drupal database? I have around 300 tables, and am not fully sure how dependent the tables are of each other, which that handles structure changes such as enabling and disabling modules and so on. Does anyone share an insight regarding this?

Maybe there's some easy solution for what I'm after that I've missed?

# Answer
> 2 votes
You can skip migrating the following tables:

* accesslog
* cache\_\*
* sessions
* watchdog

All the above contains material that you generally don't want to migate across sites.

The contents of the tables for built-in search will be regeneated by *cron* if you don't migrate them, but it may take up a lot of resouces if you've a lot content. But if this is not a concern, you can also skip migrating:

* search\_\*

As for table names, Drupal relies heavily on namespace dicipline to avoid collisions. So a module named `foobar` should *only* create tables with a name that starts with `foobar_` (or just `foobar` if it only creates a single table). In other words, you can tell what tables in the database that "belongs" to what module by their name. This goes for both core modules and for regular contributed modules. As for custom modules (i.e. modules that is managed outside the Drupal.org framework, you may find exceptions to this naming convention - but only if they're written by bozos `:-)`.

If you look at your database, you may discover a lot of tables with names starting with `field_`. These are of course from the (core) Field module, but I mention these specifically because these are the tables used for custom content types that are created using "Fields in core" (a key Drupal feature).

As for interdependencies between tables, looking at the fields in the tables that belong to the same module is usually enough. Getting familiar with the Schema API is also helpful. But to be honest: Sometimes you need to sit down and read source code.

As for creating and dropping tables, well behaved modules create datebase tables using `hook_schema` (found inside the module's `.install`-file) upon installation, and automatically drop the same tables upon un-installation.

Note that just pushing a module with git doesn't *install* the module. It just makes it available for installation. To install it, you either do it manually (using the administrator's GUI), or script it using *Drush*.

It is also useful to know that there are clear rules in the Drupal community of practice that a module should *only* write to its own tables. If a client module want to write to another module's table, it must do so through the module's API, not by interacting with the database. Module interdependency is tracked in the module's `.info`-file. This means, for instance, that you'll not be able to disable a service module a client module relies on (provided their interdependency has been correctly declared).

---
Tags: 7, commerce, database, version-control
---


title: Cant get the site out of maintence mode

text:
# Question
Title: Cant get the site out of maintence mode
I am using Drupal 7. I just started creating a new drupal site. Instead of downloading all of the necessary contributed modules, I copied them from a different test site I had made recently. There were a few modules which needed to be updated, so I put the site in maintenance mode, deleted those module folders, pasted in the new ones, ran the update script and now I have no errors. However, now it still says "Operating in Maintenance mode - Go Online", and clicking "Go Online" brings me back to the maintenance configuration page, but I remain in Maintenance Mode! I cleared all caches and nothing helped! I could just restart everything from scratch, but I would like to understand this issue.

I'm not sure if this make a difference, but originally when I installed the drupal database, I used a previously created database which had only one table (non-drupal) which I deleted before installing the drupal database tables. Should this have effected anything?

# Answer
If your description of what you do is accurate, the problem is simple to solve.

Clicking "Go online" is only the first step required to take your site out of maintenance mode. You *also* need to remove the tick from the box to the left of "Put site into maintenance mode", and then click "Save configuration".

However, if you go through all these steps, and it still fails, you need to update your question to accurately descibe what you do, and we'll take it from there.
> 3 votes

---
Tags: maintenance-mode
---


# Question
Title: override variable in template.php with variable from module_preproccess_node
I create custom template for node, and put variable in template.php

```
$colors = array('black', 'white');
$variables['group']['color'] = $colors;
$variables['size'] = 'double';

```

then i also create module and want to do hook to node template.

```
mymodule_preproccess_node() {
$colors = array('blue', 'red', 'green');
$variables['group']['color'] = $colors;
$variables['size'] = 'regular';
}

```

i want to show in my result:

```
//colors are blue, red, green instead of black, white
foreach ($group['color'] as $color) {
print $color.', ';
}
//and size is regular instead of double
print $size;

```

am i right? i want to override variables in template.php with variables from my module. then if i disable my module color will back from template.php.

# Answer
> 0 votes
If I am understanding/reverse engineering your question correctly, in your module, you can do something like this:

```
function YOURMODULE_preprocess_node(&$variables) {

  if ( // whatever logic ) {

    $colors = array('blue', 'red', 'green');
    $variables['group']['color'] = $colors;
    $variables['size'] = 'regular';

  }

}

```

This will create variables that can be accessed inside node.tpl.php and its variants.

In template.php you can then do something like this:

```
function YOURTHEME_preprocess_node(&$variables) {

  if (!isset($variables['size'])) {
    $variables['size'] = 'double';
  }

  if (!isset($variables['group']['color'])) {
    $colors = array('black', 'white');
    $variables['group']['color'] = $colors;
  }

}

```

which will set them to your defaults if they haven't already been set.

Then you can do whatever you want with them in node.tpl.php.

---
Tags: hooks, theming
---


title: Adding a logout, but not login

text:
# Question
Title: Adding a logout, but not login
Somewhat weird situation, but it is what it is.

Decreed that user accounts are no longer required for access to spec documents. That's good.

However, we have various editors who will still edit content and will need to log in. The simple thing is to just give them a url to bookmark with the ?q=user added. Works fine.

However, I need to add a logout link so they can actually sign out. So, I need to somehow tell Drupal, based on role authentication, show this link.

I tried putting the default User Login block in the header and checked the domains and roles of the various editors and authenticated web user but they aren't showing. Could this be due to login/logout links of the Primary menu being disabled?

Next, I tried making a block with simple text: logout with the link of logout but it's not showing up in the header either. And yes, I tried other pages using the basic page.tpl.php template to make sure the block was in a used region.

I'm not afraid to slam some php somewhere, but I'd like to think I'm just missing something.

# Answer
You can add a standard menu item to any menu with a path of `user/logout`.
> 4 votes

---
Tags: users
---


# Question
Title: Nesting a View in a View... or something like that
**THE SETUP**

I have a View set up to create a page out of a particular content type called "enticements". For context, an enticement is something that would make a guest want to stay at a hotel. Things like local attractions and dining.

So my view uses the content types \[machine\_name\] in this order

* Image \[field\_image\]
* Title \[title\]
* External URL \[field\_link\]
* Body \[body\]

All fields are set to hidden because I want them to be arranged just so, all within the \[body\]. The body rewrite result looks like this:

```
<div class="enticement-wrap">
  <div class="enticement-image">
    [field_image]
    <div class="enticement-link">[field_link]</div>
  </div>
  <div class="enticement-body">
    <h2 class="enticement-title">[title]</h2>
    [body]
  </div>
</div>

```

**THE QUESTION** This all works fine except that the \[field\_image\] can be one or more images, but no matter what I try it only shows the first image. Even when I tried telling views to show the \[field\_image\] with "Multiple Field Settings" set to "Display all values in the same row" in an unordered list, it still just shows the first image.

Why only the first image? Is there a way to get Views to use every image in the rewrite?
Or can I somehow nest a Slideshow View inside the Enticement view?

# Answer
> 7 votes
Check out the Views Field View module. I have not used it, but it is supposed to embed a view in another one. Please post back if it works.

# Answer
> 2 votes
I was trying to figure this out for an embarrassingly long time. I have a situation where I am trying to do a many to many relationship between two taxonomies (you could do this with content types too). I realize taxonomy can do this by default for just term names but I have image and other fields on my taxonomy terms that I wanted to use in a custom sub-view:

## Page 1

### Locations

* Location A
    + Activity A (including title, image, descrip, etc...)
    + Activity C
* Location B
    + Activity A
    + Activity B

## Page2

### Activities

* Activity A
    + Location A
    + Location B
* Activity B
    + Location B
    + Location Z

On the Location Page's view I used the **views\_field\_view** module to embed a secondary view of Activities inside the first view. The secondary view is set up as a block which has a relationship with a field-based reference to the Location's terms. (So each Location has many activities stored in a term reference field.) The block also has a contextual filter for `Taxonomy Term ID` that uses this relationship to point to the Location's `tid`. On the main view I have the Taxonomy Term ID field setup and excluded from display so we can use it as a token replacement. The views field is set up with the secondary view with a contextual filter for `[!tid]`. This way each Location row passes in its tid to the secondary Activity view which uses it in a reference to the Locations terms.

Hope this helps someone out!

# Answer
> 0 votes
I found a solution for making a nested unordered list of content (or content titles) with a view, basing the list results on hierarchical taxonomy. If that is helpful, you'll find it 3/4 down \[this page\]\[1\].

1. Set up your hierarchical vocabulary
2. Add it to any selected content type
3. Create a view listing nodes from that content type, displayed as an HTML list of the type "unordered list", with one of these contextual filters:

* "Content: Has taxonomy term ID", if you want to list only nodes assigned to specific term
    * "Content: Has taxonomy term ID (with depth)", if you want to list nodes assigned to a specific term as well as to its child terms.

In this case, in filter configuration you need to set the depth, how many levels below (or above) you want this filter to work.

This will give you an unordered list of the entire hierarchy of node content (titles or whatever) in whatever sort order you have established. I have not yet discovered a way to display that listing as a hierarchical unordered list. It seems there must be a way; if I find it I will add it here.

---
Tags: 7, views
---


# Question
Title: How to redirect user to previous page after form submit?
I can redirect user after adding a node to any another page but would like to redirect them to previous page they were linked from. Now I use the following code:

```
function user_add_node_form_foto_node_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'user_add_node_foto_node_form_submit';
}

function user_add_node_foto_node_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/add/foto';
}

```

How can I change a code to redirect users to previous page after submitting the form?

**EDIT**: Every foto node type has a node reference field "field\_relate\_to\_gallery". By using this I created a gallery in Views and added a link "Add foto in gallery" on gallery page linking to add node form. I would like returning users back to gallery after adding a node "foto". That means that a have a lot of galleries with different ID and a cannot redirect the this form only to one particular gallery.

**My Solution** If someone is interested in. I did it by using node reference from url module. Now my user can add an image from gallery page (there is a link to add node form) and after submitting it he returnes to the gallery page.

# Answer
> 7 votes
You want `drupal_get_destination()`. This function creates a 'destination' query parameter suitable for use in `l()` that will redirect the user back to the page they came from after submitting the form. So, when you create your link to add a new node, use the `l()` function along with `drupal_get_destination()`. For example...

```
l('Add new foto', 'path/to/add/a/foto', array('query' => drupal_get_destination()))

```

That should do it.

# Answer
> 1 votes
there are 2 possibility:

1. use $\_SERVER\['HTTP\_REFERER'\]
2. add something to the current page url (like a "from=XYZ") and use it.

Remember that some browser does not set $\_SERVER\['HTTP\_REFERER'\] and if a user browses directly to the page, no referer header will be present. So be sure to have a fallback in place such as not showing the back link, or linking to a default start page or something other.

# Answer
> 0 votes
Try with this code:

```
//Custom submit handler
function _custommade_custom_submit($form, &$form_state) {
   $form_state['rebuild'] = TRUE;
   $form_state['redirect'] = 'whatever';
}

```

Also, you can use a "destination in the link to the form like this: /domain.com/mipath?destination=anotherurl

look at:

http://drupal.org/node/1361246#comment-5325508

also:

http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7#comment-13259

Oskar

# Answer
> 0 votes
I hope this get you idea about how you can achieve it, (**save pervious url in somewhere(variable, session,static variable etc** ) and in submit function redirect to it .

```
 function user_add_node_form_foto_node_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    variable_set('perUrl'.$user->uid,$_SERVER['HTTP_REFERER']);
    $form['actions']['submit']['#submit'][] = 'user_add_node_foto_node_form_submit';

    }
function user_add_node_foto_node_form_submit($form, &$form_state) {
global $user;
$form_state['rebuild'] = TRUE;
$form_state['redirect'] = variable_get('perUrl'.$user->uid);
}

```

---
Tags: 7, nodes, redirection, forms
---


title: Add custom jQuery to form as a module

text:
# Question
Title: Add custom jQuery to form as a module
I'd like to get the following jQuery code to run on any forms on my site:

```
(function($) {
  // Hide any N/A radio buttons
  $('.form-radio[value=_none]').parent().hide();

  // Uncheck a radio button on double-click
  $('.form-radio').dblclick(function(){
    $(this).prop('checked', false);
  });
})(jQuery);

```

I've read that I can probably just add it to my template.php file, but I'd like to put it in a module. How would I do that?

**UPDATE:**

Thanks for the suggestions! So I went with option 3 because it seemed to make the most sense to me for my use-case. I still wasn't getting my jQuery to actually work though. I've updated it to this now:

```
(function($){
  Drupal.behaviors.doubleClickNA = {
    attach: function (context) {
      // Hide the N/A radio button
      $('.form-radio[value=_none]').parent().hide();

      // Enable the double-click unchecker function
      $('.form-radio').dblclick(function(){
        $(this).prop('checked', false);
        $(this).parent().parent().$('.form-radio[value=_none]').prop('checked', true);
      });
    }
  };
})(jQuery);

```

That seems to get the N/A radio button to disappear, but the second function still doesn't work. The $('document').ready part was the key for the first function (duh, right?), but I believe I need to use a behavior to get the double click action to work after the page as finished rendering. What more am I missing here?

# Answer
You have different ways/options to add custom javascript/jQuery file with your module.

**Option 1:** Add myscript.js in module info file (mymodule.info).

```
scripts[] = js/myscript.js

```

**Option 2:** Add myscript.js using `hook_init` and `drupal_add_js`

```
function mymodule_init() {
  drupal_add_js(drupal_get_path('module', 'MODULE_NAME') .'/js/myscript.js', 'file');
}

```

**Option 3:** Add myscript.js to any Drupal form or any callback that contains Drupal form

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = array(
    'data' => drupal_get_path('module', 'MODULE_NAME') . '/js/myscript.js',
    'type' => 'file',
  );
}

```
> 5 votes

# Answer
The simplest way is to add it as a script file (eg. mysite.js) in the module directory and add:

```
scripts[] = mysite.js

```

to the .info file for the module. That way it will be aggregated with the other javascript files and will be an active library on all pages.
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: "Show as expanded" selected but children menu items not displaying
I am using a Bartik theme in drupal 7, and am trying to display a Page created using views under one of the Menu items. I've selected the "Show as expanded" for the parent item, however the child item is not appearing when I hover over the parent. Why would this be the case? How do I fix this?

I've displayed the same Menu in the sidebar, and there, it is displaying the child menu item. Also, I've tried disabling the css, and the drop down menu item is still not appearing...

# Answer
Bartik theme is not designed by default to show parent items in **Primary navigation section** as expanded, even if you checked "Show as expanded" for each parent item in the main menu.

In order for you to make Bartik theme to render parent items and their children items; add the following code to template.php `themes/bartik/template.php`

```
function bartik_links__system_main_menu($variables) {
  $menu_name = variable_get('menu_main_links_source', 'main-menu');
  $menu_tree = menu_tree($menu_name);
  return drupal_render($menu_tree);
}

```

**Note:** make sure to clear Drupal cache once you apply the new changes.
> 2 votes

---
Tags: routes, theming
---


# Question
Title: How can we edit www.example.com/user page?
The user page doesn't look good. I want to edit it, but (If I am right) that is a default page. I am not able to find where to edit it.

How can I edit the user page?

# Answer
> 2 votes
The page at http://example.com/user has two purposes:

* Showing the login form for the users who are not logged in
* Showing the profile page for the users who are logged in

In the first case, there isn't anything that you can edit to change how the login form is rendered. What you can do is implementing `hook_form_user_login_alter()` in the theme you are using, or in a module, to alter how the login form is rendered. In this case, you can use the #prefix and #suffix properties to inject CSS classes to the form fields, and #attached to load a new CSS file containing the CSS styles you need.
The alternative is associating a theme function to render the login form, through #theme.

In the second case, with the exception of the template file used to render the page, there isn't any file you can edit to change how the user profile page appear. Editing the user-profile.tpl.php template file used by the currently used theme is the easier, and faster way to change how the user profile page appears.
The alternatives are:

See also the other given answer; if you just need to change the order in which the fields associated with a user account are rendered, or slightly changing how those fields are rendered, that is the answer for you.

# Answer
> 1 votes
To configure how fields should be displayed when rendering a user profile page, navigate to:

```
Home » Administration » Configuration » People » Account settings

```

and click on the `Manage Display` tab.

This lets you rearrange the order fields are presented on the user profile page, and to hide certain fields, but not very much more.

To make more profound changes, you need to change the templates that determine the look of the user profile page. This is a too broad subject to cover here. Read up on Drupal templates (`.tpl.php` files), and ask specific questions here if you get stuck.

The most important of these is the `user-profile.tpl.php`. However, the Drupal template system is extremly flexible (and somewhat daunting), and allows you to create overrides at all levels, so there are not only a template for the full page, but also templates for the fields that appear in it, etc.

---
Tags: theming, users
---


# Question
Title: How is the file data in the database table file_usage created and managed?
I am deleting orphaned image files in Drupal 7, but I have to first cross reference them to other tables that might be using the images. Given that I don't upload any images via the IMCE editor interface and mainly do uploads via the image module, would it be safe to say i can cross reference the table file\_managed and image\_dimensions to file\_usage and delete what's not there?

Right now I'm just wondering how file\_usage is populated. Is it populated every time I upload any file type?

# Answer
The code used by Drupal to delete temporary files is the following one. (It runs during cron tasks.)

```
  // Remove temporary files that are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
  // Use separate placeholders for the status to avoid a bug in some versions
  // of PHP. See http://drupal.org/node/352956.
  $result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE,
  ));
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {
      $references = file_usage_list($file);
      if (empty($references)) {
        if (!file_delete($file)) {
          watchdog('file system', 'Could not delete temporary file "%path" during garbage collection', array('%path' => $file->uri), WATCHDOG_ERROR);
        }
      }
      else {
        watchdog('file system', 'Did not delete temporary file "%path" during garbage collection, because it is in use by the following modules: %modules.', array('%path' => $file->uri, '%modules' => implode(', ', array_keys($references))), WATCHDOG_INFO);
      }
    }
  }

```

file\_usage\_list() is the function that queries the "file\_usage" table.
The function that adds a row in that table is file\_usage\_add(); looking at the functions/hooks that calls it, I conclude that the "file\_usage" table is used for managed files. Since you are not deleting the files with a row in the "file\_managed" table, I would say you can avoid checking the "file\_usage" table.
> 7 votes

# Answer
The *canonical* way t do it, is to add usage mark when you use a picture, and remove it when you are no longer doing it. It means image with 3 references and one original upload will have 4 usage marks. When something reference it once more, it'll gets bumped to 5. If something unreference, one usage mark goes away. And if you only uploaded file with something like #managed\_file file is NOT marked as used untill form is saved, and even then only if function handling submit decides it should be.

When invoking file\_delete(), only if usage count 0, Drupal will delete a file - both file itself from hdd and all its metadata from tables. No tests on your side are needed, you can simply loop it over all files you want, or call it after each usage delete (that's usual practice).

The idea is - you should never interact with that table directly, only via file\_usage\_add(), file\_usage\_delete() and file\_usage\_list(). And you should never delete actual file or it's database record. Well, unless it's needed immediately due to content security issue or something like that. But otherwise, Drupal takes care.
> 4 votes

---
Tags: 7, media, files
---


# Question
Title: listing all the pages of a custom content type
I would like to know the appropriate way to listing the contents in a single page of type "news". Let me clear it once again, I have a "news" type custom content type.

Now i want to list all the pages of type "news" in a separate(say about us) page and styling them. Prior to this I have created a template file in my custom theme's template directory named as "node-news.tpl.php". Thanks In Advance.

# Answer
> 1 votes
Yes, you can use views module to generate a page to display all node of news content type.

* Install a views module
* Go to administrator -\> structure -\> views
* Add new view
* Add filter content type as "news"
* Add fields to views.

# Answer
> 1 votes
The views module do that. There's many articles about this question. Take a look on existing answers

# Answer
> 0 votes
generate a View using the view module as mentioned by Satyabrata sahoo. generate a page view for your specific purpose that would be more appropriate.

# Answer
> 0 votes
Yes You can do it in your template file . Drupal suggest names for the custom content type template files.

```
 and it is page--node--your_content_type.tpl.php .

```

You can see your nodes of type (your\_content\_type) at here.

---
Tags: theming, nodes
---


title: Change the default password encryption

text:
# Question
Title: Change the default password encryption
The default password encryption in Drupal 6 is MD5. Is it right? I want to change it to something more difficult like crypt and sha1.

Is there any module for this purpose, or do I have to hack the core myself?

# Answer
> 5 votes
Yes, you can look for the Secure Password Hashes module.

> This module stores password hashes securely.
>
> The default password hashes in Drupal 6 (and before) are rather insecure. MD5 is easy to crack, should an attacker find a database dump or gain access to your database. This module implements secure password hashes using the phpass password hashing method - multiple rounds of hashing and salting that make reversing the hash significantly more difficult to break by brute-force attack. This is the same approach that is used for Drupal 7.

---
Tags: 6, users
---


title: Load multiple nodes

text:
# Question
Title: Load multiple nodes
How can I load multiple nodes in Drupal 6?

It seems that `node_load()` only returns one record. I need to fetch all the nodes created by a user.

# Answer
> 4 votes
In Drupal 7, they addressed your use case with node\_load\_multiple(), and support for Drupal 6 is going to end soon, so if you are planning upgrade, consider postponing your work until then.

In Drupal 6, only way I know of is to use db\_query() to join {users} to {node}, or just apply WHERE to {node}, and then loop over it with node\_load().

You can pass an "array of conditions to match against in the database query" to node\_load(), but it will return one node only anyway, so that's not a solution.

You can also define your own `node_load_multiple()`, taking the code from the original `node_load()` and replacing `$node = db_fetch_object` with the following:

```
$nodes = array();
while($node = db_fetch_object) {
  // original processing
  $nodes[$node->nid] = $node;
}

```

Aggregate inside. I'm actually a bit surprised nothing like that is in core, but it's a way too late to propose it now.

# Answer
> 1 votes
You could use the following function.

```
function node_load_by_user_id($uid = NULL) {
  $nodes = array();

  if (is_null($uid)) {
    $uid = $GLOBALS['user']->uid;
  }

  $fields = drupal_schema_fields_sql('node', 'n');
  $fields = array_merge($fields, drupal_schema_fields_sql('node_revisions', 'r'));
  $fields = array_merge($fields, array('u.name', 'u.picture', 'u.data'));
  $fields = array_diff($fields, array('n.vid', 'n.title', 'r.nid'));
  $fields = implode(', ', $fields);
  $fields = str_replace('r.timestamp', 'r.timestamp AS revision_timestamp', $fields);
  $fields = str_replace('r.uid', 'r.uid AS revision_uid', $fields);

  $query = db_query('SELECT ' . $fields . ' FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.vid = n.vid WHERE u.uid = %d', $uid)

  while ($node = db_fetch_object($query)) {
    if ($node->nid) {
      if ($extra = node_invoke($node, 'load')) {
        foreach ($extra as $key => $value) {
          $node->$key = $value;
        }
      }

      if ($extra = node_invoke_nodeapi($node, 'load')) {
        foreach ($extra as $key => $value) {
          $node->$key = $value;
        }
      }

      $nodes[$node->nid] = drupal_clone($node);
    }
  }

  return $nodes;
}

```

I took the code used by `node_load()` and adapted it to return an array of nodes created by the same user.

As the function is loading all the nodes created by the user whose ID is passed as argument, this function would probably exhaust all the PHP memory when the user created enough nodes. I would rather use the following function, which loads only a limited number of nodes at time.

```
function node_load_by_user_id($uid = NULL, $from, $count) {
  $nodes = array();

  if (is_null($uid)) {
    $uid = $GLOBALS['user']->uid;
  }

  $fields = drupal_schema_fields_sql('node', 'n');
  $fields = array_merge($fields, drupal_schema_fields_sql('node_revisions', 'r'));
  $fields = array_merge($fields, array('u.name', 'u.picture', 'u.data'));
  $fields = array_diff($fields, array('n.vid', 'n.title', 'r.nid'));
  $fields = implode(', ', $fields);
  $fields = str_replace('r.timestamp', 'r.timestamp AS revision_timestamp', $fields);
  $fields = str_replace('r.uid', 'r.uid AS revision_uid', $fields);

  $query = db_query_range('SELECT ' . $fields . ' FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.vid = n.vid WHERE u.uid = %d', $uid, $from, $count)

  while ($node = db_fetch_object($query)) {
    if ($node->nid) {
      if ($extra = node_invoke($node, 'load')) {
        foreach ($extra as $key => $value) {
          $node->$key = $value;
        }
      }

      if ($extra = node_invoke_nodeapi($node, 'load')) {
        foreach ($extra as $key => $value) {
          $node->$key = $value;
        }
      }

      $nodes[$node->nid] = drupal_clone($node);
    }
  }

  return $nodes;
}

```

In this case the function should be called changing the second parameter to get the next nodes.

```
$from = 0;
$count = 50;
while ($nodes = node_load_by_user_id($uid, $from, $count)) {
  // Use $nodes.
  $from += $count;
}

```

---
Tags: 6, nodes
---


# Question
Title: HOOK_menu_alter to remove Main Menu items for specific user roles
I'm trying to add a menu link (admin/people/create?operator=1) to the Main Menu only for the user role of 'Supervisor.'

I have tried to do this:

```
function mymodule_menu_alter(&$items) {

 if(in_array('Supervisor', array_values($user->roles)))
   $items['admin/people/create?operator=1']['type'] = {idk what goes here};

}

```

But I'm not sure I am on the right track.

# Answer
I take you added a link to the main menu, and you want to make it appear only when the user has the right permission. In that case, `hook_menu_alter()` is not the right hook to implement because:

* It is not used to override the links added to that menu
* It is not possible to use admin/people/create?operator=1 as path for the menu link in `hook_menu()` or `hook_menu_alter()`

What you should do, after you added the link to the main menu, is to enable a module that contains the following code.

```
function mymodule_menu_link_alter(&$link) {
  if ($link['link_path'] == 'admin/people/create?operator=1' && $link['module'] == 'menu') {
    $link['options']['alter'] = TRUE;
  }
}

function mymodule_translated_menu_link_alter(&$link) {
  if ($link['link_path'] == 'admin/people/create?operator=1' && $link['module'] == 'menu' && user_access('use advanced user creation link')) {
    $link['hidden'] = 1;
  }
}

function mymodule_permission() {
  return array(
    'use advanced user creation link' => array(
      'title' => t('Use advanced user creation link'),
    ),
  );
}

```

The `$link['module'] == 'menu'` part allows to alter the link that you manually added in the main menu, and not other links (i.e. added from a module). In the first function, `$link['options']['alter'] = TRUE` tells Drupal to invoke hook\_translated\_menu\_link\_alter() for that link; in the second function, which is actually an implementation of `hook_translated_menu_link_alter()`, while the first function is the implementation of hook\_menu\_link\_alter(), `$link['hidden'] = 1` actually hides the menu to the currently logged-in user.
Instead of "use advanced user creation link," you can use another permission string; as long as the permission is only given to the roles that need it, and it is unique, you can use any string you want.

I didn't find one, but if there is a module that makes the links added to the main menu visible to users with specific roles, I would use that, instead.

As side note, checking for a permission is preferable to checking for the roles the logged-in user has. The reason is that when you check for permissions, the code is always similar to `if (user_access('permission to check')) {}` whatever roles have that permission, while when you check for roles, the code could change from `if (in_array('supervisor', array_values($user->roles))) {}` to `if (in_array('supervisor', array_values($user->roles)) || in_array('another role', array_values($user->roles))) {}`; in other words, you are hardcoding something that you could change in the future.
> 11 votes

# Answer
There is the Menu Per Role module which allows you to define the roles allowed to see each menu item. You either define for which roles to show it, or for which roles to hide it. For other roles, it stays with the default. Here is a screenshot of the settings screen:
> 0 votes

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


# Question
Title: Is there any module to create different menus per user?
I would like to have different menus per user.

How can I achieve this?
I searched on drupal.org, but I found a module that creates a menu per role, not per user.

# Answer
> 1 votes
Yes. You can try OM Maximenu. It is really flexible and this means you will need some time getting the configurations right but it's really good especially when it comes to controlling menus per role.

# Answer
> 0 votes
You can try preprocess\_page function in template.php and create menus as per user retrieving menus from database.

# Answer
> 0 votes
If it's whole menus, you may trigger them with the context module. Define a condition which relates to the user, and specify an action to display the menu's block on the proper region.

---
Tags: 7, routes, users
---


# Question
Title: Alter menu link lists dynamically in regards to user's role?
I have a navigation menu in a menu block. I want some of the links in the menu to be hidden if user doesn't have role xxx.

What is the best way to do so?

# Answer
The best way to do it would be simply to restrict access to those pages to only the roles you wish to be able to see them. The menu system will automatically not print out links for pages the user cannot access.

How to do this depends on what you're linking to. If it's nodes, perhaps the core per-content-type permissions are enough. If not, there is a variety of node access modules you can use to implement more fine-grained node access, using taxonomy or other methods. If those pages are Views, you can set a View to only be available for certain roles.
> 3 votes

# Answer
If you are running D6, http://drupal.org/project/menu\_per\_role is a great way to go, alas, from its documentation, it's not yet running very well on D7.
> 1 votes

# Answer
Use the Menu Per Role module - even though it's DEV it works great on my Drupal 7 sites. It allows you to define the user roles allowed to see each menu item. You either define for which user roles to show it, or for which roles to hide it. For other roles, it stays with the default. Here is a screenshot of the settings screen:
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How can I override the autocomplete.js file while developing a module?
I want to override the default tags field wherever it is used. After looking through a few files, I figured that I should override drupal/misc/autocomplete.js and the `Drupal.jsAC` object.

Is it correct to override this file, since I only want to work with tags field?
How is it possible to create a module which overrides this file?

# Answer
As long as all you want to do is achievable by using form\_alter() and #autocomplete\_path, you should avoid modifying core's JavaScript files. To address specific field widget, use hook\_field\_widget\_alter().

If you need to alter what JavaScript is doing, use corresponding behaviours, as described on StackOverflow.
> 1 votes

---
Tags: entities, ajax
---


# Question
Title: How to set non Drupal 404 and 403 pages for Drupal?
Under Site Information we can provide custom 404 and 403 pages to Drupal, but these need to be created inside Drupal, and non Drupal pages are rejected. (such as myerror/404.html).

Contrib modules like custom error and static 404 also work inside Drupal. Any ideas on how to set an external page as 404 or 403?

# Answer
If you want to catch errors *not* handled by Drupal, you can do this using `.htaccess`:

```
ErrorDocument 403 /error403.html
ErrorDocument 404 /error404.html
ErrorDocument 500 /error500.html

```

However, if you want to intercept the errors handled by Drupal, and redirect that to an standalone error page, you should be able to do this with Redirect 404.
> 5 votes

# Answer
When sending 404 or 403 header, Drupal cannot use redirect, as redirects are simply 3xx headers and you want 4xx. So, if it cannot redirect, it needs to pass the body of a file itself. But for security reasons it cannot access files outside it's own installation directory.

There are 3 solutions:

1. Use iframe, JavaScript, or other client-side technique to provide content from outside Drupal directory
2. Use webserwer's built in capabilities to substitute Drupal-generated response body with a content of outside file
3. Provide a filesystem links to files you need
> 3 votes

---
Tags: 7
---


# Question
Title: When can I, and when I can't rely on other module's classes to be loaded?
I'm writing pluggable system. For a given *name*, I want to test if there is defined class pluginActionName. If it is, I want to create an instance of it. If it's not, I want to create an instance of pluginAction (parent class for all pluginAction\* classes). That's the easy part, and Drupal unrelated.

Difficult about Drupal is to know when classes are defined. Can I rely on `class_exists`

* in my .inc code outside actual class? *no?*
* in initializers for static properties? *no?*
* in static methods of my class? *sometimes?*
* in dynamic methods of my class? *yes?*
* in helper functions that will be called by methods? *only if it would be OK in method?*

In *italics* is what I figured out so far, but I'm not sure about this and I cannot figure out exact loading order to tell **why** it's the way it is reliably.

# Answer
> 3 votes
> Drupal 7 introduces a code registry - an inventory of all classes and interfaces for all enabled modules and Drupal's core files. The registry stores the path to the file a given class or interface is defined in, and loads the the file when necessary. The registry loads classes and interfaces on demand, via php's built in class autoloading mechanism. Modules can now move all code for classes that are not regularly used into an include file, and Drupal will only load it on demand. This will cut down on the amount of code loaded per request, and reduce Drupal's memory footprint.

more info:

---
Tags: 7
---


# Question
Title: How do I set the options for a programatically created content type?
For example, if I want to set 'Publishing options - Promoted to front page' to 0 in a .install file when creating a new content type.

I've looked in the variable table, where I was expecting to see variables for these options, but it's not obvious to me. What am I supposed to set?

Thanks.

# Answer
> 1 votes
You can set a `node_options_[type]` variable,

e.g:

```
node_options_article: Array
(
    [0] => status
    [1] => promote
)

```

which can be set with:

```
// Make my_type nodes published and not promoted to front page by default
variable_set('node_options_my_type', array('status'));

```

---
Tags: nodes
---


# Question
Title: do some work when user login or register in drupal6
I want to set some fields in database when user registers or login. I know I don't have to change the drupal core and I guess I should use hooks for this purpose but I don't know how and where.

Should I write a new module and implement a hook inside it? What hook?

# Answer
In drupal 6, there is a function named hook\_user.

By using this hook in your custom module. You can do watever you want. Remember to put condition in this by '$op' like

```
function hook_user($op, &$edit, &$account, $category = NULL) {
  if($op == 'login') {
    //do watever you want
  }
}

```
> 5 votes

---
Tags: 6, hooks
---


# Question
Title: How can I get final URL of newly added node from hook_node_insert()?
I have installed `pathauto` and implemented hook\_node\_insert in my module, the problem is when I use `entity_uri` to get new node's URL I will get `node/xxx` instead of pathauto url alias.

How can I get final URL of the node, after ALL other modules had their manipulations?

```
function HOOK_node_insert($node) {
    $uri = entity_uri('node', $node);
    $uri['path']; // this should be the final path
}

```

# Answer
> 5 votes
If you also implement hook\_module\_implements\_alter then you can change when your insert hook fires, like this:

```
function mymodule_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'node_insert') {
    // Move my_module_node_insert() to the end of the list.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

```

So now when your insert code executes the path alias should be available.

# Answer
> 1 votes
The reason is that pathauto module is triggering hook after your module hook interaction. To resolve this you have to give a higher **weight** to your module.

To increase weight, Refer this link: How to update a module's weight

OR

hook\_module\_implements\_alter

> This hook is invoked during module\_implements(). A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

And also you have to use drupal\_get\_path\_alias function in node insert, Following is a working code when the module weight is set higher value.

```
function MODULENAME_node_insert($node) {
    $system_path = 'node/'.$node->nid;
    $current_path = drupal_get_path_alias($system_path);
    drupal_set_message($current_path);
}

```

# Answer
> 0 votes
There is a function in drupal which gives you the path\_alias

For e.g.:

```
$path = node/$nid;
$url = drupal_get_path_alias($path);
print $url;

```

By this you will get desired drupal set path.

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


title: Features Hook after successfull import

text:
# Question
Title: Features Hook after successfull import
I wrote a feature module that contains content types and test nodes. After importing those nodes, a certain cache has to be rebuild.

Both hooks I know (`hook_install()` and `hook_enable()`) are called before the import happens.
Is there any hook that is executed only once after the feature import is done?

# Answer
It depends on how the nodes are imported really. You should be able to use `hook_modules_enabled` which is the last hook invoked when a module is installed and enabled. You might need to tweak your module weight to make sure it's invoked after the import of the nodes.
> 3 votes

# Answer
As of Features 7.x-2.x-*something*, there are new hooks available which should help here. There are now pre/post enable/disable/revert/rebuild hooks, see for example here.

In @jantimon’s scenario, implementing `hook_post_features_enable_feature($component)` would do the trick.
> 1 votes

---
Tags: 7, features
---


# Question
Title: Add class to ul element in views 3 unformatted list using templates or module code?
I'm contributing to the Radix theme in D7 for panopoly, which uses Twitter Bootstrap.

I'm seeking out ways to implement as many of twitter bootstrap's awesome capabilities as possible, and thus not have to rely on overriding theme css, and to make it work 'natively' and rely on cleaner CSS.

So, the 'unstlyed' list property in Twitter Bootstrap is a perfect example of this.

```
<ul class="unstyled">
  <li>...</li>
</ul>

```

However, I can't figure out how I would add this class to the views unformatted style by default using the theme. Is this possible with template files, template.php code or an include file? I would prefer to do this within the radix theme. Help!

# Answer
You could use the **rewrite option** in views to get the exact html output you need. Rewrite enables you to override the output of this field with custom text or replacement tokens. I use the last field, since the replacement tokens should be above the field you are rewriting. Make sure to go through set the field, label, wrapper html to **None**

## In Views

1. Click on a **Field**
2. Click on **Rewrite the output of this field**
3. Add your code with the desired html output

### Code

```
<ul class="unstyled">
  <li>[field_degree]</li>
  <li>[field_major] </li>
</ul>

```

## Output

```
<span class="field-item">
 <ul class="unstyled">
   <li>Certificate</li>
   <li>Supervision </li>
 </ul>
</span>

```

OR you can

1. Click **Advanced**
2. Click **CSS class**
3. Add the name of your class "unstyled" to the entire view.
> 2 votes

---
Tags: views, theming
---


# Question
Title: Add VBO checkbox to send Bulk emails in Admin
We are using Enterprise Event module in Drupal 7. I checked the Views and module files but not able to locate the file as from where Manage Registration Page is formed. Please guide me how I can add VBO checkbox to send Bulk emails in Admin \> Content \> Event \> Edit \> Manage Registration Tab.

I am using enterprise event module in which people register for upcoming events. Registration module is used for registration. Admin can view registrants for specific event. I need to add a checkbox so that admin can send bulk emails to those registrants.

Please help still hoping for some solution.

# Answer
> 2 votes
This is how you do it:

* Go to *Structure* \> *Views* and locate the *Test Event* view.
* Click the *Edit* button.
* Find the *Fields* display and click the *Add* button.

* Filter the available fields by *Bulk Operations* and select a field you need, e.g. *Bulk Operations: User*.

* Now the settings for this field show up. Scroll down to *Selected Bulk Operations* and select *Send Email*.

* Click Apply.
* Don't forget to save your view.
* Now you should have a checkbox and you can select *Send Email* from a drop down menu.

I'd personaly would not use the VBO field but the Views Send module which is a bit easier to use. If you have the *Views Send* module, add the field *Global: Send Email* instead of the VBO field and proceed as described above.

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


# Question
Title: How do I delete a Panopoly landing page?
I was able to disable the page by going to `admin/structure/pages` then clicking **Disable**. However, I am not sure how to **delete** the landing page.

**Note**: I am running Panopoly on Pantheon.

# Answer
Thank you @Patrick Kenny for the information. I prefer not to "hack" as it does cause difficulty updating.

## My Solution

On `admin/structure/pages/edit/mypagename`I clicked the **Delete** tab that appeared after disabling it.
> 2 votes

# Answer
If the page is provided by a module, it is saved as part of the module's code. You cannot delete the page from the UI, only disable it. If you really wanted to delete it, you could hack the module's code and delete the lines that provide the landing page, but this is likely to cause problems down the line when you try to update Panoply.

I would just disable the page and leave it at that. End users will never see it if it is disabled.
> 0 votes

---
Tags: 7
---


# Question
Title: Show referenced nodes as links if they have content in a field
Nodes of content type A are attached to nodes of content type B with an entity reference. Im listing Nodes of type A on Node B with a view.

Now I need the list of Node As to be links if their node's body has content. If their node's body doesnt have content then I need it to not be a link.

# Answer
This can be done in Views with no PHP or templating.

Add 2 title fields, one that is a link to the content and one that isnt.

Exclude both fields from display.

Add a body field and rewrite the output of the field. Use a replacement pattern thats the node title which is a link.

Under no results behavior add the token thats the node title which isnt a link. Make sure 'Hide rewriting if empty' is not checked.
> 1 votes

---
Tags: theming
---


title: Views UI broken after site migration

text:
# Question
Title: Views UI broken after site migration
Ive migrated my site and now my View UI is broken. My relationship 'Relationship: Entity Reference: Referencing entity' works the opposite way round to the way it should. This has been confirmed by a colleague who uses Drupal.

Also fields that ive added to my content type are not available as fields in views, and sometimes the body field is missing too.

Does anyone have any ideas as to how I would start to go about fixing this? My Drupal status report doesn't return any errors.

# Answer
Disabling a custom module has fixed this.
> 0 votes

---
Tags: views
---


# Question
Title: Display Taxonomy Field vs Default Taxonomy text w/out New modules
I have a node with taxonomy term reference fields. The taxonomy term has an image field. Without installing extra modules (I already have WAY more than I should have) is there a way to display a specific field for the taxonomy instead of the textual? And do it from a Childtheme?

I have the DEVEL module installed and after selecting the specific field I still get no ideas. I have dug around inside the field, looking through the various attributes of that field without any ideas.

```
Array > 'element' > '#field_name'
Array > 'element' > '#field_type' = 'taxonomy_term_reference'
Array > 'element' > '#items' > 'tid' = 4
Array > 'element' > '#items' > 'taxonomy_term' > Object = Recursion

```

It feels like I am 'right there' and should be able to grab something like \['element'\]\[0\]\['field\_taxonomy\_term\_image'\] and render, but I can't find anything. I realize, after searching stackexchange, and google, that I could install Views and tweak around with it to get the desired output, but I know I've seen somewhere that you can (without coding) get the output of a taxonomy term to be another field than 'title' but I don't remember where I saw it.

**UPDATE:** I have found the path, but can't figure out how to output it. I did a DPR versus a KPR and just dug through the text. Here is what I see. Inside of template.php inside of a drupal-based custom function THEMENAME\_field\__content\_type($variables) I dpr'd $variables\['element'\] and found this object/array/path.

```
[#object] => stdClass Object
    [field_faction_affiliation] => Array
        [und] => Array
            [0] => Array
                [taxonomy_term] => stdClass Object
                    [field_faction_icon'] => Array
                        ...
                        [uri] => public://Faction - Jinteki.pnp
                        [filemime] => image/png
                        ...

```

So I feel like... I could theoretically, create a new $variables\['faction\_icon'\] to pass on to my tpl.php using the pieces above to generate an img tag. Any ideas?

**UPDATE:** After a bit more digging around I got this to dpr and output what I expected.

```
$variables['element']['#object']->field_faction_affiliation['und'][0]['taxonomy_term']->field_faction_icon['und'][0]

```

So... now the tough part is figuring out how to generate an image path from a URI... of which, I am fairly clueless, but I will start searching.

**UPDATE:** After tweaking the function listed above I get this to work.

```
$faction_icon_url = file_create_url($variables['element']['#object']->field_faction_affiliation['und'][0]['taxonomy_term']->field_faction_icon['und'][0]['uri']);
$output = "<img class='faction_thumb' src='". $faction_icon_url . "' />";
return $output;

```

Now I have to figure out how to make this image link back to the taxonomy\_term like the original output of text did.

# Answer
Ok... so following all of the steps above, I was able to cobble together what I wanted.

In template.php I have a custom function:

```
THEMENAME_field__CONTENT_TYPE($variables)

```

Inside this function, I check for $variables\['element'\]\['#field\_name'\] in a switch statement. IF the switch statement equals the field that has the taxonomy reference (i.e., 'field\_faction\_affiliation') then I do the following:

```
case 'field_faction_affiliation':
    $base_path = base_path();
    $faction_icon_href = $base_path . $variables['element'][0]['#href'];
    $faction_icon_title = $variables['element'][0]['#title'];
    $faction_icon_url = file_create_url($variables['element']['#object']->field_faction_affiliation['und'][0]['taxonomy_term']->field_faction_icon['und'][0]['uri']);
    $output = "<a href='$faction_icon_href'><img alt='$faction_icon_title' class='faction_thumb' src='$faction_icon_url' /></a>";
    return $output;
    break;

```

I'm almost 100% certain that the base\_path hobble I did is NOT drupal 'Best Practices' so if anyone has a suggestion for correcting that, please let me know. Otherwise. This is how I got what I wanted.
> 0 votes

---
Tags: theming
---


title: Display child terms of taxonomy term

text:
# Question
Title: Display child terms of taxonomy term
When displaying a taxonomy term, how can I also display the teasers of all the child terms of the current term? I still want to display all the content and fields of the current node, but also display the child teasers.

# Answer
> 1 votes
The taxonomy display won't do this on its own. You could create a view to do this, then display the view below the term page.

If you call the view from a taxonomy term template you could use a "Contextual filter" to pass the term id (tid).

---
Tags: taxonomy-terms
---


# Question
Title: Recurring events - retrieving/displaying the dates for the current "instance" of the event
I have an events page on my (D7) site, and the admin can set up recurring events.

When creating a list of the events, I see the recurring events come through in the right place intermingled with the non-recurring events. However, their dates don't show up right:

My "normal" date fields only ever show the date of the first event. There's an answer to this issue here, but that requires table layout. I'd prefer not to have to use table layout. Any idea how I could do this without it?

Secondly, I'm using a pre-process field (called `big_date`) to create a second date field but with a different display to the first, so I can display the same date in different formats simultaneously. How could my code here know which of the many dates in `$vars['node']->field_date_and_time[LANGUAGE_NONE]` is the one relating to the "current" instance of the event?

# Answer
I spoke briefly about this to a Drupal expert I know, and he suggested moving to using Views and the Fields view type as apparently the integration between the Date module and Views is very good.

At present, I'm using a View but also using Viewmodes and the preprocess field. His point was that all of this could instead be accomplished by just using my existing content type, not using a custom viewmode but using the Fields view type. And that this should be less buggy.
> 1 votes

---
Tags: datetime
---


# Question
Title: Theming a custom user field on register form
I have added a checkbox list field on the register form and I want to change the template for that field.

I have used `field--field-checkbox-list.tpl.php` and `MYTHEME_field__field_checkbox-list()` function, but with no luck on `user_register_form`.

# Answer
> 0 votes
Two possibilities. You could alter the form element with hook\_field\_widget\_form\_alter, or you could override theme\_checkbox.

More info: http://drupal.org/node/173880

---
Tags: 7, users, theming
---


# Question
Title: Help with Canada Post Shipping Quotes with Ubercart
Is there someone that can help me with Canada Post Shipping Quotes with Ubercart? I can't find any documentation on how to set it up. I've gotten my Canada Post account and I've put all the information into the module, but it's not showing any quotes. I also have UPS and it's displaying quotes just fine. I'm not seeing any errors or anything so I'm wondering if I've missed a set up somewhere? I tried going into the Canada Online setup but quite frankly I don't understand what I'm supposed to do. Do I have to set up every possible package size for it to work? How would that reference back to the product? We sell so many different products that could be a nightmare!!! If anyone can at least point me in the right direction I would be so grateful!! Thanks!

# Answer
> 0 votes
Make sure you have the store address information all filled out properly in the Ubercart Store Configuration and in the Shipping module. It seems like a duplication but it helped me.

---
Tags: ubercart
---


title: How to create tagadelic page in view?

text:
# Question
Title: How to create tagadelic page in view?
How can I create a **Tagadelic page** in a view? I create a tagadelic page in a view, but all tags display as a column. See the below screenshot

But I want to display them in the following style:

Would you please tell me, how to change this style? Many thanks

# Answer
> 0 votes
You can edit the field and then click on REWRITE RESULTS and check off the box strip HTML which will strip out all the html that is creating a line break between each tag. If you need more control you can use "Rewrite the output of this field" and wrap your field in its own element.

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


# Question
Title: How to assign IDs to each radio button in drupal form radios?
I am using drupal form radios, I can use Prefix and Suffix to assign IDs to group, how can I assign different IDs to each radio button inside the radios element? Thanks

# Answer
> 1 votes
You need to use theme\_radios() hook in your template.php file, if what you get is insufficient.

> **Parameters**
>
> $variables: An associative array containing:
>
> * element: An associative array containing the properties of the element. Properties used: #title, #value, #options, #description, #required, #attributes, #children.
>
> **Return value**
>
> A themed HTML string representing the radio button set.

To interfere with single radio element, see theme\_radio(), of course.

# Answer
> 0 votes
You can use jQuery for giving extra IDs for your radio buttons.

# Answer
> 0 votes
The Display Suite module might be what you're looking for:

http://drupal.org/project/ds

Display Suite lets you create your own id's and classes, and then assign them to your form fields, either keeping Drupal's default and adding your new ones, or it can completely replace the existing id's and classes with your new ones. Here's a screen shot of a radio button field I have on a form I recently created: http://www.territorialnetworks.com/design-suite.png

Design Suite also lets you control the layout of your form with different column configurations and orientations.

---
Tags: theming, forms
---


# Question
Title: limit db_select query by the value of a specific field
I am trying to build a custom drupal module to return the 'staff' that work at a specific charity when you are on the page of the charity. Both the charities and the staff members exist as separate content types. These content types are updated dynamically from a CRM system. The charities and the staff members both have a common field 'Account ID'.

I can get the account id of the charity whose page we are viewing:

```
    //Get Account ID of Charity for page we are on
    $charity_account_id = $node->field_member_account_id[LANGUAGE_NONE][0]['value'];

```

I can query the database and return only the contacts of the staff members type ('salesforce\_contacts') and optionally limit it by the title of the returned results (e.g: n.title','Abouzeid')

```
    //Use Database API to retrieve the appropriate contact(s)
      $query = db_select('node', 'n')
        ->fields('n', array('nid', 'title', 'created'))
        ->condition('status', 1) //Published.
        ->condition('type', 'salesforce_contacts') // content type is salesforce_contacts.
        ->condition('n.title','Abouzeid','=') // I can limit the returned results by a specific title
        ->orderBy('title', 'ASC') //Most recent first.
        ->execute();
      return $query;

```

I need to know how to limit the returned results by the value of a specific cck field from the staff member content type ('salesforce\_contacts'). This will allow me just to return the contacts for the charity we are looking at.

I have tried adding the drupal machine name for the field (or the mySQL database table name) to the field array as in below but both of these throw a PDOException error.

```
      ->fields('n', array('nid', 'title', 'created', 'field_account_id'))

```

I would really appreciate some help with this. This is my first Drupal database query and I am pretty new to DB queries in general. I have tried reading through the documentation but am struggling to where to look to get ideas as to how to go about achieving what I need to.

Thanks.

# Answer
Scott's answer and Triskelion's comment are both spot on, but there are also a couple of other solutions that are worth mentioning.

1. Query the database for some node IDs that match a condition, load them using `node_load_multiple()`, and inspect the field data:

```
$nids = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('status', 1)
  ->condition('type', 'salesforce_contacts')
  ->condition('n.title', 'Abouzeid')
  ->orderBy('title', 'ASC')
  ->execute();

$nodes = node_load_multiple($nids);

foreach ($nodes as $node) {
  $title = $node->title;
  $created = $node->created;
  // etc.

  if ($field_items = field_get_items('node', $node, 'field_account_id')) {
    $account_id = $field_items[0]['value'];
  }
}

```
2. Use an `EntityFieldQuery` to query the nodes. This method has the advantage of being able to add conditions based on fields, as well as just the columns available in the node table.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'salesforce_contacts')
  ->propertyCondition('status', 1)
  ->propertyCondition('title', 'Abouzeid')
  ->propertyOrderBy('title')

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  // Loop through the nodes as in the above example.
}

```
> 2 votes

# Answer
First you need to join the table with the data you need. This will add the account id information to the nodes you select.

I'd do a left join like:

```
$query->leftJoin('TABLE', 'TABLESHORTNAME', 'TABLESHORTNAME.FIELDNAME = node.FIELDNAME');

```

The 3rd argument sets the relationship for the join. In this case the entity id must be the same value in both tables.

Now you can use the account id in your fields output or your conditions.

I find it helpful to browse the database and find all the tables and fields you'll need first.

You may need to add a condition to limit the type of nodes you return since many types of nodes can have the same field.
> 1 votes

---
Tags: database
---


# Question
Title: How to check for Grouping field in Views submodule?
I'm developing on the Views Datasource module to enable grouping by field (not field aggregation). I've now got the output format that I want, but I don't know what variable the Grouping Field setting is stored in. I want to check if a grouping field is selected, and then assign the field's name as an array key if it is.

## views-views-json-style-simple.tpl.php:

```
// TODO Enclose everything in an if statement, conditional
//   on a grouping field being selected

$grouped = array();

foreach ($rows["nodes"] as $nodenum => $nodearray) {
  // TODO Replace "building" with variable representing user-
  //   selected field.
  // Variable names will obviously change too.
  $building = $nodearray["node"]["building"];
  foreach ($nodearray["node"] as $cprop => $cvalue) {
    // TODO Replace "building" with grouping field variable
    if ($cprop != "building") { // Ignore grouped field
      $grouped[$building][$cprop][$nodenum] = $cvalue;
    }
  }
}

$rows = $grouped; // Pass back to existing code

```

The above code takes the $rows output by views, and reformats the array right before it goes to `_views_json_json_encode`. The idea is to take the default output of Views Datasource:

```
{
  "nodes" : [
    {
      "node" : {
        "name" : "Energy Services Performance Contract (ESCO)",
        "geometry" : "48.7366, -122.486",
        "description" : "This project was initiated In order to advance Western’s sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus.",
        "building" : "BH"
      }
    },
    {
      "node" : {
        "name" : "Energy Services Performance Contract (ESCO)",
        "geometry" : "48.7378, -122.486",
        "description" : "This project was initiated In order to advance Western’s sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus.",
        "building" : "WL"
      }
    },
    {
      "node" : {
        "name" : "Wilson Becoming Skyscraper",
        "geometry" : "48.7378, -122.486",
        "description" : "Wilson will have 708 floors added to it, becoming the tallest building ever.",
        "building" : "WL"
      }
    }
  ]
}

```

and turn it into

```
{
  "BH" : {
    "name" : [
      "Energy Services Performance Contract (ESCO)"
    ],
    "geometry" : [
      "48.7366, -122.486"
    ],
    "description" : [
      "This project was initiated In order to advance Western’s sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus."
    ]
  },
  "WL" : {
    "name" : {
      "1" : "Energy Services Performance Contract (ESCO)",
      "2" : "Wilson Becoming Skyscraper"
    },
    "geometry" : {
      "1" : "48.7378, -122.486",
      "2" : "48.7378, -122.486"
    },
    "description" : {
      "1" : "This project was initiated In order to advance Western’s sustainability goals and reduce our carbon footprint. The project will implement 38 separate facility improvement measures in various academic and auxiliary buildings identified by an energy audit of Western's campus.",
      "2" : "Wilson will have 708 floors added to it, becoming the tallest building ever.\n"
    }
  }
}

```

# Answer
My question assumed that Views Datasource includes parent view format options such as grouping fields, but it does not. Rather than call all of the parent fields from the Views defaults, I copied only the field definition from `views_plugin_style.inc` to `views_plugin_style_json.inc`, within the `options_form` function.

The second part of my question was how to get the value of that field back out. It exists in `$options["grouping"][$i]["field"]`, where `$i` is the Grouping Field Number, -1.

So, the value entered into "Grouping Field Nr.1" is `$options["grouping"][0]["field"]`.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Sending email to hidden field using webform after calling hook_form_alter?
Drupal 7.14, Webform 7.x-3.17 : I built a webform that has a hidden field "lt\_email", and I'm assigning a session value to it using hook\_form\_alter -

```
function wbl_form_webform_client_form_1_alter(&$form, &$form_state) {
   $form['submitted']['lt_email']['#default_value'] = $_SESSION['Some']['Email'];
}

```

When I var\_dump or dpm the ($form) I see the session value for lt\_email, but after I hit submit on the webform, the value goes away, it doesn't get assigned.

Since %session\[id\] didn't handle multi-dimensional session arrays, I used the hook\_form\_alter workaround. I was under impression hook\_form\_alter would grab the session value, assign it to hidden field, and once submitted, the hidden field would retain the value, which I then use as the email component for the webform that gets triggered automatically. THe hidden field is blank upon submit.

I'm logged in as root, and all the other fields retain value upon submit (ie, name, address).

# Answer
The problem is probably caused by the hidden field having the `#value` property set which overrides `#default_value` (even if the former is `NULL` or a empty string).

To get the desired result you have 2 options:

1) Override `#value` instead of adding a `#default_value`:

```
$form['submitted']['lt_email']['#value'] = $_SESSION['Some']['Email'];

```

2) Unset `#value` then add `#default_value`:

```
unset($form['submitted']['lt_email']['#value']);
$form['submitted']['lt_email']['#default_value'] = $_SESSION['Some']['Email'];

```

If you are wondering which option is the right one for you then `#default_value` means that Drupal will accept client-side changes to the field value (via javascript for example). If you don't need/want that possibility then `#value` should be used (Drupal will ignore any client-side changes in that case). It's mentioned in the documentation as well.
> 2 votes

---
Tags: webforms
---


# Question
Title: Keep URL the same after changing page title
I create alias for every pages on my site. For example, if a page is called "My Page", then the alias will be "/my-page".

Is there a way to keep that URL the same even if I rename the page "My Page 1" ?

For the moment, it automatically changes the alias to "/my-page-1"

Thanks!

# Answer
> 3 votes
You can set the default at */admin/config/search/path/settings*. Under 'Update Action' choose 'Do nothing. Leave the old alias intact.'

---
Tags: path-aliases
---


# Question
Title: User Content with image gallery and text
i am building a little "show and tell" page, for showing pictures of a room, basically as practice to get into Drupal but the page will be used later.

What i have managed (as it was pretty easy): 1) Generate an custom content type for the room 2) Add fields for the room for the information

But now i got stuck: The users should have the ability to upload multiple pictures within the form (i think pluploads will handle this). The room should then have a gallery for the pictures. How do i add the upload form to the content type and how do i manage to get a gallery in the content type, that shows only the pictures a user added to this *post*

I tried the media gallery module, but it seems to only have static album pages and can not be embedded in a content type.

# Answer
You can configure the number of images the user can upload while creating a node in the field settings (manage fields page of your content type)

Once the images are uploaded you can display them in a slider/carrousel style using modules such as :

Or you can just display clickable thumbnails (and a bigger version in a lightbox.)

You can set the image dimensions in : /admin/config/media/image-styles

You need to tell me more about the way you want your images to be displayed. What version of drupal are you using ?
> 1 votes

---
Tags: users, nodes, media
---


# Question
Title: A field that is a multiple of a float field. How?
Let's say i have a product content type. It has a title, body and price field.

In a view (or in the node page) in addition to these fields I would like to have a multiple of the price field ?

Example :

* Title : Red tshirt
* Body : Tshirt description
* Price : $9,95
* Extra field : $99,5 *( Price x 10 )*

# Answer
> 1 votes
The easiest way would be to use the Computed Field module. Use something like:

```
if ( isset($entity->field_price)){
  $entity_field[0]['value'] = ($entity->field_price[0]['value'] * 10);
}

```

in the Computed Code (PHP) box.

---
Tags: 7
---


# Question
Title: access field data in template.php and create variable for header image in page.tpl.php
I am trying to allow the user to set a custom image to display in the header on node pages that have a header\_image field and to display a default header image on all other pages (including system and module generated pages).

I thought I could do this by creating a "Header Image" view and using a contextual filter to get the header\_image field on the displayed node. This works okay when displaying a node that has the header\_image field but not on a page that doesn't have that field. Because this view is a block the contextual filter uses the default value of "Content ID from URL" and I can't use a fixed default value.

I am guessing I have to use the preprocess\_page function and field\_has\_data or perhaps the Entity API Module to check if the node has data in the header\_image field. If there is no header\_image field or it has no value I would like to use the default image for that field. Is there anyway to specify using the default image that was set by the user? other wise I would use the default image at `file_stream_wrapper_get_instance_by_uri('public://')->getDirectoryPath().'/default_images/default_header.jpg'`

There must be a common solution to this problem.. Actually I just had a thought.. what if there are multiple nodes on a page? Any suggestions what I should do to accomplish this?

# Answer
> 0 votes
I recently tried to do this but stumbled then over the Header Image Module which does this perfectly. It allows you to create a block which holds any content (for example a custom content type) and ads it to a block. You can specify on each content where it should be displayed (nid, path, term etc.).

---
Tags: media, theming, entities
---


# Question
Title: What advantages / disadvantages is there adding a 'www' prefix to your domain name?
currently i am replicating my site and my .htaccess file has www redirection prefix enabled, but if im copying this to my local, it will prefix my site with www.localhost. I was wondering would it be ideal to just turn this www rewriting prefix off on both sites so i don't have to edit the .htaccess file everytime i do a clone to my local?

what are some issues i might have when turning it off or on? i think from a seo perspective i should have it on, but can someone clarify this?

# Answer
> 0 votes
There are no advantages. The www prefix is actually a subdomain.

Google considers example.com and www.example.com to be separate sites. From an SEO perspective, choose one and run with it. In your Google Webmaster Tools account you can list both, and configure Google treat them as the same.

Other search engines do not have the tools.

I have my servers configured to respond without the prefix, to rewrite the URL's if the prefix is requested, and to issue a permanent redirect.

If you try to honor both forms, then you give the appearance of duplicate content, and that would have a negative effect on SEO.

---
Tags: 7, .htaccess
---