# Question
Title: Check effect of hook_schema_alter() hook
I want to alter the comment subject field title width.

Core comment module sets it to 64 characters, and I want to change it up to 100 characters.

Now I tried to alter the schema using hook\_schema\_alter() function. Below is my code snippet, which I tried,

```
/**
 * Implements hook_schema_alter().
 */
function comment_alter_schema_alter(&$schema) {
    if (isset($schema['comment'])) {
        $schema['comment']['fields']['subject'] = array(
        'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The comment title.',
        );
    }
}

```

I am confused whether do I have to write some stuff in `.install` file or not?

Now after installing module how can i check whether the width of subject field is increased or not. If I see the `comment` table then it is as it is to 64 characters. I could find this in your table structure using PHPMyAdmin.

# Answer
> 2 votes
This hook is not used to edit the database as such. It is used to alter the schema when using the drupal\_get\_schema

> Gets the schema definition of a table, or the whole database schema.
>
> The returned schema will include any modifications made by any module that implements hook\_schema\_alter().

To do what you want you will have to use the db\_change\_field and this would go in the .install file.

You can check out the Schema API to get other relavent functions

You have to write db\_change\_field() in hook\_enable() function.

Here is my modified answer:

```
/**
 * Implements hook_enable().
 */
function comment_alter_enable() {
    db_change_field('comment', 'subject', 'subject', array(
        'type' => 'varchar',
        'length' => 100,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The comment title.',
        )
    );
}

```

---
Tags: 7, hooks
---


# Question
Title: Run a check on every page load programmatically
Drupal 7.

I have a site with Single Sign On (SSO) implemented. The implementation of the features is complete and the site is running perfectly.

Now, I have a requirement where I am supposed to check whether the session of the central server (on root of the domain and not using Drupal) is alive. I can do this by checking the availability of the session cookie on the root domain. And if the session is not active the user is logged out of Drupal.

I tried implementing it inside hook\_init() but it only works for non-cached pages, whereas I want my code to be triggered on every page.

I also had a look at hook\_boot() which runs even on cached pages. But, it is called while Drupal is still in bootstrap mode; even before themes and modules are loaded into memory. Which would mean that I would not be able to check the status of the user (whether the user is logged in?), because the `user` module and the included file `session.inc` would not be present in the memory while the execution of this hook.

So my question is which function (or hook) should I use which would execute on all pages(cached and non-cached) and which would give me access to common `user` properties (e.g. `global $user` object, `user_is_logged_in()` function etc)?

# Answer
(I'm assuming Drupal 6)

Looking at bootstrap.inc, `hook_boot` is called on all pages, as long as agressive caching hasn't been turned on.

At this point the global $user variable should already exist (`page_get_cache`, which is called before hook\_boot, makes use of it for example). module.inc has also been included, so you can use the functions included in that file to check for module existance and load them if necessary.

So, `hook_boot` looks like a good choice.
> 0 votes

---
Tags: users, hooks
---


title: Display term refference field in node

text:
# Question
Title: Display term refference field in node
I have term refference in user fields. I would like to show under name of author's node that field.

I try this code:

```
<?php print $node_author->field_NAME[$node->language][0]['taxonomy_term']; ?>

```

But this won't work.

Anyone can help me?

Thank you!

# Answer
I think you have a term reference field in user profile and you want to display it into the node view.

By default, the profile fields are not included in the user information of the node object. You only have `$node->uid`. You would need to load it explicitly in hook\_node\_view(). There are two ways to make that data available to the template.

**1. Directly render to the template**

You can add the field data into the `$node->content[]` which are automatically rendered in the node.tpl.php. You can adjust the field order using `#weight`.

```
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        // Load all user fields of the node author
        $node_author = user_load($node->uid);
        // Get term name
        $term_name = db_select('taxonomy_term_data', 'td')
                        ->fields('td', array('name'))
                        ->condition('td.tid', $node_author->field_taxonomy_term[$node->language][0]['tid'])
                        ->execute()
                        ->fetchField();
        // directly render to the template
        $node->content['field_taxonomy_term'] = array(
            '#markup' => '<div>'.$term_name.'</div>',
            '#weight' => -1,
        );
    }
}

```

**2. Make the field available to the template and print it as you need**

You can make the field available to the THEME\_preprocess\_node() and `node.tpl.php` by adding the field to the `$node` object which is available in `hook_node_view()`. And then print it in the template file.

```
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        // Load all user fields of the node author
        $node_author = user_load($node->uid);
        // Get term name
        $term_name = db_select('taxonomy_term_data', 'td')
                        ->fields('td', array('name'))
                        ->condition('td.tid', $node_author->field_taxonomy_term[$node->language][0]['tid'])
                        ->execute()
                        ->fetchField();

        // make it availabe to the template
        $node->field_taxonomy_term = $term_name;
    }
}

```

Print it where you want in the template file, `node.tpl.php` in this case.

```
<?php print render($field_taxonomy_term); ?>

```

The field name `field_taxonomy_term` is your field name defined in your user fields.
> 0 votes

# Answer
You can adjust some of the settings of a field on the 'manage fields' tab of the content type configuration.

To position or further manipulate the output of a particular field in the template, edit node.tpl.php and where you want your field to appear, add

```
if(!empty($content['field_term'])) {
  print render($content['field_term']);
}

```

(Or if your field isn't called 'field\_term', whatever your field's name is.)
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to place an image on a specific page
I have created a page, `page-5`. I want to insert an image only on this page through .tpl.php not through the CMS itself. I have created an empty document `page--page-5.tpl.php`.
What content would go in there and how would I place my image?

For the front page, I was able to do with the following code:

```
<?php if (drupal_is_front_page()) {?>
  <a class="join-btn" href="/node/38">
  <img src="/sites/all/themes/ypwb/images/joinb.png"></a>
<?php }?>

```

How to do for a specific page?

# Answer
> 0 votes
You can check template suggestions in the documentation.

> The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:
>
> 1. page--node--edit.tpl.php
> 2. page--node--1.tpl.php
> 3. page--node.tpl.php
> 4. page.tpl.php

The template name started with "page--" is an override of page.tpl.php for a particular node or whatever.

* Find out what is the node ID of your "page-5", let's say it is node ID 1.
* Copy **page.tpl.php** and rename to **page--node--1.tpl.php**
* Then you can update it as you need ( print your image like you did in the front page ).

---
Tags: media, theming, 7
---


# Question
Title: Display only the terms in the filter set using Views
I have got a view where I am displaying a view in a block. Basically, I want to display a list of nodes that have a few specific terms associated with it. So, for example, I want to show all nodes that have one of the following terms (red, blue, green, white). So, my block should display two fields with the following criteria:

Fields Content: Title (Title) Content: Tags (Tags)

Filter criteria Content: Published (Yes) Content: Has taxonomy term (or Black, Blue, ...)

Sort criteria Content revision: Updated date (desc)

My problem is, the result is looking fine, where it is displaying a list of all the nodes that fit the filters. However, I would only like to display the term in the result set and not all the terms that the node is associated with. So, right now, this is the what the block looks like:

---

## |Title | Tags

|Node 3 | red, horses, yellow, dogs
|Node 5 | black, white, green, cats, rain, purple

## |Node 6 | camel, case, blue

I would like the block to look like this:

---

## |Title | Tags

|Node 3 | red
|Node 5 | white, green

## |Node 6 | blue

So, in essence, display only those terms that are part of the result set. How can I accomplish this with Views? Any help would be greatly appreciated.

I have played around with the configurations in Views, like @Mohammed Shammem said, and I have gotten it to display only the colors I want. It is however, still displaying in separate lines despite selecting Group by Title under the Format settings option. So, now it looks like this:

```
Tags    Title
White   Node 1
Blue    Node 1
Black   Node 1
Red     Node 1
Green   Node 1

```

I am close enough, but would appreciate more help on getting the tags in one row.

The relevant screen shots:

# Answer
> 0 votes
I would suggest doing the following.

Instead of displaying all the tags in one line display it in different lines. That is in the multiple filed settings you would choose it to display it on different rows. The result would be something like this

node 3 | red node 5 | white node 5 | green

Without the filtered nodes.

Now you would group it with the title field so that it would be displayed together.

To do the grouping you would do the following.

Click on the settings link towards the right of `Format :`

This would bring up a screen as shown below. you would select the field you want to group from the dropdown **Grouping field Nr.1**

---
Tags: views
---


# Question
Title: Drupal 7 has lost all "safe" values and summaries
I suddenly noticed that safe\_value and safe\_summary are empty now. Regular value is filled with data, but safe values are not. They were working just fine some time ago. I am currently trying hard to find what caused this havoc.

This applies to all nodes and comments. Haven't checked other content types yet.

Thanks!

# Answer
I found out that the problem was caused by Facebook album fetcher module and its text format filter.
> 0 votes

---
Tags: nodes, entities, comments
---


# Question
Title: How to get users (entities) for a certain field value?
I want to write a function that returns users which have entered a certain value to a custom user field.

Lets say there is a custom birthday field for every user. What would be the best way to get all users with a certain birthday?

I could create a DB query that searches the field\_data\_field\_birthday table and returns the entity\_id(s) (which in this case would be the users id(s)) for which the field\_birthday\_value matches a given value and then load the user(s).

This seems a little bit crude, are there generic functions for this use case available? In the entity API or the field API maybe?

# Answer
Simple example for the use case I asked about:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_birthday', 'value', $birthday);

$result = $query->execute();
$users_ids = array_keys($result['user']);

```
> 12 votes

---
Tags: users, entities
---


# Question
Title: how do i use subquery in db_api condition?
I am using drupal 7 and i would like to create subquery in condition clause with db\_api. With db\_query it goes something like this:

```
select *
from some_table_1
where some_table_1.something =
 (select max(some_table_2.something)
  from some_table_2
  where some_table_1.id = some_table_2.id
);

```

Among other, I was trying it with

```
$query->condition('some_table_1.something', $subquery);

```

and i cant get it to work.

How can i do that?

# Answer
If I understand you properly you need to use a standard where clause rather than a condition in your sub query, e.g.

```
$subquery = db_select('some_table_2');
$subquery->where('some_table_1.id = some_table_2.id');

...

$query->condition('some_table_1.something', $subquery);

```
> 1 votes

---
Tags: database
---


title: Display form within a custom field?

text:
# Question
Title: Display form within a custom field?
I've created a module that has a 'form builder' on the admin side. Once the form has been created, I store the form array in the database. Then on the front end I've created a custom field that pulls the form array from the database and displays it as part of a node. Here is the pseudo-code to show my thinking:

```
- Create form via admin side and store form array in database
- Create node with custom field, choose which form you wish to display
- Set url alias on the node
- When user views url, display the form as part of the node

```

The problem I have is that when I complete the form on the front end and press submit, nothing happens. Looking at the html, it doesn't have a `<form>` tag, presumably because it's part of a node and not a hook\_form.

So, I'm wondering if it's possible to display a submittable form as a custom field? Or do I need to find another way around this?

**Edit:** I'm using the following code to display the form:

```
function mantis_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

    $element = array();

    switch($display['type']) {
        case 'mantisform_default': {

            // Retrieve the form from the database
            $form_data = mantis_retrieve_form_data($items[0]['mantis_form_id'], 'display');

            $element[]['#markup'] = drupal_render($form_data);

        }
    }
    return $element;
}

