title: Add taxonomy term in popup

text:
# Question
Title: Add taxonomy term in popup
I have a **select list** with some options. But now I also want an option `Other`. And when you select the `Other` option there has to open a **pop-up screen** with **the add term to vocabulary form** in it. The term should not be added directly to the vocabulary, it should be "disabled" first so the administrator can approve them.

I know how to get the taxonomy form (taxonomy\_form\_term, drupal\_get\_form, drupal\_render\_form) but I have some other questions:

* How can I open the popup and show call the function in my module to render the form? Should I add another option to my select list?
* How can I make sure when you add it, it doesn't add directly to the vocabulary (admin has to click approve)

# Answer
> 0 votes
For the first part of your question, set an event listener to bind when the `other` option is selected, and then display your popup. I would suggest **setting a custom state** (see the Form API) and listening for that state. The example given in the states API explains better:

> Each remote condition is a key/value pair specifying conditions on the other element that need to be met to apply the state to the element:
>
> ```
> array(
>   'visible' => array(
>     ':input[name="remote_checkbox"]' => array('checked' => TRUE),   ), )
>
> ```
>
> For example, to show a textfield only when a checkbox is checked:
>
> ```
>  $form['toggle_me'] = array(
>    '#type' => 'checkbox',
>    '#title' => t('Tick this box to type'),
>  ); $form['settings'] = array(
>      '#type' => 'textfield',
>      '#states' => array(
>      // Only show this field when the 'toggle_me' checkbox is enabled.
>      'visible' => array(
>        ':input[name="toggle_me"]' => array('checked' => TRUE),
>  ),
> ),
>
> ```
>
> );

jQuery UI Dialog would be a good solution for the popup.

For the second part, there is a module to handle just this situation, so that taxonomy terms can be moderated and approved. Taxonomy Other:

> Use case example: You have a taxonomy vocabulary called 'Organization type' and you want to allow users to be able to choose '- Other -' and add their own type. You want to use a simple select list and to keep the list small to encourage people to use the types you've provided.

---
Tags: forms, javascript, taxonomy-terms
---


# Question
Title: Looking for multi step form in Drupal that can also show submissions in Admin
I hope I am not offending someone with this naive question.

I am currently trying to create a customized JQuery + PHP + HTML multi step form in Drupal. I am hoping if anyone of you could let me know if there is some way I can create this and also see the submissions through Admin.

Many Thanks.

# Answer
> 4 votes
You can use Webform module and Webform steps module to visualize the steps.

The process is as follows:

* Create Webform put some fields organized in Fieldsets if you like.
* To make new page insert pagebreak

.

If you want more customization you can follow this tutorial for creating your own module for that.

---
Tags: forms
---


# Question
Title: Create a product after form submission using commerce and rules
I want to set up a rule which would create a product when the user saves a submission form. The submission form is embedded into a simple node (using entity reference) presenting the "product" being sold. What I would like to do is to use information from that node when the rule creates the product.

The problem I am having is that I cannot find any valid way to get these fields to display in rules' data selector. The only way I found was to add the event "content is viewed" in addition to the event "after saving a new entityform". But I only want to keep the event related to the submission form.

So my question is the following: how can I display the fields contained in the node being viewed in rules' data selector without using this event? Thanks in advance for you help!

# Answer
> 0 votes
It depends on the implementation of this submission form, but a common way to expose fields in Rules is to add a condition 'Entity has field' in your rule.

In your particular case, you would select node as entity and the particular entity reference field.

In this way the rule will only execute if the node indeed has this field, and also will allow you to use the field in your actions below.

---
Tags: commerce, rules
---


# Question
Title: How to copy select list value from a webform submisison into select list field new node?
This is the scenario:

A webform with the following fields

```
Question -> Textfield
Category -> Select options (Listbox) Listing vocabulary HETCAT

```

A content type Question with these fields

```
Title
Category -> Term reference listing vocabulary HETCAT

```

Once the webform is submitted i create a new question node. Everything works fine, the Question field of the webform is the new Question node title, but i can not see the way to copy the category selected on the webform to the new node

Thanks in advance

This is the export rule code

```
{ "rules_submissions_to_node" : {
"LABEL" : "Submissions to node",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "webform_rules", "rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "webform_has_id" : {
      "form_id" : [ "form_id" ],
      "selected_webform" : { "value" : { "webform-client-form-140" : "webform-client-form-140" } }
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "het_question",
        "param_title" : [ "node:title" ],
        "param_author" : [ "user" ]
      },
      "PROVIDE" : { "entity_created" : { "new_question" : "New question" } }
    }
  },
  { "data_set" : { "data" : [ "new-question:title" ], "value" : "[data:question-value]" } },
  { "data_set" : {
      "data" : [ "new-question:field-month" ],
      "value" : [ "site:current-date" ]
    }
  },
  { "entity_save" : { "data" : [ "new-question" ], "immediate" : 1 } },
  { "mail_to_users_of_role" : {
      "roles" : { "value" : { "4" : "4" } },
      "subject" : "New question to approve",
      "message" : "[new-question:title]\r\n\r\n\u003Ca href=\u0022[new-question:edit-url]\u0022\u003EEdit to publish it\u003C\/a\u003E\r\n",
      "from" : "[site:name]"
    }
  },
  { "node_unpublish" : { "node" : [ "new-question" ] } }
]}}

```

# Answer
Well, finally i figure it out how to solve it.

I'm using Webform Rules module

Just need to add an `Execute custom PHP code` action and set the value like this

```
// $new_question is my new node.
// $data['components']['category'] is my webform listbox component.
// $new_question->field_category is my taxonomy reference field select list.

$tid = substr($data['components']['category']['value'][0],4,2);
$new_question->field_category['und'][0]['tid'] = $tid;

```
> 0 votes

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


# Question
Title: Disable the Drupal 7 overlay for some administrative links
Is there a way to disable the Drupal 7 overlay for some administrative links by not others?

For usability reasons the site I'm working on would benefit from some administrative links using the default overlay behavior while 1 or 2 would benefit from having it disabled. Since the vast majority of the links make more sense for users to experience in the overlay I'd like it to be generally enabled for them, but be able to keep a couple specific links embargoed so the JavaScript does not update their behavior.

# Answer
> 5 votes
inizio's answer is very helpful, I found one other solution (which is the one that made sense in my context in the end).

Add a class of `overlay-exclude` to the anchor tag:

```
<a class="overlay-exclude" href="/node/add/page">Create New Page</a>

```

# Answer
> 5 votes
Hope this will help you.

In Drupal 7 you can achive this by using **hook\_admin\_paths\_alter**

**Programatically**

* **hook\_admin\_paths\_alter** : Redefine administrative paths defined by other modules.

```

    function HOOK_admin_paths_alter(&$paths) {
      //return FALSE to the path where you don't want to show in OVERLAY
      $paths['node/*/edit'] = FALSE;
      $paths['node/add'] = FALSE;
      $paths['node/add/*'] = FALSE;
    }

```

**Using Module**

* Overlay Paths : You can enable the overlay for selected non-admin paths and also you can disable overlay for selected admin paths.

# Answer
> 0 votes
HOOK\_admin\_paths\_alter() is a very good idea, but it seems that for the specified paths it will use the front theme, not the administrative one. The overlay\_paths module remained the second choice which seems to work fine.

---
Tags: 7, modal-dialogs, forms
---


title: Override ctools function

text:
# Question
Title: Override ctools function
I'm using the Multi-Step Registration module to have a **wizard** in my **user registration**. The wizard works fine. You can also select a `wizard trail` to see in which step you are.

As you can see it displays that you can customize it by theming ctools\_wizard\_trail\__step. Now the html code of the wizard is like this:

```
<div class="wizard-trail">
    <span class="wizard-trail-previous">Register</span> »
    <span class="wizard-trail-previous">Geslacht</span> »
    <span class="wizard-trail-previous">Politiek actief</span>
    .......
</div>

```

This is what I've done so far in the function:

```
function mytheme_ctools_wizard_trail__step($html) {
    $wizard = $html['trail'];
    $steps = ['', 'geslacht', 'politiek_actief', 'beroep', 'vakgebied', 'berichten_ontvangen', 'nicknames', 'other'];
    for($i = 0; $i < count($steps); $i++)
    {
        $step_name = (string)$steps[$i];
        $wizard_html = (string)$wizard[$i];
        $wizard[$i] = "<a href='/user/register/" . $step_name . "'>" . $wizard_html . "</a>";
    }
    $html['trail'] = $wizard;
}

```

When I dump the $html variable on the first line of the function (before any operations) I get this result:

```
array (size=1)
    'trail' =>
       array (size=8)
          0 => string '<span class="wizard-trail-previous">Register</span>' (length=51)
          1 => string '<span class="wizard-trail-previous">Geslacht</span>' (length=51)
          2 => string '<span class="wizard-trail-previous">Politiek actief</span>' (length=58)
          3 => string '<span class="wizard-trail-previous">Beroep</span>' (length=49)
          4 => string '<span class="wizard-trail-previous">Vakgebied</span>' (length=52)
          5 => string '<span class="wizard-trail-current">Berichten ontvangen</span>' (length=61)
          6 => string '<span class="wizard-trail-next">Nicknames</span>' (length=48)
          7 => string '<span class="wizard-trail-next">Other</span>' (length=44)

```

When I dump the $html variable on my last rule of the function I get this:

```
array (size=1)
   'trail' =>
      array (size=8)
         0 => string '<a href='/user/register/'><span class="wizard-trail-previous">Register</span></a>' (length=81)
         1 => string '<a href='/user/register/geslacht'><span class="wizard-trail-previous">Geslacht</span></a>' (length=89)
         2 => string '<a href='/user/register/politiek_actief'><span class="wizard-trail-previous">Politiek actief</span></a>' (length=103)
         3 => string '<a href='/user/register/beroep'><span class="wizard-trail-previous">Beroep</span></a>' (length=85)
         4 => string '<a href='/user/register/vakgebied'><span class="wizard-trail-previous">Vakgebied</span></a>' (length=91)
         5 => string '<a href='/user/register/berichten_ontvangen'><span class="wizard-trail-current">Berichten ontvangen</span></a>' (length=110)
         6 => string '<a href='/user/register/nicknames'><span class="wizard-trail-next">Nicknames</span></a>' (length=87)
         7 => string '<a href='/user/register/other'><span class="wizard-trail-next">Other</span></a>' (length=79)

```

