# Question
Title: Trying to write custom handler to extend views_handler_field_term_node_tid
Edit: solved, see first reply for answer.

I am trying to write my views filter handler to extend the views\_handler\_field\_term\_node\_tid class. I believe I have done everything correctly but I'm having no luck. In my module I have implemented hook\_views\_api()

```
/**
* Implements hook_views_api().
*/
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', mymodule') . '/views',
  );
}

```

Called the handler.inc file and the mymodule.views.inc in the module .info file:

```
files[] = views/mymodule.views.inc
files[] = views/mymodule_handler_field_term_node_tid.inc

```

This is the contents of that file:

```
class mymodule_handler_field_term_node_tid extends views_handler_field_term_node_tid {

  function option_definition() {
    $options = parent::option_definition();
    $options['convert_spaces'] = array('default' => FALSE, 'bool' => TRUE);

    return $options;
  }

  /**
   * Option to replace spaces with hyphens.
   */
  function options_form(&$form, &$form_state) {

    parent::options_form($form, $form_state);

    $form['convert_spaces'] = array(
      '#title' => t('Convert spaces in term names to hyphens'),
      '#description' => t('This allows links to work with Views taxonomy term arguments.'),
      '#type' => 'checkbox',
      '#default_value' => !empty($this->options['convert_spaces']),
    );

  }

  function render_item($count, $item) {
    return $item['name'];
  }

}

```

And finally I have implemented hook\_views\_data\_alter() in the mymodule.views.inc

```
/**
 * Implements hook_views_data_alter()
 */
function mymodule_views_data_alter(&$data) {
  $data['node']['term_node_tid'] = array(
    'title' => t('Taxonomy terms on node'),
    'help' => t('Relate nodes to taxonomy terms, specifying which vocabulary or vocabularies to use. This relationship will cause duplicated records if there are multiple terms.'),
    'relationship' => array(
      'handler' => 'views_handler_relationship_node_term_data',
      'label' => t('term'),
      'base' => 'taxonomy_term_data',
    ),
      'field' => array(
      'title' => t('All taxonomy terms'),
      'help' => t('Display all taxonomy terms associated with a node from specified vocabularies.'),
      'handler' => 'mymodule_handler_field_term_node_tid',
      'no group by' => TRUE,
    ),
  );

}

```

So the weird issue is that running dpm($data); in my mymodule\_views\_data\_alter function before I alter the $data\['node'\]\['term\_node\_tid'\] brings up no reference to that data at all. That is being originally defined in taxonomy.views.inc and should be existing in the $data array because I have added the Content: All taxonomy terms field to my test view. I've been pulling out my hair for the last couple hours trying to figure this out with no luck.

# Answer
You must adjust your module's weight so that it runs after views. Use hook\_module\_implements\_alter or Modules weight

And then you can also change your code in MYMODULE.views.inc to something simpler:

```
function MYMODULE_views_data_alter(&$data) {
  $data['node']['term_node_tid']['field']['handler'] = 'MYMODULE_handler_field_term_node_tid';
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Explain field's language opposed to node language
I'm having a hard time understanding how it supposed to work.

For example I have a node where I set up the language to English. the langcode is `en`. If I want to read values from a field from this node I will have to do something like:

```
$node->field_custom[LANGUAGE_NONE][0]["value"]

```

and not

```
$node->field_custom[$node->language][0]["value"]

```

What is the point of having LANGUAGE\_NONE for all fields if on all nodes this is the same, no matter what language the node has. Thanks.

# Answer
> 1 votes
If you use the module Entity translation you have the possibility to say that the body field can be translated but the image field should not be able to be translated.

In your example this would mean

The value of `$node->field_body` will have different values for the different languages the field is translated to. I.e `$node->field_body['en'][0]['value']` could differ from `$node->field_body['sv'][0]['value']`.

But at the same time the image field will only have value in `LANGUAGE_NONE`.

Before the most used setup to have a multilingual site was to use the Internationalization module, which would create a new node when a translation of a node was done. The new approach with entity translation translates the fields instead.

*Worth noticing, the Internationalization module can be used together with Entity translation. I am only stating the older solution to multilingual sites.*

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


# Question
Title: Slider for Select List (Text, Numbers etc) in Views Exposed Filters
I am trying to implement a vertical slider-like select list inside my views-exposed-filters as shown in the image below (on the left sidebar, vertical slider)

I am using Drupal 7 and Views 3. I have tried Better exposed filters module but I don't think it has such a feature. How can I achieve this? (See updates below)

Thanks

UPDATE: I have also tried **Views Contextual Range Filter** and **Select with Style** modules but couldn't get any of them working as desired.

UPDATE 2: One thing I have realized is, I am trying to show a an exposed filter for a term reference field, named 'Style' (based on a taxonomy term), so actually the field itself is not a multi-value field, hence it is not a select list. That is why Select with Style module doesn't work here. Is there a way to tweak my field/Views to make it work with one of mentioned modules?

# Answer
> 1 votes
There is another module called Views Contextual Range Filter

> Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range.

# Answer
> 0 votes
It seems you are looking for Select with Style:

> Slide with Style, contains a field widget to enter numbers or list values via sliders when creating content and also to filter using this widget in Views. This includes double-handled sliders to input "in-between" ranges.

---
Tags: views, javascript
---


# Question
Title: Using function of views_embed_view may caused high CPU loading
I found that a page in my Drupal site is causing high CPU/memory loading, I tried to remove each item(e.g. block, custom PHP code and so on) on this page. Finally, I found that if I remove the code below will drop down the CPU/memory usage from 90% to 10%.

```
print views_embed_view('flag_compare', 'block_1');

```

Could someone suggest another function to embed view?

# Answer
> 2 votes
The function itself has not much to do with this, it is a wrapper for creating and displaying a view. The view you are displaying is a block - if you should have chosen to enable the block instead my guess is that the result would have been the same.

The most probable cause is the view you are displaying. Tools like views and panels are great at handling displaying stuff, but it comes at a price. They are usually a lot more ineffective than if you had done it with your own code, but they are also a lot faster to use. I would recommend that you review the view and try to find a way to reduce the workload by simplifying it, or if it's really important to you, do it yourself and skip a lot of the abstractions that Views bring.

# Answer
> 1 votes
You should not use views\_embed\_view in a tpl. Drupal will boostrap twice. Use a preprocess function are create a block and embed it in a region.

---
Tags: views, 6, performance
---


title: How to display 2 blocks in one view

text:
# Question
Title: How to display 2 blocks in one view
I am using quick tabs, but I want to display 2 blocks under each tab, been told I should use attachments but I don't get.

How can I achieve this?

So each tab displays 2 blocks when clicked like in the sketch.

# Answer
You may try using the module Block Group. You can group multiple blocks into a single block using this module.
> 1 votes

---
Tags: views, blocks
---


# Question
Title: Limit amount of content creation per anonymous user
In my site anonymous users has access to create one type of content and all data the site stores is user IP address.

How do I limit lets say e.g. 2 nodes creations per IP in 12 hours? And when limit is reached, they get some message instead of creating another node until 12 hour range pass?

Because now some of anonymous users are just abusing and spamming the node creation which is unlimited by default.

UPDATE: I tried using Node Limit, but it doesn't really work. When I load a page with the form which has the limit set, it doesn't load the page and that's a home-page of the site and form is displayed as Form Block via Panels. So instead of a home-page I get redirected to node/add/ and page not found.

# Answer
> 4 votes
You could do it custom with `hook_node_access` and the Flood API.

e.g:

```
/**
 * Implements hook_node_access
 */
function MY_MODULE_node_access($node, $op, $account) {

    // Get node type, can be string or node object
    $type = is_string($node) ? $node : $node->type;
    if ($type == 'type_of_interest') {
      // Check flood limit for anon users node creation
      if ($op == 'create' && user_is_anonymous()) {
        // Ensure checked only once per page request, node/add path only
        $access_checked = &drupal_static(__FUNCTION__);
        if(empty($access_checked) && arg(0) == 'node' && arg(1) == 'add') {
          // Record the access check for drupal_static
          $access_checked = TRUE;
          // Check create_node limit of 2 per 12 hours
          // Note, you could make the threshold and window config variables.
          if(!flood_is_allowed('create_node', 2, 43200)){
            drupal_set_message(t('There is a node creation limit of 2 nodes per 12 hours. Please try again later.'), 'error');
            return NODE_ACCESS_DENY;
          }else{
            // Register the node create event to test against for 48 hours
            // Note, you could move this somewhere else to ensure the node is actually saved, e.g hook_node_insert
            flood_register_event('create_node', 172800);
          }
        }
      }
    }

  return NODE_ACCESS_IGNORE;

}

