# Question
Title: Possible to use default user picture in rewritten views field?
I have a view which displays fields and one of them is a rewritten field to display the user picture along with some other information. There is no issue if the user picture is uploaded, but if the user does not, this field does not show the default user picture. Is there anything I need to do to allow the default user image to display in this rewritten views field?

I tried unchecking the hide field if empty option under no results behaviour, but realised that since I already rewrote the field, this does not seem to apply, because my rewrite renders other fields that always have values in them.

# Answer
You can use no result behavior option to show the default picture for the user's image.

Here is my screenshot :

If you want to combine two fields then you have to take two field firstly in view fields and shown their output in diffrent-2 field after that you can combine both fields in new field using rewrite option. The first two field output is hidden who's value you want to combine.
> 0 votes

---
Tags: views
---


# Question
Title: HTML being removed when rewriting field in Views
I have completely stripped all my views/blocks down so they only produce exactly what I put into them..but I created a view and rewrote the fields and this part of my code will not print exactly as it is here:

```
<div style="background-image: url('sites/all/themes/my-theme/images/my-image.jpg');" class="slides-fullscreen-img"></div>

```

Instead, when the block is rendered I get:

```
<div class="slides-fullscreen-img"></div>

```

So it strips away come of my code. Does anyone know how I can get round this problem?

# Answer
> 0 votes
Adding a class and then the style to your stylesheet is the normal practise. Quick fix

.slides-full-screen-image { Background-image: url....

}

If you have more calls to that class where you don't want the image then you should add an additional class name.

---
Tags: views, blocks
---


# Question
Title: Commerce - How to hook into ajax call on commerce cart form variation change
When you change a product attribute on a product display page, ajax loads the fields of the new product.

See here: http://demo.commerceguys.com/ck/tops/drupal-commerce-hoodie

By changing the size, color, etc, you trigger an ajax call that changes the fields such as SKU, images, etc.

My question is, how do you add additional markup to be updated on the attribute(form field) change?

By default, the form will update all fields printed in the template in this format.

```
<?php print render($content['commerce_price']); ?>

```

This wraps markup around the price with the following classes.

```
commerce-product-field commerce-product-field-commerce-price field-commerce-price node-880-product-commerce-price

```

Im assuming the ajax call is replacing fields by looking at this markup.

So how do I add additional markup, that printed in the node template, to be replaced with ajax when a form field is changed.

Im not sure what to hook into.

Many thanks.

# Answer
There's a hook for that: hook\_commerce\_cart\_attributes\_refresh\_alter. This is invoked when the variation is selected by the user and reacts to changes in the cart widget.

It gives you the chance of using ajax commands, so you basically have the complete control over elements and behaviors, there's an excellent tutorial in here: https://drupal.stackexchange.com/a/73325/2322

Also, a couple of examples, Commerce itself invokes the hook from the cart module and there's this sandbox module called Commerce Single Page Checkout that uses the technique for adding a view on the refresh event using ajax\_command\_replace.
> 6 votes

# Answer
You can use `hook_form_alter` and check `$form_state['default_product']` for product details.

e.g, show markup from a field on the default product.

```
/**
 * Implements hook_form_FORM_ID_alter
 *
 * Alter commerce add to cart form
 */
function MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state){

  // Add some generic markup from the selected product field.
  if (isset($form_state['default_product']) && isset($form_state['default_product']->field_extra_markup[LANGUAGE_NONE][0]['value'])){
    $form['extra_markup'] = array(
      '#title' => t('Some markup'),
      '#type' => 'item',
      '#markup' => $form_state['default_product']->field_extra_markup[LANGUAGE_NONE][0]['value'],
    );
  }

}

```
> 1 votes

---
Tags: commerce, ajax
---


# Question
Title: Creating view filter that lists most recent, except the x most recent
I'm trying to create a view that will go on a front page where the three most recent articles will be featured content displayed in a slideshow. I've got that working, but my issue is displaying the rest of the most recent articles in another view, as a list formatted normally as they appear in the teaser display. My problem isn't achieving that display, it's filtering the articles properly so I get most recent - 3 most recent. I'm trying to not be redundant on this articles page.

If my approach of creating two different views to achieve this effect is totally misguided, or if there's some other glaring way to do this more easily, please correct me. I'll be very grateful.

For clarity, I'm including a rough sketch, where the numbers indicate the recentness of the article and the top unit is the featured content slideshow display:

# Answer
I would create a view and have two different displays. One display holds your slideshow thing and the other display holds the rest of the items.

The second display would be set to have the style item list and the pager settings should be set to have an offset of three. The offset will skip the first X items that are present in your first display.
> 1 votes

---
Tags: views
---


# Question
Title: How can I update from the recommended release of a module to it development snapshot?
I'm currently using the Geofield module, 7.x-1.0-beta2 (released on November 17, 2011). The development snapshot has some functionalities I want.

How do I correctly and safely update to the development snapshot, which was last update on January 10, 2012?

What I currently do is removing the geofield field from any content type, uninstalling the module, physically delete the module files from the server, download and install the development snapshot.

This seems to work but I'm wondering if there is a more efficient workflow.

(I have Drush installed; an answer about using it is welcome too.)

# Answer
From the working directory (site root) use this command:

```
drush dl module_name --dev

```

To get the DEV version.

Or:

```
drush dl module_name --select

```

To display a list of available versions.

Afterwards do `drush updatedb` to apply any database updates made by the module. You should check out https://drushcommands.com/ and all the commands on that page (the aliases are at the end of each section). For example, `drush up` will check for all possible updates.

In most cases you will not need to disable and uninstall things first but always make sure you are working in a dev environment and have regular backups (e.g. use the backup\_migrate module). Drush will also backup the previous version of the module when usingdrush up`but NOT if you directly overwrite with`drush dl\`.
> 44 votes

# Answer
You can use `drush pm-update` to update any module, and add the version information to update to a specific version. For example if you want to update to a 7.x-1.x-dev version of a module, you can use the following command:

> drush pm-update MODULE\_NAME-7.x-1.x-dev

or, shorter:

> drush up MODULE\_NAME-1.x-dev

so you can omit `7.x-`.
> 33 votes

---
Tags: 7, updating
---


# Question
Title: Drupal Rest services "access denied user anonymous"
I have created a custom service where I am passing parameters and retrieving result from another file.

So to test it I tried on Postman and I put URL with sitename/endpoint/resource and passed parameters in key value. When I submit I get an error as access denied user anonymous.

I have return my custom services under `hook_services_resources()` function

```
function mymodule_services_resources() {
 $api = array(
  'blog' => array(
    'actions' => array(
     'math' => array(
      'help' => 'Retrieves posted blogs',
      'file' => array('type' => 'inc', 'module' => 'MYMODULE', 'name' => 'mymodule'),

      'callback' => 'mymodule_blog_retrieve',
      'access arguments' => array('services_access_menu'),

      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'var1',
          'type' => 'string',
          'description' => 'variable 1',
          'source' => array('data' => 'var1'),
          'default' => '0',
        ),
        array(
          'name' => 'var2',
          'type' => 'string',
          'description' => 'variable 2',
          'source' => array('data' => 'var2'),
          'default' => '0',
        ),
      ),
    ),
  ),
),

 );
  return $api;
}

```

and inc file just takes parameters var1 and var2 and adds it and returns the sum.

Please help me finding out where i have done mistakes.

# Answer
Two suggestions on that.

1. Try removing `'access arguments append' => TRUE` and clear cache. It can interfere with the `user_access` check.
2. Depending on your authentication method, you may need to set the correct `X-CSRF-Token` authentication token in the request. See Problems with Services and CSRF token
> 2 votes

# Answer
Here is running code with access callback function:

```

function mymodule_services_resources() {
 $api = array(
  'blog' => array(
    'actions' => array(
     'math' => array(
      'help' => 'Retrieves posted blogs',
      'file' => array('type' => 'inc', 'module' => 'MYMODULE', 'name' => 'mymodule'),
      'callback' => 'mymodule_blog_retrieve',
      'access arguments' => array('views'),
      'access callback' => '_blog_access_provide_access',
      'access arguments append' => TRUE,
      'args' => array(
        array(
          'name' => 'var1',
          'type' => 'string',
          'description' => 'variable 1',
          'source' => array('data' => 'var1'),
          'default' => '0',
        ),
        array(
          'name' => 'var2',
          'type' => 'string',
          'description' => 'variable 2',
          'source' => array('data' => 'var2'),
          'default' => '0',
        ),
      ),
    ),
  ),
),

 );
  return $api;
}
```

```

/** * Access callback */
function _blog_access_provide_access() {
  return TRUE;
}

```

I hope this would help you.
> 3 votes

---
Tags: 8, services
---


# Question
Title: How to allow a user with some role to let people to register their new accounts in drupal 7?
Is it possible to let a user with some role (not an admin) that will decide if somebody can register in drupal?

I know there is an option in admin menu

> Configuration-\>Account settings Option: Registration and cancellation Who can register accounts?

Is there any other option to do it like a module that user has a permission to switch on or off registration new users?

# Answer
In Drupal 7 you can use Administer Users by Role module

> **Administer Users by Role** : This module allows site builders to set up fine-grained permissions for allowing users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

Reference:
> 2 votes

# Answer
First create a new role (e.g. "User admin") and give that user the permission: "Administer users". That gives whoaver has that role the approve new registrations (which is what you want).

However, this permission is indeed a dangerous permission to give, because anyone that holds it can assign new roles to any user (including self), so there is nothing to stop that user from promoting self to the full admin role (this *not* what you want).

To fix this, add the User protect module. This lets you protect against unwanted privilege escalation.
> 0 votes

---
Tags: users
---


title: Disable read more link

text:
# Question
Title: Disable read more link
I tried to remove "read more" link from the "basic page" content type. In `Structure -> Content types -> Basic page -> manage display` I checked "full content" and unchecked everything else and this didn't help.
Where am I doing mistake?

I found in another question the possibility to edit the template file, but I would rather do it in the settings.

thank you

# Answer
> 8 votes
There is no setting for that.

You can either do it with a preprocess function as explained in Remove the 'read more' and 'Add new comment' links on the home page or you can implement hook\_node\_view\_alter(). Both is possible in a module or in a theme.

The read more link in is added in node\_build\_content(), and you should be able to remove just that link like this:

```
function yourmodule_node_view_alter(&$build) {
  if ($build['#node']->type == 'page') {
    unset($build['links']['node']['node-readmore']);
  }
}

