# Question
Title: Execute user_save() after the form submission handler
In my implementation of `hook_form_alter()` I am using the following code; it executes `mymodule_user_form_submit()` before `user_save()`.

```
array_unshift($form['#submit'], 'mymodule_user_form_submit');

```

`user_save()` is not executing after that.

What is the problem with this code?

I want to execute `user_save()` after `mymodule_user_form_submit()`.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_register_form') {
    drupal_set_message("Form ID is : " . $form_id);
    //$form['#submit'][] = 'custom_user_form_submit';
    array_unshift($form['#submit'], 'mymodule_user_register_submit');
  }

}

function mymodule_user_register_submit(&$form, &$form_state) {
//code goes here
$form_state['field_magentopass']['und'][0]['value'] = $form_state['values']['pass'];
}

```

if the code is wrong how can i assign the value to this variable `$form_state['field_magentopass']['und'][0]['value']`

or this entire method is wrong? should i go for any other alternatives?

# Answer
In your code, your submit handler ( `mymodule_user_register_submit` ) and actual function name ( `custom_user_form_submit` ) are different.

Also, your submit handler is using

```
$form_state['field_magentopass']

```

instead of

```
$form_state['values']['field_magentopass']...

```

It should be something like

```
/**
 * Implements hook_form_FORM_ID_alter
 * User register form id: user_register_form
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  drupal_set_message("Form ID is : " . $form_id);
  array_unshift($form['#submit'], 'mymodule_user_register_submit');

}

function mymodule_user_register_submit(&$form, &$form_state) {
  $form_state['values']['field_magentopass'][LANGUAGE_NONE][0]['value'] = $form_state['values']['pass'];
}

```

UPDATE: OP changed their question to use matching function names. Apparently new $user is saved, but field\_magentopass wasn't updated.

Lastly, an alternative approach, based on form\_set\_value and the #validate handler

```
/**
 * Implements hook_form_FORM_ID_alter
 * User register form id: user_register_form
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  drupal_set_message("Form ID is : " . $form_id);
  $form['#validate'][] = 'mymodule_user_register_validate';

}

function mymodule_user_register_validate($form, &$form_state){
  $form['field_magentopass']['#parents'] = array('field_magentopass');
  form_set_value($form['field_magentopass'], array(LANGUAGE_NONE => array(0 => array('value' => $form_state['values']['pass']))), $form_state);
}

```
> 1 votes

# Answer
You have to generate an user object in your submit function. pass this object in user\_save within same function only.
> -1 votes

---
Tags: users
---


title: How to maintain a custom block content?

text:
# Question
Title: How to maintain a custom block content?
I have created a block using a custom module.

In the block, I have static text which will vary by time; thus, I will have to let the content manager decide when to modify the static text.

Could any one tell what is the best approach should I follow?

Note: I don't want the content manager to edit the text from the code.

# Answer
> 0 votes
have you considered adding a standard HTML block at

Admin \> Structure \> Blocks \> Add Block ?

`/admin/structure/block/add`

Drupal provides a standard interface for editing the HTML block content.

Alternatively, if you have PHP code, combined with alot of static text in the block, you could load a node into it instead, and use regular node editing for maintaining that text content.

e.g, in `hook_block_view`

```
$node = node_load($nid); // Load the text content from node
// PHP logic to build some content...
// ...
$block['content'] = $data; // php content
$block['content'] .= render(node_view($node)); // node content

```

---
Tags: forms
---


# Question
Title: Selective CSS Aggregation for fast D7 development performance
On D6, we had the this module. Depite the module's name, it has an *hidden* extra feature to optimizes all CSS files *except* for the module or theme being actively developed. This has the benefit of performance (since all files except the actively developed file are compressed) yet allows for quick development.

Which alternative exists for Drupal 7?

# Answer
At this time, it appears this module is not needed for Drupal 7 this has been committed and fixed in D7 core.

refer to this:

IE: Stylesheets ignored after 31 link/style tags

==========
css aggregation of all stylesheets EXCEPT certain one. just add this to your theme's template file

```
drupal_add_css(drupal_get_path('theme', 'mytheme') . '/css/custom.css', array(
'group' => CSS_DEFAULT,
'preprocess' => FALSE,
'every_page' => TRUE
));

```
> 1 votes

---
Tags: theming, performance, css-js-aggregation
---


# Question
Title: How to show breadcrumbs for taxonomy terms in Drupal 7
I've just now started working on D7 but I can't figure out how to display the terms in the breadcrumbs as we do in D6( I guess using Taxonomy breadcrumb). Taxonomy breadcrumb module for D7 is in dev release.

# Answer
> 0 votes
Use Taxonomy Menu Trails module. its better than 'Taxonomy breadcrumb'.

---
Tags: 7, breadcrumbs
---


title: Complicated Drush setup with MAMP

text:
# Question
Title: Complicated Drush setup with MAMP
Since two weeks I have replaced my optical hard drive with an SSD for my OS and all my applications while I kept my hard drive for data. So I've installed MAMP on my SSD and my Drupal directory (workspace within Eclipse) is on the Macintosh HD.

So,
Path to MAMP: `/SSD/Applications/MAMP`
Path to Drupal: `/Macintosh\ HD/Users/me/Documents/workspace/drupal`

I've put the drush folder `/Macintosh\ HD/Users/me/Documents/workspace/drush` and drush is working just fine, but for some reason, whenever I download a module by using drush, the module ends up in my homefolder while it should be using my Drupal folder I think, right?

How can I fix this and make drush work with my Drupal directory?

# Answer
> 3 votes
Try using a aliases.drushrc.php file to specify project details.

Create an `aliases.drushrc.php` file in one of the following places:

1. /etc/drush
2. $HOME/.drush

If you don't have `/etc` for `/etc/drush` perhaps it would work in: `/Macintosh\ HD/Users/me/Documents/workspace/drush`

`aliases.drushrc.php` contents

```
<?php
$aliases['dev'] = array(
  'uri' => 'dev.example.com',
  'root' => '/Macintosh HD/Users/me/Documents/workspace/drupal',
);

// or perhaps root with the escaped space char '/Macintosh\ HD/Users/me/Documents/workspace/drupal'

```

then from anywhere in the filesystem, you should be able to go

* drush @dev dl views
* drush @dev sqlc
* drush @dev updb

etc..

Fully commented example drush aliases file here

---
Tags: 7, drush
---


# Question
Title: Cannot access data passed to $vars in theme function
I have got a problem in my template.php file, where I am trying to add data to $vars. I basically have a preprocess function for a view and in it I am trying to pass some extra info to $vars. However, the view is not getting those variables. This is what I have in my template.php file:

```
/**
  * Generic preprocess that is still working on D7
  */
function mytheme_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name)) {
    $function = __FUNCTION__ . '__' . $vars['view']->name . '__' . $vars['view']->current_display;
    if (function_exists($function)) {
     $function($vars);
    }
  }
}

/**
* preprocess variables for the badge owners view
*/
//function mytheme_preprocess_views_view__badge_owners (&$vars) {
function mytheme_preprocess_views_view_fields__badge_owners__page_1(&$vars) {
  $bid = $vars['view']->args[0];

  //Get the badge info
  $badge = db_query("
    SELECT ubb.bid, ubb.weight, ubb.name, ubb.image, ubb.href,
    ubb.unhideable, ubb.fixedweight, ubb.doesnotcounttolimit, ubb.tid
    FROM {user_badges_badges} ubb
    WHERE ubb.bid = :bid", array(
      ':bid' => $bid
  ))->fetchObject();

  $vars['bid'] = $bid;
  $vars['name'] = $badge->name;
  $vars['badge'] = theme('user_badge', array('badge' => $badge));
  $vars['an_extra_variable'] = 'hope this shows up in $vars';

  drupal_set_title(t('Badge: @badge_name', array('@badge_name' => $badge->name)));
}

```

This is what I have in my views-view--badge-owners.tpl.php file:

```
<?php
/**
* Variables available:
* - $css_name: A css-safe version of the view name.
* - $header: The view header
* - $footer: The view footer
* - $rows: The results of the view query, if any
* - $empty: The empty text to display if the view is empty
* - $pager: The pager next/prev links to display, if any
* - $exposed: Exposed widget form/info to display
* - $feed_icon: Feed icon to display, if any
* - $more: A link to view more, if any
* - $admin_links: A rendered list of administrative links
* - $admin_links_raw: A list of administrative links suitable for theme('links')
*
* @ingroup views_templates
*/
?>
<div class="view view-<?php print $css_name; ?> view-id-<?php print $name; ?> view-display-id-<?php print $display_id; ?> view-dom-id-<?php print $dom_id; ?>">
  <?php if (isset($admin_links)): ?>
    <div class="views-admin-links views-hide">
      <?php print $admin_links; ?>
    </div>
  <?php endif; ?>

  <div class="view-header clearfix">
  <div class="mytheme-badge-owners-badge"><?php print $badge;?></div>
</div>

  <?php if ($exposed): ?>
    <div class="view-filters">
      <?php print $exposed; ?>
    </div>
  <?php endif; ?>

  <?php if ($attachment_before): ?>
    <div class="attachment attachment-before">
      <?php print $attachment_before; ?>
    </div>
  <?php endif; ?>

  <?php if ($rows): ?>
    <div class="view-content">
      <?php print $rows; ?>
    </div>
  <?php elseif ($empty): ?>
    <div class="view-empty">
      <?php print $empty; ?>
    </div>
  <?php endif; ?>

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

  <?php if ($attachment_after): ?>
    <div class="attachment attachment-after">
      <?php print $attachment_after; ?>
    </div>
  <?php endif; ?>

  <?php if ($more): ?>
    <?php print $more; ?>
  <?php endif; ?>

  <?php if ($footer): ?>
    <div class="view-footer">
      <?php print $footer; ?>
    </div>
  <?php endif; ?>

  <?php if ($feed_icon): ?>
    <div class="feed-icon">
      <?php print $feed_icon; ?>
    </div>
  <?php endif; ?>

</div> <?php /* class view */ ?>