```

# Answer
> 0 votes
You can use the Node Limit module

> The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create.
>
> * Per-role node limits
> * Per-user node limits

---
Tags: 7, users, nodes
---


# Question
Title: Change drupal standard messages like "You have just used your one time login link"
I'm having trouble with changing drupal default messages.

Like for example when you register you get an email with a one time login link (I know how to change this email text) and when you click on the link you get the message

> This is a one-time login for username and will expire on ... .
>
> Click on this button to log in to the site and change your password.
>
> This login can be used only once.

But how can I change this text? Another example is:

> You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.

How can I change these texts?

# Answer
> 4 votes
Try the String Overrides module. If you have more strings to change.

> Provides a quick and easy way to replace any text on the site.
>
> **Features**
>
> * Easily replace anything that's passed through t()
> * Locale support, allowing you to override strings in any language
> * Ability to import/export \*.po files, for easy migration from the Locale module
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.

---
Tags: 7, users
---


# Question
Title: Differences between value and safe_value
What are the differences between `['value']` and `['safe_value']`?

# Answer
It is a value, passed through the function `_text_sanitize()`. You can read more in the official docs.

If you are using `'safe_value'`, you may be also interested in this article: Rendering Drupal 7 fields (the right way).
> 24 votes

# Answer
The main difference it that the safe\_value is passed through the function \_text\_sanitize().
> 16 votes

# Answer
For Readers benefit, DO NOT use safe\_value data when making SQL statements. In other words, strings containing ampersand ( & ) will become ( `&` ) fail to get the expected results.
> 1 votes

---
Tags: 7, entities, security
---


title: formatting dates in views

text:
# Question
Title: formatting dates in views
I have added a date field to the article content type. I am writing a view to display this date. When I add the field I get a formatter drop-down which allows me to select three different date formats "Date & Time", "ago" or "plain". However if I add the article post date I get more options including a "custom" format option. It seems that the handler associated with my date field is 'views\_handler\_field\_field' whereas the handler associated with the 'system added' date field is 'views\_handler\_field\_date'. What is going on here? Why are the two fields treated differently? What do I need to do to get the extra options?

# Answer
> 1 votes
I dont know why the post date has extra options, it seems that it allows you to create a custom format "on-the-fly". But you can create a custom date format and use it for your date field, and for other date fields as well along with the "Short", "Medium" and "Long" formats.

If you go to: configuration \> date and time, you should see the three default ones (Short, medium,long). You can then click the "Formats" tap and then Add format. In the text field you can write a string that provides the format you want. Use the PHP date manual to find the letters that provides the month, date and so on. E.g if you want your format to be something like:

*25-03-2014 15:48*

Your string would be:

*d-m-Y H:i*

(Hint - you dont need necessarily to have minutes, you could also just have: *d-m-Y*)

Save that format and go back to the "Types" tap. Click Add date type, give it a name and then select your format on the list (it is typically at the bottom).

Then head over to your view, click the date field, and under the formatter, select Date and time, and then you should see your newly created date format on the list. Save your view and your custom date should display as the date...

# Answer
> 0 votes
```
function mymodule_views_data_alter(&$data) {

```

// loops through fields definitions looking for our date fields // and set the date handler.

```
foreach($data as $module => &$table) {
    foreach($table as $id => &$field) {
      if ($module == 'field_data_field_test_date2'){
       if (is_array($field) &&
          array_key_exists('field', $field) &&
          is_array($field['field']) &&
          array_key_exists('handler', $field['field']) &&
         ($field['field']['is date'] == TRUE)) {
          $field['field']['handler'] = 'views_handler_field_date';

        }
      }

    }
  }
}

```

My date field then acts like the post date.

---
Tags: views
---


# Question
Title: Style views row layout debending on result count
How to style views row layout debending on result count?

If views has 4 results then items should be placed on two rows and two columns:
| |
| |
And when views has more than 4 items - for example 6 then:
| | |
| | |

# Answer
You could implement `hook_views_pre_render` and count the number of results, then apply a class to the wrapper element.

```
function hook_views_pre_render(&$view) {
  switch($view->name) {
    case 'MY_VIEW_NAME':
      switch($view->current_display) {
        case 'MY_DISPLAY_ID':

          $numResults = count($view->result);

          /*
            Do your logic with $numResults here
          */
          if ($numResults <= 4) {
            $grid = 2;
          }
          else {
            $grid = 3;
          }

          $view->style_plugin->options['class'] = (isset($view->style_plugin->options['class'])) ? $view->style_plugin->options['class'] . ' grid-' . $grid : 'grid-' . $grid;

          break;
      }
      break;
  }
}

```

So then you can style the width of the views-row under grid-2 to be 50%, and 33% width for views-row under grid-3 in your CSS.

Your View display needs to use "HTML List" format for this code to work.
> 1 votes

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


# Question
Title: How to configure drush command-specific archive-dump --tar-options in a site alias
The following command does exactly what I want — It dumps an archive, excluding all of the files and directories that I don't want:

```
$ drush archive-dump --tar-options="--exclude=.git --exclude=*.psd --exclude=sites/default/files/styles/ --exclude=sites/default/files/private/backup_migrate/manual/"

```

Can anyone show me how to set these extra `command-specific` `archive-dump` `tar-options` inside a site-alias array in `aliases.drushrc.php`?

I've tried every variation I can think of, but I can't seem to get the syntax right.

**Update** Here is a gist with my full test setup including verbose output and -debug info.

# Answer
> 1 votes
It should be like this - Edit: I've just confirmed that the following works as expected with Drush 6.3:

```
$aliases['example.com'] = array(
  'uri' => 'example.com',
  'root' => '/var/www/example.com/public_html',
  'command-specific' => array (
    'archive-dump' => array (
      'tar-options' => '--exclude=directory1 --exclude=sites/all/modules --exclude=*.txt',
    ),
  ),
);

```

I did notice that %files didn't work (Warning: `sprintf(): Too few arguments exec.inc:138`).

---
Tags: drush
---


# Question
Title: How to redirect user when new node save by ajax in advance form block drupal 7?
I have a website in drupal 7. I used advanced form block module to create add form block. Advanced form block module create block for form to edit and add new content. All node saved by ajax submission.

I want to redirect the user when new node save by this form. I used rules and form\[#redirect\] method in my hooks, but these are not working.

Can any one help me to figure out this?

Thanks

# Answer
> 1 votes
A form\[#redirect\] will not work in an AJAX form.

You can use an AJAX redirect command from CTools: ctools\_ajax\_command\_redirect

To do this, you should probably have to alter the form and use your own callback function returning the ajax command (along other needed data). I don't know advanced form block module so I can't say how difficult it is.

Example from http://dropbucket.org/node/1236:

```
  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  $commands[] = ctools_ajax_command_redirect($path);
  print ajax_render($commands);