It looks the same but my wizard is gone ... . It's not added to my html.. . What could be the problem of this?

# Answer
You're not returning any markup from the theme function. The purpose of a theme function is to optionally accept some arguments and return markup. Here's an example of a theme function returning markup.

For more information see Overriding themable output.
> 1 votes

---
Tags: users, chaos-tool-suite
---


# Question
Title: Views : how to combine fields in exposed filter using is between operator
In a view showing commerce products, with exposed filters, I need to make a slider filter for *commerce\_price* field. This is easy with exposed filters (is between operator) and BEF module, but ...

*commerce\_price* field is retrieved in the view by its **relationship to Product variation type**, and I've got 2 different Product variation types for the same product display :

> And

This means you can make a slider for each one, but this makes no sense for end-user to have 2 prices slider !

And by default Views 3.x *Global: Combine fields filter* **doesn’t provide "is between" operator**, it only works with strings and operators like equal to, begins...

**How can I filter the values of both relationships in a single slider for that Price field ?** Is there a Views setup way or a module to do that? If not, how can I add a custom filter to my view using API ?

# Answer
> 2 votes
This is a "smoke and mirrors" situation, in which you want the end user to experience one thing when the code is doing something completely different.

I would do a little bit of jQuery trickery. First, I would expose all 4 fields (the high and low for each of the 2 fields) as text boxes. Then, I would use the jQuery UI slider (which ships with Drupal Core) to update the high and low values as the user changes them. Of course, the jQuery should hide the actual text boxes as well. This will give you the effect that you are looking for.

Finally, if you wanted this to be *ultra* simple in the event that Javascript fails, you can use a form alter to hide one of the pairs of text boxes and then, when the form is submitted or the view loaded, populate the values for the other filter programmatically.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'THE-FORM-YOU-WANT-TO-TARGET') {
    // you'll have to look through the $form array for the field you want
    // I suggest installing Devel and running dsm($form);

    $form['YOUR-FORM-ELEMENT']['#default_value'] = isset($_SESSION['max']) ? $_SESSION['max'] : 1000;
    // Do this for all the applicable form elements...

    // Finally, tell Drupal that you want to see the form when it is submitted.
    array_unshift($form['#submit'], 'MYMODULE_filter_submit');
  }
}

function MYMODULE_filter_submit($form, &$form_state) {
  $_SESSION['max'] = $form_state['values']['YOUR-FORM-ELEMENT'];
}

```

You'll have to double-check to see what the variables actually look like. I suggest installing the Devel module and putting `dsm($form);` and `dsm($form_state);` at the beginning of the functions.

Lastly, any time that you add a hook, don't forget to clear your cache or Drupal won't find it.

# Answer
> 1 votes
I had a similar problem and my solution was to write a custom query that fetches *distinct* values from the desired tables *in ascending order* & populating the slider with the query's result. Here are the steps:

1. In the .module file of your custom module,

```
function <module_name>_preprocess_views_view(&$vars)
{
    $view = $vars['view'];
    $query = $view->query;

    //Use this to find out the machine name of view
    //drupal_set_message('<pre>' .print_r($view->name,TRUE). '</pre>');

    switch($view->name)
    {
        case '<view_name>':

        //Fetch distinct price values from the price table(s) & sort in ascending order since a slider ranges from min to max!
        $arr = db_query("SELECT DISTINCT column1_value FROM {price_table1},{price_table2} ORDER BY column1_value ASC")->fetchCol();

        //Convert associative arrays to normal arrays
        foreach($arr as $key=>$value)
            $normal_arr[] = (float)$value;

        //Pass variables from .module to .js file
        drupal_add_js(
            array(
                'views_slider' => array(
                    'arr_values' => $normal_arr
                    )
                ),
                array('type' => 'setting')
            );

         //Include appropriate .js file
         drupal_add_js(drupal_get_path('module', '<module_name>') . '<path_to_js_file_within_module>/<js_file>.js');

         break;
     }
}

```

2. In the .js file, populate the jQuery slider using the result of the query as reference. Cookies are used to retrieve values on the slider & its textboxes even after page load/views exposed form submit.

```
    function ($) {
    Drupal.behaviors.views_slider = {
        attach: function (context, settings) {
            var arr_val = Drupal.settings.views_slider.arr_values;

            var min = getCookie("price-min");
            var max = getCookie("price-max");

            //Here 'edit-field-price-value-wrapper' is the id of the BEF slider wrapper.
            //You can find this by using Firebug or similar element-inspecting browser apps.
            $("div#edit-field-price-value-wrapper div.ui-slider").slider({
                min: 0,
                max: arr_val.length-1,
                values:[min, max],
                slide: function(event, ui) {
                    if (ui.values[0] > ui.values[1])
                    {
                        return false;
                    }
                    $("#edit-field-price-slider-value-min").val(arr_val[ui.values[0]]); //Id of min textbox in BEF slider
                    $("#edit-field-price-slider-value-max").val(arr_val[ui.values[1]]); //Id of max textbox in BEF slider
                    setCookie("price-min", ui.values[0], 1);
                    setCookie("price-max", ui.values[1], 1);
                },
                //When incorrect values are entered,this event updates the textboxes to their closest value
                change: function (event, ui) {
                    if (ui.values[0] > ui.values[1])
                    {
                        return false;
                    }
                    $("#edit-field-price-slider-value-min").val(arr_val[ui.values[0]]); //Id of min textbox in BEF slider
                    $("#edit-field-price-slider-value-max").val(arr_val[ui.values[1]]); //Id of max textbox in BEF slider
                    setCookie("price-min", ui.values[0], 1);
                    setCookie("price-max", ui.values[1], 1);
                }
            });
        }
    }
})(jQuery);

```

Hope this helps.

---
Tags: views
---


title: Stop node being edited programatically

text:
# Question
Title: Stop node being edited programatically
I have written a module that puts a "generate pdf" link on a node when it is viewed. What I now want to do is lock the original node after the pdf is generated.

I know I could just add a "locked" field to the content type I want to lock, and then programatically set that etc. But I'd prefer it to work with any content type.

How can I programatically disable the editing of a node? I'd prefer to install as few additional modules as possible.

# Answer
For this you should have to implement hook\_node\_grants and hook\_node\_access\_records. It look something like that -

```
 /**
  * Implement @hook_node_grants
  */
 function MODULENAME_node_grants($account, $op) {

  $grants =array();
  $grants['Node_Edit_Permission'][]=array($account->uid);
 return $grants;
}

/**
 * Implement @hook_node_access_records
 */
