# Question
Title: Creating a very specific custom Views argument handler
I've been employed to help fix and finish a D6 site. It's already late so any answers like "you need to change the underlying DB structure" - well, we can't we're stuck with it. (It was built by idiots and we're doing the best we can.)

This is for an educational establishment with a curriculum that has changed in the past (we're migrating from an older system and all the data has to come over) and will change in the future. Each version of the curriculum has a version number. Every student is on one of those versions depending on when they started, so they are all active.

There's a taxonomy term for each of the three versions (D6 remember) which is attached to each Course Module. Each user has a User Profile node which has the user's version.

I am trying to create a Views 3 argument handler which takes a user's UID and delivers the NIDs of all the Course Modules tagged with it.

UID -\> User Profile node -\> TID -\> Course Module NIDs

The complexity comes for example where the TID must be from the Version taxonomy (user profile's have other tags).

Now I accept I may be overthinking this, maybe it can be done with relationships, but I feel using this would be so much easier to understand for any future developers because the views concerned are complicated and already have lots of relationships in them.

A solution would be great (I know, presumptuous) but I have contributed quite a bit to the community including modules and bug-fixes (lots on Search API last year). I have produced Views handlers before but it's never easy, and I have read most if not all the various websites and documentation.

Any help would be much appreciated.

# Answer
Well this is what I ended up with, it's not entirely pretty - and I've never really grasped how the Views structure works, but it works.

```
/**
 * Implementation of hook_views_data().
 */
function msc_cc_vc_views_data() {
  return array('msc_cc_vc' => array(
    'table' => array(
      'group' => t('MSC Version Control'),
      'base' => array(
        'title' => t('MSC Version Control'),
      ),
      'join' => array(
        'node' => array(
          // links directly to node via vid
          'table' => 'node',
          'left_table' => 'node',
          'left_field' => 'vid',
          'field' => 'vid',
        ),
      ),
    ),
    'users_version_tid' => array(
      'title' => t('User\'s Version Term ID'),
      'help' => t('The taxonomy term ID (from the Version vocabulary) of the supplied user UID.'),
      'argument' => array(
        'field' => 'uid',
        'handler' => 'msc_cc_vc_views_handler_argument_users_version',
        'numeric' => TRUE,
      ),
    ),
  ));
}

/**
 * Implementation of hook_views_handlers().
 */
function msc_cc_vc_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'msc_cc_vc') . '/views',
    ),
    'handlers' => array(
      // argument handlers
      'msc_cc_vc_views_handler_argument_users_version' => array(
        'parent' => 'views_handler_argument_many_to_one',
      ),
      // field handlers
      // filter handlers
      // relationship handlers
      // sort handlers
    ),
  );
}

```

And then the handler itself. Here I have hard-coded the Taxonomy VID because for this application it doesn't matter. You could steal the code for selecting vocabularies from other handlers, you might also want to allow multiple TIDs.

```
class msc_cc_vc_views_handler_argument_users_version extends views_handler_argument_many_to_one {

  /**
   * Called to implement a relationship in a query.
   */
  function query() {
    $this->ensure_my_table();

    // This is the supplied UID
    $uid = $this->value[0];

    // Not great Drupal but let's do some easy processing:
    $profile = content_profile_load('profile', $uid);
    $terms = taxonomy_node_get_terms_by_vocabulary($profile, 8);
    $version  = reset($terms);
    if (empty($version)) {
      drupal_set_message(t('The selected user does not have curriculum version.'), 'warning');
      return;
    }

    $def = $this->definition;

    // Rebuild the definition to create a unique relationship
    // that forces all results to have the selected version TID.

    $def['table'] = 'term_data';
    $def['type'] = 'INNER';
    $def['left_table'] = $this->table_alias;
    $def['left_field'] = 'vid';
    $def['field'] = 'revision';

    $def['table formula'] = "(SELECT td.*, tn.vid AS revision FROM {term_data} td INNER JOIN {term_node} tn ON tn.tid = td.tid WHERE td.tid={$version->tid})";

    $join = new views_join();

    $join->definition = $def;
    $join->construct();
    $join->adjusted = TRUE;

    // use a short alias for this:
    $alias = $def['table'] . '_' . $this->table;

    $this->alias = $this->query->add_relationship($alias, $join, 'term_data', $this->relationship);
  }
}

```

Enjoy.
> 2 votes

---
Tags: 6, taxonomy-terms, users, views
---


# Question
Title: Default statistics module. Count views of only published nodes when administration users see it
I need to change default functionality of statistics module.

I want to count views of only published nodes by administration users too. I can't find any hook for this.

Now if administration user see unpublished node, counter is increased.

Is this possible without hacking a core?

# Answer
> 0 votes
The Statistics module doesn't use any hook because generally works when Drupal has not completed its bootstrap phase. (That is if caching pages is enabled.)

What you can do is creating a custom module that runs right after the Statistics module, and execute code similar to the following one.

```
function mymodule_exit() {
  global $user;

  drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);
  $is_node = (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == NULL);

  if (variable_get('statistics_count_content_views', 0) && $is_node) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    $node = node_load(arg(1));
    if (!$node->status) {
      db_merge('node_counter')
        ->key(array('nid' => $node->nid))
        ->fields(array(
          'daycount' => 1,
          'totalcount' => 1,
          'timestamp' => REQUEST_TIME,
        ))
        ->expression('daycount', 'daycount - 1')
        ->expression('totalcount', 'totalcount - 1')
        ->execute();
    }
  }
  if (variable_get('statistics_enable_access_log', 0) && $is_node) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    $node = node_load(arg(1));
    if (!$node->status) {
      db_delete('accesslog')
        ->condition('title' => truncate_utf8(strip_tags(drupal_get_title()), 255))
        ->condition('path' => truncate_utf8($_GET['q'], 255))
        ->condition('url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '')
        ->condition('hostname' => ip_address())
        ->condition('uid' => $user->uid)
        ->condition('sid' => session_id())
        ->condition('timestamp' => REQUEST_TIME)
        ->execute();
    }
  }
}

```

---
Tags: 7, nodes
---


# Question
Title: #value or #default_value missing from field in $form array
I made a custom content type with a couple of fields. If i go to `node/add/custom-content-type` I have a dsm of `$form` in my `.module` file which shows the array in a krumo just fine. In the krumo the array shows the custom fields made in field UI, and each field has an array of 6 elements. Here's where the key `#value` and `#default_value` are missing.

Instead, the 6 keys are:

```
#type (String, 9 characters ) container
#attributes (Array, 1 element)
#weight (String, 1 characters ) 1
#tree (Boolean) TRUE
#language (String, 3 characters ) und
und (Array, 13 elements)

```

So obviously the question is how do I get those keys/attributes of that field in that array?

# Answer
See Why is hook\_form\_alter() so messy? for a bit of background, but basically you need to drill further down into the array.

Assuming it's a standard text field you would set, for example, the default value like so:

```
$form['field_name'][LANGUAGE_NONE][0]['value']['#default_value'] = 'foo';

```
> 1 votes

---
Tags: 7, entities
---


# Question
Title: how to save new value of autocomplete field with hook_form_submit?
creating a custom submit function for the form of mymodule

```
/**
 * Implements hook_form_submit()
 */
function mymodule_form_submit($form, &$form_state){

    $new_user = drupal_anonymous_user();
    // removed basic user fields here to make it more clear

    // save taxonomy checkbox field
    foreach ($form_state['values']['third']['field_functioncat'] as $key => $value) {
        if($value > 0){
            $new_user->field_functioncat[LANGUAGE_NONE][$key]['tid'] = $value;
        }
    }

    // save text field
    $new_user->field_firstname[LANGUAGE_NONE][0]['value'] = $form_state['values']['first']['field_firstname'];

    user_save($new_user);
}

```

Above code works but I'm having trouble saving the autocomplete field.

What I'm trying:

```
// get value of the form
$tid = taxonomy_get_term_by_name($form_state['values']['first']['field_city'], 'field_city');
// get the first array value and then the tid of the left over object:
$tid = reset($tid)->tid;
// save field to user profile
$new_user->field_city[LANGUAGE_NONE][$tid]['tid'] = $tid;

```

This works for existing terms, but when I put in a new term it can't get the id of the term because that term name is not created?

**How do I create the term name and get the tid to submit it to the user creation?**

**note:** I've created the field\_city as taxonomy term and linked it to the user profile so it's visible and editable in on the user edit profile page.

# Answer
> 1 votes
As you said if you're unable to find the tid then its a new term. You can save the new term using taxonomy\_term\_save()

For example,

```
$term = new stdClass();
$term->vid = <field city vid>;
$term->name = $form_state['values']['first']['field_city'];
taxonomy_term_save($term);

```

After saving the new term you can access the tid like this,

```
$term->tid

```

If you want to fetch the vid referenced with particular field then look at the following thread - How to get the field settings in drupal 7

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


# Question
Title: Is registering the path 'node/%/ajax' bad practise?
Would anyone say that registering the path 'node/%/ajax' would be bad practise, potentially causing trouble for other modules that takes the easy path to implement AJAX functionality on node links?

I've got a node type which has a lot of AJAX functionality, and it would be an easy and obvious solution to simply handle AJAX callbacks via this link as Drupal does all the work for me on links such as 'node/19/nojs' where 'nojs' would be replaced by 'ajax'. Fallback to non-js browser would be taken care of by itself.

My concern is that it might be stupid to "occupy" this path for a single node type, and that it is a too obvious path to occupy with regards to other modules?

# Answer
I wouldn't say it's bad practice as such, but I always go under the assumption it's *good* practice to prepend paths with your module name, e.g.

```
node/%/mymodule_ajax

```

That way you can be pretty sure that you won't run into any issues with other modules that don't follow the same convention.

For the record I don't think I've ever come across a module that implements the `node/%/ajax` path, but if you're at the start of your implementation and can change the path easily, I'd go with adding your module name to it.

It'll mean some extra work on the JS side, but if you want to be as sure as possible that you won't get path conflicts in the future, I think it's your best bet.
> 5 votes

---
Tags: 7, uri
---


# Question
Title: How do I create radio button for options on a Drupal Commerce product?
I just need some radio buttons for adding on components in a drupal commerce product. The best example is Apple's build a customized MAC or laptop where you add on specific elements to the product but start with a base. I also need to know how I can do this with ajax.

# Answer
> 2 votes
Sounds like you're after either the Commerce Product Option module:

> This module adds customizable product options to the "add to cart" form. The approach is generic, so all field types / widget can be used. This module is created only for the commerce module. For other systems you need different systems / approaches.
>
> The module provides a field called option set. You can assign to your commerce product. Each option set consists of a list of fields. If a product is connected to a option set the add to cart form will be extended by the fields of the option sets.

Or the Commerce Product Attribute module:

> This module provides some enhancements to the Drupal Commerce attribute handling.
>
> The improvement contains:
>
> - Attribute field for line item
> - Edit option for attributes

I'd advise installing both of those and seeing which fits your use case better. You'll have to handle the AJAX functionality yourself as I don't think it's built in to either.

---
Tags: taxonomy-terms, entities, ajax, commerce, javascript
---


# Question
Title: How to take the node reference field from views
I have added images through image content type and tagged the node to article content type nodes using node reference , while getting the article credentials through views , i cant figure out how to take the images from the tagged node reference field through views .

some option only avail to get the node reference field in views . 1)Title. 2)Title link. 3)Full content. 4)Print.