```

---
Tags: 7, nodes, ajax
---


# Question
Title: How add/update a record conditionally based on existence of primary key?
I have a table with structure:

Table ( record\_1 int, record\_2 int, PRIMARY KEY (record\_1) );

I want to write/update a record based on its existence.

I was told to use drupal\_write\_record(), but for that I must know if the record already exists or not.

In my case I am not aware of its existence.

How can I do this?

# Answer
No, you do not *"must know if the record already exists or not"*. If you will look at `drupal_write_record` source code, you will see these lines:

```
 if (empty($primary_keys)) {
    // We are doing an insert.

```

On `else`, this function will update instead of insert. The only problem with this is that Drupal's record system expects you will leave key management to Drupal. No saving at arbitrary key, because it breaks autoincrement.

If you need to manage keys on your own, use lower level `db_merge` function instead.
> 3 votes

# Answer
You're looking for `db_merge()`

> Returns a new MergeQuery object for the active database.

Example from the docs:

```
db_merge('example')
  ->insertFields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->updateFields(array(
    'field1' => $alternate1,
  ))
  ->key(array('name' => $name))
  ->execute();

```
> 2 votes

---
Tags: 7, database
---


# Question
Title: How to add “Download file” link in Drupal 7 files attachment when chosen table formatter
By default Drupal 7 output attached files: **file name** and **size of attachment** I heed to add an additional column with Download link to every attached file.

In my **template.php** i have added:

```
// Override attachments files in case of use table formatter
function bkisk_file_formatter_table($variables) {
$header = array(t('Attachment'), t('Download'), t('Size')); // added Download column
$rows = array();
    foreach ($variables['items'] as $delta => $item) {
        $rows[] = array(
            theme('file_link', array('file' => (object) $item)),
            theme('file_link', array('file' => (object) $item)), // ???
            format_size($item['filesize']),
        );
    }
    return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
}

function bkisk_file_link($variables) {
    $file = $variables['file'];
    $icon_directory = $variables['icon_directory'];

    $url = file_create_url($file->uri);
    $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

    // Set options as per anchor format described at
    $options = array(
        'attributes' => array(
            'type' => $file->filemime . '; length=' . $file->filesize,
        ),
    );

    // Use the description as the link text if available.
    if (empty($file->description)) {
        $link_text = $file->filename;
    }
    else {
        $link_text = $file->description;
        $options['attributes']['title'] = 'откроется в новой вкладке';
        $options['attributes']['target'] = '_blank'; // add _blank param
    }
    return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}

```

**i have** https://i.stack.imgur.com/W76kW.png

**i need to do like this** https://i.stack.imgur.com/cmKMj.png

ill be very appreciated for your help!

# Answer
> 1 votes
partially solve task by adding to file\_link() function construction

```
function bkisk_file_link($variables) {
    $file = $variables['file'];
    $icon_directory = $variables['icon_directory'];

    $url = file_create_url($file->uri);
    $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

    // Set options as per anchor format described at
    $options = array(
        'attributes' => array(
            'type' => $file->filemime . '; length=' . $file->filesize,
        ),
    );

    // Use the description as the link text if available.
    if (empty($file->description)) {
        $link_text = $file->filename;
    }
    else {
        $link_text = $file->description;
        $options['attributes']['title'] = 'откроется в новой вкладке';
        $options['attributes']['target'] = '_blank'; // add _blank param

        $options_download['attributes']['title'] = 'Скачать ' . "[" . $link_text . "]";
        $options_download['attributes']['download'] = '';
    }
    return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span><br /><br />' .
           '<span class="file-download">' . l('Download', $url, $options_download) . '</span>';
}

```

# Answer
> 2 votes
use File Force Download module to add download functionality to your site. It has field formatter, views integration, good api and etc..

If you want to create a download link programmatically then you can generate download link such way:

```
l('Linktext', file_force_create_url($image['filepath']), array('query' => array('download' => '1'))).

```

---
Tags: files
---


title: Exposing Related Content filter

text:
# Question
Title: Exposing Related Content filter
I have a content type for publications that has a Related Content field for authors (which is another content type). I would like to create a view with exposed filters, where site visitors could browse or search publications by authors.

I created a page view that displays all publications and tried adding a filter \[Content: Related content (exposed)\]. It works, however I need to enter author's ID rather than name. Is there any way to make the search by related content title rather than ID?

Thank you in advance!

# Answer
The way to achieve that was adding a relationship for the referenced entity (authors in my case). As a result, all the fields from the referenced entity become available in the current content type.

After adding a relationship, I created and exposed filter for author's name and in the "Relationship" drop-down in the filter settings selected the newly created relationship.
> 0 votes

---
Tags: views
---


# Question
Title: Add multiple co-authors while creating node
I have a content type proposal. Now I would like to have multiple co-authors of the node. I want to give the author the opportunity to add users like this:

The users have to be entity references. I know there is a module Node access user reference but how can I have a collection of entity references that bundles the "co-authors". The module doesn't work with Field Collection module.

Has anyone encountered this and is there a module for this or a simple solution?

# Answer
> 2 votes
I suggest you look at these two modules

https://www.drupal.org/project/references https://www.drupal.org/project/entityreference

They're both quite similar.

They allow you to add user reference fields to your content type. On the field you created, set the number of values to be unlimited and then the author can select as many co authors as they want.

---
Tags: 7, nodes, entities, users
---


# Question
Title: How to I add specific meta tags to panels pages?
I have panels pages, and I need to set specific meta tags per page. The meta tags module lets you set up defaults, but I need specific tags per URL.

I can't seem to find this anywhere.

# Answer
> 4 votes
There is now the Meta tags: Panels module. Works fine for me.

> This module extends the Meta tags module by adding support for meta tags configuration for panels pages.

# Answer
> 2 votes
The sandbox Panels meta is the best option I have found so far. It supports context substitutions so you could get the meta tags from fields in your entities or add it manually per Panels page.

Unfortunately the project is still a sandbox but hopefully we can help Dustin make it a full project by testing it etc.

# Answer
> 1 votes
The Modul Metatag now comes with a submodul supporting customized meta tags for Panels.

---
Tags: 7, panels, meta-tags
---


# Question
Title: Automatic creation of Product Display for Drupal commerce?
Is there any way to automatically create a *Product Display* when I create a Product with the commerce module. The product display should references the product.

I'm thinking of using rules to accomplish this but not sure.

My client finds it complicated to create a product and then a product display.

Should I go with Ubercart module to accomplish this?

# Answer
> 6 votes
If your products and products display has a 1 to 1 relationship, you could use views to display your products instead. You also could do it with rules or custom code. Rules allow to create entities so it's all a matter of filling out data on the product display node with the product date.

The idea behind product displays is that you want to display multiple variants or related products. An example would be to display the variations in size, color, material etc and from the same node be able to select the product I want.

IMO you should go for Commerce and not ubercart. It's far more flexible and powerful. It's also better integrated with Drupal 7 features and the main modules in Drupal like, Views, entity, rules, and is doesn't have the history of legacy code that needs to be supported like Ubercart does.

# Answer
> 3 votes
There's also a commerce contrib module that creates products:

Commerce Bulk product Creation:

> The module also provides various ways to create display nodes for the newly-created products:
>
> * Redirect user to node creation form (with title and product reference filled in).
> * Silently create display node referencing all created products.
> * Silently create one display node for each created product. This will greatly speed up the task of adding numerous products at once.

I haven't tried it myself yet. But i just know it's out there.

# Answer
> 1 votes
Check inline\_entity\_form project on drupal, with that one you can create your product (variation too) inside the node product display.. i invite you to checkout the drupal 7 install profile commerce kickstart V2 for watching the way that drupal commerce is supposed to be used.

# Answer
> 0 votes
Also https://www.drupal.org/project/commerce\_product\_display\_manager module can be usefull for creating new *Product display* node while creating *Product variations*

> Features:
>
> ```
> A dedicated display manager page allowing you to drag products into or out of
> display nodes as desired.
> Manage references to a product directly on the product form (New: now supports
> multiple references).
>
> ```

---
Tags: commerce
---


# Question
Title: Drupal Commerce Kickstart cloud zoom image not working?
I am using Drupal commerce kickstart. I want to show the thumbnail images. I am using custom html theme in my project. How to show the thumbnail image in product page? Please anyone guide to me.I am new to Drupal commerce kickstart.

# Answer
I would suggest using the following modules (since it basically creates this straight out of the box). Once you customize it you can define how you want hte widgets to appear and essentially create the view as you have outlined above.
> 1 votes

---
Tags: 7, media, commerce
---


# Question
Title: Trying to display data from a module's table in views
I'm trying to show the purl.value value on a view's page.

It seems to be grabbing all of the data, however it isn't showing in the final results. Here's my code:

```
function mymodule_views_query_alter(&$view, &$query) {
  //watchdog("view information", print_r($view, true));
  if ($view->name == 'project_management') {

    $join = new views_join;
  $join->table ='purl';
  $join->left_table = 'node';
  $join->left_field = 'nid';
  $join->field = 'id';
  $join->type = "LEFT";
  $join->extra_type = 'AND';
  $join->adjusted = 'TRUE';

    $view->query->table_queue['purl'] = array(
    'table' => 'purl',
    'num' => 1,
    'alias' => 'purl',
    'join' => $join,
    'relationship' => 'node',
  );

    $view->query->tables['purl'] = array(
    'count' => 1,
    'alias' => 'purl'
  );

$view->query->add_field('purl', 'value');
  }
}

```

What exactly am I missing? Do I need a view handler? I was told that maybe using hook\_views\_data\_alter() might be better for my purposes.

How do I add a visible custom piece of data from that column on my view page?

# Answer
> 1 votes
you should map your data to views, so it will be available from views admin UI

check This tutorial where you will find the basics for describe custom data and tables to views.

---
Tags: views
---


# Question
Title: Schema.org itemprop="url" inside anchor object (link)
I'm trying to use the preprocess function to change the default outpot of links `<a href>` to include Schema.org's `itemprop="url"` **inside the anchor object**, as well as adding a `<span itemprop="title">` to the title of the link. For example:

```
<a href="www.example.com" itemprop="url"><span itemprop="title">Example Title</span></a>

```

\*Just to clarify: I want to do this for any link, not just menu or breadcrumb links.

I have managed to do something similar with images using the following code inside my template.php file, but had no luck with adapting it to links:

```
function THEME_preprocess_image(&$vars)
{
$vars["attributes"]["itemprop"] = "image";
}

```

Source can be found here.

I know that Microdata module might be able to handle that with a few modifications, however, I'd rather do everything manually instead.

I have spent hours searching for solutions but couldn't find any.. Any help would be greatly appreciated, thanks!

# Answer
> 0 votes
So after spending some more time on the matter, I finally found the solution and I am posting it here in case anyone is interested.

Simply put the following code in your template.php file, inside your theme folder:

```
function YOUR-THEME_link($variables) {
  return '<a itemprop="url" href="' . check_plain(url($variables['path'], $variables['options'])) . '"' . drupal_attributes($variables['options']['attributes']) . '><span itemprop="title">' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '</span></a>';
}

```

Hope that helps.. Remember to change 'YOUR-THEME' to your theme's name, and don't forget to clear the cache.

---
Tags: theming, entities, uri
---


# Question
Title: Menu Link not translating correctly on initial creation through node form
Using Entity Translation and Entity Translation Menu

On the node form, there is a section called "Menu Settings" then "Provide a menu link".

1) Create a new node, click "Provide a menu link" and put in your English menu item title. 2) Translate the node, click "Provide a menu link" and put in your French menu item title. 3) The menu item displays the french menu item title no matter which language you are viewing the site in.

The menu item's title that you created during the English version is overridden with the French menu item title. In fact, when you edit the menu item through the /admin/structure/menu interface, there is only one translation, the default. All we did was override the default translation with the french translation.

After a while I figured out how to get around this.

1) Create a new node, click "Provide a menu link" and put in your English Title. 2) Go to /admin/structure/menu/manage/main-menu, move your new menu item up or down, and click "Save Configuration". This properly sets the properties of the menu item. 3) Translate the node, click "Provide a menu link" and put in your French Title. 4) It works!

But obviously, we can't have our administrators jumping through the extra hoop. If someone can tell me if there is already a fix on this issue or if there is a hack I can do which re-saves the menu-item after it's created, please let me know

# Answer
I created a hook to set customized=1 which allowed the menu item to be translatable without editing it directly.

```
function epc_menu_insert_menu_link_insert($link){
    $link2 = menu_link_load($link['mlid']);
    $link2['customized'] = 1;
    menu_link_save($link2);
}

```
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Creating a list of node-options in different node
I am looking for a way to list nodes in a different node. Not sure how to explain this, so I will do it with an example.

Let's say I'm for example making a website for a Tennis tournament, this is not the real purpose, so if you have a different solution for this, it's probably not what I need, I want to achieve what I'll say in this example:

I have the following nodes:

* Player
* Match

In player I have:

* Player name
* Player age
* Player ranking
* etc...

In the node match, I have a few settings, including:

* Player 1
* Player 2

What I want to achieve is that in the node "match" I can choose 2 players from the node "player". In the list it shows the player name, however, I should be able to get the extra information as well when rendering the match node.

Any ideas if a certain module excists that could help me out?

Thank you very much!

---

**Edit 22/07/2014:**

As an addition, I would also like a different list to inherit his items depending on a previous selected item.

So for example I have 3 nodes:

* Car
* Brand
* Model

The first thing that I would do is: I make different brands as "Brand" nodes content:

* BMW
* Mercedes
* Volvo
* ...

Afterwards I make a Model. In model I make the models \- 'Z4' =\> And in the list I choose "Brand: BMW" \- 'S60' =\> And in the list I choose "Brand: Volvo" \- 'V70' =\> And in the list I choose "Brand: Volvo" \- ...

Now I want my third node "car" to be for example for a seller of cars. So the seller sells a car. He makes a car node and enters the following information:

* Buyer: Person A
* Address: Address X
* Age: 99
* Licenseplate: 1 XXX 999
* Brand: ....
* Model: ....

So what I'm trying to achieve is that the seller has a list of all brands. If he chooses brand "Volvo" for example, then the Model list should appear and show all models for the chosen brand.

# Answer
> 0 votes
I think what you're wanting can be accomplished with views. You may need to add some fields to make the context work for your needs.

---
Tags: entities, nodes
---


# Question
Title: Is there a "hook_user_login_failed" hook? Or something similar?
I'm needing to detect when a login failure happens in Drupal and am finding it to be exceedingly difficult even after searching Google. I have to believe this exists somewhere.

I found this post back from 2007 which seems like an entirely reasonable request for a "failed login" hook: https://www.drupal.org/node/160469 Is there something that allows this?

Thanks in advance.

AG3

# Answer
> 1 votes
At least in Drupal 7, there is no hook for that. The login form uses validators, one which authenticates, and another that follows and sets a form error if login failed.

One option would be to add a custom validator to the form using hook\_form\_FORM\_ID\_alter, and check the status of login there. See user\_login\_final\_validate in user.module for an example of how status is checked.

---
Tags: hooks, users
---


# Question
Title: Fuzzy Search in Drupal 7 gives no results
I have setup Fuzzy Search in our website to provide 'intelligent' search functionality. I believe that the setup is all proper but despite the fact, I always get back 0 results. This is my search page for Fuzzy Search:

http://indiansnakes.org/search-fuzzy

I have exposed "Fulltext search" and I have indexed few key fields of the snake nodes from the website which has to be searched upon (like Common name, scientific name, snake description etc.)

I have setup Search Server for Fuzzy search as shown below:

Minimum word length = 3.

I would also like to know if there is a way to provide a dedicated database for Search server and it's indexed data?

Next, I have setup Fuzzy Search index which shows that the items have been indexed and it looks like this:

I have setup the Views for Fuzzy Search page like this:

Despite all this, my Fuzzy Search does not give back any results. Any idea what might be going wrong here?

# Answer
In the Fuzzy Search index, make sure the Fuzzy Search processors are enabled, and that they are processed last. The Fuzzy Search except processor should be last, with the settings processor immediately before it. You may need to enable the Tokenizer processor as well, and that should be before the Fuzzy processors.

Reindex after saving the changes.
> 3 votes

# Answer
If you've some issues and you don't see your created indexes at /admin/structure/views/add then try to clear you cache. Standard core one and Views cache at /admin/structure/views/settings/advanced

Note that only fields of type Fulltext can be used in fulltext searches. So when you want to find individual words contained in this field, not just the whole field value, use this type. Other types can be used, e.g., for filtering and sorting.

also, you have some javascript errors you may want to look into:

```
GET http://localhost:8080/socket.io/socket.io.js net::ERR_CONNECTION_REFUSED
search-fuzzy:51

Uncaught SyntaxError: Unexpected identifier
search-fuzzy?search_api_views_fulltext=boa:formatted:293

```
> 2 votes

---
Tags: 7, views, search
---


title: Delete multiple revisions at one time

text:
# Question
Title: Delete multiple revisions at one time
Most articles of my site contain huge revisions. It is very tedious and annoying to delete huge revisions one by one following the url ,say, www.example.com/node/9022/revisions. I want to implement an interface in Admin panel to delete multiple revisions at one time. But dont know how to implement this concept. Plz help

# Answer
I found the most relevant module node\_revision\_bulk\_delete for the implementing my task and its working fine.
> 0 votes

# Answer
Use the Node Revision Delete module to delete and manage your revisions.

> The Node Revision Delete module lets you to track and prune old revisions of content types.
> 0 votes

---
Tags: 7
---


# Question
Title: About shaping the Drupal "add content" pages
My question is that do you change the Drupal "add content" pages appearance and fields for your final version of project?

Actually, I really do not know how it is conventionally provided for Drupal customers. If you customize those pages, how do you do it?

Thanks

# Answer
> 2 votes
I like to work with Panels to customize the Add content pages. I'll write down a small step by step tutorial to give you a starting point and maybe a better understanding how to module works if you are not familiar with it.

Once you have Panels installed you navigate to » Administration » Structure » Pages in the menu. Then enable the *Node add/edit form* variant.

When the variant is enabled click *Edit* and then *Add a new variant*. Click Create variant, choose layout and click continue on the next step click continue.

Now add the form elements you want in the respective regions by clicking the cog wheel in the top left corner of the region.

Under the category Form you will find all form elements.

In the example below I've added the title and body field to the left and the menu settings and the submit button to the right.

Under selection rules in your panel you can say that this variant is valid for the content type "Page" for example and have another layout/setup for other content types. If you don't add a selection rule the variant will take over the content creation page for all content types.

You can add new Panel layouts to a module/theme if the standard provided doesn't work out for you.

**A gotcha** One small gotcha I've experienced is that if a field is not placed in the panel, let's say an image field. And you re-save existing content it will remove the image from the node. When the node is saved the submit function interprets the value as empty. To avoid this add the pane *General form* to one of your regions and click the cog wheel for the pane and css properties. Under css class enter element-invisible. This way all form elements are present but hidden by css to avoid the missing image situation :)

---
Tags: nodes
---


# Question
Title: pass array from module to render in template
I have a module name mysite.module in that module I have function named mysite\_preprocess\_panels\_pane. That has an array and I would like to render this array inn panel.tpl.php. My code does not work. Any suggestion please, Thanks.

```
function mysite_preprocess_panels_pane(&$variables) {
 $ar = array('arg1'=> 'car', 'arg2'=> 'truck');
}

<div class="pane-content">
<div class="panel-panel panel-col-first"> <?php print  $ar['arg1']></div>
</div>

```

# Answer
> 1 votes
Place the array into the variables. like.

```
function mysite_preprocess_panels_pane(&$variables) {
 $variables['ar'] = array('arg1'=> 'car', 'arg2'=> 'truck');
}

```

# Answer
> 0 votes
You can do it with the following code.

```
function mysite_theme() {
  return array(
    'panel' => array(
      'render element'=>'element',
      'template'=>'panel',
      'variables'=>array( 'dataar'=>NULL ),
    ));
}

function mysite_preprocess_panels_pane(&$variables) {
 $ar = array('arg1'=> 'car', 'arg2'=> 'truck');
 return theme('panel',array("dataar"=>$ar));
}

// The array will be accessed in the panel.tpl.php with $dataar variable

```

Please clear cache to reflect the changes from **admin/config/development** path

Hope it will work for you!

---
Tags: 7, theming
---


title: Schema relationship

text:
# Question
Title: Schema relationship
The problems I am trying to solve are:

1- How can I connect tables defined by $schema to each other?

2- How do you insert data consistently into the database? Is there any possibility of having Transaction facilities in Drupal? (I know how to do it in mySQL, but I'm looking for something built-in for Drupal Core.)

Thank you so much

# Answer
> How can I connect tables defined by $schema to each other?

I'm not sure what you mean by that, but possibly you're asking how to describe relationships between tables to the Schema API? Drupal has no support for that currently; there is a `foreign keys` property available, but:

> Foreign key definitions were added in Drupal 7 for documentation purposes only, and do not modify the database.

---

> How do you insert data consistently into the database? Is there any possibility of having Transaction facilities in Drupal?

Yes, Drupal supports transactions. The API method to use is `db_transaction()`:

```
$transaction = db_transaction();

try {
  db_update('foo')...;
}
catch (Exception $e) {
  $transaction->rollback();
  // Recover
}

```
> 0 votes

---
Tags: database
---


# Question
Title: Why does the download page recommend the previous version?
Why does Drupal download page recommend Drupal 7.x? I can hardly see the footprint about Drupal 8.

Does it mean Drupal 8 is still under development? Does it mean Drupal 7.x can be the last stable version?

# Answer
Yes, Drupal is under development. See http://drupal.org/core/release-cycle

API freeze was in July, now API completion phase.
> 1 votes

---
Tags: 8
---


# Question
Title: How to disable links for anonymous users for SOME, but not all link items?
The link issue here is video links, which are for brightcove.com hosted videos. Now some important background:

* The site is a directory of company-produced videos. It requires login in order to view anything.
* However the user can assemble a list of videos (like a cart or wish list) and send a URL for that list to a non-authorized person; that person can view the video links and read text info about the video, but can't access other parts of the site.
* But some of the videos are designated as "not shareable." So even though it's OK to share links to most of the video pages and for anonymous users to play the video link, we need to exclude the "non-shareable" videos from being playable.
* The link field is only one of the fields in a node of this content type. The node itself must remain accessible to the anonymous user; it is only the video link that needs to be *variably* accessible or not accessible to anonymous.

Can anyone suggest a strategy for making some but not all video links not accessible to the anonymous user?

# Answer
I would create a view of the videos and control access by role. if you need control at the field level, I'm sure there is a module for that or you can use a field template.
> 0 votes

# Answer
Look at People-\>permissions,It works by restricting access to content types based on roles.

Media is a form of content type and I guess you should be able to restrict anonymous or non registered users from viewing it but then this will also restrict viewing of images or another file uploaded as media.

If this is too restrictive you may want to create your own custom content type a panel or a page that your links link into and restrict that.
> 0 votes

---
Tags: navigation, users
---


# Question
Title: Image style scale and crop not formatting right
I had a scale and crop image style created, but I had to move it to code. So, to re-create it, my code is:

```
function mymodule_image_default_styles() {
    $styles = array();

    $styles['mymodule_thumb'] = array(
        'label' => 'MyModule Thumbnail',
        'effects' => array(
            array(
                'name' => 'image_scale_and_crop',
                'data' => array(
                    'width' => 210,
                    'height' => 210

                ),
            )
        ),
        'name' => 'mymodule_thumb',
        'storage' => IMAGE_STORAGE_NORMAL

    );

    return $styles;
}

```

It's scaling to the 210px width, but it doesn't seem to be cropping right.

Am I missing something? Before this, I tried separate scale and crop effects, but got the same result.

EDIT: If it matters, I'm calling image\_style\_url() and passing the style.

# Answer
I suspect the `hook_image_defaults_styles` API page might be a bit out of date?

The features exported hook\_image\_default\_styles code is slightly different on my drupal. Maybe this will help:

```
function hook_image_default_styles() {
  $styles = array();

  // Exported image style: learning_sessions_image.
  $styles['learning_sessions_image'] = array(
    'name' => 'learning_sessions_image',
    'effects' => array(
      7 => array(
        'label' => 'Scale and crop',
        'help' => 'Scale and crop will maintain the aspect-ratio of the original image, then crop the larger dimension. This is most useful for creating perfectly square thumbnails without stretching the image.',
        'effect callback' => 'image_scale_and_crop_effect',
        'dimensions callback' => 'image_resize_dimensions',
        'form callback' => 'image_resize_form',
        'summary theme' => 'image_resize_summary',
        'module' => 'image',
        'name' => 'image_scale_and_crop',
        'data' => array(
          'width' => 963,
          'height' => 270,
        ),
        'weight' => 1,
      ),
    ),
    'label' => 'learning_sessions_image',
  );
  return $styles;
}

```

What you're missing is the `effect callback` and `dimensions callback` which are the essential parts afaik. I'm not sure about the significance of the array index under `effects`, or the `form callback` and `summary theme`. Hope this helps.
> 1 votes

# Answer
In addition to this code. Try using this

```
function mymodule_image_default_styles() {
  $styles = array();

  $styles['mymodule_thumb'] = array(
    'label' => 'MyModule Thumbnail',
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array(
          'width' => 200,
          'upscale' => 1,
          'height' => 200,
        ),
        'weight' => 0,
      ),
      array(
        'name' => 'image_crop',
        'data' => array(
          'width' => 210,
          'height' => 210
        ),
      )
    ),
    'name' => 'mymodule_thumb',
    'storage' => IMAGE_STORAGE_NORMAL
  );
  return $styles;
}

