# Question
Title: Configuring Lightbox2 to Pop-Up Images embedded in nodes
all my nodes have an image added to them (uploaded the usual way when creating new content for a content type), so when the viewer is viewing the node they can see the image inline with the text.

It's styled to look nice, but the **image is small**, and sometimes a user might want to see the details of the image more clearly (however we still want to keep it small on the page by default).

So I was thinking it would be nice for the user to be able to click the image and have the image get larger (possibly as a **pop-up** or **overlay**) on the page.

My research led me to **Lightbox2** and so I installed that module. I enabled it and when into the settings in the configuration page and made sure it's loading on all pages. I also made sure the setting for 'Automatic Image Handling' \> 'Image Node Settings' was set to 'Lightbox'. \[I actually tried all of the options available there\]. I then cleared the cache as usual.

It seemed all too simple no doubt. And indeed I went to one of my nodes and clicked on the image and nothing happened.

Can someone please help me configure Lightbox2 correctly to achieve my objective? (or perhaps give me an alternative solution).

Thanks!

# Answer
> 1 votes
Colorbox and lightbox are the famous modules for this, once you done with all configuration, go to Content type Manage display settings tab and render the image in lightbox. it will automatically shows up in the popup. https://i.stack.imgur.com/NEqGk.png

# Answer
> 1 votes
Are your images inside the node's body? (Ex: added them using CKeditor or some other Wysiwyg editor) or did you added them as an image field?

It doesn't work out of the box if they are inside the nodes body. Works out of the box only if they are an image field, I believe.

According to the readme.txt file **you need to add `rel="lightbox"` to your `<a>`**

```
    ADDING LIGHTBOX FUNCTIONALITY TO YOUR IMAGES
--------------------------------------------
No Grouping
===========
Add rel="lightbox" attribute to any link tag to activate the lightbox.
For example:
<a href="images/image-1.jpg" rel="lightbox">image #1</a>
<a href="images/image-1.jpg" rel="lightbox[][my caption]">image #1</a>

Optional: To show a caption either use the title attribute or put in the second
set of [] of the rel attribute.

With Grouping
==============
If you have a set of related images that you would like to group, follow step
one but additionally include a group name between square brackets in the rel
attribute. For example:

<a href="images/image-1.jpg" rel="lightbox[roadtrip]">image #1</a>
<a href="images/image-2.jpg" rel="lightbox[roadtrip][caption 2]">image #2</a>
<a href="images/image-3.jpg" rel="lightbox[roadtrip][caption 3]">image #3</a>

No limits to the number of image sets per page or how many images are allowed
in each set. Go nuts!

If you have a set of images that you would like to group together in a
lightbox, but only wish for one of these images to be visible on your page, you
can assign the "lightbox_hide_image" class to hide the additional images.  For
example:

<a href="images/image-1.jpg" rel="lightbox[roadtrip]">image #1</a>
<a href="images/image-2.jpg" rel="lightbox[roadtrip]" class="lightbox_hide_image">image #2</a>
<a href="images/image-3.jpg" rel="lightbox[roadtrip]" class="lightbox_hide_image">image #3</a>

Slideshow
=========
This is very similar to the grouping functionality described above.  The only
difference is that "rel" attribute should be set to "lightshow" instead of
"lightbox".  Using the same example as above, we could launch the images in a
slideshow by doing:

<a href="images/image-1.jpg" rel="lightshow[roadtrip]">image #1</a>
<a href="images/image-2.jpg" rel="lightshow[roadtrip][caption 2]">image #2</a>
<a href="images/image-3.jpg" rel="lightshow[roadtrip][caption 3]">image #3</a>

```

---
Tags: javascript
---


# Question
Title: How to add HTML class to main menu list?
Theme Developer shows me that I need to use theme\_links()

I can use this function, but I want to alter markup for main menu only.

I've tried funtion names: mytheme\_links\__menu\_main\_menu or mytheme\_links\__system\_main\_menu

but it seems that these function aren't invoked.

# Answer
One way to achieve this to create a theme key in your template file like this:

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

    $items['custom_main_menu'] = array(
      'variables' => array('links' => array()),
  );

  return $items;
}

```

And then use the function below

```
function THEMENAME_custom_main_menu($menu){
  $menu['links'][367]['#below'][526]['#attributes']['id'] = "news_ma_international";
  // this will add id to link # 367
}

```

Now to print the main menu in your page.tpl.php use something like this

```
 <?php $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu')); ?>
                <?php print theme('custom_main_menu', array(
                  'links' => $main_menu_tree,
                  'attributes' => array(
                    'id' => 'main-menu-links',
                    'class' => array('links', 'clearfix'),
                  ),
                  'heading' => array(
                    'text' => t('Main menu'),
                    'level' => 'h2',
                    'class' => array('element-invisible'),
                  ),
                )); ?>

```

I hope this will help!
> 1 votes

---
Tags: 7, theming, routes
---


title: Calendar Module Shows Two Month Links

text:
# Question
Title: Calendar Module Shows Two Month Links
So I have a view of a calendar with some events listed on it. I also have this calendar setup to be a block on a page.

The block is on www.example.com/subsite

When I click the block it takes me to the month view of the calendar at www.example.com/subsite/month

Now, on this view, there are tabs at the top of the calendar in the following order with their respective links:

Month - www.example.com/subsite/month
Month - www.example.com/subsite
Week - www.example.com/subsite/week
Day - www.example.com/subsite/day
Year - www.example.com/subsite/year

So... That second Month link is obviously wrong. How do I get rid of it and/or change the title to Home? If I make the Month view not show on the settings page, it removes the Month link that actually goes to the Month view.

Any help would be awesome, thank you.

# Answer
> 0 votes
Two tabs of Month came up in the first place don't make sense. It never happened to me. I would suggest to recreate this Calendar view, it's actually pretty easy if you "add view from template". (Consider you've installed the Calendar Module)

Make sure to select “A calendar view of the 'field\_date' field in the 'node' base table.” on the list of views/add-template

# Answer
> 0 votes
Are you using Quicktabs to create the tabs? If so, you can go to structure \> Quicktabs \> Configure \> Edit. At the bottom of the page, you'll see that you can select your block. You could try checking "Hide the title of this block" for whichever block you are using.

---
Tags: views
---


# Question
Title: How to create grouped filters based on integer range?
I'm developing a recruitment website which will allow users to filter jobs by salary. It has been designed so that the filter is grouped into salary ranges like this...

I am using the Range module in order to add a range field to my job content type (essentially just two text boxes). The idea is that the admin can enter in any 'from' and 'to' integer (doesn't have to be a value that matches one of the filters e.g. £20–25k). Instead the query should be able to adapt and show any matching results.

The issue I have is that because I essentially have two fields saved there doesn't appear to be any simple way of grouping filters. I have attempted to use the `Global: Combine fields` filter but this only works with strings, not integers.

I've also attempted to add the `Salary range filter` included with the Range module under the `Filter criteria` heading of my view but this doesn't appear to work either. Here is a screenshot of what I attempted (I'm assuming that the Range module doesn't actually store the integers in-between the 'to and 'from' fields so I guess this wouldn't work. I'm also not sure that separating the values with commas is valid either).

The only method I can think of would be finding a way of adding the two fields together to create one total integer which would then allow me to use the standard `is-between` operator available when filtering a single field in Views.

Thanks in advance.

# Answer
> 0 votes
You might try the Contextual Range Module: https://www.drupal.org/project/contextual\_range\_filter

According to the documentation, this allows you to make a contextual filter based on a range (as opposed to just a single field value).

---
Tags: entities, views
---


# Question
Title: Insert values into a node fields with entity wrapper
I've tried to use entity wrapper to create a new node and insert the values into the fields, but I get an error.

```
    <?php
$values_entity = array(
  'type' => 'anuncio',
  'uid' => $userid,
  'status' => 1,
  'comment' => 1,
  'promote' => 0,
);
$entity = entity_create('node', $values_entity);
// The entity is now created, but we have not yet simplified use of it.
// Now create an entity_metadata_wrapper around the new node entity
// to make getting and setting values easier
$ewrapper = entity_metadata_wrapper('node', $entity);
// Using the wrapper, we do not have to worry about telling Drupal
// what language we are using. The Entity API handles that for us.
$ewrapper->title->set($values['titulo']);
$ewrapper ->field_fecha_inicio->set($values['fecha_inicio']);
$ewrapper ->field_duraci_n->set($values['duracion']);
$ewrapper ->field_tipo_anuncio->set($values['tipo_anuncio']);
// Now just save the wrapper and the entity
// There is some suggestion that the 'true' argument is necessary to
// the entity save method to circumvent a bug in Entity API. If there is
// such a bug, it almost certainly will get fixed, so make sure to check.
$ewrapper->save();
?>

```

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. en EntityMetadataWrapper-\>set() (línea 122 de /opt/lampp/htdocs/tentu/ataria/sites/all/modules/entity/includes/entity.wrapper.inc).

I've tried also to insert the values of the field this way:

```
<?php
    $node = new stdClass();
    $node->nid = NULL;
    $node->vid = NULL;
    $node->type = "anuncio";
  //    node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
      $node->language = $language_url;// Or e.g. 'en' if locale is enabled
      $node->title = $values['titulo'];
      $node->uid = $userid;
      $node->status = 1; //(1 or 0): published or not
      $node->created = REQUEST_TIME;
      $node->changed = REQUEST_TIME;
      $node->promote = 0; //(1 or 0): promoted to front page
      $node->comment = 1; // 0 = comments disabled, 1 = read only, 2 = read/write
      $node->sticky =0;
      $node->field_fecha_inicio[$node->language][]['value'] = $values['fecha_inicio'];
      //$node->field_posicion2[$node->language][]['und'] = $form_state['values']['fecha_inicio'];
      $node->field_duraci_n[$node->language][]['value']= $values['duracion'];
      $node->field_municipio[$node->language][0]['tid'] = $values['municipios'];
      $node->field_tem_tica[$node->language][0]['tid'] = $values['tematicas'];
      $node->field_importe[$node->language][0]['value'] = $values['importe'];
      $node->field_texto_anuncio[$node->language][0]['value'] = $values['texto'];
      $node->field_g_nero[$node->language][0]['value'] = $values['genero'];
      $node->field_ubicacion_anuncio[$node->language][0]['value'] = $ubicacion;
      $node->field_tipo_anuncio [$node->language][0]/*['value']*/= $tipo;
  // Entity reference field
  // 'node' is default,
  // Other possible values are "user" and  "taxonomy_term"
  node_submit($node); // Prepare node for saving
  node_save($node);