function MODULENAME_node_access_records($node) {

  $grants = array();

  if ($node->type == 'node_type') {
    $user_id = /* list of user id which you want to block */;

     // Revoke Permissions from these Users
    if (!empty($user_id) {
      foreach ($user_id as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }
  }

  return $grants;
}

```
> 2 votes

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


# Question
Title: How to control editing access when node ownership keeps changing?
I'm working on a project that involves group ownership and editing of nodes. The rules that determine the visibility and editability of nodes are complicated, such that I'm having to roll my own node access code (that is, I couldn't find a module that would provide the kinds of control I need).

The following scenario is causing me some grief:

* Alice and Bob are part of a group, and are working on node 123. Node access entries exist that allow Alice and Bob to both edit the node under "normal" circumstances.
* Alice edits node 123, and so becomes the "owner" of the node, in the sense that the uid field of the database entry for node 123 points to her.
* Bob now edits node 123; he becomes the owner.
* Alice, who has some degree of admin privileges in the group, takes the node private: She should be able to edit it, but Bob shouldn't. "Taking the node private" means setting up some node access entries that are meant to deny access to the node to everyone but her.
* However, since Bob is the most recent person to have edited the node, he's still the "owner of record", and node/123/edit is available to him, as a result of the standard node access rules regarding node ownership. (This is how I'm thinking about it, anyway.)

Any ideas for how I can get around this, and keep Bob blocked from editing the node? I've thought about:

* adding some `node_insert` and `node_update` hooks that would force the uid of the node to always point to Alice; the node access entries would allow Bob to edit the node when he's supposed to be able to. Might work, but this seems questionable/risky/horrifically hackish at best.
* Maybe there's a hook that would reach down into the access system and let me test whether a request for `node/123/edit` should be permitted based on the current user and system state?

Any other possibilities out there? Thanks!

# Answer
> 1 votes
See my recent answer here: https://drupal.stackexchange.com/a/55144/7153

But basically, you can use

nodeaccess\_userreference

or

nodeaccess\_nodereference

to acheive that access control functionality there.

Basically you could deny author access and control edit access with one multi-value reference field instead.

More info, including screenshots at first link.

# Answer
> 1 votes
If you decide to create your own node access module, you may save a lot of work by making use of the ACL (Access Control List) module API. Basically, it is a well-maintained and simple to use framework to create and maintain ACLs for nodes.

The business logic you seem to have in my mind is complex (too complex for my taste), so it may be hard to solve this with only front end tools. An alternative is to rethink the business logic, and adapt it to what can be done with front end tools, such as the Node Access module (as suggested by David Thomas). However, the Node Access module has been abandoned and is listed as unsupported. This is also something you need to take into consideration when deciding on the route to follow.

# Answer
> 0 votes
For this, you have to implement hook\_node\_grants and hook\_node\_access\_records. Something like that-

```
/**
 * Implement @hook_node_grants
 */
function MODULENAME_node_grants($account, $op) {

  $grants =array();
  $grants['Node_OWNER'][]=array($account->uid);
  $grants['Node_GROUP'][]=array($account->uid);
 return $grants;
}

/**
 * Implement @hook_node_access_records
 */
function MODULENAME_node_access_records($node) {

  $grants = array();

  if ($node->type == 'node_type') {
    $user_id_group = /* list of user id which you want to block */;
    $user_id_owner = /* list of user id which you want to perform operation */;
     // Revoke Permissions from these Users
    if (!empty($user_id_group) {
      foreach ($user_id_group as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
          );
        }
      }
    }

     // Grant Permissions from these Users
    if (!empty($user_id_owner) {
      foreach ($user_id_owner as $uid) {
        if (isset($uid)) {

          $grants[] = array(
            'realm' => 'Node_Edit_Permission',
            'gid' => $uid,
            'grant_view' => 1,
            'grant_update' => 1,
            'grant_delete' => 1,
            'priority' => 0,
          );
        }
      }
    }
  }

  return $grants;
}

```

---
Tags: nodes, users
---


# Question
Title: How to implement expiring roles in Drupal 7 today?
I am in the processing of making a membership site that requires some user roles to expire after a set period of time.

The most obvious choice would be the role expire module but none of the 7.x releases have been updated in six months and the issue queue has some patches that have been marked as needing review for weeks.

Commerce subscription is another module under development that hasn't seen any action in about six months.

The only module I could find with a stable release is Commerce subscription products, which rather than being an independent module is actually a feature consisting of rules, commerce, and some fields (as per the module page).

As a site builder with a release coming in the next month or two, since it seems like there is no clear clean solution at the moment, would it be crazy to simply not implement any of these solutions and do something basic in rules myself, handling expirations manually for the first few months? (Roles will expire monthly, and I don't anticipate more than 100 or so roles needing to be removed each month.) Then, if use of the site started taking off, I could look at implementing one of these solutions again. Or is there some good way to do role expiration today that I missed?

# Answer
> 1 votes
There is the Commerce License module that has a stable release and some support. I highly recommend it.

# Answer
> 0 votes
As of the 2012-Apr-10 dev release, Role Expire includes working rules integration in D7. I am now using it successfully to meet my needs.

---
Tags: 7, users
---


# Question
Title: How to programmatically set a node field as empty?
I have some nodes with the following fields:

* Title
* Body
* Image

I want to programmatically set the body field as empty.

This is the code I used.

```
$this_node = node_load($nid);
$this_node->body = array();
node_save($this_node);

```

This code causes the following exception.

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '104418' for key 'PRIMARY': INSERT INTO {node} (nid, vid, type, language, title, uid, status, created, changed, comment, promote, sticky, tnid, translate, uuid) VALUES (placeholders and their values) in drupal\_write\_record() (line 7170 of /var/www/rotary.local/docroot/includes/common.inc).

How can I set an empty body field?

I don't want to use `field_attach_update()` for caching purposes.

# Answer
To remove the value from you field you should do like this before saving it:

```
$this_node->body[$this_node->language] = array();

```
> 4 votes

# Answer
To make body field empty you should implement hook\_node\_presave() and inside this, use-

```
   $node->body[LANGUAGE_NONE][0]['value'] = '';

```
> -1 votes

---
Tags: 7, nodes
---


# Question
Title: How should I remove a region and zone in an Omega 3 sub theme?
I have a sub theme of Omega 3.

What is the correct way to completely remove regions and zones from my sub theme? Is it OK to just simply disable them and then remove them from the .info file?

These regions and zones are never going to be used and I want to simplfy the site by removing anything that isn't needed.

Thank you

# Answer
> 0 votes
Just remove the region and zone definition from the theme info file.

---
Tags: theming, .info
---


# Question
Title: Is it possible to alphabetize a sorted view?
Drupal 7.18 w/ Views 7.x-3.8 user here.

I have a view set up that consists of rows of objects, which have names and 'yes/no' properties. By default, it is sorted alphabetically by object name. I want to allow the user to be able to sort through the view using the various properties, but to then have those sorted results be alphabetized for them post-hoc. Currently, when the user sorts through the view using property X (with either 'yes' or 'no' content), the objects seem to be retrieved based on their location in the database table, or some other factor. Either way, they are in no way alphabetical which means that this view of 500+ results is impractical to sort in this fashion.

So, is it possible to set up a sort mechanism where the results are (1) sorted by property into their respective 'yes'/'no' groups (or any other groups with identical content for that matter) and then (2) alphabetized?

To demonstrate what I mean, I currently have something like this:

```
NAME    PROPERTYX
Alpha   yes
Beta    no
Delta   yes
Epsilon no
Gamma   yes

```

Which when sorted using PROPERTYX (let's say descending), might return something like:

```
NAME    PROPERTYX
Delta   yes
Alpha   yes
Gamma   yes
Epsilon no
Beta    no

```

(As I said, I suppose this random order is based on the object's actual location in the database table.)

When the desired output would be:

```
NAME    PROPERTYX
Alpha   yes
Delta   yes
Gamma   yes
Beta    no
Epsilon no

```

Can this be accomplished somehow?

# Answer
> 1 votes
It is definitely be possible to add a second sort to the query which will give the desired effect, but you will have to write some custom code.

There are several hooks that Views provides that you can use in a custom module. I suggest looking at `hook_views_query_alter()`. The example code on the API page actually shows it altering a `WHERE` clause, but creative use of `dsm()`'s will help you figure out what you need to change.

I'm sorry that I can't give you code (because this kind of modification is highly specific to your installation), but this is definitely the way to go.

# Answer
> 1 votes
If I understand correctly, you want to sort by PROPERTYX first, and then alphabetically sort the items with the same PROPERTYX value - is that correct?

You can do that by adding multiple sort criteria. Make sure that the "Sort by PROPERTYX (desc)" criterium comes first and the "Sort bt title (asc)" comes second.

---
Tags: 7, views
---


# Question
Title: Updated an empty field collection in Drupal7
New to Drupal and I'm assuming the answer is simple, I've looked through the test suites etc. and still missing the point it seems.

I have a node with a field collection (field\_theatre\_date\_set) that will store a number of dates and times. I have loaded the node and the collection is there but it's empty.

I have used various forms of this and an obvious problem is that the $field\_collection\_item\_value below array structure just isn't there.

Any further pointers greatly received.

```
$loop=0;
foreach($showing_array as $key=>$value){

 $date='xxxx';
 $time='xxxx';

 $field_collection_item_value = $node->field_theatre_date_set[LANGUAGE_NONE][0]['value'];
 $field_collection_item = entity_load('field_collection_item', array($field_collection_item_value)); // Load that field collection item

 $field_collection_item->field_theatre_date_set_date[$node->language][$loop]['value'] = $date;
 $field_collection_item->field_theatre_date_set_time[$node->language][$loop]['value'] = $time;
 $loop++
}
 $field_collection_item->save();

```

/**\**Update\*****/

Progress has been made. I still have an empty field\_collection reference that needs to store a date and time.

I now understand that field collections store a value and a revision\_id. I now need to work out how to store these revisions. I have the following code:

```
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_theatre_date_set'));

$field_collection_item->setHostEntity('node', $node);
$field_collection_item->date[LANGUAGE_NONE][]['date']   = $date;
$field_collection_item->field_description[LANGUAGE_NONE][]['time']   = $time;
$field_collection_item->save();

```

Now when I output the field\_collection\_item I see the following where I am expecting to see the the value and revision:

```
[field_theatre_date_set] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [entity] => FieldCollectionItemEntity Object
 *RECURSION*
                            )

                    )

            )

```

And at the very bottom of the array I have the dates and times wallowing on their own:

```
[date] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [date] => 2014-03-13
                    )

            )

    )

[time] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [time] => 19:45:00
                    )

            )

    )

```

Any pointers on how to move them into my field\_theatre\_date\_set if they aren't expecting date and time values?

Thanks all for looking!

# Answer
I believe you need to load and save the node to which the field collection is attached.

This question: Modifying a field collection programmatically missing hostEntity fields is slightly different but the examples are accomplishing the same thing.
> 1 votes

# Answer
try using the EntityAPI to load the `node` and inspect it using the Devel module. The EntityAPI will also make creating/editing the field collection easier.

There are lots of ways to save or load a field collection, for examples see: https://www.drupal.org/node/1393552#comment-5428548

or any of the various answers here: How do I load a field collection from a node?
> 0 votes

---
Tags: entities
---


# Question
Title: Create 2 separated taxonomy pages with views
I have 2 nodes type "Article" and "Page", I also have 2 taxonomy for each node type are "Taxo 1" for Article and taxo 2 for "Page", is there any way to create 2 seperated views so,

```
with "taxonomy/term/%" for Article I have grid views

```

and

```
"taxonomy/term/%" for "Page" I have "Unformated List",

```

beside 2 node types have alot of different fields. Is there any way to handle that?

# Answer
> 0 votes
I really appreciate the Taxonomy Views Integrator module for things like that. https://www.drupal.org/project/tvi

# Answer
> 0 votes
Your template file name should be like this -\> taxonomy-term--tid.tpl.php Source

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


title: Using GET parameters with clean urls

text:
# Question
Title: Using GET parameters with clean urls
I have module where I'm creating a custom path in hook\_menu. When the user visits this page, they are supposed to be redirected to another site, with GET query parameters attached to the redirect URL. So for instance, if they visit `http://mysite.com/site-search?query=blah`, we are supposed to redirect them to `http://othersite.com/different-path?query=blah`.

However, we have clean URLs enabled; while I can hit the page `http://mysite.com/site-search`, it gives a page not found when I try to hit `http://mysite.com/site-search?query=blah`.

> The requested page "/site-search?query=blah" could not be found.

I tried adding another path for `site-search/%`, just to get that extra part of the URL, but that didn't work either.

Am I able to get the URL parameters while using clean URLs?

**Edit:** Here's the code:

```
function my_redirect_menu() {
  $items['site_search'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
  );

  // testing to see if this will allow me to capture get parameters
  // in the form http://site.com/site_search/q=blah
  $items['site_search/%'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
  );

  return $items;
}

function my_redirect_redirect() {
  // see if we can get the get paramters
  return "<pre>" . print_r($_SERVER,1) . "</pre>";
}

```

**Edit 2** In my example, I transcribed the query string in correctly. It looks like it's a conflict between drupal wanting to use `?q=` for its menu routing, and our search host URLs also using `?q=` for their queries. If I do `query=blah`, I am able to hit the page.