```

Hope it works!
> 1 votes

# Answer
```
function mymodule_image_default_styles() {
  $styles = array();
  $styles['mymodule_thumb'] = array(
    'label' => 'MyModule Thumbnail',
    'effects' => array(
      array(
        'name' => 'image_scale_and_crop',
        'data' => array(
          'width' => 210,
          'height' => 210,
          'upscale' => 1,
        ),
        'weight' => 0,
      )
    ),
    'name' => 'mymodule_thumb',
    'storage' => IMAGE_STORAGE_NORMAL
  );

  return $styles;
}

```

Clear your cache.
> 1 votes

---
Tags: 7, media
---


# Question
Title: How do I filter only the root terms in a vocabulary in a view?
I have have a vocabulary structured as so:

* Root Alpha
    + Term Alpha 1
    + Term Alpha 2
        - Subterm Alpha 1
* Root Beta
* Root Gamma
    + Term Gamma 1
    + Term Gamma 2

How do I filter the view to show only the root terms of the vocabulary? Currently my view is displaying the root terms as well as the children (Term * \*)

Going forward from that I would like to pass the argument 'Root Alpha' (or its tid, or whatever from a context) and then have it filter to only 'Root Alpha's direct children. (Term Alpha \*). Filtering to a depth any further than that would be a bonus.

I can get it to work if I put all my terms in one root term so that the vocab becomes:

* True Root
    + Root Alpha
        - Term Alpha 1
        - Term Alpha 2
            * Subterm Alpha 1
    + Root Beta
    + Root Gamma
        - Term Gamma 1
        - Term Gamma 2

I'm not sure which vocab structure is more correct, writing this made me realise I have some reading to do apart from figuring this out with views.

# Answer
> 14 votes
For displaying only the root terms, I have a solution which surely will make someone facepalm (at least I did that):

1. Add a contextual filter to your taxonomy view
2. Select *Taxonomy term: parent term*.

Set it up like this: *When a filter value is not available*: *Provide default value* \- *Fixed value*. Set the value to **0**.

Yeah, that's all. Terms without parent have 0 here. See the description of the parent field of the taxonomy\_term\_hierarchy table:

> Primary Key: The {taxonomy\_term\_data}.tid of the term's parent. 0 indicates no parent.

# Answer
> 2 votes
if you have a static taxonomy structure, you can filter using `filter criterion: Content: Has taxonomy terms (with depth)` then in this place you can select just the root terms to filter:

I hope information be useful.

# Answer
> 1 votes
You can also do it with a simple filter, and a non-static taxonomy structure :

1. Add a filter criterion : Taxonomy term : parent id
2. Select operator "Is equal to" and fill the value with "NULL"

It will display only the root terms of your taxonomy, and will still work if you change the taxonomy structure later...

# Answer
> 0 votes
You can select it with `WHERE parent = 0` using `db_query()` in your page.

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


title: Layout detail node + ckeditor layout

text:
# Question
Title: Layout detail node + ckeditor layout
When I create a node of content type Proposal like this:

I can add images, paragraphs, ... . But it looks like this on the detail page of the node:

No image, no paragraphs, ... . What could be the problem of this?

I'm using the Filtered html text format. When I check the html of the paragraph there is no image, nothing. Just text ... .

These are my settings of context filter filtered html:

# Answer
> 1 votes
Have a look at *Limit allowed HTML tags* in the setting for your text filter. Make sure img is among the allowed HTML tags.

The settings are found under *admin/config/content/formats*.

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


# Question
Title: How to set the profile picture validation in profile 2 module in drupal 7?
I am using profile2 module in my site. I want to hide the profile picture upload option at the time of registration. And after click on confirmation mail, i want to upload at least one profile picture means want to apply validation here. How to set the validation in profile picture that validation shows inside not at the time of registration. Please help. Thanks in Advance

# Answer
Just create the template of your registration page and need not print the upload image field over there and when user will register your self print that field to the edit profile form page from where user can upload the picture ..

Thanks
> 1 votes

---
Tags: users, media
---


# Question
Title: How to auto generate barcodes for Entity Registration in Drupal 7
I read this article about using rules and a trigger to populate/create a barcode field from a serial field, tried toy follow it but the screens/ facilities of Drupal 6 seem different for v 7 and the documented steps cannot be replicated. In particular I expected barcodes to be part of the drop down for fields but it isn't

"basically you should add a new rule that fills for you the barcode when new content is created starting from the serial field. The steps are:

create a new rule trigger it on the event: 'after new content is saved' set some condition on the type of the content (optional) **use 'populate a field' (under CCK category) as action choose your barcode CCK field** Use the token of your serial field : \[node:field\_YOUR\_TOC\_SERIAL\_FIELD-id\] -- I don't remember why I didn't use the token but the follow php code:

array('barcode' =\> \[node:field\_MY\_FIELD\_NAME-id\])); ?\> If you didn't use Rules before have a look here: http://dev.nodeone.se/node/646 "

# Answer
> 0 votes
Its complicated but I essentially ended up using the available barcode online generators (Google has an online QR Code generator) and then embedding the URL in HTML mail that I was sending out.

# Answer
> 0 votes
Have you seen the Barcode Module?

> The Barcode module provides a text field to generate barcode images.

---
Tags: rules, entities, users
---


# Question
Title: Webform - how do I change dateformat in mail
Module: Webform

The short date type is dd/mm/yy, so it appears correctly in the form (day/month/year) But in the mail it is shown with month first. (month/day/year)

How can I change the date type in the mail?

# Answer
Try go to admin/config/regional/date-time and set your site's Medium date type format.

Also, if the Medium format doesn't include at least a month, day, and year field, Webform will default to the American format of MM/DD/YYYY.

Webform uses the "medium" in e-mails and viewing submissions, though everywhere else (like a displaying the date component) it uses short for the order
> 1 votes

---
Tags: webforms, datetime
---


# Question
Title: How to theme a Quiz in Drupal 7? - part 2
Trying to customize the look and feel of my quizzes in D7 - and getting overwhelmed. I have the Skeleton base theme installed.

Calling this Part 2 because - this is an extension of How to theme a quiz in D7?.

Help sought: Which CSS files specifically to target to change the Quiz Take page?

I have added the **quiz-single-question-node.tpl.php** file - and rendered the **$question\_node-\>content\['body'\]**. And now the quiz works fine... (but without my desired changes yet).

My problem is that the **'body'** from above is a fully formed HTML Form of the quiz question. SO, where exactly should I look to: a. change this body to perhaps add a CSS class? b. where should I add the CSS class itself?

Would really appreciate some detailed hand-holding.

Thanks in advance.

# Answer
> 0 votes
\sites\all\modules\quiz\Quiz.css --\> this is the place to change.

CSS class definition to be created for: "quiz-question-body" - this is for the question itself.

---
Tags: theming, quiz
---


# Question
Title: How do I get 2 separate displays of a view in one page that are displaying contents from two different content types?
For example, I have a Page view which displays Content Type A Title, Post date and categories. This page will lists out all of the matching contents that this user has published.

Then I created a Block view that displays contents from Content Type B with Title and categories. The similarity between content type A and B is the categories. I want to display the contents of the block under each result in the Page that matches each category chosen for that node.

How would you display this in the view? I have heard of Views Attach or Entity Views Attachment . But the first one is only for D6 while second will probably not work since I'm not using entities ... or am I?

Or can this be done using Panels? How to do this dynamically with the Block view auto populating the Page view with the right amount of results?

I want to be able to display multiple views results for multiple taxonomies in one page. The content types do not have references for each other. But they do share the same taxonomy vocabulary and its terms.

Edit: This is how I want to display the entire page

```
Page Results Name