?>

```

I can create the node with the last code, but I can't save the values into the fields. I have seen in my database that the name of the fields isn't for example, field\_fecha\_inicio, instead, I have field\_data\_field\_fecha\_inicio and field\_revision\_field\_fecha\_inicio.

How can I insert the values into the fields?

ANSWERD:

```
$node = new stdClass();
    $node->title = $values['titulo'];
    $node->language = $values['idioma'];
    $node->uid = $userid;
    $node->status = 1; //(1 or 0): published or not
    $node->promote = 0; //(1 or 0): promoted to front page
    $node->comment = 1; // 0 = comments disabled, 1 = read only, 2 = read/write
    $node->sticky = 0;

        $node->type = "anuncio";
    node_object_prepare($node);
    $node->field_texto_anuncio[LANGUAGE_NONE][] = $values['texto'];
    $node->field_fecha_inicio[LANGUAGE_NONE][]['value'] = $values['fecha_inicio'];
    $node->field_duraci_n[LANGUAGE_NONE][]['value'] = $values['duracion'];
    $node->field_municipio[$values['idioma']][]['tid'] = $values['municipios'];
    $node->field_tem_tica[$values['idioma']][]['tid'] = $values['tematicas'];
    $node->field_importe[LANGUAGE_NONE][]['value'] = $values['importe'];

    $node->field_g_nero[LANGUAGE_NONE][]['tid']= $values['genero'];
    $node->field_url_del_anuncio[LANGUAGE_NONE][]['value'] = $values['url'];
    $node->field_ubicacion_anuncio[LANGUAGE_NONE][]['tid'] = $ubicacion;
    $node->field_tipo_anuncio[LANGUAGE_NONE][]['tid']= $tipo;

        $node = node_submit($node); // Prepare node for saving
    node_save($node);

```

# Answer
> 0 votes
The structure in your second code block looks correct to me.

To see what the problem is first create a node of type 'anuncio' using the UI in the backend of Drupal. Now use devel (or just print\_r) to inspect the node you just made.

```
dmp(node_load(NEW_NODE_ID));

```

Just before you save your new node you can inspect it too:

```
dpm($node);

```

The new node you are creating needs to match the structure of this node - any differences here tells you what bit is wrong.

EDIT:

In your second code block you don't need these lines:

```
$node->nid = NULL;
$node->vid = NULL;
$node->created = REQUEST_TIME;
$node->changed = REQUEST_TIME;

```

These will all be automatically set so you don't need to set their values.

Also look at the example here.

You need:

```
$node = node_submit($node);

```

and your also missing:

```
node_object_prepare($node);

```

I've edited your code slightly, I think this should work:

```
$node = new stdClass();
$node->title = $values['titulo'];
$node->type = "anuncio";
node_object_prepare($node);

$node->language = $language_url;
$node->uid = $userid;
$node->status = 1; //(1 or 0): published or not
$node->promote = 0; //(1 or 0): promoted to front page
$node->comment = 1; // 0 = comments disabled, 1 = read only, 2 = read/write
$node->sticky = 0;

$node->field_fecha_inicio[$node->language][]['value'] = $values['fecha_inicio'];
$node->field_duraci_n[$node->language][]['value']= $values['duracion'];
$node->field_municipio[$node->language][0]['tid'] = $values['municipios'];
$node->field_tem_tica[$node->language][0]['tid'] = $values['tematicas'];
$node->field_importe[$node->language][0]['value'] = $values['importe'];
$node->field_texto_anuncio[$node->language][0]['value'] = $values['texto'];
$node->field_g_nero[$node->language][0]['value'] = $values['genero'];
$node->field_ubicacion_anuncio[$node->language][0]['value'] = $ubicacion;
$node->field_tipo_anuncio [$node->language][0]/*['value']*/= $tipo;

$node = node_submit($node); // Prepare node for saving
node_save($node);

```

EDIT 2:

So, if the fields are not getting populated then there is something wrong with this line (let's just focus on 1 field at a time):

```
$node->field_fecha_inicio[$node->language][]['value'] = $values['fecha_inicio'];

```

Initially I would try hard coding the values to get it to work, so see if this line works:

```
$node->field_fecha_inicio[LANGUAGE_NONE][0]['value'] = 'my test value';

```

Does this line work?

# Answer
> 0 votes
Hope this function will help you. I am creating a basic node of type page.

```
/**
 * Create a custom node.
 *
 * @param string $type
 *   Type of node (bundle).
 */
function _custom_work_create_a_node($type = 'page') {
  global $user;
  $node = entity_create('node', array(
     'type' => $type,
     'uid' => $user->uid,
    ));
  $wrapper = entity_metadata_wrapper('node', $node);
  $wrapper->title->set('Demo title');
  $wrapper->body->value->set('body value');
  $wrapper->save();
}

```

---
Tags: 7, nodes, database
---


# Question
Title: Clean URLS work with http, but not with https
When I visit **?q=admin/config/search/clean-urls** via HTTP I am able to enable clean URLs and they work fine.

However, when I visit the same path via HTTPS I am not able to enable clean URLs and get this error:

Here is my apache conf file for http:

```
NameVirtualHost *:80

<VirtualHost *:80>

    UseCanonicalName Off
    ServerAdmin webmaster@localhost
    DocumentRoot /media/www_drive/drupal7

  <Directory /media/www_drive/drupal7>
    Require all granted
    AllowOverride All
  </Directory>

</VirtualHost>

```

Here is my apache conf file for https

```
NameVirtualHost *:443
<VirtualHost *:443>

    SSLEngine on
    SSLCertificateFile /etc/ssl/cgps/star.cgps.org.crt
    SSLCertificateKeyFile /etc/ssl/cgps/np_cgps.key
    ServerAdmin webmaster@cgps.org
    DocumentRoot /media/www_drive/drupal7
    SSLCACertificateFile /etc/ssl/cgps/RapidSSL.crt

    <Directory /media/www_drive/drupal7>
      Require all granted
      AllowOverride All
    </Directory>

</VirtualHost>

```

Shouldn't this config use the same `.htacess` file in the drupal root for both HTTP and HTTPS? What could cause clean URLs to fail to pass the check via HTTPS?

# Answer
> 0 votes
You can try below with changing in `.htaccess` file:

```
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

```

---
Tags: uri
---


# Question
Title: How can I hide the title in my user registration form?
I am using LoginToboggan module. And I want to hide the title.

As you see in first picture "Log in" title is shown, and in second "Create new account" title is shown. How can I hide these titles?

# Answer
> 2 votes
Use disable/hide title module. Alternatively, you can disable the title pretty easily with css. Another way is to disable the title using template.php using `drupal_set_title()`

# Answer
> 0 votes
You can do it by using `hooK_form_alter`

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check the form_id
  if ($form_id == 'YOUR_FORM_ID') {
    // To hide the label
    $form['your_form_element']['#title_display'] = 'invisible';
    // To alter the label
    $form['your_form_element']['#title'] = t('Your new title');
  }
}

```

put this code in custom module or if you want to use it in theme page then use mytheme instead of mymodule.

Or you can be do it by creating tpl file and comment title part code in tpl file

---
Tags: users, authentication-authorization
---


# Question
Title: add custom data attributes to block from block configuration page
Here is what I would like to accomplish: 1. Add data attributes to block (for example: data-key="value") 2. Nice to have: add a text area to block config page where i can enter data attribute key-value pairs (one per line) and have them added to the block.

Any guidance is greatly appreciated

# Answer
> 0 votes
You will need to create a custom block using hook block info, hook block view and hook block configure. That last hook will let you as a form render array (see drupal form api).

The custom block system in drupal 7 isn't very good. If you need anything but the simplest HTML code then you should create your own blocks using the above hooks.

# Answer
> 0 votes
I actually just built a module to handle this specific use case, called Block Data.

---
Tags: blocks
---


# Question
Title: Extract final value from nested field collection
I have a content type with a **field collection**. This field collection has, as fields, other field collections. It works well, it groups the content for a node perfectly, but when trying to extract the data programmatically, I cannot access the values introduced. How would be the method. I tried with this piece of code, but it throws an error. Also not sure if adequate to my case (nested field collections):

```
$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_rich_text_group as $field_collection_wrapper) {
            $field_collection = $field_collection_wrapper->value();
                print_r($field_collection);
}

```

# Answer
Try this :

```
$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_rich_text_group->value() as $value) {
  $field_collection_wrapper = entity_metadata_wrapper('field_collection_item', $value);
  $field_collection_myfield = $field_collection_wrapper->field_myfield->value();
  print_r($field_collection_myfield);
}

```

**Field Collection** is an entity, so if you want to access its field you have to pass the field collection in `entity_metadata_wrapper`. Then you can access the value of your fields in field collection like you do with your `$node_wrapper`
> 1 votes

# Answer
I have managed to get the value by direct access.

```
$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
echo $node_wrapper->field_rich_text_group->field_meta_datos->field_meta_title->value();

```

I guess that the foreach would be needed if I have multivalued data. Please someone explains to me why this solution works and `pbonnefoi` does not print anything and throws error. Adapting from his code,