and two more which is not helpful for me .

Here i need to get a image from image content type which is tagged in article content type through node reference .

Anyone help for this as soon as possible.

# Answer
What you do is set up a relationship, as the image itself isn't the node reference, rather a field in that node. So, you go into Views and after setting it up to grab your article fields, you then set up a relationship, and there, you select that node reference field from your article type. Then, in fields, you go and select that image field, and there, you use that relationship. What this does is go and grab that image content type's node id from your article and then using that node id, grab the image field out of it for display.
> 0 votes

---
Tags: views
---


# Question
Title: Rate module: rate icon disappears and no vote is recorded
I am having a problem with the rate module. I have implemented it on node 'project' and it appears. When I click on 'thumbs up', the icon disappears. It looks like the AJAX is not working.

# Answer
> 4 votes
I was finally able to resolve this issue by enabling Clean URLs (configuration -\> clean URLs). Note, if you are prompted with a Clean URLs test that inevitably fails, you will likely need to uncomment the "RewriteBase" line in your .htaccess file.

---
Tags: rating
---


# Question
Title: What filter should be used for date field in views
I am building a view for showing upcoming events.

I have my own content type with CCK field with format Date (Unix timestamp) and widget as Pop-up calendar. All works fine, but i views i don't know how to filter it out. I have shown the filter criteria in a screeshot and i don't know what to give in the value field.

# Answer
In the value field you can use the PHP `strtotime()` function. So for example you select `Is greater than` and you put `-7 days` in the value field and your view will restrict to contents from 7 days ago.

Also a smoother solution for the end user is to expose this filter and they will be able to use a popup calendar to restrict the view.
> 4 votes

# Answer
You need to activate the date\_views module to see the filters appearing in the Views module interface.
> 8 votes

---
Tags: 7, views, datetime
---


title: Tokens for Webform Component

text:
# Question
Title: Tokens for Webform Component
Is there a way to set up a Webform such that I can turn component field submissions into tokens for use in the submission email?

For example, I want to include "Message from \[email address\]" in the email subject line. The default options only allow for including only the component field in the email (subject: \[email\]), or only custom text.

Is there a way I can turn the component field submission into a token for use in the email? Looks like there's a module for turning webform items into tokens, but it's not for use within webform.

# Answer
> 1 votes
I figured it out. Use `%value[key]`.

---
Tags: 6, webforms
---


# Question
Title: How can I avoid extraneous divs in my form?
When I create a form using the form API, the resulting html includes all sorts of unwanted divs. For example, if I use:

```
$form = array(
    'myFieldset' => array(
        '#type' => 'fieldset'
    )
);

```

The resulting html looks like this:

```
<form action="/drupal-7.15/?q=chercheur" method="post" id="form-chercheur" accept-charset="UTF-8">
    <div>
        <fieldset class="form-wrapper" id="edit-myfieldset">
            <div class="fieldset-wrapper">
            </div>
        </fieldset>
        <input type="hidden" name="form_build_id" value="form-87Dv5ezVpaLI5mD345ofMkLgPhsv_dawudUp73ePQTc" />
        <input type="hidden" name="form_token" value="sXXINWr7rmParm0tRJoEb6QKGIH_QH-ffRSOtnvxYY0" />
        <input type="hidden" name="form_id" value="form_Chercheur" />
    </div>
</form>

```

As you can see, two extraneous divs are added here. They are making the javascript I'm writing uselessly complicated, so I was wondering if there was a way to remove the extraneous divs. Ideally, I would like to obtain something like this:

```
<form action="/drupal-7.15/?q=chercheur" method="post" id="form-chercheur" accept-charset="UTF-8">
    <fieldset class="form-wrapper" id="edit-myfieldset">
    </fieldset>
    <input type="hidden" name="form_build_id" value="form-87Dv5ezVpaLI5mD345ofMkLgPhsv_dawudUp73ePQTc" />
    <input type="hidden" name="form_token" value="sXXINWr7rmParm0tRJoEb6QKGIH_QH-ffRSOtnvxYY0" />
    <input type="hidden" name="form_id" value="form_Chercheur" />
</form>

```

Is this possible?

# Answer
> 2 votes
The first `<div>` is hard coded into the `theme_form()` function, so you can override that in your theme's template.php file if you want to. You should be aware, though, that the wrapping `<div>` is actually there to ensure XHTML compliance; if you remove it your page will fail validation.

That said, this is the code to do it (replacing `MYTHEME` with the name of your theme):

```
function MYTHEME_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }

  return '<form' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</form>';
}

```

The only change from the original function is the removal of the `<div>` and `</div>` from the last line, and the removal of the XHTML compliance comment as that no longer applies.

Overriding the fieldset theme is pretty much the same, except you'll be borrowing the code from `theme_fieldset()`:

```
function MYTHEME_fieldset($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend><span class="fieldset-legend">' . $element['#title'] . '</span></legend>';
  }

  if (!empty($element['#description'])) {
    $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }

  $output .= "</fieldset>\n";
  return $output;
}

```

Once you clear Drupal's caches the extraneous markup should just disappear.

---
Tags: forms
---


# Question
Title: How to force absolute links on a menu tree in Drupal 7
# What I have

I currently have a menu with subitems printed out in my page.tpl like this:

in template.php

`function THEMENAME_preprocess_page(&$vars, $hook) {`

````
       $sitemap_tree = menu_tree_all_data('menu-sitemap');
       $vars['sitemap_expanded'] = menu_tree_output(i18n_menu_localize_tree($sitemap_tree));

````

`}`

then in page.tpl.php I have

`print render($sitemap_expanded);`

# What I want

While this prints out the entire menu tree perfectly I need the links to be absolute in stead of relative (what they are now). Any way of doing this in a Drupal fashion without too much extra lines ?

Thanx all.

# Answer
> 1 votes
What you probably want to do is theme the menu links differently for this menu. In D7, you would be overriding this function:

```
/**
 * Returns HTML for a menu link and submenu.
 *
 * @param $variables
 *   An associative array containing:
 *   - element: Structured array data for a menu link.
 *
 * @ingroup themeable
 */
function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

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

```

In `menu_tree_output()`, it also sets up per menu theme overrides, so, in your `template.php` file, you could create your own `YOURTHEME_menu_link__MENU_NAME()` function. On first flush, it could look something like this:

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

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

```

but this is an intellectual exercise for me, not a real world one, since I don't have a D7 sandbox to test it out in but it looks pretty accurate, or at least a starting point.

---
Tags: routes
---


title: $node->type and $node problems

text:
# Question
Title: $node->type and $node problems
The following doesn't work after calling the $node-\>type. Can someone help?

```
$nid = 0;
$term_1 = "";

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

$node = node_load($nid);

if(true == strpos($node->type,'article'))
{
    $result = field_view_field('node', $node, 'field_tags_test', array('default'));
    $term_name = isset($result['#items'][0]['taxonomy_term']->name) ? $result['#items'][0]['taxonomy_term']->name : "";
   }
 }