Page Result 1: Title    Date Posted     Categories
    Block Result 1 Title     Matching Categories

Page Result 2: Title    Date Posted     Categories
    Block Result 2 Title     Matching Categories

Page Result 3: Title    Date Posted     Categories
    Block Result 3 Title     Matching Categories

...

```

The Page is populated by Content Type A The Block is populated by Content Type B

Want Each Block to have 10+ results that matches categories on Content Type A

It's not just placing Block view underneath the Page view. They're embedded together.

Right now, I have the 2 views displaying the correct results separately. But having trouble integrating them together.

Oh and the results for Content Type A should only display contents that the logged in user published. But the Content Type B can be from any author as long as it matches the Categories.

# Answer
You can use a combination of Taxonomy, Views & Panels.

1. Add the same taxonomy vocabularies to both the Content types A & B
2. Create a view for Content type A with Contextual filter for Term-ID
3. Repeat the same for Content type B
4. Override the Panels page for Taxonomy & create the variant for your vocabulary
5. Add the above 2 views on the created Panels variant & also pass the argument term id to the view.

Well, you will have to dig into the Panels to get your requirement implemented.
> 1 votes

# Answer
If You are not comfortable with Panels, then

1. Create one of the required views, a view page (for Content-type A) with proper contextual filters.
2. Create the other view (Content-type B) as an attachment (attachment Views).
    * Select INHERIT contextual filters while creating it.
    * Basically, both the views should have the same contextual filters.
3. Attach it to the first view created for Content-type A.

This might be an alternate solution.

For overriding the default taxonomy term paths check this tutorial - Overriding the default taxonomy page with a view in Drupal 7

* Hope you are able to manipulate the contextual filters properly in the views.
> 2 votes

# Answer
assuming you have the contextual filter set correctly and both views show the correct data, you can do this without using any additional modules - include the block view as a footer to the first view - or under admin/structure/blocks you can assign the block view to only appear in the content area on the page address for the first view.
> 0 votes

---
Tags: taxonomy-terms, nodes, panels, views
---


title: Backlinks from UUID hrefs

text:
# Question
Title: Backlinks from UUID hrefs
The goal is to hack core so that the search module will populate the `search_node_links` table from uuid-link hrefs in node content.

Planned approach is to modify the parsing functions of `search_index` in the core `search.module`.

The targeted section of code is lines 633-643 of `search.module`.

```
if (preg_match($node_regexp, $value, $match)) {
  $path = drupal_get_normal_path($match[1]);
  if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
    $linknid = $match[1];
    if ($linknid > 0) {
      $node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();
      $link = TRUE;
      $linktitle = $node->title;
    }
  }
}