```

Any help would be appreciated. Thanks.

# Answer
OK, it looks as though you're using the $badge variables in a more general parent/container views template, when the $badge variables are added in a child template preprocess function. The tpl variables aren't available at that container point.

The solution is to implement

hook\_preprocess\_views\_view

and add the badge data vars there instead.

e.g

```
THEMENAME_preprocess_views_view(&$vars){
  if (isset($vars['view']->name)) {
    switch($vars['view']->name){
      case 'badge_owners':
        if($vars['view']->current_display == 'page_1'){
          // Rename current function to this
          THEMENAME_preprocess_views_view_badge_owners_page_1($vars);
        }
      break;
    }
  }
}

```
> 1 votes

---
Tags: theming, users
---


title: Is the lower version update required?

text:
# Question
Title: Is the lower version update required?
When I upgrade a site from Drupal 6 to Drupal 7, is it necessary to upgrade version by version, or can we directly upgrade to Drupal 7?

# Answer
> 4 votes
It is strongly recommended that you upgrade to the *latest* version of Drupal 6 before trying to upgrade to Drupal 7. Make sure you read the text under "MAJOR VERSION UPGRADE" in the file `UPGRADE.txt`that comes with Drupal 7 - it is also online. You should be able to go from where you are directly to the latest Drupal 6 version (currently 6.27) - there is no need to go through intermediary minor versions. And you can go directly from the latest Drupal 6 to the latest Drupal 7 (currently 7.18).

Before you start, disable and uninstall all contributed modules you don't need. Also disable and uninstall all modules (such as CCK) that say upfront that no upgrade path exists. If a module offer an export/import feature (e.g. Biblio), then use it. Export all content from Drupal 6, then disable and uninstall the module. Reinstall the module and import the data when your Drupal 7 configuration is stable.

For all contributed modules that remain installed at this point, make sure you upgrade them to their latest stable Drupal 6 version before you start.

Also make sure you make a backup of *everything* before starting. You may have to go through the upgrade several times. In your first attempts you will discover contributed modules that break your site when you upgrade. You must disable and uninstall those, and then try again. Repeat as many times as necessary.

Depending on the complexity of your site, you may want to fasten your seatbelts. It's going to be a bumpy night.

Upgrading a stripped core configuration is fairly painless. But not all contributed modules has a (working) upgrade path. In particular, if you've used CCK, expect that some data does not make it into Drupal 7 automatically. (I ended up writing my own DB conversion scripts using flat text files as intermediaries - and in some cases: scraping content and pasting it back into the upgraded site).

---
Tags: upgrading
---


# Question
Title: How to customize registration process in Drupal 7?
I want to customize default registration process in Drupal 7. The registration process includes 3 steps:

1. Show some account types (in a page or form?). For example "personal", "business", "organization"... And users will choose their own account type.
2. Fill information into registration form. Each account type which users choose in step 1 has some corresponding fields.
3. Finish registration with an confirmation email or something else.

The registration process is similar to https://secure.payza.com/signup

Thank you for helping.

# Answer
> 1 votes
You can create three roles named:

* Personal
* Business
* Organization

Now you can use profile2 Registration Path module. This module will give you three separate profile for each roles. You can add separate fields for each profile. And from the configuration of profile pages you can enable separate registration path also.

Thus you can have three registration path for three roles and three registration forms also.

Now to create multistep form for profile2 module you can follow this question from this site.

# Answer
> 0 votes
That requires quite a lot customization.

Here is a tutorial you may find helpful.

http://grasmash.com/article/building-multistep-registration-form-drupal-7

And there is an module for that:

Multi-step forms: http://drupal.org/project/mforms

---
Tags: users
---


# Question
Title: Children links disappear when access to parent blocked
When blocking access to a page -- its child links get skipped both in code and display.

The block is achieved via an access callback attached to the menu item that checks whether the user is logged in or not.

The desired behavior is to show the links regardless of the login status.

Any hints?

P.S. I'm using drupal6

# Answer
> 0 votes
With the caveat you should be very careful adjusting any core menu item permissions, and I'm presuming you know what you're doing there, it is possible to adjust any menu with

hook\_menu\_alter

for example:

```
function mymodule_menu_alter(&$items) {
  // Enable open access for everyone to foo/bar
  $items['foo/bar']['access callback'] = TRUE;
}

```

You can also specify your own access callback there, e.g

```
function mymodule_menu_alter(&$items) {
  // Add custom access callback to foo/bar
  $items['foo/bar']['access callback'] = 'mymodule_special_access';
}

function mymodule_special_access(){
  global $user;
  if($some_condition_is_true){
    return TRUE;
  }
  return FALSE; // default deny
}

```

---
Tags: 6, routes
---


# Question
Title: How do I hide the title when creating/editing a specific type of content?
Here's what we'd like to do when create/edit node of specific type of content (we have 2 specific types, let's call them "type A" and "type B"):

* hide the title (= the user can change all fields but *not the title*)
* show a combo box to choose an item (lot of items, and this field is a long name)
* depending on the **type** of the content, when validating the node, update the title like this: `title = name of the item + " - " + type of the content`

Example:

User creates a node of "type B". He chooses the item called "The item XYZ long name" and validates `=>` the title of the node is auto-magically created: `The item XYZ long name - Type B`.

Any idea how to do this (I don't know how to hide the title when creating/editing a node as well)?

# Answer
> 3 votes
A great module you can use is Auto NodeTitle :

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.
>
> When the token module is installed it's possible to use various node data for the auto generated title - e.g. use the text of a CCK field (since 5.x).
>
> Advanced users can also provide some PHP code, that is used for automatically generating an appropriate title.

---
Tags: nodes
---


# Question
Title: Conditional field in node type depending on user profile
I have a site with two user profiles (group/single). I have a node type repertoire with a field function which I only need for the profile single (mandatory field). Is there a way to hide this field when a user with profile group is adding a node? I don't want to make two different content types with only one little difference. Thanks in advance!

# Answer
> 1 votes
If you want to hide a field from particular role via a contrib module, you can try

http://drupal.org/project/field\_permissions

or if you're comfortable in code, see

hook\_field\_access

e.g:

```
function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'field_of_interest' && $op == 'edit') {
    // TODO: some special access check for TRUE or FALSE in $access
    return $access;
  }
  return FALSE; // default deny
}

```

---
Tags: users
---


# Question
Title: log / capture all the queries executed in drupal
I want to log / capture all the queries executed by the drupal?
update, select, insert any query, is there any hook or what will be the method to do this.

# Answer
You want Devel.

It has a lot of helpful tools for Drupal developers, including a helper function to print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took.
> 2 votes

# Answer
Note that Drupal can generate a lot of queries for a single page view. So if you don't want to be doing anything programmatic with the queries then maybe a better option is to just log everything with the MySQL query log.
> 0 votes

---
Tags: hooks
---


title: How to backup just a node?

text:
# Question
Title: How to backup just a node?
I need to backup just a node. Usually I get this by searching the info of the node in the database but I'm just wondering if the **backup and migrate module** could help to do it?

# Answer
> 3 votes
You could export it with Node export module.

> This module allows users to export nodes and then import it into another Drupal installation, or on the same site.
>
> Using this module you can save yourself a lot of time setting up new websites that have similar nodes to websites you've already made, migrating nodes to new Drupal versions, or between development/staging/production sites.

# Answer
> 2 votes
You could potentially load a node and serialize it to file

e.g

```
$nid = 12;
$node = node_load($nid);
// This converts the node object to a string
$data = serialize($node);
// Now save the file
$filename = date("Y-m-d").'_node_backup_'.$nid.'.txt';
// Create the backups folder within the files folder.
$filepath = 'public://backups';
$uri = $filepath . '/' . $filename;
// Create the backup file.
file_prepare_directory($filepath, FILE_CREATE_DIRECTORY);
if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
  drupal_set_message("Failed to backup node");
}else{
  drupal_set_message("Successfully created backup of node");
}

```

It could then be loaded from file and unserialized with `unserialize($node);`

---
Tags: nodes, backups
---


# Question
Title: Trying to change the body in presave nodeapi - not working
I'm trying to make a small modification in the body a node when it's saved:

```
function radicalislam_utils_nodeapi(&$node, $op) {
      if ($op == 'presave')
             $node->body = 'test';
}

```

but what I'm getting is strange. when I view the node, i really see only "test" as the body. but when i go edit the post, i see all that previously on the body and "test" appended in the end...

Why is that?

# Answer
> 2 votes
If the body of a node differs from its teaser, it will show both when editing (it'll append the real body to the teaser, which is why it looks like you're still seeing the old version of the body).

In other words: make sure your body *and* your teaser are both altered before saving.

---
Tags: 6, nodes
---


# Question
Title: Translated menu items with menu_build_tree in drupal 7
I'm having an issue with menu item translations with custom rendering of menu tree.

I see all languages displayed at the same time whenever I change the current language. Items have translation set it works if I enable the built-in main menu block but not with my code.

I've tried adding 't($string)' and set 'language' in params; but no luck.

What am I doing wrong here ?

I have the following code in template.php for my theme :

```
function theme_preprocess_page(&$variables) {

    $params = array('max_depth' => 3, 'language' => 'fr');
    $menu = menu_build_tree('main-menu', $params);
    $main_menu_tree = menu_build_tree('main-menu', $params);
    $html = '<ul id="dropdown-menu" class="fixed">';

    if (arg(0) == 'node' && is_numeric(arg(1)))
        $nodeid = arg(1);

    foreach ($main_menu_tree as $item_menu) {//for each main element
        $isSecondLevel = isset($item_menu['below']) && !empty($item_menu['below']);
        $active = '';
        if ($item_menu['link']['link_path'] == 'node/' . $nodeid) { $active = 'active';
        }
        if ($isSecondLevel) {
            $html .= '<li>';
        } else {
            $html .= '<li>';
        }

        $html .= '<a class="' . $active . '" href="' . url($item_menu['link']['link_path']) . '">';
        $html .= $item_menu['link']['link_title'];
        $html .= '</a>';

        //is there any sub elements to display
        if ($isSecondLevel) {
            $html .= '<ul class="sub-menu">';

            foreach ($item_menu['below'] as $item_submenu) {//for each sub element
                $isThirdLevel = isset($item_submenu['below']) && !empty($item_submenu['below']) ? 'main-menu-third_level' : '';

                $html .= '<li>';
                $html .= '<a href="' . url($item_submenu['link']['link_path']) . '">';

                $html .= t($item_submenu['link']['link_title']);

                $html .= '</a>';
                $html .= '</li>';
            }
            $html .= '</ul>';
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    $variables['main_menu_html'] = $html;
}

```

# Answer
Normaly I use `i18n_menu_translated_tree` function. For example:

```
$main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));