```
$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
foreach ($node_wrapper->field_rich_text_group->value() as $value) {

$field_collection_wrapper = entity_metadata_wrapper('field_collection_item', $value);

 $field_collection_myfield = entity_metadata_wrapper("field_collection_item", $field_collection_wrapper->field_meta_datos->value());

print $field_collection_myfield->field_meta_title->value();

```

Print OK but throws this error, probably because in the loop there is something it does not locate:

```
`// EntityMetadataWrapperException: Unknown data property field_meta_datos. en EntityStructureWrapper->getPropertyInfo() (line 335 of /home/public_html/sites/all/modules/entity/includes/entity.wrapper.inc).`

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to add the relationship for tittle of content type of other in view
How to add the relationship for tittle of content type of other in view of different content type.

# Answer
> 0 votes
You need to relate the two content types somehow. One of the most popular ways of doing it is using the module entity\_reference.

After you install the module, create a field of type "entity\_reference", and by then you should be able to add a relationship in your view using this field, allowing you to use all fields of the second content type on the primary content type's view.

---
Tags: views
---


title: Views 3 Exposed Filter AJAX HTTP Error

text:
# Question
Title: Views 3 Exposed Filter AJAX HTTP Error
Relevant modules & themes:

* zurb\_foundation-7.x-4.0
* views-7.x-3.11
* jquery\_update-7.x-2.6 (front-end using 1.7 and backend using 1.5)

I have an exposed views filter on the front page that is auto-submitting when the dropdown field changes. I'm using Zurb Foundation base them (v4) along with the 'custom' field style. Here's what my view and filter looks like:

When I choose another option, I get this:

The weird thing is that watching `views/ajax` with a debugger, Drupal generates a proper response but jQuery presents the error alert even before the debugger acknowledges the debugging request. There is no "error" showing up in the Drupal or Apache logs. Once you click "OK" the page refreshes and the block shows the proper information based on the date selected.

# Answer
> 0 votes
So in this particular problem, what was actually happening was a double-posting of the Ajax submit handler. The first call was being interrupted and it was coming back empty. Removing the extra submit handler fixed the problem. This was directly related to the use of Zurb's custom form fields and a couple of browser issues that caused me to believe that the submit handler was not firing, but indeed it was.

---
Tags: ajax, views
---


# Question
Title: How to create Facebook style user notifications?
Using Heartbeat I have been able to effectively make streams of user activities through Rules triggers. However I would like to be able to have users notified of new activities, and keep a count of the number of new activities like in facebook, or even similar to new email counts in most email systems.

In Drupal 6 there were a few modules which could achieve this well, however how can this be done in Drupal 7?

I have done quite extensive research on this but am unable to find the right module at this point: There's the User Notifications and Notifier modules, which would be the perfect solutions except only D6 versions exist. There's Notifications which cannot be integrated with any activity logging module since it lacks proper Rules support. Two interesting implementations are Appbar and Taskbar which provide dropdown trays with lists of activities, but don't count the number of new activities and no longer integrate with Rules. Finally DLike is great as a dynamic counter, even though at the moment it only counts Flags and provides a link to a list of the flagging users. Perhaps with some tweaking it could be used via Flags Rules integration to track recent (flagged) activities and link to a list of these recent activities.

Is it possible to achieve functionality similar to this in Drupal 7?

# Answer
# Approach 1: Menu Badges

Use the Menu Badges module to add such notifications to any **menu item** and/or **menu tab** of your choice. Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

### Video tutorials:

# Approach 2: Message stack