# Answer
> 4 votes
I use $\_GET variables as needed in my clean-url installs without issue. Views uses $\_GET variables, too. Drupal uses $\_GET\['q'\] so you don't want to use that ID, but you should be able to do something like:

```
function my_redirect_menu() {
  $items['site_search'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_redirect_redirect() {
  return $_GET['query'];
}

```

This is working for me locally. The 2nd item you present in hook\_menu only matches for /site\_search/foo?query=bar so you only want the first. Be sure to set the `'type'` property as well.

# Answer
> 1 votes
Sorry to be VERY late to the party. For anybody still looking for the answer:

```
function my_redirect_menu() {
    $items['site_search/%'] = array(
      'title' => 'Edit Product Details',
      'page callback' => 'my_redirect_redirect',
      'page arguments' => array(1),
      'access arguments' => array('access content')
    );
}

function my_redirect_redirect($id) {
   return t("your url % value was:".$id);
}

```

---
Tags: uri
---


title: #states does not hide #suffix in a form

text:
# Question
Title: #states does not hide #suffix in a form
I am new to Drupal, so please be fair with me :)

I am trying to create a custom form using FAPI. The code is as follows :

```
$form['format_document'] = array(
  '#type' => 'radios',
  '#options' => array(
    'yes' => t('Yes'),
    'no' => t('No')
  ),
  '#title' => t('Should we format your document?:'),
  '#required' => TRUE,
  '#default_value' => 'no',

  '#suffix' => 'markup for the help image',

  '#states' => array(
    'visible' => array(
      ':input[name="select_service"]' => array(
        array('value' => '1'),
        array('value' => '2'),
        array('value' => '3'),
      ),
    ),
  ),
);

```

The `#states` work fine on the form element visibility; however the `#suffix` part is always visible. I can create a new form element with the same #states, but I have to do this on large number of elements. Is there something I am missing in the `#states`?

# Answer
> 3 votes
You could put your form element with the suffix into a container forms element. The container can also have states:

```
$form['format_document_container'] = array(
  '#type' => 'container',
  '#states' => array(
    'visible' => array(
      ':input[name="select_service"]' => array(
        array('value' => '1'),
        array('value' => '2'),
        array('value' => '3'),
      ),
    ),
  ),
);

$form['format_document_container']['format_document'] = array(
  '#type' => 'radios',
  '#options' => array(
    'yes' => t('Yes'),
    'no' => t('No')
  ),
  '#title' => t('Should we format your document?:'),
  '#required' => TRUE,
  '#default_value' => 'no',

  '#suffix' => 'markup for the help image',
);

```

# Answer
> 1 votes
I faced similar issue. Problem is that `#suffix` is rendered outside element's template, so #states have no way to know about it.

My solution was to put image inside element. First, I registered it's theme function in my module:

```
function mymodule_theme() {
  return array(
    'preview_upload' => array(
      'render element' => 'element',
      'file' => 'mymodule.module',
    ),
  );
}

```

And then I defined this function as follows:

```
function theme_preview_upload($variables) {
  $element = $variables['element'];

  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] = (array) $element['#attributes']['class'];
  }
  $attributes['class'][] = 'form-managed-file';

  // This wrapper is required to apply JS behaviors and CSS styling.
  $output = '';
  $output .= '<div' . drupal_attributes($attributes) . '>';
  if (isset($element['#file']->uri)) {
    $output .= '<img src="' . image_style_url('thumbnail', $element['#file']->uri) . '" class="preview" />';
  }
  $output .= drupal_render_children($element);
  $output .= '</div>';
  return $output;
}

```

Now wherever I add `'#theme' => 'preview_upload'` to my `'#type' => 'managed_file'` elements, it provides me with preview image *inside* element's wrapper.

# **How** I did it, exactly?

I searched api.drupal.org, found the original theme function for the element I wanted co change (`theme_file_managed_file`), copied it to new name and edited last lines, the `$output .=` block. Just do the same.

Remember that you can add arbitrary attributes to your form element. Nothing against setting:

```
'#theme' => 'with_help_image',
'#help_image' => 'http://example.com/sites/default/files/image.png',

```

and then using `$element['#help_image']` in a way similar I was using `$element['#file']`, if your form element does not have this image "naturally".

---

Of course you may also forget `#states` and create custom JS code, that will be aware of your `#suffix`. Choice is ultimately yours, I would prefer theme change and built-in states, but it's just my own "I feel it's simpler in the long run" opinion, not a hard measurable fact.

# Answer
> 1 votes
On searching through the documentation of Form API, I found that there is a shorter way of doing this.

I have used `#field_suffix` instead of '#suffix' and it works.. !!

The suffix that is being added this way actually becomes a part of the main div wrapping the element.

---
Tags: 7, javascript
---


# Question
Title: How do I extract individual fields from rendered user?
I am developing a community website. We have two separate types of members -- regular members and business members. Business members can access subscription options to sponsor the chapter (website) but the members are not able to access these subscriptions.

I am using lm\_paypal for the subscriptions, as it seems to do just what we need it to do.

My only problem is that lm\_paypal hardcodes their information in the user profile. THere are three blocks it places on the user profile (or rendered user): a donations block, an active subscriptions block and a block to allow you to subscribe and unsubscribe from subscriptions.

Here is the function in lm\_paypal\_paid\_averts that does this (I think!)

```
/**
* Implements hook_user_view().
*/
function lm_paypal_paid_adverts_user_view($account, $view_mode) {
global $user;

// In the "my account" view area show all paid_adverts
if (user_access('administer lm_paypal') || $user->uid == $account->uid) {
$account->content['paid_adverts'] = array(
  '#type' => 'user_profile_category',
  '#title' => t('PayPal Paid Adverts'),
  '#weight' => 6, // under History which is 5.
);
$account->content['paid_adverts']['subs'] = array(
  '#type' => 'user_profile_item',
  '#title' => t('Adverts you paid with us:'),
  '#markup' => lm_paypal_paid_adverts_list_nodes($account->uid, 10),
);
 }
}

```

The only way I can see to display this information is by using the "Rendered User" field in Panels, which displays a lot of other things, including history, recent content, etc. It also displays it on all user profiles, regardless of whether the user can actually access the subscriptions or not (my members can click on the link, but they get access denied page). I would like to have the subscription blocks showing only on the business member profiles and the donation blocks showing on all profiles.

What I need is a way to pull out just this lm\_paypal information from the rendered user so that I can display it in its own block and set access control on it so only business members can actually see the subscriptions.

I've been googling for an answer to this for almost a week and found a few different solutions that *may* work, but require extra modules to be installed and it seems like a lot of extra weight for just needing a piece of a whole. I've found some answers regarding placing code in places, but I have to admit, I'm so close to having this presentable, I'm slightly terrified of trying too many things and somehow messing up. I've built this site myself, starting with no experience at all, and I've had many ups and downs along the way... I am terrified being this close to done and doing something to mess it up and not be able to recover it.

So I am hopeful that someone here can give me a clear answer where I don't have to make guesses and assumptions and perhaps mess myself up!

Is there a way to pull these fields from the user profile and print them separately in their own block?

# Answer
A lightweight custom module to create a block for your business members and one for your regular members should do it. Creating a custom block isn't as daunting as it seems, it's one of the easier customizations you can do. The Block API should be very helpful here. Here's a quick example:

```
 /* Implements hook_block_info() */

function myblock_block_info() {
  $blocks['my block'] = array(
    'info' => t('Business User Block'),
    'cache' => DRUPAL_CACHE_PER_PAGE
  );
  return $blocks;
}

/* Implements hook_block_save() */

function myblock_block_save($delta = '', $edit = array()) {
  variable_set('block_text_prefix', $edit['block_text_prefix']);
  variable_set('block_text_suffix', $edit['block_text_suffix']);

}

/* Implements hook_block_view() */
function myblock_block_view($delta = '') {
  //get the information you want out of the profile here
  $block['content'] = //your information formatted here
}

```

---

**Devel info:**

If you double click on a row in the devel table, it will tell you how to reference it:
> 0 votes

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


# Question
Title: How to hide a block based on content type?
I have a custom content type where when loaded, I want to HIDE (no show) a regions block. Been looking around trying to find the answer and have come up short. Ideally, I'd want to do it in a preprocess or something, not within a template. Tried accomplishing it with Context, but appears that only allows you to add blocks to regions, not remove them. Fairly new to Drupal, so bare with me.

# Answer
Sadly, it is not yet part of Context to negate the context (that I am aware of).

You have 2 options (slightly different than the link mentioned by @Mołot):

1. Write your own context. It's actually not that hard, and you can follow the general flow suggested in (this post)\[http://dtek.net/blog/extending-drupals-context-module-custom-condition-based-field-value\].
2. Use the built-in visibility settings on the block configuration page to enable the block on all content types but the one you want, and all pages desireable (e.g, `user/*`, views pages, etc.).
> 0 votes

# Answer
Display Suite Extras (comes with Display Suite) allows you to do this. Context will also allow you to do it, but it is theme-dependent (not all themes can allow it, and not for all regions).
> 0 votes

# Answer
When PHP filter is enabled you can set the visibility by PHP code. Then you can do the following to hide the block when viewing a node of a special type:

```
$node = menu_get_object();
if ($node->type == 'CONTENTTYPE') {
  return FALSE;
}
return TRUE;

```
> 0 votes

---
Tags: blocks, nodes
---


# Question
Title: Review your selections and rate them in Webform within Drupal 7
I have created a Form with the help of amazing Webform module in Drupal 7. It's a kind of various selections (through checkboxes) user makes.

This is all working fine but the problem is the last step.

I want user to review all the selections he made in the last page and give a priority to each selected option.

Now there are two things I want to do:-

* Review the selections made in the Form at the end.
* Prioritize them; by selecting a number 1-5 with each entry.

Please pardon my ignorance, but is it even possible with Webform?

Many Thanks.

# Answer
Preview functionality is now part of the 7.x-4.x branch. There is an involved discussion about it here: Summary/review/preview page before final submission in multistep forms.

As for prioritizing, I think you would want to add a rating field for each field, and theme the form and the preview such that the initial form would not show the rating field, and the preview would.