```
> 1 votes

---
Tags: routes, i18n-l10n
---


# Question
Title: Which is the database table in which Boost stores the cache expiry time of a node and what is the column name?
I was looking for a way to manually set the Boost expiry time of a node and happened to chance upon the boost\_cache table. There is an expire column and I am assuming that it contains the timestamp denoting the expiry time of the database. Then I happened to see the timer column and now I am confused as to which column houses the expire timestamp. Could someone explain?

Site runs on Drupal 6.

# Answer
> 2 votes
Basing on boost\_schema(), the description of those fields is the following:

* expire: UNIX timestamp for the expiration date of cached page
* timer: Time in milliseconds that the page took to be generated

The expiration time is contained in the "expire" database column.

---
Tags: 6, database, caching
---


title: How to create nodes using node_save?

text:
# Question
Title: How to create nodes using node_save?
I'm trying to migrate my current html site into Drupal. I have over 80,000 pages I have to migrate so I thought instead of sitting in front of a computer for 50 years I would create a module. I was able to create a script that extracts the html from each directory and now I got to a road block where I need to create a node. I'm trying to create a new node using `node_save()`, but when node\_save is executed, I get a `PDOException` error with everything I try. I'm passing in `$node`, which is an array which is then casted into an object.

> PDOException: in field\_sql\_storage\_field\_storage\_write() (line 424 of /srv/www/htdocs/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module).

This is how we are currently creating the node, but it produces an error:

```
$node= array(
    'uid' => $user->uid,
    'name' => $user->name,
    'type' => 'page',
    'language' => LANGUAGE_NONE,
    'title' => $html['title'],
    'status' => 1,
    'promote' => 0,
    'sticky' => 0,
    'created' => (int)REQUEST_TIME,
    'revision' => 0,
    'comment' => '1',
    'menu' => array(
        'enabled' => 0,
        'mlid' => 0,
        'module' => 'menu',
        'hidden' => 0,
        'has_children' => 0,
        'customized' => 0,
        'options' => array(),
        'expanded' => 0,
        'parent_depth_limit' => 8,
        'link_title' => '',
        'description' => '',
        'parent' => 'main-menu:0',
        'weight' => '0',
        'plid' => '0',
        'menu_name' => 'main-menu',
    ),
    'path' => array(
        'alias' => '',
        'pid' => null,
        'source' => null,
        'language' => LANGUAGE_NONE,
        'pathauto' => 1,
    ),
    'nid' => null,
    'vid' => null,
    'changed' => '',
    'additional_settings__active_tab' => 'edit-menu',
    'log' => '',
    'date' => '',
    'submit' => 'Save',
    'preview' => 'Preview',
    'private' => 0,
    'op' => 'Save',
    'body' => array(LANGUAGE_NONE => array(
        array(
            'value' => $html['html'],
            'summary' => $link,
            'format' => 'full_html',
        ),
    )),
        'validated' => true,
);

node_save((object)$node);

// Small hack to link revisions to our test user.
db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('vid', $node->vid)
    ->execute();

```

# Answer
Instead of casting an array into a `stdClass` object, you could try creating a new `stdClass()` object and then using node\_object\_prepare() to prepare the object for creating a new node and then finally manually changing the values of uid, name, title, language, body, etc. Also, be sure to use node\_submit() before saving the new node to the database.

Example: http://drupal.org/node/1173136
> 6 votes

# Answer
I think that you should read How to programmatically create nodes, comments and taxonomies in Drupal 7.

```
$node = new stdClass(); // We create a new node object
$node->type = "page"; // Or any other content type you want
$node->title = "Your title goes jere";
$node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
$node->path = array('alias' => 'your node path'); // Setting a node path
node_object_prepare($node); // Set some default values.
$node->uid = 1; // Or any id you wish

// Let's add standard body field
$node->body[$node->language][0]['value'] = 'This is a body text';
$node->body[$node->language][0]['summary'] = 'Here goes a summary';
$node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field

$node = node_submit($node); // Prepare node for a submit
node_save($node); // After this call we'll get a nid

```
> 6 votes

# Answer
Your problem is, that you are trying to create a new node with nid=null and vid=null, which is screwing up the node table as you are trying to insert new records with index number 0 - which is creating a duplicate entries problem and confusing drupal core. By the way - drupal core is vulnerable for such actions as node\_save will not see the problem and try to insert that record into the db - which is causing a sql error - and throwing out a PDO exception
> 1 votes

---
Tags: 7, nodes, migrations
---


title: Preview with another theme

text:
# Question
Title: Preview with another theme
I'd like to preview using a different theme, but I'd like the admin theme to be used for everything else related to content editing and creation.

I've tried out the "pageview" module, but it does not work the way I expect it to. This could be related to a conflict with other modules related to themes, such as Role Theme Switcher and Mobile redirection tools.

# Answer
> 2 votes
You may find the ThemeKey module useful. This module allows you to define arbitrary rules to determine when to show each theme. You can make as simple or as complex a configuration as you want.

From the module page, the following features are supported:

> * individually-styled channels
> * a front-page / "splash" screen
> * a date/time-selected Christmas theme
> * mobile themes for different auto-detected mobile devices
> * special themes for "limited" or "old" browsers
> * content, user, or role -specific themes
> * indicating your environment (production, staging, testing, sandbox, … )
> * testing your redesign safely on a live server

See the documentation for more details.

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


# Question
Title: Using hook_form_alter() and hook_cron() together
I am interested in adding a function to the cron queue after I submit a form. I am confused how to call the cron after the form submits.

I am using hook\_form\_alter for catching the submit:

```
function rating_form_alter(&$form, $form_state, $form_id) {
    switch ($form_id)  {
        case 'comment_node_form':
            $form['#submit'][] = 'add_rating_queue_function';
            break;
     }
}

function add_rating_queue_function($form, &$form_state) {
    ....
}

```

my hook\_cron\_queue\_info:

```
function add_rating_cron_queue_info(){
  $queues['update_rating'] = array(
    'worker callback' => 'add_rating_queue_function',
    'time' => 120,
  );
  return $queues;
}

```

I am a little confused on how to call `hook_cron` or `hook_cron_queue_info` to add my `add_rating_queue_function` to the cron.

Can I just call `$form['#submit'][] = 'add_rating_cron_queue_info';` inside my `hook_form_alter`

# Answer
> 1 votes
You don't invoke `hook_cron_queue_info()`; you add an item to your cron queue, which is nothing else that a normal Drupal queue that is exposed to Drupal cron through hook\_cron\_queue\_info().

What you should do in your `add_rating_queue_function()` is using code similar to the following one.

```
$queue = DrupalQueue::get('update_rating');
// Add a new item to the queue.
$queue->createItem($data);

```

`$data` is the data that is passed to the worker callback you define for the update\_rating queue in `add_rating_cron_queue_info()`.

As for running the Drupal cron tasks, you can simply call drupal\_run\_cron(). This is what system\_run\_cron\_submit() does.

```
function system_run_cron_submit($form, &$form_state) {
  // Run cron manually from Cron form.
  if (drupal_cron_run()) {
    drupal_set_message(t('Cron run successfully.'));
  }
  else {
    drupal_set_message(t('Cron run failed.'), 'error');
  }

  drupal_goto('admin/config/system/cron');
}

```

`system_run_cron_submit()` is the submission callback for the "Run cron" button you find at admin/config/system/cron.

In your case, you simply need to call `drupal_run_cron()` without checking the error code.

As Jeremy French said, `drupal_run_cron()` should not be called too often, and in this way. In admin/config/system/cron, the function call is triggered by the user, but a module should not be calling `drupal_run_cron()`, especially because Drupal 7 includes the code from Poormanscron. This mean that cron tasks could be already executed during page requests; adding a further call to `drupal_run_cron()` could make the site slower. A better code could be the following one.

```
if (lock_acquire('cron', 2.0)) {
  $last_cron_execution = variable_get('cron_last', 0);
  lock_release('cron');

  // Check cron tasks were not already executed, or they were not executed few minutes ago.
  // Set $execute if they were executed far enough.

  if ($execute) {
    drupal_run_cron();
  }
}

```

---
Tags: 7, cron, forms
---


# Question
Title: How do I prevent a menu item from appearing?
I have a View with a page display. I placed the path of that page view in a menu item. I placed this link under the menu path Primary Links \> Apps \> Home \> Admin View.

In the View defaults section, I set two roles to be able to view the page: administrator and a custom admin role I created.

I have a user that does not have the administrator or the custom admin role. They can see the Home menu item, but they can also see the Admin View. If they click on Admin View, they receive the error "You are not authorized to access this page."

I thought that in Drupal 6 menu items do not appear unless the user has access to them. I have another View for Project Manager Admin, and my user does not see that menu item.

Does anyone have any suggestions regarding where to start debugging this problem? I would like for the Admin View menu item to not appear for my user because my user does not have access to it.

I have tried logging on as the user in question in a different browser and on a different machine, and I can still see the menu item.

Thank you!

# Answer
I deleted the menu item in question, and then I re-created it.

I could see the menu item when logged on as my self. I could NOT see the menu item when logged on as the user in question.

Deleting the menu item and re-creating it caused my issue to go away.
> 0 votes

---
Tags: views, 6, routes, users
---


# Question
Title: Changing the url which the logo links to
I'm using Zen Theme 5.x and want that the site logo links non to the front page but another page in my base url, like to a contact page. It seems that I can achieve this modifying the page template file but I don't know how to do it. Could anybody help me with this?

Thank you.

# Answer
> 4 votes
Don't do it.

Linking the logo to the front page has become a de facto standard. Linking it to the contact page would only confuse users who expect to go to the front page, while users who *want* to go to the contact page would probably not click the logo.

*Update in response to the comment below:*

In my opinion, a language selection front page is a bad idea. Remember that people come to your site in order to accomplish a task. That task is never to choose a language. Also, consider how you want Google to see your front page.

A better alternative is to serve the front page in a language determined y the Drupal Language Negotiation API and make it really easy for users to switch languages if they want to. Read more about multilingual front pages at HowTo: Different home page (default front page) for each language and Drupal 7: Cracking the multilingual front page nut.

Now, if you still want to change the url the logo and site name link to, enable the `THEMENAME_preprocess_page` function in your Zen sub theme (you did create a sub theme, right?) and alter value of `$variables['front_page']`.

---
Tags: navigation
---


title: Remove language prefix from files URL

text:
# Question
Title: Remove language prefix from files URL
I have a drupal installation in a sub folder (demos/drupal) and it supports two languages (english -default- & arabic). I imported the drupal content from an old site. My problem is that the language prefix (i.e. en or ar) is added to the url of all images and this causes the images to not appear. for example: `http://www.mysite.com/demos/drupal/en/sites/default/files/image.png)`.