```

The plan is to use `entity_uuid_load` to grab the `nid` directly like so:

```
if (preg_match($uuid_regexp, $value, $match)) {
  $entity = entity_uuid_load('node',$match);
  $linknid = key($entity);
  if ($linknid > 0) {
    $node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();
    $link = TRUE;
    $linktitle = $node->title;
  }
}

```

I've used this code to pull a node title with `$value` set to an HTML snippet containing a UUID-href link; however, this still seems to fail to populate the `search_node_links` table.

`$uuid_regexp` is working as expected, but here it is for reference along with `$node_regexp` for comparison.

```
$node_regexp = '@href=[\'"]?(?:' . preg_quote($base_url, '@') . '/|' . preg_quote(base_path(), '@') . ')(?:\?q=)?/?((?![a-z]+:)[^\'">]+)[\'">]@i';
$uuid_regexp = '@href=[\'"]?(?:\[uuid-link:node:)([0-9a-f]{8}-(([0-9a-f]{4}-){3})[0-9a-f]{12})(?:\])(?:[\'">])@i';

```

And here is the UUID link format:

```
<a href="[uuid-link:node:dc2c18f0-0abb-43b9-899c-f7c0a16934fd]">UUID link</a>

```

I'm sure there's something I'm just not seeing in `search.module` that is preventing this from working as desired. Any comments/support/pointers would be greatly appreciated.

UPDATE: Finding now that it's not UUIDs causing the issue, but aliased paths instead (probably combined with Global Redirect module). Tried the following code instead, still no change in `search_node_links`.

```
if (preg_match($node_regexp, $value, $match)) {
  $clean_url = preg_split('![(en)|(fr)]/!', $match[1])[1];
  $path = drupal_lookup_path("source", $clean_url);
  if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
    $linknid = $match[1];
    if ($linknid > 0) {
      $node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();
      $link = TRUE;
      $linktitle = $node->title;
    }
  }
}

```

Again, this code is able to pull a node title but is not contributing to `search_node_links`.

# Answer
Ok, so this problem was being caused by the language prefix in our paths in conjunction with aliases. `drupal_get_normal_path` was returning aliases instead of node numbers, and it returned nothing when the path had a language prefix. Also found that the substitute function `drupal_lookup_path` only works for aliased paths. The final code replaces line 634 of `search.module`:

```
$path = drupal_get_normal_path($match[1]);

```

becomes

```
$clean_url = preg_split('!(^[a-z]{2})/!i', $match[1])[1];
if ($non_aliased = drupal_lookup_path("source", $clean_url)) {
  $path = $non_aliased;
} else {
  $path = drupal_get_normal_path($match[1]);
}

```

The `search_node_links` table is now being populated properly and the "What links here"/Backlinks views are working correctly.
> 1 votes

# Answer
yea sorry umm the Search API module can't help you to index and search your own content?

```
/**
 * Define new types of items that can be searched.
 *
 * This hook allows modules to define their own item types, for which indexes
 * can then be created. (Note that the Search API natively provides support for
 * all entity types that specify property information, so they should not be
 * added here. You should therefore also not use an existing entity type as the
 * identifier of a new item type.)
 *
 * The main part of defining a new item type is implementing its data source
 * controller class, which is responsible for loading items, providing metadata
 * and tracking existing items. The module defining a certain item type is also
 * responsible for observing creations, updates and deletions of items of that
 * type and notifying the Search API of them by calling
 * search_api_track_item_insert(), search_api_track_item_change() and
 * search_api_track_item_delete(), as appropriate.
 * The only other restriction for item types is that they have to have a single
 * item ID field, with a scalar value. This is, e.g., used to track indexed
 * items.
 *
 * Note, however, that you can also define item types where some of these
 * conditions are not met, as long as you are aware that some functionality of
 * the Search API and related modules might then not be available for that type.
 *
 * @return array
 *   An associative array keyed by item type identifier, and containing type
 *   information arrays with at least the following keys:
 *   - name: A human-readable name for the type.
 *   - datasource controller: A class implementing the
 *     SearchApiDataSourceControllerInterface interface which will be used as
 *     the data source controller for this type.
 *   - entity_type: (optional) If the type represents entities, the entity type.
 *     This is used by SearchApiAbstractDataSourceController for determining the
 *     entity type of items. Other datasource controllers might ignore this.
 *   Other, datasource-specific settings might also be placed here. These should
 *   be specified with the data source controller in question.
 *
 * @see hook_search_api_item_type_info_alter()
 */
function hook_search_api_item_type_info() { /* ... */ }

```
> 0 votes

---
Tags: 7, search, i18n-l10n, path-aliases, entities
---


title: How do I configure the mock server?

text:
# Question
Title: How do I configure the mock server?
According to the documentation, the test module included with the LDAP module should contain the mock LDAP server.

Where can I find it after enabling this module? How should I configure it so that I can start testing logging in with a LDAP server?

# Answer
The "Mock LDAP" server that is being used for the LDAP Test module is, in fact, a mock server object. It allows the tests to run, and doesn't exist outside the scope of the simpletests.

If you're looking to provide a way to "mock" an LDAP instance on your development site, it can't provide that functionality.

If you're trying to write your own simpletests for LDAP integration, check out the Examples for Developers project. The included module, `simpletest_example`, has excellent documentation for writing simple tests.
> 2 votes

---
Tags: testing, authentication-authorization
---


title: taxonomy_get_tree return only few terms

text:
# Question
Title: taxonomy_get_tree return only few terms
i have a problem with `taxonomy_get_tree()`.

I want to get all tags from taxonomy. Tags's vocabulary ID (vid) is 1. When I check this in database there are about 4000 terms. If I use `taxonomy_get_tree(1)` it returns only 150 terms.

Do anybody know what I'm doing wrong?

Thanks for every advice.

# Answer
This problem was caused by wrong migration from drupal 6 site to drupal 7. Some connection were missing.
> -1 votes

# Answer
Try this on your code: `taxonomy_get_tree(1,0,NULL,TRUE)`

Syntax:

```
taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE)

```

> Parameters
>
> **$vid:** Which vocabulary to generate the tree for.
>
> **$parent:** The term ID under which to generate the tree. If 0, generate the tree for the entire vocabulary.
>
> **$max\_depth:** The number of levels of the tree to return. Leave NULL to return all levels.
>
> **$load\_entities:** If TRUE, a full entity load will occur on the term objects. Otherwise they are partial objects queried directly from the {taxonomy\_term\_data} table to save execution time and memory consumption when listing large numbers of terms. Defaults to FALSE.
> 0 votes

---
Tags: taxonomy-terms
---


title: Shared database during development?

text:
# Question
Title: Shared database during development?
Sometimes I need to collaborate with a more frontend-centric developer to help implement a site. So typically they're only changing CSS and minor template changes.

The way we've handled this in the past is that I work locally. When I have everything in a good state, I clone my environment to a staging server. The frontend dev then uploads his changes via sftp.

We'd like to move toward a setup where we're both working locally. The problem of course is keeping the configuration changes all in sync. I have been using Features, but there is still a lot of global configuration that would need to be manually migrated between instances.

I'm not quite ready to make the jump to each of us having a local database. I have considered taking a "half step" by having a shared database that we both connect to over the network.

I've found a few blog posts here and there where people have suggested it, but I thought I'd ask here: have you tried this, and if not, is there's any reason this is a bad idea?

# Answer
We've been through the same scenario as you in our company, and currently we've ended up with a situation where we work on a remote development server and have our code locally via sshfs mounts. It works pretty well, you can read more about it in this blog post I wrote.

You can't use graphical clients (e.g. gitx or gitl) so we use git and drush on the commandline, but that actually made people more aware of how those tools works rather than just clicking the same buttons every time.

On a different note, you should also use memcached so your cache doesn't get shared via cache tables in the shared database. It's pretty simple to setup and after that just make sure every developer has a unique memcache prefix.
> 0 votes

---
Tags: 7, database
---


title: Taxonomy Tags Comments

text:
# Question
Title: Taxonomy Tags Comments
I am having a problem removing the comments link from a page. I am using Taxonomy and Tags, I added a term to Tags and gave it a URL alias such as tags/sandy\_repair. I created a new basic page and added that term to the page. When you display the page it lists that tag at the bottom. When you click on the tag link it takes you to the alias you created that would display the teasers of all the

pages with the same tags. So the tag links to tags/sandy\_repair On this page there is a comment icon and a link to 0 comments () I would like to remove that icon and comments link entirely. The structure of the Basic page is not set to display comments, manage display does not even show comments and the

Comment Display tab has the comment field hidden. The only thing I can figure is that this comment display is not coming from the basic page settings.

# Answer
> 0 votes
What theme do you use? Have your tried unsetting the comment links in your node template using something along `unset($content['links']['comment']['#links']['comment-add']);`?

---
Tags: taxonomy-terms, comments
---


title: Write form value to database

text:
# Question
Title: Write form value to database
I need to save this to database, but could not find a way to make it work. Now this paypal\_email is only saved to current user. Apparently it is saved somehow to the database under user table, but it can not be read there? Or use views to read it.

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

  $enabled_methods = variable_get('commerce_funds_withdrawal_methods', array());

  if (!$enabled_methods['paypal'])
    return FALSE;

  global $user;

  $form['paypal_email'] = array(
      '#type' => 'textfield',
      '#title' => t('Paypal Email'),
      '#description' => t('Withdrawals using Paypal will be sent to this email'),
      '#default_value' => $user->data && array_key_exists('paypal', $user->data) ? $user->data['paypal']['paypal_email'] : '',
      '#size' => 40,
      '#maxlength' => 64,
      '#required' => TRUE,
  );

  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
  );

  return $form;
}

function commerce_funds_manage_withdrawal_method_paypal_submit($form, &$form_state) {

  global $user;

  user_save($user, array('data' => array('paypal' => $form_state['values'])));
}

```