Use the Message Stack, which consists of these modules (quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium.

If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the *Answers Notification* sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

And the Message Stack will make you well positioned for Drupal 8 also (because of he modules' object orientated architecture). Even though there is no such a thing as 8.x-dev yet, the Message code repository already does contain something already (not yet for the 2 other modules though). I assume the `wip` part of the branch name stands for 'Work In Progress'.
> 4 votes

# Answer
There's a relatively new pair of modules that I think would be great to use for this: Message and Message-notify.

*Message* is basically a framework for creating "messages", which in your case would be notification items. One cool thing is that these are actually all created as entities, so it would be easy to show then in a dropdown block, have an All Notifications page, as well as have a custom field or flag on them that indicates whether they've been seen (or are new). You can then connect this to email notifications with the *Message-notify* module.

Note though that integrating this into your site would be a development task more than a site building task. The module has a good API that can be used in appropriate hooks, etc to create messages when desired, but I'm not sure how the Rules integration is going.
> 3 votes

# Answer
For real time integration you can use nodejs module.

This module integrates Node.js with Drupal.

It provides an API that other modules can use to add realtime capabilities to Drupal, specifically enabling pushing updates to open connected clients.
> 3 votes

---
Tags: 7, rules, social-network, notifications, heartbeat
---


# Question
Title: How to switch language on pages containing charts created using Forena?
I have created a chart using Forena Reports. I have created a menu with this chart as one of the links.

I have also installed the Language Switcher Dropdown module for choosing between 3 languages. When I choose between any of the languages, the page will get refreshed and I will be able to see the transalated version.

But this is not happening when I am in the chart page. When I choose other language page is not even getting refreshed also language is not getting changed. When I go to other pages and try the same, everything is working as expected.

**Note**: When I go to the chart page I can see this error in console:

> Uncaught TypeError: $(...).dataTable is not a function

which is coming from the `datatables.js file` inside the forena report.

# Answer
As per the "**uncaught TypeError: $(...).dataTable is not a function**" you mentioned, it sounds to me that what your language problem is actually not a language problem, but some installation issue related to what's required to Enable Data Tables support. I'd recommend you to first try to resolve that error (as explained in the documentation in the mink I mentioned before, which you can also find in your own site located at `/reports/help.setup#datatables`.

You may also want to look at my answer to the question about "How to translate the title, axis labels and legend of a chart?" for the typical steps required to correctly translate a chart create with Forena (just to make sure such translation exist for each of your languages, and that the URL for each translation of the report is correct, and does exist).

If neither of this helps to sort out what's happening, then please further enhance your question by including your report/chart specifications (= what's called the "frx"-source in Forena). After doing so, I'd be happy to try to further enhance my answer also.

Disclosure: I'm a co-maintainer of Forena Reports.
> 1 votes

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


# Question
Title: Content-type linked to specific users and user-groups
I am creating a system which has 2 types of user: a **Member** and a **Group Admin**. **Members** are put into **Groups** and are managed by that groups **Admin**. A **Member** can contact *their* **Group Admin** but not other **Group Admins**. Some of this contact data/messages should be visible to other **Members** of that particular **Group**, some information should be visible only to that **Member** and the **Group Admin**. In certain situations, a **Group Admin** should be able to become the **Group Admin** of another **Group**. **Members** can make *complaints* to **Group Admins** who are able to respond. **Anonymous** users should be able to make complaints, provided they provide extra information, e.g., name, address, telephone number. Ideally, when making a complaint they would be asked if they would like to create an account.

Being new to Drupal (started looking through the Docs a week ago) I'm having trouble with pretty much everything. Using Drupal has been made a requirement as it is meant to make the process easier; however, for me it is not. As there are approximately 800 different groups does this mean that I'm going to have a huge matrix of permissions? Am I going to have to create 800 different roles? I'm struggling visualising the architecture of the system and the modules I'll need. For example, I'd created a content-type `Complaint`; however, everyone could see it. Drupal 7 Core has no way to restrict different users from viewing specific content. I remedied this by installing a module: `Content Access`. Any suggestions for the architecture and modules would be useful.

# Answer
> 1 votes
Often times when using Drupal there are recipes or a collection of modules that will help you achieve your goals for a website so that your workload is not burdened with custom PHP business logic code or SQL. Drupal helps to take away these technical difficulties when creating websites.

It sounds like you want to a site with groups of content and users. There exists active module(s) to allow easier site development of sections and groups of users within a website. The defacto module for this is Organic Groups (typically referred to as the "OG" module) and its set of sub-modules and contributed add-on 3rd party modules.

> **Overview**
>
> Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.
>
> They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.
>
> Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.

OG is not a small or simple module in it's administrative configuration, or it's supported API. But, it's goal is to make your stated problem easier to implement in a standard fashion/codebase for site developers.

---
Tags: users
---


# Question
Title: Exporting and importing a view from a custom module
From my understanding you can export your views and content types to a module so that you can replicate the view and content type on another server. My question is, if I export the view to a module and write the views api in my module, will the view/content type show up under the structure menu, if so would any changes made there be reflected back in the code of the module, or does this require another export and saving the output back into the module code?

Thanks

# Answer
Content types and Views are 2 different things. It's your job as a module developer to keep the two in sync over time.

Some modules can help with this such as the Features module, if you dont want to track all this by hand every time.
> 0 votes

---
Tags: views, importing-exporting
---


# Question
Title: How to use some code only in the template of selected content types?
I have some code (calling JS and CSS) in the head section that I only want to appear if the HTML template is used for the content type 'home page'.

I did it like this in the html template:

```
<?php if ($variables['node']->type = 'home_page'){ ?>
Code....
<?php } ?>

```

But if I check the source code of my pages, the code is showing up in all off my pages, not only on the pages that use the 'home page' template.

Any tips, code, links?

PS: I'm not good at PHP (I normally cut and paste)

# Answer
> 1 votes
Typo:

`if ($variables['node']->type = 'home_page'){`

change it into:

`if ($variables['node']->type == 'home_page'){`

# Answer
> 1 votes
You can do it by using `hook_init`

```
<?php
/**
 * Implementation of hook_init()
 */
function Hook_init() {

     // Check for front page
    if(drupal_is_front_page()){
        // Add css/js files
       drupal_add_css($module_path . '/css.css');
       drupal_add_js($module_path . '/js.js');
    }
}
?>

```

If you add in `template` file look this code :

```
function yourtheme_preprocess_node(&$vars) {
  // Add JS & CSS by node type
  if( $vars['type'] == 'your-node-type') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }

  // Add JS & CSS to the front page
  if ($vars['is_front']) {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }

  // Add JS & CSS by node ID
  if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'your-node-id') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

```

# Answer
> 0 votes
IF you are trying to include the code only on the **front page** of your site, I'd suggest you override its template by creating `page--front.tpl.php` inside the template directory of your theme. See this explanation.

EDIT: If you want to use the logic you had in your posting, I would be sure to check the syntax of your `if` statement. I may be wrong about this, but I've mostly seen this as:

```
<?php if ($variables['node']->type == 'home_page'): ?>
Html, css or Javascript code here.
<?php endif; ?>.

```

Notice, no curly braces. Also, as another answer pointed, it's `==`

# Answer
> 0 votes
If you are putting condition for your sites home page its better to use : if(drupal\_is\_front\_page()){
CODE... }

Alternative is:

If you print all your $variables array you will find $variables\['is\_front'\] set to either true or false which you can use.

Just remember to set site's front page.

---
Tags: theming
---


# Question
Title: Referencing logged user and node relations.
I am trying to solve a problem with no luck:

I have 4 objects in Drupal:

* -Company user (role company)
* -Mod user (role moderator)
* -Node Project
* -Node Person (not a user entity)

Company user can add/edit/delete own Project nodes.
Mod user can a/e/d own Person nodes.

I would love to accomplish next:

Mod can reference (add) Persons to Projects. Example : Person A, Person B,... (both owned by Mod1 user) can be referenced (added) to Project 1, Project 2, etc. (or unreferenced/removed).

I imagine this as M:N relation, with two extra attributes - status (value 0-5) and author/createdBy (logged Mod1 user) to prevent mod users from editing/viewing others relation entities.

Next level is creating this by Rules module and Rules link module.

Lets have a View with Projects

* clicking on a project should display a project page with list of referenced and unreferenced Persons owned by logged-in Mod user.
* Persons list should be clickable (rules link) for adding/removing reference from actualy displayed project.

I had some progress with field collection module - was able to create relation entities with status, but cannot made it with Rules - dont know how to send two parameters in rule link (project id, person id) and create project page with persons lists (maybe as view blocks with contextual filters?)

Thank for any help, or idea.

# Answer
I dont use Rules Link alot, I have used Rules Link Event and Rules. Anyways this issue queue item for Rules Link describes how to setup Parameters for a Rules Link:

https://www.drupal.org/node/1926196

From the issue:

> For your example, add the product sku field to your view and pass the token for that in the views rules link field settings under: Additional parameters for the rules link
>
> Edit the rules link component, click the configure rules tab, under settings, add the additional parameter. I assume it could be string, integer or whatever that matches your sku. The view is going to pass that parameter as a variable to use in the rules link component rules so you can do whatever you want with it from there.

The issue queue explains adding 1 parameter. but it does sound like it supports additional parameters to send to Rules, so just assure your View is passing 2 parameters instead of just the 1 in the *Additional Parameters*.
> 0 votes

---
Tags: rules, navigation, entities
---


title: Tracking the fields in view

text:
# Question
Title: Tracking the fields in view
How to track the content fields changes in view, just like history review.

When we click on that particular field of content, my aim is some how to track the field of content type have gone through field track changes module. But its of no luck.

# Answer
> 0 votes
Using the track\_field\_changes module, I was able to get the side by side values in a view. Note , I also have revisions turned on for this node type.

# Answer
> 0 votes
Considering your scenario you can set 'Number of values' property of field to multiple and its also easy to handle in view. But if you do so, remember to fetch latest value from the field.

Here you go:

* Admin » Structure » Content types » Your Content type » Manage fields » Edit Your field
* Set 'Number of values' property to multiple. i.e. suppose you want to track 10 time values changed in history.

Now when you use this field in view:

* Edit your view and add this field
* In setting of this field you'll find 'MULTIPLE FIELD SETTINGS'
* Here select the checkbox 'Reversed' i.e. start from last values.

This will work as history to your field.

---
Tags: views, entities
---


title: How to fetch taxonomy fields

text:
# Question
Title: How to fetch taxonomy fields
I am using drupal 7.36. My question is I have created one taxonomy term **"skin type"**.In this **skin type** I have created many fields.So I want to fetch all taxonomy terms.

How can I fetch this using query or any other way ?

# Answer
To fetch taxonomy term data have different function to use depend on requirement .

Custom Code :

```
<?php
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
  ->fieldCondition('field_ingredients', 'tid', $term_id_of_pepper)
$result = $query->execute();
if (isset($result['taxonomy_term'])) {
  $tids = array_keys($result['taxonomy_term']);
  $terms = entity_load('taxonomy_term', $tids);
}
?>

```
> 0 votes

# Answer
I have archive this use view too, but in slightly different way compare Ashlar.

1. Add **Taxonomy term: Term ID** in CONTEXTUAL FILTERS.
2. Add **Taxonomy term: Parent term** in RELATIONSHIPS. (leave Require this relationship unchecked.)
3. Add **Taxonomy term: Parent term** in filter section. select **great than 0**.
4. do not forget to filter your taxnonmy term in mycase Taxonomy vocabulary: Machine name (= Business Directory).
5. add Taxonomy term: Rendered Taxonomy term to your fields , select relationship to **parent** , check the Exclude from display.
6. In setting, under FORMAT section. In grouping field 1, select **(Parent) Taxonomy term: Rendered Taxonomy term**.

You should good to go. you can use view tpl to add more class base on the group. I have enclose my screenshot for references. Sorry for my English.
> 0 votes

# Answer
These functions would help

try this too:

```
 $v = taxonomy_vocabulary_machine_name_load($machine_name);
  $terms = taxonomy_get_tree($v->vid);

  foreach ($terms as $term) {
        $parentree = taxonomy_get_parents_all($res->tid);
        $strarr = array();
        foreach ($parentree as $parent) {
            $parentList[] = $parent->tid;
        }
  }

    $child_term = taxonomy_term_load($parent_tid[0]);
    $parent_term_level1 = taxonomy_term_load($parent_tid[1]);
    $parent_term_level2 = taxonomy_term_load($parent_tid[2]);

```
> 0 votes

---
Tags: taxonomy-terms
---


title: Bootstrap Theme $variables

text:
# Question
Title: Bootstrap Theme $variables
I've made a sub-theme of the Bootstrap theme; however, I am having trouble understanding where `$variables` comes from in the *page.vars.php* file. I made a little "debug" code to print out the variables - unfortunately, the output is exceptionally large and has some strange outputs. I have edited *page.vars.php* using the variables already retrieved from the `$variables` associative array, e.g. I edited the size of the main content section on the page:

```
 $variables['content_column_class'] = ' class="col-md-8 col-sm-6"';

```

This suggests there should be a `'content-column-class'` in the `$variables` array; however, amazingly when I perform `print_r($variables)` it turns out there is none! Furthermore, every variable I have checked that is being accessed in `page.vars.php` seemingly does not exist.

I'd like to edit the `class` of the `primary` / `sidebar_first` sections; however, currently I cannot do this as I don't know how to access them from the `$variables` array.

In sum, *why does* `print_r` *not output the expected?* And, *how do I find out what variables are actually in* `$variables`*?*

# Answer
> 0 votes
The proper way to add a new variables in a class is to use `hook_preprocess_page(&$vars)` you can add the classes like the following:

```
$classes = array(
    'classes_main_page' => '',
    'classes_sidebar_first' => '',
    'classes_sidebar_second' => '',
  );

  // Classes when no sidebar
  if(empty($vars['page']['sidebar_first']) && empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-12 large-12';
  }
// Classes when left and right sidebars
  if(!empty($vars['page']['sidebar_first']) && !empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-6 large-6 columns';
    $classes['classes_sidebar_first'] = 'small-12 medium-3 large-3 columns';
    $classes['classes_sidebar_second'] = 'small-12 medium-3 large-3 columns';
  }

  // Classes when only left sidebar
  if(!empty($vars['page']['sidebar_first']) && empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-9 large-9 columns';
    $classes['classes_sidebar_first'] = 'small-12 medium-3 large-3 columns';
  }

  // Classes when only right sidebar
  if(empty($vars['page']['sidebar_first']) && !empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-9 large-9 columns';
    $classes['classes_sidebar_second'] = 'small-12 medium-3 large-3 columns';
  }
$vars = array_merge($vars, $classes);

```

and then in your page.tpl.php print something like this:

Don't forget to clear cache afterwards

```
<aside class="<?php print $classes_sidebar_second; ?>"> for sidebars
<aside class="<?php print $classes_sidebar_second; ?>"> for main container

```

Thanks

---
Tags: theming
---


# Question
Title: Does Drupal have some kind of Structure system?
I looked all over but no result ...

I wonder if there is a Structure System for Drupal like: **Spaces - Sections - Groups - Blocks - etc**.

Where to use Spaces and may I have groups in spaces? The documentation is somehow messy, I'm lost. But there seems to be no good guides (like books) for a Drupal beginner.

**Edit**:

It takes time to find out what I need, where to install, etc.

Drupal 7 with Open Atrium 2 should be used for a Information an collaboration suite for a company. Login and all user-information and its roles comes over LDAP and active directory. So far I haven't got any problems.

But now I would like to build a user page:

* I take a layout with two cols.
* In the right column I have all the information read from active directory and user information.
* In the left column there should be some different things.

But I would be very happy if I could understand how to build a user page with all the logged in user information automatically where user will be redirected after logged in.

I don't know how the hierarchy in Drupal works:

* Do I need a space for all user who are logged in in Drupal?
* And do I have groups inside a space or can I have groups without a space?

**Edit**:

So please don't mind if I give you this advice:

Not to explain all this modules and for what they are all for but to give specific projects and go through this from the first plane and road-map over the modules which we need till the building and setup.

So we can see it quit from the other side. Starting from a project going through drupal. And not from Drupal and for what it could be all for.

In my case I should build a company platform for all employees with there personal date from active directory (LDAP) and build up a personal page for each employee with his personal data with Drupal.

# Answer
> 2 votes
If you're new to Drupal, you might have a hard time getting your head around the (amazing) Panels module, and things like "context", etc. But it sounds that's part of what you're looking for. Watch the videos about Learn Page manager for more details. After you reviewed these videos, you should understand various features that come with the Panels module ... but also its challenges.

As an alternative, you may want to give it a try to see how far you can get with any (or all?) of these modules:

* Display Suite (a typical alternative for using Panels).
* DataTables used in combination with Views (especially because of its client side search facilities).
* You might want to check also to what extend the features provided by Organic Groups module might help in your case.

Fairly sure that at some point you should also look at the Rules and Flag module.

# Video tutorials

---
Tags: organic-groups
---


# Question
Title: copy term reference from one to other field
I have two fields (fieldtype = term reference) in the same content type and I would like to copy the settings from the first to the second one. After searching for a solution I found this thread but I think the description I need is just the one that is not available:

> "Copy contents of a CCK node reference field to another CCK node reference field"

Can somebody give me some guidelines, or even an explanation how to achieve this?

# Answer
> 0 votes
You could do something like this:

```
$result = db_query("SELECT nid FROM {node} WHERE type = 'my_type'");
foreach($result as $row){
  $node = node_load($row->nid, NULL, TRUE); // reset cache
  // Assign one node reference field to another
  $node->field_termreference_2 = $node->field_termreference_1;
  node_save($node);
}

```

If you've got a lot of nodes, you may need to use the Batch API for that.

Alternatively, you may be able to copy the field tables to another field table at the database level with SQL ( backup first )

Something like:

```
INSERT INTO field_data_field_termreference_2 SELECT * FROM field_data_field_termreference_1;
INSERT INTO field_revision_field_termreference_2 SELECT * FROM field_revision_field_termreference_1;

```

and clear Drupal caches after that.

# Answer
> 0 votes
I ran into the same issue last week. If you want you can try the sandbox project I created with the working title "field\_value\_copy"

It uses Entity API to load, fetch values and set them on the target field.

Put the module in you modules folder, run drush cache-clear drush and the you execute the command with

```
drush fieldcopy field_termreference_1 field_termreference_2 my_content_type

```

If you want to try it on just one node you can run

```
drush fieldcopy field_termreference_1 field_termreference_2 my_content_type node 12

```

where 12 is the node id.

# Answer
> 0 votes
Adding to what David Thomas said, about using INSERT INTO SELECT statement, http://dev.mysql.com/doc/refman/5.1/en/insert-select.html \- reference

INSERT INTO field\_data\_field\_\[term reference 2\] SELECT * FROM field\_data\_field\_\[term reference 1\];

I was able to use the above insert statement to copy term/table to another term reference table.

MySQL approach is a simple solution and works for my use case because how often will I need to merge or copy from one term reference to another? If I'm writing a module it would make sense. If I'm doing this just once, MySQL is simpler solution.

* Sam

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


# Question
Title: How to check which enabled modules are really used?
Is there a module or something else that you can use to check if all enabled modules on a site are really used?

I've searched the internet but with no results ...

# Answer
It sounds as if you're installing modules on a *production* site willy-nilly, just to try them out. I suggest you stop doing this. While people like me earn some of our living from helping the owners of such garbage piles sort through their wreckage, I'd rather get paid for building stuff than for cleaning up.

Instead:

* Set up a staging site for testing stuff. Only deploy on the production site if it is proven useful.
* Keep a log of everything you deploy on the production site, with details about *when* and *why*. Log also when you disable and uninstall, so you don't forget and make the same mistake twice.

The above is absolutely essential if more than one person runs the web site - but I've found it helpful even if there is only a single webmaster that does it all.

There is really no way of keeping tabs on "what you really use" automatically or semi-automatically. Configuration management is just one of the tasks a webmaster is supposed to do as part of a honest day's work.
> 7 votes

# Answer
I see sites with this issue a lot. Not all of us get to build wonderful clean sites from the ground up, sometimes you get stuck with a project where people were irresponsible about modules and installed them willy nilly. The method I use is:

1. Make a list of potentially unused modules. Sometimes you just know something is being used, but if you've never heard of it, you might want to see if it's actually in use.
2. By examining the module's code, look for what database schema it uses. Then examine your databases and see if those tables contain information at all. If they do, does it look important? (Now that I'm thinking about it, you could probably use the Schema module for this).
3. If it doesn't look important, pull up the site in your local development environment and test out disabling that module. It's a good idea to have functional tests or at least a site function testing checklist to work with at this point.

It's kind of a lot of work, which is why in my own from scratch projects I take a hard line in making sure unnecessary modules aren't installed on live sites. But not everyone does this.
> 5 votes

# Answer
A few years ago, I inherited a handful of Drupal sites. Upon looking at the installed modules, it was obvious that some were unnecessary (e.g. the LDAP module, when no LDAP authentication was being used, and the module was not even configured). But others weren't so obvious, like Views Isotope and Webform Hints, which I eventually discovered were installed and enabled but not used in any capacity within the sites.

In my case, it took some good old detective work and digging through the sites; however, I also got some help from the module called Unused Modules.

It lists unused modules and projects that can be safely deleted.
> 3 votes

# Answer
Perhaps you could setup a development environment for testing these modules. But as soon as a module is registered it does something. It might hovever never get called. On the other hand, you might install a module to perform a future function, so at the moment it does nothing, but it might later.

The way Drupal uses hooks makes it very hard to find if a module actually is called. The only way would be to fire all available hooks and see if something comes back. But since most modules invoke hook\_menu (to register pages) they all do something and the system will never know if this is just a settings page or a fancy page doing magic things.

In short, a module won't be able to tell if it actually performing a function.
> 0 votes

# Answer
I understand the need, but as far as I know there is no way to do this automatically.

Creating a universal module that would work in any installation would be quite complex. There are too many ways in which you can use a module in a non-standard way.
For example, you could use some of the module functions in a theme, a block (PHP input filter), Rule (raw PHP), Context (again raw PHP), etc.

You have to understand/check the installation yourself and then remove unnecessary modules manually.
> 0 votes

---
Tags: 7
---


# Question
Title: What are the major differences between Views Datasource and Views data export?
I'd like to create dynamic XML feed export using View based on my content type nodes.

There are two huge modules: Views Datasource (17k usage) and Views data export (67k usage) which sounds pretty similar.

On Views data export homepage we can read that:

> *Views Datasource* allows exporting to XML/JSON among many others, but is geared towards small exports.

Does it mean *Views Datasource* should be used only for small exports?

In other words, what are the main differences between these two modules? And what are the preferred ways (use cases) of using one over another?

# Answer
> 1 votes
Views Datasource can be thought as providing a view format that takes over the whole page; each submodule you enabled (JSON/RDF/XHTML/XML) provides a format that it outputs the view as a specified document type without your site theme.

Views Data Export can be thought of providing an attached exportable format of some complementary view format (e.g. a Page view formatted as a table that as an exportable CSV file); when enabled, it provides a new view display that you can make available at a specified path and attached to existing view as a button which can be configured to be a downloadable attachment.

There is some overlap (e.g. both could be used to produce an XML-producing custom path), but only Views Datasource provides a JSON (unless you use some other contrib module), while Views Data Export has other options (e.g. batching support) that make it better suited for large data exports.

---
Tags: importing-exporting
---


# Question
Title: Can Location Modules Geo Code on node save?
When I save a node that has a Location associated to it, it does not add the Longitude and Latitude values. When I run the Autofill empty locations path: admin/config/services/la it fills in all my nodes that have blank Latitude and Longitude values.

Is this normal? I wish the Longitude and Latitude values get entered as soon as I save.

# Answer
I figured out the problem. I have to set a Service for each country I want to use in the Geo Coding Settings: admin/config/content/location/geocoding
> 0 votes

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


# Question
Title: How to force forms only through your own submit functions?
If I want a custom submit handler, the usual answer is to add the function call to $form\['#submit'\], and if need be, $form\['actions'\]\['submit'\]\['#submit'\]. The standard warning is do something like

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

```

instead of

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

```

because you generally want the form submission to still go through the core form submission handlers.

I have a case where I need to completely manage the form submission process and don't ever want the form to be passed to the core submission handlers. To test that I could do this, I have:

```
global $user;
module_load_include('inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'my_content_type';
$node_form->uid = $user->uid;
$node_form->name = (isset($user->name) ? $user->name : '');
$form = drupal_get_form('my_content_type_node_form', $node_form);
$form['#submit']='';
$form['actions']['submit']['#submit']='';
$render($form);

```

I would have thought that since there are no submission handlers, the form shouldn't submit, or even if the page reloaded due to the action attribute in the html form element, that the content wouldn't be added to the database.

But it is.

So how can I keep Drupal from processing a submission through the normal core submission handlers, but still process through custom handlers? (I already know how to write custom form submission handlers, so that's not part of this question.)

# Answer
> 0 votes
Since I suggested this in my comment (the first in the thread) I'll rephrase as an answer so that you can mark it as correct.

Rather than using `drupal_get_form()` to build the node edit form (which just doesn't work the way you tried to do it, as there is no such callback `my_content_type_node_form` as far as I know) and then modifying the $form array, my suggestion is to:

* Let Drupal build your node edit form (you can do this by calling the appropriate URL `/node/8/edit` or `/node/add/[type]`)
* Then use the widely documented way of altering a form by implementing `hook_form_alter`.

EDIT: Digging a bit more I did find a `hook_form` function callback for nodes, but it's standard for all nodes - it's implemented in the node.module as `node_content_form()`. The hook is invoked in `node_form()` but as far as I can tell (I did some trials) it's the same for all Content Types regardless of their machine name. I think this may be where the confusion started.

---
Tags: forms
---


title: How to check if parent variables

text:
# Question
Title: How to check if parent variables
My login form generated by `theme_form()` contains a password field, which is generated by `theme_password()`.

My goal is to add certain variable into $variables of `theme_password()`. But ONLY in case, when parent's form NID == 5.

# Answer
You can use your theme's **template.php** to add a `theme_password()` wrapper to inject your custom vars:

```
function MYTHEME_password(&$variables) {
  $node = menu_get_object();
  if(isset($node->nid) && $node->nid == 5) { //Check for display on node/5
    //@TODO: Add $variables altercation
  }
  return theme_password($variables);
}

```
> 0 votes

---
Tags: theming
---


# Question
Title: Show user email from the user entity to anonymous users
Through views I am trying to show the account email address of any user to any user.

I have checked "Disable SQL rewriting", made sure the view didn't have any permissions, allowed anonymous user to view profiles. After all this it still won't show.

Note: I really don't want to create an additional field that is just syncs up this info just to show it. I want to show the actual field.

# Answer
Have you tried setting the permission so that anonymous users can view the profile of other users? Go to `admin/people/permissions` . See image below

The view (for anonymous user):
> 1 votes

# Answer
Once you done creating views, go to permission tab and check Role

https://i.stack.imgur.com/SWUU7.png

in the settings check anonymous, now the user will see the view.
> 1 votes

---
Tags: users
---


# Question
Title: Email-only subscription form with mailchimp module?
I have a mailing list in MailChimp and I recently installed the mailchimp module in my Drupal 6.0 site.

The subscribe form for anonymous users has first name and last name input elements, as well as an (empty and ugly) interest groups div.

Is there a way, using the mailchimp module, to present simply an email+button subscription form block?

# Answer
> 1 votes
I haven't got a mailchimp enabled Drupal site in front of me, but from memory the simplest way to do it is to set the fields you don't want captured as optional in the Mailchimp interface (NOT the Drupal module) and then just hide the fields using CSS on your subscribe form.

If you don't need to capture anything other than email for your mailing list, you can remove those fields entirely from your list on Mailchimp's site, and (again from memory) they won't show up in your Drupal form.

# Answer
> 0 votes
You can also hide elements (such as the groups area) with CSS, using

`display: none;`

Mailchimp actually recommends doing this in the case where you want to have people automatically subscribed to a specific group (without giving them the choice).

As long a given field isn't required, you could hide it this way.

---
Tags: 6, forms, emails
---


# Question
Title: Wrapping fields together in a Views Exposed Filter
I'm trying to insert *divs* (or any tag) in my exposed filter form with the purpose of grouping related fields together. I want to have something like this:

```
<div class="my-group">
  field one
  field two
  ...
</div>

```

So far, I have tried this in my `hook_form_alter()`, with no luck, since the prefix and sufix are added within field\_one, instead of *before* field one and *after* field two:

```
$form['field_one']['#prefix'] = '<div class="my-group">';
$form['field_two']['#suffix'] = '</div>';

```

How can I accomplish this (without external modules)?

# Answer
I solved it by using a `fieldset` to group my fields.

```
  // Create a fieldset to group related fields.
  $form['my_group'] = array(
    '#type' => 'fieldset',
    '#attributes' => array(
      'class' => array('my-group')
    ),
  );

  // Move the desired fields in it.
  $form['my_group']['field_one'] = $form['field_one'];
  $form['my_group']['field_two'] = $form['field_two'];

  // Unset the original fields, so they don't show up in the form anymore.
  unset($form['field_one']);
  unset($form['field_two']);

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Can Pathauto fallback to another pattern if the first pattern yields an empty path?
I want pages to have an auto generated path if they are in a menu and another one if they are not in the menu; not an empty path like Pathauto currently generates if the page is not in a menu.

How can I do that?

**Details:** I'm using this pattern for my pages content type which works perfectly when a page is in a menu.

```
[node:menu-link:parents:join-path]/[node:menu-link]

```

The problem is, when a page is not in a menu, it gets an empty path. I want to give it another path based on the "title" of the page, for example.

# Answer
Sadly, conditional tokens was requested many times and never implemented, so fallback you ask for is not possible.

You can use Rules instead. Description on Drupal.org claims it's easy - instead of pathauto, set up a rule on node creation / update, and create aliases needed. Rules support conditions, as you can see in Rules examples project, so you can create aliases conditionally all right.
> 0 votes

# Answer
You can now achieve this using hook\_pathauto\_pattern\_alter(). Something like:

```
<?php
/**
 * Implements hook_pathauto_pattern_alter().
 */
function mymodule_pathauto_pattern_alter(&$pattern, array $context) {
  // Alter any node entity path patterns we need to
  if (isset($context['data']['node'])) {
    $node = $context['data']['node'];

    switch ($node->type) {
      case 'page':
        // Check condition, and change the pattern when appropriate
        $pattern = '[node:title]';
        break;

    }
  }
?>

```
> 1 votes

# Answer
I took what m4olivei wrote and made it work for falling back to node title if no menu item is generated:

```
/**
 * Implements hook_pathauto_pattern_alter().
 */
function mymodule_pathauto_pattern_alter(&$pattern, array $context) {
  // Set up pathauto fallback to node title if no menu item is generated
  if (isset($context['data']) && isset($context['data']['node'])) {
    if (isset($context['data']['node']->menu) && isset($context['data']['node']->menu['enabled'])) {
      if (!$context['data']['node']->menu['enabled']) {
        $pattern = '[node:title]';
      }
    }
  }
}

```
> 0 votes

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


# Question
Title: How can I create a Views list of all users with either a node OR a comment?
I need to do some major user pruning. I run a Q&A site and need to find all users who have written a comment or created a node . Currently in Views I can't figure out how to do this.

Is it possible in Views or do I need a custom query ? What might that query look like?

Thanks!

# Answer
> 0 votes
As far as I know you can't create Views for more than one entity type. You would have to create separate Views, one for nodes and one for comments; you CAN however make them appear in the same page by using Views Field View. You can sort each view by author, and get rid of duplicates by using the Aggregation option.

**EDIT:** There IS a way to do two EntityFieldQuery (one for node and one for comment) and then create a single array of authors. Something like this:

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node');
$node_list = $query->execute();

$query2 = new EntityFieldQuery();
$query2->entityCondition('entity_type', 'comment');
$comment_list = $query2->execute();

$author_ids = Array();

$nodes = node_load_multiple(array_keys($node_list['node']));
foreach ($nodes as $node) {
  $author_ids[] = $node->uid;
}

$comments = comment_load_multiple(array_keys($comment_list['comment']));
foreach ($comments as $comment) {
  $author_ids[] = $comment->uid;
}

$author_ids = array_unique($author_ids);
dpm($author_ids);

```

You can then do whatever you want with the list of uid's - for example load the users and create a table programmatically for display.

---
Tags: views
---


# Question
Title: Search inside the view, if not found, how to set up no results behaviour?
All view need a No results behaviour, this applies to Courses list(view), information list(view) and activities list(view);please tell to how to do this

# Answer
Please set this at the field level or at the right corner at the views edit.

No Result Behaviour. If you want to set this with all the views than select All display at field level.
> 0 votes

# Answer
In the Advanced configuration section of the views, you will find **NO RESULTS BEHAVIOR**, you can use the 'Add' button next to it to select **Global: Text area** option. Then add your no result description there.

FYI, this is for **Drupal 7**.
> 0 votes

---
Tags: views
---


# Question
Title: Feeds: update nodes using a second import
Is there a way in which you can use a second feeds import, to update nodes created during a first import?

In my first import, I create nodes and save a custom ID (from old system), and I want to reuse that custom ID in the second import to update the existing nodes and add a taxonomy value.

1. First importer:

2. Second importer:

# Answer
To update existing content using feeds importer, you will have to mark **Customer ID** field as a ***Unique Key***.
> 2 votes

---
Tags: feeds
---


# Question
Title: Aplying image styles to images return 404 for images
When image styles are aplied to images the modified images are not created and the image url returns a 404 error. I've been checking for solutions and none worked for me. I commented the Options +FollowSymLinks in the .htaccess (https://www.drupal.org/node/1170440), I changed the files folder permissions to 777, I changed the theme and back... (image style (imagecache) images are not being created), and still nothing.

The worst part is that it was working fine until yesterday (at least i found it yesterday) and many of the pictures have their modified versions working, but not the new ones for which the url returns de 404.

Is there any thing I can do that I've not tried yet?

Thank you

# Answer
> 1 votes
I don't know what caused the issue but at the end I solved It following this steps:

http://www.aldibier.com/blog/articulo/drupal-7-cuando-no-aparecen-las-imagenes-generadas-por-image-style

1- Adding to the Nginx():

```
location @rewrite {
  # Some modules enforce no slash (/) at the end of the URL
  # Else this rewrite block wouldn't be needed (GlobalRedirect)
  rewrite ^ /index.php;
}

location ~ ^/sites/.*/files/styles/ {
  try_files $uri @rewrite;
}

```

2- Adding to the settings.php:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

3- Rebooting the server.

This solution may bypass the error since, for what I know, nothing in the server configuration was changed when the problem started so this shouldn't be the root of the problem.

# Answer
> 0 votes
This could still be a permission problem. You need to make sure webserver can write to the image style folder. You need to use something like `ls -al` to check the permissions and the ownership of that folder. You may have to change the ownership of that folder so web server can view and write to it. Add another image, clear your cache.

# Answer
> 0 votes
Have you checked if the modified file ACTUALLY does exist? Modified files (the files where the style has been applied) should be stored in the public directory, usually inside the folder `file/style/[name of style]/public/field/image`. Go to www.yoursite.com/admin/config/media/file-system to find out the path public the public directory. The path is different if the pictures are uploaded by your users, in which case the exact path can be found at `www.yoursite.com/admin/config/people/accounts`, scroll down to **Picture directory**.

I would check if the files are actually being created and stored in the first place, by going to the folders where they should be stored.

---
Tags: media
---


title: Dependent select and form rebuild?

text:
# Question
Title: Dependent select and form rebuild?
I would use 3 dependent selects using D7 Form Api #ajax. It almost works, that is, when I change the level 1 select, the level 2 is populated, then if I change the second one, the third is well populated.

But when I validate my form (ajax validation), if an error occurs (not related to the selects, just missing field, wrong value etc.), I return the whole form to display error messages. And in this case, the level 2 and level 3 select loose their options et selected value. And as the level 1 select keeps the selected value, I have to change it twice to polulate level 2 select again... not good.

I suppose I loose my selects options because the form is rebuild from cache, and the selects options are not in cache... So I'm doing something in the wrong way. Maybe related to selects or maybe related to form (maybe both !).

```
    // Called when select level n change to populate select level n+1
    // It does work, but in case of form rebuild, select level n+1 looses its
    // options
    function mymod_fiche_select_ajax_callback(&$form, &$form_state) {
      // Get select caller
      $sel1 = $form_state['triggering_element']["#name"];
      // Get its value
      $val1 = $form_state["input"][$sel1];

      // Get an array to get the next select level
      $info = mymod_var("select_ajax_$sel1");

      $tab=$info["TAB"];
      $col=$info["COL"];
      $table=$info["TABLE"];
      $fld=$info["FLD"];
      $linkfld=$info["LINKFLD"];
      $sel2=$info["SEL2"];

      // Get the options form database
      $options =  mymod_get_fen($table, array($linkfld=>$val1));

      // All my form are structured in tab/col
      $form['mc'][$tab]['form_container'][$col][$sel2]['#options']=$options;
      return $form['mc'][$tab]['form_container'][$col][$sel2];

    }

    // This function links two selects
    function mymod_fiche_select_ajax(&$form, &$form_state,$sel1, $sel2,$table,$tab){

      $linkfld=$sel1;
      $fld=$sel2;

      // Liste les colonnes (left/right)
      $cols=array("left","right");
      foreach($cols as $column){
        if (isset($form['mc'][$tab]['form_container'][$column][$sel1])){
          $formsel1 = &$form['mc'][$tab]['form_container'][$column][$sel1];
        }
        if (isset($form['mc'][$tab]['form_container'][$column][$sel2])){
          $formsel2 = &$form['mc'][$tab]['form_container'][$column][$sel2];
          $col=$column;
        }
        if (isset($formsel1) && isset($formsel2)){
          break;
        }
      }
      $wrapper="wrapper-$sel1-$sel2";
      if (isset($formsel1) && isset($formsel2)){
        $formsel1['#ajax'] = array(
                'callback' => 'mymod_fiche_select_ajax_callback',
                'wrapper' => $wrapper,
        );
        $formsel2['#prefix']=(isset($formsel2['#prefix']) ? $formsel2['#prefix']."<div id='$wrapper'>" : "<div id='$wrapper'>");
        $formsel2['#suffix']=(isset($formsel2['#suffix']) ? "</div>".$formsel2['#suffix'] : "</div>");

          // this will be get in the callback function
    mymod_var("select_ajax_$sel1",array("TABLE"=>$table,"FLD"=>$fld,"TAB"=>$tab,"LINKFLD"=>$linkfld,"SEL2"=>$sel2,"COL"=>$col));

        // sel1 initial value
        if (isset($formsel1["#default_value"]) && $formsel1["#default_value"]!=""){
          $options=mymod_get_fen($table, array($linkfld=>$formsel1["#default_value"]));
            $formsel2["#options"]=$options;
      /* select sample
      $form['mc'][$tab]['form_container'][$column][$field] = array(
          '#type' => 'select',
          '#access' => $access,
          '#title' => t($title),
          '#options' => $options,
          '#default_value' => $value,
          '#required' => $required,
          '#validated' => true,
          '#attributes' => array("class"=>array()),
      );*/
    }

    // Ajax validation function
function mymod_fiche_ajax(&$form, &$form_state){

        // Save changes in database
        $ret = mymod_query_form_save($form, $form_state);
        if ($ret==0){ // No change detected..
          return $form;
        }
        else if($ret==1) { // Changes saved without error
          $commands = array();
          $commands[] = ajax_command_invoke(NULL, 'fen_close');
          return array(
              '#type' => 'ajax',
              '#commands' => $commands,
          );
        }
        else{ // Errors detected, returning form to display messages
          $form_state['rebuild'] = true;
          return $form; // $ret contient la form + messages d'erreur
        }
      }

```

Thanks in advance.

# Answer
> 0 votes
Ok, I found my mistake : The ajax callback function must not modify $form.

So my code is now :

```
        // Called when select level n change to populate select level n+1
        // It does work
        // Not &$form, &$form_state, just $form, $form_state as parameters
        function mymod_fiche_select_ajax_callback($form, $form_state) {
          // Get select caller
          $sel1 = $form_state['triggering_element']["#name"];
          // Get its value
          $val1 = $form_state["input"][$sel1];

          // Get an array to get the next select level
          $info = mymod_var("select_ajax_$sel1");

          $tab=$info["TAB"];
          $col=$info["COL"];
          $table=$info["TABLE"];
          $fld=$info["FLD"];
          $linkfld=$info["LINKFLD"];
          $sel2=$info["SEL2"];

          // Get the options form database
          $options =  mymod_get_fen($table, array($linkfld=>$val1));

          // All my form are structured in tab/col
/*  NO !
Instead of that, I now use a function to populate my select in my main form function.
          $form['mc'][$tab]['form_container'][$col][$sel2]['#options']=$options;

*/
          // I replace the code above by this one (just save new options to read them in the main form function
          mymod_var("ysSelect_$sel2",$options);

          // Return the element to tell drupal to rebuild it
          return $form['mc'][$tab]['form_container'][$col][$sel2];

        }

```

What I understand, is that Drupal doesn't use the element I return ( $form\['mc'\]\[$tab\]\['form\_container'\]\[$col\]\[$sel2\]) to replace it "as is" using the wrapper. It does rebuild it before that. So the options have to be set in main form function, not in ajax callback.

---
Tags: forms
---


title: Contextual filter is not working

text:
# Question
Title: Contextual filter is not working
I have **views1** and **view2**, where in first view linked with view2 so I have given contextual filter in view both for entity reference field of view2.

Now my problem is when I pass nid of view1 at Preview with contextual filters: it not retaining any data the contextual filter is not working.

# Answer
> 0 votes
So you just need to place 1 contextual filter for nid and one relationship with referenced entity, and use that relationship in fields. See the attached screenshot of a demo view.

---
Tags: views
---


# Question
Title: How can I fix the "Could not delete temporary file"?
I'm getting below error when run cron:

> **The specified file could not be deleted, because it is not a valid URI. More information is available in the system log**.

Due to TMP files, my site will be crashed, again we will restored site and unable to clean **TMP** files in my live site.

# Answer
Change to another tmp folder destination? Configuration -\> file system

I not sure will this help you.
> 1 votes

---
Tags: 7, files, cron
---


# Question
Title: How can I collapsible the facet search block with checkbox
I need to create a collapsible facet search block with check-box. Has anyone done this type of functionality. I tried the Facet API Collapsible module but this modules provides the link and not the check-box.

# Answer
I did work on similar functionality, where the client wanted a set of check boxes inside the collapsible Facet Block. I found a module Collapsiblock which allows us to have check boxes inside the Facet Block. This module will most probably help you.
> 1 votes

---
Tags: search
---


title: How do I change a core error message?

text:
# Question
Title: How do I change a core error message?
I would like to change the default error message from Drupal core.

The error message is "Please Select the Valid File Format".

My problem is in brief below.

* I have created a CCK called 'Assignment'.
* There I have given the users an option to upload files.
* In such case if the user uploads invalid file format drupal will throw the error message as mentioned above.
* I need to change the error message in to "The file upload field cannot upload the speicified filed".

How can I achieve this?

**(Should not use string overrides module)**

Thanks in advance..

# Answer
> 3 votes
If that string is run through the t() function (which is probably is) and you don't want to use String Overrides, then you can update your settings file.

For Drupal 6, putting this in your "settings.php" file should work.

```
$conf["locale_custom_strings_en"] = array(
  "Please Select the Valid File Format" => "The file upload field cannot upload the speicified filed",
);

```

In Drupal 7, you would change it to

```
$conf["locale_custom_strings_en"][""] = array(
  "Please Select the Valid File Format" => "The file upload field cannot upload the speicified filed",
);

```

However, I am not seeing the string "Please Select the Valid File Format" in any of my D6 installs, and that is not the message I get when try to upload to a CCK filefield with the wrong file type or the MIME type doesn't match the file extension.

# Answer
> 3 votes
1. Get the messages using drupal\_get\_messages(). Make sure to leave the `$clear_queue` parameter at the default `true`.
2. Search the resulting array for the relevant messages and replace them. The resulting array is indexed by message type and the values are arrays of messages for that type (even if you only retrieve messages of a particular type).
3. Inject the messages back into the message queue using drupal\_set\_message().

Drupal retrieves the message queue in function theme\_status\_messages() which is called from template\_preprocess\_page(), so one place to achieve this would be an override of that theme function. Depending on the exact circumstances of the message, you might find some hook that is closer to the point when the message is generated.

Because the messages are rendered in template\_preprocess\_page(), an implementation of hook\_exit() is not an option, because this hook is invoked when the page is already rendered.

BTW: I often wished for a hook\_message\_alter().

# Answer
> 1 votes
I placed the following code in template\_preprocess\_page() and it worked perfectly. I'm not totally convinced this is the best way to do it but it was faster than building a module to generate the custom errors.

To get this done I looked at all the error messages generated by drupal\_get\_messages() and cycled through them. If they matched the string I was looking for I would then use drupal\_set\_message() to generate the error with new text. The final step was to pass the remaining errors through drupal\_set\_message() otherwise they wouldn't be called.

Again I'm not certain this is the best way of pulling it off, if anyone has any suggestions on how to do this in the theme layer I'd love to hear them.

```
$getmsg = drupal_get_messages('error');
    if ($getmsg){
      foreach($getmsg['error'] as $err) {

          switch($err) {
          case 'SUBSCRIBE TO THE NEWSLETTER field is required.':
            drupal_set_message('Sorry, you must sign up to the newsletter to enter', 'error');
          break;
          case 'I AGREE WITH THE CONTEST RULES & REGULATIONS</a> field is required.':
            drupal_set_message('Sorry, you must agree to the rules and regulations', 'error');
          break;
          default:
            drupal_set_message(t($err), 'error', FALSE);
          break;
        }

      }
    }

```

# Answer
> 0 votes
The easiest way is to use the String Overrides module.

Install the module and you can replace the string with your own string. The string overrides module also allows you to replace any string wrapped in the `t()` function.

# Answer
> 0 votes
### Drupal 7

You can customize error messages by using Field validation per entity field.

To do that, edit field settings, go to Validation and add a new validation rule (*Required field* rule). There, you should have textfield to set-up *Custom error message* for that field.

---
Tags: 6, entities
---


# Question
Title: How to override checkout form validation error message?
Im using D7 and Ubercart 3. But I think this is more a form question than anything else. When validating the checkout form I get a list of errors saying fields are required. And thats all fun and stuff, but I just want the error to say:

> Please complete the form by filling out the highlighted fields.

And only once off course.

# Answer
You'll want to use: `theme_status_messages`.

First, use `drupal_get_messages` to clear the queue.

Then, use `drupal_set_message` to add your new generic message.
> 1 votes

# Answer
Although @jdu solution will get you there, it seems like it will effect all messages rather than target this specific form. I would be inclined to use something a bit more specific:

Within template.php OR a custom module:

```
function themename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'formid_form') {
    array_push($form['#validate'], 'custom_form_validation');
  }
}

function custom_form_validation($form, &$form_state) {
  if ($_SESSION['messages']['error']) {
    drupal_get_messages('error');
    drupal_set_message('Please review the form for errors', 'error');
  }
}

```
> 0 votes

# Answer
By default the common validation messages is provided by IFE module.

Other alternative could be to use Field validation and its form validation rules (*Required field* rule). Alternatively check Rules module with the relevant condition/action rules.
> 0 votes

---
Tags: 7, ubercart, forms
---


# Question
Title: How to force drupal to use English version of the field?
I have bean block with a list (list\_block) of other bean blocks (content\_block) which I use in slider. I have multilingual site, so I have 2 languages English and Spanish. Each content\_block has translation (so it has both English and Spanish variants). So the problem is:

I have an empty field Description in one of my content\_blocks and it's empty only for English version, but it has data in Spanish version. So when I go to see the slider (with the list of content\_blocks) on my homepage in English version I see Spanish value of this field but not empty value. When I add English value to that field the problem disappearing and English value appears in the slider. So why this happening? And **how to force Drupal to use English version of the field even if it has no value but it has Spanish version of the field** ?

# Answer
> 0 votes
Go to the Views admin of the block, and filter by language. It will automatically only show the node in the language that you select.

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


title: Coding standards for long strings?

text:
# Question
Title: Coding standards for long strings?
I've been looking for some official guidelines on how to format long strings in module code, but the closest thing I've found is an ambiguous section on indenting long SQL queries which suggests any of the following styles:

```
$text = '
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula odio,
  hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer
  hendrerit varius felis id dignissim.
';

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula'
. 'odio, hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer'
. 'hendrerit varius felis id dignissim.'
;

$text = <<<TEXT
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula odio,
  hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer
  hendrerit varius felis id dignissim.
TEXT;

```

The Drupal Coding Standards talk about how to use the concatenation *assignment* operator:

```
$string .= 'Foo';
$string .= $bar;
$string .= baz();

```

but they don't actually state whether single long strings should be broken up that way.

To add further confusion, the Coder module handles long strings differently again in its "good.php" test file:

```
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ' .
        'ligula odio, hendrerit consectetur porta vitae, sollicitudin sit ' .
        'amet eros. Integer hendrerit varius felis id dignissim.';

```

Personally, I've just been doing it like this until now:

```
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula
        odio, hendrerit consectetur porta vitae, sollicitudin sit amet eros.
        Integer hendrerit varius felis id dignissim.';

```

However, I'd like to start doing it the "right" way (if there is one). Does anyone have a definitive answer?

# Answer
> 2 votes
Drupal does not restrict the usage of long strings in code. It is advisable to concatenate each line ($output .= '...';) for a readable code, but as you can see in Drupal code, long strings are not broken up, especially when used with t():

```
function field_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.field':
      $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#';
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Field module allows custom data fields to be defined for <em>entity</em> types (see below). The Field module takes care of storing, loading, editing, and rendering field data. Most users will not interact with the Field module directly, but will instead use the <a href=":field-ui-help">Field UI module</a> user interface. Module developers can use the Field API to make new entity types "fieldable" and thus allow fields to be attached to them. For more information, see the <a href=":field">online documentation for the Field module</a>.', array(':field-ui-help' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) :'#', ':field' => 'https://www.drupal.org/documentation/modules/field')). '</p>';
      $output .= '<h3>' . t('Terminology') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Entities and entity types') . '</dt>';
      $output .= '<dd>' . t('The website\'s content and configuration is managed using <em>entities</em>, which are grouped into <em>entity types</em>. <em>Content entity types</em> are the entity types for site content (such as the main site content, comments, custom blocks, taxonomy terms, and user accounts). <em>Configuration entity types</em> are used to store configuration information for your site, such as individual views in the Views module, and settings for your main site content types.') . '</dd>';
      $output .= '<dt>' . t('Entity sub-types') . '</dt>';
      $output .= '<dd>' . t('Some content entity types are further grouped into sub-types (for example, you could have article and page content types within the main site content entity type, and tag and category vocabularies within the taxonomy term entity type); other entity types, such as user accounts, do not have sub-types. Programmers use the term <em>bundle</em> for entity sub-types.') . '</dd>';
      $output .= '<dt>' . t('Fields and field types') . '</dt>';
      $output .= '<dd>' . t('Content entity types and sub-types store most of their text, file, and other information in <em>fields</em>. Fields are grouped by <em>field type</em>; field types define what type of data can be stored in that field, such as text, images, or taxonomy term references.') . '</dd>';

```

I would stick with this drupal usage, this is the best compromise for usage and good readability. Your first examples looks good, but adds extra line feeds. The second example is not good to read and the third is often used in scripts, but not very common in php code.

---
Tags: coding-standards
---


title: Chosing the container for a form

text:
# Question
Title: Chosing the container for a form
I am currently programmatically constructing a form. For that, I used the `hook_form()` . My form is displayed and all its functionality are good.

The problem is that it is not displayed inside the `div` container as it normally should be. Anyone knows how to define, maybe as an attribute, the form in this tag?

# Answer
in `hook_form`:

```
$form['first_element'] = array(
  '#prefix' => '<div class="wrapper>',
  '#title' => t('First name'),
  '#type' => 'textfield',
  '#default_value' => '0',
  '#required' => TRUE,
);
$form['last_element'] = array(
  '#suffix' => '</div>',
  '#title' => t('First name'),
  '#type' => 'textfield',
  '#default_value' => '0',
  '#required' => TRUE,
);
return $form

```
> 1 votes

---
Tags: forms, webforms
---


# Question
Title: Display content between squares with links
I want to build a Drupal 7 website with big squares which contain a title and some text. In a desktop layout there will be 3 rows of 3 squares. Each square is a link to one or more underlaying pages. I am thinking of using the views module to make this work.

After clicking on a square, the content of the underlaying page has to be displayed right under the row of this square. So, if a visitor clicks on a square in the first row, content should be displayed between row 1 and row 2. By clicking on a square in the second row, content should be displayed between row 2 and 3. I have no idea how to do this. Any suggestions would be welcome.

Thanks, Steven

# Answer
> 1 votes
What you want to do can be easily accomplished with **JavaScript and CSS**. And. since Drupal already ships with jQuery, you could make use of the `slideToggle()` effect to slide up and down your content.

**I'll give you a general idea:**

1. In Drupal, create a page that displays your 3 nodes. For example, you could create a View and show the *Title* and *Body* fields of your articles.
2. In your JavaScript, hide the *Body* field by default and then add a *click* event to your *Title* field, so when users click on it, the following *Body* field slides down or up.

```
$('#title-one').click(function() {
    $('#body-one').slideToggle();
});

```

Of course, this is just a starting point and *one* way of doing it. Good luck!

---
Tags: 7
---


# Question
Title: How to import multiple taxonomy terms from csv using Feeds
I have a csv with the following structure:

```
1024    Huwelijk
1024    Communie/Lentefeest
1024    Bedrijfsfeest
1024    Seminarie
1024    Koffietafel
1024    Receptie
1024    Jubileum
1024    Verjaardagsfeest
1024    Doopfeest / Baby borrel
1024    Vergadering

```

1024 is an ID I have linked to a node and want to use to update taxonomy terms.

When I run this importer , only the last Item (vergadering) is checked on the node.

All terms already exist in the vocabulary.

How can I process this so all items are checked on the node?

# Answer
Taxonomy CSV import/export

This module will help you to import the taxonomies in system.
> 1 votes

# Answer
You could put all the terms into a single row like

```
1024    Bedrijfsfeest, Seminarie, Koffietafel, Receptie

```
> 0 votes

---
Tags: taxonomy-terms, feeds, importing-exporting
---