```

**Edit**: $form\_data structure can be seen here http://pastebin.com/JfeNGBGA and $element is here http://pastebin.com/HU5NSHd5

# Answer
> 0 votes
Figured this one out. The reason the form wasn't submitting was because I wasn't calling drupal\_get\_form. It seems that drupal\_get\_form carries out a lot of essential processing that allows the form to function. Simply creating a form array and calling drupal\_render is not enough to create a functional form.

The solution was to create an implementation of `hook_form` and retrieve my form data from the database:

```
function mantis_form($form, &$form_state) {

    $data = db_select('mantis_forms', 'f')
    ->fields('f', array('form_data'))
    ->condition('id', $form_state['build_info']['args'][0], '=')
    ->execute()
    ->fetchField();

    if($data) {
        $data = unserialize($data);

        // If we're on the admin side then disable the submit button
        if($form_state['build_info']['args'][1] == 'admin') {
            $data['form_wrapper']['submit_form']['#disabled'] = true;
        } else {
            // If we're on the front end then enable the submit button and remove the optional fields
            $data['form_wrapper']['submit_form']['#disabled'] = false;
            array_slice($data, 1, 1);
        }

        return $data;
    }
}

```

And then amend the hook\_formatter\_view to use drupal\_get\_form:

```
function mantis_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

    $element = array();

    switch($display['type']) {
        case 'mantisform_default': {

            $form_data = drupal_get_form('mantis_form', $items[0]['mantis_form_id'], 'display');

            $element[]['#markup'] = drupal_render($form_data);

        }
    }
return $element;
}

```

# Answer
> 1 votes
You have to check your field handler, node tpl.php or field tpl.php and use drupal\_render($yourform), it's the cleanest solution I see.

---
Tags: 7, entities
---


# Question
Title: Taxonomy path to a view instead to the taxonomy page?
I have a Vocabulary taxonomy with some terms (alfa, beta,). This vocabulary is se to be sync with a menu (myMenu) using the taxonomy\_menu module.

I need the path of the terms (the path of the menu items) to be products/\[term:name\] instead of taxonomy/\[term:name\].

'products' is the path of a view page and the **term name** will be taken as a argument.

How can I accomplish this?

# Answer
The TVI module should help you with this:

> The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabuarly.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Custom field doesn't show up in 'field type' dropdown
I've been trying to create a custom field for my module. I have used the field\_example module as a guide but my field doesn't show up in the 'field type' dropdown on the 'manage fields' page.

Here is my code:

**mantis.module**

```
function mantis_field_info() {
    return array(
        'mantisform' => array(
            'label' => 'Mantis ' . t('Form'),
            'description' => 'Mantis Support Request Form',
            'default_widget' => 'mantis_mantisform_widget',
            'default_formatter' => 'mantisform_default'
         )
    );
}

function mantis_field_is_empty($item, $field) {
    if($field['type'] == 'mantisform') {
        if(empty($field['mantis_form_id'])) {
            return true;
        }
    }
    return false;
}

function mantis_field_widget_info() {

    return array(
    'mantis_mantisform_widget' => array(
        'label' => 'Mantis ' . t('Form'),
        'field_types' => array('mantisform'),
        'behaviors' => array(
            'multiple_values' => FIELD_BEHAVIOR_DEFAULT,
            'default_value' => FIELD_BEHAVIOR_NONE
            )
        )
    );
}

function mantis_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

    $base = $element;

    if($instance['widget']['type'] == 'mantis_mantisform_widget') {
        $widget = $instance['settings'];
        $settings = $widget['settings'];

        $element['mantis_form_id'] = array(
            '#type' => 'select',
            '#title' => t('Support Request Form'),
            '#default_value' => isset($items[$delta]['mantis_form_id']) ? $items[$delta]['mantis_form_id'] : NULL
        );
    }
    return $element;
}

function mantis_field_formatter_info() {
    return array(
        'mantisform_default' => array(
            'label' => t('Default'),
            'description' => t('Allows a ') . 'mantis' . t('support form to be selected'),
            'field types' => array('mantisform'),
        )
    );
}

function mantis_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

    $element = array();

    switch($display['type']) {
        case 'mantisform_default': {

        }
    }
    return $element;
}

```

**mantis.install**

```
function mantis_field_schema($field) {
    if($field['type'] == 'mantisform') {
        $schema['columns']['mantis_form_id'] = array(
                'type' => 'int',
                'not null' => false,
        );
        return $schema;
    }
}

```

I haven't completely fleshed out mantis\_field\_formatter\_view but figured that I should still be able to see the new field as an option in the dropdown.

Can anyone see where I'm going wrong?

# Answer
> 0 votes
This does appear to have been a caching issue. The field has appeared now. weird.

---
Tags: 7, entities
---


# Question
Title: What is best way to combine multiple fields in template preprocess?
I have 3 fields I want to join into one line to wrap inside some tags. Is template.php in a preprocess function the best place to do this? I won't need the fields after I join them, so I assume I call hide() on them as well?

# Answer
> 2 votes
I would do this using hook\_node\_view() or theme\_preprocess\_node(), but I'm not sure which is the best way.

```
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        if($node->type == 'your_content_type'){
            $field_1 = $node->content['your_field_1'];
            $field_2 = $node->content['your_field_2'];
            $field_3 = $node->content['your_field_3'];

            // remove individual fields
            unset($node->content['your_field_1']);
            unset($node->content['your_field_2']);
            unset($node->content['your_field_3']);

            // combine those fields in a tag
            $html = '<div id="some-id">';
            $html .= '<span>'.$field_1.'</span>';
            $html .= '<span>'.$field_2.'</span>';
            $html .= '<span>'.$field_3.'</span>';
            $html .= '</div>';

            $node->content['combined_field'] array(
                '#markup' => $html,
                '#weight' => 1
            );
        }
    }
}

```

Another way is to alter these from `THEME_preprocess_node()` in the template.php.

```
function MYTHEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $field1 = strip_tags($variables['content']['field_1']['#markup']);
    $field2 = strip_tags($variables['content']['field_2']['#markup']);

    // remove individual fields
    unset($variables['content']['field_1']);
    unset($variables['content']['field_2']);

    // combine those fields in a tag
    $variables['content']['combined_fields'] = array(
        '#markup' => '<div id="some_id">'.$field1.$field2.'</div>',
        '#weight' => 2
    );
  }
}

```

---
Tags: 7, entities, theming
---


# Question
Title: Drupal 7: Find which user created a given user
I have a number of users admins (group: "**users\_admin**") who create users who can view content (in many groups, like "**students\_a**", "**students\_b**", "**students\_c**", and so on).

Is there a way to filter the users by their creators?

Let me clarify:

* User "**A**" from "**users\_admin**" create a user "**S1**" in "**students\_a**".
* User "**B**" from "**users\_admin**" creates a user "**S2**" in "**students\_a**".

I would like to be able to differentiate users created by "A" and "B", has anyone done that before? Is it possible?

I hope I made myself clear enough; please tell me if you need some clarifications.

Thanks in advance for you insights!
Regards

# Answer
> 1 votes
Drupal, by default, does not keep any authoring information of users.

However, there is a module for that! Try Sub User module. It uses Relation module to maintain the relationship with parent user.

---
Tags: users
---


title: Is it possible to add a menu to a menu?

text:
# Question
Title: Is it possible to add a menu to a menu?
I've created a "Staff menu" with various menu items. However I want to add it to the "Main menu" as a drop-down list (e.g. set Staff as Vertical, while Main is the navbar / horizontal menu).

Is it possible to just add a menu to a menu by creating a new menu item in the "Main menu" and linking it to "Staff menu" ?

# Answer
> 2 votes
You can use this module http://drupal.org/project/om\_maximenu then create parent menus and its child menus .Even you can create blocks inside with the sub menus.

# Answer
> 0 votes
As far as I know, there's no way to add a menu to a menu as you describe. However, you can make one big menu with parent/child/grandchild relationships and then use a module such as Superfish or Nice Menus to display it the way you want (main links horizontal/children drop-down vertically).

---
Tags: routes, navigation
---


title: D7 - hide the ajax_command_html message

text:
# Question
Title: D7 - hide the ajax_command_html message
I'm using the following code to display a (success) message, it's working quite nicely, however I want it to disappear after, lets say 3 seconds.

```
  $commands = array();
  $commands[] = ajax_command_html('.ajax_messages', ' message ');
  $page = array(
  '#type' => 'ajax',
  '#commands' => $commands,
  );

  ajax_deliver($page);