```

# Answer
> 3 votes
As of Drupal version 7.x and 2014 May, I dare say that the correct approach to the functionality of disabling the "Read more" link would be via the installation and configuration of the Read More Control module found at Read More Control module.

There are other features that the above module is capable of, and would be the best approach to solve such issues without diving into code or hacking away at any file directly.

# Answer
> 1 votes
We can hide it through css. Just take the body class as parent and then node-readmore

```
 .parentclass .node-readmore
 {
   display: none;
 }

```

# Answer
> 1 votes
Perfect solution: Read More Control Module

Just enable and configure module.

> A module to control when the teaser Read More link appears in Drupal 7.
>
> There is no mechanism in core to decide if the read more link should appear. This means that this link will always show no matter if there is additional content to display. This module tries to overcome this issue by allowing administrators to determine how to handle this link in relation to both the content type and individual fields.
>
> The module allows you to add Read more links to other supported view modes (RSS feed, Search results, etc) or even other supported entity types. Particularly useful if you use panels or views and either programmatically add additional view modes or use other contrib modules to provide these.

# Answer
> 0 votes
This is an other way that you can hide the read more link simply using CSS code:

```
.node-readmore {
     font-size: 0;
}

```

Edited: You have to add this code in your css override file

# Answer
> 0 votes
This can also be done with Panels.

1. Create a new Panels page
2. Click Add Content on a Panel
3. Click 'Node' to access node related panes
4. Click 'Node Content'
5. Un-check 'Include node links for "add comment", "read more" etc.'

You may have to add panes for comments, etc..

# Answer
> 0 votes
Also, to remove the read-more from just the teaser while keeping other elements that may be using the links section (like the sharing widget from AddtoAny for example), you could do the following in a custom module:

```
function [your-module-name]_node_view_alter(&$build) {
  /* remove just the read-more while preserving other elements using Links section */
  if ($build['#view_mode'] == 'teaser') {
    unset($build['links']['node']['#links']['node-readmore']);
  }
}

```

This also comes in handy if you're using the excellent Smart Trim module to put the read-more at the end of the trimmed summary and not in the Links section.

# Answer
> -3 votes
You can combine Ram's, and user175...'s answer to get where you want to.

Just add this to the top of the page you want the read more's to dissapear. (e.g. inside the post that you want to have the button removed from, or in a custom block on the same page)

```
<style type="text/css">
.node-readmore {
     display: none !important;
}
</style>

```

No need to mess with css files or modules, will work on-the-fly.

---
Tags: 7, nodes
---


# Question
Title: How can set a custom action with a custom attribute selected in form?
I have a view of persons. I like to add the persons to an event. I also like to set the status of the resulting relation to one of the values "optional" or "required".

Therefore I use VBO on a list of persons. With the submitted NIDs I like to build a relation from the person to the event and fill the relation data field "status" with the selected value from the from.

To create only the relation it was easy to create a new action with custom php code, which builds my relations programmatically.

To add a parameter to the relation I have to edit the view's form programmatically. So I hook into the form alter of the views form and add a custom dropdown with the two values "optional" or "required".

The questions are:

1. Is it possible to use the selected dropdown value in the vbo action with custom php code? I only know how to handle the selected nid's. This option would be easier for me to implement.
2. If 1) is not possible: Should I use a custom submit function for the vbo form? And where to assign the function?

I tried the following code to assign a custom submit `custom_webform_pre_build_list_vbo_submit`function but it isn't called.

```
function custom_webform_pre_build_list_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "views_form_person_list_panel_pane_9"
    and $form['#id']=='views-form-person-list-panel-pane-9') {
        $form['#submit'] = array('custom_webform_pre_build_list_vbo_submit');
    }
}

```

# Answer
It is possible to use the $\_POST array in the custom php code, which can be called in the action, which is assigned to the vbo action! The page to show the view with the vbo fields is: `/node/%node/add_person_to_event`, so arg(1) is the nid of the event.

So my custom action code is: `$status = $_POST['status'];
$event = arg(1);
foreach ($_POST['views_bulk_operations'] as $key->$vbo_nid) {
 build_relation_person_event($event, $vbo_nid, $status);
}`
> -1 votes

---
Tags: forms, views
---


title: Using images instead of text in menus

text:
# Question
Title: Using images instead of text in menus
I have a client who wants to use images instead of text for his menu items. Is there a native way to do this in Drupal 7?

# Answer
In Drupal 7 you can using

Reference:

Replacing menu items with images
> 3 votes

---
Tags: 7, routes, media
---


# Question
Title: What's the data structure that needed by services for posting new node with drupal7 services?
I have content type named "shen" and gona to create new node with services module from crawl machine data.

For now, it can login in system and post new node but it can't save image field data.

this is the data It post to services module:

```
{'body': {'und': {'0': {'value': 'I am Shen'}}}, 'type': 'shen', 'field_shen_image': {'und': {'0': {'new': 1, 'display': 1, 'fid': '541'}}}, 'title': 'just a little title'}

```

I'm sure lost a little thing and really need your help.

Cheers

# Answer
> 0 votes
Corrected JSON format and tested on my local environment.

```

{
    "body": {
        "und": [
            {
                "value": "IamShen"
            }
        ]
    },
    "type": "shen",
    "field_shen_image": {
        "und": [
            {
                "new": 1,
                "display": 1,
                "fid": 541
            }
        ]
    },
    "title": "justalittletitle"
}

```

---
Tags: services, 8
---


# Question
Title: How to override template for view mode of a entity within a module?
I see in theme suggestion array that I can override template for my custom entity type based on view mode like this:

> custom\_entity\__custom\_entity\__view\_mode\_name

Now I want to put

> custom-entity--custom-entity--view-mode-name.tpl.php

inside custom module.

I'm trying something like:

```
function custom_module_theme_registry_alter(&$theme_registry) {

  if (isset($theme_registry['entity'])) {

    $entity = &$theme_registry['entity'];

    if (!isset($entity['theme paths'])) {
      $entity['theme paths'] = array();
    }

    $entity['theme paths'][] = drupal_get_path('module', 'custom_module') . '/templates';

    if (isset($entity['theme path'])) {
      $entity['theme paths'][] = $entity['theme path'];
      unset($entity['theme path']);
   }
  }
}

```

So my template file is in custom\_module/templates directory.

But after clearing cache always entity.tpl.php is used for all view modes.

# Answer
I did this using hook\_process\_HOOK($variables) for nodes view mode tpls :

```
function view_mode_tpl_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__' .$vars['view_mode'];
}

```

hope this will help you.
> 0 votes

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


title: How to migrate taxonomy with hierarchy?

text:
# Question
Title: How to migrate taxonomy with hierarchy?
I'm trying to create a hierarchical taxonomy from a perpared migration database table which looks like that:

```
ID | NAME | PARENT
------------------
 0 | FOO  |
 1 | BAR  |
 2 | LORE | FOO
 3 | IPSE | FOO
 4 | DOLO | BAR

```

It's a pretty messy data structure, but fact is there are parent and child terms in one table.

What I did so far is migrating the parent terms first. Now my custom taxonomy looks like this:

```
_
|_ FOO
|_ BAR

```

The migration code snipped I used to achieve this works like that:

```
$this->addFieldMapping('name', 'PARENT');

```

Until now everything works as expected!

---

Now, in a second migration step I want to add the child terms like that to my taxonomy:

```
_
|_ FOO
  |_ LORE
  |_ IPSE
|_ BAR
  |_ DOLO

```

What I tried is to add a hierarchical mapping to my migration:

```
$this->addFieldMapping('name', 'NAME');
$this->addFieldMapping('parent_name', 'PARENT')
    ->arguments(array('source_type' => 'name'));

```

But this does not work, the result is an unhierarchical list like that:

```
_
|_ FOO
|_ LORE
|_ IPSE
|_ BAR
|_ DOLO