Depending on what you want to do with those ratings, you may want to use a module like Star Rating (which is a simple module that doesn't have any other dependencies) or FiveStar (which is more complex and has more functionality).
> 1 votes

# Answer
for your first issue:

you should check out node/\[nid\]/webform/configure - At the bottom of the page you find "Preview page" if you activate it, the user can see a preview button.

for your second issue:

as far as i know there is no module that does that. So i think you have to code it by yourself! As a startingpoint i would say you have to use the hook\_form\_alter() hook and insert your priorization fields... after that you have to alter the submit handler for saving the priority values.

\*edit

after some research i found the webform-fivestar module... but i'm not sure if it is possible to show them only on the preview page and make them editable... i think you need some custom-code...

is it really necessary to rate them on the review page and not directly on the form?
> 1 votes

---
Tags: webforms
---


# Question
Title: Best way to test if a commerce price field has a value
So I have an entity called "Discount" with the following fields:

* `field_discount_percentage` is an integer field.
* `field_discount_price` is a commerce price field.

I can test whether the percentage field contains a value to avoid exceptions via:

```
if (empty($discount_wrapper->field_discount_percentage))

```

However this does not work for commerce price fields, as `$discount_wrapper->field_discount_price` is an object in itself and so the following is always true:

```
if (empty($discount_wrapper->field_discount_price))

```

Alternatively I tried:

```
if (empty($discount_wrapper->field_discount_price->amount))

```

However this produces an exception on zero values, and the following:

```
if (empty($discount_wrapper->field_discount_price->value()))

```

Which returns a PHP Fatal error as `empty()` can only take variables and not functions.

I am now resorting to:

```
if ($discount_wrapper->field_discount_price->value())

```

However this does not feel explicit and I was hoping there is a more conventional means to test price fields.

# Answer
> 0 votes
Adding isset() to that last `if` statement is a bit more explicit.

```
if (isset($discount_wrapper->field_discount_price->value()))

```

# Answer
> 0 votes
Not sure what you're looking for but you've got `commerce_price_wrapper_value` function to extract a price from an entity in a consistent way, example:

```
$unit_price = commerce_price_wrapper_value($wrapper, 'commerce_unit_price', TRUE);

```

The third parameter is a boolean that indicates to return the default price structure.

---
Tags: commerce
---


# Question
Title: Search API Views - Show search string in text
I created a view to display my indexed data, anything works just fine. What I now want to achieve is, that only the part of the bodytext is displayed, that contains the search string. The default drupal search engine can do this, but I have no idea how to achieve this using views.

Someone got an idea how to do that?

Greetings

SG

# Answer
> 0 votes
Views Search module will work for you.

---
Tags: views, search
---


# Question
Title: Media module and wysiwyg inserts image link rather than rendered image
I'm using wyswig and ckeditor with media module to insert images into the body field of a node.

Instead of displaying the image it displays a link to the image. Viewing source this is what is inserted:

```
<p><span class="file media-element file-default" data-file_info="%7B%22fid%22:%2213%22,%22view_mode%22:%22default%22,%22type%22:%22media%22%7D"><img alt="" class="file-icon" src="/modules/file/icons/image-x-generic.png" title="image/jpeg" /> <a href="http://dev.charm.ucsf.edu/sites/dev.charm.ucsf.edu/files/feature_MB2.jpg" type="image/jpeg; length=22001">feature_MB2.jpg</a></span></p>

```

I have "**Convert Media tags to markup** checked" and I am NOT **limiting HTML tags**. Any ideas why it's stripping out the **"\["** and **"\]"**?

Thanks, Jon

# Answer
You can fix this in the web admin GUI:

Configuration \> Media \> File Types \> Image \> Manage File Display \> Check the "Image" box.
> 2 votes

# Answer
Not sure if you've found a solution by now, but I had the same issue and it turned out to be panels that was causing the problem. To solve this, I went to Page Manager \> My Variant \> Content. I then chose the piece of content that had the image in it and in the settings changed the formatter to 'Rendered File' and chose the view mode 'Large' (it had been 'Rendered File': 'Default', which displayed the link to the image rather than the image itself). I hope this helps!
> 0 votes

---
Tags: wysiwyg, media
---


# Question
Title: How to create Scald Atoms media library for each content type?
I need to categorize the "Atoms Library" items in a way that there would be a "Atoms Library" for each content type. How could create a Atoms Library for each conten type? or How I could categorize the items in "Atoms Library" according to content type?

Is this possible to create a "Atoms Library" for each content type?

# Answer
> 1 votes
There are two Views that come with Scald:

* scald\_library - Which, for our purposes, is what controls the format of the menu in the editor.
* scald\_atoms - Which controls the format of the Scald Library at /admin/content/atoms.

Both are fully editable views.

For the admin page, clone the View and assign each one a unique filter for Atom:Type and give each View a unique path URL. Add these URLs to an admin menu somewhere to make them findable.

The editing menu is a little more complicated. Cloning and filtering the View is the same, but I believe using them would require adding new functionality to either the editor or Scald. Though people editing content can still filter by type in the Scald search pane.

---
Tags: nodes, views, scald
---


title: How to add a div wrapper around a zone?

text:
# Question
Title: How to add a div wrapper around a zone?
I'm using the Omega theme and have a zone that I need a div around for a certain content type. Trying to figure out the best way to do it. Was thinking a preprocess, but no clue which. Fairly new to Drupal so bare with me.

# Answer
> 0 votes
Adding something like this to the template.php of your subtheme should get you in the right direction.

```
function MYTHEME_alpha_preprocess_region(&$vars) {
  $menu_object = menu_get_object();
  if (isset($menu_object->type) && $vars['region'] == 'content') {
    $vars['theme_hook_suggestions'][] = 'region__content__'.$menu_object->type;
    $vars['attributes_array']['class'][] = 'region-content-'.$menu_object->type;
  }
}

```

Then you just need to create .tpl files for them in the same way you would for other content type based tpl files (example: region--menu--page.tpl.php)

---
Tags: theming
---


# Question
Title: Restricting the term reference field from creating a new vocabulary term
I have a `term reference field` in a form and it is an `auto-complete term widget`, it has a vocabulary that supplies the values to it. My intention is to allow users to input only the terms which are defined with in the vocabulary and it shouldn't accept entries other than the vocabulary terms. But, the field is allowing other entries from the user.

For example, consider the `term reference field` is associated with a `vocabulary`. Now,if an user enters the values(other than the vocabulary terms) within that field and submits the `form`. It accepts the values and inturn creating a new vocabulary term with the given values. Here I want to restrict the automatic creation of terms. If the value is not defined in the vocabulary terms, it shouldn't accept the form.

I want to restrict user to enter the values which are defined. If a user enters the value which is not defined in the vocabulary, it should give an error message.

Here, my problem is the vocabulary has already been assigned with some data and I couldn't delete the vocabulary anymore.

Any alternatives to restrict the term references??

# Answer
Thanks to @Molot for directing me to the post Limit of the creation of tags. It works and the key is Content Taxonomy module.
> 0 votes

# Answer
Is there a specific reason why you want users to type in the term? You should be able to change the widget type to something else (select list or multiselect). This has also been discussed at length as an issue against the Taxonomy module (Autocomplete term widget: disable creation of new terms).
> 0 votes

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


# Question
Title: Getting all the Submitted field values after the Webform is just submitted in Drupal 7?
I created a webform for which I need all the submitted fields with values on the confirmation page after the user submitted the form. I am using WebForm 7.3.

The user when confirms the information, can make any final change before submitting it (updating the existing one, I guess).

This is what I used and placed it in the template.php but sadly it doesn't work:-

```
function user_register_webform_submission_insert($node, $submission){
// Load information about form components
$comps = $node->webform['components'];
$fields = array();

//Extract the component info to get form_key=>cid to resolve relation
foreach($comps as $cid => $comp_info){
    $fields[$comp_info['form_key']] = $cid;
}

// Load the submitted data (field values)
$data = $submission->data;

//Prepare a user info
$user = array(
    'mail' => $data[$fields['mail']]['value'][0],
    'name' => $data[$fields['name']]['value'][0],
    'pass' => user_password(8),
    'status' => 1,
    'init' => $data[$fields['mail']]['value'][0],
    'roles' => array(2, 3),
);

$account = user_save(null, $user);
}

```

# Answer
If you are able to upgrade Webforms, preview functionality is now part of the 7.x-4.x branch of the Webform Module. There is an involved discussion about it here: Summary/review/preview page before final submission in multistep forms.
> 1 votes

---
Tags: webforms
---


# Question
Title: How do I create a simple breadcrumb with pathauto?
I'm using Pathauto to setup my url paths like this:

www.blah.com/parent1/parent2/page-name

I want my breadcrumbs to mirror this on every page:

Home \>\> Parent1 \>\> Parent2 \>\> Page Name

I've installed custom breadcrumbs but it wants me to create a custom breadcrumb for each content type. Can I just create one to use site wide? Preferable add via a block or view.

# Answer
I guess easy\_breadcrumb module would be good to use for this scenario.

> The Easy Breadcrumb module provides a plug-and-play block to be embedded in your pages, typically at some place near the page's header. Easy Breadcrumb uses the current URL (path alias) and the current page's title to automatically extract the breadcrumb's segments and its respective links.

Example: URL like `gallery/videos/once-a-time-in-cartagena`, Easy Breadcrumb will automatically produces the breadcrumb as

> Home \>\> Gallery \>\> Videos \>\> Once a time in Cartagena

or

> Home \>\> Videos \>\> Once a Time in Cartagena

Again, the breadcrumb presentation will vary depending on your module's settings.
> 1 votes

# Answer
A little digging into this topic and I found there is an alternative module that is highly rated with good support. https://www.drupal.org/project/path\_breadcrumbs

> Path Breadcrumbs module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL!
> 0 votes

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


# Question
Title: How to configure Facet displays that comes with Commerce kickstart
Commerce kickstart comes with some filtering when viewing all the products, I do not have idea how to make my own facet displays, and I cannot find anything in the drupal configuration about facet displays. Can someone explain it to me?, would be great if it is with an example

# Answer
Ok I could figured it out thanks to this great tutorial

http://vimeo.com/53404289

There is how you can manage your own commerce facets
> 2 votes

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


title: Add button to default D7 view

text:
# Question
Title: Add button to default D7 view
Is there a way to add a selection button or a check box to the display of a default view? I am hoping to catch the node information of the selected row into a bucket or into a container. Below is the screen shot of my default view, I need to add the button or check box at the end of the 'Treatment' column. I have little understanding about the hook\_views\_default\_views\_alter(hoping that its implementation is relevant in this case) but not sure how a button could be added using it. Let me know if the question needs more clarification or any additional information is required.

Thanks

# Answer
See this drupal.org documentation page called How to add a column with dynamically generated action buttons in a View. `hook_views_default_views_alter` has essentially nothing to do with this task. Optionally an easier path is like Rules with Views Bulk Operations if you can live with like a checkbox per row, and a dropdown for the operation selection.

The more custom a look, or outside of Drupal's default behavior you deviate. The more work you have to do.
> 0 votes

---
Tags: views
---


# Question
Title: Commerce checkout form all pane errors to be displayed on top of form
I am using latest commerce module with D7 site. By default commerce displays form errors inside individual commerce checkout form panes. This is designed by default and every pane has it's own validation callback. So this is different from Drupal's form API error displaying.

Is it possible to display them at the top of the form, same as Drupal form API does it? Does form\_set\_error works well for all checkout form elements and they get error class? (it seems to not work for me).

# Answer
As Ryan mentioned, it's difficult to change that behaviour server-side, however you could move the error messages to the top of the page with JavaScript instead.

e.g

**style.css**

```
/* Hide checkout messages by default to show with JS later */
body.page-checkout .messages{
  display:none;
}

```

**script.js**

```
Drupal.behaviors.moveCheckoutMessages = function (context) {
  $('body.page-checkout form .messages', context).each(function () {
    $('.region-content').prepend($(this));
    $(this).css({"display":"block"});
  });
}

```

A client-side approach like that should work.
> 1 votes

# Answer
Given the way we developed the checkout form as a composite of checkout pane "sub forms", it isn't possible to change the way we're trapping and displaying error messages. You would need to create a drop-in replacement for the checkout form.
> 0 votes

---
Tags: 7, theming, forms, commerce
---


# Question
Title: What is the best way to get array in some drupal data
By example, I get this array :

```
content_device
    ...
    fields_examples
        und
            0
                sub_field_one
                sub_field_two
                ...
            1
                sub_field_one
                sub_field_two
                ...
            2
                ...
            ...

```

And currently, if I want modify a subfield, I do this :

```
content_device['fields_exemples']['und'][1][sub_field_two] = ...

```

Is there a best way (drupal or php way) for get a sub data more cleany ? I mean (sorry for my poor english writing x) ), I find the "\['und'\]\[1\]" heavy. If I get the fields\_examples array, can I get the sub-arrays '0', '1', '2' ... without use the 'und' in this example ?