```

How can I achieve this?

# Answer
Maybe something like this in a js file included on the page.

```
(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      $('.ajax_messages').delay(3000).fadeOut();
    }
  };
})(jQuery);

```
> 1 votes

---
Tags: 7, ajax
---


title: Check in php if a view display exists?

text:
# Question
Title: Check in php if a view display exists?
I've created a display called 'stats' for some views I've created - its cached and its generic and its quick and I use it for things like this

```
$result = views_get_view_result($view_name,'stats');
$count = count($result);
if ($count) $variables['title'] .= ' ('.$count.')';

```

However, not all views have this display. How can I check, in php, if a given view has a display called 'stats' ?

# Answer
Off the cuff, this should work:

```
$view = views_get_view($view_name);
if ($view && $view->access('stats')) {
  // it has a 'stats' display
  $view->set_display('stats');
  $view->pre_execute();
  $view->execute();
  return $view->result; // or do whatever with it...
}

```

but realize at this point you're halfway through the 'heavy lifting' views does, so you should probably use `$view` inside that `if` instead of then calling `views_get_view_result()`

ADDITION: I added what I think the correct `$view` incantations should be for getting just the results above :)
> 5 votes

# Answer
First make a **views\_get\_view($view\_name);** it will give you the $view object, which I'm sure will tell you which display it has. Then you'll be able to if().
> 0 votes

---
Tags: views
---


# Question
Title: User group / user access to files Drupal 7
Is there an easy way (as in with some module) to restrict file downloads to certain user groups or users in Drupal 7? Tried to search and found only questions with no proper working answers.

I know about private files however that seems to restrict files only with logged in users not with certain user groups or individual users. I also know about content access module, but that does not restrict file downloads at all if user knows the direct url to the file.

# Answer
> 1 votes
Drupal supports this natively.

Use private file access and content\_access to support granular access to your content.

Due to some bugs here and there I had to rebuild the permissions (/admin/reports/status/rebuild) after configuring content\_access a usual clear cache wont work here.

# Answer
> 0 votes
I have similar issue and I am far from stating that drupal supports natively any form of access control for content of (organic) groups, not even mentioning files.

So far the most promising article I've found is http://www.onyxbits.de/content/drupal-and-problem-protecting-uploaded-files

I'll be trying it out this week and if it works I'll try to post an update here.

---
Tags: files
---


# Question
Title: Could anyone suggest a Drupal database versionning tool?
> **Possible Duplicate:**
> How do I manage collaborative development on a Drupal site?

Is there any Drupal database version like GIT for versionning files ? with drush or any thing else ?

I've already used features module but it doesn't cover all needs in database versionning to get back to one saved version of the project.

The real point is to get drupal usable by many "site builders" and can manage conflict. on some features

Thanks. :)

# Answer
I think the Backup and Migrate module will help you. Here is a quote about it (from the module's project page):

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
>
> With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.
> 0 votes

# Answer
What exactly are you missing?

Features combined with Strongarm will do a pretty good job.
> 0 votes

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


# Question
Title: Drupal 7 View tab on user profile empty as default?
In a default Drupal 7 installation where no custom fields were been added to user profiles is it the normal behavior that the user profile tab View is empty? I would expect to see for example the registration email. Thank you all for help

# Answer
I ended up creating a page view with path /user/% where I can show any user field I need. Thank you for help.
> 1 votes

# Answer
The user view tab should include the default user entity\_view information as per

Normally that's information such as the history / length of time since registration and other default content.
> 1 votes

---
Tags: users
---


# Question
Title: Custom PHP code as a Panels selection rule
Panels allows selection rules to be created with custom PHP code (disclaimer: I know this approach is insecure and should be avoided).

When adding PHP code as a selection rule, the helpful description states:

> Access will be granted if the following PHP code returns TRUE. Do not include . Note that executing incorrect PHP-code can break your Drupal site. All contexts will be available in the $contexts variable.

I made a function in a custom module to use for the selection rule:

```
function mymodule_selection_rule_is_location_set() {
  global $user;
  $user_fields = user_load($user->uid);
  if (isset($user_fields->field_acc_location['und']['0']['lat'])) {
    $location = $user_fields->field_acc_location['und']['0']['lat'];
  }
  if (empty($location)) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

```

However, when I set the selection rule as shown below, the selection rule is not triggered even when there is a value for `$location` and the function returns `TRUE` (confirmed with devel module).

**Evaluates false as a selection rule even when the function returns TRUE**

```
mymodule_selection_rule_is_location_set()

```

To get it to work, I had to write the selection rule like this:

**Evaluates correctly**

```
if (mymodule_selection_rule_is_location_set()) {
  return TRUE;
}

```

My question is why do I have to write it like the latter rather than the former?

# Answer
I think the calling function which executes your PHP code would expect the RETURN true/false statement. Thus, you would need return to the calling function as returned by the called function.

```
return mymodule_selection_rule_is_location_set();

```

If you don't have `return`, the calling function would expect `NULL` and it would execute as `FALSE` always regardless of what is returned by the called function.
> 2 votes

---
Tags: panels
---


# Question
Title: Drupal Commerce Product Pricing Rules disapear
When I add a new rule in Product Pricing rules they disappear out of the Product Pricing Rules Window. They are still available in Workflow-\>Rules.

I am also finding that it seems to be hit and miss weather I am able to access all data on the system. Sometimes the rule I create sticks in the Product Pricing Rules window for a few minutes and those rules when created give full access to all referenced data. But I create a new rule and cant see data that I know I should be able to I know then that this is going to be one of the rules that will disapear into the Workflow-\>rules window.

Any idea what is happening.

Thanks Simon

# Answer
> 0 votes
It sounds like for some reason the event is getting removed or changed to something other than "Calculating the price of a product." However, without seeing a screenshot of your Rules list, there's no way to tell. Look at the list and see what the event is getting set to.

If you use the product pricing rule add link from the product pricing interface, it should be altering the form to pre-select the proper event and hide the select list. Perhaps you have some other code on the site that undoes that selection or otherwise invalidates it.

---
Tags: commerce, rules
---


# Question
Title: Show all group content of a specific group type
I'm having a very difficult time figuring this out, and I'm wondering if it's even possible. I'm using organic groups 7.x-2.x, and I have two "group" types: a student group type and a faculty group type. I also have a "group content" type called blog posts which can post in either group type. What I would like to do is create two views, one to show all blog posts that got posted in all student groups, and another to show the same for faculty groups.

**Can anyone provide me insight into how to do this?**

Side note: Since OG has switched to using entity reference to assign group membership, I thought it would easy to use this relationship in views to accomplish this, but it looks like it is only using entity reference for the widget, and does not store the data as a normal entity reference field would. Everything I tried with the og\_membership relationship seemed to fail, so I'm at a loss here. Any help would be appreciated!

# Answer
> 3 votes
Wow, I actually figured this out. Basically you need to do the following:

* Add the "OG Membership: OG membership from Node" relationship to the view.
* Add the "OG Membership: Group Node from OG membership" relationship, assigning the above relationship.
* Add a Filter Criteria of "Content: Type" = the group content type you want to show, and (here is the trick) assign the above relationship for this.

Here is a screenshot that might be more helpful:

# Answer
> 2 votes
I have no idea how to do it using views gui but I can tell you how to write your own query which you can use to override the query from views to display it.

All the data you need will be stored in 2 tables

```
field_data_group_audience.entity_id   // node id of the content you are looking for
field_data_group_audience.bundle      // type of content in your case blog posts

JOIN
node -> type // equal to student group or faculty group

```

because nid of a group is not the same as gid of a group you have to join the two tables using og table

```
JOIN
og
WHERE
og.etid = node.nid
AND
og.gid = field_data_group_audience.group_audiance_gid

```

This should result in something similar to this:

```
$query = db_select('field_data_group_audience');
$query->join('og', 'og', 'og.gid = field_data_group_audience.group_audiance_gid');
$query->join('node', 'node', 'og.etid = node.nid');
$query->addfield('field_data_group_audience','entity_id','tricky_name_expected_by_views');
$query->condition('field_data_group_audience.bundle', blog post,'=');
$query->condition('node.type', 'student group','=');
$view->build_info['query'] = $query;

```

Once you have a working query you plug it into views using hook\_views\_pre\_execute. https://drupal.stackexchange.com/a/56322/12153

---
Tags: 7, views, organic-groups
---


# Question
Title: Apply percentage coupon to entire order (Commerce)
I am using Drupal Commerce and Commerce Coupon Percentage. It works great for most products. However, I have a product priced at $0 and the price is then altered through rules which changes the line item total for that order.

Because the product is priced at $0, the percentage does not apply. Therefore, I am wondering if there is a way to apply the percentage coupon to the entire order rather than the product price. Any thoughts on how to approach this?

# Answer
Price calculation in Drupal Commerce always happens at a line item level. There are order level coupons for knocking a set amount off an order total, but we treat percentage coupons as these line item level price calculations. You should be able to adjust the weight of your product pricing rules so your rule that updates the price gets evaluated prior to the rule that applies the percentage coupon to the item. Give that a shot and leave me a comment if it doesn't work.
> 2 votes

---
Tags: rules, commerce
---


# Question
Title: Drupal 7 Display legal module fieldset on user/% instead of user/%/edit
How can I display the legal module fieldset on /user/% instead of /user/%/edit? Please note my /user/% is a view page so I can use views template schema.

# Answer
> 0 votes
I just took a look inside the code of Legal module, what you describe is not possible by design, as of legal is hooking in existing forms:

legale.module line 223

```
function legal_form_user_profile_form_alter(&$form, $form_state) {

```

legale.module line 223

```
function legal_form_user_register_form_alter(&$form, &$form_state) {

```

You might want to try out building a custom user-page form and hide the unwanted elements from profile form.

For reference in how to to that see this answer.

I also think you will need to go a bit further than views only and use Panels to add multiple views on one page.

---
Tags: users
---


# Question
Title: Rules: fire at adding term only when one of this term anscestors is other specific term
I'm trying to add menu items programatically by using rules - the item should be added after user will create a term, but I need a specific condition that I cannot accomplish - fire rule only if ONE OF THE ANCESTORS of created term is specific term. So for example if I have hierarchy:

```
Term 1
Term 2
 - Term 2.1
 - Term 2.2
   -Term 2.2.1

```

I would like the rule to fire when the added term is 2.x.x.x... How can I accomplish this? I was trying for few hours different approaches without luck.

# Answer
Write your own condition for rules

```
function mymodule_rules_condition_info() {
  return array(
    'mymodule_condition_needs_veryfication' => array(
      'label' => t('ONE OF THE ANCESTORS of created term is specific term'),
      'group' => t('mymodule'),
      'arguments' => array(
        'aplication_node' => array(
            'type' => 'node',
            'label' => t('A fancy condition'),
        ),
      ),
      'module' => 'mymodule',
    ),
  );
}
function mymodule_condition_needs_veryfication($node)
  if(condition($node))
    return true;
  return false;
}

```
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Drupal 7 e-mail driven forum (mailcomment)
I've been tasked to set up a forum on drupal 7 that can support outgoing e-mail notifications with incoming e-mail posting for a forum section akin to Google Groups. I.e. a fully e-mail integrated forum where content comments and threads can be generated and responded to entirely by e-mail.

My question is, how do I achieve this? In most cases, I'm finding deadends with dependencies as it does not seem mature on drupal 7; many of the modules only have recommended or released versions for drupal 6. In the first case I tried, my host (hostgator) did not support the required PHP module dependencies.

I have tried:

http://drupal.org/project/femail Issue: Unable to install PECL MailParse a requirement of femail. Our host (hostgator) won't support: 'not compatible' apparently.

Listhandler Issue: Untried. No D7 version.

and the most promising route:

Mailhandler/Mailcomment with Notifications and Messaging Guides: hyperlinkhttp: drupal.org/node/1045918 hyperlinkhttp: peterthorndycraft.com/tutorial/mailhandler

Issue: Depenendies that cannot be met.

From the mailcomment INSTALL.txt:

Dependencies: \- Mailhandler (matching version required - i.e., if you are using Mail Comment 7.x-2.0-alpha5, you must use Mailhandler 7.x-2.0-alpha5) \- Notifications and Messaging (7.x-4.x branch)

The 7.x-4.x branch appears to not exist: http://drupal.org/project/messaging

I have tried it with the 7.x-1.0 version but without success.

EDIT: My issue is identical (the OP is not me) to: http:// drupal.org/node/1889550

EDIT: I have managed to be able to create nodes via e-mail using the mailhandler/notif+messaging framework, but as of yet, unable to get replies from e-mails to trigger new comments.

My question is really: is achieving this aim possible with D7? What framework have people achieved this in in other D7 sites? I'm reasonably new to Drupal, so sorry if there is something obvious I haven't tried.

Thanks

PS: Couldn't post all the hypoerlinks i was referencing. J

# Answer
> 1 votes
This is in no way trivial since you will need to setup an email SERVER to react to certain emails and trigger a drupal 7 process. I have been tinkering with a bunch of modules and the most promising is og\_mailinglist Within the module you will find a lot of information and Documentation of how to achieve this. You might even want to read through this to meet the makers

Even so the requirements are really tough and it is a project of several weeks if not months. most customers think this should be easy, well it is not. And it has security implications that have to be thoroughly solved. You are allowing an email to add content!

Good luck.

---
Tags: emails, nodes
---


title: Menus and mobile sites

text:
# Question
Title: Menus and mobile sites
We're using a theme based off Adaptive Theme, but even dropping columns below the main content still has undesired rendering outcome. When `region-sidebar-first` drops below `content-inner` there is a problem -- since the link colors contained within sidebar first and the body background color are both white.

What I'd like to have happen is that for mobile devices or when the browser size is under a certain width, I'd like to remove `region-sidebar-first` and `region-sidebar-second` and move the menu into another field that into another collapisable region to function as a 'mobile menu'.

Question: Could context handle this? Is there a mobile to handle such logic?

Current our setting appear as follows

# Answer
> 2 votes
This is more a CSS question I think. I solved this problem already for various sites using another menu block, with its own css markup, or using a jump menu.

Using media queries you will have to set the threshold on where to break:

```
@media all and (max-width: 370px) {
    .default-menu-region {
        display:none;
    }
    .mobile-menu {
        display:block;
    }
}

@media all and (min-width: 371px) {
    .mobile-menu {
        display:none;
    }
}

```

Adaptive theme provides files for those media queries already, you can just drop your custom content in there instead of writing new media queries like in this example.

---
Tags: theming
---


title: Add user points for every up vote

text:
# Question
Title: Add user points for every up vote
My drupal 7 site has an user rating system for authors content, but problem is, every up-vote and down-vote do not add point's automatically in users profile. But i think, it is possible by User Points module. From Userpoints Karma module page i have learned that vote/up down module allows a voter to add or subtract points to the author of a given node or comment, thereby awarding or punishing the author for what they wrote.
So, i have configured vote/up down module successfully, here is a screenshot of a views of my website:
Now my question is, How to add point's automatically for votes using vote/up down module and User Points module? So, if an user vote a content then the user points for that content author will be `10 + 5 = 15`! {Here `10` is previous user point for the content author and `5` is the value for every up-vote!} I can't understand that How to do it automatically? Any ideas? Thanks

# Answer
Theres is a module to add rules to voting api: http://drupal.org/project/voting\_rules

Userpoints comes with native rules support.

I just set the whole thing up on my test environment, added a new Rule with

```
Event: User votes on a Node

Condition: User has role(s)
Parameter: User: [vote:user], Roles: authenticated user

Condition: Check the value of the vote
Parameter: Vote: [vote], Operator: is greather than, Data value: 0

Action
Grant points to a user
Parameter: User: [vote:user], Points: 5, Points category: General, Operation: Insert, Moderate: Use the site defaul

```

additional info: you must enable **userpoints** and **userpoints\_rules** as well as **voting\_rules**

Here's the export of the rule

```
{ "rules_reward_voter" : {
    "LABEL" : "reward voter",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : [ "voting_rules_insert_node" ],
    "IF" : [
      { "user_has_role" : { "account" : [ "vote:user" ], "roles" : { "value" : { "2" : "2" } } } },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "operator" : "\u003E", "value" : "0" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "5",
          "tid" : "0",
          "entity" : [ "" ],
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "default"
        }
      }
    ]
  }
}