```

Did anyone try to do something like this before? Any ideas? Thanks!

# Answer
> 3 votes
I had to migrate a nested Vocabulary from Drupal 6 to Drupal 7. My Strategy was:

1. Migrate the plain terms
2. Use the postImport() of Migrate-API to map the Parent-Relationship

```
public function postImport() {

// Get alle Terms from features_dd_private_contact_form_subjects
// Query zum Laden der Daten aus Drupal6
$source_query = Database::getConnection('legacy', 'legacy')
  ->select('term_data', 't');

// Join Terms with voab
$source_query->join('vocabulary', 'v', 'v.vid = t.vid');

// Join Hierarchy
$source_query->join('term_hierarchy', 'th', 'th.tid = t.tid');

$source_query->condition('th.parent', '0', '<>');

$source_query->fields('th', array());

$source_query->condition(
  'v.module',
  'features_dd_private_contact_form_subjects',
  '='
);

$source_query->fields('t');

$source_records = $source_query->execute();

foreach ($source_records as $source_record) {

  // Term-ID in destination db.
  $dest_tid = $this->get_destination_tid_by_old_tid($source_record->tid);

  // Parent-Tid in the destination.
  $dest_parent_tid = $this->get_destination_tid_by_old_tid($source_record->parent);

  $child_term = taxonomy_term_load($dest_tid);
  $child_term->parent = $dest_parent_tid;
  taxonomy_term_save($child_term);
}

```

}

---
Tags: taxonomy-terms, migrations
---


# Question
Title: Term reference with radio buttons + bootstrap tooltip
In the details of a user I have a term reference that is presented as radio buttons. You can select one radiobutton. The html looks like this:

```
<div id="edit-field-abonnement-und" class="form-radios">
    <div class="form-type-radio form-item-field-abonnement-und form-item radio">
        <input type="radio" id="edit-field-abonnement-und-2" name="field_abonnement[und]" value="2" class="form-radio">
        <label for="edit-field-abonnement-und-2">Abonnement 1 </label>
    </div>
    <div class="form-type-radio form-item-field-abonnement-und form-item radio">
        <input type="radio" id="edit-field-abonnement-und-3" name="field_abonnement[und]" value="3" class="form-radio">
        <label for="edit-field-abonnement-und-3">Abonnement 2 </label>

    </div>
    <div class="form-type-radio form-item-field-abonnement-und form-item radio">
        <input type="radio" id="edit-field-abonnement-und-4" name="field_abonnement[und]" value="4" class="form-radio">
        <label for="edit-field-abonnement-und-4">Abonnement 3 </label>

    </div>
    <div class="form-type-radio form-item-field-abonnement-und form-item radio">
        <input type="radio" id="edit-field-abonnement-und-5" name="field_abonnement[und]" value="5" class="form-radio">
        <label for="edit-field-abonnement-und-5">Abonnement 4 </label>
    </div>
</div>

```

But I would like to have a tooltip on each div. I can add a javascript file and send some data to the javascript and set the title with the data (I would do this with taxonomy\_term\_load).

But how can I get a structure like this and make sure the tooltip works?

```
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Tooltip on left">Tooltip on left</button>

```

# Answer
> 1 votes
**Part 1**

You can theme a field, using theme suggestions:

> field--\[type|name\[--content-type\]|content-type\].tpl.php base template:
>
> field.tpl.php
>
> Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:
>
> * field--field-name--content-type.tpl.php
> * field--content-type.tpl.php
> * field--field-name.tpl.php field--field-type.tpl.php
>
> Note that underscores in a Field's machine name are replaced by hyphens. Also remember to include "field-" in custom field names, e.g: field--field-phone.tpl.php.

Get a copy of the base field theme from `modules/field/theme/field.tpl.php` and copy to your theme's folder, rename and modify as required.

**Part 2**

A better options is to use the Fences Module which allows for greater control over theming your fields.

> Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.

All of the field tempaltes are in `/sites/all/modules/fences/templates` and correspond to the type of wrapper you have applied to your field.

Like part 1, copy the field you need into your theme's folder, rename and modify as required.

---
Tags: 7, javascript, taxonomy-terms, tooltips
---


# Question
Title: How to not show user signatures in comments?
In D7, user signatures appear in their comments. It can be very annoying for many, especially when the signature is long or contain big pictures. So I'm wondering how to disable this?

# Answer
There is feature in admin panel of Drupal to disable signature option directly. Follow the below steps:

1. Go to admin/config/people/accounts (admin \> configuration \> account settings)
2. Uncheck "Enable signatures" checkbox under Personalization section.
3. Once finished, go down to the bottom of the screen and click the Save Configuration button.
> 3 votes

# Answer
In Drupal 7 you can achieve it by overriding the comment tpl file

Steps

* Copy comment.tpl from modules\comment and paste in your active theme(sites\all\themes\your\_active\_theme\templates) inside templates folder.
* Edit the and comment the following code
```

<?php if ($signature): ??>
  <div class="user-signature clearfix"?>
    <?php print $signature ??>
  </div?>
<?php endif; ?>

```
> 2 votes

---
Tags: 7, comments
---


title: Add menu item programmatically Drupal 6

text:
# Question
Title: Add menu item programmatically Drupal 6
I am trying to add a menu item to a custom menu programmatically in Drupal 6 and have almost gotten it but ran into a weird problem. I can add the item to the menu using the code: `drupal_execute('menu_edit_item', $item_array, 'add', NULL, array('menu_name' => $menu_name));
drupal_flush_all_caches();` This somewhat works, but for the link to actually show up in the menu I have to either save the page twice, or save the page and clear the cache from Admin \> Performance. Does anyone know why I need to flush the caches twice, or is there a better way to do this? Let me know if you need any more information, I included what I thought was relevant but I may have left something out.

# Answer
> 1 votes
To add menu items use hook\_menu():

> This hook enables modules to register paths in order to define how URL requests are handled. Paths may be registered for URL handling only, or they can register a link to be placed in a menu (usually the Navigation menu).

example:

```
function YOUR_MODULE_NAME_menu() {
  $items['a/b/c'] = array(
    'title' => 'Example menu',
    'page callback' => 'example_callback',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'your-custom-menu-name',
  );
  return $items;

```

}

To learn more about hooks see here

# Answer
> 1 votes
The API you are looking for is `menu_link_save`. And, as documented use `menu_cache_clear_all` after.

# Answer
> 0 votes
Try menu\_rebuild() instead of flushing caches.

> (Re)populate the database tables used by various menu functions.
>
> This function will clear and populate the {menu\_router} table, add entries to {menu\_links} for new router items, then remove stale items from {menu\_links}. If called from update.php or install.php, it will also schedule a call to itself on the first real page load from menu\_execute\_active\_handler(), because the maintenance page environment is different and leaves stale data in the menu tables.

---
Tags: 6, routes, navigation
---


# Question
Title: get file path of image style as replacement patterns in views
i need something like

```
<img attribute1='value' src='sites/default/files/styles/thumbnails/**pic_0**.jpg'>

```

in views.

i have to use rewrite result because i need attribute1. but i have no idea how to get src of image. `[filename]` is not always same with file path. -for example `[filename]` is pic.jpg but file path is pic\_0.jpg- .

and `[uri]` give me http://example.com/sites/default/files/pic\_0.jpg not http://example.com/sites/default/files/styles/thumbnails/pic\_0.jpg.

how can i get pic\_0.jpg or http://example.com/sites/default/files/styles/thumbnails/pic\_0.jpg?

# Answer
You can get file path of image style in view.tpl

**Example:**

```
/**
 * field with image: "field_image"
 * uri:  (image from field_image) File: Path
 */

$style_name = $view->field['field_image']->options['settings']['image_style'];
$thumb_path = image_style_url($style_name, $uri);

```

I didn't wrote how to get $uri because it depends on type of template file. The general idea is to get a file path of image style by using **image\_style\_url($style\_name, $uri)** in view.tpl file.
> 0 votes

# Answer
You can achieve that by using Image URL Formatter module.

> This module add a url formatter for image field. Then you can output image url directly.
>
> Most of the code, maybe more than 90%, is just copy from the drupal core. I think it is stable enough.
>
> **Usage**
>
> 1. After install this module,then you add an image field,then you can goto this bundle's manage display page,here at format column,you can choose "Image URL" instead of "Image".
> 2. When you add an image field in your views,then you config the Formatter for this field, here you can choose "Image URL" instead of "Image".
>
> Then you can output image's URL instead of Image itself.
> 0 votes

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


title: How to pass arguments to rules_event?

text:
# Question
Title: How to pass arguments to rules_event?
```
rules_invoke_event('example_entry_add',$user,$result);

 function warden_rules_event_info() {

 dd("Event info");

   return array(
     'example_entry_add' => array(
       'label' => t('An entry has been added'),
       'module' => 'example',
       'variables'=>array(
         'user' => array('type' => 'user', 'label' => t('user')),
         'entry' => array('type' => 'entry', 'label' => t('entry')),
     ),
       'group' => t('example'),
     ),   );

 }

```

I have a question, when I add an entry to a user I want to invoke an event (rules\_invoke\_event ('example\_entry\_add', $ user, $ result);) with two variables that need these variables passed to them rules\_event function, but how the step after another to function, in this case the rules\_condition, can someone help me?, thank you, excuse me for asking, but I'm starting to develop in drupal.

# Answer
You can use `rules_invoke_event_by_args` read details here

Example:

`rules_invoke_event_by_args('node_view', array('node' => $node, 'view_mode' => $view_mode));` Also, this tutorial may possibly help
> 0 votes

---
Tags: rules
---


# Question
Title: Create a view block for display of taxonomy term children
I am trying to create a View of Taxonomy Terms which lists the child terms for the currently displayed term. Is this even possible for taxonomy terms or is it only possible for Content Nodes?

# Answer
yes,you can do this by : on CONTEXTUAL FILTERS add "Taxonomy term: Parent term" and on once you've chosen it, there's a set of radio buttons entitled When the filter value is NOT available. Set this to provide a default value and then, in this case, choose "Taxonomy term id from url" from the drop-down menu.you are good to go.
> 1 votes

# Answer
What you need to do is to create a contextual filter by making a new View and add a Block Display to it. From there you add the contextual field of Taxonomy to parse the URL path. Then pass an argument into the contextual filter which selects the Taxonomy vocabulary. From there you add in the fields you want to show.

Watch this as it will help you out on setting up a contextual filter: http://nodeone.se/en/learn-views-with-nodeone-part-19-contextual-filters-with-paths
> 0 votes

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


# Question
Title: Is there a way to resolve a list of references in a view without cloning entire rows of data?
I'm playing around with the drupal views and reference relationships. I have an entity of type A that has a reference to entity of type B, and a list of references to entities of type C. Reached this point thanks to : this question

Using views -\> advanced -\> relationships I can create a relationship to B and then add the fields that I want from B in the view of A. However, when doing the same thing for the list of C, I am seeing the same entity of type A repeated as many times as there are references to the entity of type C.

Is there a way to have the list of C entities without the duplication behavior?

# Answer
Depending on how you want to use the results of the query, you could use a GROUPBY option within the Views config. Find the GROUPING options by clicking on the word "Settings" under FORMAT. The link for "Settings" appears to the right of the pipe symbol which separates the chosen format from the "Settings" link. Once you do this, it should remove the duplicates.
> 0 votes

---
Tags: views
---


# Question
Title: Send site emails to multiple administrators
Simple question, though I cannot find the answer anywhere --

**How does one specify multiple addresses for the primary administrator account in Drupal 7?**

Put another way -- how does one make Drupal administrator emails go to multiple people, without setting up a bunch of forwarding filters on the mailserver?

Thanks!

# Answer
> 3 votes
This is *much* similar to Pontus's answer but in a different approach. and I have tested this and it worked on a Ubuntu server email program (not through an external SMTP server but it should work in a decent program). Pontus's solution will work as it seems. But recipient will see both email addresses. A good approach would be to set the BCC address (Blind Carbon Copy) instead of a new CC.

If you are not willing to make a module, I'd suggest http://drupal.org/project/maillog .

```
function MYMODULE_mail_alter(&$message) {
 if (-- enter your condition here -- ) {
   $message['headers']['BCC'] = $message['headers']['Bcc'] = 'hidden@example.com';
 }
 }

```

Note that now you have opened a **serious** security risk that hidden@example.com can now see any email, including password reset email address for the super user. So don't forget to add some condition using $message\['id\] that contains the message's ID.

You can make the module fancy and really usable by adding some sort of system\_settings\_form()'d form and a few variable\_get().

Also, if the purpose of this is to send multiple emails on new security releases for modules, don't forget that you can add multiple email addresses in settings out-of-the-box.

# Answer
> 1 votes
I haven't hit this problem before but the only way I can think of is to implement hook\_mail\_alter().

Untested code but I think it would look something like this:

```
    function MYMODULE_mail_alter(&$message) {
      $additional_emails = ',extra@extra.com';
      $site_mail = variable_get('site_mail', '');
      if ($message['to'] == $site_mail) {
          $message['to'] = $site_mail . $additional_admins;
        }
      }
    }

```

# Answer
> 0 votes
The "Multiple Email" module does not appear to send to multiple email addresses within the user profile. The below code checks (a) if the user role is not "administrator", then checks if there are email values in a "home\_email" field and "email\_for\_text\_messages" field, and sends emails to these addresses in addition to the profile's default email field.

```
function MYMODULE_mail_alter(&$message) {
 $user = user_load_by_mail($message['to']);
 $roles = array('administrator');
 $check = array_intersect($roles, array_values($user->roles));
 if (empty($check)) {
    if (isset($user->field_home_email['und']['0']['value'])) {
      $additional_emails = ','.$user->field_home_email['und']['0']['value'];
    }
  if (isset($user->field_email_for_text_messages['und']['0']['value'])) {
    $additional_emails .= ','.$user->field_email_for_text_messages['und']['0']['value'];
    }
   $message['to'] = $message['to'].$additional_emails;
 }
}

```

# Answer
> 0 votes
with multiple\_email in D6

```
function MYMODULE_mail_alter(&$message) {
  if ($message['id'] != 'multiple_email_confirmation') {
    $user_info = array('mail' => $message['to']);
    $loaded = user_load($user_info);
    if (isset($loaded->uid) && $loaded->uid) {
      $to = multiple_email_load_addresses(1);
      foreach($to as $mail_add) {
        if (isset($mail_add->confirmed) && $mail_add->confirmed && ($mail->primary_address == 0)){
          $message['to'] .= ", " . $mail_add->email;
        }
      }
    }
  }
}

```

# Answer
> -1 votes
there is a module available. drupal 6 version is stable and d7 dev is also working for me you can try that http://drupal.org/project/multiple\_email

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


# Question
Title: Auto-filling a form field with the sender page title
Basically, the user clicks on a "Book" button, which is in a "Trip" node; the user then is redirected to a booking form (Webform) where he will fill in basic info for the reservation. I need to auto-fill a field in the form with the title of the node from where the user was redirected.

I tried to use the Rules module and I successfully made the redirection process, but I'm stuck on how to prepopulate the field with the title of the sender page.

I've never developed a custom module, I'm new to Drupal but I have programming experience, so if there is a straight way to accomplish this (contrib modules) that would be great. Alternatively, I'm not afraid of digging into code.

# Answer
You could find the referring page by using $\_SERVER\['HTTP\_REFERER'\] in PHP and then lookup the node by using drupal\_lookup\_path and menu\_get\_object. At that point you then have the node object from the previous page and you can use "$node-\>title" to get the title you want.

```
$request_url =  $_SERVER['HTTP_REFERER'];
$host = $_SERVER['HTTP_HOST'] . "/";
$request_uri = explode($host,$request_url);
$path = drupal_lookup_path("source", $request_uri[1]);
$node = menu_get_object("node", 1, $path);

```

As far as how you put this into the webform, you could alter the submission using a hook or a specific component. I'm not aware of a module that lets you put PHP into a webform component. Potentially the Computed Field module (https://drupal.org/project/computed\_field) could be of help.

Help from: How to get a node by its url alias?
> 0 votes

---
Tags: 7, rules, webforms
---


# Question
Title: How to create tabbed menu consisting of views and a contact form while having unique paths for each tab?
I'd like to create a tabbed menu of my support page like this:

```
           | FAQ | Contact us |

```

I'm using views accordion to create a view for my FAQ, but I'm using the contact form for my Contact form.

How can I combine them in a same menu tab while having each tab have its own path so that I can theme the current tab using a:active and for seo purposes?

I've tried quicktabs and block tabs, which work but doesn't give me separate paths. The node tabs module comes close but it doesn't seem to be able to work with a form.

I'm thinking I might need to build it programmatically using a custom module and hook\_menu: How can I create a simple tab? but I'd prefer not going into that if possible

# Answer
> 1 votes
If your "Contact us" page is not the default Drupal contact page, but a webform (i.e. a node), you could use views to create tabs (see this tutorial, for example). In that case you would create a view that shows just the one webform node and configure it the way that it is displayed as a tab - and the FAQ view as default tab.

I suppose that there is also a workaround embedding the contact form instead of using a webform node.

# Answer
> 0 votes
You can achieve that using Quick Tabs.

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*. You can create a block on your site containing multiple tabs with corresponding content.

---
Tags: 7, routes
---


# Question
Title: How can I use View modes for entity without bundles?
I have an entity that has no bundles(ie. it has itself as a - 1 - bundle) and I need to be able to use View modes for it.

My understnading is that the Field UI needs the 'bundle of' entity to exist in order to attach itself to it.

Is somehow possible to get around this?

Should I file an issue on d.org?

# Answer
tl;dr: If your entity annotation contains an admin form, field UI will work.

This is what they would mark on Quora as 'Questions That Contain Assumptions' and those questions usually contain false assumptions. In this case 'bundle of' doesn't even appear in the field UI directory anywhere. Instead, here's how I'd found the answer to your question -- it's not hard at all. First look in `core/modules/field_ui/field_ui.routing.yml`. Nothing. Well, it's dynamic, if it's dynamic then it's going to be in `core/modules/field_ui/lib/Drupal/field_ui/Routing/` and it is. Let's look in `RouteSubscriber.php` in that directory:

```
foreach ($this->manager->getDefinitions() as $entity_type_id => $entity_type) {
  $defaults = array();
  if ($entity_type->isFieldable() && $entity_type->hasLinkTemplate('admin-form')) {

```

Now a quick counter check on the `Node` annotation and see, under `links`, there's `"admin-form" = "node.type_edit"` so that's that.
> 3 votes

---
Tags: entities, 8
---


# Question
Title: Find top and average value from input field text
H i have like 2000 nodes with field type - text field.

Purpose of that field is to be filled with best time that someone had on race. Format is something like 02:43:02 ( keep in mind that is text field and not time picker ).

Now i have been asked to show top 10 times, and average time, and im not sure how to do math here if that is text field?

Can views find top 10 times from text field?

# Answer
The PHP function strtotime() might help you here:

> strtotime — Parse about any English textual datetime description into a Unix timestamp

For example, you could create a computed field and use that function to convert the text input to a time value.

But as you're using a text field and not a date/time filed, I doubt that you'll be able to get all values correctly (because user input can differ enormously).
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I link an image field to an pdf file
I have a challenge in linking my image to a pdf file. I have a content type with 2 fields, image field which will contain the cover picture and an attachment field which is file of type pdf.

In my view am trying to link an image to attachment so that when a user clicks on the image it open a pdf file.

In some instances where am just using description to link to a pdf file, this what I have put in my Global PHP(Description) output code in my view. nid, 'filename.pdf'); ?\> As soon as click on the description my pdf opens. works fine

But I need to do the same thing with my image, to just click on image then should open my pdf file. Any idea???

# Answer
> 5 votes
Hope this will help you,

In Drupal 7 you can use VIEWS **Rewrite results** to link an IMAGE to a PDF file.

Steps:

* In PDF field, exclude it and change the **format** to "**URL of file**"
* Go to your **VIEW** -\> **Image field** and under **Link image to** select **NOTHING**
* And then go to **Rewrite results** and check **Output this field as a link** and give the path of the PDF file.
* You can also use **TOKENS** by using **Replacement patterns** for PDF file path name

# Answer
> 1 votes
You may want to try the Image link to file module, which I developed because I had the same problem. The module is very small and very simple to use. It is stable, even though it's an alpha release.

Hope this helps

—Alex

# Answer
> -2 votes
You can go to your view\>Click on the fild name(image) \>After you select from list **Link image to** the option File.

And that's it.

---
Tags: views
---


# Question
Title: Entity Reference field fails when choosing from more than 1000 items
I've set up my Drupal system to allow users to select from a list of locations, which are registered as nodes.

However, after importing my ~6000 locations the field lookup no longer works with the following error:

> PDOException: SELECT revision.vid AS vid, base.uid AS uid, revision.title AS title, revision.log AS log, revision.status AS status, revision.comment AS comment, revision.promote AS promote, revision.sticky AS sticky, base.nid AS nid, base.type AS type, base.language AS language, base.created AS created, base.changed AS changed, base.tnid AS tnid, base.translate AS translate, revision.timestamp AS revision\_timestamp, revision.uid AS revision\_uid FROM {node} base INNER JOIN {node\_revision} revision ON revision.vid = base.vid WHERE (base.nid IN (:db\_condition\_placeholder\_0, :db\_condition\_placeholder\_1, :db\_condition\_placeholder\_2, *... (trimmed) ...* :db\_condition\_placeholder\_5915, :db\_condition\_placeholder\_5916)) ...
>
> SQLSTATE\[HY000\]: General error: 1795 OCIStmtExecute: ORA-01795: maximum number of expressions in a list is 1000 (ext\pdo\_oci\oci\_statement.c:148)

I am using an Oracle backend, so it's possible this error is a quirk of Oracle. But in general, is the Entity Reference module intended to allow lookups on large lists of nodes? Or should I move to another module such as the References module?

# Answer
> 0 votes
I haven't tested whether Oracle's performance with Entity Reference is substantively worse than another backend such as MySQL.

However, implementing the workaround detailed here and converting a Drupal user.module query to a dynamic form to also implement partitioning worked, albeit with a 50 second execution time and a hugely increased PHP memory requirement. This is because of multiple complex queries across the whole node set.

Switching to use of the references module and the node\_reference content type has vastly improved performance.

---
Tags: entities, nodes
---


# Question
Title: Features_extra: after enabling fe_block, no Machine Name field appears on block edit form
I installed and enabled fe\_block 6.x-1.x-dev, but when I reload one of my blocks' edit form, no machine name field appears. I tried clearing the cache; no dice.

What's missing? Thanks.

# Answer
The `fe_block` module only allows exporting blocks represented in the `boxes` table — those created via the `admin/build/block/add` user interface.

Exportable blocks will have `block` as the second-to-last component of the admin URL:

Blocks created using, say, Views, or a module's `hook_block()` implementation, however, are not exportable using `fe_block` — it doesn't make sense to export blocks such as those, since Views provides its own export mechanism, and other module-owned blocks are already in code to begin with.
> 1 votes

# Answer
You are using a module that is in unstable version, and that's version is almost 2 years old without any work on it. So "missing" part is 2 years of maintenance, 2 years when Drupal changed and this module did not follow.

It's a good practice to avoid dev versions that are updated less than once in a month. Using dev versions updated rarer than Drupal's minor version number is asking for trouble.
> 0 votes

# Answer
I just ran into this in drupal 6.31. Does your user have permission to edit Features-related stuff? (See https://drupal.org/node/520310)

(I didn't have permission to add that permission on my site, but disabling permissions by temporarily removing the check && user\_access('administer features') from the two lines that had it in sites/all/modules/features\_extra/fe\_block.module does make the machine name UI appear when editing blocks.)
> 0 votes

---
Tags: 6, blocks, features
---


# Question
Title: Is there a Drupal module that can create a content type from an SQL Query or a CSV file?
Is there a Drupal module that can create a content type from an SQL Query or a CSV file?

I am looking for a module which can carry out the process itself, at least based on simple types like strings, dates, floats, and integers, something that can use an SQL table definition to create it.

Another option is one that provides a form similar to the table creation dialogs in database applications like SQLite Manager or Microsoft Access, where you specify the name of the field, the size and the type and the system goes off to carry out the task.

# Answer
A module referred to as ECK has the functionality you're looking for.

Although, it works in the entity system to create new entity types. You might be looking for something to pragmatically create entity bundles (node content types). I would suggest researching the difference between Entity's and Bundles if you're not familiar.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Minimum password length for registration form
For user registration, I have disabled "Require e-mail verification when a visitor creates an account." to allow user create their own password at the registration form. Now, I wonder how to limit the password characters to minimum 6? I have tested several times, it seems drupal doesn't restrict any password characters even user keys in just 3 characters.

# Answer
> 0 votes
You might be looking of Password policy module

> Features
>
> Current constraints include:
>
> * Complexity constraint
> * Digit constraint
> * Letter constraint Letter/Digit
> * constraint (Alphanumeric)
> * **Length constraint**
> * Uppercase constraint
> * Lowercase constraint Punctuation constraint
> * Delay constraint Username
> * constraint Digit placement constraint
> * History constraint (checks
> * hashed password against a collection of users previous hashed
> * passwords looking for recent duplicates)

Also checkout this Quick demo.

---
Tags: users
---


# Question
Title: Pathauto , Using Body Value for URL Alias
I am trying to use the use the node body value for URL alias using Pathauto . I am trying the below path pattern : content/\[node:body:?\] But this doesn't seem to have any effect . I have tried this also : content/\[node:body:Text\] ..yet no result .

Any pointers to resolve this is highly appreciated .

Thanks

# Answer
Without questioning why you would want body text in a URL alias you should be able to access this by using:

```
[node:body:value] for the value
[node:body:summary] for the summary

```
> 0 votes

---
Tags: path-aliases
---


# Question
Title: $_POST returns empty value in custom service
created a custom service resource to catch some data from the user through post method. but while I am accessing the service ie http://dev.localhost:8082/rest/send\_mail/retrive.json

Query: curl -X POST -H "Accept-Encoding: gzip" -H "Content-Type: application/json; charset=utf-8"

sending the data in POST is : { "nid" :"1834", "recipient" :"charubachi.rath@abc.com", "sender":"charubachi.rath@abc.com", "subject": "xyz", "body":"a" }

How to accept the data

in my .module file

```
<?php

/**
 * Implementation of hook_services_resources().
*/
function send_mail_service_services_resources() {
 $api = array(
'send_mail' => array(
  'operations' => array(
    'create' => array(
      'help' => 'Drupal 7 Services 3 test',
      'file' => array('file' => 'inc', 'module' => 'send_mail_service'),
      'callback' => '_send_mail_service_create',
      'access callback' => 'user_access',
      'access arguments' => array('access content'),
      'access arguments append' => FALSE,
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('data' => 'nid'),
          'type' => 'int',
          'description' => 'The nid of the node to get',
        ),
        array(
          'name' => 'recipient',
          'type' => 'string',
          'description' => t('recipient'),
          'source' => array('data' => 'recipient'),
          'optional' => TRUE,
          'default' => '0',
        ),
        array(
          'name' => 'sender',
          'type' => 'string',
          'description' => 'sender',
          'source' => array('data' => 'sender'),
          'optional' => TRUE,
          'default' => '0',
        ),
        array(
          'name' => 'subject',
          'type' => 'string',
          'description' => 'subject',
          'source' => array('data' => 'subject'),
          'optional' => TRUE,
          'default' => '0',
        ),
        array(
          'name' => 'body',
          'type' => 'string',
          'description' => 'body',
          'source' => array('data' => 'body'),
          'optional' => TRUE,
          'default' => '0',
        ),
      ),
    ),
  ),
),
);
 return $api;
}

```

in my call back function when I am trying to print $\_POST I am getting empty values.

# Answer
You are passing every element as individual element, so you can't get these values in $\_POST array. I have executed your code at my end and retrieve each element value by following call back function.

```

function _send_mail_service_create($nid, $recipient, $sender, $subject, $body) {
  echo "nid => ".$nid;
  echo "\nrecipient => ".$recipient;
  echo "\nsender => ".$sender;
  echo "\nsubject => ".$subject;
  echo "\nbody => ".$body;
}

```

**Output:** `nid => 1834
recipient => charubachi.rath@abc.com
sender => charubachi.rath@abc.com
subject => xyz
body => a`

If you want to have these values in an array then you can use this in following way:

```

 /**
   * Implementation of hook_services_resources().
   */
  function send_mail_service_services_resources() {
    $api = array(
      'send_mail' => array(
        'operations' => array(
          'create' => array(
            'help' => 'Drupal 7 Services 3 test',
            'callback' => '_send_mail_service_create',
            'access callback' => 'user_access',
            'access arguments' => array('access content'),
            'access arguments append' => FALSE,
            'args' => array(
              array(
                'name' => 'title',
                'optional' => FALSE,
                'source' => 'data',
                'type' => 'string',
                'description' => 'The data collected through JSON',
              ),
            ),
          ),
        ),
      ),
    );
 return $api;
}

function _send_mail_service_create($arg) {
  print_r($arg);
}

```

**Output:** `Array
(
 [nid] => 1834
 [recipient] => charubachi.rath@abc.com
 [sender] => charubachi.rath@abc.com
 [subject] => xyz
 [body] => a
)`
> 0 votes

---
Tags: services
---


# Question
Title: Which parameter do I need to pass for user registration?
I have first name, lastname, email, password, confirmed password and gender for user registration like facebook registration when I visit https://example.com/my\_services/user/register.

Then I get the error "You are not allowed to change your username" when I select put method. How do I find the keys of that fields so that I send key and values?

I don't know which parameter I need to send with the URL.

# Answer
> 0 votes
```
$user_data["field_name_first"]["en"][0]["value"]='testranjeet8';
$user_data["field_name_last"]["und"][0]["value"]='testgholave8';
$user_data["mail"]="testranjeet12@example.com";
$user_data["pass"]["pass1"]="test123458";
$user_data["pass"]["pass2"]="test123458";
$user_data["field_gender"]["en"]="Male";

```

Just pass the parameter you will get the result .I had problem with android side that they are not passing value correctly finally i got answer

# Answer
> 0 votes
Sample JSON that you can use with poster:

```
{
    "name": "priya1",
    "pass": "priya1",
    "pass1": "priya1",
    "pass2": "priya1",
    "mail": "priya1@gmail.com",
    "conf_mail": "priya1@gmail.com",
    "field_name_first": {
        "und": [
            {
                "value": "ranjeet"
            }
        ]
    },
    "field_name_last": {
        "und": [
            {
                "value": "gholave"
            }
        ]
    },
    "roles": [
        "3",
        "4"
    ]
}

```

---
Tags: 7, services
---


# Question
Title: Can 1 FullCalendar show dates from more than one content type?
I want to show "dates" and "Board Meetings" on my FullCalendar. How?

Background info:
In D7 I created a Calendar using the wizard, which shows titles and dates/times of events that I create using a content type "Date" that the wizard created. Works great. But then I added another content type "Board Meeting" with a date field, the Board meetings only show up on the preview, not on the calendar month view itself. How to get them to show on the calendar?

Dave N

# Answer
Well I found the answer before I even finished posting this. Thanks to those "Similar Questions" over there on the right...

I got my answer from How to use multiple content types in a "Calendar" View sorting by the field type of "Date"?
> 0 votes

---
Tags: 7, datetime, javascript
---


# Question
Title: To pass the tid as an array value in callback funtion
Am using drupal 7 site,am using a callback function to get the nodes list tagged to the particular tid, the process is if i gave the tid value 25 it must return the nodes list which are tagged to this tid.As far this it is working fine.I wish to give the tid as multiple values ie as an array value, the thing am expecting is , if I give 25,17,28 (these are tid values) the result must be the nodes tagged to these tid's .Below is my function

```
'actions' => array(
        'selectNodes' => array(
          'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/taxonomy_resource'),
          'help'   => t('Returns all nodes with provided taxonomy id.'),
          'access arguments' => array('access content'),
          'callback' => 'taxonomy_service_select_nodes',
          'args'     => array(
            array(
              'name'         => 'tid',
              'type'         => 'string',
              'description'  => t('The vocabulary ids to retrieve, separated by comma.'),
              'source'       => array('data' => 'tid'),
              'optional'     => FALSE,
            ),
            array(
              'name'         => 'pager',
              'type'         => 'int',
              'description'  => t('Whether the nodes are to be used with a pager (the case on most Drupal pages) or not (in an XML feed, for example).'),
              'source'       => array('data' => 'pager'),
              'optional'     => TRUE,
              'default value'=> TRUE,
            ),
            array(
              'name'         => 'limit',
              'type'         => 'int',
              'description'  => t('Maximum number of nodes to find.'),
              'source'       => array('data' => 'limit'),
              'optional'     => TRUE,
              'default value'=> FALSE,
            ),
            array(
              'name'         => 'order',
              'type'         => 'int',
              'description'  => t('The order clause for the query that retrieve the nodes.'),
              'source'       => array('data' => 'order'),
              'optional'     => TRUE,
              'default value'=> array('t.sticky' => 'DESC', 't.created' => 'DESC'),
            ),
          ),
        ),
      }

