# Question
Title: Render field collection multiple times on node.tpl.php
I have created a custom view mode for field collections with this code:

```
/**
 * Implements hook_entity_info_alter().
 */
function view_modes_entity_info_alter(&$entity_info) {
  $entity_info['field_collection_item']['view modes']['myviewmode'] = array(
    'label' => t('My view mode'),
    'custom settings' => TRUE,
  );
}

```

And I'm trying to render the field in the node.tpl.php using the view mode with this code:

```
$display = array(
  'label' => 'hidden',
  'type' => 'myviewmode',
);
$output = field_view_field('node', $node, 'field_page_collection', $display);
print render($output);

```

But the field is rendering with the default view mode, not with the custom one I created. Is there a way to render it using the new view mode??

Thanks a lot!

# Answer
You should read manual for field\_view\_field function.

1. **Do not use inside node (or any other entity) templates**; use render($content\[FIELD\_NAME\]) instead.
2. Do not use to display all fields in an entity; use field\_attach\_prepare\_view() and field\_attach\_view() instead.
3. The field\_view\_value() function can be used to output a single formatted field value, without label or wrapping field markup.
> 2 votes

---
Tags: entities
---


# Question
Title: Sending variable from php to js file not working
I've followed this : how to send variable from .php file to .js file?.

But following my code isn't working

What I want to do is whenever anybody logs in I want to send the login/password to browser javascript which will send it to another server.

It's only for a test case and not for production environment.

**Details**:

cyberoam.js

```
(function($) {
  Drupal.behaviors.cyberoam = {
    attach: function (context, settings) {

        alert(Drupal.settings.cyberoam.login) //on commenting this below alert works

      alert("hello");
    }
  };

})(jQuery);

```

In the cyberoam.module

```
function cyberoam_from_alter_submit(&$form, &$form_state)
{
     $username = $form_state['values']['name'];
     $password = $form_state['values']['pass'];

     dsm($username.':'.$password); //working fine

     drupal_add_js(array('cyberoam' => array('login' => $username )), 'setting');
}

```

What could be the problem? I've read same solution in multiple places but mine isn't working. In the Firebug console it shows TypeError: Drupal.settings.cyberoam is undefined

# Answer
You shouldn't set the values in the submit hook, you should use hook\_init().

In the submit hook you should set a variable ( `variable_set("name", "value")` ) and read it in the `hook_init` using `variable_get("name", "dafault_value")`;

On the other hand, you should **NEVER** add the password in js variables. It's a huge security risk.
> 0 votes

---
Tags: 7
---


# Question
Title: How can get five star rating data in drupal 6 services views?
i am using drupal 6.x, added five star(fivestar module) rating functionality to a node in my site. Everything working fine but i want to users rated data in drupal json services for mobile development, In json services i m getting nodes every data except rating.. so can you please help me. How can i get the users rating data in json services(Services\_view module).

Thanks in advance.

# Answer
You can use Services views module to achieve this,

**Procedure :**

Using services views you will need to add all your required fields on your views.

Step 1: For adding new view navigate to

```
[your-site]/admin/structure/views/add

```

Step 2: Adding your fields

You will fetch the resource as below,

```
http://example.com/<endpoint path>/views/<view name>

```
> 0 votes

---
Tags: 6, services, rating
---


# Question
Title: Where does drupal store LDAP server information?
I am looking for the location where drupal stores the LDAP server once it is set in the website.

# Answer
By default Drupal doesn't store any LDAP server information. If anything is stored by other modules, it's stored in the database. Depending on different modules, these data is saved in different tables.

If you're using LDAP module for Drupal 7, you can find the settings in `ldap_servers` table.

If you're using LDAP module for Drupal 6, you can find the settings in `ldapauth` table.
> 2 votes

# Answer
Looking at the ldap\_servers module install file it looks like it stores the server settings in a table called **ldap\_servers**.
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: Form added to content in hook_page_build lacks of AJAX
I'm adding a form to the footer using hook\_page\_build because a want to show it using a popup, so when user launches the popup the form appears inmediatly.

The problem is that the form is not AJAX processed: the submit button hasn't the ajax-processed class so AJAX is not working. But if I render the form using hook\_menu and drupal\_get\_form the form has the ajax-processed class and AJAX is working.

Form code fragment:

```
  $form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Your Personal Message'),
    '#default_value' => '',
    '#cols' => 50,
    '#rows' => 5,
    '#description' => '',
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send Message'),
    '#ajax' => array(
      'wrapper' => 'myform-wrp',
      'callback' => 'myform_ajax_callback',
    ),
  );

```

Implementation of hook page build:

```
function mymodule_page_build(&$page) {

  // Get the current $node
  [...]

  $form = drupal_get_form('mymodule_form', $node);

  $page['footer']['my_form'] = $form;

}

```

Hook menu that the retrieves a working AJAX form:

```
function mymodule_menu() {

  $items = array();

  $items['node/%node/mymodule-form'] = array(
    'title' => 'My form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form', 1),
    'access callback' => TRUE,
  );

  return $items;
}

```

I've tested it with hook\_page\_alter too.

What can be needed to ajaxify this form? I suppose is something related to adding the form too late...

# Answer
The problem is the element's name: submit. In the rendered page there's another form that have the same button name (submit), so the AJAX layer just ofund one of the buttons but not the two.

To fix this just rename the element's name:

```
 $form['myform-submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send Message'),
    '#ajax' => array(
      'wrapper' => 'myform-wrp',
      'callback' => 'myform_ajax_callback',
    ),
  );

```
> 0 votes

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


# Question
Title: Form validation after drupal_build_form in hook_node_view
In hook\_node\_view of one node I add a node form of a different content type as follows:

```
global $user;
$node_form = (object) array('uid' => $user->uid,
                            'name' => (isset($user->name) ? $user->name : ''),
                            'type' => 'my_type',
                            'language' => LANGUAGE_NONE
                            );
//create form state
$form_state['build_info']['args'] = array($node_form);

form_load_include($form_state, 'inc', 'node', 'node.pages');
$form = drupal_build_form('my_type_node_form', $form_state);

//change default save button
$form['actions']['submit']['#value'] = t("Nice Save");
$form['#validate'][] = 'my_module_my_validate';

//hide few fields
if(!in_array('administrator', $account -> roles)) {
    $form['field_field_1']['#access'] = FALSE;
    $form['field_field_2']['#access'] = FALSE;
    $form['field_field_3']['#access'] = FALSE;
}

$node -> content['my_form'] = $form;

```

All of above works great. Form is nicely displayed, fields are hidden, submit button value is changed and additional validation handler seems to be added correctly as `debug($form['#validate'])` returs:

```
array (
  0 => 'node_form_validate',
  1 => 'my_module_my_validate',
)

```

default validation is trigged as one of the fields in embedded form is required and left empty Drupal as expected returns: `My required filed field is required.` Node is created just fine using this form.

The problem is that for some reason my custom validate handler is not called at all.

```
/*
 *
 */
function my_module_my_validate($form, &$form_state) {
    debug('test');
    form_set_error('', 'error');
}

```

Am I missing something? I could potentially use `hook_form_alter` but I would like to get this working correctly.

# Answer
You do need a form alter. You're modifying the form array after it's already been built, which includes caching the form and processing the input.

> Form is nicely displayed, fields are hidden, submit button value is changed

Those are handled at render time, whereas the input processing (and therefore handler execution) are done at form build time. Or to put it another way, consider the form returned by `drupal_build_form()` as nothing more than a render array that happens to render a form. If you want a form array proper, you need to get the form via an alter (ie before `drupal_process_form()` is called on it).

You can use `hook_form_FORM_ID_alter()` if you want to target just one content type form, or `hook_form_BASE_FORM_ID_alter()` if you want to target multiple types or be dynamic. If you need to know within the form alter whether the form's embedded via a `hook_node_view()` you can pass that state via `$form_state`.
> 2 votes

---
Tags: 7, forms, nodes
---


# Question
Title: How do I remove gid from og_group_ref field's autocomplete?
At first I thought this was a job for `hook_preprocess_field()`; however, it then occurred to me that this field is populated by an ajax look up.

Where might be the best place to remove the group id from this? That is, how do I remove the *(2)* from the "TEST GROUP, Private" result pictured below?

I keep having users ask me why it's there.

I've also explored this in the Firefox Inspector. When I key in test, I see that requests are being sent to `/og/autocomplete/tags/og_group_ref/node/post/default/NULL/test`

And going a bit of work, I see that that path maps to these callbacks:

```
mysql> select path, page_callback from menu_router where path like 'og%';
+--------------------------------+------------------------------------------+
| path                           | page_callback                            |
+--------------------------------+------------------------------------------+
| og/autocomplete/single/%/%/%/% | og_entityreference_autocomplete_callback |
| og/autocomplete/tags/%/%/%/%   | og_entityreference_autocomplete_callback |
+--------------------------------+------------------------------------------+
2 rows in set (0.00 sec)

```

Which I find in these files:

```
$ grep -Rin 'og_entityreference_autocomplete_callback' *
profiles/commons/modules/contrib/og/includes/og.field.inc:313:function og_entityreference_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $field_mode, $entity_id = '', $string = '') {
profiles/commons/modules/contrib/og/og.module:100:    'page callback' => 'og_entityreference_autocomplete_callback',
profiles/commons/modules/contrib/og/og.module:107:    'page callback' => 'og_entityreference_autocomplete_callback',

```

And the callback function returns `entityreference_autocomplete_callback_get_matches`.

# Answer
Well, I changed the form field `og_group_ref` to a select box. This is enough to hide the group id number from users and has curbed confusion. Though I'd be happy to hear what others would do in this situation.
> 0 votes

# Answer
For Drupal 7 Commons we can override it using hook\_menu\_alter and hook\_form\_alter with the copy of OG and Entity reference functions. Also need a DB query to get the reference ID(nid) using the Group Title.

* **hook\_menu\_alter**

+ Alter OG autocomplete page callbacks
    ```

    /**
    *Implements hook_menu_alter
    */
    function hook_menu_alter(&$items) {
            $items['og/autocomplete/single/%/%/%/%']['page callback'] = 'override_entityreference_autocomplete_callback';
            $items['og/autocomplete/tags/%/%/%/%']['page callback'] = 'override_entityreference_autocomplete_callback';
    }

    ```