```
> 6 votes

---
Tags: users, userpoints, rating
---


title: using theme_menu_link()

text:
# Question
Title: using theme_menu_link()
I am currently using `theme_menu_link()` but it themes every menu in Drupal. I only want to theme my main menu. How can I check for a specific menu?

```
function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

//if(id == main_menu){ theme it different }

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";

}

```

# Answer
> 2 votes
You can get the ID of a menu by looking at the URL when you edit it in the menu configuration admin interface and converting dashes to underscores.

For example, on `admin/structure/menu` if I hover 'User Menu' I see `admin/structure/menu/manage/user-menu/edit` which means that the menu machine name is 'user\_menu'.

The `$element` contains the menu's id: `$element['#original_link']['menu_name']`.

So you can put that in your `if()` and get

```
if($element['#original_link']['menu_name'] == 'user_menu') {
  ...
}

```

where you replace 'user\_menu' with the name of the menu you want.

---
Tags: routes, theming
---


# Question
Title: How to get the children terms of a taxonomy in views?
I just created a view to show terms of a given vocabulary. I works but the children terms aren't shown.

How do I do to get children terms?

# Answer
Depending on how many levels of the tree you want to show. If entire, complex vocabulary, then Views Tree module would be an answer.

> This module provides a tree-based style plugin for Views.

However if this is just a 2-level tree, you might want to set up a view that displays terms and groups them by their parent. For that you'd need to select also Term: Parent, exclude it from display and group the view by Parent.
> 2 votes

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


title: Image styles based on node type

text:
# Question
Title: Image styles based on node type
Let's say i have two node types:

* `Article` \- with `300x300` photo
* `News` \- with `100x100` photo

For now, i can define those two sizes in Image Styles menu and they'll be both created for both content types (so both `Article` and `News` will have two images generated - in size `300x300` and `100x100`).

My question is - is there any way to set which content type shoud use which image style(s) ? **Please note that i'm not interested in generating both of them and displaying just one. It would kill my server and my wallet (i'm using Amazon s3).** Thanks in advance.

# Answer
The setting on the content type's field display settings page allows you to choose image style to display. Drupal only generates styles when they're used somewhere.
> 1 votes

---
Tags: 7, nodes, media
---


title: Group similar nodes in a view

text:
# Question
Title: Group similar nodes in a view
I have a group of universities that have a director. However, BYU has 2 directors. I try and "group multiple values" and turn on distinct in the "basic settings", but then fields for only one director appear while both director names appear.

Basically I want the same layout as below, but Tracy and Carl to be on the same row with their contact information.

I've tried for a few hours and googled for another few hours... Thanks!

https://i.stack.imgur.com/awWQ4.jpg
https://i.stack.imgur.com/TdFxS.jpg

# Answer
For those that might have a similar issue (having one node with 2 relationships and all other nodes in the view have 1 relationship to display) I found that by displaying the node teaser instead of just the field, I can get the information I need.
> 0 votes

---
Tags: nodes, views
---


title: Product comparison with Drupal Commerce

text:
# Question
Title: Product comparison with Drupal Commerce
How can I implement a product comparison with the Drupal Commerce module?

For example, if there is a list of products, will the user be able to click on checkbox of 3 products, and click the "Compare" button to see a table where products, features, and prices are compared?

# Answer
> 5 votes
I think that this page could be useful for you: Product comparison in Drupal. This tutorial explains how to to implement a node comparison with Flag and Views modules: in short creating an Include in comparison per-user node flag, which users will use to mark the interesting nodes. Then, creating a table view with the nodes previously marked.

# Answer
> 2 votes
There's this interesting module, the Properties module, which allows you to do comparisons, but it hasn't anything to do with Drupal Commerce. You could have these properties in any Drupal entity.

> Provides a dynamic properties field that allows to store product properties or similarly structured information. A property consists of an attribute, the name of the property and a value. It belongs to a category.
>
> Properties are stored in a structured way so that they can be compared, indexed, processed and displayed in different ways. By default, a table and a definition list formatter is provided.

# Answer
> 0 votes
There is module for that

Commerce Comparer

http://drupal.org/sandbox/ymakux/1908654

---
Tags: commerce
---


# Question
Title: Use one textfield for searching in two or more fields in Views
I have a simple content type in Drupal 7 with title and body (and other fields). I've defined a view with exposed filters.

I want just one text field that searches in title or body. So, if I search for 'foo' both nodes with 'foo' in their body or/and title will be matched.

One solution is to use "Global: Combine fields filter" and combine title and body, but Views then uses a CONCAT function in where clausule, something bad for performance.

I've a solution, but there're drawbacks and I'm not sure if it's optimal.

# Answer
Using Vies or/and funcionality I set (using more fields not related to this question):

filed1 AND field2 AND ... fieldN AND title OR body

title is not expsed, but body is.

My solution is to implement hook\_views\_pre\_build(&$view).

```
if ($view->name == 'my-view') {
  // Look for the search string, is it present?
  if (!empty($_GET['search'])) {
    $view->filter['title']->value = check_plain($_GET['search']);
  }
}