Can I remove the 'en' and direct all urls to "sites/default/files..etc" using htaccess rules?

I can't modify the content and find/replace the urls in the database so I'm looking for a solution to avoid that.

Appreciate your help.

# Answer
> 1 votes
If you want to use `mod_rewrite`, here's what to put in `.htaccess`:

```
RewriteEngine on
RewriteRule ^en/(.*)$ /$1

```

Btw. this has little to do with Drupal, it is either an Apache thing or a DB thing (depending on how you decide to solve it).

---
Tags: i18n-l10n, .htaccess, uri
---


# Question
Title: What would be the minimal modules I need to have for a simple registration page?
I would like to make a registration page that is only going to add Users to a list for an event, basically my site is not as concerned with accounts and detailed registration we only really care about name and a contact email that we can add to a list. Basically it's a group that has monthly events and all we ever really need is a way to track people who say they will attend, not a lot of heavy requirements for people to modify their registrations (most won't anyway) or capture a lot of information.

The various registration and event options for Drupal look overwhelming, I am using Drupal 7 and at this point using only modules and the CMS system to add pages (no coding yet). Is there a minimal set of modules that would give me the ability to obtain just a User's name and contact info (email or whatever) to put onto a list in a page? Or for this is it just easier to just code a page that can add in what I want using PHP or JSON.

# Answer
> 1 votes
You should be able to do this with the default installation of the core + Views, Views UI, and CTools. (You may be able to strip it further down by doing a custom installation of the core with some of the default core modules not enabled - but why bother).

I assume you're going to handle multiple events, and here taxonomy (in core) is your friend. Just enable the taxonomy module (if necessary) and create one taxonomy term for each event. Add a taxonmy field (or multiple to allow one user to sign up for more that one event) to the users' profiles. Ask users to register the events they plan to attent in their profile when they register (or later).

Then use Views to generate lists of names and contact addresses for the various events.

You may want to add refinements, such as not letting users cancel after they've signed up, but the above is a rough sketch of how to meet your minimal requirement.

# Answer
> 0 votes
For such a simple form, you could probably just use the Webform module.

It allows you to easily build contact/survey/questionnaire style forms through the user interface.

It can email the form submission data to you as people sign up and stores the results to be viewed and downloaded as .csv/xls as needed.

While there are also more complex solutions, webform may be the simplest.

---
Tags: 7, users
---


# Question
Title: How do I give a user limited access to theme settings?
I am interested in giving the site administrator some limited access over the appearance. Currently I can give them access to administer themes or not to, and nothing more granular than that. I would like, for instance to limit the themes they can enable and disable to a small number, and perhaps also limit what, within the settings they can change.

# Answer
> 0 votes
You could do that with hook\_menu\_alter to change the access callback on your theme settings page.

e.g,

```
/**
 * Implements hook_menu_alter
 */
function mymodule_menu_alter(&$items){
  $items['admin/appearance/settings/my_theme']['access callback'] = 'user_access';
  $items['admin/appearance/settings/my_theme']['access arguments'] = array('administer nodes');
}

```

You can also add your own access callback and return TRUE or FALSE depending on more custom user access rights access there.

See system\_menu for the core `'admin/appearance/settings/' . $theme->name` menu definition

---
Tags: theming, users
---


# Question
Title: Panels content not displaying on copied site
I'm prepping to convert a large D6 site to D7, so I've copied everything from the server to my local Mac, something I've done a bazillion times w/o a problem. Concurrently, I changed my dev environment from MacPorts to Homebrew, using PHP54 and MySQL from Homebrew along with the native Apache (2.2.22) on the Mac. What I'm running into is that Panels content isn't being displayed at all. I've tried two other sites of ours, one with Panels and one w/o Panels, and the one w/o Panels displays fine.

On my panels pages (using 6.3.9 of Panels), all of the panes are filled by Views content panes and nodequeues, so here's what I've done:

* checked the nodequeues to make sure they have content (they do),
* edited the view itself to make sure content is being returned (it is).
* cleared caches (I actually don't export cache\_\* table content
* when I get the SQL dump from the server)
* went through all of my Apache and PHP configs to make sure everything is set up the same.

The code I'm using is identical to the server (both git clones), and this exact same site worked fine before I switched to Homebrew. Any thoughts on what would keep the panels content from being displayed like this?

Thanks.

# Answer
> 3 votes
Check your Apache error logs and see what errors are reported when loading the Panels page - this is an essential part of your debugging toolkit.

Are you really using PHP5.4? That is likely to be the issue. http://drupal.org/node/1469736 indicates that the published release of Panels is not PHP5.4 compatible, but the dev release may be.

---
Tags: views, 6, panels, nodes
---


# Question
Title: What kind of content ends up in the "System help" block? How could I answer this question myself?
I saw the answer to this question and wanted to enable the "System help" block. When I did, I wondered what other content would be showing on my site besides the "Explanation or submission guidelines" field upon node editing.

Via some grep-ing, I found `modules/block/block.module` and from what I can tell the block is populated from code there. But it isn't clear to me what would end up in that block. What's the correct "Drupal way" of knowing?

# Answer
> 2 votes
Help content, defined in hook\_help is added to the "System help" block for display in

system\_block\_view

via

menu\_get\_active\_help

which returns the valid help content for the current menu path.

> How could I answer this question myself?

You can answer this question yourself by

1. Studying the Drupal API
2. Grepping / searching the codebase for relevant text
3. Asking on Drupal Answers ;)

---
Tags: blocks
---


# Question
Title: Syntax to display only the node body using node embed module
Would appreciate it if someone could let me know what the syntax is to display only the node body within another node. I tried something like this:

\[\[nid:1234 body\]\]

Obviously, that is not working. Any ideas???

# Answer
> 2 votes
That should be only `[[nid:1234]]` without `body` in it, as it embeds body by default. Also, make sure you've enabled the filter at `admin/config/content/formats/TEXT_FORMAT`.

**Edit:** Adding my comment in here to make it more clear.

If you wish to only show body of a node within node, you can do so by:

* Turning on the "Node Embed" view mode at admin \> structure \> types \> manage \> CONTENT\_TYPE \> display
* Changing the settings of the "Node embed" mode to only display body of the node. Node embed module uses this view mode by default (if enabled for a particular content type).
* You will now be able to use the above syntax without any need to specify any options.

P.S. - You could use the Display Suite module to have a better control the display of the fields.

---
Tags: nodes
---


title: Skinr classes on <body> tag

text:
# Question
Title: Skinr classes on <body> tag
I would like to use page level skins in my theme, for example.

If I make Colors widget for my skin where I can choose Red/Green/Blue colors and I choose Blue, the class blue is added to body tag.

As far as I know, I've set up Skiner properly, the above is working for regions, blocks etc, but when I set it for page, the class is not showing anywhere.

I appriciate any help, thank you!

# Answer
I solved the problem in the meantime.

In fact, there wasn't even a problem. I was adjusting the skins for the node, when I tought I'm doing that for the whole page. What I didn't notice at the time is that there is a contextual link icon in the top righ corner, and you have to use that in order to adjust the skin for the whole page.
> 0 votes

---
Tags: 7, theming
---


title: Hook for URL admin/people/create

text:
# Question
Title: Hook for URL admin/people/create
What is the hook to alter the form that appears for the URL admin/people/create?

I tried `hook_form_alter()`, but that's not the right one.

# Answer
```

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case "user_register_form" :
      //Your Logic
    break;
  }
}

```

But for performance issue use hook\_form\_FORM\_ID\_alter()
> 2 votes

# Answer
```
function modulename_form_user_register_form_alter(&$form) {
  // modify $form var
}

```

`hook_form_FORM_ID_alter()` API Docs
> 1 votes

---
Tags: hooks
---


# Question
Title: How to create table view with progress bar?
I want to create a tabular view with progress bar. The drupal-6 view consists of goals of activities I need to do. I have created a content type called Goal that is composed of activities/task. I want to list the goals in a tabular view and show a progress bar in one of the column that indicates how many task/activities under the goals have been completed. How can I do it?

# Answer
> 1 votes
You either need

1. A custom views field
2. A themed/templated existing field.

A good option in D7 for progress bars is jQuery UI progressbar ( API docs here ), as it's shipped with core.

You can add the required JS with

```
drupal_add_library('system', 'ui.progressbar');

```

---
Tags: views
---


# Question
Title: How to get the feeds log entry from hook_feeds_after_import
I have a feed and I want to email the log entries from feeds\_log after it has completed a run. I thought that if I could get the feed\_id, I could query the db to get the log entries.

I'm using `hook_feeds_after_import()`, which gives me access to the `$source` object, but in looking through some documentation, I don't see a way to get the feed\_id.

How can I get the log entries from a feed run?

# Answer
From `hook_feeds_after_import($source)`, I have access to `$source->imported`, which is the timestamp value in `feeds_log.request_time`. So I have

`$result = db_query('SELECT message, variables FROM {feeds_log} WHERE request_time = :imported',
 array(':imported' => $source->imported) );`
> 1 votes

# Answer
you can always use:

```

function yourmodule_feeds_after_import(FeedsSource $source) {
  $feed_nid = $source->feed_nid;
}

```

Hope this helps
> 0 votes