```

can anyone please tell me how can I pass this tid value as array to the callback function used here?

# Answer
I am sharing here some dummy data with you, it might help you.

```

{
    "tid": "25,17,28",
    "pager": 1,
    "limit": 5,
    "order": "desc"
}

```

```
   array(
                  'name'         => 'order',
                  'type'         => 'string', // it should be string because it can be either ASC or DESC
                  'description'  => t('The order clause for the query that retrieve the nodes.'),
                  'source'       => array('data' => 'order'),
                  'optional'     => TRUE,
                  'default value'=> array('t.sticky' => 'DESC', 't.created' => 'DESC'),
                ),

```

// Call back function

```
function taxonomy_service_select_nodes($tid, $pager, $limit, $order) {
  $tid_collection = array();
  $tid_collection = explode(',', $tid); // Here your tids are in array format and you can use in your code accordingly.
  echo $pager;
  echo $limit;
  echo $order;
}

```
> 0 votes

---
Tags: 7, services
---


# Question
Title: How can I send an email using the Rules module to a user specified via Entity Reference in a Content Type?
This question is similar to others posed, but all the answers I can find appear to refer to Drupal 6, with CCK fields.

I am using Drupal 7 with the Rules module enabled.

I have created a custom Content Type and one of the fields is an Entity Reference, which allows a registered user to be selected as the Content Type is added. Essentially an administrator can associate a registered website user with the content item being added.

I need to email the referenced user when another field value within the Content Type is changed. I'm sure this is possible via the Rules module, but I cannot get the mail to send.

It must be a fairly common situation, emailing a referenced user when a field value is updated, but I have looked at the online notes for the Rules module and cannot find an example of this particular use case.

Has anybody managed to achieve the same outcome as I am seeking?

Thank you.

# Answer
After some trial and error, I found how to reference the field.

Within the Conditions section of the rule, I needed to:

* Add "entity has field"
* Enter "node" within the Data Selector box
* Select the entity reference field within the Value dropdown

I was then able to refer to the field required, with the mail parameter appended, directly from a standard Send Mail action (i.e. \[node:MY-REFERENCED-FIELD:mail\]).
> 2 votes

# Answer
I would do a custom module to add a function to run in the "To" value field of your rule. Try:

```
<?php