My example isn't very explicit, but I know I have some array in my website who contain sub-sub-sub-...-array in sub-sub-...-array in ... in array. And often, an array contain one only sub-array. So if I want get the sub-sub-array, I find the 'only' sub-array very useless, and he complicates the code.

I hope I was clear x)

# Answer
I'd recommend you to look at `entity_metadata_wrapper()` function which comes with the Entity API module.

> The Entity API provides wrapper classes you may use to make dealing with the values of an entity's properties and fields easier. Wrappers make it easier to get and set the values of fields and properties as well as to programmatically retrieve additional information about these elements and iterate over lists of values in a consistent manner.

For example, using `entity_metadata_wrapper()` you can modify a field (or a "subfield" with your terms, I think you mean a field in a field collection) in a following way:

```
// You should first wrap your node with entity_metadata_wrapper().
$node_wrapper = entity_metadata_wrapper('node', $node);

// To get the value of a field
$field_value = $node_wrapper->field_example->value();

// To get the value of a field in a field collection etc.
$field_value = $node_wrapper->field_example->sub_field_one->value();

// To set/modify the value of a field in a field collection etc.
$node_wrapper->field_example->sub_field_one->set('Some new value');

// To save the entity after modifying some values
$node_wrapper->save();

```
> 0 votes

---
Tags: nodes
---


title: problem in search

text:
# Question
Title: problem in search
D7

I have this site http://thefracdepot.com/ I developed this at drupalgardens then move to other hosting. The problem is that at new hosting search not displaying all the nodes which have searched keyword. It only showing gallery and about us page. No other basic page is appearing. It was working fine at drupalgardens, and I also can see all products pages in google search, but my site search is not displaying related nodes.

note I have done re-indexing but still no luck. Can anyone help in finding out the reason for this problem and solution?

# Answer
> 1 votes
The content get re-indexed only after the next cron run. If you didn't run cron after re-indexing, the search will not show all the content.

---
Tags: search
---


title: Slideshow business theme on every page

text:
# Question
Title: Slideshow business theme on every page
I have the business drupal theme aplied on a test site, in this theme u have a slideshow on the front page. I wanted to display it on every page so I copied following code to page-tl.php

```
    <?php if (theme_get_setting('slideshow_display','business')): ?>
    <?php
    $url1 = check_plain(theme_get_setting('slide1_url','business'));
    $url2 = check_plain(theme_get_setting('slide2_url','business'));
    $url3 = check_plain(theme_get_setting('slide3_url','business'));
    ?>
      <div id="slider">
        <div class="main_view">
            <div class="window">
                <div class="image_reel">
                    <a href="<?php print url($url1); ?>"><img src="<?php print

base_path() . drupal_get_path('theme', 'business') . '/images/slide-image-4.jpg'; ?

>"></a>
                    <a href="<?php print url($url2); ?>"><img src="<?php print

base_path() . drupal_get_path('theme', 'business') . '/images/slide-image-5.jpg'; ?

>"></a>
                    <a href="<?php print url($url3); ?>"><img src="<?php print

base_path() . drupal_get_path('theme', 'business') . '/images/slide-image-6.jpg'; ?

>"></a>
                </div>
                <div class="descriptions">
                    <div class="desc" style="display: none;"><?php print check_markup

(theme_get_setting('slide1_desc','business')); ?></div>
                    <div class="desc" style="display: none;"><?php print check_markup

(theme_get_setting('slide2_desc','business')); ?></div>
                    <div class="desc" style="display: none;"><?php print check_markup

(theme_get_setting('slide3_desc','business')); ?></div>
                </div>
            </div>

            <div class="paging">
                <a rel="1" href="#">1</a>
                <a rel="2" href="#">2</a>
                <a rel="3" href="#">3</a>
            </div>
        </div>
      </div><!-- EOF: #banner -->
    <?php endif; ?>

  <?php print $messages; ?>

  <?php if ($page['homequotes']): ?>
  <div id="home-quote"> <?php print render($page['homequotes']); ?></div>
  <?php endif; ?>

  <?php if ($page['home_high1'] || $page['home_high2'] || $page['home_high3']): ?>
    <div id="home-highlights" class="clearfix">
     <?php if ($page['home_high1']): ?>
     <div class="home-highlight-box"><?php print render($page['home_high1']); ?></div>
     <?php endif; ?>
     <?php if ($page['home_high2']): ?>
     <div class="home-highlight-box"><?php print render($page['home_high2']); ?></div>
     <?php endif; ?>
     <?php if ($page['home_high3']): ?>
     <div class="home-highlight-box remove-margin"><?php print render($page

['home_high3']); ?></div>
     <?php endif; ?>
    </div>
  <?php endif; ?>

```

Now the sliding effect is gone (except on the front page), so I thought that there was missing javascript. However I can't find a solution...

U can see the problem on Click for problem here

# Answer
You should also include the javascript files on every page instead of only on the front page.

If you look at the `template.php` file in the theme folder, at the end of the file:

```
/**
 * Add javascript files for front-page jquery slideshow.
 */
if (drupal_is_front_page()) {
  drupal_add_js(drupal_get_path('theme', 'business') . '/js/sliding_effect.js');
}

```

You should remove the if statement to make it load on every page:

```
/**
 * Add javascript files for front-page jquery slideshow.
 */
drupal_add_js(drupal_get_path('theme', 'business') . '/js/sliding_effect.js');

```
> 0 votes

# Answer
You may have to review your code, your sliding effects javascript file is missing from your other pages except for the front page.

```
<script type="text/javascript" src="http://karelmaes.stijnaerts.be/sites/all/themes/business/js/sliding_effect.js?n8jrx6"></script>

```

Above missing.

You can check this out for more information Adding Javascript to themes
> 0 votes

---
Tags: javascript
---


# Question
Title: Which permission do I need to give to see all open tasks in the Maestro taskconsole
It is unclear to me which permission I do need to give to a specific role, to see all open tasks in the Maestro taskconsole, just like an admin sees all tasks.

Thanks for your help

# Answer
Seems that you need to give the following permissions:

* Access Maestro Task Console
* View Outstanding Tasks
> 0 votes

---
Tags: workflows
---


# Question
Title: Drupal doesn’t create clean links – checkbox doesn’t do anything
After migrating my Drupal 7.27 site to a new server, I can’t get Drupal to re-enable Clean URLs.

The .htaccess file works and I can access clean URLS, but Drupal doesn’t create clean links. (For example, /admin/config/search/clean-urls works fine, but the link in Drupal points to /?q=admin/config/search/clean-urls.)

The clean URLs configuration page doesn’t say anything about the test, but offers me the option to enable clean URLs:

When I do that, it says the configuration options have been saved, but the checkbox is still unticked:

I also manually changed the settings.php to include `$GLOBALS['conf']['clean_url'] = 1;` but that doesn’t help either.

Does anyone have any ideas why this is happening and how I could get Clean URLs to work properly?

# Answer
1)enable rewrite module on apache.

a2enmod rewrite

(to disable type a2dismod rewrite)

2)Set directory permission. You must find the file that sets permission of each directory for apache. In my case it was /etc/apache2/sites-enabled/000-default edit the page so that the directory that you will be using to serve webpages has "AllowOverride All". My file contains the following:

Options Indexes FollowSymLinks MultiViews

AllowOverride All

Order allow,deny

allow from all