# Answer
If you have the module Views turned on there is a view provided by Feeds that has the path node/%nid/log where you can see the log.

If that is not what you wanted you could clone the view and adjust it to your settings.

If you want to code it instead you could always query the database. Have a look in feeds.install to see what the tables are named.
> -1 votes

---
Tags: feeds
---


title: how to show links inside a block

text:
# Question
Title: how to show links inside a block
```
function custom_block_view($delta = '') {
$brands = $brand->getChildrenCategories();
      foreach ($brands as $node) { #print_r($node);
        $items[] = array(
            'data' => t($url = Mage::getUrl($brand->getUrlPath()).'.html')
            #'data' => t($node['name'])
        );
      }

$block['content'] .= theme('item_list', array(
          'items' => $items
              ));

    }

```

I use this code to display items in a block. I want this to be a link but was not able to achieve it. The output is shown below:

# Answer
You need to use the `l()` function in place of `t()` (which is a string translation function):

```
$url = Mage::getUrl($brand->getUrlPath()).'.html';
$link = l('Link Title', $url);

```

If the URL is external you'll also want to provide that information in the `$options` parameter:

```
$link = l('Link Title', $url, array('external' => TRUE));

```
> 0 votes

---
Tags: blocks
---


title: Setting admin theme using Profiler

text:
# Question
Title: Setting admin theme using Profiler
I'm using Profiler to create a Drupal 7 installation profile, which works great -- however, it doesn't set Seven as an admin theme, and thus falls back on Bartik (The default theme).

**Is there any way to set the default admin theme within Profiler?**

# Answer
> 0 votes
One way to accomplish this is to use Strongarm to set the admin theme variable as part of a Feature.

Given that the "Standard" Drupal installation profile creates a lot of other stuff that won't be in a custom installation profile -- Basic Page and Article content types, for instance -- I've created a Feature with all those and added the Admin Theme Strongarm variable as part of that.

That said, leaving question open in case somebody knows how to set the Admin theme as part of a Profiler makefile.

---
Tags: installation, distributions
---


# Question
Title: How should I define a MENU_LOCAL_ACTION menu item, and which is the involved page callback?
Looking at user\_menu() to check the answer for another question, I noticed the function contains the following definition.

```
  $items['admin/people/create'] = array(
    'title' => 'Add user',
    'page arguments' => array('create'),
    'access arguments' => array('administer users'),
    'type' => MENU_LOCAL_ACTION,
  );

```

The page callback is not explicitly defined.

Reading the definition of `MENU_LOCAL_ACTION` given in hook\_menu(), I read the following:

> MENU\_LOCAL\_ACTION: Local actions are menu items that describe actions on the parent item such as adding a new user or block, and are rendered in the action-links list in your theme.

That doesn't explain which is the involved page callback that is called to handle that menu item.

Which is the page callback that is called to handle a `MENU_LOCAL_ACTION` menu item? Is there any other property that is necessary to define such menu items?

# Answer
Router items can inherit properties from parent paths.

In this case, the `page callback` is inherited from the 'admin/people' path:

```
$items['admin/people'] = array(
  'title' => 'People',
  'description' => 'Manage user accounts, roles, and permissions.',
  'page callback' => 'user_admin',
  'page arguments' => array('list'),
  'access arguments' => array('administer users'),
  'position' => 'left',
  'weight' => -4,
  'file' => 'user.admin.inc',
);

```

The fact that the menu item is a `MENU_LOCAL_ACTION` doesn't actually come into it, the same is true of any type of item.

So if you define a router item like this:

```
$items['mymodule/path'] = array(
  'title' => 'Something',
  'page callback' => 'mymodule_page_callback',
  'access callback' => 'mymodule_access_callback',
);

```

And then define one like this:

```
$items['mymodule/path/sub-path'] = array(
  'title' => 'Something',
  'type' => MENU_LOCAL_ACTION,
  'access callback' => 'mymodule_access_callback',
);

```

The `page callback` will be inherited from the 'parent' item.
> 7 votes

---
Tags: routes
---


# Question
Title: How to enable Submit Button after filling out the required fields?
I have created custom Content Type and I would like to disable the submit button, till the user has filled out all the required fields.

I should enable the submit button, once the user fills out the required fields, how do i achieve this?

# Answer
check out `#states visible` `#states invisible` in drupal.

http://api.drupal.org/api/examples/form\_example!form\_example\_states.inc/function/form\_example\_states\_form/7

http://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_process\_states/7
> 1 votes

# Answer
This sounds like a job for javascript.

This thread should get you started:

http://www.webdeveloper.com/forum/showthread.php?147187-how-to-Disable-enable-submit-button-using-javascript.

I'd create a set of javascript validation functions that once they all returned true for the fields you need it would reenable the submit button.

Here is a link to another, simple, example that may be just what you are looking for:

http://www.webmasterworld.com/javascript/4083623.htm
> 0 votes

---
Tags: nodes
---


# Question
Title: Language switcher doesn't work with my views
I am new to this forum, but I hope to get an answer to my problem. Searching 2 days already, bur no success...

I have a multilingual (French and Dutch) D7 website. Besides the needed core modules enabled, I installed the i18n module and the variable i18n module. As for normal pages, everything works perfect. I have a menu for each language, the menu links refer to the correct pages. I have also a language switcher, which works perfect with my nodes.

Now comes my problem. I created a view to display a teaser of all products. Look at http://www.solarine.eu/solarine/ to see what I mean. I made a view for the Dutch language (called "producten"), and one for the French ("produits"). When you access the pages by the main menu, they display correcly (5 products for Dutch, only 1 for French). BUT if you use the language switcher to toggle between languages when visiting the products page, the content of the views stays in the wrong language.

Can anyone please help me with this? It MUST be possible to solve this, but after 2 days searching on different websites with no result, I am out of ideas.

Many thanks! Steven

# Answer
> 2 votes
It is possible to solve this with Views, here is how:

1. Go to your view's edit page.
2. Add a Filter Criteria called 'Content translation: Language'
3. In the popup that comes after that, select 'Current user's language'
4. Save the Filter Criteria and your view as well.

After this, this view will only show items that are the same language as the language you are using at the moment on the website.

You can however set a specific language to your view as well with the same criteria. You just have to select a language instead of 'Current user's language' and that view will only list content that are in that specific language.

---
Tags: views
---


# Question
Title: How can I create multiple dashboards with Open Atrium?
By default each Open Atrium group has its own dashboard. What I'd like to do is to create multiple dashboards (pages?) for each group. My goal is to create separated dashboards with different contents, just like website's pages. Any idea on how to do this with Open Atrium?

# Answer
In the end I created a normal PHP node and used that one as a Dashboard.
> 0 votes

# Answer
Users with sufficient permissions should see an "Add custom" link on the Dashboard. This link lets you create additional Dashboards for a single group, each with its own content and layout.
> 0 votes

---
Tags: distributions, dashboard
---


# Question
Title: How to use drupal_mail() to send emails with custom template
I would like to use the `drupal_mail()` function to send out emails but with a custom HTML template so that they are in keeping with my website design but I am a complete newbie to hooks and modules etc., so I'd appreciate some sort of explanation or beginners guide please.

I can create the template myself, I just need to know how to get `drupal_mail()` to use it.

# Answer
If you are trying to send the mails via your custom module then you can follow the below mentioned guide. Say, I had one Module called "Commerce Canvas(commerce\_canvas)" 1. First Alter the Drupal's mail function to support links and add other encoding types

```

/**
 * Implements hook_mail_alter()
 * @param string $message
 */
function commerce_canvas_mail_alter(&$message) {
    $headers = array(
        'MIME-Version' => '1.0',
        'Content-Type' => 'text/html; charset=iso-8859-1; format=flowed',
        'Content-Transfer-Encoding' => '8Bit',
        'X-Mailer' => 'Drupal',
    );
    foreach ($headers as $key => $value) {
        $message['headers'][$key] = $value;
    }
}

```
1. Then next, hook the HOOK\_mail in your module as

```

/**
 * Implements hook_mail()
 * @param string $key
 * @param string $message
 * @param unknown_type $params
 */
function commerce_canvas_mail($key, &$message, $params) {

    //Language Selection
    $options = array(
        'langcode' => $message['language']->language,
    );
    switch($key) {
        case "user_payment_notification" :
            $message['subject'] = isset($params['subject']) ? $params['subject'] : $message['subject'] = t('Payment recieved @site-name', array('@site-name' => variable_get('site_name', 'Express Canvas')), $options);
            $message['body'][] = isset($params['body']) ? $params['body'] : NULL;
            if (isset($params['headers']) && is_array($params['headers'])) {
                $message['headers'] += $params['headers'];
            }
            break;
    }
}

```
1. Then you need to create a wrapper function to invoke the mail from your module.

```

function commerce_canvas_mail_send(array $values = array()) {
    $module = $values['module'];
    $key = $values['key'];
    $to = $values['to'];
    $from = $values['form'];
    $language = isset($values['lang']) ? $values['lang'] : language_default();
    $params = array(
        'subject' => $values['subject'],
        'body' => $values['body'],
    );
    if(array_key_exists('headers', $values)) {
        $params['headers'] = $values['headers']; //Assumed as an array
    }
    $send = TRUE;
    $mail = drupal_mail($module, $key, $to, $language, $params, $from, $send);
    if($mail['result']) {
        return TRUE;
    } else {
        $error_msg = 'Failed to send the email in commerce_canvas Module';
        watchdog('canvas-email', $error_msg, array(), WATCHDOG_ALERT);
        return FALSE;
    }
}

```

This function will send the email and as well as create debug messages if anything happens wrong. But still you won't be able to send the HTML mail because you need to extend the Drupal 7's default **DefaultMailSystem** with your own. So need to do as following,