function my_module_user_lookup($nodeid) {
    $node = node_load($nodeid);
    $userid = $node->YOUR_FIELD_NAME_HERE['und'][0]['target_id'];
    $user = user_load($userid);

    return $user->mail;
}
?>

```

Then in your rule add this php function (make sure to run it as PHP to your To field. I believe `<?php my_module_user_lookup($node->id); ?>` should do it. From there you just need to add the logic for sending when the node is updated, but that is all apart of rules.
> 0 votes

---
Tags: 7, rules, entities, emails
---


title: Using "Or" opertor in EntityFieldQuery

text:
# Question
Title: Using "Or" opertor in EntityFieldQuery
could you help me to fix my problem? note: each user have two field (fields are taxonomy reference)

I want to get two fields with `OR` condition the output of my code returns in the shape of `AND` result

here is my code :

```
 $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_software_abilities', 'tid', $abilities, 'IN')
    ->fieldCondition('field_other_abilities', 'tid', $abilities, 'IN');
    $result = $query->execute();

```

I read an article about using addtag and `hook_query_tag_alter()` but I can't use it

# Answer
> 0 votes
EntityFieldQuery does not support `'OR'` operators. There is a workaround presented here 'OR' Queries with EntityFieldQuery where an `'OR'` operator is added.

---
Tags: database
---


# Question
Title: Inserting tokens into a text field, such as body
For many years I've used the excellent token filter module. However, viewing development activity on the module, (Seeking co-maintainers, Maintenance fixes only, and last updates are over a year ago) suggests that this module's future may not so bright. Which, in turn, suggests that there is another or better way of achieving similar functionality? For example, I commonly use token filter to construct the current year for the copyright mark. Other examples include referencing the site email or slogan.

What's the best "future-proof" method for inserting token-like content into text fields?

# Answer
> 2 votes
I think you are looking for Advanced Text Formatter module which allows you to enable token replace on fields you choose. The mantainer says it would have a Drupal 8 version too.

---
Tags: 7, entities, tokens
---


title: Create product programmatically

text:
# Question
Title: Create product programmatically
I have a product with a custom field, according to this. I know I can create product with

```
$cp = commerce_product_new('product');
$cp->is_new = TRUE;
$cp->revision_id = NULL;
$cp->uid = 1;
$cp->status = 1;
$cp->created = $cp->changed = time();
$cp->sku = $product[sku];
$cp->title = $product[name];
$cp->language = LANGUAGE_NONE;
$cp->commerce_price = array(LANGUAGE_NONE => array( 0 => array(
 'amount' => $product[sale_price] ? $product[sale_price] : $product[retail_price],
 'currency_code' => 'USD',
)));$product[retail_price];
commerce_product_save($cp);