# Answer
> 3 votes
I don't think the $user-\>data value can be read by views. You are probably better off creating a field to store the email value.

---
Tags: 7
---


# Question
Title: Is it possible to use another menu as a submenu of a menu?
Is there a setting or a module, this would facilitate re-use of menus...

For example:

```
Menu 1
  option A
  option B
  option C
  option D

Menu 2
  option 1
  option 2
  option 3
  option 4

Full Main Menu
  option A (use menu 2 for sub menu options)
    option 1
    option 2
    option 3
    option 4
  option B
  option C
  option D

```

# Answer
> 1 votes
Answering my own question, the closest existing solution appears to be Advanced Menu:

From the Advanced Menu module project page:

> **Sub-Menus with Menu Merge (7.x-1.3+)**
>
> Menus can now be merged into other menus. This allows users with the appropriate permission to add links to other menus which are then displayed as if there were a single menu.

# Answer
> 1 votes
There are not settings I am aware. I have not done an exahaustive search for a module. However, you could write your own implementation with a custom module implementing hook\_menu(). Simply put, you would create a new menu. Then, you would iterate through the other menu's in your implementation adding each element to the new menu.

---
Tags: 7, routes
---


# Question
Title: Passing PHP variables to JS file initiated from theme .info file
I know it's perfectly possible to pass PHP variables to JS but what if the JS file is initiated from the theme.info file? Can you access it in template.php or? Please some advice..

Thanks!

# Answer
> 2 votes
You don't access the Javascript file in PHP, rather, you tell Drupal to send values to Javascript variables and then access those from your Javascript files. You would use drupal\_add\_js.

For example, in template.php add:

```
drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

```

Then in your Javascript file, you can access that variable as:

```
Drupal.settings.myModule.key

```

---
Tags: javascript, .info
---


title: Month Displaying Earlier Than Expected

text:
# Question
Title: Month Displaying Earlier Than Expected
I have the following code to print last month once a new month starts.

$prevmonth = date('F Y', strtotime("last month")); print $prevmonth;

The problem I encountered recently was that last month was printed before this month (August) begins. E.g. July was showing although it was still July 31.

Any help on this issue is greatly appreciated.

# Answer
What about the timezone settings ? This could be a lead. http://php.net/manual/en/function.strtotime.php
> 0 votes

# Answer
Your time zone settings may not be set correctly so I would check that. If those are correct I would suggest a better way then to rely on strtotime:

```
$date1 = new DateTime();
$month_ago = new DateInterval( "P1M" );
$month_ago->invert = 1; //Make it negative.
$date1->add( $month_ago );

$prevmonth = date('F Y', $date1);

```
> 0 votes

# Answer
Thank you, chadpeppers. I tried your code but it didn't do anything for me. My co-worker was able to help. The following code fix the problem:

```
$prevmonth = date('F Y', strtotime("first day of last month"));
print $prevmonth;

```
> 0 votes

---
Tags: views
---


# Question
Title: How to use the Leaflet 'maxBounds' option?
I'd like to restrict the panning of my leaflet map in Drupal.

The Leaflet documentation mentions the maxBounds option

And I'd like to know the best way to implement it for my map.

# Answer
> 3 votes
Got it working. Override the leaflet.drupal.js file as follows. See the leaflet markercluster module for how to override in an 'As You Like it kind of way.' in a custom module. Pretty useful.

```
// instantiate our new map
  var lMap = new L.Map(this.mapId, settings);
//note, the comma (NOT A semi-colon) at the end of the next line - this is  important.
  lMap.bounds = [],
// Now set your maxbounds, see the leaflet documentation for reference.
    lMap.setMaxBounds([
      [40.712, -74.227],
      [40.774, -74.125]
    ]);

```

---
Tags: javascript
---


# Question
Title: Make email validation message in drupal 7 webform come out in spanish
I have a webform in spanish and I have manually put in all of the validation error messages in spanish, however I cannot find where I can make the "Please enter an email address" message which comes out if you put an invalid email into an email type field come out in spanish instead.

Thank you

# Answer
> 1 votes
another way I found to do it: Go to configuration, translate interface, do a search for the error message in english and then add the spanish translation.

# Answer
> 1 votes
Try with String Overrides module.

When you go to module settings choose 'Spanish' tab (if you have more than one language enabled), on the left side put "Please enter an email address" (without quotes of course) and on the right side write Spanish translation. (clear cache)

Let me know if this is working.

# Answer
> 0 votes
I just changed it to a text field instead of an email field and validated it with regex so I could put the error message in spanish.

---
Tags: webforms
---


# Question
Title: Drag and drop no longer working on my drupal 7 site after workbench acess install
When I enable the workbench access module, all drag and drop reordering is broken. It doesn't work under blocks or under the menus. This doesn't happen on my local computer.

The working bench acess module I have is 7.x-1.2 under drupal 7.28

# Answer
> 0 votes
It got fixed by installing the speedy module which compreses all the js.

# Answer
> 0 votes
Try selecting a newer (or older) version of jQuery using "jQuery Update"

---
Tags: workbench
---


title: conditional validation in webform

text:
# Question
Title: conditional validation in webform
I have webform 7.x-3.18+3-dev and webform presav e 7.x.1.1 installed

how can I make one field be obligatory depending on another field.

Eg if someone selects phone as best form of contact they must fill out the phone field. If they choose email they must fill out the email field.

# Answer
I had to make a custom module to do it without hiding the fields . Followed the instructions here https://www.drupal.org/node/908600
> 0 votes

# Answer
Take a look at https://www.drupal.org/project/webform\_conditional

Just make both e-mail & phone mandatory, but only show the relevant field, based on what was chosen in 'best form of contact'.

The module takes into account the 'state' of the form. It doesn't force mandatory, even if the field is set to be mandatory, but is hidden due to a certain select option ( in your case, the 'best form of contact' ).
> 0 votes

# Answer
i think field permissions module will help you
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: ICalendar and Outlook opeing as node For Add to Cal Module Even After Clearing Caches
I installed the Add to cal module and enabled it.

Created a View using with fields or Event Date,Location and Title.

Thus when I added Event Date fields to the View and While Configuring i Choosed Formatter to Add to Cal. The Add to Cal Works fine For Google and Yahoo calendar But When I choose The ICalendar or Outlook Option , corresponding node file gets open eg:- \[website name\]/node/207/field\_date1/addtocal.ics but doesnt downloads the ics file.

I tried Clearing the Cache Varnish Cache as it hosted on the Acquia.com and also the Performance cache but that seems to not work.

# Answer
> 2 votes
I'm a maintainer of the Add To Cal module. It turns out that this is in fact a bug, which we're patching right now.

Until the patch is released, you can fix the issue by downloading and enabling the Entity module on your site. The patch will add this as a dependency to Add To Cal.

Here's the issue on drupal.org: https://www.drupal.org/node/1744684#comment-9056553

EDIT: The 1.x-dev version now includes this bug fix, and it will be included in the beta4 release.

# Answer
> 0 votes
Loking at the above problem, I thought maybe that's Add to Cal module problem, but it was poor configuration problem from my side. I reviewed the configuration and then tried following :

1. Go to Your content type (in my case Event).
2. Then choose manage display tab.
3. Choose the date field and change the formatter to Add to Cal
4. Use subsequent available fields to be inserted into the XXX.ical file which gets downloaded.

thanks..!

---
Tags: views
---


# Question
Title: How can I register a image_style theme function in my module which only works in my theme's template?
Is there a way to tell drupal that my module has a theme function which usually only works in my theme?

If I write in my theme's template.php:

```
function mytheme_image_style($variables) {

  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the URL for the styled image.

  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);

  // do additional stuff

  return theme('image', $variables);
}

```

everything works fine. If I move this code to a module it does not work, though:

```
function mymodule_image_style($variables) {

  // code

  return theme('image', $variables);
}

```

How can I use the theme\_image\_style function/hook in my module?

# Answer
> 2 votes
You need to use `hook_theme_registry_alter()` to replace the callback function for the `image_style` theme. Something like this should do it:

```
function MYMODULE_theme_registry_alter(&$registry) {
  $registry['image_style']['function'] = 'mymodule_image_style';
}

```

# Answer
> 0 votes
I think you have to use hook\_image\_styles\_alter instead of your function.

Here is an example found on drupal.org:

```
<?php
function mymodule_image_styles_alter(&$styles) {
  $styles['myimagestyle'] = array(
    'label' => 'My Image Style',
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array(
          'width' => 500,
          'height' => 300,
          'upscale' => 1,
        ),
        'weight' => 0,
      ),
    ),
    'name' => 'myimagestyle', // You need this and the next line to avoid PHP notices
    'storage' => IMAGE_STORAGE_NORMAL,
  );

  return $styles;
}
?>

```

---
Tags: 7, theming
---


title: Rule is not changing field value

text:
# Question
Title: Rule is not changing field value
I am new to Drupal.

I have created a rule on specific event, and changing the value of `node:field-seat-limit`

### Event

* After updating an existing order product

### Conditions

* Content is of type event
* `uc-order-product:node:field-seat-limit` (negate)

### Action

* Decrement uc-order-product:node:field-seat-limit by using `$value= $value-1;`

Result: I am displaying field-seat-limit in a view, where it is showing the decremented count but when I go to the node, it shows the count that I entered first time.

What is causing the node to fail to reflect the updated value?

# Answer
> 2 votes
You may have to save the changes after you make them. After your decrement action, add another action to save the entity.

---
Tags: nodes, rules, ubercart
---