```

If I take out the inner if-statement, then it works just fine.

Thanks for any help.

# Answer
> 1 votes
`strpos()` returns the zero-based offset of the first occurrence of the test string. So if your string is `article` and the node type is `article`, it will return `0`.

Your `if` statement is basically doing this check:

```
if (true == 0) { ...

```

Since `0` is a boolean `FALSE` in PHP the condition isn't satisfied, and the `if` construct is never entered.

There are a few ways you can change the `if` statement which basically boil down to the same thing:

* `if ($node->type == 'article') {`
* `if (strpos($node->type, 'article') !== FALSE) {`
* `if (strpos($node->type, 'article') === 0) {`

# Answer
> 1 votes
current strpos return 0 (this is FALSE)

change

```
true == strpos($node->type,'article'

```

to

```
$node->type == 'article'

```

---
Tags: nodes
---


# Question
Title: Prevent certain user roles from showing up in results
I have a special role (role A) that I have to have set with view user profiles permission. I then have another role (role B) as well as the administrator role that I don't want for that roles users to show up in a views exposed filter and/or for the users with role A to be able to view their profiles. Is there:

a. a way to stop users from certain roles showing up in the exposed filters.

b. a generic way (or module) that stops certain roles being able to view other certain roles.

**UPDATE:**

I solved b with this module which works well:

http://drupal.org/project/view\_profiles\_perms

So just need to come up with a way of preventing certain roles from showing in a views exposed filter

# Answer
> 0 votes
Thanks to googletorp's answer here, I have figured it out. If anyone has a better way of doing it then please add. Basically you do a form\_alter on the exposed filter:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['field_my_field_target_id']['#options'] = mymodule_options_filtered_by_roles();
  }
}

function mymodule_options_filtered_by_roles() {
  $role_users = db_select('users_roles', 'ur')
    ->fields('ur', array('uid'))
    ->condition('rid', array(3, 6)) //Here I add the role id's I dont want to show
    ->execute();

  foreach ($role_users as $ru) {
    $role_uids[] = $ru->uid;
  }

  $users = db_select('users', 'u')
    ->fields('u', array('uid','name'))
    ->condition('uid', $role_uids, 'NOT IN') // get all the uids of users not in the above roles
    ->condition('uid', 0, '!=') // get rid of uid 0
    ->execute();

  $user_array = array('All' => t('- Any -')); //Start the array with all
  foreach ($users as $user) {
    $uid = $user->uid;
    $name = $user->name;
    $user_array[$uid] = $name;
  }
  return $user_array;
}

```

# Answer
> 1 votes
For A.

Set up another filter in your view for "User: Roles". Choose the Operator "Is none of" and then, choose in the options the role you dont want seen. You can use the roles filter after the exposed one.

Attached is a pic of the user:roles filter section. The options are cutoff to the right (taken from a working site..want to leave the role names private)

You can also expose the role filter and, limit it to the selections you choose in the options pane.

---
Tags: views, users
---


# Question
Title: Performance and optimisation when using panels with views and content pane
I would like to know if there is a *best practice* when we use panels with views and content pane?

**Some explanation:** I have a layout with multiple blocks (related to the taxonomy etc.) and a main content.

I'm asking myself what is the best way to have the better result in term of performance: I made many `content pane` for my views (as many as there are blocks, see my picture for a better understanding)

But i don't know if it's very good to do that.

I would like to know if it's not better to do just one `content pane` and to check or uncheck the fields that i want in each block.

My site i slow so i try to optimize it. I don't know how panels works "behind the scene".

Thanks

# Answer
The primary thing you should do, is cache as much *rendered output* as you can. If you cache the generated markup itself, whether you're Views configuration is optimal mostly becomes a non-issue.

Views itself, can be cached with Views content cache, or if you complicated invalidation criteria, with a long timed cache and Cache actions.

More experimental, is a module I've written myself, called Panels cache, which moves the caching one layer higher up, for even better performance, but it requires that the content being cached all comes from the same entity. (I use the module in production, but would still love testing and feedback on the module)

On the actual Views configuration, you should avoid having a single with multiple panes, *if you have a lot of overrides*. If your displays are significantly different, you waste processing time as builds must build and then alter the display. This however, will be a very small optimization, compared to the caching solutions suggested above.

You can read about more different performance improvements in my answer on How do you improve Drupal performance?
> 3 votes

---
Tags: views, panels
---


# Question
Title: Cascading taxonomy term selection widget
To be honest, I'm not sure if cascading is the right term, and if it's not then this can just be edited in the future for clarity.

I need a taxonomy term widget that is a drop-down list, and all that is initially populated are the top-level taxonomy terms in the particular vocabulary associated with the widget. After selecting a top-level term, another drop-down list is added next to the previous (the one you just selected from) with all of the children of the selected term. The parent drop-down list is then disabled.

You should be able to click a link to go "up a level", basically removing the right-most drop-down list at the time and re-enabling the right-most list after that.

For example, say I have the following structure:

* A
    + AA
    + AB
    + AC
* B
    + BA
    + BB
    + BC
* C

The initial drop-down list would just contain: A, B, and C. You now select 'A'. The list with A, B, and C would then become disabled, and another list would be added directly to the right of it with the terms: AA, AB, and AC.

The term submitted along with the form would be the term represented by the right-most disabled list's selection at the time.

Is there anything that exists with this functionality (or similar)? If so, I haven't seen it (and I'm looking hard). Otherwise I guess I'll just have to code it up myself, but I'm hoping I don't have to invent a new wheel.

# Answer
> 3 votes
You can use the Hierarchical Select module:

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

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


# Question
Title: How do I get the display id of a view in Drupal 6?
I'm trying to use the views\_data\_export module to get the content of a Drupal 6 view in xml format. On the module's page, it says to use this command:

```
drush views-data-export [view-name] [display-id] [output-file]

```

I can figure out the view name well enough, but how do I get the display id?

# Answer
Edit the view, then hover over the tab link for your display. Look at the URL. It will look something like:

http://thesite.com/admin/build/views/edit/the\_view\_name#views-tab-the\_display\_id

You should be able to use "the\_view\_name" and "the\_display\_id" in the drush command.
> 2 votes

# Answer
If you go and look/edit a view, the display-id is the "Machine Name" listed when you click on any of the displays. It looks like 'page\_#' or 'block\_#' by default plus you also have the 'default' display. They can be anything, though, if you edit them.

ADDITION per @MPD. This is what I see here on D6 with Views 3, so I guess it doesn't exist with Views 2 (which I've not used in ages)

and the Machine Name: `page` in the Basic Settings box is telling me this display\_id is `page` in View `archive`
> 2 votes

---
Tags: views, 6
---


title: Drupal 7 Field Performance

text:
# Question
Title: Drupal 7 Field Performance
I've created a Content Type that will have \>50 fields. I've noticed that each field has a corresponding table. Is Drupal joining 50 tables in order to load the page with all of the designated content?

Would a high amount (but not an unnecessary) amount of fields cause a noticeable decrease in performance?

Thanks in advance for your answers.

# Answer
Answer really depends on your database backend. If you're using something like MySQL 5.6 or MariaDB 5.5 I would say probably not http://www.mysqlperformanceblog.com/2012/04/04/join-optimizations-in-mysql-5-6-and-mariadb-5-5/. If you're using a different database backend, it will be hard to tell without testing.

If using something like MongoDB for the field backend then it shouldn't cause any performance issues.

If you don't want to go with MongoDB or bleeding edge MySQL you can also look into using something like the Entity Cache if you find that all the fields is causing performance issues.
> 7 votes

---
Tags: 7, entities, performance
---


# Question
Title: Site running from accidental upload of core in subdirectory
Several months ago I accidentally uploaded the folder containing Drupal 6.25 core files to sites/all/modules.

The site now sees that folder as the base install and ignores the installation in the site root. How can I safely get Drupal to look at the files in the site root as the base install and delete these files? I tried simply deleting them when I did it and it takes down the site with a configuration error.

Configuration error: 500 - Internal server error - neither front end or back end will load

# Answer
> 1 votes
I had a similar incident where someone had put a second set of core modules in a second folder called "modules" inside the main modules directory. As a result Drupal was running off of the `system.module` located in `modules/modules/system`. This made updating the site problematic.

The only way I fixed it was by dumping the database as a text file (.sql), editing the `modules/modules` file paths in the systems table, then re-importing, overwriting the database. You may also be able to do this via MySQL commands or using an interface such as phpMyAdmin. You should also look at my other answer about steps taken when editing the database. (*You would almost think that cowboy edits of the database is all I do everyday*)

Know that editing the database is not best practice, but sometimes it is the only fix. Make sure that you should have a backup in case you mess things up, which in most likely happen on our first attempt.

---
Tags: installation
---


# Question
Title: complete installation proess for drupal 7.15 and ubercart-7.x-3.0
I install drupal 7.15 and working successfully. After that i add ubercart-7.x-3.0 module. enabled product and store module but cant enable cart and order. how to enable cart and order. I am the beginner of drupal and ubercart. please help me

# Answer
> 1 votes
**Note:** This is an alternative way by using Drupal commerce module and not the Ubercart module.

As a beginner I'd suggest you should try the Commerce Kickstart distribution first. It includes the latest versions of Drupal core, Drupal Commerce, and the other modules it depends on. You can explore Drupal after that ;)

Just make sure you select the Commerce profile while installing (see screenshot) And also create the example content after configuring the site

---
Tags: ubercart
---


# Question
Title: Header region causing the page to be too wide
When viewing my website on Internet Explorer there seems to be a big space on the right where the page has scroll bars to take in the full width. I think its to do with my header image. It seems ok in Firefox and chrome. Can anyone suggest a way to get this working on IE?

# Answer
Its because of your fb\_reset facebook iframes.

```
<div class=" fb_reset" id="fb-root">
<script src="http://connect.facebook.net/en_GB/all.js" async="true"></script>
<div style="top: -10000px; width: 0px; height: 0px; position: absolute;">

```

If you remove the css rules in the style and change to

```
<div style="display: none;">

```

Add to css:

```
.fb_reset {
display:none;
}

```
> 2 votes

---
Tags: theming
---


title: Drupal Relative Path

text:
# Question
Title: Drupal Relative Path
I am using Drupal 7. The website I am on was configured previously. My goal is to add an external link to a page. However, i am having trouble. Every link I add to any page is read as a relative link. For example, if I have the following code:

`<a href="http://www.google.com/">Google</a>`

The URL in the browser becomes: dev.mysite.com/#http://www.google.com But, I want the URL to be http://www.google.com

First, Can i fix this using PHP? Second, Is this something the Pathauto Module is responsible for, or maybe the Rewrite module? Both are enabled on the site Lastly, is it a mod rewrite issue? If so, how would i fix it?

# Answer
> 2 votes
You must have some kind of text filter that is acting on your text see what filters are applied here: admin/config/content/formats

Or you are using a WYSIWYG editor to add the link. If that is ckeditor, you have to set relative links to "Other" rather than http in the link editor.

---
Tags: path-aliases, .htaccess, uri, navigation
---


title: Show image filenames on Drupal 7 node

text:
# Question
Title: Show image filenames on Drupal 7 node
I upload multiple images to a node using one content type image field. I need to render the file name for each image under the image when viewing the node, all I get at the moment is just a page of images. Tried a view but that REALLY screws everything up. Any ideas how this can be done on the node?

Thanks.

# Answer
> 2 votes
You can do this using `hook_preprocess_node()` either in your theme's template.php file, or a custom module file. You'll want to use API functions to get the data from the node rather than accessing the arrays directly, so you don't need to worry about language codes etc.

```
function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  if ($node->type == 'the_type' && $vars['view_mode'] == 'full') {
    $field_items = field_get_items('node', $node, 'field_name');

    if (!empty($field_items)) {
      $filenames = array();
      foreach ($field_items as $item) {
        $filenames[] = $item['filename'];
      }

      $vars['filenames'] = theme('item_list', array('items' => $filenames));
    }
  }
}

```

You can obviously change the output to whatever HTML you need, but the above will produce an unordered list of image filenames, available in the `$filenames` variable in your node.tpl.php file.

# Answer
> -1 votes
in templete.php file create

```
    function THEMENAME_preprocess_node(&$vars){
       dpm($vars)//find image name etc with devel module enabled
       //for example i have field - field_image first element is 0 and filename is = file_name
       $vars['image_name'] = $vars['field_image'][0]['file_name']; //i have created a new variable
  //  $image_name, now u can out this variable in your tpl file
    }

```

output them in your \*.tpl.php file do this

```
<?php print render($image_name) ?>

```

you can actually put them into array and foreach

---
Tags: theming, nodes, entities
---


# Question
Title: Drupal 6 Module Storing configuration setting in file
I have built a module that uses encryption and I need to store the encryption key somewhere so that it is configurable.

I would like to put it in a file (the equivalent of web.config of .NET website) so that it can be altered but is safe.

Assuming the web server will take care of restricting access to the file, where should I put this file? Is there an existing file for adding configurable settings to per module or even per website (and how can I read these)? Do I have to do something on module install, or in the module info file?

Any help would be appreciated.

# Answer
The Question was not so clear to me but I can suggest you 2 things.

1. You can use variable\_set('salt', 'unique\_hash'); in the .install file in hook\_install(). Then this variable will be stored in the variables table. In hook\_uninstall() you add variable\_del('salt'); So this will remove the variable from the table if the module is uninstalled. You can access it via variable\_get('salt', 'default\_value'); Also if you want to change it then make a form text field and in the hook\_submit for that form make a variable\_set('salt', 'edited\_value') call. This will update the variable in the variables table. Use user\_access() to restrict all users to access it.
2. The second is, to make a text file in the server file system and make it's permission as 644. Then read the file by php's fread() function and access the file value.
> 0 votes

---
Tags: 6
---


# Question
Title: Trying to show multiple relationships with Drupal view
I have a website with Car manufacturers (c\_manufacturer), each Manufacturer has car Models (content type: c\_model), and each model has picture (content type: model\_pictures).

I'm trying to create a view to display on every Manufacturer's page and show the car pictures of the car models that belong to that Manufacturer.
Using Contextual Filter for the Manufacturer node ID, I added 3 relationships:
Content: c\_manufacturer - reverse
Content: c\_model - reverse (Using Relationship: c\_manufacturer)
Content: model\_pictures - reverse (Using Relationship: c\_model)

I tried to show the Title field (something that all of the content types have on my site)
and I keep getting no result on the view Preview (when giving a manufacturer ID as an argument), what am I missing ?

# Answer
> 1 votes
I would have used references to start with.

You would create a manufacturer (e.g BMW). Now BMW will have a picture/logo description etc.

Then you would create a CAR (e.g 320i). Now the car will have all the fields you want and most importantly the reference to the manufacturer.

You will then need to create a block view of content type CAR.

**Fields** will be picture and title(320i).

**Filters** will be "Content: Type (=Car)".

**Contextual filters** will be "Content: Nid".

Then in Structure-\>blocks you move the newly created block view into the Content section under "Main page content".

When visiting the BMW node the view should display the car + title.

---
Tags: 7, views
---


# Question
Title: Can I write MySQL settings in drupal settings.php file?
I am using Drupal 7 and i am getting `MySQL server has gone away` error in my current site. By doing Google i figured out that i need to increase some of the parameters of my.ini file

```
key_buffer
max_allowed_packet
table_cache
sort_buffer_size

```

Is there any way that I can write this in Drupals settings.php?

# Answer
No, those need to be set in your MySQL server's my.ini/my.cnf file.

Those settings can't be changed on the fly from any process (PHP, Apache, even MySQL itself), you need to set them in the .ini/.cnf file and then restart the MySQL server for the changes to take effect.
> 9 votes

---
Tags: database
---


title: Newsletter and email limit of provider

text:
# Question
Title: Newsletter and email limit of provider
> **Possible Duplicate:**
> How to add newsletter functionality in drupal 7 (just stable modules if possible)

I need to know a good email newsletter system for Drupal that can trigger email send in batch. I know in WP how to do that, but have to previous experience with Drupal. I Have about 1000 email, and the provider allow only 200 mail / hour, so i need and option to send let's say 150 mail / hours and let the system go under the radar. Please, don't tell me to use mail-chimp, i know and it's not in Drupal but outside. i like a solution build in !

thanks in advance

# Answer
> 0 votes
My advice is to use "MailQ" (For Drupal 7 you can use "Queue Mail" instead) and "Elysia Cron" modules together.

Configure MailQ module to send 50 mails per one batch.

Configure Elysia Cron module to run MailQ cron hook every 15 minutes. (note you need configure you cron job to run every 5 minutes or even often, more details in Elysia Cron readme.txt)

In this case MailQ will send 50 emails each 15 minutes - and you will got no more than 200 emails per hour.

---
Tags: 6, emails
---


# Question
Title: How fix an inverted execution order problem?
When the order of calling the implementation of a particular hook by different modules matter, you can change the weight of modules by tweaking system database table.

But it looks like I'm in a more difficult situation involving interaction of the field\_group, and the clientside\_validation modules with my custom module.

I use `hook_field_group_build_pre_render_alter()` provided by the field\_group module to add some `'#states'` attributes to a field group form element.

The states I add change the `'#required'` attribute, besides other things. This form relies on a clientside\_validation module suite to provide a JavaScript validation.

There is a brand-new module, clientside\_validation\_states which perfectly fits me, but I ran into the difficulties trying to make use of it. clientside\_validation\_states uses `#after_build`, which should be called after my code, but `hook_field_group_build_pre_render_alter()` is called in field\_group by using a '#pre\_render' FAPI attribute.

This together results in an inverted calling order. Do you have any idea on how to fix this?

# Answer
Posted this answer in the issue @attiks mentioned as well:

The easiest thing to do is to add the states in hook\_form\_alter() or in hook\_form\_FORM\_ID\_alter().

I got Clientside Validation to work on fields within a group, within a field collection.

Here's my code:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function fgtest_form_article_node_form_alter(&$form, $form_state) {
  $group = 'group_customgroup';
  $collection_bundle = 'field_my_collection';
  $fields = array_keys($form[$collection_bundle]['und'][0]['#group_children'], $group);
  foreach (element_children($form[$collection_bundle]['und']) as $delta) {
    $collection = &$form[$collection_bundle]['und'][$delta];
    foreach ($fields as $field) {
      $collection[$field]['und'][0]['value']['#states'] = array(
        'required' => array(
          "#edit-field-my-collection-und-{$delta}-field-make-required-und" => array('checked' => TRUE),
        ),
      );
    }
  }
}

```

And here's my setup:

**Node Article:**

**Field Collection field\_my\_collection:**
> 2 votes

---
Tags: 7, forms, hooks
---


title: Fixed width for columns in grid

text:
# Question
Title: Fixed width for columns in grid
I have a block with a 3-column grid view. The three products are next to each other on the left side. I cannot get them to use the full block width, so that each column has a fixed width, for example 33%.

I have searched for an answer the whole day. I tried some CSS adjustments, but I can't get anything to work.

# Answer
> 1 votes
I had success with explicitly setting the width of the table that contains the images/titles.

Set the width of `<table class="view-view-grid cols-3>` to 100% in your CSS and see if that doesn't help.

---
Tags: views
---


# Question
Title: Import Drupal Database, Excluding Database Connection Parameters
Another developer and I have the same Drupal theme installed. The other developer is the one doing the development work and I'm simply trying to import his updates into my theme so I have the latest and greatest and can see how the work is progressing. I am able to IMPORT his EXPORTED database, however, his MySQL database connection parameters are different in that he's not using a password, and my MySQL database connection parameter INCLUDES a password.

The way I am importing his export, is simply by using PhpMyAdmin, I first DROP all the website's Tables, and then simply IMPORT his EXPORT.

QUESTION IS: Which tables should I NOT Drop, and when he does his EXPORT, which Tables should he NOT Export... so I receive everything I need to get all the updates into my database, but don't have a problem with database connectivity?

# Answer
I've actually never heard of database settings being stored in the database. Are you sure you aren't updating your site's **settings.php**-file as well?

Do you have different database prefixes?

Could it be related to some stale cache?
> 1 votes

# Answer
Backup and Migrate Module could be of help to you.
> 0 votes

---
Tags: database, importing-exporting
---


# Question
Title: How to use a translated taxonomy in autocomplete term-reference fields?
When I translate a taxonomy to other languages, I cannot use it in autocomplete term-reference fields.

The auto complete field will show items only in the default language; if I try to fill the form from another language, nothing shows up in the field when I type.

It happens only when I use the autocomplete widget.

I am using Drupal 7.15.

# Answer
Are you using 'Entity Translation' or the core 'Content translation'?

I think the sub-module **Multilingual select** (from **Internationalization**) should handle this for 'Content translation' (didn't test it, though).

But for Entity Translation, this doesn't seem to work (yet): see Entity translation and the Multilingual select i18n submodule interactions and Language aware edit form and autocomplete.
> 2 votes

# Answer
read this "Localize terms show always the default language" . but I personally suggest you don't translate terms, you can add both terms in you vocab . terms\_data table impproved in Drupal7 and handle very much terms charmly.
> 1 votes

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


# Question
Title: Redirect language-specific URL to correct path prefix
Drupal 7. I have a multi-language website. Let's call it website.com.

At admin/config/regional/language/configure/url I have selected "Path prefix" as the "Part of the URL that determines language".

My host is using nginx. The hosting company has configured the site so that when I go to my Spanish language url (let's call it sitio-web-en-español.com) the browser ends up at website.com.

What I would like it to do is end up at website.com/es so that the users have Spanish language immediately without having to use the language switcher.

My question: Can I do this within Drupal or do I need to get my hosting company to change their configuration?

Thank you!

# Answer
> 1 votes
Here's the solution that worked for me.

In the end I came to the conclusion that it was easiest to do this at the domain hosting company end.

So in the account where my Spanish-language domain (sitio-web-en-español.com) is managed, I set up a redirect that goes to:

website.com/es

... and it seems to work fine.

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


# Question
Title: How to make views slideshow, shows more items per page than one
I made a slideshow using views slideshow in drupal 7 to show bunch of logos, but it only shows one item per page, what I want is to show for example 6 logos per page when the visitor hit next, it slides to next 6 items and etc.. I checked views slideshow field setting, but couldnt find anywhere that I can set how many items to show per page.

thanks.

# Answer
> 26 votes
In Views Slideshow 7.x-3.0, you can find this option by selecting slideshow as your format and then clicking on settings. From there, you need to find the Action section and check "View Action Advanced Options", there you can choose how many items to display.

# Answer
> 4 votes
From your explanation, you would require a module called jCarousal. It has built-in views support too. You can configure its settings change the number of items to show per page.

---
Tags: 7, views
---


title: Switch theme based on screen size

text:
# Question
Title: Switch theme based on screen size
I need to switch my theme based on the users screen size instead of their user agent. Currently I'm using the Browscap & Mobile Switch modules and they work perfectly. My problem is that for tablets, I want users to use the desktop site. For mobile phones or anything under a 7 inch tablet, I want users to use my mobile site. What modules can help me with this OR how can I create the switch based off screen size?

UPDATE: I've just found ThemeKey. Anyone know if using this in conjunction with Browscap/Mobile Switch will cause issues?

# Answer
> 1 votes
The ThemeKey module is definitely the way to go for this. Here is a quote about it (from the module's project page):

> ... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:
>
> * 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

---
Tags: theming
---


# Question
Title: How do prevent other users from seeing certain views in a user profile?
I have setup a View which showscertain information to a user, when he/she is logged in provided that logged in user is referenced in the content type containing that information.

The View shows this information user the name of the `uid from the url`.

The website is such that the logged in user can view the profile of other users, this makes the logged in user have access to the information of the user whose profile is viewing which shouldn't be the case. Please tell me how do I prevent this?

# Answer
> 1 votes
This is honestly, a question that I have faced many times. You have 2 options.

Use a path like `/my_posts` and then using UID argument with "logged in user" as the failback argument. This is a common wa. Modules like Flag comes with default Views that uses "logged" in user as the failback argument so it doesn't need to mess with php.

However, the ideal solution would be,

A. Add the UID argument as necessary (user reference, author, etc).

B. Set `When the filter value is NOT available` to `Provide default value` and then to `User ID From URL`.

C. Check `Specify validation criteria`. and choose "php code".

```
<?php
global $user;
if ($user->uid == $argument && is_numeric($argument) && $argument >0 ){
  return TRUE;
}
?>

```

D. 'Action to take if filter value does not validate' =\> `Display "Access Denied"`

Good luck!

# Answer
> 0 votes
Let's say for example:

You have parents who can log in to a site, and see data relating to their children.

So: you have a 'child' content type with a 'user reference' field pointing at the parent's user account.

In your View, do this:

Click 'Advanced' (top left)

Contextual Filters - Add

Find the field which contains the user reference (in my case this is called 'Parent')

WHEN THE FILTER VALUE IS NOT IN THE URL

Provide default value

Type = User ID from Logged In User \<--- this is the important bit.

Save.

You can test the view at the bottom, where it says 'Preview with contextual filters' --- put the User ID of the user you want to test for.

Now, try logging in as that user, and go to the View, it should be filtered the way you need.

---
Tags: views, users
---


# Question
Title: Unable to use user fields from the global variable $user
I have created a module where I am declaring `$user` as global variable in `hook_init()`. I can access the values of `$user->x_field` in page.tpl.php. When I try to use `$user->x_field` in `hook_contents($display)`, it causes the following error:

> Undefined variable:x\_field

Can I use the user fields in `hook_contents()`? Am I doing it the wrong way?

# Answer
The global `$user` variable doesn't contain all the values you would find from a user object loaded from the database; in particular, it doesn't contain any field associated with the user entity. If you need a full-loaded user object for the currently logged-in user, you should use the following code.

```
$account = user_uid_optional_load();
// Use $account to access the user fields.

```

If need to load a full-loaded user object knowing its user ID, then you should use the following code.

```
$account = user_load($1);
// Use $account to access the user fields.

```

Also in this case, you could use `user_uid_optional_load()`; since it only passes the given user ID to `user_load()`, you can directly use `user_load()` and use `user_uid_optional_load()` when you don't have always a user ID, and need the user object for the currently logged-in user in that case.
> 3 votes

# Answer
according to globaluser in drupal ,$user is global variable object , you can use it every where, the only thing you must do before it is this

```
    global $user;

```

after this, $user object refer to logon user.
> 0 votes

# Answer
I found solution for your problem,
first load user and after it use x\_field

```
global $user;
$user_info = user_load($user->uid);
$user_info->x_field['und'][0]['value'];

```
> 0 votes

---
Tags: hooks, users
---


title: EntityFieldQuery in a loop

text:
# Question
Title: EntityFieldQuery in a loop
i'm using EntityFieldQuery to retrieve some nodes according to some conditions.

```
foreach (array("important", "normal") as $type) {
  $query = new EntityFieldQuery();
  $query->entityCondition("entity_type", "node")
    ->entityCondition("bundle", "Announce")
    ->fieldCondition("field_ann_cat", "value", array($nid))
    ->fieldCondition("field_ann_type", "value", array($type));
  $result = $query->execute();
  var_dump($result);
  // Some actions
}

```

The first time it loops, i have my announces marked as "important" (`field_ann_type`). The second time it loops, i dont have any announces marked as "normal".

I've tried to intervert them, and when i have `array("normal", "important")` instead of `array("important", "normal")` in my foreach, i can see my announces marked as "normal", but not my announces marked as "important".

Does anyone knows why? Thanks.

# Answer
> 2 votes
There's no need to use a loop, if you pass an array as the 3rd argument to `fieldCondition` it will create an `IN()` statement for you in MySQL.

As far as I can tell your query should just look like this:

```
$types = array("important", "normal");
$query = new EntityFieldQuery();
$query->entityCondition("entity_type", "node")
  ->entityCondition("bundle", "Announce")
  ->fieldCondition("field_ann_cat", "value", $nid)
  ->fieldCondition("field_ann_type", "value", $types);

$result = $query->execute();

```

If you want to go one step further and ensure the `IN` operator is used you can pass it (but it's not necessary):

```
$query->fieldCondition("field_ann_type", "value", $types, 'IN');

```

As NenadP has already mentioned, there's no need to explicitly use an array as the 3rd argument unless you're putting the value in inline, e.g.

```
$query->fieldCondition("field_ann_type", "value", array("important", "normal"));`

```

# Answer
> 3 votes
It may be because you are doing this:

```
->fieldCondition("field_ann_type", "value", array($type));

```

try just check it against $type like this:

```
->fieldCondition("field_ann_type", "value", $type);

```

---
Tags: database
---


# Question
Title: How do I prevent Drupal from sending an email to the admin every time a new user is created
I've inherited maintenance of a drupal 7 site from another group. Currently, every time a new user account is created the admin is sent an e-mail about it. The admin wants this disabled.

I've been unable to find what's sending the e-mail. There's no workflow rule for it, and the Trigger module is disabled. Admin Notify doesn't have any setting turned on for new users, and visitors do not require admin approval in order to create their accounts.

Some of the research I've done suggests that this is drupal core functionality with no settings attached to it. If that's the case, how would I go about stopping it? Any ideas on where else the setting might be for the e-mail?

# Answer
> 1 votes
Do the email sent to the admin have the link to activate the user's account?

If so, go to: `example.com/admin/config/people/accounts`

Check the REGISTRATION AND CANCELLATION paragraph (should be the 2°): if `Visitors, but administrator approval is required` is checked, every time a user create an account an email is sent to the admin to let him approve/refuse the user new account.

---
Tags: 7, emails, users
---


# Question
Title: Setting up a development environment for drupal site
I have a production site at example.com (with a subdomain multi-install) and I have been meaning to setup a development environment at beta.example.com (also having all of the multi-sites). I would like these machines to be as identical to each other as possible so the push from the development machine to the production machine goes very smoothly. Is it possible to have the sites folders named the same on the development machine as they are named on the production machine? That is, they do not have beta in the file name. Does this involve hostname rewriting? Can apache even do that?

# Answer
Yes it is possible to have the same DIR structure as on your live site using sym links.

Suppose subsite.example.com is a folder on live site on production you need a link like `beta-subsite.example.com -> subsite.example.com` And you can use subsite.example.com in both your environments.

SO folders on Live site will be

* default
* subsite.example.com

In dev environment one extra link has to be created pointing to subsite.example.com.
> 3 votes

# Answer
@kantu's answer makes sense for Drupal 6.

When you migrate to Drupal 7, you can create a sites.php file. In it, you can create mappings from domain/path/port triplets (eg, the parts of the HTTP request) to paths within sites. For example, you could make

```
$sites['beta.example.com'] = 'example.com';

```

and this would map requests from beta.example.com to sites/example.com/.

I don't really see a way around having individual settings.php files for each, though.
> 3 votes

---
Tags: staging
---


# Question
Title: Printing a function on a content type page?
So if I have a custom function with a DB query within *template.php* such as

```
function innovista_get_page_children() {

 $result = db_query("SELECT link_path FROM {menu_links}");
 return $result;

}

```

and I have a content type specific template page, then how do I echo the results in the template file?

I tried this:

```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
    print $result;
}
?>

```

I get the following error

> Recoverable fatal error: Object of class stdClass could not be converted to string in include() (line 83 of /var/www/vhosts/vidanlawnes.co.uk/innovista2/sites/all/themes/innovista/node--level\_1.tpl.php).

If I remove print $result; and replace with print 'hello'... e.g

```
<?php
$results = innovista_get_page_children();
foreach($results as $result){
//print $result;
print 'hello ';
}
?>

```

It echoes hello out multiple times, so the query is providing results, but I can't seem to print them as $result. Any ideas?

Thanks for your time

# Answer
The error message itself is clear I think. You are trying to print an object as a string. otherwise, your query seems correct.

```
function innovista_get_page_children() {

 $result = db_query("SELECT link_path FROM {menu_links}");
 return $result;

}

<?php
$results = innovista_get_page_children();
print '<pre>';
foreach($results as $result){
    print_r($result);
}
print '</pre>';
?>

```

Now you will see a formatted variable information of each $result. it will look like

```
stdClass Object (
  [link_path] => admin/structure/views
)

```

So when you print the results, it will be like,

```
<?php
    $results = innovista_get_page_children();
    foreach($results as $result){
      print $result->link_path;
      print '<br/>';
    }
?>

```

However, keep in mind that it's never OK to print link paths or database queries like this. It will cause huge performance problems and will arise security problems. Try to use url() and/or l() functions for links (suggested it because you seem to make a link). Also, in most cases, there is a function for core/contrib modules to retrive data.
> 3 votes

# Answer
Every theme function/template runs `hook_preprocess_HOOK()` and `hook_process_hook()` before executing the function/template. `hook_preprocess_HOOK` is where you'd want to set up any new variables. The hook is passed an array of variables by reference, and you add to that array. The key of the array becomes the name of the variable in your template. People often try to keep all the logic out of the template file in this way. For example to set up a variable `$foo` in a page template (ie what's used for `theme('page', ...)`) you could do this.

```
/**
 * Implements hook_preprocess_page().
 */
MYMODULE_preprocess_page(&$vars) {
  $vars['foo'] = 'bar';
}

```
> 1 votes

# Answer
First I dont suggest put your function in template.php directly, (you can put in in custom module)
I suggest you act more professionaler in function, This code showed your are begginer in drupal developing,
however . this code have to work because template.php function in exist form basic drupal bootstrapping.
Your problem is your function maybe not return anything and $var will be empty. When I was begginer in drupal put my global fuction in themplate.php and use them in every where i want, test something like this

```
function myfunction() {

      $result = db_query("SELECT field FROM {table} WHERE field = 'query' ");
       if ($result)
       return $result;
       else
       return "sorry,no result";
     }

```

and in your tpl file

```
<?php
      $myvar = mytheme_myfunction();
      print $myvar;
?>

```

I know this is not principle method but sometimes we just need it just work. :)
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Content Type Display different per theme
I'm using ThemeKey to switch my theme for mobile users. The problem i'm having is that i'm using image zoom for my products and on iphones it blocks the dropdown due to a hidden element. My question is, is it possible to change the way a content type is displayed per theme without disturbing the regular 'desktop' version of the site?

Clarification: What I'm referring to is when you go to Manage Display, how can you reposition content entities differently per theme.

# Answer
> 1 votes
Those settings are one per content type and will be applied for all themes you enabled.

I suggest to do that within the themes themselves - start by adding the node--\[content type machine name\].tpl.php and then exclude/move around the fields you need.

Example for hiding a specific field:

```
hide($content['field_name_goes_here']);

```

Other useful things:

```
hide($content['links']);
hide($content['comments']);

```

To see a full list of fields and exact names, install devel and do a `dpm($content);` in tpl file.

Also check the template\_preprocess\_node() function for more and better control of the fields values.

---
Tags: theming
---


# Question
Title: How do I configure the "input format" for the File Tree module?
My question is in the input format step. How do I "add File Tree to your input format?"

Here are the instructions from the File Tree module: "Enable the module, and add File Tree to your input format. Then, enter \[filetree dir="some-directory"\] into the body field of a node, and it will render a list of all the files in that folder. (Note, the folder must reside in your site's "files" folder.)"

When I go to configure the module, I'm taken to Home » Administration » Configuration » Content authoring » Text Formats

Filtered HTML - anonymous user, authenticated user, administrator Full HTML - administrator Plain text - All roles may use this format.

It says "Improper text format configuration is a security risk," so I want to make sure I have this right. What is it that I need to add where to make File Tree work, safely and securely?

---

I found how to set the input format to use the input filter implemented by the File Tree module:

* Go to text format configuration, accessible again by Home » Administration » Configuration » Content authoring » Text Formats (or by clicking on "Configure" for the File Tree module)
* Click on Full HTML.
* Halfway down, there should be several check boxes, among them one for "File Tree." Just check that box and you're set.

Now, from here, I still haven't been able to get the module to run. Despite this change, I still see `[filetree dir="dirname"]` printed plainly where I try to insert a file tree.

(This video helped me: http://www.youtube.com/watch?v=ASKqit7kDak.)

# Answer
> 2 votes
If you want to get File Tree to work, after you set up the input filter, the directory you are referring in `[filetree dir="dirname"]` must be a directory contained in your site's "files" directory. If you want to display all the files in the "files" directory use `[filetree dir="/"]`, or if you want to display a particular directory, put the files in a directory (say, dir1) under files and specify `[filetree dir="/dir1"]`.

---
Tags: input-formats
---


title: Related Links for Content

text:
# Question
Title: Related Links for Content
In the design for my article pages I have related links in a right hand side column.

In Drupal administration when you edit content I want to have a 'Related Links' section, which prints a list of the content currently on the site with checkboxes so a user can choose which pages should be displayed as related.

I'm new to Drupal development, however have experience in working with PHP/mySQL and writing modules for other content management systems.

What steps should I go about to achieve this? And how would I then print the selection on the front-end of the site?

Thanks so much for your time

# Answer
> 1 votes
With References or Entity References (recommended) module, you can add node reference fields to your node type. It's pretty straight forwad. I'd suggest looking at drupal.org docs about making node types asyou are new to Drupal. You will not need to code anything in most cases. for content display, you can use theme templates and/or Views.

---
Tags: 7, users
---


# Question
Title: Node teaser with a different size than other nodes
I have created a content type, and for some reason the teaser text has a different size than the size used by all the other nodes.

This is what happens for "Stenhousemuir For Sunday Success."

Could anyone enlighten me on why this happens?

# Answer
> 4 votes
That particular bit of text is wrapped in a `<span>` that includes inline styles that change the font size of that text.

If your content is entered via a WYSIWYG editor, you may want to adjust the settings for that WYSIWYG so that it strips out inline styles like this.

---
Tags: theming, nodes
---


title: Showing routes in maps

text:
# Question
Title: Showing routes in maps
I have a collection of points (latitude/longitude) that i would like to represent on a Map as route. Is there a module that permits this?

# Answer
> 4 votes
Funny you should say that. I just fixed a bug in leaflet module that was preventing me from showing linestrings (i.e. a route).

There are other ways of doing this but this is a good efficient way and leaflet maps are beautiful!

1. Install the patched version (i.e. the latest and greatest version) of leaflet module - http://drupal.org/node/1707882
2. Apply the tiny change I put here - http://drupal.org/node/1667780
3. Install http://drupal.org/project/geofield (7-1.x-dev version) and http://drupal.org/project/geophp
4. Install http://drupal.org/project/leaflet\_more\_maps to get a whole bunch of ready made tiles.
5. Add a field to your node using geofield with WKT format.
6. Add a node with your points using the WKT linestring format for your route = LINESTRING(lon lat, lon lat, lon lat)
7. Change the display format for the field to leaflet and choose which map style you want.

http://en.wikipedia.org/wiki/Well-known\_text

http://leaflet.cloudmade.com/

Add a comment here if you get stuck at any point.

---
Tags: 7, google-maps
---


# Question
Title: Feed import many fields into single content type
I have a content type that I want to import some sitenames and siteurls from a csv file. So basically create a node type with option to import csv file to fill up field types sitenames and siteurls under one project with feeds or any other solution need help

Setup: Drupal 7, Views 2, Feeds

# Answer
> 1 votes
You are in the correct path, the Feeds module will allow you to import into the a content type data from a CSV file. You should install the feeds module first, create the content type after and last map the columns of data on your CSV file to the content type fields.

If you want to manipulate the data first before creating the node the Feeds Tamper module will help you do that.

**Note:** On the feed module page that are a couple of links to help you with the setup. Also Mustard Seed Media released a new podcast about the feed module as well.

---
Tags: 7, feeds
---


title: How to add two products in one click

text:
# Question
Title: How to add two products in one click
In my Drupal Commerce site, I have a product type - an attribute which refers to another product type (via reference product).

The display is:

Type 1

Product 1-1 x

Product 1-2 x

Product 1-3 x

Add to Cart

Type 2

Product 2-1 x

Product 2-2 x

x produces 2-3

Add to Cart

I would like only one "add to cart" button to be visible, and that clicking it should add two products which were selected at the same time.

How can this be accomplished?

# Answer
> 1 votes
I would do this with rules:

**Event**

After adding a product to the cart

**Action**

Add a product to the cart

* Parameter: User: \[site:current-user\],
* Product SKU: \[other product sku\] Provides variables: Added product line item (product\_add\_line\_item)

# Answer
> 0 votes
You can alter add to cart form and insert there your own submit.

```
$form['#submit'][] = 'my_own_submit';

```

Than in your submit you can do anything you want.

E.g. you can get your product from $form\_state. Than you can load related product and add it to cart by drupal commerce API. Example of adding product to cart is here

---
Tags: commerce
---


title: Drupal exposed filter theming

text:
# Question
Title: Drupal exposed filter theming
Is there a way to show views exposed filter with in betweeen operator for integer type as a select list(0-10, 10-20, etc)?

# Answer
1. You can alter your exposed form and print needle select list.
2. Than you hide your exposed filter with betweeen operator. E.g. display:none.
3. Than you write js that fills your hidden filter when user change select value.
> 1 votes

---
Tags: views, theming
---


# Question
Title: Creating secondary menus, that are different based on the page being viewed
I'm new to Drupal development so bear with me. I'm attempting to copy a production site that has used old school page controller organization into a newly setup Drupal 7 install. I've set up the header, sidebar, and footer all of which will always be the same so I've created them as blocks.

The content within those blocks is categorized into 5 categories and each one uses a slightly different layout at the top and bottom. What is the best way of handling this situation?

Create multiple additional blocks and make sure to assign the appropriate pages to those blocks, or set up a template of sorts that can tell what blocks need to be displayed based on the category of the content.

# Answer
> 1 votes
If you want to have different layout on different pages you can use power combo Omega \+ Context \+ Delta. Using this modules you can create different layouts, different menu items and other things on different pages without codding.

See tutorial and Theory

---
Tags: blocks, theming
---


# Question
Title: How can I render my output in a series of DIVs rather than an "item_list"?
The following code works in the sense that it outputs my series of photos in an unordered list. My question is - What changes would I need to make in order to render my output in a series of DIVs with class IDs? I plan to hook this up to JQuery Masonry and I'd prefer to break away from the limitations of them being in a list.

The following code pulls in my data.

```
function photo_gallery_contents($display) {
  $max_num = variable_get('photo_gallery_max', 3);
  $query = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('status', 1) //Published.
    ->condition('type','portfolio') // Only want our photos aka Portfolio content type
    ->orderBy('created', 'DESC'); //Most recent first.

  if ($display == 'block') {
    // Restrict the range if called with 'block' argument
    $query->range(0, $max_num);
  }
  // Now proceeds to execute().
  // If called by peg, query proceeds directly to execute().

  // Fetch the results for the nid field into an array.
  $nids = $query->execute()->fetchCol();

  // Load the node objects and return.
  return node_load_multiple($nids);

```

}

The code that renders all (but would like it to create a series of DIVs) is the following one.

```
function _photo_gallery_page() {
  $result = photo_gallery_contents('page');

  // Array to contain items for the page to render.
  $items = array();

  //Iterate over the resultset and format as links.
  foreach ($result as $node) {
    // Build a render array based on the field's display settings.
    $image = field_view_field('node', $node, 'field_image',array('label' => 'hidden',   'settings' => array('image_style' => 'thumbnail')));

    // Render the array down to the image HTML.
    $image_html = drupal_render($image);

    $items[] = array(
      'data' => l($image_html, 'node/' . $node->nid, array('html' => TRUE)),
    );
  }

  if (empty($items)) {
    // No content in the last 2 weeks.
    $page_array['photo_gallery_arguments'] = array(
      //Title serves as page subtitle.
      '#title' => t('All photos from ever'),
      '#markup' => t('No photos available.'),
    );
    return $page_array;
  }
  else {
    $page_array['photo_gallery_arguments'] = array(
      '#title' => t('All photos from ever'),
      '#items' => $items,
      // Theme hook with suggestion.
      '#theme' => 'item_list',
      '#type' => 'div',
    );

    return $page_array;
  }
}

```

# Answer
> 3 votes
As far I understood you want render the following code in multiple `<divs>`.

```
$page_array['photo_gallery_arguments'] = array(
  '#title' => t('All photos from ever'),
  '#items' => $items,
  // Theme hook with suggestion.
  '#theme' => 'item_list',
  '#type' => 'div',
);

```

Replace it with the following code.

```
   foreach($items as $item_key => $item) {
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'container',
       '#attributes' => array(
         'class' => array(
           'my-class-' . $item_key,
         ),
       ),
     );

     $page_array['photo_gallery_arguments'][$item_key]['content'] = array(
       '#type' => 'markup',
       '#markup' => $item,
     );
   }

```

Or use the following code.

```
   foreach($items as $item_key => $item){
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'markup',
       '#markup' => '<div class="my-class-"' . $item_key . '>' . $item . '</div>',
     );
   }

```

Alternatively, you can use the following code.

```
   foreach($items as $item_key => $item){
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'item',
       '#markup' => $item,
     );
   }

```

You can find more information about rendering arrays, and Form API.

---
Tags: theming
---


# Question
Title: Get node values from array with Drupal API?
With Drupal API I found you can get the values of a node with noad\_load like so:

```
$thisnode = node_load($nid = $child2, $vid = NULL, $reset = FALSE);

```

Now it is easy to echo the title in this way

```
$thisnode->title;

```

But the array begins to get quite complex when I try and get data from the custom image\_thumbnail field because it is array within array. See the full printed array for one node:

```
stdClass Object ( [vid] => 4 [uid] => 1 [title] => Who we are [log] => [status] => 1 [comment] => 0 [promote] => 0 [sticky] => 0 [nid] => 4 [type] => level_2 [language] => und [created] => 1345561152 [changed] => 1346982536 [tnid] => 0 [translate] => 0 [revision_timestamp] => 1346982536 [revision_uid] => 1 [body] => Array ( [und] => Array ( [0] => Array ( [value] => blah blah blah [summary] => [format] => plain_text [safe_value] =>

blah blah blah
 [safe_summary] => ) ) ) [field_parent2] => Array ( [und] => Array ( [0] => Array ( [target_id] => 2 ) ) ) [field_level2_thumbnail_image] => Array ( [und] => Array ( [0] => Array ( [fid] => 4 [alt] => this is a photo [title] => this is a photo [width] => 308 [height] => 198 [uid] => 1 [filename] => article-image.png [uri] => public://article-image.png [filemime] => image/png [filesize] => 105660 [status] => 1 [timestamp] => 1346982536 [rdf_mapping] => Array ( ) ) ) ) [rdf_mapping] => Array ( [rdftype] => Array ( [0] => sioc:Item [1] => foaf:Document ) [title] => Array ( [predicates] => Array ( [0] => dc:title ) ) [created] => Array ( [predicates] => Array ( [0] => dc:date [1] => dc:created ) [datatype] => xsd:dateTime [callback] => date_iso8601 ) [changed] => Array ( [predicates] => Array ( [0] => dc:modified ) [datatype] => xsd:dateTime [callback] => date_iso8601 ) [body] => Array ( [predicates] => Array ( [0] => content:encoded ) ) [uid] => Array ( [predicates] => Array ( [0] => sioc:has_creator ) [type] => rel ) [name] => Array ( [predicates] => Array ( [0] => foaf:name ) ) [comment_count] => Array ( [predicates] => Array ( [0] => sioc:num_replies ) [datatype] => xsd:integer ) [last_activity] => Array ( [predicates] => Array ( [0] => sioc:last_activity_date ) [datatype] => xsd:dateTime [callback] => date_iso8601 ) ) [name] => slawrence10 [picture] => 0 [data] => b:0; )

```

What's the best way to extract for example *alt* from \*field\_level2\_thumbnail\_image\*?

I can do it like so:

```
$thisnode->field_level2_thumbnail_image['und'][0]['alt'];

```

But is this stable? Will 'und' always be 0? Am I missing something here?

# Answer
If it is for page view of some kind, I think you can maybe try for this more robust way of getting at field values:

```
$output = field_view_field('node', $node, 'field_name');

```

An important trick that shows *one of the ways* to deal with field data properly. Initially learned a while back off this site.

Another method of getting at the data I just thought of and use quite a bit in a recent project is entity api. Highly recommended add-on. Consider the following borrowed snippet that shows how to deal with mail field. Other fields are the same.

```
   $wrapper = entity_metadata_wrapper('node', $node);
   $wrapper->author->mail->value();

To update the user's mail address one could use

   $wrapper->author->mail->set('stefp@example.com');

   or

   $wrapper->author->mail = 'stef@example.com';

```

Last but not least, there are still yet other alternatives surely?

Best practice for language key for "und" in hook\_form\_alter. I did not flag as duplicate as I did not check into detail if other question was detailed or not, but it should be enough to give you ideas.

Good-luck.
> 6 votes

# Answer
It is sorta like this:

```
$node->FIELDNAME[LANGUAGE][DELTA][INFORMATION]

```

So, in your example, it would be:

```
$node->field_level2_thumbnail_image['und'][0]['filename'];

```

Some details:

```
['und'] =======> LANGUAGE_NONE or none defined for this node
[0] ===========> The first value.  If this were a multiple value field, you could have more
['filename'] ==> The filename you are looking for.
['alt'] =======> The alt tag

```
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: User or Content Type for employee directory
I am trying to create an employee directory using drupal 7. I have the following fields for each employee profile:

• Name
• Department
• Job Title
• Phone
• Email
• Optional photo
• A narrative-paragraph
• Note

Here is my requirement:

• Data (including photo) can be entered/updated by each employee using their login/password. • Data can also be entered by the administrator
• Employees cannot remove their name.
• Admins can see when information was updated.
• Listing that is searchable by name and department

I could not decide which is the best way - content type 'employee' or user role 'employee' with profile fields. If I create user as employee, how can I have the feature of the red information "updated" which we have in the content list (admin/content) when each content was updated?

# Answer
I think you would be dealing with 'users' so using profile fields on user profiles would be your best shot. As a bonus, Drupal is well thought out and flexible enough to handle whatever kind of userbase you throw at it. Unless you want to re-invent the wheel in node hooks, I would shoot for profile fields and if you need to code up a custom module (or two), I can highly recommend entity api module to help you deal with profile field data.

The 'red' information you want (I assume) added to new content for example, (or any other possible variable) is easily done in templates. Usually based on conditionals and often (but not always) based on a bool variable of some kind.

For example, consider a 'flag' variable called $is\_new. If $is\_new isset (or !empty), either you send a conditional stylesheet, or set up a template to show that background in red text in black. As simple example here is a repost of recommended way to use if's in a template:

```
<?php if (!empty($is_new )): ?>
  <p><?php print $is_new ; ?></p>
<?php endif; ?>
 // You can use foreach statements for arrays you want to render
<?php foreach ($new_items as $item): ?>
  <p><?php print $item; ?></p>
<?php endforeach; ?>

```

As for the different views for different is totally a different matter, but happily is also built in natively via roles, permissions and content-access system.

Good-luck!
> 1 votes

---
Tags: nodes, users
---


# Question
Title: jquery get or post methods for drupal block module
Is it possible to use jquery get or post methods to fetch data dynamic in a a drupal7.x block module. I am a newbie to drupal.

Here is my event\_calendar.module file

```
      function event_calendar_help($path, $arg)
      {
          switch ($path)
          {
          case "admin/help#event_calendar":
          return '<p>'.  t("A block module that creates events and lists them in a event calendar") .'</p>';
      break;
          }
    }
     /**
    * Implements hook_block_info().
    */
    function event_calendar_block_info() {
      $blocks['event_calendar'] = array(
        'info' => t('Event calendar'),
        'cache' => DRUPAL_CACHE_PER_ROLE, //Default
      );
      return $blocks;
    }

    /**
    * Implements hook_block_view().
    *
    * Prepares the contents of the block.
    */
    function event_calendar_block_view($delta = '')
    {
      switch($delta)
      {
        case 'event_calendar':
          $block['subject'] = NULL;
          if(user_access('access content'))
           {
            $items = array();
            $basepath = drupal_get_path('module', 'event_calendar');
            $markup = '<div id="content">
                    <div style="float:right;margin-bottom:5px">
                        <label style="float:left;padding:3px;">Week :</label>
                        <div id="date_picker">
                            <span id="startDate"></span></span> - <span id="endDate"></span>
                            <div class="week-picker" style="display:none;position:absolute"></div>
                        </div>
                    </div>
                    <hr style="clear:both;"/>
                    <div id="calender_content">

                    </div>
                    <div id="color_code" style="float:right">
                        <div class="lane1 colorbox"></div><div style="float:left">Lane 1</div>
                        <div class="lane2 colorbox"></div><div style="float:left">Lane 2</div>
                        <div class="lane3 colorbox"></div><div style="float:left">Lane 3</div>
                        <div class="lane4 colorbox"></div><div style="float:left">Lane 4</div>
                    </div>
                </div>';
      $block['content'] = array(
        '#markup'   => $markup,
        '#attached' => array
            (
            'css' => array($basepath . '/css/event_calendar.css',$basepath . '/css/smoothness/jquery-ui-1.8.16.custom.css'),
            'js'  => array($basepath . '/javascript/event_calendar.js',$basepath . '/javascript//jquery-ui-1.8.16.custom.min.js'),
            ),
        );

          }
return $block;
      }

    }

```

I want to know how to write functions inside above .module file to access some content dynamically through jquery get or post method?

Or should I use something like 'hook\_menu' other than block?

# Answer
> 3 votes
For using get data by jquery ajax you need first seta menu link for listen to your ajax requst, and in callback of your menu you passed back a block or any data you want.

```
function yourmodule_menu () {
   $items=array();
   $items['youruniqepath'] =array(
        'title' => 'my menu',
        'description' => 'A menu link to handle ajax request',
        'page callback' => 'yourhandlerfunction',
        'access callback' => TRUE, //you can set it with your permission
      );
   return $items;
   }

```

and in yourhalderjust need pass a block :

```
function yourhandlerfunction () {
  //with any method you want get your block,
  // I suggest something like this
    $block = module_invoke('module_name', 'block_view', 'block_delta');
    print render($block);
}

```

and in your clientside get it with something like this

```
$.ajax({
    type: "POST",
    url: 'youruniqepath',
    //data: {}, you can also pass block name and act more dynamicly
    success: function (data){
        $('#yourplace').html(data);
    }
});

```

---
Tags: 7, hooks, blocks, javascript
---


# Question
Title: How do you handle long runtime updates needed in hook_install()?
I have a new module that includes a series of `hook_update_N()` implementations. I had written these without knowing a module is installed, `hook_update_N()` isn't invoked.

Several of the `hook_update_N()` implementations take advantage of `$sandbox` parameter, as they are lengthy database changes. As far as I know batch API isn't supported in `hook_install()`.

What are my options to run these during module installation?

# Answer
> 2 votes
My suggestion is to not make it automatic on install. Provide a page from where an admin can launch the batch job.

However, if it absolutely must be automated, I have a suggestion, albeit somewhat crude.

```
function mymodule_init() {
  $run_batch = variable_get('NOT_INSTALLED_YET', FALSE);
  if ($run_batch) {
    // Redirect to batch launch, or possible just set an approprite message.
  }
}

function mymodule_install() {
  variable_set('NOT_INSTALLED_YET', TRUE);
}

```

---
Tags: 6, drush, installation
---


# Question
Title: token_replace : operate on two different 'user' entities?
I've got an e-mail message with the following contents:

```
Dear [receiver:name],

[sender:name] would like to recommend the following link [node:url].

```

Now, I could certainly implement hook\_tokens() and make sure that all 'receiver' and 'sender' tokens are replaced, but these entities are plain old 'user' objects. It would be great if I could just use the functionality already available, but as far as I can see, that requires me to specify replacement patterns in the format \[user:name\]. However, that doesn't work as it would mix up the sender and receiver.

Any idea if this is doable withouth having to reimplement the 'user' replacement logic?

# Answer
I don't think you can do what you require as the data fed to \[user:name\] belongs to the currently logged in user. Sender and receiver would be different objects in your database.
> 0 votes

---
Tags: 7, tokens
---


title: Create a time span field

text:
# Question
Title: Create a time span field
The date module provides a handy widget for specifying a date. Is there something similar on Drupal 6 for specifying a length of time such as 6 months or 3 days? The time span will need to be converted to or stored as seconds for use by my module.

# Answer
> 2 votes
The Interval Field module looks like it would do the trick.

> Interval field gives you a simple field and widget to allow users to enter interval values eg
>
> * 2 months
> * 3 days
> * 4 years

# Answer
> 1 votes
For Drupal 6, try the Duration module.

Another great module for Drupal 7, is the Time Period module.

---
Tags: 6, entities, datetime
---


# Question
Title: How can i put popup box captcha on managed file remove button?
Can We write function for remove button as I want to display Captcha in popup on Remove button for security reason.

same type of some function like used in below post.

How can I automatically upload images on file selection rather than pressing the upload button?

# Answer
I have solved it. I have hide remove button access. and then put my own remove button, and open dialog box in form to display popup box.

please see code.

`drupal_add_library('system', 'ui.dialog');
drupal_add_js('jQuery(document).ready(function(){
jQuery("#clicky").live("click", function(){
jQuery("#dialog").dialog({ modal: true ,height: 250,width: 350,
buttons: [
{
text: "Cancel",
click: function() {
jQuery(this).dialog("close");
}},
{
text: "Submit",
click: function() {
jQuery("#dialog-form").submit();
}}
]});});});', 'inline');`
> 0 votes

---
Tags: 7, forms, ajax, files
---


title: xmlrpc function in another file

text:
# Question
Title: xmlrpc function in another file
I would like to put all my xmlrpc functions in a separate inc file and the problem is, how would we tell drupal it is in another file. Right now, my hook\_xmlrpc in my module file looks like this:

```
function mymodule_xmlrpc() {

  $methods['mymodule.get_myfunction'] = 'xmls_mymodule_get_myfunction';
  return $methods;
}

```

xmls\_mymodule\_get\_myfunction resides in mymodule.xml-rpc.inc file. How do we let drupal know that in this hook?

# Answer
> 0 votes
Why not just use `xmls_mymodule_get_myfunction()` as a proxy to the file where the real code is held?

```
function xmls_mymodule_get_myfunction($args) {
  module_load_include('inc', 'MYMODULE', 'MYMODULE.xml-rpc');
  _xmls_mymodule_get_myfunction($args);
}

```

You only incur 4 extra lines of code at the most, and you get the separation you're looking for. Obviously you can extend that function to become generic for several xmlrpc methods, the above is just a very simple example.

# Answer
> 1 votes
Unfortunately, I don't believe you can.

Many core hooks, such as hook\_menu, let's you define a `file` and a `file path` which Drupal can use to find the actual callbacks for the menu.

However, I don't believe this functionality is supported by hook\_xmlrpc.

Considering also that the module is likely to leave core soon, it's unlikely that there will be any large improvements to it.

---
Tags: hooks
---


title: Featured image for teasers?

text:
# Question
Title: Featured image for teasers?
I have a client who is an architect. I've created a content type called "project" that allows them to select multiple images to display on a page. These project items get promoted to the home page as teasers, however I'd like the customer to be able to select a featured image to display in the teaser, rather than having every image display.

Anyone know an easy way of doing this without having multiple image fields?

# Answer
> 0 votes
may be with some code in custom module, first image is featured

```
/**
 * Implementation of hook_node_view_alter().
 */
function HOOK_node_view_alter(&$build) {
  if ($build['#view_mode'] == 'teaser' && isset($build['field_image'][1])) {
    foreach ($build['field_image'] AS $k => $item) {
      if (is_numeric($k) && $k > 0) {
        unset($build['field_image'][$k]);
      }
    }
  }
}

```

change "field\_image" to your field\_name

# Answer
> 0 votes
I would say the easiest way is to make the *first* image also be the "featured" one, as then you already have most of the functionality built in.

It is then trivial to use a view that filters on "Image field: delta = 1", to give you only that one image, and then output it where appropriate.

A php savvy themer could also pull out the first image right in the template as well.

---
Tags: media, nodes
---


# Question
Title: Unable to save term "Big Honor for Branford's Le Petit Café"
I was trying to save term with name "Big Honor for Branford's Le Petit Café" using taxonomy\_term\_save function which throws me the following error

```
PDOException: in drupal_write_record() in common.inc

```

Is it some thing related to character encoding ? should i have to convert the character? I am not sure how to do that.

Please find the code that throws the error,

```
$term_name  = new stdClass();
$term_name->name = urldecode("Big%20Honor%20for%20Branford%27s%20Le%20Petit%20Caf%E9");
$term_name->vid = 1;
taxonomy_term_save($term_name);

```

If we are using the exact "Big Honor for Branford's Le Petit Café" is a file then i could not get the error but, when url encoded and decoded again, we will have the same character set.

# Answer
This code works perfectly for me:

```
$term = (object)array(
  'name' => "Big Honor for Branford's Le Petit Café",
  'vid' => 1
);

taxonomy_term_save($term);

```

No errors, and the term is saved as expected. So it looks like the issue is something to do with your server configuration. Without more details it's impossible to say what that problem might be though.

**UPDATE**

Turns out this a multibyte encoding issue. Wrapping the string in `utf8_encode()` will fix it:

```
$term_name->name = utf8_encode(urldecode("Big%20Honor%20for%20Branford%27s%20Le%20Petit%20Caf%E9"));

```
> 5 votes

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


# Question
Title: How can i select taxonomy terms applying filters on its fields?
I'm building a project where i've decided to heavily use Drupal items (nodes, taxonomy, views) but i find hard to retrieve data in a simple way.

I've defined a taxonomy vocabulary with custom fields that are references to other vocabulary terms.

For example i have a book\_author vocabulary and books vocabulary and need to get all the books written by a certain author tid.

Are there apis that i can use with a single call or do i have to use Sql queries on taxonomy\_\* field\_data\_\* tables?

# Answer
> 1 votes
The `EntityFieldQuery` class is the normal tool fot this sort of task. Have a look at the docs for more information, but this is a basic example based around what you've mentioned in your question:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $vocab_id_of_terms_you_want_to_select)
  ->fieldCondition('field_author', 'tid', $the_author_tid);

$results = $query->execute();

$found_terms = taxonomy_term_load_multiple(array_keys($results['taxonomy_term']));

```

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