```

but I have some custom field.

How can I create a Drupal Commerce product programmatically with full custom fields?

Is `$cp->myfield1='22';` sufficient?

# Answer
A commerce product is an entity like any other, so...

```
$cp->field_my_field[LANGUAGE_NONE][0]['value'] = '22';

```
> 7 votes

# Answer
Just a tweak: the create method on the product controller already has some defaults so no need to add things like is\_new or status.

```
  public function create(array $values = array()) {
    $values += array(
      'product_id' => NULL,
      'is_new' => TRUE,
      'sku' => '',
      'revision_id' => NULL,
      'title' => '',
      'uid' => '',
      'status' => 1,
      'created' => '',
      'changed' => '',
    );

    return parent::create($values);
  }

```

So I'd just do:

```
$cp = commerce_product_new('product');
$cp->uid = 1;
$cp->sku = $product[sku];
$cp->title = $product[name];
$cp->language = LANGUAGE_NONE;
$cp->commerce_price = array(LANGUAGE_NONE => array( 0 => array(
 'amount' => $product[sale_price] ? $product[sale_price] : $product[retail_price],
 'currency_code' => 'USD',
)));$product[retail_price];
$cp->my_field[LANGUAGE_NONE][0]['value'] = 22;
commerce_product_save($cp);

```
> 3 votes

---
Tags: commerce
---


# Question
Title: Get webform values in page which is action for this webform
I have created a form using webform in Drupal 6. I have set a action URL like `node/15` a new node. When form is submitted it will be redirect this node. I want to display all values which are filled by user at this page. Please help.

Thank you

# Answer
> 0 votes
You can use `hook_form_alter` and add your custom submit handler.

```

    /**
     * Implements hook_form().
     */
    function hook_form_alter(&$form, $form_state, $form_id) {
        if ($form_id == 'WEBFORM_ID') {
            $form['#submit'][] = 'custom_webfrom_submit';
        }
    }

    /**
     * Implements webform custom handler
     */
    function custom_webfrom_submit($form, &$form_state){
        //get the values here $form_state['values']
    }

```

---
Tags: webforms
---


title: Display only the first n field items

text:
# Question
Title: Display only the first n field items
Goal: For a multiple-value field, display only the first n (e.g. the first 3) field items.

E.g. only the first 3 of 10 images in an image field.

I realize this is possibly by writing a custom field formatter. But I wonder if there is an existing solution available. Also to mix this up with existing formatters.

Hint: I use Display Suite, so solutions which involve that are welcome.

# Answer
There is a setting how many items to display in Display Suite. The setting is demoed in this screencast: http://youtu.be/fa56OZcJq-4?t=1m20s
> 3 votes

# Answer
Specifically for images there's the Image Delta Formatter module

> This module provides a custom formatter for imagefields, that allows the user to specify which values (deltas) should be displayed.
> 2 votes

# Answer
If you are using Manage Display to display fields, you can try out Field multiple limit

UI example

> This is a simple module that provides settings to limit the number of values to display on fields with multiple values.
>
> The module extends the field display settings for fields which permit multiple values. Site administrators can specify how many values to display for each display mode (e.g. teaser). Optionally, an off-set can be specified to skip some values.
> 2 votes

---
Tags: entities
---


# Question
Title: Styling views table - Toogle row class on click
I have a view which is shown as table. I would like to add a css class to entire row, once the user has clicked somewhere on the row.

With views i added '.baza-pregled-strank-row' class to each row. Below is my jquery code, which is successfully loaded, but not doing what it should, because once i click on the view-field, the class is not aded to the row. Big thanks.

```
(function ($) {
$('.view-field').on('click', function(e) {
      $('.baza-pregled-strank-row').toggleClass("highlight");
      e.preventDefault();
    });
}(jQuery));

```

# Answer
> 1 votes
First of all you need to add custom class to your VIEWS wrapper and also for TABLE ROW. I have added `my-view-wrapper` for the VIEWS and `row-wrapper` for TABLE ROW

* Add CLASS to your VIEWS
* Add CLASS to your TABLE ROW

```

(function ($) {
  Drupal.behaviors.viewRowHighlight = {
    attach: function (context, settings) {
      $('.my-view-wrapper .row-wrapper').click(function(e){
        $(this).toggleClass('clicked');
      });
    }
  };
})(jQuery);

```

# Answer
> 0 votes
The class Views adds to the fields is called views-field. This code would toggle the class hightlight for each field (cell) in the table.

```
Drupal.behaviors.highlightViewsField = {
  attach: function (context) {
    $('.views-field').on('click', function(e) {
      $(this).toggleClass("highlight");
    });
  }
}

```

If you want to toggle the row you would do something like

```
Drupal.behaviors.highlightViewsRow = {
  attach: function (context) {
    $('.view-content tr').on('click', function(e) {
      $(this).toggleClass("highlight");
    });
  }
}

```

# Answer
> 0 votes
I followed the documentation that Mołot suggested and managed to make it work. Below is the code with dummy classes, targeting the views row inside views wrapper. Thanks for all the help guys.

```
(function ($) {
  Drupal.behaviors.views_row_highlight = {
    attach: function (context, settings) {
      $('.views-table-wrapper .views-table-row', context).click(function () {
        $(this).toggleClass('highlight');
      });
    }
  };
})(jQuery);