```

I've renamed body key in GET to be search.

This way search is performed as I want. The drawback is I can't position search element anywhere becasue it must be in its own group, but I can live with it.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Is there any way to reset a menu's default order (e.g. Management Menu)?
I have installed Drupal Commerce Kickstart and included with the distro is a mega menu. It also restructures the menu items to a more "End-user friendly" order. I personally prefer the default order that core gives you. Is there any way of resetting the "Management menu" to it's default order (without manually reordering them again)?

This is what it looks like after disabling the mega menu and enabling good ol admin\_menu

# Answer
Not that i'm aware of.

It sounds like the mega menu being active is firing something like a `hook_menu_alter` to be evaluated by Commerce -- they've hardcoded their own ordering because its more "user friendly".

`hook_menu_alter` overwrites values that the menu had, so drupal has no knowledge what the default ordering was. If the mega menu is active it forces their ordering, if it isn't you get the default ordering.

You'd have to look in Commerce where they add the custom menu items, or activate the mega menu and see how their adjusting menu `#weight` values.

You could then write your own `hook_menu_alter` that undoes their changes.
> 0 votes

---
Tags: routes, commerce
---


# Question
Title: Drupal 7 Add user delete tab in user profile
I would like to show the user delete confirmation form as a tab in user profile, just near View and Modity. I am trying the following code in a custom module but it is not working, I'm not sure I am calling the right callback and arguments:

```
function custom_morebuttons_menu_alter(&$items) {
  $items['user/%user/cancel'] = array (
    'title' => 'Cancel profile',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_cancel_confirm_form', 1),
    'access callback' => 'user_cancel_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
}

```

# Answer
You need to use hook\_menu() instead of hook\_menu\_alter() because you are adding a new menu item rather than altering an existing one.

```
function YOUR_MODULE_menu() {
  $items['user/%user/cancel'] = array(
    'title' => 'Cancel profile',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_cancel_confirm_form', 1),
    'access callback' => 'user_cancel_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'file' => 'user.pages.inc',
    'file path' => drupal_get_path('module', 'user'),
  );

  return $items;
}

```

Don't forget to return $items at the end of the function, since it is not passed by reference.

Though I'm not sure if the page callback and arguments are right, I didn't check that, I've just copied from your code.
> 12 votes

# Answer
using hook\_menu() and a custom module

```
function mymodule_menu() {
    $items['user/%user/canceltask'] = array(
    'title' => 'Cancel profile',
      'page callback' => 'mymodule_goto_user_cancel',
      'page arguments' => array(1),
      'access arguments' => array('cancel_account'),
      'access callback' => TRUE,
      'type' => MENU_LOCAL_TASK,
      'weight' => 10,
    );
    return $items;
}

function mymodule_goto_user_cancel($arguments=0) {
    drupal_goto('user/'.(int)$arguments->uid.'/cancel');
}

```

This solution offers the advantage of not needing to mess around with any forms at all. Its a simple redirect Button.
> 6 votes

---
Tags: 7, users
---


title: Use Bias with apachesolr module

text:
# Question
Title: Use Bias with apachesolr module
I want to use Apache Solr in my site build with Drupal7. The server is UP, simples searches are working but I can't boost a field with bias.

For example, I boosted the title (or label in the administration page), giving him a 5 in the select field.

After re-index the node, I searched and the order of the result still the same.

I tried to create a little module with apachesolr's hook to watch the document it send to solr server.

`hook_apachesolr_index_documents_alter()`:

```
[_fieldBoosts:protected] => Array
(
[id] =>
[site] =>
[hash] =>
[entity_id] =>
[entity_type] =>
[bundle] =>
[bundle_name] =>
[path] =>
[url] =>
[language] =>
[path_alias] =>
[label] =>
[content] =>
[teaser] =>
[ss_name] =>
[tos_name] =>
[ss_name_formatted] =>
[tos_name_formatted] =>
[is_uid] =>
[bs_status] =>
[bs_sticky] =>
[bs_promote] =>
[is_tnid] =>
[bs_translate] =>
[ss_language] =>
[ds_created] =>
[ds_changed] =>
[ds_last_comment_or_change] =>
[is_comment_count] =>
[type_name] =>
[created] =>
[changed] =>
[last_comment_or_change] =>
[comment_count] =>
[name] =>
[tos_content_extra] =>
[access__all] =>
)

```

All the data are empty.

This is a screenshot of my module setting page.

screenshot http://img338.imageshack.us/img338/7984/drupalsolrconf.png

# Answer
> 2 votes
To verify the boost values are included in your queries, tail the Solr `request.log` file. You'll see things like `&qf=label%5E5.0` (%5e is a caret ^, which marks the boost value).

Another useful trick for optimizing the scores is to include the score in your themed results output. You may find the boosts are affecting the scores, but aren't high enough to substantially change the ranking. This can be added with a small hook:

```
function hook_preprocess_search_result(&$variables) {
  if (user_access('administer search')) {
    $variables['title_suffix'] = '<code>[score: ' . $variables['result']['score'] . ']</code>';
  }
}

```

# Answer
> 1 votes
The settings page you are referring to controls query-time boosts, not index-time boosts. So perhaps you can find the effective boosts better in a query-modifying hook.

---
Tags: search
---


# Question
Title: WSOD on node edit/view pages only after migration - subdomain multisite
just migrated my company's website, foo.com, to a new server. It is a multisite installation with an intranet, intranet.foo.com, installed at /sites/intranet.foo.com. Everything migrated successfully except for one thing: node view and edit pages are not loading on the intranet (whereas admin pages, view pages, etc., are loading perfectly).

I tried a blank node.tpl.php and the page still didn't load, so the error must be elsewhere.

I have php error reporting enabled in index.php – but I don't see any php errors (is this even possible - for some types of error? Anyway I have a ticket open asking the host to enable error reporting in php.ini).

I don't see any WSOD documentation on drupal.org that pertains to this specific predicament (node page WSOD only).

Does anyone have any ideas about server settings that could be causing this to happen on the new server? Or database issues that could be affecting node pages only? Or if it is a php code error, where would it be such that it would break only node edit and view pages?