```

class CommerceCanvasMailSystem extends DefaultMailSystem {
    /**
     * Concatenate and wrap the e-mail body for plain-text mails.
     *
     * @param $message
     *   A message array, as described in hook_mail_alter().
     *
     * @return
     *   The formatted $message.
     */
    public function format(array $message) {
        $message['body'] = implode("\n\n", $message['body']);
        return $message;
    }

    /**
     * Send an e-mail message, using Drupal variables and default settings.
     *
     * @see http://php.net/manual/en/function.mail.php
        * @see drupal_mail()
     *
     * @param $message
     *   A message array, as described in hook_mail_alter().
     * @return
     *   TRUE if the mail was successfully accepted, otherwise FALSE.
     */
    public function mail(array $message) {
        $mimeheaders = array();
        foreach ($message['headers'] as $name => $value) {
            $mimeheaders[] = $name . ': ' . mime_header_encode($value);
        }
        $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
        return mail(
        $message['to'],
        mime_header_encode($message['subject']),
        // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
        // on Unix and CRLF on Windows. Drupal automatically guesses the
        // line-ending format appropriate for your system. If you need to
        // override this, adjust $conf['mail_line_endings'] in settings.php.
        preg_replace('@\r?\n@', $line_endings, $message['body']),
        // For headers, PHP's API suggests that we use CRLF normally,
        // but some MTAs incorrectly replace LF with CRLF. See #234403.
        join("\n", $mimeheaders)
        );
    }
}

```

Next you need to register a new theme function that will call your custom template file in your hook\_theme().

```

/**
 * Implements hook_theme();
 */
function commerce_canvas_theme($existing, $type, $theme, $path) {
  if($type == 'module') {
    return array(
      'tracking_code_email' => array(
        'variables' => array(
          'image_path' => NULL,
          'user' => NULL,
          'page' => NULL,
        ),
        'template' => 'commerce-canvas-tracking-code',
        'path' => drupal_get_path('module', 'commerce_canvas').'/theme',
      ),

    );
  }
}

```

Last you need to call this theme function in time of sending the email as,

```

function a_custom_function($params) {

$email_text_user = theme('tracking_code_email', array(
                    'image_path' => $base_url . '/' . drupal_get_path('module', 'commerce_canvas') . '/images',
                    'user' => null,
                    'page' => array(
                        'greet_text' => t('Thank you for your order at Express Canvas. Your order is ready and has shipped. You may track your order using FedEx tracking with your tracking number: **'.$order->field_tracking_number['und']['0']['value'].'**'),

                    ),
                ));
$sent_to_user = commerce_canvas_mail_send($email_values_user);

}

```

These are the full snippet to handle the HTML email correctly in Drupal 7 thus in the hook\_theme you can give your custom template.
> 39 votes

# Answer
If you want to theme the outgoing mails with the help of custom templates, you should use the HTML Mail module.

> Lets you theme your messages the same way you theme the rest of your website.

It works well with other modules, like Print, Mail mime, etc.

You have to install the Mail System module in order to use HTML mail.
> 11 votes

# Answer
Example usage:

```
    $module = 'module_name';
    $key = 'key';
    $language = language_default();
    $params = array();
    $from = NULL;
    $send = FALSE;
    $message = drupal_mail($module, $key, $email, $language, $params, $from, $send);

    $message['subject'] = $subject;
    $message['body'] = array();
    $message['body'][] = $line1;
    $message['body'][] = $line2;

    // Retrieve the responsible implementation for this message.
    $system = drupal_mail_system($module, $key);

    // Format the message body.
    $message = $system->format($message);

    // Send e-mail.
    $message['result'] = $system->mail($message);

```
> 4 votes

# Answer
To send HTML e-mail, you can use the Mimemail module. Once it's set up and configured, you can simply prepare the template, name it `mimemail-message.tpl.php`, drop it in your theme directory, and it will automatically be applied to all outgoing e-mail (assuming you have configured all mail to be sent out by Mimemail).

Setting up the module is probably easier than overriding `drupal_mail()`.
> 3 votes

---
Tags: 7, hooks, emails
---


title: How can I edit the search form?

text:
# Question
Title: How can I edit the search form?
I have an OpenAtrium distribution installed on Drupal 6. As you may already know OpenAtrium already implements a search feature. What I'd like to do is change the following form:

by adding another button alongside the Search one (there are other modifications that I'd like to do but it doesn't matter this is just the final goal).

The problem is that I don't know what is the PHP page that builds that form. All I know is that page.header.inc prints the content of that form:

```
 ...
 <div id='space-tools'><div class='dropdown-blocks toggle-blocks clear-block'><?php print $space_tools ?></div></div>
 ...

```

As you can imagine $space\_tools contains the entire menu and also the form. But who's the one who builds the $space\_tools variable? Is there an OpenAtrium API that I can read somewhere?

This is the result HTML which I'd like to change:

```
<div id="space-tools"><div class="dropdown-blocks toggle-blocks clear-block processed">
<form action="/openatrium/XXXXXX/" accept-charset="UTF-8" method="post" id="atrium-search-form">
<div>
    <div class="form-item form-item-labeled" id="edit-search-wrapper">
        <label for="edit-search">Search XXXXXXX: <span class="form-required" title="This field is required.">*</span></label>
        <input type="text" maxlength="128" name="search" id="edit-search" value="" class="form-text required fluid">
    </div>
    <input type="submit" name="op" id="edit-submit" value="Search" class="form-submit">
    <input type="hidden" name="form_build_id" id="form-31ea0a19166f0619050f7ac923ebf331" value="form-31ea0a19166f0619050f7ac923ebf331">
    <input type="hidden" name="form_token" id="edit-atrium-search-form-form-token" value="aaf2e5374720acee5769fcafb6421e35">
    <input type="hidden" name="form_id" id="edit-atrium-search-form" value="atrium_search_form">
</div>
</form>

```

Thank you. Almost forgot, here where I work imgur is blocked by the proxy so I can't tell if the image has been uploaded or not.

EDIT: This is driving me crazy I looked up over the entire OpenAtrium folder for the word "atrium-search-form" and no result at all inside files. How can this even be possible lol? Unless the ID is built upon different variables, in that case I don't know what to do...

# Answer
It's displayed using the Context module. I found it like this:

* Go to `admin/build/context` and select the `global` context
    + Click the `Blocks` reaction
    + Under the `Space tools` region, `Atrium: Search form` block is being shown

I then searched for the name `Atrium: Search form`, and found that the block is defined in the `atrium_features` module, in functions `atrium_block` and `atrium_search_form` of file `atrium/atrium.module`.

You could modify the search form using a `hook_form_FORM_ID_alter` hook, such as `hook_form_atrium_search_form_alter`.
> 1 votes

---
Tags: forms, search, 7, distributions
---


# Question
Title: How do I format a picture field as raw source url in a view
I have a view of users, I'm displaying a number of fields, I want to output the path to the image, without rendering any of the html around it, I cant seem to figure out how to do this.

# Answer
The easier option is:

1. Go to Configure field
2. "Rewrite results" and check "Rewrite the output of this field"

Add whatever html you want to display your image field. Below you can find "Replacement patterns". Those are tokens you can use in your html.

And the more advanced option is to:

1. Go to "Advanced" (on the right side of your view)
2. Theme: Information

Here is a link that can help you with that: http://www.group42.ca/theming\_views\_2\_the\_basics
> 1 votes

# Answer
I found that "there's a module for that", Image URL Formatter:

> This module add a url formatter for image field. Then you can output image url directly.
> 2 votes

---
Tags: views, users, media, entities
---


# Question
Title: Create a log of create/delete users in Drupal 7
I'm creating a log with several actions in drupal.

I register similar actions with hook\_watchdog.

```
/**
* Implements hook_watchdog().
*/
function MYMODULE_log_watchdog(array $log_entry) {

  if($log_entry['message']=='Login attempt failed for %user.'){
    my_log_function();
  }
}

```

But I do not know how to detect that is created or deleted a user, and record this information in my custom log.

I'm new in drupal development and I Appreciate any guidance to investigate. Thanks :)

# Answer
You could actually log the details about user creation at hook\_user\_insert(), and deletion using hook\_user\_delete().

User creation: Acts on new user creation

```
function MODULE_user_insert(&$edit, $account, $category) {
  watchdog('user', 'User created with ID: %userid', array('%userid' => $account->uid]), WATCHDOG_NOTICE, $link = NULL);
}

```

User deletion: Acts on account deletion

```
function MODULE_user_delete($account) {
  watchdog('user', 'User having ID: %userid deleted', array('%userid' => $account->uid]), WATCHDOG_NOTICE, $link = NULL);
}

```
> 4 votes

# Answer
Keep in mind, the user module already creates watchdog log entries when a user is created or deleted:

## User created

```
watchdog('user', 'New user: %name (%email).', array('%name' => $form_state['values']['name'], '%email' => $form_state['values']['mail']), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $account->uid . '/edit'));

```

in user\_register\_submit

## User deleted

```
watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);

```

in \_user\_cancel

## Other user watchdog calls ( filename:line-number)

```
./user.pages.inc:81:    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
./user.pages.inc:131:          watchdog('user', 'User %name used one-time login link at time %timestamp.', array('%name' => $account->name, '%timestamp' => $timestamp));
./user.pages.inc:171:  watchdog('user', 'Session closed for %name.', array('%name' => $user->name));
./user.pages.inc:450:    watchdog('user', 'Sent account cancellation request to %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
./user.admin.inc:355:      watchdog('file system', 'The directory %directory does not exist or is not writable.', array('%directory' => $picture_path), WATCHDOG_ERROR);
./user.module:616:    watchdog_exception('user', $e);
./user.module:2174:      watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
./user.module:2223:  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
./user.module:2368:    watchdog('user', 'Attempted to cancel non-existing user account: %id.', array('%id' => $uid), WATCHDOG_ERROR);
./user.module:2419:      watchdog('user', 'Blocked user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
./user.module:2430:      watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
./user.module:2485:      watchdog_exception('user', $e);
./user.module:3145:        watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
./user.module:3641:  watchdog('action', 'Blocked user %name.', array('%name' => $account->name));
./user.module:3807:  watchdog('user', 'New user: %name (%email).', array('%name' => $form_state['values']['name'], '%email' => $form_state['values']['mail']), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $account->uid . '/edit'));

```

An alternative approach would be to look into the Rules module which can intercept various events, such as a watchdog entry, and perform an action, such as emailing someone - all configured via the user interface with export/import functionality and a good API.

Rules can act on the following user events out of the box:

