# Question
Title: A view consisting of user's first and last posts
I setup to create a view that would show me all users, their total post counts. Now I need to show when their first post was made and when their last post was made. I have included an export of my current view. Any help would be welcome.

```
$view = new view;
$view->name = 'user_node_counts';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'User Node counts';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Number Of Posts';
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  3 => '3',
  7 => '7',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'counter' => 'counter',
  'name' => 'name',
  'points' => 'points',
  'field_phone' => 'field_phone',
  'type_1' => 'type_1',
  'type' => 'type',
  'uid' => 'uid',
  'php' => 'php',
  'created' => 'created',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'counter' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'points' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_phone' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'type_1' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'type' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'uid' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'php' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'created' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['style_options']['override'] = 1;
$handler->display->display_options['style_options']['sticky'] = 0;
$handler->display->display_options['style_options']['empty_table'] = 0;
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = 0;
/* Field: Global: View result counter */
$handler->display->display_options['fields']['counter']['id'] = 'counter';
$handler->display->display_options['fields']['counter']['table'] = 'views';
$handler->display->display_options['fields']['counter']['field'] = 'counter';
$handler->display->display_options['fields']['counter']['label'] = '#';
$handler->display->display_options['fields']['counter']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['counter']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['counter']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['counter']['alter']['external'] = 0;
$handler->display->display_options['fields']['counter']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['counter']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['counter']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['counter']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['counter']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['counter']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['counter']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['counter']['alter']['trim'] = 0;
$handler->display->display_options['fields']['counter']['alter']['html'] = 0;
$handler->display->display_options['fields']['counter']['element_label_colon'] = 1;
$handler->display->display_options['fields']['counter']['element_default_classes'] = 1;
$handler->display->display_options['fields']['counter']['hide_empty'] = 0;
$handler->display->display_options['fields']['counter']['empty_zero'] = 0;
$handler->display->display_options['fields']['counter']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['counter']['counter_start'] = '1';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['external'] = 0;
$handler->display->display_options['fields']['name']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['name']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = 1;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['name']['link_to_user'] = 1;
$handler->display->display_options['fields']['name']['overwrite_anonymous'] = 0;
$handler->display->display_options['fields']['name']['format_username'] = 1;
/* Field: Userpoints total: Current total money */
$handler->display->display_options['fields']['points']['id'] = 'points';
$handler->display->display_options['fields']['points']['table'] = 'userpoints_total';
$handler->display->display_options['fields']['points']['field'] = 'points';
$handler->display->display_options['fields']['points']['label'] = 'Total Money';
$handler->display->display_options['fields']['points']['exclude'] = TRUE;
$handler->display->display_options['fields']['points']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['points']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['points']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['points']['alter']['external'] = 0;
$handler->display->display_options['fields']['points']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['points']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['points']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['points']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['points']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['points']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['points']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['points']['alter']['trim'] = 0;
$handler->display->display_options['fields']['points']['alter']['html'] = 0;
$handler->display->display_options['fields']['points']['element_label_colon'] = 1;
$handler->display->display_options['fields']['points']['element_default_classes'] = 1;
$handler->display->display_options['fields']['points']['hide_empty'] = 0;
$handler->display->display_options['fields']['points']['empty_zero'] = 0;
$handler->display->display_options['fields']['points']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['points']['format_plural'] = 0;
/* Field: User: Phone Number */
$handler->display->display_options['fields']['field_phone']['id'] = 'field_phone';
$handler->display->display_options['fields']['field_phone']['table'] = 'field_data_field_phone';
$handler->display->display_options['fields']['field_phone']['field'] = 'field_phone';
$handler->display->display_options['fields']['field_phone']['relationship'] = 'uid';
$handler->display->display_options['fields']['field_phone']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['external'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['field_phone']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['field_phone']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['trim'] = 0;
$handler->display->display_options['fields']['field_phone']['alter']['html'] = 0;
$handler->display->display_options['fields']['field_phone']['element_label_colon'] = 1;
$handler->display->display_options['fields']['field_phone']['element_default_classes'] = 1;
$handler->display->display_options['fields']['field_phone']['hide_empty'] = 0;
$handler->display->display_options['fields']['field_phone']['empty_zero'] = 0;
$handler->display->display_options['fields']['field_phone']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['field_phone']['field_api_classes'] = 0;
/* Field: Content: Type */
$handler->display->display_options['fields']['type_1']['id'] = 'type_1';
$handler->display->display_options['fields']['type_1']['table'] = 'node';
$handler->display->display_options['fields']['type_1']['field'] = 'type';
$handler->display->display_options['fields']['type_1']['label'] = '';
$handler->display->display_options['fields']['type_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['type_1']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['external'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['html'] = 0;
$handler->display->display_options['fields']['type_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type_1']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type_1']['hide_empty'] = 0;
$handler->display->display_options['fields']['type_1']['empty_zero'] = 0;
$handler->display->display_options['fields']['type_1']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type_1']['link_to_node'] = 0;
$handler->display->display_options['fields']['type_1']['machine_name'] = 0;
/* Field: COUNT(Content: Type) */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
$handler->display->display_options['fields']['type']['group_type'] = 'count';
$handler->display->display_options['fields']['type']['label'] = 'Posts';
$handler->display->display_options['fields']['type']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type']['alter']['external'] = 0;
$handler->display->display_options['fields']['type']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['type']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type']['alter']['html'] = 0;
$handler->display->display_options['fields']['type']['element_label_colon'] = 0;
$handler->display->display_options['fields']['type']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type']['hide_empty'] = 0;
$handler->display->display_options['fields']['type']['empty_zero'] = 0;
$handler->display->display_options['fields']['type']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type']['separator'] = '';
$handler->display->display_options['fields']['type']['format_plural'] = 0;
/* Field: Content: Author uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'node';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
$handler->display->display_options['fields']['uid']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['uid']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['uid']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['uid']['alter']['external'] = 0;
$handler->display->display_options['fields']['uid']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['uid']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['uid']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['uid']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['uid']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['uid']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['uid']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['uid']['alter']['trim'] = 0;
$handler->display->display_options['fields']['uid']['alter']['html'] = 0;
$handler->display->display_options['fields']['uid']['element_label_colon'] = 1;
$handler->display->display_options['fields']['uid']['element_default_classes'] = 1;
$handler->display->display_options['fields']['uid']['hide_empty'] = 0;
$handler->display->display_options['fields']['uid']['empty_zero'] = 0;
$handler->display->display_options['fields']['uid']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['uid']['link_to_user'] = 1;
/* Field: Global: PHP */
$handler->display->display_options['fields']['php']['id'] = 'php';
$handler->display->display_options['fields']['php']['table'] = 'views';
$handler->display->display_options['fields']['php']['field'] = 'php';
$handler->display->display_options['fields']['php']['label'] = 'Reset';
$handler->display->display_options['fields']['php']['exclude'] = TRUE;
$handler->display->display_options['fields']['php']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['php']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['php']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['php']['alter']['external'] = 0;
$handler->display->display_options['fields']['php']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['php']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['php']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['php']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['php']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['php']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['php']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['php']['alter']['trim'] = 0;
$handler->display->display_options['fields']['php']['alter']['html'] = 0;
$handler->display->display_options['fields']['php']['element_label_colon'] = 1;
$handler->display->display_options['fields']['php']['element_default_classes'] = 1;
$handler->display->display_options['fields']['php']['hide_empty'] = 0;
$handler->display->display_options['fields']['php']['empty_zero'] = 0;
$handler->display->display_options['fields']['php']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['php']['use_php_setup'] = 0;
$handler->display->display_options['fields']['php']['php_output'] = ';
$handler->display->display_options['fields']['php']['use_php_click_sortable'] = '0';
$handler->display->display_options['fields']['php']['php_click_sortable'] = '';
/* Field: User: Created date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'users';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['relationship'] = 'uid';
$handler->display->display_options['fields']['created']['label'] = 'Member Since';
$handler->display->display_options['fields']['created']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['created']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['created']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['created']['alter']['external'] = 0;
$handler->display->display_options['fields']['created']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['created']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['created']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['created']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['created']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['created']['alter']['more_link'] = 0;
$handler->display->display_options['fields']['created']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['created']['alter']['trim'] = 0;
$handler->display->display_options['fields']['created']['alter']['html'] = 0;
$handler->display->display_options['fields']['created']['element_label_colon'] = 1;
$handler->display->display_options['fields']['created']['element_default_classes'] = 1;
$handler->display->display_options['fields']['created']['hide_empty'] = 0;
$handler->display->display_options['fields']['created']['empty_zero'] = 0;
$handler->display->display_options['fields']['created']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['created']['date_format'] = 'custom';
$handler->display->display_options['fields']['created']['custom_date_format'] = 'd/m/y';
/* Sort criterion: Userpoints total: Current total money */
$handler->display->display_options['sorts']['points']['id'] = 'points';
$handler->display->display_options['sorts']['points']['table'] = 'userpoints_total';
$handler->display->display_options['sorts']['points']['field'] = 'points';
$handler->display->display_options['sorts']['points']['order'] = 'DESC';
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'post_count';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Post Count';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['name'] = 'user-menu';
$handler->display->display_options['menu']['context'] = 0;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->display->display_options['block_description'] = 'user stats';

```