* **hook\_form\_alter**

+ Add custom form validation handler

    ```

    /**
    *Implement hook_form_alter()
    */
    function hook_form_alter(&$form, &$form_state, $form_id) {
            switch ($form_id) {//add your forms based on your requirement
                    case 'post_node_form':
                    case 'poll_node_form':
                    $value = preg_replace('/\s+\((\d+)\)/', '', $form['og_group_ref'][LANGUAGE_NONE][0]['default']['#default_value']);// On page load remove entity ID
                    $form['og_group_ref'][LANGUAGE_NONE][0]['default']['#default_value'] = $value;
                    $form['#validate'][] = 'override_form_validate';//custom validation handler
                    break;
             }
    }

    ```
    + **hook\_form\_validate function**

    ```

    /**
    *Implement hook_form_validate()
    *Function to handle the OG reference
    */
    function override_form_validate($form, &$form_state) {
      $ids = array();
      $def_arys = override_og_ref_autocomplete_handler($ids, $form_state['input']['og_group_ref']['und'][0]['default'], 'default');
      $cmp_ary = override_og_ref_autocomplete_handler($def_arys, $form_state['input']['og_group_ref']['und'][0]['admin'], 'admin');
      $i = 0;
      foreach ($cmp_ary as $fieldmode => $value) {
          foreach ($value as $key => $ogid) {
            //assign the reference ID
              $form_state['values']['og_group_ref'][LANGUAGE_NONE][$i]['target_id'] = $ogid['nid'];
              $form_state['values']['og_group_ref'][LANGUAGE_NONE][$i++]['field_mode'] = $fieldmode;
          }
      }
    }
    /**
    *Implementing OG autocomplete handler
    */
    function override_og_ref_autocomplete_handler($ids, $og_ids, $type) {
      $og_ids_ary = explode(',', $og_ids);
      foreach ($og_ids_ary as $key => $value) {
          $target_id = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('title', trim($value), '=')
            ->condition('type', 'group', '=')
            ->execute()
            ->fetchAssoc();
          $ids[$type][$key] = $target_id;
      }
      return $ids;
    }

    ```
    + Copy *og\_entityreference\_autocomplete\_callback* function from *profiles\commons\modules\contrib\og\includes\og.field.inc* and paste in your custom module and rename it to *override\_entityreference\_autocomplete\_callback*

    ```

    /**
    *Menu callback: autocomplete the label of an entity.
    *@param $type
    *The widget type (i.e. 'single' or 'tags').
    *@param $field_name
    *The name of the entity-reference field.
    *@param $entity_type
    *The entity type.
    *@param $bundle_name
    *The bundle name.
    *@param $field_mode
    *The field mode, "default" or "admin".
    *@param $entity_id
    *Optional; The entity ID the entity-reference field is attached to.
    *Defaults to ''.
    *@param $string
    *The label of the entity to query by.
    *@see entityreference_autocomplete_callback()
    */
    function override_entityreference_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $field_mode, $entity_id = '', $string = '') {
        $field = field_info_field($field_name);
        $instance = field_info_instance($entity_type, $field_name, $bundle_name);
        $instance = og_get_mocked_instance($instance, $field_mode);
            if (!$field || !$instance || $field['type'] != 'entityreference' || !field_access('edit', $field, $entity_type)) {
              return MENU_ACCESS_DENIED;
            }
            return override_entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id, $string);
    }

    ```
    + Also copy *entityreference\_autocomplete\_callback\_get\_matches* function from *profiles\commons\modules\contrib\entityreference\entityreference.module* and paste in your custom module and rename it to *override\_entityreference\_autocomplete\_callback\_get\_matches* and *remove ( entity\_id ) suffix*.

    ```

    /**
    *Return JSON based on given field, instance and string.
    *This function can be used by other modules that wish to pass a mocked
    *definition of the field on instance.
    *@param $type
    *The widget type (i.e. 'single' or 'tags').
    *@param $field
    *The field array defintion.
    *@param $instance
    *The instance array defintion.
    *@param $entity_type
    *The entity type.
    *@param $entity_id
    *Optional; The entity ID the entity-reference field is attached to.
    *Defaults to ''.
    *@param $string
    *The label of the entity to query by.
    */
    function override_entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') {
    $matches = array();
    $entity = NULL;
    if ($entity_id !== 'NULL') {
        $entity = entity_load_single($entity_type, $entity_id);
        $has_view_access = (entity_access('view', $entity_type, $entity) !== FALSE);
        $has_update_access = (entity_access('update', $entity_type, $entity) !== FALSE);
        if (!$entity || !($has_view_access || $has_update_access)) {
            return MENU_ACCESS_DENIED;
        }
    }
    $handler = entityreference_get_selection_handler($field, $instance, $entity_type, $entity);
    if ($type == 'tags') {
        // The user enters a comma-separated list of tags. We only autocomplete the last tag.
        $tags_typed = drupal_explode_tags($string);
        $tag_last = drupal_strtolower(array_pop($tags_typed));
        if (!empty($tag_last)) {
            $prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : '';
        }
    }
    else {
        // The user enters a single tag.
        $prefix = '';
        $tag_last = $string;
    }
    if (isset($tag_last)) {
        // Get an array of matching entities.
        $entity_labels = $handler->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator'], 10);
        // Loop through the products and convert them into autocomplete output.
        foreach ($entity_labels as $values) {
            foreach ($values as $entity_id => $label) {
                $key = "$label"; //removed the entity id
                // Strip things like starting/trailing white spaces, line breaks and tags.
                $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key)))));
                if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
                    $key = '"' . str_replace('"', '""', $key) . '"';
                }
                $matches[$prefix . $key] = '' . $label . '';
            }
        }
    }
    drupal_json_output($matches);
    }

    ```

Note: Add the additional conditions as per your requirements.
> 0 votes

---
Tags: organic-groups, entities, ajax, 7
---


# Question
Title: Image gallery as a field, not a content type?
Tutorials I've found seem to only cover creating Image Gallery content types. Any suggestions on how to make an image gallery as a field, rather than as a content type?

Ideally, I'd like to have something similar to the Photoswipe responsive galleries, but with captions, and appearing inside another content type, be it an article, basic page or in this case a new content type.

Perhaps there's simply something I'm missing about embedding one content type within another?

# Answer
> 1 votes
Make a View for your gallery and put that view in a block. Then activate that block for the desired content type; putting that block in the region you want it to appear.

# Answer
> 0 votes
Try this:

* Create a content type with image field. Create a view for that content type.
* create a tpl for the view
* Within the tpl you can write your code for Photoswipe responsive galleries.

Hope this helps.

# Answer
> 0 votes
Yes you can do this. First create a content type, for example an `article` then create another content type called `gallery` and insert your images in there, its display must be slideshow. download and install entity module and create a reference from `gallery` to `article`. in this way you can determine which image belongs to which `article`. download and install eva module. go to this link, it is a very good tutorial of `eva` module (you also need to set a contexual filter which in your case is going to be your article), then as I have asked in this address a filed which is your slideshow will be attached to the manage display of `article` content type. now it is field of `article` nodes and can be reordered.

**`"Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity.`**

**`The placement of the view in the entity's content can be reordered on the "Field Display" administration page for that entity, like other fields added using the Field UI module.`**

---
Tags: entities, media
---


# Question
Title: Drush Remote Aliases Line Wrapping Different Than Local Line Wrapping
We are using Drush version 5.9 and Drupal 7.27 and 7.26.

We have a variety of drush aliases, some marked specifically as REMOTE and one for the LOCAL instance.

Example for REMOTE: $aliases\['ALIASNAME'\] = array( 'root' =\> 'PATH', 'uri' =\> 'URI', 'remote-site' =\> TRUE, 'remote-host' =\> 'REMOTEHOSTDNS', 'remote-user' =\> 'DRUSHUSER', );

Example for LOCAL: $aliases\['ALIASNAME'\] = array( 'root' =\> 'PATH', 'uri' =\> 'URI', );

When we run a drush command for the LOCAL instance, the line wrapping in the output looks as expected. For REMOTE instances, the line wrapping is different and difficult to interpret.

Example of REMOTE Drush line wrapping:

```
Other        Fusion Starter Lite                Theme   Disabled       7.x-2.0
          (fusion_starter_lite)                                     -beta2

```

Example of LOCAL Drush line wrapping:

```
Other                                  Fusion Starter Lite (fusion_starter_lite)                           Theme   Disabled       7.x-2.0-beta2

```

What can we do to get the REMOTE line wrapping to match the LOCAL line wrapping style?

Thank you for your help.

# Answer
> 0 votes
I'm surprised no one has brought this up before. Perhaps it has come up, but I do not remember an incident about it. In any event, Drush does not pass the COLUMNS information to remote servers, so the remote side defaults to wrapping at 80 columns.

I added a commit to the master branch (Drush 7), 17c18fb331, to do this. I'll also open an issue to discuss backporting to Drush 6.

**UPDATE:**

I also committed this fix to the Drush 6.x branch. https://github.com/drush-ops/drush/issues/662

---
Tags: drush
---


# Question
Title: Teasers/summaries don't show when body begins with picture
I have a blog content type which uses a WYSIWYG editor and allows media to be inserted. Usually things work out fine, and the blog page shows a list of nice trimmed teasers and/or summaries. But when the blog post begins with a picture, the teasers and/or summaries don't show up on the blog page. Instead, there is just a --- where the text would normally be.

I tried deleting the

tags around the image, but it didn't help.