* After a user account has been deleted
* After saving a new user account
* After updating an existing user account
* Before saving a user account
* User account page is viewed
* User has logged in
* User has logged out
> 3 votes

# Answer
Don't forget about the module Role Watchdog! It will log user delete / user create for you via an entry that shows the 'authenticated user' role being added/removed in concert with the user addition / removal. It also works with og, and is more persistent than the watchdog messages (presuming that you periodically flush your watchdog cache, as most do).
> 2 votes

---
Tags: hooks, log-messages
---


title: Quick-edit button in Drupal Commerce

text:
# Question
Title: Quick-edit button in Drupal Commerce
I'm using Drupal 7 and Commerce Kickstart 2.0-rc1. I can't find a way to remove the possibility for a user role to use the "Quick Edit" button in admin/commerce/manage-products . I tried using hook\_permission() but, despite the permission is taken into account, the button is still here and still works.

Is there a clean way to remove this action from the drop-down list ?

Thanks.

# Answer
> 1 votes
The whole "Products Listing" requires the "super permission" (a permission that grants all kinds of access, including the ability to quick edit) "administer products." I have filed a feature request in the Commerce Kickstart Issue queue that requests the quick edit button have a more granular permission.

http://drupal.org/node/1883280

Josh

---
Tags: users, commerce
---


title: Adding cherry-picked nodes to a list

text:
# Question
Title: Adding cherry-picked nodes to a list
On a project I'm working on, we'd like to give users the ability to search for nodes via a View with exposed fields, and then have them able to select specific nodes to be added to a list.

We've thought about doing this via taxonomy terms and Views Bulk Operations, but that's not very streamlined (I'd have to set the action to "Modify entity data," selecting the taxonomy field -- but then there'd be a bunch of options on the next page and the default behaviour is to overwrite all the terms attached to a node.).

Any ideas how one can create a simple cherry-picked list, ideally from Views result content?

# Answer
We have done this using the Flag module:

> Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

Make a flag and add it to your content type. You may be able to use one of the default flags.

Configure the flag to appear on just teasers.

In your view, configure it for node output, and choose teasers and show links. I think you can add the flag as a "field" in field-based output, but I don't remember.

Then, your view should show your list of nodes and each will have a flag link with it. Users can flag their nodes.

You can then make views over the nodes that your users have flagged, either all together or per user. The Flag module integrates very nicely with Views.
> 0 votes

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


# Question
Title: How to create invisible widget in Drupal
I need to create an auto-generated value for every user on my site. No one should be able to edit this field so it should not appear on the user edit form. Is there a better way to achive this than simply removing its edit field with hook\_form\_alter?

# Answer
> 1 votes
Install the Field Permissions module:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

And the Computed Field module:

> Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it.

You can then create a field for your value, hide it from the registration/profile form, and use Computed Field to set its value to whatever you need it to be automatically.

# Answer
> 0 votes
I would use Field Extra Widgets that provides a "Hidden" widget which is probably what you're looking for.

In any case, instead of removing the field with a unset or alike, it's better to do an #access =\> FALSE in the form alter.

---
Tags: 7, entities
---


# Question
Title: How to create add custom style to specific view in drupal
Please check this site

I am trying to create rounded corner rectangle on right hand side where products are listed. This is currently working because I modified view-view-grid.tpl.php. Doing this has changed everywhere wherever I was using grid. I want to add this style only to a particular view. How can I achieve this in views. I also want to modify style of each category displayed within the box eg. Product category should be bold or some different color.

I am beginner so please let me know steps or some good references.

# Answer
> 3 votes
This is actually really easy with views. I am going to assume you are using Drupal 7 with Views 3. But this works almost the same in previous versions of both as well.

First, go into your view. On the far right expand the "Advanced" fieldset if it isn't already expanded. Then click on the "Information" link next to Theme at bottom of the list.

This will popup a modal that will display how to name your template files to replace the default template. It specifically allows you to modify different levels of the template. Find the level you want to modify. Then, while reading the list from left to right (right being the most specific) pick the name that is specific enough for your uses.

Next, go into the views module and find a copy of the bolded template file and copy that into your theme folder into a templates folder or into a custom module. Then give it the name you found above and make your changes.

Finally save it and flush the Drupal cache. Now when you go back to that information page it should show your new template file highlighted. This may require a few refreshes.

Now on another note, if you use the built-in field controls you can add custom CSS classes to help target the specific view and thus a specific button underneath it. You can also add specific classes to the view in the advanced section.

Though keep in mind drupal already gives us a ton of classes to each element, so you shouldn't need any of this just to target that view and a specific button within it.

---
Tags: views, theming
---


title: Add arguments to core search

text:
# Question
Title: Add arguments to core search
Is it possible to add arguments from $\_GET to the core search? For example:

search/term1/mystring

This search page should show results that have the "term1" term. Like views, but I've to add this function to core search :)

# Answer
certainly possible.

http://api.drupal.org/api/drupal/modules!search!search.api.php/function/hook\_search\_preprocess/7

Check out that function.
> 1 votes

---
Tags: 7, search
---


title: Advice concerning lay-out homepage

text:
# Question
Title: Advice concerning lay-out homepage
I'm having a bit of an issue here and I'm hoping for some professional advice.
Here is my situation:

That's my homepage. In the upper part, there is an image slideshow (no issues there), but underneath are 3 textblocks. The text inside those blocks is quite static but the end-user has te be able to change the content. The tricky part is it can't be blocks or panels. So the one thing I can think of is make a content type for those blocks and use a view filter to show those 3 blocks. But even then, I'm not quite sure on how to do this...

Is there anyone here who can advice me about this issue? Or alternatives on how to tackle this?

# Answer
> 1 votes
I would still use blocks for this, because I always prefer to use the most appropriate and lightweight solution for the data storage, and then tweak the admin interface to enhance usability.

You could solve this with a special content type, combined with views or display suite. However, experience has taught me that if you're creating a content type for a small, fixed number of nodes, it usually means that there are better solutions out there.

You are right that the blocks page is too complex for many users. To solve that problem, I would:

* Create the 3 blocks;
* Enable the Contextual Links module (part of Drupal 7 core) to provide edit links on the blocks, right there in the front end;
* Install and configure Block Access to make only those 3 blocks editable by the site maintainer;
* Implement hook\_form\_alter to hide specific form fields from the site maintainer on the block edit form.