# Answer
> 1 votes
Is it necessary to do this with *one* Views display? It's trivial to do two displays, getting post dates, limiting to a single one, and then only overridding the sort order.

That would be

1. A *Field* on *Content: Post date*.
2. A *Contextual filter* on *User:uid*
3. A *Pager* limiting to a single hit
4. A *Sort* on *Content: Post date*.

The two displays will then override the Sort, one does ascending, one descending.

I can't think of a good way of doing it with a single display.

# Answer
> 1 votes
What you want, requires *aggregation*, that is, pulling out multiple rows of data, and summarizing it.

This is a non-trivial task, and you may find it difficult to accomplish with Views. It's possible that you will need to write the query yourself.

With that said, here's a link to some Views aggregation related screencasts.

---
Tags: views
---


# Question
Title: How to load multiple values from a field with views_php module?
I'm trying to build a responsive gallery. Since views won't let me rewrite the field's output with html5 data attributes I need to print the output using a PHP field in views.

Using the module views\_php, I'm accessing the values of the image field this way:

```
$source = $data->_field_data['nid']['entity']->my_field['und'][0]['filename'];

```

This way I load the value from the \['und'\]\[0\] array, this would work properly if a field has a single value. But what if in the node creation, in my field I want to upload multiple images. How could I change the \[und\] numerical value to load as many values as my field has.

Thanks in advance.

# Answer
As Syd said, it seems like you need a foreach loop. It's not readily apparent what you're wanting to do with the `$source` variable, but I'm guessing it's something like the following:

```
foreach ($data->_field_data['nid']['entity']->my_field['und'] as $a_file) {
    echo '<img src="' . $a_file['filename'] . '">';
}

```
> 2 votes

---
Tags: 7, views, entities, media
---


title: Unique IDs for nodes

text:
# Question
Title: Unique IDs for nodes
I would like every node created to have a unique ID. What's the best way to go about this? I know of the UUID module, but I don't really want the IDs to be formatted like a UUID. Does there exist a module that creates a unique ID that looks like (for example) an md5 hash?

The reason for doing this is that information about certain nodes has to be passed around between a few servers (in emails in some cases) and I don't wan't people to be able to have access to the drupal server's systems, I'd rather them see something like a hash as opposed to drupal's nid.

# Answer
> 2 votes
Interesting question. Here's how I'd do it.

1. Use Custom Tokens to create a custom token that runs the nid through `md5();`.
2. Use that custom token in Pathauto.

---
Tags: nodes
---


# Question
Title: how to get a node field value in a html.tpl.php template file?
I have a field in a node type called `body_styles`.

I need to modify html.tpl.php to get the value of `body_styles` to add it to the classes of the body tag.

I tried with `dpm($node->content['body_styles']['#value']);` but I get nothing. I think it is because $node is not available in html.tpl.php.

how do I get a node field value in a html.tpl.php template file?

**@svetlio: almost done**:

The class is correctly added to $variables\['classes\_array'\] but if I inspect the body (see my capture below the code) tag is not there

```
    function omega_subtheme_2_preprocess_html(&$variables, $hook) {
    if (arg(0) == 'node' && is_numeric(arg(1))) {
        global $language;
        $node = entity_load_unchanged('node', arg(1));

        dpm($node -> field_body_class['und'][0]['value']);

        if (isset($node -> field_body_class['und'][0]['value']) && $node -> field_body_class['und'][0]['value']){
            $variables['classes_array'][] = $node -> field_body_class['und'][0]['value'];
            dpm($variables['classes_array']);
        }
  }

```

# Answer
> 1 votes
Another way - without edit template and adding code in template.php

```
function THEME_preprocess_html(&$variables, $hook) {
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = entity_load_unchanged('node', arg(1));

      if (isset($node -> field_FIELD_NAME['und'][0]['value']) && $node -> field_FIELD_NAME['und'][0]['value']) {
        $variables['classes_array'][] = $node -> field_FIELD_NAME['und'][0]['value'];
      }
    }
  }

```

replace THEME with your theme\_name and FIELD\_NAME with your field\_name, clear the cache

edit: I change "$node = entity\_load('node', arg(1));" to $node = "entity\_load\_unchanged('node', arg(1));"

---
Tags: nodes, theming
---


# Question
Title: help to understand files in sites/all/default/files/js folder
I'd like to understand what are the ....js.gz files located in `sites/all/default/files/js`.

I thought they are cached js files.

But if I clear all caches (drush cc all) these files still remain there.

I've made a capture of the folder:

# Answer
> 1 votes
Like you said these are just cached versions of the javascript files. Drupal compresses them so they can be served to the user faster, notice the difference in file size between the version 29.1 KB opposed to 117.4 KB.

Are there any error when you clear cache through drush? Mostly I've found that they stay behind when you run drush as a user that cannot modify the files, e.g. a user not in whatever group owns the files. In this case you need to add your user to whatever group owns the files.

---
Tags: files
---


# Question
Title: How can I make a node link to another node
According to this site http://asblab.mie.utoronto.ca/news, you can see how Home\>\>News just below the menu. If I could add in this node http://asblab.mie.utoronto.ca/node/12525

such that Rise of the robots page would have

Home\>\>News\>\>Rise of the robots . How do I link them together?

Thank you guys, this forum has been helping me alot. If my question doesnt make sense, please inform me so I can try my best to edit and make the question better.

# Answer
Try to use drupal\_set\_breadcrumb() in template file if you want to do it programmatic.

Or configure Custom Breadcrumb module.
> 0 votes

---
Tags: nodes, navigation
---


title: Search user's all fileds in drupal 7

text:
# Question
Title: Search user's all fileds in drupal 7
I want to make a text fields that will make user able to search all the fields. I have tried few modules but nothing is working for me the way i want.

# Answer
You can combine multiple field values into one (hidden) field using Computed Field. Be sure to save the value to the database, so that it can be used as a Views exposed filter. You'll also need to re-save each existing node in order to populate the computed field (VBO can do that in bulk).