```

---
Tags: views, javascript, theming
---


# Question
Title: Drupal multi-site Aegir caching strategy
We are migrating many sites from various content management systems onto a single Drupal/Aegir platform. We used to have a high density of sites on the same servers and Aegir definitely makes managing high density Drupal sites easier. Unfortunately having the same density of Drupal sites on scaled up hardware is leaving us with slower response times for the same amount of traffic. The platform/codebase is itself a bit of a beast, with some sites having 250+ modules enabled and response times stretching to 30+ seconds with Drupal caching disabled. The shared codebase acts as a sort of menu for business divisions to be able to choose features/themes from. With APC, Drupal cache and memcached running we still struggle on ocassion.

I think it makes sense to look at building up a caching layer in front of Apache-Drupal-Aegir before we start scaling the application layer horizontally. Aegir brings a big benefit to managing multiple sites and ending up with multiple Aegir instances takes away some of that benefit. In particular I like the idea of being able to cache some/all of the dynamic content for anonymous users in case the Aegir server is unavailable for any reason.

The options as I see it are:

* Drupal boost module. Probably the easiest to setup but unfortunately does not appear to work with Aegir without some manual patching.
* nginx as a reverse caching proxy. SSL support, easier to configure
* Varnish as a reverse caching proxy. No SSL support, more difficult to configure
* Ditch Apache and run Aegir on nginx/PHP-FPM. I prefer running Aegir on Apache at this stage as it will be easier for other engineers to troubleshoot.

We also have an HAProxy installation which load balances (actually failover/fault tolerance) for other applications, so we could always terminate the SSL at HAProxy and failover across multiple nginx or Varnish instances, with a single Drupal application server at the back. Though that means requests jumping through 3 layers to potentially hit the back-end, which doesn't sound too great.

Questions:

1. I'm tending to go for nginx as the reverse caching proxy because of simple configuration and management by other users and a single entry point for SSL management.
Is there any reason why I should choose Varnish instead?
2. Is nginx able to serve cached "dynamic" content to anonymous users in the eventuality of the back-end Drupal server being down?
Or is it purely restricted to static content such as images, JS, CSS etc?
3. What about having HAProxy on top of that, so we can failover between multiple nginx instances?
Or is it insane to have requests potentially going through 3 layers of proxy to reach the Apache/Drupal back-end?

# Answer
> 1 votes
1. Use what your comfortable with for maintenance and configuration.
2. Probably, depending on config. (I don't use nginx)
3. Not crazy, it allows for a very quick switch time to another webserver.

I have varnish combined on my webservers with a separate apache reverseproxy doing ssl termination.

A little custom hook triggers a reverse proxy update on a Aegir migrate task.

---
Tags: caching, proxies
---


# Question
Title: Autocomplete field - fill the selected id into another form element (eg. hidden field)
this was already asked here Handling id from autocomplete field

but still without answer: I have an autocomplete field which uses geonames query to search cities. After value is selected I want the city name and admin area to fill into the autocomplete field, and to fill geoname\_id of selected value into another (hidden) field. I don't want the geoname\_id to be visible - it looks kind of ugly...

I've tried to hack the autocomplete.js and added following line

$("#search-geoname-id").val($(this.selected).data('autocompleteValue'));

into Drupal.jsAC.prototype.hidePopup function

then also tried

$("input\[id=search-geoname-id\]").val($(this.selected).data('autocompleteValue'));

but both without effect :/

Thanks for your help, Tomas

# Answer
> 3 votes
I've found solution, so I'll share it with others:

Both options in the question were correct. I just expected that the new value of hidden field will be visible through "see source code" which it's not. When I check the $form\_state\['values'\]\['geonameid'\] it is filled correctly.

The complete solution:

1) In Drupal.jsAC.prototype.found I've filled the 'autocompleteValue' with value instead of key, and added new data 'autocompleteKey' which I've filled with key, surprisingly :)

2) In Drupal.jsAC.prototype.hidePopup just added $('input\[id="search-geoname-id"\]').val($(this.selected).data('autocompleteKey'));

Hope this helps to someone in future.

P.S. I know modifying core functions is not the cleanest way to do things, but it works.

---
Tags: ajax
---


# Question
Title: Use entity relationship to exclude records on view
I have a content type, lets say PRODUCT I have another type, PURCHASE, which points to PRODUCT with an entity reference

It is simple using views relationships to get PRODUCTS that have PURCHASE relationships, get totals, all kind of groovy things...

**BUT**

How do I get all PRODUCTS without any PURCHASEs? So create a view with a relationship "Entity Reference: Referencing entity" but exclude all those that are referenced by a PURCHASE?

Contextual filters have that nice negate checkbox, but that does not help me under relationships.

# Answer
> 1 votes
You should be able to add a contextual filter, negated, that uses the relationship that you want.

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


# Question
Title: Unable to find out how a content type node is getting themed
I have a drupal 7 installation with a paid template which I am trying to tweak. The template has a demo installation, which has a `content-type` named 'Team'.

So I created a bunch of content with type as Team. Now if I create a `Basic Page` content and in the `URL Alias` if I give '**content/team**', then it shows a grid view of all the team content I created (each team members photo, name & designation with a read more button).

There is a `node--view--team.tpl` file available in the codebase.

My problem starts when I try to rename the content-type called `Team` to 'Students`(machine name was also changed to`students`). After renaming I renamed the tpl file to`node--view--students.tpl\`. In the URL alias, if I give any url other than '**content/team**', all I get is an empty page. If I change the URL alias to '**content/team**' - everything works!!

This is driving me mad, I know I cannot get a complete answer since I am tweaking a custom theme, but any pointers would be greatly appreciated!

# Answer
> 0 votes
I have run into this before; it's the result of some bad practices commonly used by the commercial Wordpress—ehem, wait, I mean, Drupal—themers.

The culprit code is probably in a function in `template.php` or similar. Try searching the entire theme codebase for "team" - if you are on a Unix system you can use the grep command like this

```
grep -r "team" /path/to/theme

```

This might help you find the dirty function.

---
Tags: nodes, theming, uri
---


title: Content type to Drupal commerce

text:
# Question
Title: Content type to Drupal commerce
I currently have a Drupal site with a content type of Training where a variety of different training courses are listed. We are looking to sell these courses with Drupal commerce.

How do we go about turning these courses to items visitors can buy?

EDIT:

OK. I think I may have it now. Sorry for the poor comment, it was late and I hadn't messed around with commence much - Now I have!

My query is how and where best to have the fields, which I believe is a common Commerce question

Each Training has the fields of: \- Title \- Body \- Who should attend this course \- Course Structure \- Dates

How is best to sort the content fields for a Training course:

1) Product Variation type to have all the fields above - So each course will essential be a product variation?

OR

2) Content type to have the fields with only reference to product for the price?

My reasoning for this question is I don't have the experience to know what is best for future development where I might be looking at managing available places (Which I fore see done with stock?)

# Answer
> 0 votes
I recommend making a sandbox install of Commerce Kickstart to see how they set up "Product display node" and "Product entities" to work together. Your "Training" content type would be the Product display node, and each course offering would be the product. To replicate this on your existing site, the high-level approach (you will need to sort details) is this:

* Install Commerce and create references from Commerce `product` entities to your `Training` content type
* Create some `products` that represent your courses. You can add custom fields where needed.
* Display the `products` that are referenced to the Training nodes using Views module or methods similar to those used in Commerce Kickstart
* This should give you a list of courses on each Training node that can be added to Commerce cart.

---
Tags: commerce, nodes
---


title: Views Grouped filter returns empty set

text:
# Question
Title: Views Grouped filter returns empty set
I am using Drupal 7 and Views 7.x-3.7.

In a view I have an exposed filter "gender".

If I select the filter type as 'single', it works fine. But I want radio buttons rather than dropdown so I select 'grouped filter' option.

Then the filter renders as I like.

But it always returns an empty result set.

There must be a setting that I am missing. Can you please point me to it?

Thank you.

# Answer
> 0 votes
Well, I could not find a way to make the grouped filter work for me. The solution I found was to use the Better Exposed Filters module. It is quite easy to configure. It worked smoothly for me.

---
Tags: views
---


title: Lock editing on node except for Admin

text:
# Question
Title: Lock editing on node except for Admin
I have a content type with a select field. When the selected value from that field is "Locked", I would like to lock editing on that node for all roles except admin (or other role I choose to be admin). Then if the admin selects a different value, I would like to unlock editing on the node. For this reason it seems that rules are the best way to trigger an action like this. I have the content access module installed, which allows targeted access permission both for content types, and individual nodes. But how can I combine the two parts to lock editing automatically based on the select list? If I couldn't do it automatically, is there some way to restrict all access per node?

Edit: This is possible with Rules and content access. There is an action provided by the content access module which will revoke access to a node based on role.

# Answer
It sounds like you could accomplish this with a combination of rules and user roles. I assume to don't want the node to be editable by anonymous users so set the rule to grant editing permissions to all users who have a particular role when the value of the field changes from locked to unlocked (or whatever your corresponding value is). If you want more granular control, (i.e. when a node is unlocked some fields are editable but others remain editable only by admin users), you'll need to install the field permissions module (https://drupal.org/project/field\_permissions.
> 1 votes

---
Tags: nodes, rules, users
---


title: Certain js File Not Working in Drupal

text:
# Question
Title: Certain js File Not Working in Drupal
I'm trying to render one div before another.

I've tested the js on my local machine to make sure it works by creating a simple page. The code is as follows:

```
<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
    <div id="QWERTY">
        <div class="content">
            <div class="field-name-field-image-one">IMAGE</div>
            <div class="body">BODY</div>
        </div>
    </div>
<script>$('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples</script>

</body>
</html>

```

I've added the following code to a js file on my Drupal site:

```
(function ($, Drupal, window, document, undefined) {

    $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples

})(jQuery, Drupal, this, this.document);

```

My .info file links to the js and it is loading. Other elements that require javascript are working too. I've even tried adding the script in the html.tpl file, but that did not work either.

The divs I am trying to affect are nested deep within the html markup, and have several classes applied to them, compared to the simple version I have made. Could that be the reason? Am I not being specific enough?

# Answer
> 0 votes
It's most likely because you're attaching the event before the DOM is fully loaded (so the element you're trying to attach to doesn't exist yet). In your example HTML the JS is included *after* the DOM is loaded which is why it works.

Try this:

```
(function ($, Drupal, window, document, undefined) {
  $(function() {
    $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples
  });

})(jQuery, Drupal, this, this.document);

```

# Answer
> 2 votes
This will help you

```
(function ($) {

Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
  $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples

}

};
})(jQuery);