# Question
Title: Taxonomy block in views which show the description of the children taxonomy, selected by two exposed filters
I would like to build a simple block, where my visitors can check our shipping locations. There are 3 outcome of this form:

1. Visitor can not find his/her county or city -\> we dont deliver there
2. Visitor finds his/her city and the city field has no description -\> we delivery there
3. Visitor finds his/her city and the city field has description -\> we delivery with the desciption's conditions.

I have the following taxonomy tree in Location vocabulary:

* County #1
    + City #1
    + City #2
    + ...
    + City #300
* County #2
* ...
* County #15

What i did:

1. I created a new view which shows taxonomy in a block, no pager, only 1 item.
2. Fields: Taxonomy term: Description
3. If description has value show that, if empty show "we delivery there"

And this is where I got lost. I would like to have 2 exposed filters, where the visitor can select his/her county and its children cities.

Any help, any suggestions are appriciated, thanks!

# Answer
One way to do this is possible with contextual filters.

1. Add a contextual filter based on term name
2. Add a relationship to parent term.
3. Add another contextual filter on term name, but this time use the parent term from the relationship.
4. Tweak the settings (override number of items to show, probably remove the count from the item list, and switch to jump menu instead of regular list if you want a dropdown display.)
> 0 votes

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


# Question
Title: Copy data of Email in registration to the username not showing in the registration page
I want to copy the value of email to the username, which is not showing in the registration page, but it is showing in the /user/edit page as **Display Name**, which is randomly generated such that my username is my email, giving more flexibility to the user.

# Answer
> 1 votes
The Email Registration module will allow for using the email address as the username.

The LoginToboggan module will allow the user to create a username, and allow them to login with either the username OR email address.

Email Registration also provides a hook which will allow a custom module to set the account name to whatever you want it to be. That does require writing a module, however, it doesn't have to be very complicated.

The only thing you would need to include in your module file is the hook. Example adapted from http://www.grasmash.com/article/using-your-email-address-your-drupal-username#sthash.uZkOo6j6.dpuf

```
<?php
/*
* Implements hook_email_registration_name().
*/
function grasmash_email_registration_name($edit, $account) {
  return $account->mail;
}

```

---
Tags: emails, users
---


# Question
Title: Replace URL query string with slash for a cleaner URL
I have created a new content type with a body and multiple fields.

I use the following query string

```
?article=referral-partners

```

to change the content of the node's body according to the value of the value of article.

The full URL looks like this (with my path alias I created):

```
http://localhost/userguides/contacts/my-first-user-guide?article=referral-partners

```

I would like to clean up the url to look like this instead:

```
http://localhost/userguides/contacts/my-first-user-guide/article/referral-partners

```

How can I do this with Drupal 7?

# Answer
Unless there's a chance your URL is going to change a lot as far as "depth" goes, you can use arg() to access any element in the path.

If your path is `userguides/contacts/my-first-user-guide/article/referral-partners`, you would use something like this...

```
$article = arg(4);     // $article is set to 'referral-partners'

```

... and then just check the value of $article. If the code can potentially be run on nodes or pages you don't want it to, then you'd also probably want to check other "args" for safety. Generally Drupal will let you tack on all kinds of extra path elements without needing to go through extra hoops as long as the initial path is a real one.
> 0 votes

# Answer
You can use something like this on your custom module for the redirects with the query strings.

```
/*
 * custom redirect with query string
 * module implements hook_init()
 */

function MyModule_init() {
  if ($_GET['q'] == 'userguides/contacts/my-first-user-guide/article/referral-partners') {
    drupal_goto('userguides/contacts/my-first-user-guide', array('query' => array('article' => 'referral-partners')));
  }
}

```
> 0 votes

# Answer
I was able to accomplish this by using the module Subpathauto

Instead of using query parameters like this: ?article=referral-partners I just use them like this /my-arg-i-want and I am able to get them in my module using arg(2).
> 0 votes

---
Tags: 7, path-aliases
---


# Question
Title: How can I get Panelizer to link my panels to a specific URL instead of the Content option?
This is the page that is shown when I configure a panel. How do I link the image to some other page than the content page? I am using Drupal 7. I think this question would benefit others who wish to link their images to other URLs when using Panelizer. I tried using the panels image link module, but I couldn't find any documentation and it didn't seem to do much.

# Answer
> 1 votes
I found out that I can make a user-uploaded image linkable to a fixed location that I choose. If I create a view that takes in the user-uploaded picture, and then add a link through views, Panelizer will let me place the view in a pane. This means I can have a linkable image in a pane. I have included step-by-step pictures.

This shows up upon the creation of a view. Click the add button by the fields in the left column to add the picture from a content type.

This shows you that a content node needs to be picked. In this case, it is a picture that the user uploads

Upon the selection of the picture views will ask how to display it. I have selected "Output as a link" This will then open up this part of the menu:

Here you can select the URL you want the link to go to. For example, somewhere on your site or to drupal.org :)

You then need to save everything. Then, go back to panelizer, or panels. There select a cog wheel and add content. This page should look like this:

Then, it will bring up a window where you will need to click on the views option:

Then you should see these windows:

---
Tags: media, navigation, panels
---


title: Custom Breadcrumbs remove duplicates

text:
# Question
Title: Custom Breadcrumbs remove duplicates
I am using custom breadcrumbs and almost all is working well but a few issues. One problem stated in another question, this problem is that on the landing page of my views I am getting home \>\> Homme \>\> Homme. I need to remove the duplicate. I see there is a form in the configuration for breadcrumb visibility. Is this where I solve this problem. I see no other way to do this. Does anyone know or have the code I need?

# Answer
I think you could use `theme_breadcrumb($variables)` in your `template.php` to remove duplicates.

Code could be something like this:

```
themeName_breadcrumb($variables) {
  [...]
  $breadcrumbs = array_unique($variables['breadcrumb']);
  [...]
}

```
> 4 votes

# Answer
For some reason I was getting duplicates in my breadcrumb. But they weren't quite duplicates, one would have an anchor element with a title, the other wouldn't, thus I had to check only the html within the anchor element, not the entire row of the array.

I didn't have time to totally debug it. Here's what I did:

```
function [yourtheme]_breadcrumb($variables) {
  // Convenience variable:
  $breadcrumb = $variables['breadcrumb'];

  //For some reason there are duplicate entries in the breadcrumb, this will remove them
  $flags = array();
  foreach($breadcrumb as $key => $bc){
    $startPos = strpos($bc,'>');
    $flag = substr($bc,$startPos);
    if (in_array($flag,$flags)){
      unset($breadcrumb[$key]);
      continue;
    }
    $flags[] = $flag;
  }

  //That's the only relevant code, the rest of this is for another purpose

  // If we have any breadcrumbs:
  if (!empty($breadcrumb)) {
    $breadcrumb[] = drupal_get_title();

    // Convert 'em to a string:
    $breadcrumbs = implode(' <span class="divider">/</span> ', $breadcrumb);
    // Build a heading--here at least, we're following the D7 convention of
    // accompanying menus with invisible headings to aid in text-only navigation:
    $heading = t('You are here');
    // Pattern for output:
    $output_pattern = '<h2 class="element-invisible">%s</h2><ul class="breadcrumb">%s</ul>';
    // Return the markup:
    return sprintf($output_pattern, $heading, $breadcrumbs);
  }
}

```
> 0 votes

# Answer
Why do you use theme function instead of the preprocess?

```
function THEME_preprocess_breadcrumb(&$variables) {
  $all = array();
  foreach ($variables['breadcrumb'] as $key=>$item) {
    if (preg_match('|href="(.*)"|Ui', $item, $matches)) {
      if (isset($all[$matches[1]])) {
        unset($variables['breadcrumb'][$key]);
      } else {
        $all[$matches[1]] = 1;
      }
    }
  }
}

```
> 0 votes

---
Tags: 7, breadcrumbs
---


# Question
Title: Creating a form with GET bypases the validation and submit
I am creating a simple form, when sumits, shows result from an external API. But URL remain the same, so you cant get a url if your search result and send it to someone.

But when I use get

```
$form['method'] = 'get';

```

It shows a construted url..

```
mysite.com/search?cat=2$coutry=3

```

But it donot fetch the result, cause it is bypassing the submit and validation functions. Any help?

# Answer
> 0 votes
Have the page or form check for the presence of your variables, using `drupal_get_query_parameters()`, and if present, perform validation checks and get results from the external API, and display.

For example,

```
$params = drupal_get_query_parameters();
if ( isset($params['cat']) ) {
  //validate $params['cat']
    if ( myValidationCheck($params['cat']) ) {
      $results = myExternalAPIGetResults($params['cat']);
      $form['results'] = myResultsDisplay($results);
    }
  }

```

---
Tags: 7, forms
---


# Question
Title: How to convert a webform into an ordered list?
I've tried to preprocess a webform in order to convert the form items into an ordered list. My webform is composed of questions, and I want each question to be a enumerated list element.

The problem is that I cannot find where to convert the `<div>` following the `<form>` into an `<ol>`, and the next nested `<div>` into an `<li>`. After navigating webform's source code I could not find a function that says "give me all the webform elements", for example. It all seems to work in the following order:

* implement hook node load (load webform components)
* implement hook node view (order webform components into a structure that is hard to modify?)
* create form
* render form using some theming functions

When I use the node preprocessor to alter the components (and attempt to insert a #type = item\_list somewhere), it doesn't work. And when using one of the webform theming functions, the data structure comes in a way that is hard to modify. Example:

That variable that I tried to modify was the `$variables['elements']['webform']['#form']['submitted']` in a **hook\_preprocess\_node**.

# Answer
> 1 votes
Install Theme Developer and look for theming function name.

# Answer
> 1 votes
Combine the following options

1/ Have a look at the theme functions in webform.module: * webform\_element\_wrapper * theme\_webform\_element * theme\_webform\_element\_wrapper

2/ Make use of webform.tpl.php

Or try with jquery/css to alter the whole structure

# Answer
> 1 votes
If you just want it to look like a list, you can use css to style it.

```
#webform-client-form-70 .form-item {
  display: list-item;
  list-style-type: decimal;//for ordered list appearance
}

```

---
Tags: 7, webforms
---