This is another interesting idea (I haven't tried it): http://drupal.org/node/732458#comment-4750574
> 1 votes

---
Tags: 7, users, search
---


title: Images and CSS effect not showing

text:
# Question
Title: Images and CSS effect not showing
Hello I'm using Drupal 6 and I've successfully finished with the site. However, after I uploaded the site to the server, I realised the the header image which is the logo is not showing even though the path is correct in the theme logo path.

Also there is a slide show which was made with Dynamic Display Block module and its images does not show up even though their path is present and correct.

The css style I applied to the three column under the DD Block is also not showing.

This still persists even if I change theme.

Does anyone know what's wrong under the hood?

Thank you

# Answer
> 0 votes
I think you should check the permission of "sites" and "files" folders. You cannot access to the folder.

I think something happened when you uploaded the website. Usually I do a fresh installation of drupal then I upload the files inside "all" folder and the files insidethe "files" folder inside "default". In the end through Backup and Migrate module I upload the db.

It must be a permission problem if you see the images there.

Let me know.

---
Tags: theming
---


# Question
Title: How can I update a field on a user profile with Drush
I'm creating users with `user-create` but I have added extra fields to the user like membership number.

Is there a way to update that field with a number when I create the user?

# Answer
Take a look at Drush Entity. Here is a quote from its project page:

> ... you can query the entity system available for Drupal 8, 7 and (some of) 6.
> 2 votes

---
Tags: users, drush
---


# Question
Title: Calculate sum in View of ISO-style timestamps
I have a text field on a node type, which the user fills out with a video duration in ISO format (no validation or anything). So, '4:33' or '04:33' would be likely values for this field.

The client now needs a View which shows all these videos' titles and durations, and adds up the durations. I've looked at solutions like Views Calc and have had no real success. I've also have bad luck formatting the duration as a datestamp and trying to manipulate it that way. I need a way to show something like this:

```
+----------+--------------+
|TITLE     | Duration     |
+----------+--------------+
|Swimming  | 4:33         |
|Diving    | 2:42         |
|Running   | 1:27         |
+----------+--------------+
|TOTAL     | 8:42         |
+----------+--------------+

```

# Answer
Imho your two best bets would be to either create a custom formatter, or to use `hook_field_attach_view_alter()` to modify the display (this answer might help if you go down that road). I'd be happy to expand on either of those methods.

Is there any reason you're using a text field? I would've thought a dedicated duration field would've been the way to go. I've never used any myself, but Google suggests: HMS Field, Time Period. Have you had a look at them? They might already have a formatter that supports what you want (a longshot, perhaps!).
> 1 votes

# Answer
you have to create a custom view tpl in your theme . To add time using php may be this link will help
> 0 votes

---
Tags: views, entities
---


# Question
Title: View with entityreference: make exposed filter autocomplete
I have two content types A and B. B has an entity reference to A. When creating a view to list all nodes from type A, I want to use some exposed filters. One filter would be to give all nodes from type A that have a reference to a certain node of type B. The exposed filter I get is a textfield that needs a nid. I made it autocomplete (via form\_alter), but now the value that gets saved is "node title (nid)".

Anyone having the same problem, and knows how to fix it?

EDIT: I found this patch for entity\_reference, but it doesn't seem to work. http://drupal.org/node/1492260

# Answer
The patch I added to the initial question did the trick: http://drupal.org/node/1492260 The only thing you need to know is that you need to enable a checkbox on the fieldsettings of the field on you content type.
> 1 votes

# Answer
You can add a validate handler, that pulls out of the nid from the autocompleted text - most use a text like `title [nid]` or similar. Then set that as the submitted values which View then would use. You need to make sure your validate handler acts first in order for this to work.
> 0 votes

---
Tags: views, entities, ajax
---


# Question
Title: Adding template to garland, preprocess page doesn't work
So I am trying to add an additional page to garland at http://site.com/processfront, this code does not seem to run and or change the template. I know the code is being run however, since i get an error if i purposefully mess up syntax. But, I tried defining some other arbitrary variables and printing them and that didnt work either... What's going on? Thanks

function phptemplate\_preprocess\_page(&$vars, $hook) { $vars\['tabs2'\] = menu\_secondary\_local\_tasks();

if (arg(0) == 'processfront') { $variables\['template\_file'\] = 'page-processfront'; }

# Answer
> 0 votes
If `processfront` is an alias for a specific node, let's say 228, then its system path is really `node/228` and `arg(0)` will be `node`. If you've set your system up so that this node is your front page, you can just use `page-front.tpl.php` and drupal will take care of it automagically. Otherwise, you can use `drupal_get_path_alias()` and check against that.

---
Tags: 6, theming
---


# Question
Title: hook_menu() items created in a custom module don't retain the active-trail of the parent tab
So I have a custom module that is adding 3 menu items (a main tab, and 2 sub-tabs). When navigating to the main tab (url: /casereports) the default\_local\_task is displayed as expected and both menu items (Case Reports and Jobs Completed) are active as expected. Everything is working fine except that when I click on the second tab (Jobs Created), the main tab (Case Reports) loses it's active status. I can't seem to figure out what I am missing here and why it is not picking up it's parent and the active-trail. Any ideas?

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

  $items['casereports'] = array(
    'title' => t('Case Reports'),
    'page callback' =>'drupal_get_form',
    'page arguments' => array('casereports_completed'),
    'access arguments' => array('access content'),
    'menu_name' => 'features'
  );
  $items['casereports/default'] = array(
    'title' => t('Jobs Completed'),
    'type' => MENU_DEFAULT_LOCAL_TASK
  );
  $items['casereports/created'] = array(
    'title' => t('Jobs Created'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('casereports_created'),
    'access arguments' => array('access content'),
    'type' => MENU_LOCAL_TASK
  );
  return $items;
}

```

# Answer
> 1 votes
OK...so this basically ended up being more of an Open Atrium issue than anything else. Due to the fact that Open Atrium relies heavily on Features and Context, the style sheet was setup to deal with the classes added by those modules. Drupal's implementation of active-trail and active classes was working fine, however the theme's 'active' styles weren't setup to work without the classes added by the Context module.

I could either a) add a Context for the menu item added via my module (which is the route I took), or I could have (b) modified the CSS for the theme by adding a custom stylesheet.

Thanks for all the help guys, but I am embarrassed to say that in the end, it was just a bit of a theme problem from the Open Atrium install.

# Answer
> 0 votes
I really can't tell why is this happening, but I can give suggestions for finding out *why* is it happening. The best way to start would be by checking the `menu_router` database table to verify what is the difference between the MENU\_DEFAULT\_LOCAL\_TASK and the MENU\_LOCAL\_TASK items in the database. If that does not uncover any clues, then I would start looking at the theming layer for answers. I would start by using Firebug to see what is the name of the active tab CSS class for the MENU\_DEFAULT\_LOCAL\_TASK item, then search Drupal core for that class. Once I found the function that is outputting the active tab CSS class, I would pepper it with breakpoints (or debug statements if not using a debugger), and see what makes it giggles, so to speak. This process should give you enough information to know why is the MENU\_LOCAL\_TASK not being marked as active.

---
Tags: 6, routes, distributions
---


# Question
Title: A strategy question regarding content types vs. basic pages plus taxonomy/tags
I'm having trouble deciding what makes more sense. I am building a somewhat simple site and so far it seems fairly straightforward to use the basic page content type for nearly everything and add a field for taxonomy (to associate the page with the categories of the main menu) and if needed, tags to further categorize the pages for various views and lists. But is that the best strategy? The end-user is going to have to remember to choose a taxonomy term for each page, and choose the right one. If a tag is needed, they are going to have to remember to add a tag and spell it correctly. People are notoriously unable to do simple things like this without making mistakes. So, would it be better to create separate content types for each main menu category, even if they basically are the same basic page content type? If I did separate content types, I wouldn't have to ask people to select an item in the main menu taxonomy. I would still have to ask them to tag some of the content types, but I could leave that field off for those content types that don't need tags. But then I'd be faced with having to instruct the end-user to select the correct content type before creating a new page.

What is your opinion? Is there a better strategy among these choices or perhaps even another choice I didn't consider?

# Answer
You could use radio buttons for your 'content type' taxonomy terms and make it required. That way your user sees all the content types available and has to pick one. For your free tagging, you might be able to use a module like Active Tags to make it a bit more accurate as well.
> 0 votes

---
Tags: nodes
---


# Question
Title: how to apply two themes for an element in custom module?
In the custom field module that i have written, i am trying to use two themes for same element. One is pager theme and another one is item\_list theme ..

I want to make both of these themes work for this element. Do i have to add them in array one item after another ?

Thank you very much :)

**Edit:** I have modified my code as per patmacs suggestion. I will put that code below, since my page is not displaying anything with change in code.

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

// Retrieve documents from Solr function using query
foreach($items as $delta => $item) {
$records = solr_get_results($item['query']);

// iterate through the documents and put them in the array $items in which every record is passed over a theme defined in hook_theme()
foreach($records as $record) {
  $items[] = array(
    'data' => array(
    '#theme' => 'event_webpages_field_list',
    '#node' => $record,
    ),
  );
}

// Number of items per page
$per_page = 10;
// Initialise the pager
$current_page = pager_default_initialize(count($items),$per_page);
// Split your list in to page sized chunks
$chunks = array_chunk($items, $per_page, TRUE);

// The pager theme element
$element1 = theme('pager', array('quantity',count($items)));

// The item_list theme element
$element2 = array(
  '#theme' => 'item_list',
  '#items' => $items,
  '#pre_render' => array('event_webpages_item_list_child_render'),
  );

// the final element passed along with the theme defined in hook_theme()
$output = array(
  '#theme' => 'event-webpages-theme-list',
  '#element1' => $element1,
  '#element2' => $element2,
 );
drupal_add_css(drupal_get_path('module', 'event_webpages') . '/event-webpages.css');
return $output;
 }

```

The above one is my formatter\_view function and my hook\_theme function looks like this

```
/**
 * Implements hook_theme()
 */
function event_webpages_theme($existing, $type, $theme, $path) {
  return array(
    // The theme applied for each item in the item_list
    'event_webpages_field_list' => array(
    'variables' => array(
    'node' => NULL,
    ),
    'template' => 'event-webpages-field-list',
    ),
    // The theme applied to the final output and each variable is theme element
    'event_webpages_theme_list' => array(
    'variables' => array(
      'element1' => NULL,
      'element2' => NULL,
    ),
    'template' => 'event-webpages-theme-list',
    ),
  );
}

```

The code in event-webpages-theme-list is

```
<?php
// $Id$
?>
<div class="<?php print $classes; ?>">
<?php print $element1; ?>
<?php print $element2; ?>
</div>

```

Sorry if it made it more confusing but i thought this will give a overall view of what i have done. Should i use a preprocessor function for 'event-webpages-theme-list' before passing the variables ?

Many Thanks

# Answer
> 0 votes
```
**
* Implements hook_theme().
*
* Defines the theming capabilities provided by this module.
*/
function YOURMODULENAME_theme() {

  return array(
    'THEMENAME1' => array(
    'template' => 'PATHTOTEMPLATEFILE',
       // EXAMPLE URL FOR ABOVE - 'templates/mymodulename--event--list-item',
       // This will make the module look for mymodulename--event--list-item.tpl.php
       // in the template folder within the module's directory
    'variables' => array(
      'SOMEVARIABLETOPASSTOTHETEMPLATE' => NULL,
      'ANOTHERVARIABLETOPASSTOTHETEMPLATE' => NULL,
      ),
    ),
  ),

}

```

Then when you have to return the content for the block or page, just call this function:

```
$output = theme("THEMENAME1", array('SOMEVARIABLETOPASSTOTHETEMPLATE' => "this is the variable that gets passed to the tpl", 'ANOTHERVARIABLETOPASSTOTHETEMPLATE' => "Another variable that is being passed to the template"));
return $output; // You could also just return the theme function above

```

Now, within your mymodulename--event--list-item.tpl.php file (Or whatever you named it) you can print any of the variables that you defined above.

```
<div class="somemarkup">
  <?php print $SOMEVARIABLETOPAsStOTHETEMPLATE; ?>
</div>

```

---
Tags: 7, theming, paging
---


# Question
Title: views in D7 :: remove doubles in exposed filter list
I have two content types, one (A) refering to the other (B). I also have two languages and I want to create a view where I show a list of all content type nodes of type A with an exposed filter, filtering the refering content type nodes of type B. this will show me all nodes of A that refer to B. so my filters are

* content type (A)
* language (en)
* refering node (exposed)

this works great but inside my exposed filter list of all nodes of type B every node is shown two times, representing every language translation. I now want to only show the english nodes of type B in the exposed filter list. how could I do that? thnx!

ps: I tried to use the filter groups, but this did not work.

# Answer
> 1 votes
The Views exposed filters block is a Drupal form, one that can be modified via a hook\_form\_alter or hook\_form\_FORM\_ID\_alter implementation. Here is a simple sample implementation of the more generic hook\_form\_alter.

```
/**
 * Implements hook_form_alter.
 */
function foo_helper_form_alter(&$form, &$form_state, $form_id = NULL) {
  if($form['#id'] == 'views-exposed-form-content-page') {
    // Do something with mah filters...
  }
}

```

If you are in doubt of what #id to use, you can always just implement this hook, go to your Views page, and watch the output of the $form variable to figure out what is the correct id to use. If you are in D7, the ID you are looking for will most likely be prepended with `views-exposed...`.

---
Tags: 7, views
---


# Question
Title: When should I create multiple Displays of a View instead of multiple Views?
Is it simply a matter of convenience to create multiple Displays of a View instead of multiple Views, or is there a performance benefit?

Does having any of the following items present in some Displays but not others affect the View as a whole?

* contextual filters
* content type filters
* aggregation

For example, I'm curious whether having a display show just Article content type results, another showing Forum results, another showing a custom Photo content type makes each display run slower. Or if the Views all share the same content type, but differ only in that one has a contextual filter for nid, and the others don't, do they all slow down?

If I have 30 Displays for a single view, should I refactor it for performance benefit, or just because the UI wasn't meant to show that many Displays.

# Answer
> 8 votes
Code-wise, both Views and displays are represented by objects. When a View is being processed, it loads all it's child displays into memory, regardless if you are rendering only one View in the page you are looking at. While database queries are executed only for the active display, the properties of the inactive displays are still loaded into memory.

This means that if you have 50 displays in one View, 50 displays will be loaded into memory, regardless if you are only displaying only one of them. So the answer to your question is yes, typically the more displays in a view you have, the more inefficient the View becomes memory-wise.

With that being said, I personally think that having anywhere between 2-10 displays in a View should prove negligible memory-wise. Having a discreet amount of displays in a View does serve it's practical purposes, after all (otherwise, why would they be there in the first place?).

As to your second question (performance impact of additional filters, etc), yes, adding certain parameters to your View will affect performance. If you want to know by exactly how much, you can go to *admin/structure/views/settings* (if you are in D7) and select ***Show information and statistics about the view during live preview***, ***Show the SQL query***, and ***Show performance statistics***. Here is a screenshot of the performance screen:

If you are further interested in the behavior of the queries (how many rows are analyzed, which keys are used), you can copy the query from the Views interface (once you've selected "Show SQL query"), and analyze the query using the MySQL `explain` command. There's plenty of articles like this one for `explain` usage on Google.

---
Tags: views, performance
---


# Question
Title: How to load a apache solr document and send it for reindex after editing is done in drupal 7
As title says,

I want to load a particular node's document and When the editing is done, I need to send the modified document to Solr for re-index programtically.

How it can be done?

# Answer
When using the apachesolr module, nodes are automatically marked for reindexing after an edit. So there is nothing you need to do.

If for some reason you need to manually mark a node, the code is

```
apachesolr_mark_entity('node', $nid);

```
> 6 votes

---
Tags: 7, search
---


title: Using hook_query_alter

text:
# Question
Title: Using hook_query_alter
I am using hook\_query\_alter to make changes in get taxonomy terms query.

```
    function MYMODULE_query_alter(QueryAlterableInterface $query) {
    global $user;
    if($user->uid > 1) {
        if ($query->hasTag('term_access') && strstr(current_path(), 'admin/structure/taxonomy')) {
            $permission = $query->leftJoin('term_permissions_user', 'tpu', "t.tid = tpu.tid");
            $ored = db_or();
            $ored->condition('uid', NULL, 'IS');
            $ored->condition('uid', $user->uid, '=');
            $anded = db_and();
            $anded->condition($ored);
            $query->condition($anded);
        }
    }
}

```

I want to have above query clause on the page which lists taxonomy terms only but this hook is adding the clause on all pages. I mean this hook is called on any page load of my drupal site.

Other issue is that the alias for table taxonomy\_term\_data is `base` on same pages and `t` on other pages and if i join using alias `t` it gives me error on most of the pages and vice versa.

I am checking the table alias to ensure the use of table alias used in my query and have changed the code as

```
function MYMODULE_query_alter(QueryAlterableInterface $query) {
    global $user;
    if($user->uid > 1) {
        if ($query->hasTag('term_access') && strstr(current_path(), 'admin/structure/taxonomy')) {
            $tables = $query->getTables();
            if(isset($tables['t']) && isset($tables['t']['alias']) && $tables['t']['alias'] == 't' && $tables['t']['table'] == 'taxonomy_term_data') {
                $permission = $query->leftJoin('term_permissions_user', 'tpu', "t.tid = tpu.tid");
                $ored = db_or();
                $ored->condition('uid', NULL, 'IS');
                $ored->condition('uid', $user->uid, '=');
                $anded = db_and();
                $anded->condition($ored);
                $query->condition($anded);
            }
        }
    }
}

```

But I am not sure if I have used a correct check, as of now my aim of adding query clause is fulfilled. Just to ensure this will work for long and will not break in any case. Please help me to have this hook call on the page where I need this and use the exact table alias.

Thanks in advance for your help.

# Answer
`hook_query_alter()` is executed for every dynamic query run by Drupal. If you want to execute the hook for queries having a specific tag, you should implement hook\_query\_TAG\_alter().

The code for getting the alias for the main table is similar to the following one.

```
function mymodule_get_main_table_alias($tables) {
  $alias = '';

  foreach ($tables as $id => $info) {
    // If 'join type' is not set, then it's the main table.a
    if (empty($info['join type'])) {
      $alias = $id;
    }
  }

  return $alias;
}

```

I would write then the hook code as follows.

```
function mymodule_query_term_access_alter(QueryAlterableInterface $query) {
  global $user;
  if ($user->uid > 1) {
    if (strstr(current_path(), 'admin/structure/taxonomy')) {
      if ($alias = mymodule_get_main_table_alias($query->getTables())) {
        $alias = $query->leftJoin('term_permissions_user', 'tpu', "$alias.tid = %alias.tid");
        $query->condition(db_or()
          ->isNullcondition("$alias.uid");
          ->condition("$alias.uid", $user->uid, '=')
        );
      }
    }
  }
}

```

Notice that:

* In `$query->leftJoin()`, %alias is replaced with the alias the query is using for the table being joined. As you are altering an existing query, you cannot know if the alias you chose is already used.
* The result of `$query->leftJoin()` is the alias being used for the joined table. It is better not to hard core that alias, for the reason said in the previous point.
* To check if a field is `NULL`, you should not use QueryConditionInterface::condition(); as the documentation says, you should use QueryConditionInterface::isNull().
* There is not need to create a `QueryCondition` object with `db_and()`; the conditions used to a query with `$query->condition()` are ANDed with each other.
> 3 votes

---
Tags: hooks, database
---


# Question
Title: Language paths per country- how to redirect users to their respective language's path on login?
I have a website that is available in both English and Japanese.

English is the default language and has a path prefix of "en".

Japanese has a path prefix of "ja".

Users can log in from the front page via a block.

If a user whose account is set to Japanese lands on the English front page and logs in, he/she will be taken to /en/mylogindestination instead of /ja/logindestination.

How can I redirect users with Japanese-language acconts to /ja/mylogindestination (and users with English-language accounts to /en/mylogindestination)?

I already have a number of login-related fixes in Rules so if this can be done in Rules that would be a plus, but a custom module is also ok.

# Answer
> 1 votes
```
    function module_user_login(&$edit, $account) {

     drupal_goto($user->language."/logindestination");

    }

```

Also, iirc, if your user has a language set, you can set one of the language detection method's to be "user preference", which would kick them over to the correct language after login.

---
Tags: i18n-l10n
---


title: Customizing Drupal 6 MP3 Player

text:
# Question
Title: Customizing Drupal 6 MP3 Player
I'm going to use MP3 Player module to play some audio files on drupal 6. as you know it uses Wordpress MP3 Player as standalone player and it only has one skin, so how can I obtain more skins or maybe a flash API explaining how to build one?

# Answer
I have never used that particular module, but I used to use the standalone version of the WordPress Audio Player a lot. The player isn't really skinnable in the same way you can skin other Flash components. There are some JS properties that you can set to change colors and dimenstions.

The documentation for the module claims

> Player can be styled and changed through Drupal admin interface.

so you should visit the settings page to see what you can do.

That said, there are other options you can explore
> 1 votes

---
Tags: 6, theming, media
---


# Question
Title: How to create a Drupal database on the server if you only have access via an FTP client
I am a bit confused about how to set up server database,because my host provider(is a university site),only provided me with a ftp client username and password. I don't have access to phpmyadmin.:/

# Answer
You need to ask your server admin to create a database and a user for that database to be able to install drupal. You don't need phpmyadmin but you do need a database/user.
> 1 votes

# Answer
You will have to get a username and password generated by administrator as well and maybe the computer name where the database is installed it is usually on a localhost but that depends on the way the network is setup
> 0 votes

---
Tags: database
---


# Question
Title: How to use hook_user_login and hook_user_logout to output content to the page
I came across this post: execute a php code after a user login and I implemented the accepted solution. In my implementation, however, I'm trying to output content to the page. This simply doesn't show up. My module name is "alert", and here's the code:

alert.module

```
<?php

function alert_user_login(&$edit, $account) {
  for ($i=0; $i < 1000; $i++) {
    echo 'hi<br>';
  }
}

```

alert.install

```
<?php

function alert_install() {
  // Set the module weight so it can override other modules.
  db_query("UPDATE {system} SET weight = 99 WHERE name = 'alert'");
}

function alert_uninstall() {
  // Remove the module from the system table
  db_query("DELETE FROM {system} WHERE name = 'alert'");
}

```

alert.info

```
; $Id$
name = Alert
description = Present dialogs or perform redirects based on certain events
core = 7.x

```

I'm implementing this in my theme's `template.php` file. Should this work?

# Answer
> 4 votes
It will not work in template.php You need to add this in a module file, check here on howto instead of `myTheme` it will be `modulename` If module name is foo then it will be `foo_user_login`

```
    // @file : foo.module
    function foo_user_login(&$edit, $account) {
      fluenz_user_function($account->uid);
    }
    // and this function name was also different just an FYI
    function fluenz_user_function($uid) {
      for ($i=0; $i < 1000; $i++) {
        echo 'hi<br>';
      }
    }

```

# Answer
> 1 votes
hook\_user\_login(), and hook\_user\_logout() are not thought to be used to alter the content of a page. They are thought to record the fact a user logged in, or logged out, and eventually set a message with drupal\_set\_message(). To notice that the answer for the question you are referring is talking of executing code, not printing a string through `print()`, or `echo()`.

`hook_user_login()` could be used to set a global variable, or a static variable (see drupal\_static()) that is retrieved from another hook.

For altering the content of a page, there are other hooks; which one you should use depends from what exactly you want to achieve.

---
Tags: 7, hooks, users
---


title: Split PDF's into multiple parts

text:
# Question
Title: Split PDF's into multiple parts
Is it possible to allow pdf uploads to be split automatically by drupal?

Example1: If I upload a PDF with 4 pages. Drupal will split it into pdf(page1), pdf(page2),etc...

Example2: I upload a pdf that is 10mbs, It can logically split the files into a limit. So if the limit was 5mbs. It would split the file into 2 even parts...

# Answer
Drupal can't out of the box. Doesn't mean YOU couldnt in PHP :) (i think)

I've written PDFs on-the-fly using Ruby and mucked with it in PHP soooo ....

Using Fields in Drupal you could supply an File Upload widget for PDFs.

Then write a module to process the file on upload,

Using PHP's built in PDFs functions like:

http://php.net/manual/en/function.pdf-get-pdi-value.php

simply get the numbers of pages, and then retrieve each page's content and make a new simple 1 page PDF out of it. Then save the file and FID to another Field of files with unlimited values for any number of pages .... It sounds doable for most PDFs (not necessarily crappy built non-standard PDFs) -- but definately some work .... :)
> 1 votes

# Answer
Re: per page, you might look at the PDF to ImageField module. It can create image snapshots of each page.
> 0 votes

---
Tags: files
---


# Question
Title: What does a basic module look like that includes a content type, a couple of fields and a view?
I am looking at turning my Features into proper modules. There is nothing fancy to them other than a content type, a couple of textfields attached and a view. It looks like the features module pretty much exports these into a module anyways but it looks like it relies on some helper functions in the features module to get this going. How can I convert my feature so that it doe not require the features module to be installed?

# Answer
> 1 votes
I don't know of an example module that has all of those pieces together, but I think you'll find that field\_example and node\_example from the Examples for Developers project useful.

As well, this page of the Features documentation mentions something interesting:

> Technically, an exported Feature is a Drupal module – it has a .info file and a .module file (along with some .inc files matching the components of the feature).
>
> If you're a developer and find a feature bundle a good starting point for a module, you could just extend the feature by editing its .module file (and if need be also the .info file) to include hooks and what have you.

So you may wish to export your Feature, then develop on it from there based on the samples in field\_example and node\_example.

# Answer
> 0 votes
In my experience, you just want to create a content type by a custom module.

If this is your goal, all you need is to create a .install file.

When you install your module all the content type and field will be set up completely.

---
Tags: 7, features
---


# Question
Title: Function for showing thumbnails for nodes with imce
I am looking for a function, to show thumbnails for nodes. There are some sized defined in imce and I want to show on of these.

This is my current function which puts out only the large Version of the Image:

```
if (isset($content['field_image'])) {
    echo render($content['field_image']);
}

```

What would be a correct Drupal 7 conform function the show the 'medium' thumbnail in the node template?

# Answer
You can change style output in display fields settings of your content type. This will affect you render.

Also you can use theme\_image\_style function to set your image style

Url of image you can find in `$content['field_image']['und'][0]['uri']`
> 0 votes

---
Tags: media, nodes, files
---


# Question
Title: How do I sort a view based on when a specific field was last updated?
I have a field(field\_video) for Embedded Videos. I have a view that shows a list of all Videos and I want to be able to sort that view by when the video was last accessed(Recently Viewed), when the video was added(New Videos), and total number of views(Popular). Is it possible to sort a view based on attributes of the field? I have a quicktab that would then show a block of each view by each specific sort criteria.

# Answer
Such attributes are not available on fields, but they are available for nodes, and it sounds like that's all you need.

Views already provides a Sort Criteria for "Content: Updated date."

To sort by node statistics, make sure that the Statistics module is enabled (it's part of Core). That will provide additional Sort Criteria in Views. Add a Sort Criteria and filter by "Content statistics" to see three new options.

If you *really* need to use similar attributes on fields, you can use Rules to update extra fields based on whichever events you desire, and filter Views with those values.
> 0 votes

---
Tags: views
---


# Question
Title: Views- how can I hide one specific value of a series of checkboxes displayed in views?
On my user profile, I am displaying a **field** that looks like this:

Choose your favorite fruits:

* Apples
* Strawberries
* Bananas
* Grapes
* Click to enter your own

Using the Conditional Fields module, clicking "Click to enter your own" displays a text field where the user can input whatever they like. This all works great.

However, if a user chooses "Apples", "Strawberries", and "Click to enter your own", when I display the user profile in views by adding the "favorite fruits" field, it looks like this:

Fruits I like: Apples, Strawberries, Click to enter your own

Needless to say this is very ugly and I want to hide "Click to enter your own"-- and that's all I want to do, hide that text. Is there an easy way to do that?

EDIT: I'm attempting to find the values for my site for `($view->field['my-field-name']['my-field-value']`. Using print\_r, it appears that the value I want to remove is: `[field_purpose]['und'][0]['o']`; "o" is the value of the checkbox for other in the field\_purpose field. However, when I use this code: `($view->field['field_purpose']['und'][0]['o']`, I get this error: **Fatal error: Cannot use object of type views\_handler\_field\_field as array mymodule on line 325**

Perhaps I have the value wrong? When I use dpm instead of print\_r (`dpm($view->field['field_purpose']);` I don't see the values of the checkboxes stored anywhere...

The dpm output is as follows:

# Answer
> 0 votes
Ultimately, I solved this as described here: https://drupal.stackexchange.com/a/38624/5147

It turns out that using a views template file is a much easier, more maintainable, less complicated solution.

# Answer
> 3 votes
You can remove it with jQuery. Find that element by the value and just do .remove().

Even though this is not the perfect solution, it needs least amount of time and you can use it in the short term.

\[EDIT\]

Check Views selective filters. They can limit the options only to the ones available in the results; all others will be hidden.

# Answer
> 1 votes
Sorry, I think that there is no easy way. My solution would be to do it programatically. Create your own module and add a hook function for the prerender view function. This is how I would do it in drupal 7.

Something like this:

```
function mymodulename_views_pre_render(&$view) {
  if ($view->name == 'my-view-id-name'){
     unset($view->field['my-field-name']['my-field-value']); //not sure about the correct construct of this fields array,
       //but print_r it and you'll find out, maybe an if and setting it to '' would be better, but pop should work too
  }
}

```

# Answer
> 1 votes
To delete an element from an array you could simply execute something like this (copying from the previous answer):

```
unset($view->field['value'];

```

If you are not able to debug the module, use print\_r. To the previous answer should be useful also to check the display:

```
function mymodulename_views_pre_render(&$view) {
  if ($view->name == 'my-view-id-name' && $view->display == 'my-display') {
     unset($view->field['my-field-name']['my-field-value']);
  }
}

```

Check obviously every name and variable used in the function :)

# Answer
> 0 votes
The best approach is to use Select (or other) field in user profile instead of two fields (select and textfield to enter custom value)

In this case all values that are entered by user will be available in view filter and "Click to enter your own" option will not be shown in exposed filters.

# Answer
> 0 votes
In view edit your filter criteria settings for field "Fruits I like".

In popup window you will see list of all available options for this field- check all options except "Click to enter your own" and under this list check "Limit list to selected items".

Thats all.

---
Tags: views
---


# Question
Title: Attaching the comment form programmatically
How do I add the comments form (of the comments module) programmatically in a custom-made module?
In other words, what proper code should be added to your module code to add a complete "Post New Comment" form (of the Comments core module)?

That said, how do I force the installation of the Comment module with the installation of your own module?

---

I'm re-asking my question in an edited version with some new results i've reached :).
I've created a custom menu in a custom module of mine, with items of course.
I wanted to add the comment form (of the Comment module) to the page that my item takes me to.
The problem is that the page i'm redirected to is not a node, but it is a render-able page that displays the data according to it's 'page\_arguments'.
It is as follows:

```

$items['car/%'] = array(
        'title' => 'Cars',
        'page callback' => 'car_page',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
);

```

I want to attach the comment form (of the Comment Module) to that page.
I used the following code:

```

module_load_include('module', 'contact');

$build = array(
    'header_text' => array(
        '#type' => 'markup',
        '#markup' => 'Building comments in page.',
    ),
    'the_form' => drupal_get_form('comment_form', ''),
);

return $build;

```

All is correct code.

But the problem is that the comment form and the posted comments are loaded depending on the node Id (nid), and in my case there is no node Id (nid)!

How could i assign a specific identifier of that custom page so that the comment form functions correctly and comments related to that page are correctly loaded?!

And in the code above, i managed to call the form using drupal\_get\_form(), and assigned an empty second argument! I don't think that's right, right?

Any ideas!?

# Answer
`comment_form()` is expecting the parameter to be an object rather than an array so you should be doing something like this:

```
$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);

```

Note the lack of a 3rd parameter passed to drupal\_get\_form(), comment\_form() only accepts the comment as a parameter, if you want to add a title you'll have to print that separately.

Finally drupal\_get\_form() returns a render array rather than a string so you need to pass it through the render() function:

```
print render($form);

```

The extra errors you're getting are just side-effects of passing an array rather than an object to the comment\_form() function
> 3 votes

# Answer
Attach comments to what? Note that you can only attach comments to nodes.

The API function for saving comments is comment\_save(). You will have to figure out what kind if properties you need to have on the $comment object that you want to pass in. Probably at least `nid`, `subject` and `body['und'][0]['value']`.

> That said, how to force the installation of the comments module with the installation of your own module?

Thtat is a separate question, try to only ask a single question at once. You need to add `dependencies[] = comment` in your .info file.
> 2 votes

---
Tags: 7, comments
---


# Question
Title: Find out the user's IP address given their UID?
I'm running Drupal 7 web site with a Russian multiplayer card game and have to block some very annoying players every 4-5 days.

Before Drupal I was using phpBB 3. When these persons would come from a small city/village I'd just add their IP-network to the firewall rules, so that they can't re-register with a new mail address. This worked well in my case and my question is not about this policy.

My problem is that with Drupal, I can't find the last IP address used by a user id. I.e. the abuser is reported to me by other users and I know his uid, but I can't find his IP address in the logs, because:

1. I've enabled syslog-logging and see the Drupal messages in /var/log/messagess but there is rarely a message about a user logging in, probably because sessions are long by default, and I'd like to keep it this way for user comfort.
2. I've also enabled "database logging," but don't know where to see it (which database table).

# Answer
> 9 votes
If you have statistics module enabled, the "accesslog" table contains the IPs for all your visitors.

```
SELECT hostname FROM accesslog WHERE uid = %UID_FOR_YOUR_USER% LIMIT 1

```

If you do not have statistics enabled, I advise you to leave it off, even for this result, because enabling it, causes a severe performance-penalty.

In that case, you can use `sessions` table:

```
SELECT hostname FROM sessions WHERE uid = %UID_FOR_YOUR_USER% LIMIT 1

```

The benefit of the first over the latter, is that the first will always show you the latest hostname, whereas the latter might not always be up to date.

# Answer
> 5 votes
As far as I know, Drupal doesn't reports the IP used by users in their user profile. You could create a custom module, verify the IP used by the user, and record it in your own database table; then you could show it in the user profile, to users who has the right permission (for example, to users with the permission to administer users).

The function you need is ip\_address(), which you can use in your implementation of hook\_user\_login(). Implementing hook\_user\_view(), you can then show such information to the users with the right permission.

# Answer
> 3 votes
If you are using the database logging module, Drupal stores this information in the watchdog table, under the `hostname` column. You can either write custom queries to get at this information, or use the Views Watchdog module (currently only a dev release for 7.x, so I'm not sure how well it works in Drupal 7) to expose that table to Views.

# Answer
> 1 votes
Two recent modules may help with this:

User IP Log, which has Views integration, and IP Address Manager, which does not have Views integration but is intended to integrate with Manifest, Cave Your Trolls, and Misery-- all banning related modules.

# Answer
> -1 votes
**session\_id()** gives you current user session-id whether he/she is a guest or a member.

```
$result = db_query("SELECT hostname FROM sessions WHERE sid = '".session_id()."'");
$data = db_fetch_object($result );
echo $data->hostname;

```

---
Tags: 7, users
---


# Question
Title: Left and Right region is not showing on ZEN sub theme
I've been working right now on a custom sub theme via ZEN for a certain Drupal site. I had it first developed in my localhost. Right after I had the half of the basic design implemented, I uploaded it immediately to the site and had it enabled. Now, something is wrong. The two regions are not showing up when I tried to view them on the block administration page. Even if I put a block on each of them, still they don't display on the page... what could it be?

In my localhost, it's working fine. I'm not sure why it's not working well on the live site. Has anyone of you experienced the same issue? Any help or suggestion is very much appreciated.

thanks in advance.

# Answer
I finally found the solution for this problem. That is the put 'zen' folder under the same location of the sub-theme folder. Actually, the site I've been working on is a multi site setup and there is also an entity there that is also using zen as it's theme. I thought putting just my sub-theme is enough since the site still recognized the main theme, which is Zen.

The reason why the two region of the theme I uploaded is not being recognized, is because it's info file is not being read properly. The info file that is being read by the site is found, on the other zen sub-theme I mentioned above.
> 0 votes

---
Tags: theming
---


title: How to call a CCK Field value in a node

text:
# Question
Title: How to call a CCK Field value in a node
I want to load one last post's title and call value of CCK fields. I defensibly don't want to use views module. so How can I call those CCK Fields?

anyway is this code correct to load one last post from all terms? I wish there was a way to do it with node\_load()

```
<?PHP
$output = '';
$terms = "*";
$count = 15;
$qry = "SELECT n.title, n.nid FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE tn.tid in ($terms) AND n.status=1 AND n.promote=1 ORDER BY n.created DESC";
$result = db_query_range(db_rewrite_sql($qry), 0, $count);
$output = node_title_list($result);
echo $output;
// echo [cck_field1_value];
// echo [cck_field2_value];
?>

```

# Answer
> 1 votes
I will tell you that the easier way it to use `node_load`. You do your query to simply get the last nodes according your criteria and then with the `nid` you load each node with `node_load`.

Why ? Because CCK changes his database structure according the fields that are attached or not to one or more content type. If you will change the CCK field one day, you will have to change your code, so the easier way to avoid it, its simply use `node_load`.

---
Tags: theming, 6, entities
---


title: Token Replacements

text:
# Question
Title: Token Replacements
What is the proper way to store token replacements in a variable? Or should i even bother and call them directly?

Things like:

```
$author_uid = [node:author:uid];
$name = [node:title];
$picture = [node:field-image-upload:file];
$link = [node:url];

```

Are giving me an error:

```
PHP Parse error:  syntax error, unexpected ':'

```

Am i doing something wrong?

Also in regards to this line:

```
$picture = [node:field-image-upload:file];

```

What I'm really trying to get is the url link to that image file. How can I do this with a token?

# Answer
> 2 votes
Token are a kind of meta language that needs to be processed to get the proper value. For it, you should send your token into a process function called `token_replace`.

Here is an example :

```
$author_uid = token_replace('[node:author:uid]');

```

Check this documentation page for further informations

---
Tags: 7, tokens
---


# Question
Title: Ubercart attribute changes price without page reload on Drupal 7
Running Drupal 7, and the latest stable UB. Currently, each product's price is set to $0. We have attributes that get selected and that is what determines a product final price. When a user selects the attribute. We want it to automatically change the product price without a page reload or needing to add it to the cart. How can I accomplish this?

Update: This is the latest patch that was mentioned here. I have patched my code as follows. I attached a pastebin of the patched code for review in case I missed something. Also if anyone wants post-patch code prior to it getting released to dev.

Some people report that the patch works. I unfortunately haven't been able to get it to work. The blue spinning ajax icon shows like its doing something but my display price doesn't change.

UPDATE FIX!: This thread details the answer to this question.

# Answer
> 1 votes
This is planned to be included in Ubercart itself, see http://drupal.org/node/1380772 \- any tests or comments are welcome in that issue.

---
Tags: 7, ubercart
---


# Question
Title: Locating a specific position on the page
I want to provide a clickable link on drupal such that it easily locates the position of the content in a page. e.g http://asblab.mie.utoronto.ca/people , I want to have a link , that automatically scrolls this page to locate "Past lab member" without requiring me to create a new node. Thank you in advance.

# Answer
> 3 votes
If you put whatever you want in a div or span with an id, you can then use that id for an anchor. For example, `<a href="http://asblab.mie.utoronto.ca/people#content-inner">GO HERE</a>` will GO HERE

---
Tags: nodes
---


# Question
Title: getting Drush to cooperate with Mercurial
I just tried to update a site on my local machine from Drupal 7.14 to 7.15 with "drush up". I use Mercurial (hg) for version control. (I know that most Drupal sites use Git, but we standardized on Hg before we started working with Drupal.)

I was surprised to see that the update process pretty much hollowed out the .hg folder, which is where Mercurial stores all of its information. I got the following warning from drush:

rmdir(C:/Dev/mysite/.hg): Directory not empty filesystem.inc:141

Is there something I need to do to tell drush to please leave that folder alone? I googled this issue and didn't find anything helpful.

\[update 08/29/2012\] I thought I'd post an update to this, since I still haven't solved the problem. I tried to update a fairly vanilla test Drupal site from 7.14 to 7.15 this morning, and got the same error. Drush failed to update Drupal, and pretty much destroyed the .hg folder in the process. Here's a full dump of the messages from Drush as it did this:

```
    Code updates will be made to drupal core.
    WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
    Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

    Do you really want to continue? (y/n): y
    rmdir(C:/Dev/drupal-7-test/.hg): Directory not empty filesystem.inc:141              [warning]
    string(2) "\037ï"
    array(1) {
      [1] =>
      int(35615)
    }
    string(2) "\037ï"
    array(1) {
      [1] =>
      int(35615)
    }
    Destination directory C:/Dev/drupal-7-test/drupal-7.15 already exists.                 [error]
    Project drupal was updated successfully. Installed version is now 7.15.
    Backups were saved into the directory                                                     [ok]
    C:\Users\ahuey/drush-backups/drupal_7_test/20120829131850/drupal.
    Backups were restored successfully.                                                       [ok]
    rmdir(C:/Dev/drupal-7-test/.hg): Directory not empty filesystem.inc:141              [warning]

```

I'm running Drush 5.5. I'm OK with having to update Drupal manually for now, but it's a weird problem, so I may spend some more time on it, if I can spare the time.

# Answer
wow ... drush up to my knowledge shouldnt touch any (dot) hidden files or directories. Drush up just looks for more recent module packages and updates them, which has nothing todo with .hg or .svn or .git directories.

Are you talking about a global .hg directory for your projects, or like an .hg directory within a module folder somewhere!?
> 1 votes

---
Tags: drush, version-control
---


# Question
Title: Programmically displaying imagecache presets no longer works
I have noticed that recently imagecache no longer displays images when used programmatically. I have seen this happen on an existing site in which it did work at one time and on a new site (that I am currently developing). I am using the command:

```
print theme('imagecache', 'listing_thumbnail', $node->field_photos[0]['filepath'],
    $node->field_photos[0]['data']['alt'], 'Listing thumbnail', '');

```

I have tripled checked that the preset name is spelled correctly, the node attributes field\_photos are correct so it should work. I have searched high and low to see if anyone else is having this problem but can't find anything. What am I missing? Why does this no longer work?

I am using Drupal 6.25 and imagecache 6x-2.0rc1

# Answer
> 1 votes
I discovered that the problem in this particular case is that the imagecache 6x-2.0rc1 module has a regression bug in it. Reverting to the previous version restored the functionality and everything works as it should. Hopefully this will be fixed with the next release of imagecache.

# Answer
> 0 votes
I would check that the user running the web server process has the correct permissions to write in the files directory. Imagecache writes the images into physical files and if it cannot do so, no images will be displayed.

---
Tags: 6, media
---


# Question
Title: Easiest way to get term entities from a term reference field?
I always end up with lots of juggling to get seemingly simple things, like "All term names".

```
$field_terms = field_get_items($entity_type, $entity, $tags_field);

if ($field_terms) {
  $tids = array();
  foreach ($field_terms as $field_term) {
    $tids[] = $field_term['tid'];
  }
  $terms = taxonomy_term_load_multiple($tids);

  $tags = '';
  foreach ($terms as $term) {
    $tags .= $term->name . ',';
  }
  $tags = rtrim($tags, ',');
}

```

Can anyone share any neat tricks for making the above easier?

The part that really annoys me is the first loop, that I need just to untangle the field api array.

# Answer
This one annoys the bejesus out of me too. Things are slightly nicer using the entity API module, but it's still not pretty.

I've resorted to including a helper function in most projects now to extract an array of values for a single field column:

```
function _field_get_column_values($entity_type, $entity, $field_name, $column_name) {
  if ($field_items = field_get_items($entity_type, $entity, $field_name)) {
    $values = array();
    foreach ($field_items as $item) {
      if (isset($item[$column_name])) {
        $values[] = $item[$column_name];
      }
    }
    return empty($values) ? FALSE : $values;
  }

  return FALSE;
}

```

Using that your code would shrink a little:

```
if ($tids = _field_get_column_values($entity_type, $entity, $tags_field, 'tid')) {
  $terms = taxonomy_term_load_multiple($tids);

  // ...
}

```

It's still not a great solution, but I find it saves a fair bit of time on projects that need a lot of custom code.
> 2 votes

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


# Question
Title: How would you implement function rich forms to your module
I'm having a hard time deciding on how to develop the following functionality in my upcoming module:

I'm developing a module which should eventually be able to create "event" type nodes. Which extend the nodes functionality to have:

1. One or multiple **plannings** which consist out of...
2. ... **timespaces**, which has the following properties, per timespace:
    * **from** (datetime)
    * **to** (datetime)
    * **limit of subscribers** (int)
    * And other stuff (not related to the question)
3. The website visitors should be able to subscribe to each timespace with a form, filling out their information. But if, and only if the **limit of subscribers** has not been reached yet for this timespace.
4. After subscription, the visitor should get an automatic mail with a PDF (ticket) attached to it.
5. Our customer should be able to **export all the data**, at any time to an Excel sheet...
6. ... and (preferably) quick-review all the subscriptions at all time.

Well, the **plannings** and the **timespaces** won't be a problem, I'll manage that. But I would absolutely LOVE to incorporate Webforms into this. Since, point 3 through 6 all address functionality that already exists in Webforms... It'll save my butt a lot of time developing this thing.

**My question is**... Does anyone have any experience developing a module, incorporating Webforms? If so, how did you combine the two? I was thinking about something in the lines of:

* Developing a new Field widget which would make it possible for the moderators to create the event's plannings and timespaces.
* Somehow, (and this is the part where I'm not sure how to do this) creating a field for "webform" that would fetch the possibilities from the field.

I'm not sure.. I don't think this is the right way to go... I wonder what you guys think about this and if I simply should develop my own form + all the functionalities with it. Or maybe know a contrib module that does all of this...

# Answer
I've found the solution today myself. I've been developing Webform components. I've found this way to be the best solution without altering any database structures and still getting the full functionality I wanted to get.

# Instantiating - The base of your webform component

hook\_webform\_component\_info \- will be your friend in defining your components base structure. Since I needed the **planning** which would consist out of more **timespaces** (could've done better here on the termonology ;) ), I added a component named "*planning*" and gave it a "feature": group. This way I can extend the component "*planning*" with the "*timespace*" component.

# Values - Add a limit of subscriptions and other parameters for your timespace

\_webform\_edit\_component \- Makes it possible to alter the edit form of your component. Make sure you at least add an "limit\_subscription" (adjust naming to your liking) field so we can check against it.

\_webform\_defaults\_component \- Will be needed to inject the defaults to your edit form, which you have created with the function here above.

# Cosmetics and security - Make sure you get the checkbox and disable it when full

\_webform\_render\_component \- Arranges all the cosmetics on your webform component. So make sure you edit your **timespace** component to get the checkbox you want so people can check a timespace. Also, you can (ofcourse) add some additional markup to your liking.

**Security, checking the limit**

This is also the right place to check for your limits and disabling the checkbox when full. (see the function `webform_events_check_timespace_limit($component)`, use that to set `#disabled` on your element. Also make sure you give your element the right validation, something like this, so they can't screw around by simply enabling the checkbox:

```
'#element_validate' => array('_webform_validate_timespace'),

```

Then check against the database in your validation function for the limits, this is how I got it done:

```
/**
 * Validation for timespace elements
 */
function _webform_validate_timespace ($element, &$form_state) {
    // If checked, make sure this timespace has some space left.
    if ($element['#value'] === 1) {
        $remaining_subscriptions = webform_events_check_timespace_limit($element['#webform_component']);
        if ($remaining_subscriptions === -1) form_error($element, t('The timespace that you\'ve chosen is already full!'));
    }
}

/**
 * Check if the limit has been reached, returns remaining count to the limit, or -1 when full, or FALSE when no limit is set
 */
function webform_events_check_timespace_limit ($component) {
    $limit_subscriptions = $component['extra']['timespace_properties']['limit_subscriptions'];
    if (!empty($limit_subscriptions)) {
        $count_subscriptions = webform_events_get_timespace_count($component['nid'], $component['cid']);
        if ($count_subscriptions >= $limit_subscriptions) return -1;
        else return $limit_subscriptions - $count_subscriptions;
    }
    return FALSE;
}

/**
 * Get the count of the current timespace subscriptions
 */
function webform_events_get_timespace_count ($nid, $cid) {
    $select = db_query('SELECT count(*) FROM {webform_submitted_data} WHERE nid = :nid AND cid = :cid AND data = 1', array(':cid' => $cid, ':nid' => $nid));
    return $select->fetchColumn();
}

```

# Backoffice - Exporting, table views, analysis..

For this you need the following functions, I'm not writing out these, I could go publish a book if I would:

**Exporting (CSV, Excel):**

**Submission view** (The page you get at individual submissions)

**Table view**

**Analysis view**

# More help

Since I've just outlined the basics of this thing, I'd recommend you check out some good examples.

I've managed to figure this all out and fix get somewhat of the following (of course; early beta screenshots)

**Submission view**

**Analysis view**

**A simple export**

**Front-end example**

**Table view**

**Setting up a event**
> 1 votes

---
Tags: 7, forms, webforms
---


# Question
Title: Problems connecting to database in drupal 6
Whew, ok I am new to Drupal, and I am dealing with a outdated drupal site. Ive been told not to upgrade yet, so for now I am dealing with Drupal 6. I am trying to stage it on our test server, but it won't seem to connect to the database. (It returns a page that says "Site off-line" and "Deprecated: Function ereg() is deprecated in E:\development\ump\_2010\includes\file.inc on line 926") Below that, it states that I could not connect to the database:

```
The mysql error was: Access denied for user 'root'@'localhost' (using password: YES).

```

I went into the settings.php file and changed $db\_url to the correct one, and $db\_prefix remains empty. Where is drupal getting 'localhost' and the password from as well?

Thanks, Austin Slominski

# Answer
All of those values are set in `$db_url`, in the sites/default/settings.php file.

```
$db_url = 'mysqli://username:password@server_ip_or_host/databasename';

```
> 2 votes

---
Tags: database
---


# Question
Title: How to disable and grey out a form button if the textfield is empty?
I have a custom module built, and I would like to grey out and disable the submit form button if the textfield is empty. Can anyone help?

Here is the code for the textfield and the form button:

```
$form['ro-user-details']['nickname'] = array(
    '#type' => 'textfield', '#width' => 50,
    '#title' => t('Nickname'),
    '#default_value' => $ro_user->nickname,
    '#size' => 50,
    '#maxlength' => 200,
    '#required' => TRUE,
    );

    $form['ro-user-details']['change_nickname'] = array('#type' => 'submit', '#value' => t('Change Nickname'));

```

# Answer
> 1 votes
Obviously you will want to do this with some jQuery...And of course there is more than one way to do this, but:

```
$(function(){
      //Set button disabled
      $("input[type='submit']").attr("disabled", "disabled");

      //Append a change event listener to your input
      $("input[name='nickname']").change(function(){

            if($(this).val().length > 0) {
              $("input[type='submit']").removeAttr("disabled");
            }
      });

      // You could then trigger the a change event on load just to check
      $("input[name='nickname'").trigger('change');
});

```

That should be the gist of it. Of course you would want to change your "name" value to whatever your input name is.

---
Tags: forms, javascript
---


# Question
Title: How do you change the default value on a CCK text field that is part of a field group via hook_form_alter()?
I'm trying to programmatically set the default value (#default\_value) on a textfield added via CCK. This field is in a field group. Here is my code:

```
/**
 * Implements hook_form_id_form_alter().
 */
function EXAMPLE_form_profile_node_form_alter(&$form, $form_state) {
  // We need to jump into a CCK field, so say we all.
  $form['#after_build'][] = 'EXAMPLE_form_profile_node_form_after_build';
}

function EXAMPLE_form_profile_node_form_after_build($form, &$form_state) {
  $form['group_company_profile']['field_pro_name']['#default_value'][0]['value'] = t('test');

  return $form;
}

```

I've tried various other points in the array and nothing seems to work. Both CCK and my module are weight 0. I must be missing something super obvious...?

**UPDATE**: One mistake was the field name. It should be field\_pro\_name. Updated above. It's still not working. Interestingly, I can use the after build to change the field title with:

```
$form['group_company_profile']['field_pro_name'][0]['value']['#title'] = 'ttt';

```

However, none of these changes the default value:

```
// In form alter:
$form['group_company_profile']['field_pro_name'][0]['#default_value']['value'] = 'ttt';
$form['group_company_profile']['field_pro_name'][0]['value']['#default_value'] = 'ttt';

// In after build:
$form['group_company_profile']['field_pro_name'][0]['value']['#default_value'] = 'ttt';
$form['group_company_profile']['field_pro_name'][0]['#default_value']['value'] = 'ttt';

```

# Answer
You *should* be able to do something like this:

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

  if ($form_id=='profile_node_form') {
    $form['group_company_profile']['field_pro_type'][0]['#default_value']['value'] = 'hello world';
  }

  // all other form alters here...

}

```

or

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

  $form['group_company_profile']['field_pro_type'][0]['#default_value']['value'] = 'hello world';

}

```

directly from whichever form\_alter() style you like.
> 2 votes

---
Tags: entities, 6
---


# Question
Title: How to get or extract the link path for terms in View
I have created a Taxonomy Term view in Drupal 7, and list out all my terms through "Taxonomy term: Name" field.

Now, I wonder how to extract the link path of each term so that I can reconstruct and adding the passing value through the url.

e.g.

```
http://www.domain.com/fruit/apple?quantity=100

```

# Answer
A quick solution will be:

1. Use "pathauto" to generate path for term pages (taxonomy/term/term\_id =\> fruit/apple)
2. Use "global redirect" to force default path to custom paths
3. In your View build the URL like taxonomy/term/term\_id?quantity=100 and should be translated at rendering time to fruit/apple?quantity=100

Thank you.
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: looking for views gallery module compatible with lightbox module
I would like to achieve a behaviour like this:

At the bottom of the screen there are thumbnails. Above them is a big image styled for 800x600 which changes after clicking a thumbnail. When the user clicks on the big image, then an overlay with lightbox opens and the image is not 800x600 but full size, scaled to screen. There are working Next and Previous buttons on the lightbox (not necessarily linked to the underlying thumbnails gallery).

How to achieve it? I am interested in a solution working either out of the box or having clear tweak instructions. Any gallery module and any lightbox will do, as long as they are compatible and have next/previous buttons working.

So far I tested Views Galleriffic and Lightbox2 and Colorbox, using patch from here and I managed to open the big image in original size using lightbox2 and colorbox. However, Previous and Next buttons are not working in either case.

# Answer
> 0 votes
Have you tried Views Slideshow with Views Slideshow Xtra?

Here are some more details about these modules (quotes included are from their project pages):

* Views Slideshow:

> ... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
* Views Slideshow Xtra:

> ... is an enhancement module for Views Slideshow, providing the ability to create overlays for a Views Slideshow. HTML elements are placed in overlays, with overlay visibility controlled by toggling the CSS display property, so that overlays are displayed with their corresponding slide. Animation of the overlay displays is also supported.

---
Tags: 7, views, javascript, media
---