```

Read this https://drupal.org/node/756722 It will definitely help you.

---
Tags: javascript
---


# Question
Title: Sending a message to users of a flagged node when it is referenced
I have a site where a user can watch a node using the Flag module. Users can also reference the node and I wanted to set up a rule that when the node is referenced, a message is sent to all the flagged users of the original node notifying them that the node was referenced.

Can anyone help with the rule?

# Answer
> 2 votes
I would do this by creating a component of type `Rule` and calling this component from a separate rule that fires on one of the node save or node is updated events.

**First create the component** with *two* parameters of `node` type and name them "referencing\_node" and "referenced\_node". Create conditions `Content is of type [your content type]` for both referencing\_node and referenced\_node (this will bring in data selectors you need for the flagging user list and replacement patterns to construct your email subject and body). Next add a loop under `Actions` and choose the data selector for `referenced_node:flag [your_flag]:user (Users who flagged the entity with flag [your_flag])` and name the list "flagging\_users". Now add an action under your loop `System: send mail` and in your data selector for the To: field, use `[flagging-users:mail]` and also build your desired subject and message body from replacement patterns.

**Next create a rule that calls your component** with `React on event: After saving new content` of type \[your\_content\_type\] (you can also create a separate rule later to react on event `After updating existing content` however you need to build in conditions to prevent repeat email messages when no new references have been added). Now simply call your component as an action and provide your component's parameter with the variables from `node` (for "referencing\_node") and `node:your_reference_field_name` (for "referenced\_node").

I hope this helps you get the solution you are after.

---
Tags: rules, nodes, flags
---


title: Find all aliases for a given node

text:
# Question
Title: Find all aliases for a given node
I'm currently working with a client and running some scripts to generate reports (orphaned pages, etc). Right now, I need a way to get all possible registered aliases for a node. Right now, I'm using

```
$node = node_load($nid, NULL, TRUE);
$nurl = 'node/' . $nid;
$alias = drupal_get_path_alias($nurl);

```

I'm realizing, though, that the client has more than several pages where multiple aliases lead to the same node. Is there a function to retrieve an array of possible aliases?

Thanks!

# Answer
You can do it with a database query

```
$aliases = db_query('
  SELECT alias
  FROM {url_alias}
  WHERE source = :source
', array(':source' => 'node/' . $nid))->fetchAll();

```

You may need to modify things a little if you have a multilingual site to take the `language` column into account.
> 4 votes

---
Tags: path-aliases
---


# Question
Title: Can I migrate content to non drupal sites
I've been reading up on Drupal migration module recently and it seems like very powerful tool. That's why I was wondering is it possible to make migrations like `Wordpress -> Joomla` with Drupal only as intermediary between those two.

I tried to find some answers to this question but so far I've found only X -\> drupal migration

# Answer
Sure, but none of the pre-created classes are there for you such as `MigrateDestinationNode` where all the fields would be known by the Migrate system. Migrate is a general migration tool to move X to Y; but if you're new to it you may find trying to leverage it to the fullest capabilities as a migration tool somewhat difficult.

But, what I like Migrate is that it encapsulates the concept of a migration lifecycle:

1. get me the data from the source X
    * should I sanitize it before I grab it from source X ?
2. prepare to use the data
    * should i translate the data before making use of it in destination Y?
3. use the data in destination Y
4. do something with the data after using it (like create a cross reference)

Optionally, if the above steps are a migration of 1 element of data; you may configure pre and post migration tasks per migration as well.
> 1 votes

# Answer
It's probably better to try to go directly from one system into another. Placing Drupal in the middle is likely to add complexity to your migration strategy. But hey, if you find that it solves some issues that your migrations face, then I see no reason why it can't be done.
> 2 votes

---
Tags: migrations
---


title: Language select: how to set up

text:
# Question
Title: Language select: how to set up
In the current set up for every English page, there's a Spanish equivalent. Each page has its own unique URL.

Previously we had it set up so that you could click "Spanish" within the English page and it would call the Spanish URL and visa-versa.

We've been asked to make it global -a button at the top of the site.

Is there a clean way to detect what the Spanish equivalent is of the current page with PHP and make the switch?

# Answer
Locale module by default provides you a block, Language Switcher, that switches language of the site. It's a list of installed language.

If you like a fancy switcher, you can install this module: Language Switcher Dropdown

> Language Switcher Dropdown is a very simple module that exposes a new block, similar to the default Language Switcher block provided by Locale module. The new block allows site visitors to switch languages using a drop-down select list instead of using hyperlinks.
>
> The module also integrates well with Language Icons module if installed.

Here's an example
> 2 votes

# Answer
I use i18n serie for multilingual websites and there is a block language which works on its own for this purpose. I'm not sure to understand your multilingual setup, if it is not using i18n, I wouldn't say if you can use it independantly from the i18n suite. More info here: https://drupal.org/node/1279698
> 0 votes

---
Tags: entities, i18n-l10n
---


title: Callback function on change event

text:
# Question
Title: Callback function on change event
I need to execute some functions when a field value changes. I tried both Drupal AJAX framework and classical Jquery, but in both cases the callback function is not executed. Adding a Jquery .change() :

```
(function ($, Drupal, window, document, undefined) {
  $(document).ready(function(){
    $("#foo").change( function(){
      var selected_date = $(this).val();
      $.ajax({
        type: "POST",
        url: "MYURL/"+selected_date ,
        data: selected_date,
        success: alert( selected_date)
      });
    });
  })
})(jQuery, Drupal, this, this.document);

```

The Jquery works fine. Then

```
/**
* Implementation of hook_menu().
*/
function MYMODULE_menu() {
  $items['MYURL/%'] = array(
    'page callback' => 'MYMODULE_get_liberte_id',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}

function MYMODULE_get_liberte_id ($selected_date) {
  //DB queries and form alter or error messages here
}

```

I also tried with AJAX Framework :

```
//hook form alter
$form['foo']['#ajax'] = array(
  'callback' => 'MYMODULE_ajax_callback',
  'wrapper' => '.center-wrapper',
 );

function MYMODULE_ajax_callback($form, $form_state) {
  //is the function fired ???
  $commands[] = ajax_command_alert(t('MYMODULE_ajax_callback fired'));
  return '<div id="wrapper">'.date('Y-m-d').'<xmp>'.print_r($form_state['values'], true).'</xmp></div>';
  //DB queries and form alter or error messages here
}

```

`dsm($form)` shows that the field got #ajax attribute, but the callback function isn't executed.

I'm afraid I'm not on the right way, or at list I'm missing something :(

# Answer
The `#ajax['wrapper']` value should be id attribute, not a class, and without '#'. You can look about this here. The callback function should return a html content, a renderable array (which will replace the 'wrapper' on a call) or array of drupal ajax commands. You can try this and your code should work:

```
function MYMODULE_ajax_callback($form, $form_state) {
   $commands[] = ajax_command_alert(t('MYMODULE_ajax_callback fired'));
   return array('#type' => 'ajax', '#commands' => $commands);
}

```
> 1 votes

---
Tags: ajax, javascript
---


# Question
Title: Aegir tasks not running, after accidentally upgrading drush
I have a BOA installation where I accidentally run the command drush self-update. This overrided the aegir-comparible drush with a newer version. When I realized the issue, two days later, I replaced the new drush with old one (4.6-dev), found in the backups. The issue I am facing is that the tasks in the Aegir queue have stopped running. They give the message that they should run in the next cron, in about a minute, but then nothing happens. It keeps telling me that the last cron was run two days ago.

I have tried sudoing as Aegir and running the following:

drush vdel hosting\_queue\_cron\_running -y in case a semaphore is left, but this gives the message hosting\_queue\_cron\_running not found.

/var/aegir/drush/drush.php '@hostmaster' hosting-dispatch --debug and it runs fine, which means that the drush kicks the cron, but for some reason it doesn't reach Aegir

I tried to run barracuda up-stable in order to recover .drush, but it didn't recover it. I also tried to clean cache and rebuild registry. The time of the server is correct. Could you suggest some way to further debug the issue?

# Answer
> 1 votes
I found the solution. The problem occurred due to incomplete barracuda + octopus upgrade. One has to run the following commands to finish update

```
 barracuda up-stable
 octopus up-stable all

```

---
Tags: drush, aegir
---


# Question
Title: How to load entity by UUID from url argument?
Usually routes have `{entity_type}` in their routes's path and Drupal loads the entity by its ID.

I need to load entities by their UUID, so the path would look like /node/0ff3b31b-5abb-4377-bb00-af71882e38a4.

Is it possible to have a route that allows to load entities by their UUID? Do I need to create a `ParamConverter` class for this?

# Answer
> 4 votes
Yes, you need your own param converter for this, the default implementation can only load by UUID.

Loading by UUID is less performant as long as the primary ID is still a serial ID, this means that it first needs to do an entity query to fetch the ID and then load that.

---
Tags: entities, 8, routes
---


title: connect view to content type

text:
# Question
Title: connect view to content type
I am working on a drupal 7 installation. This has a content type called Team. In `Structure > Views` there is a view called Team content. In the folder structure there is also a corresponding view file named `node--view--team.tpl.php` which renders the Team content.

My task is to duplicate the content type to a new content type called Managers. So I created a new content type called Managers with all the same fields as in Team. I cloned the Team view as well. I then copied over the team tpl file into a new file named `node--view--managers.tpl.php`.

The problem I am facing is that the manager tpl file is not used when drupal renders the content. It falls back to node.tpl.php - however the design of this page is not how I want it.

What am I missing here? Is there any place in the code/ admin interface where I can specify that node--view--manager.tpl.php should be used instead of node.tpl.php?

Any pointers are greatly appreciated!

# Answer
> 1 votes
Your theme may create `node--view--CONTENTTYPE.tpl.php` but per content type theme suggestions are not provided out of the box. Your theme layer or a custom module typically provides the theme suggestion, there are a ton of tutorials online about this.

I recommend installing Devel Themer to inspect the View theme template file usage on the page for Teams. Then see why/if the Managers is failing by visiting that page.

Then look through your theme sourcecode and custom modules to see what is providing the `hook_theme` suggestions.

---
Tags: views, nodes, theming
---