# Answer
You have to also turn on display\_errors (see the examples section of http://php.net/manual/en/function.ini-set.php ).

Usually when display\_errors is off php is configured to log errors to some file. You might want to find that file and look at it.

My guess would be that some php-module is missing on that server and some drupal-module that is active on node-edit forms tries to use a function from that php-module.
> 1 votes

---
Tags: migrations, multi-sites, wsod, subsites
---


title: Incredibly slow speed in admin pages

text:
# Question
Title: Incredibly slow speed in admin pages
I've been using my 4 year old Mac Book Pro for a development environment for the past few years, and with memory (8 GB) and hard drive upgrades, speed was pretty decent. I just got a new iMac with a 3.4 GHz quad core processor and 16 GB RAM, and navigating between admin pages is slower than an arthritic snail. It literally takes up to 1 minute to just change pages in the admin section. The same pages with the exact same codebase and db change on my MBP is a matter of seconds. I'm using the same stack setup on both (Mac's Apache, MySQL and PHP via Homebrew). I have both XHProf and Webgrind set up, but both are disabled (in Devel settings for XHProf and xdebug.ini for Webgrind), so I know that's not what's causing the problem.

To troubleshoot, I turned on the query log in Devel, and it looks like at least one problem is the cache\_set function. There are multiple calls to it, and every time it takes way more time than any of the other functions. Also, in looking at webgrind, the top function I'm seeing called is php:sleep, which is being called from the lock\_wait() function. According to the comments in the function, sleep should only be called when a request failed to get a db lock.

So, with that info, it appears that I need to tweak my db settings. Can anyone give me some suggestions on what to change? I'm a noob to db tuning like this, so this is unfamiliar ground for me. I'm still searching myself, but any tips would be welcomed.

As a side note, my PHP memory\_limit is set to 256MB, so I don't think that's a problem.

Thanks.

# Answer
> 2 votes
After posting this, I was perusing the site, and came across a similar question where someone had suggested disabling the Update module. I had noticed a lot of calls to the update\_xml\_parser object in Update module, so it made sense. I disabled the module and voila! the page change speed went to a couple of seconds.

---
Tags: 6, database, performance
---


# Question
Title: Superfish Menu: looking for specific css value
Using Drupal 7.19 and Superfish 7.x-1.8

I was able to override most of the CSS and we are working towards a menu that we would like. However, I would like the parent menu item that is looked at to show a certain color. But it goes transparent once the mouse if off if it is unactive.

I am looking to make the unactive parentmenu item go a certain color if the child is hovered. I can't find the id/class via firebug, but am still looking.

If you look at the image provided, we want "Nuestro Institución" to show `#fec24a` (yellow) when it is expanded and unactive.

The site is in Spanish and these are the institutional colours.

I had an image attached, but I can't post it as a new user, so I will include the site I am working on.

Please remember that it is a work in progress.

http://devel.idl.org.pe/

# Answer
> 0 votes
The HTML element for "Our Institution" is:

```
<li id="menu-679-1" class="middle even sf-item-2 sf-depth-1 sf-total-children-5 sf-parent-children-0 sf-single-children-5 menuparent"><a href="/content/nosotros" title="" class="sf-depth-1  menuparent">Nuestro Institución</a>

```

You want the :hover value of this li item when you're on a child item. This is:

```
<li id="menu-679-1" class="middle even sf-item-2 sf-depth-1 sf-total-children-5 sf-parent-children-0 sf-single-children-5 menuparent sfHover"><a href="/content/nosotros" title="" class="sf-depth-1  menuparent">Nuestro Institución</a>

```

In my opinion this always gets ugly in CSS, for just that 1 menu item you could do (depending on your rules already in CSS):

`#menu-679-1.sfHover {background-color: yellow;}`

or if that doesnt work:

```
#menu-679-1.middle.even.sf-item-2.sf-depth-1.sf-total-children-5.sf-parent-children-0.sf-single-children-5.menuparent.sfHover { background-color: yellow; }

```

I would just write 1 css class per menu ID you want to target. If you use LESS CSS preprocessor you can use a small template to apply the hover color. You might be able to use a descendant selector but I always run in problems selecting all child `<li>`s when I do that ....

# Answer
> 0 votes
Normally, you should start by chosing a style from the superfish block administration and see if the background changes for hovered menu parent elements. (It should - only the default style - that you are using now has no background). If it is, copy the stylesheet to a new one (let's say newstyle.css) and rename(use a find/replace all tool) all occurances of old stylesheet name in the classes names with the "newstyle". Then edit the colors or other formatting as you like in the new stylesheet.

If not, which is again your case, you should remove or edit the .sf-menu classes from yoour sites/devel.idl.org.pe/themes/corolla/css/navigation.css

the background for your main parent elements is given in the corrola navigation stylesheet by :

```
.sf-menu li.sfHover

```

and by(line42) :

```
.sf-menu.sf-style-space-orange li.sfHover

```

in the orange-space.css(as an example) file - that you should have it in the sites/all/libraries/superfish/style

Also you should look in sites/devel.idl.org.pe/themes/footheme/css/footheme.css and i guess the generated css of footheme sites/devel.idl.org.pe/files/color/footheme-9c3b33ed/colors.css for conflicts on the lines that start with #menu-bar

---
Tags: theming, navigation
---


# Question
Title: How to get rid of added URLs when printing a Bootstrap-themed page?
When I print a page from my Bootstrap-themed site, all the links (and images with attached urls) have a printed representation of the link inserted into the printed page, right after the linked object. I can see some situations where this would be helpful, but for now it's just messing up my printed layout. I smell jQuery at work here, but I can't figure out where it is or how I can turn it off. Any hints out there? Thanks!

# Answer
Found it: it wasn't jQuery, but CSS3. Down in bootstrap.css, we find:

```
@media print {
  ...
  a[href]:after {
    content: " (" attr(href) ")";
  }
  ...
}

```

Overriding the style with `content:none` handles the situation fine. There are some similar `:after` clauses in there doing similar things, but this is working for now.
> 32 votes

---
Tags: javascript
---


# Question
Title: Link image to another view mode with Media 2 and File Entity
I'm trying to test Media 2.x and File Entity. I've edited the "Image" File Entity to add taxonomy terms and all and then I'm trying to leverage views to list all images in a grid in a page, and my end goal is to be able to click on a thumbnail and then get a larger image with more details.

I'm finding it complicated (impossible?) to link the images to another display (teaser to full content for instance). It works just fine with regular "Content" views but it seems that when you start with the "Files" view this is not an option.

Do you have any idea what I'm missing? Is there a way (relationship or anything) to be able to get the "Link this image to its content"-like option?

# Answer
> 1 votes
I'm not sure what you're asking. Normally you say "show title" and check "link this to content". Same thing here, Make your File view\_mode whatever you want and link it to your content url. You may be asking for a Lightbox approach to showing a set of images.

If there's no option to "link to content" for this field, simply create a rewrite url in the Views Field settings to generate a link using tokens.

Now you may ask -- this isnt addressing the teaser -\> full view\_mode switch for the Entity (or Field?). Creating links in Views, or with the `l()` function has nothing todo with View Modes ... they're just links you're making.

I find it helpful to add additional view modes to entities, I have used Entity View Modes for that.

You either setup a custom URL to your content that forces the view mode, using for instance View Mode Page or you could try to set a context or something and hand code something that forces the view mode on your destination url yourself using a custom module, for a small example:

```
/**
 * Implementation of hook_entity_view_mode_alter().
 * Change the view mode of an entity that is being displayed.
 */
function MYMODULE_entity_view_mode_alter(&$view_mode, $context) {
  if ($context['entity_type'] == 'node' && $context['entity']->type == 'slang_word') {
    $view_mode = 'slang_dict_word';
  }
}

```

You could use a custom view mode to only show the Field in question -- with the custom view\_mode set.

... maybe this rambling will help you or someone else :)

# Answer
> 0 votes
There is also the Image URL Formatter module that might help. Here is a quote about it (from the module's project page):

> (1) After install this module, then you add an image field, then you can goto this bundle's manage display page, here at format column, you can choose "Image URL" instead of "Image".
>
> (2) When you add an image field in your views, then you config the Formatter for this field, here you can choose "Image URL" instead of "Image".
>
> Then you can output image's URL instead of Image itself.

---
Tags: views, media
---


# Question
Title: How to create a node in Drupal 7 with a custom nid
I have to create a node in drupal 7 with a custom nid but the solution I've tried doesn't works (The created node not appears in the backend). If I create the same node without the custom nid, it works.

Code:

```
$node = new stdClass();

$node->nid = intval($insert['id']);
$node->vid = intval($insert['id']);
$node->uid = 1;
$node->type = 'nodetype';

$node->title = $insert['name'];
$node->created = time();
$node->changed = $node->created;
$node->promote = 0;
$node->sticky = 0;
$node->format = 2;
$node->status = 1;
$node->language = 'en';

$node->field_custom_1 = array('und' => array(array( 'value' => $insert['foo'] )));
$node->field_custom_2 = array('und' => array(array('value' => $insert['hello'])));
$node->field_custom_3 = array('und' => array(array('value' => $insert['world'])));

if ($node = node_submit($node)) {
    node_save($node);
    drupal_set_message(t("Node ".$node->title." : ".$node->nid." added correctly"));
}
else {
    drupal_set_message(t("Node ".$node->title." added incorrectly"), "error");
}

```

What's wrong? Thanks

# Answer
http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_save/7

I believe node\_save() takes all the node edit form input and builds a new node with a `node->id` for you.

`node_save()` either tries to update an existing node, or give you a newly saved one. You want to set what NID it gives you back.

Assuming an SQL storage engine for Nodes. You'd have to pick a NID greater than the current SQL `MAX(id) FROM {node}` ...

You could then make a new node entity with `entity_create`( See Creating and Editing Entities Documentation ) just passing the bare parameters you want: NID, type, bundle.

Then you could do a `node_load()` and then a `node_save()` with your code above to actually build out the rest of the node ...

That's what I would try.
> 3 votes

---
Tags: nodes
---


# Question
Title: Files in Media and Plupload module not showing in content selector
I've got the Media module installed along with Plupload. I go to the Media listing, click Add File, then I drop 3 files onto the Drag and Drop area. They show up correctly and I click Upload. They all upload correctly and the Media listing reloads and they all show up.

However, when I go to add Content and click Select Media to choose those files they are not listed.

If I go to the Media List, click Add File and then I use the File Selector to select those same 3 files and upload them that way... it works properly and I can choose them in the Content Select Media popup.

I've verified this on Chrome and Firefox. Am I doing something wrong? Has anyone run into this before? I'll post this as an issue on the Media module, but I figured maybe someone here had experienced this.

# Answer
> 1 votes
Upgrade to the latest 2.x-dev versions of media and file\_entity modules. I doubt you will see this issue anymore.

---
Tags: 7, media
---


# Question
Title: Multiple/Bulk Image Upload Tutorial? Plupload etc
I want my users to be able to upload multiple images at once. They need to be able to upload 60 images for one gallery and doing that one at a time is just not feasible. I've been reading other posts here and doing a ton of searches. I'm told that using the Media module and plupload (I have the javascript library and the drupal integration module installed) that I can do it, but I can't figure out how to actually make it work.

Would anyone be willing to explain it below? I've seen at least one video on youtube that shows the person clicking the Select Media button which pops up a little window, and that window has a drag and drop plupload area where they drop their images. I don't see anything like that.

# Answer
> 7 votes
Install Multiupload Filefield Widget and, if you're so inclined, Multiupload Imagefield Widget.

Make sure your PHP upload limit will allow all the files to upload.

# Answer
> 0 votes
I would try using http://drupal.org/sandbox/fangel/1652676 Media Multi-select module.

# Answer
> -4 votes
In Drupal 7 You can't add a bulk upload field to content types because it does not support CCK. According to this post others want to do this too. There are several side projects but nothing official.

Bulk upload only works as a stand alone tool that creates individual nodes under "create content."

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


title: Modules update failed

text:
# Question
Title: Modules update failed
I just tried to update some Modules on drupal 7 and got this:

> Update failed! See the log below for more information. Your site is still in maintenance mode.
>
> ckeditor
>
> ```
> Error installing / updating
> File Transfer failed, reason: Cannot remove file /home/myinvoice/public_html/sites/all/modules/ckeditor/ckeditor/plugins/dialog/dialogDefinition.js.
>
> ```
>
> imce
>
> ```
> Error installing / updating
> File Transfer failed, reason: Cannot remove file /home/myinvoice/public_html/sites/all/modules/imce/tpl/imce-file-list.tpl.php.
>
> ```
>
> menu\_token
>
> ```
> Error installing / updating
> File Transfer failed, reason: Cannot remove file /home/myinvoice/public_html/sites/all/modules/menu_token/menu_token.module.
>
> ```
>
> recaptcha
>
> ```
> Error installing / updating
> File Transfer failed, reason: Cannot remove file /home/myinvoice/public_html/sites/all/modules/recaptcha/recaptcha.install.
>
> ```
>
> Next steps
>
> ```
> Your modules have been downloaded and updated. - DOES THIS MEAN THAT IT DID IN FACT WORK???
> Run database updates
>
> ```

# Answer
Your site will most likely work, but with some bad luck the files could cause errors. The reason is either a file permission issue or, less likely, that you had the files open and that they were locked for that reason.

To be on the safe side you should manually update the affected modules, i.e. delete the directory and replace it with a downloaded copy. Then run the update script.

Do this for the affected ones:
> 0 votes

---
Tags: updating
---


# Question
Title: How can I add multilingual taxonomy breadcrumbs?
I have a site with two languages and a large number of taxonomy terms. I want to use breadcrumbs on my taxonomy pages, but I can't find a system that works well with multiple languages.

I translated my taxonomy terms with the Entity Translation module, using the field method. What can I do?

# Answer
You can do this by making a content pane in Views. Here's what you need to do.

1. For hierarchical taxonomies, determine the maximum depth. Example: United States -\> Illinois -\> Chicago (child, parent, and grandparent)
2. Create a view showing fields of taxonomy terms. Add a contextual filter: *Taxonomy term: Term ID*. For **When the filter value is NOT available**, choose *Provide default value* of *Taxonomy term ID from URL* and leave *Load default filter from term page* checked.
3. Add a relationship of *Taxonomy term: parent term*. Do this as many times as you need to get to the maximum possible depth. Do not require the relationship because the term may be a root term. To make sure that you can keep track of all the relationships even though they will be of the same type, when adding the relationship, click *More* at the bottom of the add dialog and type in an appropriate name (parent, grandparent, great-grandparent, etc.) for the **Administrative title**.
4. Add the taxonomy term name field (the one provided by the Title module, since we are using Entity translation). Don't use a relationship. As the administrative title, set "current page term" or something easy to remember.
5. Now to get the parent and grandparent terms. First, add a term id for each relationship (parent, grandparent, etc.) Make sure to uncheck *create a label* and check *Exclude from display*. Make sure to set the proper relationship for each tid.
6. Then, add the taxonomy term name field again as many times as necessary so that you have a name field for each relationship. Again, make sure to set the relationship each time you add a new field. Also, for each term name that has a relationship, make sure that *Hide rewriting if empty* is checked under **No results behavior**. Under **Rewrite results**, check *Output this field as a link* and enter `taxonomy/term/[tid]` where `[tid]` is the replacement pattern for the appropriate relationship.
7. Reorder the fields from "oldest" (grandparent) to "youngest" (current term).
8. Under **Format**, click *Settings* next to *Fields*. Check the boxes next to all of the non-tid fields to make them inline fields. Add the separator of your choice and you're done!
> 0 votes

---
Tags: taxonomy-terms, i18n-l10n, breadcrumbs
---


# Question
Title: Can't get drupal_array_get_nested_value to work
I'm trying to use this helper function drupal\_array\_get\_nested\_value and I can't seem to get it to run. http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_array\_get\_nested\_value/7 I have a specific field type I am looking for, and I can find it using a recursive array search, but I would rather use the helper function. Essentially this is what I want

```
$field_type = "my_field_type";
$value = drupal_array_get_nested_value($field_type, $form);

```

but that is not working, it's wants me to pass an array. How can I use this function to search for a string, or am I using the wrong function?

# Answer
> 1 votes
The function actually takes an array as the input and the first value is the array to be searched.

so your code should be as follows

```
$field_type = array('my_field_type');
$value = drupal_array_get_nested_value($form,$field_type);

```

---
Tags: forms
---


# Question
Title: Right way to redirect to paypal with data
I am altering the user registration form and sending the user to paypal on submission. I am fetching all the values and sending them in query. But when I am returning from there...I am not getting anything in $\_POST variable...

I am wondering...what can be wrong here in my sending process. Here is my code --

```
//Form alter for registration form.
function user_type_register_form_alter(&$form, &$form_state, $form_id){
  switch($form_id) {
      case 'user_register_form':
        $form['account']['user_type'] = array(
          '#type' => 'select',
          '#title' => t('Membership Type:'),
          '#options' => array(
            0 => t('General $50.00/Yr'),
            1 => t('Student $50.00/Yr'),
            2 => t('Government $50.00/Yr'),
            ),
           '#weight' => 1,
           '#description' => t('Select the membership type, which you want to have.'),
          );
        $form['account']['user_type_submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
          '#submit' => array('user_type_register_form_submit'),
          '#validate' => array('user_type_register_form_alter_validate'),
          '#weight' => 10,
        );
        $form['account']['name']['#description'] = t('');
        $form['account']['mail']['#description'] = t('');
        $form['#method'] = 'post';
        unset ($form['actions']); //unset the default submit Button
        return $form;
      break;
    }
}

function user_type_register_form_submit($form, &$form_state){
  global $base_url;
  $username = $form_state['values']['name'];
  $user_email = $form_state['values']['mail'];
  $user_pass = $form_state['value']['password'];
  $user_type = $form_state['values']['user_type'];
  $user_first_name = $form_state['values']['field_first_name']['und'][0]['value'];
  $user_last_name = $form_state['values']['field_last_name']['und'][0]['value'];
  $user_company_name = $form_state['values']['field_company_name']['und'][0]['value'];
  $user_address_line_1 = $form_state['values']['field_address_line_1']['und'][0]['value'];
  $user_address_line_2 = $form_state['values']['field_address_line_2']['und'][0]['value'];
  $user_city = $form_state['values']['field_user_city']['und'][0]['value'];
  $user_state = $form_state['values']['field_user_state']['und'][0]['value'];
  $user_zip = $form_state['values']['field_user_zip']['und'][0]['value'];
  $user_phone_number = $form_state['values']['field_phone_number_']['und'][0]['value'];
  $user_mobile_number = $form_state['values']['field_mobile_number_']['und'][0]['value'];
  $user_fax_number = $form_state['values']['field_fax_number_']['und'][0]['value'];

  $paypal = array();
  $paypal['cmd'] = '_xclick';
  $paypal['business'] = 'rajeev_1359782736_biz@gmail.com';
  $paypal['page_style'] = 'Primary';
  $paypal['bn'] = 'PP-DonationsBF';
  $paypal['item_name'] = 'Membership';
  $paypal['currency_code'] = 'USD';
  $paypal['no_shipping'] = '1';
  $paypal['tax'] = '0';
  $paypal['lc'] = 'US';
  $paypal['rm'] = '1';
  $paypal['notify_url'] = $base_url.'/?q=paypal/payment';
  $paypal['return'] = $base_url.'/?q=paypal/payment';
  $paypal['cancel_return'] = $base_url.'/?q=user/register';
  $paypal['uname'] = $username;
  $paypal['email'] = $user_email;
  $paypal['pass'] = $user_pass;
  if($user_type == 0){
    $paypal['user_type'] = 'General';
  }
  elseif($user_type == 1){
    $paypal['user_type'] = 'Student';
  }
  elseif ($user_type == 2){
    $paypal['user_type'] = 'Government';
  }
  $paypal['first_name'] = $user_first_name;
  $paypal['last_name'] = $user_last_name;
  $paypal['comp_name'] = $user_company_name;
  $paypal['address1'] = $user_address_line_1;
  $paypal['address2'] = $user_address_line_2;
  $paypal['city'] = $user_city;
  $paypal['state'] = $user_state;
  $paypal['zip'] = $user_zip;
  $paypal['phone'] = $user_phone_number;
  $paypal['mobile'] = $user_mobile_number;
  $paypal['fax'] = $user_fax_number;

  switch($user_type){
    case '0':
      //dpm("General");
      $membership_price = 10;
      $paypal['amount'] = $membership_price;
      $paypal['item_number'] = 1;

      $query = http_build_query($paypal, '', '&');

      //watchdog('Query--',$query);

      $form_state['redirect'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr?' .$query;

      break;

    case '1':
      //dpm("Student");
        $membership_price = 12;
      $paypal['amount'] = $membership_price;
      $paypal['item_number'] = 2;

      $query = http_build_query($paypal, '', '&');

      $form_state['redirect'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr?' .$query;
      break;

    case '2':
      //dpm("Government");
      $membership_price = 15;
      $paypal['amount'] = $membership_price;
      $paypal['item_number'] = 3;

      $query = http_build_query($paypal, '', '&');

      $form_state['redirect'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr?' .$query;
      break;
  }

}

```

Anybody have any idea about it ?

# Answer
It doesn't look like a Drupal problem, but your wrong HTML variable for PayPal. You should use `rm = 2` for POST.

```
$paypal['rm'] = '2';

```

Here is the description for its value:

> Allowable values are:
> 0 – all shopping cart payments use the GET method
> 1 – the buyer’s browser is redirected to the return URL by using the GET method, but no payment variables are included
> 2 – the buyer’s browser is redirected to the return URL by using the POST method, and all payment variables are included
> The default is 0.
> NOTE:
> The`rm`variable takes effect only if the return variable is set.
> 1 votes

---
Tags: 7, forms, payment-gateways
---


title: Where to set the DOCTYPE?

text:
# Question
Title: Where to set the DOCTYPE?
My zen subtheme doctype is currently !DOCTYPE html and I would like to change this. What is the correct place to add the doctype I want to use?

I copied the html.tpl.php file and pasted it into the templates directory of my subtheme thinking that's where it's set, but it's not being picked up...

# Answer
You're in the correct place (html.tpl.php) to modify the doctype assuming you're using Drupal 7, thats the default theme implementation for altering the basic page structure (documentation). In Drupal 6, you're looking for the page.tpl.php file.
> 2 votes

---
Tags: theming
---


# Question
Title: How to restrict a specific user to an IP range he can login from?
I want to create a subscription service where the user can only login with the IP address the user registered with and all Class C & D's of that IP range. How can this be done?

Would also be great if I can restrict the user to logging in from withing that state if possible.

# Answer
> 5 votes
Have a look at IP Ranges module.

> IP Ranges is a module that let's you completely ban both single IP-addresses as well as full ranges from your site. The ban is triggered already at the early bootstrap phase, so you can get rid of unwanted visitors as early as possible without wasting server resources.
>
> You can also define whitelists that override blacklists, both single and ranged. The UI is similar to core ip-ban, so you will feel like home immediately.

---
Tags: users
---


# Question
Title: how to make a page with record displayed from database
I am using a cutom module to display records from database.code below fetches all the record from database table but does not know how to display it on a page in my Drupal site (version 7):

---

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

  $items['form/formModule'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Form', //page title
    'description' => 'A form with a text field and Submit button.',
    'page callback' => 'formModule_intro', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form

    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['form/formModule/form1'] = array(
    'title' => 'Form One',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formModule_form'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'weight' => 1,
  );

  $items['form/formModule/reviewOrder'] = array(
    'title' => 'Review Order',
    'page callback' => 'formModule_page',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'weight' => 2,
  );

  return $items;
}

function formModule_page() {
return array('#markup' => '<p>' . t('Review Order: The table below shows the TOTAL STOCK and TOTAL QUANTITY of product purchased.') . '</p>');

  $query = db_select('formmodule_order', 't'); // Using the TableSort Extender is what tells the
  $query->fields('t');
  $result = $query->execute()->fetchAll();

 $rows[] = array('data' => (array) $row);

  foreach ($result as $key => $row) {
  $rows[$key] = array();

  foreach($row as $col) {
   $rows[$key][] = array('data' => $col);

   }
  }
drupal_set_message("<pre>" . print_r($rows, true) . "</pre>");

}

```

---

iam using the following code to dispaly it on a page but no results:

---

```
$header = array(
    // The header gives the table the information it needs in order to make
    // the query calls for ordering. TableSort uses the field information
    // to know what database column to sort by.
    array('data' => t('S.No.'), 'field' => 't.S.No.'),
    array('data' => t('Product Name'), 'field' => 't.Product Name'),
    array('data' => t('Total Stock'), 'field' => 't.Total Stock'),
    array('data' => t('Total Purchasing'), 'field' => 't.Total Purchasing'),

  );
 drupal_set_message("<pre>" . print_r($header, true) . "</pre>");**/
  $query = db_select('formmodule_order', 't'); // Using the TableSort Extender is what tells the

            // the query object that we are sorting.
  $query->fields('t');

//drupal_set_message("<pre>" . print_r($query, true) . "</pre>");

 $result = $query->execute()->fetchAll();

// drupal_set_message("<pre>" . print_r($result, true) . "</pre>");

  foreach ($result as $key => $row) {
  $rows[$key] = array();
   foreach($row as $col) {
   $rows[$key][] = array('data' => $col);
   }
  }
drupal_set_message("<pre>" . print_r($rows, true) . "</pre>");
  // build the table for the nice output.
  $build['formmodule_order'] = array(
    //'#theme' => 'table',
    //'#header' => $header,
    '#rows' => $rows,
  );

 drupal_set_message("<pre>" . print_r($build, true) . "</pre>");
  return $build;

```

---

what is wrong in the code?

# Answer
Probably because before anything has a chance to print you are already returning `#markup` from `formModule_page()`. You might also want to use the Devel module's `dpm()` function for more cleaner and convenient debug messages and variable inspection.
> 0 votes

---
Tags: forms
---


title: How to Disable Profile2 Field Elements

text:
# Question
Title: How to Disable Profile2 Field Elements
I would like to disable some form elements within a Profile2 form in Drupal 7 (ie still visible but not editable). I figured using hook\_form\_alter would be the way to go but I can't figure out where I need to set the \['disabled'\] field to true.

Here is the code that I have:

```
$fields = field_info_instances('profile2', 'student')
if ($fields) {
  foreach($fields as $field) {
    $field['#disabled'] = true; <- don't know what attribute to set here
  }
}

```

In Drupal 6 this seemed pretty straight forward but using dsm($field) is not helping me determine what field attributes need to be set. I have Googled this and looked at the Drupal 7 API and I am still lost.

I am hoping someone can help me out here.

Thanks.

# Answer
In drupal 7. You can use the "field permissions" module + profile2 module.
In order to disable some fields for anonymous user, you just edit the fields with custom permissions.
You can see the demo of configuration page from here :

Currently to disable some fields from profile2 for register form, I just set permissions that don't allow the anonymous user to see that fields.
> 3 votes

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


# Question
Title: dpm function doesn't display results for arrays
I need to work over the hook\_menu\_alter function and I found that the dpm() function is not working for arrays. I have devel and admin\_devel enabled. I flushed all cache to make sure the hook is fired.

```
function MY_MODULE_menu_alter(&$items) {
  dpm('hello'); // This is printed
  dpm($items); //This one is not printed at all
}

```

# Answer
> 0 votes
`hook_menu_alter()` is fired directly in the same call that flushes the caches - and only once. If you do that via `drush cc all` the result is never displayed.

---
Tags: debugging
---


# Question
Title: How can I print $submitted in a region template?
I have a region--content.tpl.php and am trying to figure out how to print the $submitted variable (usually printed in node.tpl.php).

--- EDIT ---

Including here the final code I used. This lets you print out the themed user link where as the original code only printed the name as plain text.

```
function theme_preprocess_region(&$vars) {
  if ($vars['region'] == 'content') {
    $node = menu_get_object();
    $user = user_load($node->uid);

    if ($node) {
      // Adapted from template_preprocess_node().
      $vars['submitted'] = 'By ' . theme('username', array('account' => $user)) . ' | ' . format_date($node->created, 'short');
    }
  }
}

```

# Answer
> 1 votes
The region template has no concept of the page context, so it doesn't know about the node by default.

You can give it that context by implementing `hook_preprocess_region()` in your theme's template.php file (or a module file), and seeing if there's a node available there:

```
function MYTHEME_preprocess_region(&$vars) {
  if ($vars['region'] == 'region_name') {
    $node = menu_get_object();

    if ($node) {
      // Adapted from template_preprocess_node().
      $vars['submitted'] = t('Submitted by !username on !datetime', array('!username' => $node->name, '!datetime' => format_date($node->created)));
    }
  }
}

```

After you clear the caches, your region template on node pages should have the `$submitted` var available to it. Obviously that might need a bit of tweaking to suit your needs.

---
Tags: 7, theming
---


title: How to empty a taxonomy?

text:
# Question
Title: How to empty a taxonomy?
I have been messing around with data migration and I ended up with a rather corrupted taxonomy with the wrong terms in it.

I would like to completely delete the terms inside the taxonomy. I have not found any drush command for doing it. A module search was also unsuccessful, in fact I found a dead one named cleantaxonomy.

I can try to build a SQL query to do this but I am sure someone stepped into this before.

# Answer
Taxonomy Manager makes that pretty easy:

> This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.

Or you could do it manually:

```
foreach (taxonomy_vocabulary_load_multiple(FALSE) as $vocab) {
  taxonomy_vocabulary_delete($vocab->vid);
}

```

If you have a lot of vocabs/terms it would be better to split that up into a batch job to avoid out of memory errors.
> 3 votes

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


title: How do I display a block on a page

text:
# Question
Title: How do I display a block on a page
I simply want to display a table generated from an external database on a page. In researching this I found it would be easiest to do it by writing a module. Using a tutorial I created a block module that does what I want, but I can't figure out how to make a block module appear on a normal page. This must be something people do on a regular basis. This is version 7.

Is there such a thing as a page module rather than a block module?

Thanks, Jim

Just to extend this a bit, eventually I want to be able to add a select form element and perhaps write a bit of javascript (jQuery calls) to change the query that generates the table, etc. But for now just to be able to display the table on a node/page would be fine.

# Answer
There are a couple of ways to tackle this...

1. If you're coding the node content yourself you can use the following snippet to get the output of a particular block into a string:

```
$block = block_load($module, $delta);
$render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
$output = render($render_array);

```
2. There's the Block Reference module

> Defines a field type Block reference which creates a relationship to a block and allows the block to be displayed as the content of the field. It saves this relationship using the block's bid, not its delta + module.
> 1 votes

# Answer
You can render a block using the following code snippet in your template file.

```
<?php
$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);
?>

```

The template file would be **page.tpl.php** for every page, but for a specific page, let's say your have a page **node/13**, you may have a custom page template **page--node--13.tpl.php** for that page.

But I think the good practice is to create a variable in `hook_preprocess_page()` and make it avaibable to the template. Then print it in **page.tpl.php**.

```
function MYTHEME_preprocess_page(&$variables) {
    if(isset($variables['node']) && $variables['node']->nid == 13){
        $block = module_invoke('module_name', 'block_view', 'block_delta');
        $variables['myblock'] = render($block['content']);
    }
}

```

OR, another way is to use the Panel module to create a custom page in which you can create layouts and place any content such as blocks, nodes, views, forms, etc.

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.
> 0 votes

# Answer
You can also add the block directly in your body, using Insert Block module :

> \[block:name of module=delta of block\]
>
> ...will insert the contents of a rendered sidebar block into the body of your node. If no delta is specified, the default block for that module will be displayed.
> 0 votes

---
Tags: blocks
---