3)Just restart apache and it should be working: /etc/init.d/apache2 restart

There are several other checkpoints to fix this issue. All the points are discussed here
> 1 votes

---
Tags: uri, configuration, forms
---


# Question
Title: How do you remove the search box on the search results page?
I'm working on customizing my search results page. By default, the results page contains another instance of the search box at the top. I have the search box in a block at the top of every page, so it's just cluttering things up on the results page. I have already overridden the two template files, but I don't see anything in there that outputs the second search box. How can I remove it?

# Answer
Here's a simple approach to work within your theme, without requiring a dedicated module:

add to your template.php file...

```
function YOURTHEME_page_alter(&$page)
{
  if (arg(0) == 'search')
  {
    if (!empty($page['content']['system_main']['search_form']))
    {
      hide($page['content']['system_main']['search_form']);
    }
  }
}

```
> 1 votes

# Answer
This is a fun one... The Search box is returned as part of the render array returned by `search_view()`.

I suggest that you make a `hook_menu_alter()` which replaces the default callback for the search page with your own, which is basically a pass-thru to the core function, but that unsets the search form. Something like this:

```
function MYMODULE_menu_alter(&$items) {
  $items['search']['page callback'] = 'MYMODULE_search_view';
}

function MYMODULE_search_view($module = NULL, $keys = '') {
  $build = search_view($module, $keys);
  unset($build['search_form']);
  return $build;
}

```

Don't forget to clear your cache to pick up the new hook and menu changes.

You may need to add additional paths to the `hook_menu_alter()` as needed (e.g., if you search users, then you may need to add entries for `search/user` and `search/user/%menu_tail`).
> 4 votes

---
Tags: theming, search
---


title: Show related content. Search results?

text:
# Question
Title: Show related content. Search results?
I am working on an Equipment Checkout system using Drupal 7, MERCI, views, panels, rules, and many other modules. I am working for a community college in Oregon. I am upgrading features on an already running system that was built by myself with the help of a few other people last year. The system is offline for the summer.

One of the features that I am trying to implement is that when we pull up a customer account, we also see content related to the customer blog posts, reservations, and some custom content types.

I have created a block called 'Customer History' on the customer view for the information to be displayed.

So now I need to figure out how to get the content into that block.

I'm thinking that I could somehow do a search for the customers name and display results in the block. What do you think? Is this a good way to go?

Any help would be great thank you.

# Answer
> 0 votes
Views is probably your best option, using a contextual filter, and various Views Blocks

If for example the url was www.mysite.com/user/12/profile, you could list all of any number of content types where the user id matches 12.

The specific answer depends on the structure however. If you include that information, I will update this answer with more specific direction.

**EDIT 1:**

* create a separate view for each content type you want visible on the user's page
* for each, set it as a BLOCK, not a page, and set the fields and order, etc as appropriate
* set a contextual filter - this will depend on your structure, but I will show one as an example and you should be able to extrapolate. Contextual Filter-\>Content:Author uid
* Contextual Filter, When not Available -\> Provide Default Value, Raw Value from URL, Path Component 2 (for /user/12/\*)
* go to admin/structure/blocks and you should see the new views blocks. set them to only show on user/\* for example to show in the profile pages, and place the blocks in the appropriate region

---
Tags: views, panels
---


# Question
Title: Search API display message when match not found
I had an issue before (Search API with views -\> Apply filters) that has been solved already.

I have a website where i manage to create a database, display it with the views module and add a Search box with Search API.

The search module works great but i would like to know how can I make it to display a message when there's no match found. Something like "Your search didn't match any documents. Please try again."

Does anyone know how do I do that?

Thanks in advance!!

# Answer
In Views, under the Advanced Tab, click on NO RESULTS BEHAVIOUR. There you can include a general statement (global text) when it returns nothing.
> 0 votes

---
Tags: views
---


# Question
Title: Privatemsg through a Multi Site configuration?
Is it possible to do such a thing for users in site 1 to message users in site 2 and visa versa? Using the Privatemsg module?

# Answer
Multi-site is just a way to share code. Different sites are completely separated and know nothing of each other\*.

There might be ways to theoretically do this using special recipient types, it would have to use services (or raw SQL queries) to another drupal installation, multi-site or not. And it wouldn't be easy to implement and likely also be very slow.

\*With the exception of shared tables, but if you'd share your users, you wouldn't have different users in the first place.
> 1 votes

---
Tags: 7, multi-sites, privatemsg
---


# Question
Title: Why do we duplicate field data in the field_revision_* tables when revisions are disabled?
Even with revisions turned off for a given content type, the field\_revision\_\* tables for the fields each contain a single record that matches the corresponding record in the corresponding field\_data\_\* table.

I've always been aware of this, and previously, I've never had a reason to question it. However, now I am dealing with an extremely large database, and almost 50% of the database size is made up of this duplicated data in the revisions tables.

Why do we duplicate all the field data in the revision tables when revisions are disabled for a content type?

# Answer
> 0 votes
That's a great question - I wonder if it's any different in D8.

The field\_data tables, and node table also track the "current vid" which is the current revision id, I guess they felt there had to be at least one. But it does seem like there should be another way to do this. Maybe they could just store a 0 or something as a flag in the field\_data tables current\_vid column to indicate there's not a revision.

---
Tags: database, nodes
---


title: How do I create a tree system?

text:
# Question
Title: How do I create a tree system?
Before I knew Drupal, I made a CMS that was working like Wikipedia, where each page and link could have parent and children. Now I want to create that website with Drupal.

Is there any module for this?

This is what I need: Each page may have children, and each children may have children too and so on.

# Answer
There is a core module namely 'Book' . Use that module to get desired structure of pages.

For more information visit here
> 3 votes

# Answer
In Drupal you just create the pages - pages (nodes) are separate from the menu navigation system. There are no relationships between pages until you create links in the menu system. Use the menu to make the links to the various pages, then organize the tree relationship in the menu admin tool using drag & drop to place the navigation links in their proper structure.
> 0 votes

---
Tags: 7
---


# Question
Title: Programmatically render an imagefield in Drupal 6 as defined in content-field.tpl.php
What sounds like simple task in the first place, has taken me hours without getting a solution: All I want is to render single values of an imagefield just as in the normal node, i.e. as defined in content-field.tpl.php. This is important for me, because there I add captions from the Imagefield Extended module

I tried with content\_format(), but with the "default" formatter it gives me just an icon and a link and with the "image\_imagelink" formatter from the imagefield.module I get an image, but not as defined in content-field.tpl.php and in the node type's display settings:

```
print content_format('field_image', $vars['node']->field_image[1], 'default', $vars['node']);
print content_format('field_image', $vars['node']->field_image[1], 'image_imagelink', $vars['node'])

```

I have tried a couple of other things and searched for hours, but I cannot find an answer. Any ideas how I can render the image "just the normal way"?

The HTML out I want is a defined in the template something like this:

```
<div class="field field-type-filefield field-field-image">
  <div class="field-items">
    <div class="field-item odd">
      <a class="imagefield imagefield-lightbox2 imagefield-lightbox2-page-grid-6 imagefield-field_image imagecache imagecache-field_image imagecache-page-grid-6 imagecache-field_image-page-grid-6 lightbox-processed" rel="lightbox[field_image][Caption text]" href="http://example.com/files/imagecache/image_full/img/2014/img.jpg">
        <img width="364" height="242" title="Caption text" alt="Caption text" src="http://example.com/files/imagecache/page-grid-6/img/2014/img.jpg">
      </a>
      <div class="img-meta">
        <div class="img-title">
          <p>Caption Text</p>
        </div>
        <div class="img-source-info">
          <div class="img-source">
            <span class="img-source-label label">Source:</span>
            <span class="img-source-content content">Source text</span>
          </div>
          <div class="img-license">
            <span class="img-license-label label">Licence:</span>
            <span class="img-license-content content">Licence text</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

```

# Answer
> 0 votes
Do you have more than one image?

```
print content_format('field_image', $vars['node']->field_image[0], 'default', $vars['node']);
print content_format('field_image', $vars['node']->field_image[0], 'image_imagelink', $vars['node']);

```

Try again with `[0]` instead of `[1]`. I use those all the time and it works fine like that.

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


# Question
Title: Can a content type have default input in fields
Is there a way for a user to add new content and have some of the fields already pre populated with default text/input.

That way the user can amend what changes are required for a node without having to copy and paste what will be very similar details into the add content screen node/add/\[content type\]?

Hope that makes sense.

# Answer
Yes almost all fields have a section to add default content. Go to "Structure" \> "Content Types" \> Your content type \> "Manage Fields" then select edit on the field that you want to add the default text to
> 2 votes

# Answer
You are probably looking for prepopulate...

https://www.drupal.org/project/prepopulate

Although that may not be workable for all forms as you wish, but when I used it, it worked as expected.

This module allows you to enter field names and their default value on a URL and the module take that data and puts it in the input fields as default.
> 2 votes

---
Tags: 6, nodes, users
---


# Question
Title: How to get different size image on views
I have a view that fetches content that is then shown in a block. It shows 16 nodes and each node has title, date and image. The images are set to use the imagecache preset in the view field settings.

I need to show the first and the seventh image with different sizes, 750x400 instead of 300x300.

Is it possible to achieve this changing the view settings or on template level?

# Answer
> 0 votes
I used IMCE under Drupal 6.x. However, the resize only occurs at the time you upload and image with their editor which is cumbersome, to say the least. It depends on who has to upload the images, I guess.

Otherwise, CSS, as others mentioned, is probably your best bet. Now a day, browsers properly (cleanly) resize images so they still look good. (10 years ago, however, it was horrible!)

If you want to use IMCE and need to resize existing images, you could look into using `convert` on your server to resize existing files. However, you'll have to write an intelligent script that properly renames everything properly...

---
Tags: views, 6, media
---


# Question
Title: Boost Cache helps some pages, hurts others?
I'm working on fixing some performance issues of a Drupal 6 site. Very new to Drupal, been figuring things out as I go, so please bear with me here.