Any advice? (We have to continue using the WYSIWYG editor/media insert, so that part can't change, unfortunately.)

# Answer
Try this How to Add a WYSIWYG Editor to a "Text with Summary" Field if it works for you.
> 0 votes

---
Tags: media, wysiwyg, nodes, entities
---


title: Webform User Contact Form in Block

text:
# Question
Title: Webform User Contact Form in Block
I cant seem to find any solid info on how to do this in the Webform module, is there a function or a module that goes with webforms to do this?

Thanks

# Answer
Webforms when created are nodes by default. In drupal 6 there was a module called webform block (http://drupal.org/project/webformblock) this got encorprated into webform with webform 3 (which as your using drupal 7 you will be using, I dont think its even possible to get webform 2.x on D7)

To get the webform as block:

1. Create your webform in a node.
2. Edit the node.
3. Select the Webform tab.
4. Select the Forms settings tab.
5. Select the Forms settings tab.
6. Select Advanced settings.
7. Switch on Available as block.
8. Save configuration.

Source: http://drupal.org/node/1447436
> 12 votes

# Answer
Here's a video to show you how to make a web form block

http://www.youtube.com/watch?v=p5CLio9\_DfU
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How can I prevent anonymous users from accessing taxonomy pages?
I would like to prevent anonymous users from accessing any of the taxonomy pages on my site.

I am already using the Panels module to provide variants for each vocabulary, and these variants have access rules limiting them to authenticated users only. However, anonymous users can still access the default taxonomy pages provided by Drupal.

I thought about adding a new variant (301 redirect) and forcing anonymous users to the front page-- is there a better solution?

# Answer
Don't need to force using panels.

Having better solution to set permission for your taxonomy pages by code.

Default taxonomy page permission is 'Access content'.

Override that permission in your own by custom module.

**Using hook\_menu\_alter() to change permission**

Sample:

```
function [MODULENAME]_menu_alter(&$items) {
  $items['taxonomy/term/%']['access arguments'] = array('custom permission');
}

```

**Set that custom permission in your hook\_perm().**

sample :

```
function [MODULENAME]_perm() {
  return array('custom permission');
}

```

Clear your site cache once.

Then Goto admin/user/permissions

Set permission by role.
> 5 votes

# Answer
This video tutorial will show you how to hide pages from anonymous using panels

https://www.youtube.com/watch?v=cE14tLom8W8
> 0 votes

---
Tags: users, taxonomy-terms
---


# Question
Title: How do I access a field value in the $row variable in a field view theme template?
I'm overriding a field template for one of my views and I want to be able to access another field value from the $row variable. The documentation on the template file shows this:

> When fetching output from the $row, this construct should be used: $data = $row-\>{$field-\>field\_alias}

My field is called field\_calendar\_title, but the following doesn't work as expected:

```
$row->{$field->field_calendar_title}

```

I get the following error:

> Fatal error: Cannot access empty property...

Is the field "alias" different from the name of the field in the content type?

"Cleansed" output from var\_dump of $row:

```
stdClass Object
(
    [node_title] => ...
    [nid] => 568
    [field_data_field_performance_date_delta] => 0
    [field_data_field_performance_date_language] => und
    [field_data_field_performance_date_bundle] => event
    [field_data_field_performance_date_field_performance_date_val] => 2012-03-02 19:00:00
    [field_data_field_performance_date_node_entity_type] => node
    [_field_data] => Array
        (
            [nid] => Array
                (
                    [entity_type] => node
                    [entity] => stdClass Object
                        (
                            [vid] => 878
                            [uid] => 0
                            [title] => ...
                            [log] =>
                            [status] => 1
                            [comment] => 0
                            [promote] => 0
                            [sticky] => 0
                            [nid] => 568
                            [type] => event
                            [language] => und
                            [created] => 1329332968
                            [changed] => 1331836509
                            [tnid] => 0
                            [translate] => 0
                            [revision_timestamp] => 1331836509
                            [revision_uid] => 1
                            [body] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [value] => ...
                                                    [summary] => ...
                                                    [safe_summary] => ...
                                                )
                                        )
                                )
                                [field_resident_company] => Array ( [und] => Array ( [0] => Array ( [tid] => 3 ) ) )
                                [field_series] => Array ( [und] => Array ( [0] => Array ( [tid] => 36 ) ) )
                                [field_venue] => Array ( )
                                [field_rotator_image] => Array ( )
                                [field_exclude] => Array ( [und] => Array ( [0] => Array ( [value] => 0 ) ) )
                                [field_performance_image] => Array ( )
                                [field_premiere] => Array ( [und] => Array ( [0] => Array ( [value] => 1330714800 [timezone] => UTC [timezone_db] => UTC [date_type] => datestamp ) ) )
                                [field_closing] => Array ( [und] => Array ( [0] => Array ( [value] => 1330714800 [timezone] => UTC [timezone_db] => UTC [date_type] => datestamp ) ) )
                                [field_exclude_update] => Array ( [und] => Array ( [0] => Array ( [value] => 0 ) ) )
                                [field_performance_date] => Array ( [und] => Array ( [0] => Array ( [value] => 2012-03-02 19:00:00 [timezone] => UTC [timezone_db] => UTC [date_type] => datetime ) ) )
                                [field_performance_id] => Array ( [und] => Array ( [0] => Array ( [value] => 1436 [format] => [safe_value] => 1436 ) ) ) [field_event_status] => Array ( [und] => Array ( [0] => Array ( [value] => open ) ) )
                                [field_calendar_title] => Array ( [und] => Array ( [0] => Array ( [value] => PSYCHIC EXP [format] => [safe_value] => PSYCHIC EXP ) ) )
                                ...
                        )
)

```

# Answer
> 11 votes
From the looks of the `var_dump` you should be able to find your field value with this:

```
$row->_field_data['nid']['entity']->field_calendar_title['und'][0]['value'];

```

I really hope there's a better way than that though!

# Answer
> 7 votes
A simpler approach:

```
$rendered_field = $view->render_field($fieldname, $view->row_index);

```

Here, $fieldname is the original (not the view-aliased) fieldname, e.g. 'field\_myfield'.

# Answer
> 3 votes
Maybe a bit late, but for future reference here's my answer:

The description is pretty vague, but you should literally use:

`$row->{$field->field_alias}`

In your template file it is also noted that:

Variables available:

* $view: The view object
* $field: The field handler object that can process the input
* $row: The raw SQL result that can be used
* $output: The processed output that will normally be used.

In $field there's a field called field\_alias. So `$row->{$field->field_alias}` is actually pointing to, in your case, field\_calendar\_title.

Try making a var\_dump of $field and you'll see for yourself.

Hope this helps anyone coming across this post.

Gerben

# Answer
> -1 votes
The simplest way is : $fields\["field\_name"\]-\>content; Where field\_name -\> cck field name.

Hope that will help !!

Cheers ! Raj

---
Tags: 7, views
---


# Question
Title: Output of entity_metadata_wrapper does not dump to dsm()/dpm()
Given this code in a theme\_preprocess\_page($vars)..

```
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
dsm($wrapper);

```

Why doesn't $wrapper produce a debug dump in dsm() or dsp()? I can get data using print\_r. Can someone please explain this?

# Answer
> 16 votes
Never mind, I found it. Leaving the answer here for anyone who follows

Basically, `dpm($wrapper->getPropertyInfo());`

https://drupal.stackexchange.com/a/42542

---
Tags: entities
---


# Question
Title: Do Drupal 8 / backbone.js have conflict when using AngularJS on top?
I've just pulled D8 HEAD for my website and I want to use AngularJS instead of backbone.js to create a web app but realized D8 have already embedded backbone.js on every page.

I can disable modules that depends on it like edit or ckeditor if needed.

Even if I could disable it on a specific custom path I create with my module is still a good alternative for now.

There is also a conflict with Twig and AngularJS double curly braces in Drupal 8.

# Answer
Seems like Backbone.js and AngularJS don't have conflict if used in the same page.

So one can ignore Backbone.js existence and do stuff with AngularJS.

Still there might be better ways doing this in future since D8 is still in development as I post this.

And for curly braces conflict with Twig in AngularJS we can config **interpolateProvider** service explained here
> 1 votes

# Answer
It's not a perfect solution but you can use `hook_library_alter(array &$library, $name)` and just set css, js or dependencies of the library to empty arrays(since it's not possible to really just remove the library from the list). Though libraries depending on the one you are altering wll break so I wouldn't recommend it.
> 0 votes

---
Tags: 8
---


# Question
Title: How can I map multiple fields to one 'parent' field?
What I want to do is best illustrated with an example.

Apartments have different price ranges for different units according to how many bedrooms/bathrooms those units have.

How could I set up a content type that will allow me to do something like this:

$500 -- 5br/4ba

$400 -- 4br/3ba

$350 -- 4br/2ba

In the above example each price range has a corresponding 'bedroom' and 'bathroom' value. In order for this to work I need to map these price ranges to these values. Each apartment entity can have up to 10 of these mapping pairs.

I hope this makes sense. I can't figure out how to set up the content type.

Thanks for your patience and help.

# Answer
See this example post on Select lists for content types: How to have CCK "Select list" field on my content type?

you would just make the values for the list option as (`value | display text`):

```
500 | $500 - 5br/4ba
400 | $400 - 4br/3ba
350 | $350 - 4br/2ba
... 6 more options of whatever conditions ...
 25 | $25 - you sleep in the closet

```

This price field could allow up to 10 values if that's your limit.

Since the keys (values) of the prices are integers. You could SUM or Aggregate the values using Views if needed.
> 0 votes

# Answer
Have you looked at Conditional Fields?

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.

With this module, I think that you could create a scheme whereby the field containing the bed/bath values would be dependent on the field containing the price values. Selecting $500 (for example) would automatically update the bed/bath value for the node with '5br/4ba'. Not entirely sure if that's what you're looking for.
> 0 votes

---
Tags: entities
---


title: Listing Latest Blog Post in a Block

text:
# Question
Title: Listing Latest Blog Post in a Block
This is my first time using Drupal so I'm not entirely sure if I'm asking the right questions. I come from a WordPress background so I may be approaching this problem in the wrong manner.

I'm attempting to create a list of the latest blog post in a block that I created. How would I go about doing something like this? Would I list it via PHP within the block editor or is there some type of module (?) that I should be using? Any help would be much appreciated.

# Answer
The easiest way is to create a block view of nodes (of whatever type you are calling a post). You actually create the block in Views. Views are one of the things that separates Drupal from WordPress. If you have no idea what they are, check out this page.
> 0 votes

---
Tags: blocks, nodes
---


# Question
Title: Prevent editing for role after date in field
Individual nodes of a content type need to have their edit capability for a role removed after a date provided by a CCK field. The idea is that these nodes are entered by various roles, given a "start date" and displayed on the site in a few layouts. After the start date has passed, the node should be uneditable by this specific role.

How can this be achieved, is it possible by using a module-only method or can it be done in code?

# Answer
Yes, you can do that with

`hook_node_access`

For example, something like:

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

  // If editing target node type
  if ($op == "edit" && $node->type == 'target_type') {
    // Check against passed account or current user
    if (empty($account)) {
      $account = $GLOBALS['user'];
    }
    // If date field is set, user has target role and date is in the past
    if(isset($node->field_target_date[LANGAUGE_NONE][0]['value'])){
      $date = $node->field_target_date[LANGAUGE_NONE][0]['value'];
      if((in_array('target_role', $account->roles)) && (REQUEST_TIME > strtotime($date))){
        // Deny edit access
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;

}

```
> 1 votes

---
Tags: 7, users
---


# Question
Title: With states, how to uncheck a disabled checkbox, but not check it when it becames enabled?
I have a Form API checkbox that can be enabled and disabled by another ("parent") one:

```
$form['my_checkbox']['#states'] = array(
  'enabled' => array(
    ':input[identifier="parent"]' => array('checked' => TRUE),
  ),
);

```

Works like a charm, but now I want it to get cleared if it is dizabled. So I made my code look like this:

```
$form['my_checkbox']['#states'] = array(
  'enabled' => array(
    '[:input[identifier="parent"]' => array('checked' => TRUE),
  ),
  'unchecked' => array(
    ':input[identifier="self"]' => array('disabled' => TRUE),
  ),
);

```

Sadly, this also automatically checks that checkbox when it becomes enabled, and that's not what I want - I want to give my user an option, but not suggest him to check that field at all.

Can this "one way" action be achieved with `'#states'`? If so, how? Or is it always two way deal, and there is no option to uncheck on disabling without checking on enabling?

Note: I tried to use both disabled and enabled of self, and checked & unchecked of parent, with the same results.

I know I can achieve it with behavior, that's how I have it done now, but states api is there to avoid behavior's complexity and my use case seems pretty simple.

# Answer
Turns out that with current implementation of states it is not possible. When condition gets true, state is applied, and when it gets false, state gets removed. No way around it so far, not without hacking core, so it's more feasible to write custom behaviors instead.
> 5 votes

# Answer
it's possible create states with unchecked.

See https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_process\_states/7

\[\]'s
> -2 votes

---
Tags: javascript
---


title: In views how to merge two columns?

text:
# Question
Title: In views how to merge two columns?
I am using Views to display submitted contents as table and I need to merge two columns ("Uploaded covering letter" and "Uploaded e-book") into one.

How can I achieve this?

# Answer
> 4 votes
You first need to add one more field in your view i.e **Global Custom Text**.

After that you need to merge your two fields result in this field output using **Replacement patterns**

As in attached screenshot, I am merging *nid* and *first name* field in global custom text field output.

You also need to exclude "Uploaded covering letter" and "Uploaded e-book" field from output using **Exclude from display** attribute. You need to checked this check box for both the fields.

---
Tags: views
---


# Question
Title: I'm trying to set a $page variable but it's not working.
i'm studying, trying hard to understand what is show in the kpr($page) output. So as an exercise, I'm trying to change #show\_messages element. by default, i get this

```
....(Array, 10 elements)
◦ #show_messages (Boolean) TRUE

```

so in the theme\_hook\_alter() function i did this (before the kpr() output).

```
$page['show_messages'] = FALSE;

```

but when i refresh it's not changing the output. why is that.

also, i don't really understand the difference between elements with a # before them and the ones without.

# Answer
```
<?php

/**
 * Implements hook_preprocess_HOOK()
 *
 */
function YOURTHEME_preprocess_page(&$vars) {

    // All you need to do is to set the appropriate preprocess variable:
    $vars['show_messages'] = false;

    /**
    We also have $vars['page'] which is an array.

    $page = $vars['page'];
    This array is a Drupal Render Array which means would pass through drupal_render() function.
    In a Render Array keys starting with # are attributes and the others are children elements.
    Read more about that on @see https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_render/7

    */
}

```
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: Rewrite rules for Development & Production Environments
I'm having trouble with the file path when I upload my development environment to the server.

The problem is actually quite simple.
Development is working on the root folder ( development.tld )
Production is working on the sub-folder ( production.tld/**sub-folder** )

When I **manually** add a image in node content on the development environment, the path to that file is `/sites/default/files/test.jpg`

That path will not work in the production environment because of the sub-folder.

**Sample node content:**

```
<div class="row">
    <div class="span6">
        <img alt="test 1" src="/sites/default/files/test1.jpg">
    </div>

    <div class="span6">
        <img alt="test 2" src="/sites/default/files/test2.jpg">
    </div>
</div>

```

`RewriteBase /sub-folder` method works properly in general but I need to remap requests for the manually added assets
`( /sites/default/files/* **to** /sub-folder/sites/default/files/* )`

Is there a Rewrite rules for this process?

Thank you.

# Answer
> 0 votes
Try changing (or assigning) the base url in sites/default/settings.php

# Answer
> 0 votes
Try changing the path of **public file system path**,

Navigate to `example.com/admin/config/media/file-system`

---
Tags: 7, .htaccess
---


# Question
Title: How to disable Create new revision option in a node programmatically
I am trying to disable the 'Create new revision option' in each existing nodes programmatically. I tried with below codes but it was not working.

```
$results = db_select('node', 'n')
->fields('n', array('nid','vid'))
->execute();
foreach ($results as $result) {
$node = node_load($result->nid);
// Disabling the Create new revision option
$node->revision = FALSE;
node_save($node);
}

```

Can anyone help me on this? Thanks.

# Answer
Code you have mentioned in your question solves the problem of create new revision or just update with out a new revision when a node is updated programatically in that particular instance.. It has nothing to do with form option in node edit page...

When you do `$node->revision = FALSE;`

It is just like telling to node your are updating should be saved as a new revision or not when a node is updated at that particular instance of node\_save...

Use hook\_form\_alter to disable this option in node edit page form..

in your custom module implement MODULE\_form\_alter and check for node id's you want to disable this option..

```
$form['revision_information']['#access'] = FALSE;

```

OR

```
$form['revision_information']['#disabled'] = TRUE;

```
> 3 votes

# Answer
Seems like you are not getting the correct data in the array `$results`

Try this,

```
    $results = array();
    $results = db_select('node', 'n')
    ->fields('n',array('nid','vid'))
    ->execute()
    ->fetchAll();
    foreach ($results as $result) {
    $node = node_load($result->nid);
    // Disabling the Create new revision option
    $node->revision = FALSE;
    node_save($node);
    }

```
> 2 votes

---
Tags: nodes
---


# Question
Title: Request a new password using username only
We don't want to use email id for request a new password. How can we accomplish this without customizing/touching to core module.

# Answer
> 2 votes
User module accepts either username or email to reset password.. Code goes below in user module...

```
/**
 * Form builder; Request a password reset.
 *
 * @ingroup forms
 * @see user_pass_validate()
 * @see user_pass_submit()
 */
function user_pass() {
  global $user;

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username or e-mail address'),
    '#size' => 60,
    '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH),
    '#required' => TRUE,
    '#default_value' => isset($_GET['name']) ? $_GET['name'] : '',
  );
  // Allow logged in users to request this also.
  if ($user->uid > 0) {
    $form['name']['#type'] = 'value';
    $form['name']['#value'] = $user->mail;
    $form['mail'] = array(
      '#prefix' => '<p>',
      '#markup' =>  t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the e-mail.', array('%email' => $user->mail)),
      '#suffix' => '</p>',
    );
  }
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password'));

  return $form;
}

function user_pass_validate($form, &$form_state) {
  $name = trim($form_state['values']['name']);
  // Try to load by email.
  $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1'));
  $account = reset($users);
  if (!$account) {
    // No success, try to load by name.
    $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
    $account = reset($users);
  }
  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }
  else {
    form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
  }
}

```

You need to implement hook\_form\_alter in your own custom module and alter above form validation to add your own which accepts only username... You can achieve using custom module with out touching Drupal core... In hook form alter check for form id user\_pass and override validate handlers like below..

```
$form['#validate'] = array('custom_module_user_pass_validation');

function custom_module_user_pass_validation(($form, &$form_state) {

}

```

---
Tags: users
---


# Question
Title: Is it valid to use entries in #default_value if they are not in the #options?
I have a form. On this form I have a select element, like this:

```
  array(
    '#type' => 'select',
    '#title' => t('Animals'),
    '#multiple' => TRUE,
    '#options' => array(
      'rat' => t('Rat'),
      'cat' => t('Cat'),
      'dog' => t('Dog'),
    ),
  );

```

I also have a function called `get_suggested_animals($user_id)`. Let's assume that this code works:

```
global $user;
print_r(get_suggested_animals($user->uid));

// Array
// (
//    [0] => lizard
//    [1] => cat
// )

```

Would it be OK to just write:

```
array(
    '#type' => 'select',
    '#title' => t('Animals'),
    '#multiple' => TRUE,
    '#options' => array(
      'rat' => t('Rat'),
      'cat' => t('Cat'),
      'dog' => t('Dog'),
    ),
    '#default_value' => get_suggested_animals($user->uid),
  );

```

without testing if default options are on the list of available ones? I know it works (in this example - only 'cat' is selected by default), it does not generate any warnings or anything, but I still feel uncertain if it's legit, or if there are hidden traps I simply don't know yet.

# Answer
Reading through the code of `form_process_select` it is obvious that the situation where `#default_value` is set, but the value isn't a valid option, is not being handled properly:

This piece of code may "fail" in that case:

```
// If the element is required and there is no #default_value, then add an
// empty option that will fail validation, so that the user is required to
// make a choice. Also, if there's a value for #empty_value or
// #empty_option, then add an option that represents emptiness.
if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
  $element += array(
    '#empty_value' => '',
    '#empty_option' => $required ? t('- Select -') : t('- None -'),
  );

```

In your sample code, you don't set `#required` for the select field. That is why you don't observe any effect.

However, in the general case, you can't supply a bogus value for `#default_value` and *always* be sure that theFAPI will treat it just the same as *not set* or *NULL* `#default_value`.

If change your example and set `#required` to `TRUE`, and `#multiple` to `FALSE`, you should be able to reproduce a situation where having a bogus default value (such as "lizard") behaves different from the default value being *NULL* or absent.
> 2 votes

# Answer
Garbage in, garbage out applies -- if `#default_value` is not an `#options` who knows and also who cares what will get into the page. Quite likely nothing good will happen cos if memory serves it'll try to use `#default_value` as an array index into `#options` and that can't possible work. So a notice might happen and depending on what we put into `form_select_options` the option might or might not appear.

This is all totally irrelevant because if you actually submit a value that doesn't exist in `#options` (whether by messing up your form building code or tampering with `POST`) then you will get a validation error.
> 0 votes

# Answer
I would use something like the below:

```
  '#type' => 'select',
    '#title' => t('Animals'),
    '#multiple' => TRUE,
    '#options' => array(
      0 => t(' - Select - '),
      'rat' => t('Rat'),
      'cat' => t('Cat'),
      'dog' => t('Dog'),
    ),
    '#default_value' => !empty($default = get_suggested_animals($user->uid)) ? $default : 0,

```

Using the ? and : in for #default value says that if the first condition is true (the default value is not empty), use that. Otherwise, default to 0 (the select option).
> -1 votes

---
Tags: forms
---


# Question
Title: Modifying an Existing Entity Column in hook_update_N
This is a tricky problem but here is the jist of it. I have an entity that has a property called revision\_id. Through hook\_update\_N I want to do 2 things.

* Change the db column name to node\_id
* Convert the data in this db column from VIDs to NIDs

The code that takes care of this is...

```
function research_annotator_update_7100(&$sandbox) {

  // Change the db column.
  db_change_field(
    'research_annotator_annotation',
    'revision_id',
    'node_id',
    array(
      'description' => 'The node the annotation belongs to.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => 0,
    )
  );

  cache_clear_all();

  // Change revision ids into node ids.
  $arr_annotations = entity_load('research_annotation');

  foreach ($arr_annotations as $o_annotation) {
    $o_annotatedNode = node_load(NULL, $o_annotation->node_id);
    $o_annotation->node_id = $o_annotatedNode->nid;
    entity_save('research_annotation', $o_annotation);
  }
}

```

I also updated the entity property definition to represent the new node\_id column...

```
research_annotator_entity_property_info() {

  $arr_propertyInfo = array();

  $arr_propertyInfo['research_annotation'] = array(
  'properties' => array(
    'node_id' => array(
      'label' => t('Revision'),
      'type' => 'integer',
      'description' => t('The revision id this annotation belongs to.'),
      'setter callback' => 'entity_property_verbatim_set',
      'required' => TRUE,
      'schema field' => 'node_id',
    ),
    ...snip

```

The problem is, when I run the update the first time, it gives me the following error...

**Failed: PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'base.revision\_id' in 'field list' ...**

In the database, the changes have been made to the column but the data has not been converted. If I clear all caches and run the update again then everything works as planned. I suspect that because the entity cache is not cleared after the db column change, the error appears.

If this is the case, how can I ensure the entity cache is cleared immediately after db\_change\_field is called in the update hook?

# Answer
`cache_clear_all()` with no arguments clears `cache_block` and `cache_page` only; entity and schema cache both live in the `cache` table, so clearing that bin explicitly should do the trick:

```
cache_clear_all(NULL, 'cache');

```

Or if you want to clear the specific entries:

```
cache_clear_all('entity_info', 'cache', TRUE);
cache_clear_all('entity_property_info', 'cache', TRUE);
cache_clear_all('schema', 'cache', TRUE);

```

I'm assuming you've already updated your `hook_schema()` implementation to match the new scheme, or implemented `hook_schema_alter()` for the same if you're doing this on behalf of a different module.
> 0 votes

# Answer
For whatever reason,

```
cache_clear_all(NULL, 'cache');

```

does not work in update hooks.

Instead you will have to clear cache table in a much more direct manner.

```
db_truncate('cache')->execute();

```
> 0 votes

# Answer
Holy... don't use the entity API in update hooks. That won't lead to anything good. Just use a direct SQL query, this can be done nice and easy with `UPDATE {whatevertable} SET node_id = (SELECT vid FROM {node} WHERE nid = node_id)` boom!
> 0 votes

---
Tags: entities, updating
---


title: views3 and SELECT

text:
# Question
Title: views3 and SELECT
I use D7 and Views3.

When I make a view with images don't appear in sql statements the reference after SELECT at the images.

I'd like to see a complete SQL statement for my development.

I don't believe it is a configuration problem.

# Answer
As you say this, **I'd like to see a complete SQL statement for my development.**

**Step 1:** Navigate to `http://example/admin/structure/views/settings` and select the option **Show the SQL query** as in picture.

**Step 2:** Now try adding new or editing your views, below the views edit section there you can see all your SQL statements.
> 0 votes

---
Tags: views
---


title: Just want to submit field values

text:
# Question
Title: Just want to submit field values
Created a custom form, which submit values to a table. Fields on the form created on the go. For example if we have 5 users, we will have 5 fields, if 6 then six fields

Say if it has 5 fields

```
Field 01
Field 02
Field 03
Field 04
Field 05

```

Just want to submit all values of all fields being created on the go.

when I dsm

```
dsm[$form_state[values]];

```

It shows me array with form fields and form info like

```
Field 01
Field 02
Field 03
Field 04
Field 05
form_build_id
form_token
...
..

```

So I can't just run loop to submit all fields because 'form\_build\_id' etc is also there.

How can I do this dynamically?

# Answer
```
$user_ids = array(1, 2, 3, 4, 5, 6); // This will be dynamic based on your users

foreach ($user_ids as $uid) {
  // Your form element goes here
  $form['field_user_value_' . $uid ] = array(
    // form elements
  );
}

```

In your submit function you have above values

```
$values = $form_submit['values'];

foreach ($values as $key => $values) {
  if ($substr($key, 0, 17) == "field_user_value_") {
    // Push values to database
  }
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to display different page content to Anonymous user and to Authenticated User in drupal 7.x?
Am don't have much knowledge on drupal. Just starting my first drupal site. I created a "content" under a menu named "information". The menu "information" is given permission for both "anonymous user" and for "authenticated user" as well. As i click the menu "information" (as in anonymous user), the content i set was ***"please login as authenticated user, if you unable to login, please contact the administrator".***

Then, i login as the "Authenticated user" and i click the menu "information", am getting the same content message as **\*"please login as authenticated user, if you unable to login, please contact the administrator."**\*Please, i don't need this content message, under "information" menu if i login as the "authenticated user".

I needs to "DISPLAY DIFFERENT PAGE CONTENT TO ANONYMOUS AND TO AUTHENTICATED USER"? I don't know how to proceed this ? Can anybody please help me out the step by step procedure to do this task ? Please help me out . Thanks in advance...

# Answer
The "content" and "information" part of your question doesn't make sense to me. I'm posting a general guide to displaying different content on a per *role* basis, and you can update your question/comment if you need any part clarified.

I would use Panels. You can use it on either a custom page such as "example.com/information" or on a per conent basis to display different content or parts of the content, on a per *role* basis. Example below if for "content"/"nodes".

1. Install the Chaos tool suite (ctools) module, and Panels.
2. Enable the Page Manager and Panels modules.
3. Enable the node template.
4. Create a variant of type "Panel", call it "Authenticated user view".
5. Pick a suitable layout.
6. Go to the "Selection rules" settings and add a "User:role" setting to limit viewing to a certain role, such as authenticated user.
7. Go to the content tab, and add your "Node: Content" to a suitable region so that your content shows up.
8. Repeat steps 4-6 but call the variant "Anonymous user view". Make sure it's *below* the first variant in the list.
9. Add whatever you want your anonymous users to see to the second variant.
10. Save

That should be all. Using Panels requires a bit of understanding of the tools it provides, and I probably introduced a great deal of new Drupal terms to you in this answer. I recommend you start by viewing these videos here.
> 5 votes

# Answer
This video tutorial will show you how to display different content to different users

https://www.youtube.com/watch?v=cE14tLom8W8
> 0 votes

---
Tags: 7
---


title: Drupal SOLR search for attachments

text:
# Question
Title: Drupal SOLR search for attachments
Is there a way to search for files attached to taxonomy terms ?

I mean I have a vocabulary, with some terms. Each term have some files attached (Field) (Ex: example.pdf, Image.png).

I want my search to show that files, for example::

Search result:

--- Example.pdf

--- Image.png

Is that possible ? I don't want to search file contents, I just need filenames and path's shown on the search page.

Thanks and sorry for my english.

# Answer
> 0 votes
You can index taxonomy terms with this module: https://drupal.org/project/apachesolr\_term

There is a hook that allows you to specify a custom field for the solr index: hook\_apachesolr\_index\_document\_build\_' . \[entity type\]

Then you can add this field to the solr query by using: hook\_apachesolr\_query\_prepare

There is a more detailed article on how to do this here: http://rapiddg.com/blog/adding-customized-fields-apache-solr-index-drupal

---
Tags: 7, search
---


# Question
Title: What's best practice when working with the language[und]?
I'm starting to use this form to access data in my module. (See comment #1.)

```
$node->field_test[$node->language][0]['value']

```

I thought that looked like a pretty good solution, but further down that same question I found this:

> Don't assume that 'und' is for fields of entities without language, it is also for fields that are not translatable, and without the entity translation module that is all fields. Moreover, there are differences in this between the various 7.x versions of Drupal.
> Better to use the `field_get_items()` function which will sort out for you under what language code the data is stored.

And now I don't know if what I'm using could break something down the road.

# Answer
I find that using the Entity API module is a great help and also makes code more readable. The above code will not always work, since the language of the node and the language of the field can be different.

With the entity API module, and its wrapper, you can use the following code:

```
 $node_wrapper = entity_metadata_wrapper('node', $node);
 $field_val = $node_wrapper->field_test->value();

```

This should be bullet proof. One thing about using the entity module is that if you try to access a field that doesn't exist, you will get a nasty error and an exception thrown instead of a notice and wrong behavior.

To avoid this, you could do try/catch like this

```
try {
  $field_val = $node_wrapper->field_doesnt_exist->value();
} catch (EntityMetadataWrapperException $e) {
  $field_val = 'default/fallback value';
}

```

Or you can use `isset()` which `EntityMetadataWrapper` handles internally:

```
$field_val = 'default/fallback value';
if (isset($node_wrapper->field_doesnt_exist)) {
  $field_val = $node_wrapper->field_doesnt_exist->value();
}

```
> 40 votes

# Answer
For reading, you should always be able to use field\_get\_items(), which will pick the correct language for you and also check if the field has any values.

Unfortunately, the field API is very limited in 7.x, there is no way to get e.g. the first field item, don't even dare to ask about getting the value with a single function call... And there is no field\_set\_items() counterpart.

So yes, entity API module *does* provide a nicer API with the drawback that it also comes with quite a bit of overhead (It basically converts every single value to wrapper objects which have tons of nested property info arrays attached to them). Trying to dump an entity wrapper will usually get you either nothing or a wall of unreadable arrays.
> 19 votes

# Answer
```
$node = node_load($lot_id);
$field_language = field_language('node', $node, 'field_name');
$node->field_name[$field_language][0]['value'] = $custom_value;

```
> -2 votes

---
Tags: entities
---


# Question
Title: How to make the search engine use search api db?
I have installed search\_api, with search\_api\_db, create 2 indexes, one for node, one for users. The conf:

* server: search\_db server,
* 2 indexes: default\_node\_index and user\_index
* service class: database service

The one for users has parameters:

* field: email (fulltext)
* filter:role (limit to one only).

The index seems working good, it indexes the right number of users, I checked the uids in the db and it is corresponding to the good users. But still when I use the search (search/user/something), the search is on the names instead of emails, and the role filter is not applied. So in short, it is not using the search\_api\_db. It looks like the whole system is overriden by some other fulltext on everything search. I'm stuck here

# Answer
> 1 votes
So ok I found out what is my problem. I miss the other entity necessary to build to use the search api db: the search page using the search page module or views, instead of the system search page.

There is a tutorial here to have a more accurate and complete picture of the process: http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages

---
Tags: search
---


# Question
Title: Tried to create a custom page template for my home page and now get a 404 error
I'm new to Drupal so I may have done something horribly wrong.

Using Drupal 7.

I tried to create a custom home page by using the Page builder. I created a page template and assigned it to be used as the home page. Then decided against and deleted the template.

Now I get a 404 response when I go to my home page. The rest of the site works and shows all the pages. I tried clearing the cache but no luck.

Andy help or ideas would be greatly appreciated. Thank you

# Answer
> 0 votes
I figured out the answer. I needed to install the Panels module so that I could use it as a variant. And that allowed me to set my home page template the way I needed it to be. Sorry for any confusion I may have caused with my question. And thanks for the help!

---
Tags: theming
---


# Question
Title: View | So taxonomy terms plus some links associated with current taxonomy page
I have made a view that show taxonomy terms. What i want is show Taxonomy terms plus some content with. ex. I have Auto Manufactures like

```
Auto>
     Audi[taxonomy term :taxonomy/term/1]
     Renault[taxonomy term :taxonomy/term/2]
     Mazda[taxonomy term :taxonomy/term/3]
     [AllNon][content node/1 has field taxonomy ->selected:auto]

```

How i can make a view that shows taxonomy terms and include some content links. The content links is pages that use a taxonomy field.

# Answer
If I understand the question correctly:

* create a view (table) of the content type that contains the taxonomy terms
* add fields as appropriate
* add a `Content: Link` field that links to the actual content
* under Table Settings, Group by the taxonomy term

This will however, create multiple rows of the each taxonomy term (one for each node in which it is used).

If your intent was to create one row for each taxonomy term with multiple links (one for each node using that term), I don't believe you can do that in Views.
> 0 votes

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


title: Coldfusion - MsSQL to Drupal Mysql

text:
# Question
Title: Coldfusion - MsSQL to Drupal Mysql
I would like to receive some input on how you guys would approach the following:

We have an internal Projects Database application that was intially developed in ColdFusion and Microsoft SQL, approx. 5 - 6 years ago.

We now want to rebuild the entire application on the Drupal platform (with entities) and of course a Mysql Database, so far so good.

Now,

I am wondering how we approach the datamigration from one platform to the other. Basicly we want to migrate all the database records to the new Drupal database structure once the project is finished.

-\> Do we need to try and match the database structures when we are developing the platform in Drupal? Or will we have to write a migration script that matches all records one-by-one anyway?

-\> Are there tools out there that can assist us in this project?

Developing the new, empty Drupal platform is not a big deal, it's a lot of work (a lot of fields and views basicly), it's the data migration from the old one to the new one that i would like to receive some opinions on.

Thanks for your advice in advance!

Best Regards,

# Answer
> 1 votes
I would definitely start by looking at the Migrate module. It has a plugin for MSSQL. Then, with writing some code to extend the module, you can tailor your migration to fit your needs. You can define data sources and targets, extend the migration classes, hook into the migration function, run batch migrations to test, and many other cool stuff. It is also well documented and has a few examples and case studies. You can read the documentation here on how to use and extend the Migrate module to build and/or enhance your migration process.

---
Tags: database, entities
---


# Question
Title: Commerce: Unique single products + Custom line items, How to handle?
I am building a shop with several types of custom cushions available. Each product (cushion shape) will have different options therefore i am using custom line items.

The issue is that to me it seems i need to create just as many different content types (product display) in order to reference the custom line item in the add to cart form of the Display?

There must be better way to do this?

# Answer
Unfortunately there's not, you need a content type to match every line item type if you're dealing with different attribute fields. That was the original intention of Commerce custom product but it's at the point of providing different product types, but the feature hasn't been developed yet.
> 1 votes

---
Tags: commerce
---


# Question
Title: It is possible to have an action for the condition rules?
I have several conditions that are called in rules\_condition\_info () and wanted to have an action for each, for whenever a function returns true, it is called an action. I know it's probably possible, but how do I tell the action you want to perform a certain action for a certain condition ... thanks

# Answer
> 0 votes
Events, conditions and actions are bound together in a Rule. So to match them up you need to define them in your Rule. I am assuming you want to create a Rule programmatically to go along with your hooks?

You can define events, conditions and actions, as you say with `hook_rules_event_info()`, `hook_rules_condition_info()` and `hook_rules_action_info()`, but to create a default Rule, you'll need to use `hook_default_rules_configuration()`. It is recommended you put the hook implementation in `MODULE.rules_defaults.inc` to optimize the memory footprint.

For further details on how to use the hook, see Default rules in the Site Building Guide, and look at the default Rules the module provides.

Personally I would recommend that you build your Rule through the UI and featurise, or export it as a Rules string and then import it like so:

```
function MYMODULE_default_rules_configuration() {
  $items['test_rule'] = entity_import('rules_config', 'EXPORT STRING HERE');
  return $items;
}

```

That will save you a lot of pain.

---
Tags: database, rules
---


# Question
Title: Is there a way to pass a form #value to the form #action in Drupal 7 form API?
In the example below I want to take elements from the form and include them as part of the URL that I am submitting the form (using #action) so the submitted URL would look like http://example.com/name\_storage/John/Lewis/123412341234.

```
    <?php

function my_module_menu() {
  $items[‘testform’] = array(
    'title' => 'First Last Name',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_form'),
    'access callback' => TRUE,
    );
  return $items;
}

function my_module_form($form,&$form_submit) {
  $form[‘first_name’] = array(
    '#title' => t(The first name of the person),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form[‘last_name’] = array(
    '#title' => t('The first name of the person'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['passcode'] = array(
    '#title' => t('Passcode for this domain.'),
    '#type' => 'textfield',
    '#value' => '123412341234',
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#value' => ‘Submit,
    '#type' => 'submit',
    );
  $form['#action'] = url('http://example.com/name_storage/' . $form['first_name']['#value'] . '/'. $form['first_name']['#value'] . '/' . $form['passcode']['#value']);
  return $form;
}
?>

```

# Answer
In FAPI, #action changes the form's action parameter, which, you should not override if you want to make Drupal handle the submission.

In your case, you need to define a custom submit handler and redirect the user in that function. You could do something similar by changing the form's method to GET, but it is not possible to define a complex path like the one you want.

Remove this line:

```
$form['#action'] = url('http://example.com/name_storage/' . $form['first_name']['#value'] . '/'. $form['first_name']['#value'] . '/' . $form['passcode']['#value']);

```

Then, add a new submit handler like this:

```
function my_module_form_submit($form,&$form_state) {
  $values = $form_state['values']['first_name'] . '/'. $form_state['values']['last_name'] . '/' . $form_state['values']['passcode'];
  $form_state['redirect'] = 'name_storage/' . $values;
}

```

To set the redirect parameter to an external URL, you can do this:

```
$values = 'http://example.com/name_storage/';
$values .= $form_state['values']['first_name'] . '/'. $form_state['values']['last_name'] . '/' . $form_state['values']['passcode'];
$form_state['redirect'] = array(
  $values,
  array(
    'external' => TRUE,
  ),
);

```
> 1 votes

---
Tags: forms, actions
---


# Question
Title: Removing/Restricting for wrapper by role
I want to remove the div that holds the comment wrapper from a content type. What is the best wayto do this?

I could create a module, but I think I would only hode the form and not the headers that are inside the wrapper (just outside the form).

I guess I could hold it via the template, but I'm not sure how to pull the roles.

Thanks

# Answer
If it's Role based, why not remove the permission for that Role to View or Post Comments under admin/people/permissions?

If you need more granular control, try the Comment Permissions Module (https://drupal.org/project/comment\_perm)
> 0 votes

---
Tags: comments
---


title: Open filters in pop-up

text:
# Question
Title: Open filters in pop-up
I have a **search field** in my view and also some **other filters** like filtering between 2 dates or filtering between 2 prices.

Now I have something like this:

When I click on `Uitgebreid zoeken ...` the div pops open like this:

Now I would like to replace the div that pops open when you click on the link with a pop-up. The pop-up should contain all the filters and the apply button.

But I don't now how to start with this. What would be the best solution?

# Answer
A custom Views template for the exposed form might do it.

wrap it in a div, and use either a custom jQuery or third party pop-up script within the tpl.
> 1 votes

---
Tags: views, javascript, modal-dialogs
---


title: How to upload funds in Drupal website?

text:
# Question
Title: How to upload funds in Drupal website?
I want to upload funds in my Drupal website using stripe and paypal methods. I am not able to find sub module in ubercart which can help me

# Answer
> 0 votes
Ubercart comes with paypal options for payment, there is a Stripe module under development, but you would have to wait, or use the dev version. (https://drupal.org/project/stripe)

---
Tags: ubercart, commerce
---


# Question
Title: Adding link with image in the .tpl.php file
I have just started with drupal and have very little understanding and experience with it. I was able to develop a module by referring to sample modules available online. I have a .tpl.php file that is supposed to have a link in the form of an image, I am hoping to execute a php function (php function is ready) by clicking on that image. So my question is how to add a link inside the .tpl.php file, do I have to implement a form? if so, what file should have this form? How to execute the php function on click from this link?

Please let me know if the question doesn't make enough sense.

Thanks

# Answer
I think what you want is something to link to that will execute your PHP "callback". Have a look at hook\_menu() in the Drupal API.

Here's an example:

```
/**
 * Implements hook_menu().
 */
function MODULENAME_menu() {
  $items = array();
  $items['mymodule/callback'] = array(
    'page callback' => 'MODULENAME_do_callback',
    'access arguments' => array('access content'), // You can specify a permission here.
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function MODULENAME_do_callback() {
  // your php here
}

```

With that you should be able to link your image (just with standard HTML) to yourdomain.com/mymodule/callback and it will execute your code.

Note: Be sure to clear all caches after adding your `hook_menu()` implementation.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Views: Use default value from URL for contextual filter, THEN show all if default value empty?
**Short version, general question**: You want to pipe in a 'Default value', specifying a URL argument, to a contextual filter in Views 3. You also want all results (the full unfiltered view) to be displayed if this argument in the URL is empty. However, "Default value" and "Display all rows if empty" settings in Views contextual filters are mutually exclusive, and the default if nothing is passed to the filter is to show nothing.

How can you achieve this?

---

**Full version with case specifics**: I'm using a Context View with a contextual filter on a Search API index to search based on search terms in a URL: path like "/search/my%20search%20terms, loaded into a Page Manager panels page as a page context so that bits of the view can be dispersed across the page regions. Pretty standard use of Search API Views.

Since you can't specify what arguments or contexts to pass to a context view in Page Manager / Panels when loaded as *contexts* in the Contexts form (unlike block views etc, loaded as *content*, where you can explicitly pass in arguments or contexts), I need to tell it which URL argument it will find the search terms in using the 'Provide default' options under Contextual Filters in the Views settings for the view.

This works, but has an unintended side effect - if someone goes to the search page without any terms (navigates to /search or submits an empty search box), they get nothing. I'd like this path to show the full unfiltered view (it's full of search facets and such so just navigating to it without search terms works like a drill-down browse/advanced search page).

If this was a block or loaded as content in panels/page manager, I could set "If no filter value is provided" to show all rows and use panels/page manager to pass in the current URL argument. But, in Views UI, default values and 'Show all' are mutually exclusive.

So, how to use a default value for a contextual filter, then show all if that default value isn't present or is empty?

# Answer
> 2 votes
Here's something that works, not sure if it's the best way (can only be done by admins with Views UI PHP priviledges):

* Under "**When the filter value IS available or a default is provided**" tick "Specify validation criteria"
* Choose PHP code and enter: `return empty($argument) ? false : true;`
* Under "**Action to take if filter value does not validate**", choose "Display all values"

So, it displays everything if it gets an empty ('' or null) default value.

It works fine, but feels like a cludge - I might be missing some way to pass contexts/args in page manager or some simpler way to achieve this in Views.

# Answer
> 5 votes
Even faster: PHP is not even needed to just display all values...

* Under "When the filter value IS available or a default is provided
* Tick "Specify validation criteria" Choose 'Basic validation'
* Under "Action to take if filter value does not validate", choose "Display all values"

---
Tags: panels, views, chaos-tool-suite
---


# Question
Title: How to display devel dpm messages on a panels generated page?
I am testing a custom module for a site using Panels Everywhere & Panels. I need to put the results of a Devel module `dpm()` message into a pane so that I can see it on page displays. Does anyone know what content type it might be? I assumed it would be System Help, but no luck.

# Answer
Put the code inside ***panels-pane.tpl.php*** file which is responsible for printing panel pane. You can find this on Panels directory but you should better copy this into your theme folder and do there any modifications.
> 0 votes

---
Tags: panels, debugging
---


title: How to modify Author Pane date fields?

text:
# Question
Title: How to modify Author Pane date fields?
I have Author Pane installed along with D7 Advanced forum. I am wondering how to shorten the display format of 'Join' and how to remove 'Last seen:' from the pane? I could not see any guidelines in the module's docs or issues about this.

# Answer
Author Pane module contains appropriate templates files which control output. author-pane.tpl.php is something that will help.

Just copy it in your theme directory, flush cache and do whatever you like with this file to customize Auth Pane block.

To remove 'Last seen:' from the pane comment or remove from the file

```
<?php /* Last active */ ?>
<?php if (!empty($last_active)): ?>
    <div class="author-pane-line author-last-seen">
       <span class="author-pane-label"><?php print t('Last seen'); ?>:</span> <?php print t('!time ago', array('!time' => $last_active)); ?>
    </div>
<?php endif; ?>

```

To shorten the display format of 'Join' find appropriate admin page (/admin/config/regional/date-time) and change Short date format to the format you prefer.

```
 * - $joined: Date the post author joined the site. (Uses shortdate format)

```
> 1 votes

# Answer
Indeed, following this guide solved my problem. That is,

I copied

```
function THEMENAME_preprocess_author_pane(&$variables) {
  $variables['show_template_location'] = TRUE;
}

```

To THEMENAME/template.php and it showed the respective template path which in my case was in all/modules/advanced\_forum/styles/naked/advanced-forum.naked.author-pane.tpl.php

Then I just edited the template and flushed cache.
> 0 votes

---
Tags: nodes
---


# Question
Title: Is there a way to get Views Bulk Operation to place field options in the main VBO exposed dropdown
I am using VBO to set the author for a one of my content types. Currently, when you want to use the change author page, you have to..

1. Navigate to the page.
2. Select the target content items
3. Select 'Change Author' from the VBO drop down list (this is the only option)
4. Wait for the new page to load
5. Select the new author form the (only) drop down lost on this page.
6. Submit

It seems that there are a lot of extra steps here. Is there a way to set-up the primary VBO drop down list (refereed to in step 3) so that it displays the different authors (like the drop down refereed to in step 5?)

# Answer
> 2 votes
If you check the "Skip confirmation step" box below the "Change the author of content" action, you can remove the confirmation step.

As for making it a one-click change, that would probably require either extending VBO with another module, or somehow invoking ctools modal windows with VBO. I haven't found any success stories with the latter, but there's this: Ctools Modal + Views Bulk Operations? (drupal.org)

---
Tags: 7, views
---


# Question
Title: Fatal error: Call to a member function diff() on a non-object
I have an entityform that has a computed field. In computed field, I have to compute two time fields.

When I tried using this code that declares value for the two time field, it works fine

```
$timefrom = '06:00PM';
$timeto = '8:30PM';
$from = DateTime::createFromFormat('h:iA', $timefrom );
$to = DateTime::createFromFormat('h:iA', $timeto );

$ot_hour =  $to->diff($from);
$ot_minute =  $to->diff($from);
$hour = $ot_hour->format('%h');
$minute = $ot_minute->format('%i');
$hourtominute = $hour*60;
$total = ($hourtominute+$minute)/60;
$entity_field[0]['value'] = $total;

```

But when I used the variables from the entityform,

```
$timefrom_value = array_pop(field_get_items($entity_type, $entity, 'field_time_from'));
$timeto_value =array_pop(field_get_items($entity_type, $entity, 'field_time_to'));

$timefrom = $timefrom_value['value'];
$timeto = $timeto_value['value'];
$from1 = DateTime::createFromFormat('h:iA', $timefrom );
$to1 = DateTime::createFromFormat('h:iA', $timeto );

$ot_hour =  $to1->diff($from1);
$ot_minute =  $to1->diff($from1);
$hour = $ot_hour->format('%h');
$minute = $ot_minute->format('%i');
$hourtominute = $hour*60;
$total = ($hourtominute+$minute)/60;
$entity_field[0]['value'] = $total;

```

It show error "Fatal error: Call to a member function diff() on a non-object"

Why is this happening? I need some help to solve this. thanks a lot!

# Answer
> 0 votes
It seems like you're getting confused with your `$to` and `$to1` objects. There is **typo** in your code. Try this on your later code:

```
$ot_hour =  $to1->diff($from);
$ot_minute =  $to1->diff($from);
$hour = $ot_hour->format('%h');
$minute = $ot_minute->format('%i');
$hourtominute = $hour*60;
$total = ($hourtominute+$minute)/60;
$entity_field[0]['value'] = $total;

```

---
Tags: entities
---


# Question
Title: Anonymous users unable to download purchase
I've set up a Drupal Commerce store (on localhost) for a book shop. One of the requirements is that people can buy ebooks without creating an account.

It all works fine if I buy a book as the administrator; at the end of the checkout process I can download the book. However, when I buy a book as an anonymous user I'm shown the 'Download now' link in plain text.

I'm using a content type named 'Books' with a field named 'Ebooks'. The latter uses the 'File' field type. The rest of my set-up is as follows:

**Commerce File 7.x-2.0-beta2:**

* Product types: *Books*
* Download limits: *5*

**Commerce License 7.x-1.2**

* Product types: *Books*
* Line item types: *Product*

**Permissions for anonymous users:**

* Checkout, Access checkout
* Commerce licenses, View own licenses
* Order, View own orders of any type

**Rules:**

* Create a new account for an anonymous order: *inactive*
* Assign an anonymous order to a pre-existing user: *inactive*
* Activates licenses of an order: *Completing the checkout process* \> *Activates all licenses of the provided order*
* Update the order status on checkout completion: *Completing the checkout process* \> *Update the order state* (to 'Pending')

At first I though the issue was that the order status is changed to 'Pending' once the checkout process has completed. However, changing this made no difference.

I then found that giving anonymous users permission to 'bypass license control' does instantly resolve the issue. However, that permission setting comes with a "give to trusted roles only; this permission has security implications".

So... something is not quite right in my set-up. It seems that anonymous users aren't given a license allowing them to download their purchase. I've run out of ideas though. What have I done wrong?

# Answer
> 1 votes
You have disabled the rules for creating an account for the anonymous user. Therefore, the license never gets assigned to an actual user, stays assigned to user 0.

Commerce License and Commerce File were designed to license the file to an actual customer. I suggest either re-enabling the rules and creating the user accounts or developing a custom solution for the file downloads (you don't need most of commerce file if there's no actual user... just a temporary file link).

---
Tags: commerce, rules, users, files
---


# Question
Title: Is it possible to add a class to an image field of a node wise
I have a content type that has title, body, image etc. I am displaying the Title, image with caption and body using Manage Display. But here there is no option to align (Left, Right, Center) the image. How to align the image node wise.

OR

Is it possible to add a class to an image field of a node wise.

# Answer
> 0 votes
1. Have you checked the already built-in classes drupal adds to fields in the HTML? That is the way I style a single content view.
2. Is this https://drupal.org/node/1795294 the module? In the description they explain how to add a class.

PD: I wanted to leave a comment but do not have enough reputation to do so.

# Answer
> 0 votes
Francisco has the right idea. Use Display Suite to wrap a div around your displayed image, and put your css class there.

Another option is to use the insert module and style the image any way you want after inserting it into another field.

---
Tags: 7, nodes, media
---


title: Can't install Drush on FreeBSD

text:
# Question
Title: Can't install Drush on FreeBSD
I'm running FreeBSD 10 with PHP5.3.28

I can't use the port or package to install Drush because it will install the default PHP (5.4) as a dependency. So I installed Drush manually. Then when I invoked Drush it said:

> Can't find PHP

So I added this to csh.cshrc: `setenv DRUSH_PHP /usr/local/bin/php`

After reboot I now get this:

> Could not open input file: @pear\_directory@/drush/drush.php

I don't have PEAR on my system and trying to install it also means it will install PHP5.4. I was able to install Composer manually but I'm afraid it too will install PHP5.4 as a dependency for Drush.

Any ideas?

Note: `php -i` works.

# Answer
composer install will not install php; go ahead and follow the instructions in the Drush README for the composer install, and you should be fine.

Note also that Drush master (Drush 7) will soon require php 5.4, so you should use Drush 6 if you'd like to stick with php 5.3.

I don't have a FreeBSD system to try this on, but `composer global require drush/drush:6.*` works fine on my Linux box. If you have problems with the composer install, you might want to try `composer self-update`, to insure that you have a recent version; I can't imagine why FreeBSD should be different than Linux when finding and installing Drush.
> 1 votes

# Answer
Not sure why Composer failed...

Resorted to Pear which worked. Pear isn't automatically included with PHP built from FreeBSD ports, so first had to:

```
# wget http://pear.php.net/go-pear.phar
# php go-pear.phar

```

Then:

```
pear channel-discover pear.drush.org
pear install drush/drush

```
> 0 votes

---
Tags: drush
---


# Question
Title: Add custom html to a facet api facet block
How can i add custom html to a facet api facet block. Like a link to another page or some descriptive text and an image. It would be good for user experience.

# Answer
> 0 votes
You can create your own facet widget. Just extends from one of existing widgets. You can found examples in module facetapi.

---
Tags: search
---


# Question
Title: Preferred way of loading a specific entity revision
In drupal 7 you can do this to load an entity revision using

entity\_load($entity\_type, $ids = FALSE, $conditions = array(), $reset = FALSE)

like this:

```
$old_revision = entity_load('node', array(), array('vid' => 123));

```

However now $conditions is being deprecated. Pretty much wherever you go you see people saying that you should use EntityFieldQuery instead of conditions, however that doesn't help in this case. You can use age() to query revisions using EntityFieldQuery however it doesn't give you fully loaded node results so you then still have to load the entity and how do you load that revision of that entity without the conditions.

# Answer
> 19 votes
Currently the preferred way is to get the storage instance (EntityStorageInterface) for the entity type from the EntityTypeManager and then use its loadRevision() function. For example, you could do this for a node:

```
$node_revision = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

```

Previously to this you would get the storage instance from the EntityManager like this:

```
$node_revision = \Drupal::entityManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

```

This still currently works however it has been deprecated in favour of the first method. The change record relating to this is at https://www.drupal.org/node/2549139

The old way, which still currently works in Drupal 8 but is also deprecated, is the function entity\_revision\_load(), which is also available in drupal 7 via entity\_revision\_load() in the Entity API module.

This function replaces the use of conditions to load old entity revisions. You can see the history of this change in the Drupal core issue about Remove deprecated $conditions support from entity controller.

The way you would use this function as per the original question is:

```
$old_revision = entity_revision_load('node', 123);

```

---
Tags: entities
---


# Question
Title: How to theme the create content of custom content type?
I have a custom content type *property*. The registered user can create the *property* when logged in. I want to theme the "create property page" the same as the site's default theme. Please let me know how we can theme the "create propery page". Is there any module or do we need to do something else?

# Answer
Sometimes I want certain roles to see the admin theme on a given page, and sometimes I don't. whitefleaCH's ThemeKey suggestion might address that better (haven't tried that module) but another module suggestion that addresses this is Page Theme. Extremely simple module that does exactly what it's name implies:

1. Install the module
2. Go to /admin/structure/page-theme and click "Add theme"
3. Pick your installed theme and add "node/add/property" and "node/edit/property" and any number of other relative paths to the "Pages" field.

Anyone visiting any of those paths will see the content through the theme you designated.
> 3 votes

# Answer
The link is in the other Question: here it is for you again: Drupal 7 Theme Hook Suggestions

And this module will help also: devel\_themer

You also can set the admin theme to the same theme as the website. Under `/admin/appearance`
> 1 votes

# Answer
I guess you have admin\_theme installed and you want the `node/add/property` page to look like the frontend theme NOT the admin theme is that right? If it is then you need to make a very simple small custom module, and if you're using Drupal 7 implement hook\_menu\_alter() and a custom callback (Of course replace `hook` with your module name):

```
/**
 * Implements hook_menu_alter.
 */
function hook_menu_alter(&$items) {
  $items['node/add/property']['theme callback'] = 'hook_custom_get_default_theme';
}

function hook_custom_get_default_theme() {
  return variable_get('theme_default', '0');
}

```

(Source)

For Drupal 6 implement hook\_init()

```
/**
 * Implementation of hook_init().
 */
function hook_init() {
  global $custom_theme;

  // Set default theme for specific node types when use administration theme for node editing is set
  if (variable_get('node_admin_theme', 0)) {
    $node_types = array( // The node types you want to use default theme for
      'property',
    );

    if (arg(0) == 'node' && arg(1) == 'add') {
      $current_type = arg(2);
    }
    else if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'edit') {
      $node_to_check = node_load(arg(1));
      $current_type = $node_to_check->type;
    }

    if($current_type && in_array($current_type, $node_types)) {
      $custom_theme = variable_get('theme_default', '0');
      init_theme();
    }
  }
}

```

(Source)

If that's not the case, you seriously need to rephrase your question, cause it doesn't make any sense otherwise.
> 1 votes

# Answer
ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.

Also take a look at a Tutorial.
> 1 votes

# Answer
If you are facing issue that the node add form is picking up the admin theme instead of site default theme, the reason might be setting of permission of allowing registered user to see the admin theme, check the screen shot below

So If we do not allow registered users to see the admin theme, the node add form will take the site default theme itself.

While in case the above solution seems off beat to your issue, solution proposed by Beebee must work, I have used that before in different scenario when I was supposed to open a particular node add form in site default theme for administrator itself.
> 1 votes

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


# Question
Title: Send Email to user after click submit button
Currently I am doing a recruitment system using Drupal 7 where the applicant can apply the job and HR admin can shortlist the applicant.

I have created a "shortlist button" in the content type to let the HR admin change the applicant status from pending (by default) to shortlisted. I put some rules to change the user status.

So my question is: How can I send the email to notify the user after the HR admin clicks the "shortlist button" to inform the user that they has been shortlisted?

# Answer
You are looking for Workbench email module.

> Provides a way for administrators to define email transitions and configurable email subject / messages between those transitions. **Email transitions can be defined as when content moves from state to state.** Based on those email transitions, configurable emails can be created / updated / deleted as the site admin see's fit.
> 1 votes

---
Tags: rules, emails, notifications
---


# Question
Title: Drupal 6 - Build Menu "...not available at this time." Issue
I was just recently given administrative rights to the Drupal account to our firm to do some front-end work. I need to revamp a lot of the structure and content, however I do not see the 'Menus' option under 'Site building', more so I cannot access it via URL with I type `"http://mysite.com/admin/build/menu"`. I get the following 404 Message "This content is not available at this time." My DBA says that it used to be accessible for he gave me an account. My question is what did he or I do wrong? I edited some of the Input Type Profiles and used the Rebuild Permissions option several times but have had no luck. I have not be able to find much mention of this through research. Is this a common scenario?

**Full HTML prefs:**

**WYSIWYG Configs:**

**Type Settings Per User:**

**Filters for Filtered HTML:**

# Answer
Since you are saying **../admin/build/menu** , I assume that you are using Drupal6.

Step 1: Navigate to `example.com/admin/user/permissions`

Step 2: Search for **menu module** and give permission for your **user roles** as required.
> 0 votes

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


# Question
Title: how to make a field in a view be the link destination to another field?
I am trying to create ads on the sidebar to my site. I have created a content type that has 2 fields; an `image` field, and a `link` field. I now want to display the ads in a view by having the image appear, and when you click on the image, it brings you to the link that was specified by the `link` field. I know how to do this in a block with `HTML`, but I want to do it dynamically through a view. Is there any way to do this?

# Answer
Make sure the **Row Style** is *Fields*. Add both fields, link field first and then image field.

Edit the link field (in the Views UI) and check **exclude from display** and use the **URL as plain text** formatter.

Finally, edit the image field and check **output this field as a link**. There are replacement patterns you can use for the link destination, the link field should be available there. You will need to check **use absolute path**.
> 14 votes

# Answer
The Image Link Formatter module also seems to be an option.

> This module is the result of the discussions around a requested feature to allow an image field to be displayed with a link to a custom URL:
> 1 votes

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