# Answer
> 0 votes
I do something similar with like where I have a slideshow and then like news and events below it and another 3rd bar (I've redacted some stuff from the image):

But I'm talking about like News and Events.

I have this in `template.php` for my theme:

```
/**
 * Override or insert variables for the page templates.
 */
function MYTHEME_preprocess_page(&$vars) {
  $page =& $vars['page'];
  if ($vars['is_front']) {
#dpm($page['content']);
    unset($page['content']['system_main']['default_message']);
    $page['content']['system_main']['views_slideshow-block']['#weight'] = 1;

    // Make the news/events view wrap via a custom div for fluid bg.
    // The .clearfix is needed so the div fills the space vertically.
    $page['content']['views_news-block_2']['#prefix'] = '<div class="fluid-bg clearfix">';
#    $page['content']['views_events-block_1']['#suffix'] = '</div>';
    $page['content']['block_2']['#suffix'] = '<div class="clearfix"></div></div>';
    $vars['title'] = '';
    if (isset($page['header']['mysite_core_menu_header_image'])) {
      unset($page['header']['mysite_core_menu_header_image']);
    }
  }
}

```

The blocks, views\_news-block\_2, views\_events-block\_1 are made using Views. block\_2 is merely a block made from the block UI. They are placed via Context onto the frontpage in the order they should appear (top to bottom). CSS is merely adding container divs and inlining stuff.

**EDIT:**

just for clarification. The blocks are placed in order via context (or you could use the block ui) onto the given page as:

* slideshow
* news
* events
* other sidebar

`#prefix` and `#suffix` render array elements are used on sibling `$page['content']` arrays to embed the css wrapper divs.

# Answer
> 0 votes
Create a content type specifically for the frontpage with three text field (Field Type: Text / Widget Text area (multiple rows) and put it in place either with Display Suite or with some CSS. Then your customer can click edit and edit the text in the text fields. Give him an text editor like CKEditor to make him/her completely happy. Show the node you created with that content type your frontpage and throw in the slideshow via a views block.

# Answer
> 0 votes
I would use the Display Suite module for your web content. With Display Suite you can choose the layout you prefer.

Create then a new content type with 3 text fields for your 3 blocks of text. Each textfield can be added to a specific place in your layout. With some css you can finetune the result on your page.

Your end-user/editor can easily make changes because your pages are simple nodes.

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


# Question
Title: Updating Drush when installed using pear
When I run `drush self-update`, I get the following message:

> A newer version of drush, 7.x-5.8, is available. You are currently running drush version 6.0-dev. The update process depends on how you installed drush. Some common update commands are: `pear upgrade drush/drush`, `git pull`, `drush dl drush --destination=[/path/to/drush]`.

When I execute `pear upgrade drush/drush`, I get the following message:

> Nothing to upgrade

When I execute `sudo drush dl drush --destination=/usr/local/bin/pear/bin` (/usr/local/bin/pear/bin is the directory where Drush is found from `which`), I get the following messages:

```
Unable to create /usr/local/bin/pear/bin/drush.                                             [error]
Project drush (7.x-5.8) could not be downloaded to /usr/local/bin/pear/bin/drush.

```

How should I update Drush when installed with `pear`?

# Answer
Although there is a pear package for Drush-8.x-6.x, if you are going to run this version of Drush I would recommend cloning it from git, and updating it with git pull. You can also check for newer code with git status instead of drush self-update.

Discussions on the deficiencies of drush self-update should probably happen in the Drush issue queue. Briefly, it no longer handles the update operation itself, and while it works well enough when using stable versions of Drush, it is easily confused in other circumstances (e.g. when Drush-7.x-5.8 is newer by date than the 8.x-6.x-dev that you are running, even though 7.x-5.8 is built exclusively from features backported from 8.x-6.x-dev.)
> 4 votes

---
Tags: drush, upgrading
---


# Question
Title: I can't access a provided variable in rule action
In a rule I have 2 actions, the first one provides a variable (my\_var\_name). But in the second action this var is not shown as available.

I can't figure out what the problem is.

# Answer
> 1 votes
I was having this problem with a different module with Rules. I believe the data types are conflicting. `node:author:name` is a string, while the value have calculated is an integer, a decimal or a float.

My Problem:

User Field - Voting Currency (set as integer)

**Event:**

* Vote was cast on entity

**Action:**

* Query database for the value of the vote cast
* *Calculate the value* to add/subtract from the Voting Currency field
* *Set the new value* of Voting Currency field.

I discovered the vote was a decimal data type. I removed the Voting Currency integer field with a Voting Currency decimal field and everything worked!

---
Tags: rules
---


# Question
Title: Can I override/modify an existing hook_widget_info for an existing CCK field type
I want to modify the default Link field, so that instead of just a text field it will always have a Validate Button next to it (for active checking).

I don't want to create a new Widget, I want to override the basic link, so that any link field deriving from the original will inherit these changes. Also of course, is it then possible to override the override (for a specific link variant - say, Twitter link, to change this new button to a checkbox or just remove it for that type)? Can I just add in my custom module the link\_widget\_info() function?

Thanks!

# Answer
You can do that with hook\_field\_widget\_form\_alter

```
hook_field_widget_form_alter(&$element, &$form_state, $context)

```

> Alter forms for field widgets provided by other modules.

The function parameters there allow you to check and target specific cases as needed.
> 1 votes

---
Tags: hooks, entities
---


# Question
Title: How can I create a field to hold data on users' countries and states?
I'm trying to create a content type that has multiple countries available to be selected and then multiple states/territories within those countries based on the country, but I'm not sure how to best accomplish this.

When a user is creating a piece of content they need to be able to select their country, then based on the country they select, they can select their state or territory with only those states/territories for that country available as options. I have two such countries that will have multiple states/territories - the U.S. and Canada.

I'm creating a text field using the field module that lists all the U.S. states when a parent item is selected using a list (text) and a "select text" drop-down. I also need to create a way to present the user with the Canadian territories when selecting Canada as the territory.

Right now I have two fields - "Country" and "State". Can you recommend the best way to accomplish presenting the user with the correct options for the state/territory based on their country selection? I'm drawing a blank on this one.

# Answer
In Drupal 7 you should use the dedicated addressfield module for that purpose.

The composite address field provides a country drop down box with other address fields such as state loaded via ajax depending on the selected country.

## USA

## Canada

It's a requirement of the Commerce module for address selection.

You can hide some of the address sub-fields if needed.
> 1 votes

# Answer
Probably two text fields with widget select, and use form #ajax to update the region list when the country is selected. See Dynamic select list in the form (dependent dropdown) for a similar answer.

Another option might be Hierarchical Select which does this "out of the box" - you could use a vocabulary for the country/region structure. Consideration here is that you'll need to look up the parent term of the region to find the country, and maybe you'd rather have an easy way to query "content from Canada" than "content from any region which has a parent term of Canada".
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to add fields to a form from a custom module
I'm working on a custom module that will allow payments through a particular bank API.

The API requires me to do a POST to a certain URL that they have provided me, where the user will enter his credit card information. To do so, I created a form with the #action set toward the provided URL, and with the mandatory fields asked by the bank (name, address, phone, etc.)

Unfortunatly, the form is in the module, and I don't think that is good practice, since it gets more complicated for a user to add his own custom field (lets say a date of birth for example).

Is there anyway that my module can get a form created by the form API in another module ("my\_custom\_cart") and add to it the mandatory fields needed for the transaction?

Thank you

# Answer
> 0 votes
I think using the form #action is the wrong approach there.

You should instead use

drupal\_http\_request

> Performs an HTTP request.
>
> This is a flexible and powerful HTTP client implementation. Correctly handles GET, POST, PUT or any other HTTP requests. Handles redirects.

In your form submit handler, to pass on the required parameters to the payment gateway.

Ensure everything is done under HTTPS.

To get another form, you can simply use

```
$form = array(); // new form
$defaults = drupal_get_form('my_default_form_builder_function');
$form += $defaults; // add defaults to new form

```

---
Tags: forms
---


# Question
Title: How to get a field's value for all nodes in a content type?
I would like to get values of a field from all nodes of a content type. How can I do this? EntityFieldQuery seems to return only node ids, so will I need db\_query? Sg similar to this In a custom module how do I get all the nodes of a certain type?

I guess I just need to lookup the table name of the field...

# Answer
> 5 votes
In your case, you can probably simply query the field data table, with a condition on the entity type and bundle.

In any case, something like:

```
$field_name = 'FIELD_NAME';
$result = db_select("field_data_{$field_name}", 'f')
  ->fields('f', array('entity_id', "{$field_name}_value"))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'article')
  ->condition('deleted', 0)
  ->range(0,10)
  ->execute();

foreach ($result as $row) {
  // drupal_set_message($row->field_name_value); // example
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}

```

As an aside you might want to join on the node table to only select published content, but that's the gist of it.

---
Tags: 7, entities
---


# Question
Title: Webform Tokens lets me access form meta-info but not user-submitted values (with Fill PDF)
I'm attempting to use the Fill PDF module to populate an editable pdf. The data source is a Drupal Webform submission. I'm specifying those values to Fill PDF using tokens from the Webform Tokens module. I have also tried this using Webform's tokens made available to Fill PDF via the Webform Rules module, which does not work at all (no PDF is generated).

With the Webform Tokens module I have partial success: I can get a PDF to fill in with non-user-submitted values from the webform (such as the submission ID and the webform component label) but user-submitted values always end up blank. For example:

1. I enter the following into the Value field of the PDF-Field key in /admin/structure/fillpdf/\[form ID\]/edit/\[pdfkeyname\]:

```
The SID of this submission is [webform:meta-sid].
The value of the form component titled [webform:meta-label-textmetest]
is [webform:val-textmetest].`

```

For the submission in question the value of the `textmetest` field is "glasstest."

1. I go back to /fillpdf?fid=53&webform\[nid\]=4&webform\[sid\]=10 and it now reads

```
The SID of this submission is 10.
The value of the form component titled textmetest
is  .

```

Thus, the `[webform:meta-sid]` and `[webform:meta-label-textmetest]` tokens are being replaced, but not the token `[webform:val-textmetest]`.

I have confirmed that the webform's ID is indeed 4, the SID is 10, the value of textmetest for SID 10 is glasstest, and the form ID for the pdf is 53.

I know that it is trying to access a specific submission, because if I use a nonexistent SID in the URL (e.g., /fillpdf?fid=53&webform\[nid\]=4&webform\[sid\]=99) the field reads: `The SID of this submission is . The value of the form component titled is .` , i.e. the SID and title don't populate for a nonexistent submission. However, I can't get at the values for any specific submission.

If I try Webform Rules enabled instead, instead using the tokens `[webform:sid]`, `[webform:textmetest-value]`, and `[webform:textmetest-title]`, which are the corresponding tokens that Webform Rules exposes to Fill PDF, it does not even generate a PDF; I get a 500 internal server error.

Does anyone have any suggestions, either for how to make this work or for another way to get at webform values?

# Answer
> 1 votes
The issue is that Fill PDF 7.x-1.9 doesn't work with Webform 4 due to a change in the structure of the $submission variable from Webform via webform\_get\_submission(). See this post for an explanation and an ad hoc fix.

---
Tags: webforms, tokens, files
---


# Question
Title: How do I create an AJAX filter for a view?
I have created a page using Views and it works fine. I want to add an AJAX filter to this page to allow visitors to filter the contents based on PubDate or by Taxonomy/Vocabulary for this content type. How can I accomplish this?

# Answer
> 10 votes
1. Edit the view, and add a filter to the page:

* **Drupal 6:** Third column, section is called *Filters*
    * **Drupal 7:** First column, section is called *Filter Criteria*
2. When you configure the filter, you want to expose it:

* **Drupal 6:** Click the *Expose* button in the top right of the configure area
    * **Drupal 7:** Check *Expose this filter to visitors, to allow them to change it*
3. Enable AJAX:

* **Drupal 6:** *Use AJAX* is under *Basic settings* in the first column
    * **Drupal 7:** *Use AJAX* is under *Advanced**Other* in the third column

When the view is saved, there will now be a form that'll allow users to filter the view dynamically via AJAX.

# Answer
> 0 votes
Maybe, you can use the Better exposed filters module to change output of your filter items to links.

And Use AJAX option in Advanced settings of a view to make filtering ajaxifyed.

http://drupal.org/project/better\_exposed\_filters

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


# Question
Title: What is the best-practice for managing Aegir sites in Git?
I know there is a million ways this could be done, I'm more looking for the "best-practice" of how this "should" be done.

I have an Aegir setup with 4 different Drupal platforms. Within each platform there are several Sites. There is also modules/themes in the "all" directory that are shard between the sites.

How would one one manage these platforms/sites in Git?

Should we create 1 repo for the entire "platforms" folder? A repo for each platform folder? A repo for each platform folder and a repo for each site? A repo for each site and a repo for each "all" site?

What would be the best practice for this?

thanks!

# Answer
> 2 votes
Here's the recommended way for Barracuda/Aegir by Omega8:

> The recommended (and also more advanced) way to manage your Sites code is to use Makefiles (and then Drush Make) to build your Platforms, apply patches to contrib or custom modules etc, then using Profiler module to create your custom Installation Profile and manage in your Git repo just your Makefiles, your Installation Profiles and only your custom modules and patches – in a separate repo per module and per theme.

Source: http://omega8.cc/managing-your-code-in-the-aegir-style-110.

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


# Question
Title: drupal 7 views horizontal align not working in grid?
First time ever had this problem with views not rendering images to horizontal align in grid.

I have the Views module version 7.x-3.5 installed on Drupal 7.18.

I actually realized it is aligning for immediate view of links, but not within the view after clicking a link. How do I make all images horizontal align?

# Answer
You can horizontally align things with CSS

e.g

```
.container{
  text-align:center;
}

```

You can also align using a margin or padding.

In your case:

```
.view-galleryofimages .views-view-grid {
  margin:0 auto;
}

```

Should suffice.

See this summary for more info: CSS Horizontal Align
> 2 votes

---
Tags: 7, views
---