My client has a rather busy site and uses Boost cache. On pages where Boost cache is applicable -- their home page, reviews pages, etc,... -- it works great. Pages are fast, load testing shows that they can take whatever's thrown at them. I just discovered that with Boost enabled, pages that are not eligible for its caching, such as pages with polls that need to pull from the DB each time, they are significantly slower to load then when Boost is disabled entirely.

For instance, here are the Loader.io results of a page in question. The instances where it completed successfully were with Boost disabled, instances where it failed were with Boost enabled. Ignore that 100% error rate test that's second from the top, MySQL actually crashed after the previous test and I forgot to restart it before running again.

All I know for sure is that the errors are caused by MySQL. It appears that Boost adds database overhead, maybe it has to check for information about cached pages and then it has to do a second query to draw the page if it doesn't find the cached information? I'd love any insight anyone can provide!

**Edit: Screenshot of Boost expiration settings**

# Answer
> 0 votes
There is an option in boost that let you count the number of hits even of cached pages. That version hits your database on each page hit. It's fairly small, but it still loads all the modules as it has to go through the standard Drupal initialization.

Make sure you turn that off if it is on to ease the load on the DB.

---
Tags: 6, caching
---


# Question
Title: How to define an optional argument to Route callback
I want define a simple controller action, which receive optional argument:

```
<?php

namespace Drupal\hello\Controller;

class SimpleCallback extends ControllerBase
{
    public function sayHiAction($name = 'there')
    {
        return new Response('Hi ' . $name, 200);
    }
}
?>

```

If I define the routing like this

```
# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
  requirements:
      _permission: 'access content'

```

GET `/hello` just gives me 404 response.

Follow official documentation, I updated my route:

```
# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
    custom_arg: 'there'
  requirements:
      _permission: 'access content'

```

But nothing changed.

# Answer
The docs you link to say:

> Finally, if any static arguments should be passed to the controller, provide those in the defaults array as well. **Name them to match the arguments of your controller method**. See below.

Emphasis mine.

So your code should be:

```
# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
    name: 'there'
  requirements:
      _permission: 'access content'

```

See also Required and Optional Placeholders in the Symfony routing docs.
> 20 votes

---
Tags: 8, routes
---


title: How to Retrieve Env Var in Drush

text:
# Question
Title: How to Retrieve Env Var in Drush
Is there a way to retrieve shell variables in Drush? I cannot find anything in Drush API docs. If there is no way, how does one handle environment (dev, staging, testing etc.) configurations? Any help is much appreciated. Thank you.

# Answer
What do you mean by "in Drush"?

If you are working in a Drush commandfile (e.g. writing your own Drush command), then you can get environment variables via php using the getenv function.

If you are calling Drush from bash, then you can use bash to expand environment variables (e.g. `drush dl --destination=$HOME/.drush`)

If you are wondering what to do because you have set up your web server to define environment variables that you are using in settings.php to bootstrap Drupal, then you cannot read these from Drush or bash, because they are only defined by your webserver. Try defining equivalent variables in your .bashrc.
> 3 votes

---
Tags: drush
---


# Question
Title: How can I indent parts of a Views field?
I have a content/node View listing several node fields in an unformated list. The fields are displayed inline since they combine to make a message to users; on their own the fields don't mean much.

As you can see there are 3 fields above; user picture, user name, and the comment body. I have marked the order and the areas of the 3 separate span classes. The problem of course is that when field 3 has more than one line of text the subsequent lines are not indented enough and overlap field 1. I have tried using margin-left and padding-left in combination with the text-indent property, but since field 3 is inline the CSS only ends up indenting the first line instead of the lines after the first as I need. I can display field 3 as a block and this does allow me to have better control, however it places the field on a separate row, and as mentioned previously I need the fields to be displayed inline so that they combine to make a message. In other words, if you see the red line below I would like the field 3 text to wrap and indent in a way that it stays to the right of the red line for lines 2 and after.

So it would end up looking something like below, but of course with the beginning of the lines not clipped.

The only thing I can think of is having 2 copies of field 3, both of which are trimmed. Therefore the first copy would be trimmed to only show 1 line and the second would be trimmed to show everything after the first line, however the problem is that I'm not sure how to trim the beginning of a field. So how can this be achieved?

# Answer
> 1 votes
1. Put the class clearfix as the row class (format-\>settings). If your theme does not have clearfix defined, define it yourself.
2. Hide the output of the other two fields (click on the field in views form and you will see this setting 'exclude from display').
3. Create a global: Custom text field and make sure it is the last field in the views list of fields.
4. Rewrite results -\> rewrite the output of this global text field, and from the replacement patterns select field 2 and 3 as tokens. Also add a class for that field in style settings such as 'align-block'. Define it as follows:

align-block { overflow:hidden; }

in your css file.

1. Add a class to your image field such as 'float-left'. Define it as follows:

float-left { float:left; }

in your css file.

---
Tags: views, entities, theming
---


# Question
Title: Referencing other nodes created by the same author
I have a site where members can sign up and post an article (standard content type) which I'll call STYLE A. I now need to allow the members to create a different article (another content type) which I'll call STYLE B.

One of the fields within STYLE B will be a drop down list of all the article STYLE A's that this specific user has created. The user can then select one of the STYLE A's from the list.

I've tried using the reference and the entity reference modules but I can't quite get it. I've been able to create the reference field so that there is a dropdown of all STYLE A articles but these are not limited to that specific user.

Could anybody help me out. I've tried reading articles on relationships in views etc but it's not quite making sense.

thanks

# Answer
> 1 votes
some time ago, I created something similar. A drop down box (client profile) for the current user only - i.e. when creating a content type, the user would be able to choose a client profile, but only from a list of client profiles THEY authored.

I accomplished this using the following:

* using a custom Node Reference Module, I created a field on the content type that used the node reference as a drop down box
* added the following to the .module file, around line 878:

global $user;

if($user-\>uid != '1') $query-\>condition('n.uid', $user-\>uid, '=');

This creates a condition on the sql query that if the user isn't 1 (admin) it references the user id of the node creator, relative to the current logged in user, while Admin can override

If you going to go with this approach, be sure to rename the files and module into a CUSTOM module (I renamed mine custom\_node\_reference for simplicity).

# Answer
> 1 votes
Install the entity reference module.

Create a view of Content of type STYLE A. Do not create a page or a block, just the base view. Add a Entity Reference Display to the view (click on +Add next to Master at the top). Make sure that in fields Title is displayed. Click on format settings, and select Title as the search field. Make sure you have no pager and are displaying all content. Add a Contextual filter of Content: Author uid, and in the top section of its config page under WHEN THE FILTER VALUE IS NOT AVAILABLE, select provide default value -\> User Id from logged in user. This will ensure that you filter your results by the author of content of STYLE A, which is the user looking at the page.

Add an entity reference field to STYLE B. The target type must be Node, and in entity selection, Mode, select Views:Filter by an entity reference view. Then Select your view that you created above. It has a view argument input box, you can ignore that as we provided a default argument in the view, but if you need something more advanced in the future, you can look at this which will allow context to be passed in as tokens.

When you now create content of STYLE B it will have a box in which you can type titles, and it will search for content of TYPE A containing the search letters in its title, and authored by the person who is creating the new content of STYLE B.

Avoid using a drop down list at all costs as this might lead to performance issues

# Answer
> 0 votes
Have you managed to create this reference field manually or by using the References module ? If you custom built it, you can easily check `uid` of the node with the current logged in user, before this node `title` can gets populated in your drop down in STYLE B.

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


# Question
Title: How to trim the beginning of a field (reverse trim)?
In Views and several field formatting modules you are given the ability to trim the end of text fields to show for example only the first 100 characters. However what if I want to do the reverse. What if I want to trim a field to **not** show the first 100 characters but to show everything else, how could I do this?

# Answer
> 1 votes
The right way would be to write your own view field plugin.

The quick way is as follows: I assume your text field is the main body field. Install views\_php. In your view hide the text field. Add a Global PHP field. Make sure it is after the text field. In its output code put the following:

```
<?php print substr($data->field_body[0]['rendered']['#markup'], 100);?>

```

In Rewrite Results strip out HTML tags. As you are truncating text you will run into problems with unmatched tags, so you have to do this. Also, this sanitises the text. If you do not do this you have to run check\_markup in the php.

Also, this is not the preferred way to output a field. The correct way is to use field\_view\_field.

And if your field is anything other than the body, then install devel module, and include this PHP snippet in the output code of the PHP field.

```
<?php print dsm($data);?>

```

This will help with getting the right field.

---
Tags: views
---


title: CKEditor does not work

text:
# Question
Title: CKEditor does not work
The ckeditor on my site suddenly stopped working without changing anything.

This is what I tried up to now:

* update all other modules and drupal core
* remove ckeditor
* clear caches of drupal and browser
* download the latest drupal ckeditor module
* download the latest ckeditor full version and copy it in ckeditor/ckeditor
* copy all to modules/ckeditor
* check if ckeditor.config.js is their.
* turn module on
* check status report -\> no error
* set permission -\> admin -\> full html

PROBLEM: ckeditor is not showing nor is its configuration (admin/config/content/ckeditor).

\**extra info\* jquery version 1.7 using the default compression level production jQuery and jQuery UI CDN none\*

Non of the answers found on this site concerning this subject has been of help yet. I tried using firefox and chrome.

Thanks in advance.

# Answer
You have done everything I would have done.

Try a different path to ckeditor library. Install the libraries module and put the ckeditor library under libraries/ckeditor/ckeditor.js.

Try uninstalling the Drupal CKEditor module and go with the WYSIWYG module and see if that helps.

Also, try with different versions of jQuery. Sometimes the newer versions (1.9+) conflict with a lot of modules, though 1.7 which you are using is the sweet spot I have found.

And lastly try with an older version of CKEditor plugin.
> 0 votes

# Answer
1- See in libraries folder and check Ckeditor library.

2- With firebug see consule tab for javascript errors and fix them.

3- Config Ckeditor in drupal.

-- config permissions.

-- Config profiles use from Ckeditor in this path: admin/config/content/ckeditor

-- Text format of Editor: - plain text. - full html or filtered html when create content.

See this links:

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

Ckeditor doesn't work
> 0 votes

---
Tags: 7, wysiwyg
---