# Question
Title: Pathauto URL alias Node taxonomy term translation
How can i get pathalias to get the translated taxonomy term for the path alias?

The pattern:

\[node:field\_glp\_product\_types\]-\[node:field\_glp\_address:city:?\]

\[node:field\_glp\_product\_types\] is a taxonomy reference field.

The following tokens are available, but only the node:field\_glp\_product\_types token gives output, but not translated.

# Answer
> 0 votes
That is a bit complicated and is not possible with the normal translation methods.

You will need to use Entity Translation Module and Title module

Once you have the above modules configured you should have an option to include translated token for all the entities.

---
Tags: nodes, taxonomy-terms, i18n-l10n, path-aliases
---


# Question
Title: Pathauto taxonomy term alias for content paths
I am trying to make my nodes URL aliases use taxonomy term aliases through Pathauto, but I cant seem to figure it out if there is an alternative.

For example, I am trying to use questions/\[term:url:alias\]/\[node:title\], but I am getting an error because taxonomies are not in content patterns.

# Answer
Pathauto taxonomy terms in content paths
there is a comment to the answer on this post that links to a drupal.org issue.

http://drupal.org/node/741914#comment-3714746 This is a patch for Token. It seems to be for an older version than the latest beta I've got installed... So I had to hand apply the patch to token.tokens.inc "by hand".

It gave me taxonomy for content paths. stuff like \[node:term\], \[node:term:tid\], \[node:Term:vocabulary\], etc.

I don't have files in front of me atm but I will post the token.tokens.inc later if need be. (would post the text, but it's more than the limit for a post here)

Token.tokens.inc \- 7.x-1.0-beta
> 1 votes

# Answer
You can do that using Entity Translation Module and Title module

Once you have the above modules configured you should have an option to include translated token for all the entities.
> 0 votes

---
Tags: taxonomy-terms, path-aliases
---


# Question
Title: Re-import nodes daily using feeds and hook_cron
My requirement is to import nodes daily night after deleting all the contents in that node type.

I enabled the cron settings in feeds module as 1 day and tried to write hook\_cron() to delete all nodes.

```
function my_module_cron() {
  $results = db_select('node', 'n')
              ->fields('n', array('nid'))
              ->condition('type', 'ars', '=')
              ->execute()
              ->fetchCol();
  if (!empty($results)) {
    node_delete_multiple($results);
  }
}

```

But the doesn't seems to be deleted. I think this might be because of the user access problem.

I also want to know will the delete occurs before re-importing. How to order the cron jobs or shall I run the import via code after deleting the nodes.

# Answer
There is no need to do that manually.

Under `Settings for Node Processor` just select `Replace Existing Nodes.`

For further details you can check https://www.ostraining.com/blog/drupal/feeds/ which explains the steps in detail.

There is a field called GUID. Make sure that you set it to an appropriate value so that nodes will be updated(deleted and reimported). If the GUID in your site matches to that of the import then current nodes will be deleted(irrespective of whether they were created manually or imported) and the nodes from your news source will be reimported.
> 0 votes

---
Tags: 7, feeds, cron
---


# Question
Title: How to select an address field city from dropdown list?
I am using Address field module to populate address. A requirement needs to limit cities to a particular set, and also countries to particular set too. so I would like to present a set of cities in drop down list based on country selection. From the answer here I could figure out that something has to be done in plugins but I could not figure out what exactly. If anyone has sample code for city drop down in Address Field modules's plugins it would be of great help!

# Answer
Consider using the Select (or other) module. Here is an excerpt about it from its project page.

> Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

So basically you could "start" from a few cities (City 1, City 2, City 3), and whenever somebody needs another one (not in the list yet), they just enter "City 4". Here is a sample about it (just replace "Option" by "City" to get the idea):
> 1 votes

---
Tags: 7, navigation, entities, taxonomy-terms
---


# Question
Title: Is it possible to use features or some other technique to compare two sites?
I have a virgin copy of Open Outreach running alongside a copy where I've made configuration changes such as site name and configurations of various modules. Is it possible to use Features or some other technique to discover and document changes I've made?

# Answer
> 1 votes
If you are using Drupal 8, yes you can. But if you are using Drupal 7 I doubt you can yet do it. There is a backport of Configuration Manager to Drupal 7, which might make it possible.

The reason I said you can't do it in Drupal 7 is that the settings are saved in database and it is very difficult to make a comparison of the databases for settings. So if you have already made the changes and don't have a log, I would suggest exporting individual features using Features Suit of Modules.

You can checkout my presentation http://www.slideshare.net/gokulnk/features-15841090 for related Features modules which will make your work easier.

As a suggestion next time you want to keep a journal of your configuration changes please use Journal Module which should serve you well to keep track and document your changes.

---
Tags: features
---


# Question
Title: How to install a specific version of a project with drush
I observed that by default "drush dl module\_name" installs the latest version possible may it be dev version available.

How can we install a specific version of a project with Drush?

# Answer
To download a specific version of a project, specify the '*project name*', followed by a dash, then the version name. The -y argument answers "yes" to any and all prompts.

The exact '*project name*' for a module, is what is included in the URL of the module on D.O., i.e. everything following the last '/' in the URL. So for the Organic Groups module, that would be `og`, because its URL is `https://www.drupal.org/project/og`.

As an example, consider something like this:

```
drush dl og-7.x-1.3

```

With this command, you download the Organic groups module (replace it with your "module\_name"), and more specifically the 7.x-1.3 version of it (replace it with the "version" you want).

You can also specify a development version of a module, as in this exmple (which would download the current 7.x-2.x-dev version of Organic Groups):

```
drush dl og-7.x-2.x

```

For many more details, samples, etc, refer to http://www.drushcommands.com/drush-6x/pm/pm-download and/or http://www.drushcommands.com/drush-7x/pm/pm-download. Or to Installing a specific version of a project with drush.

After you downloaded the specific version, you "enable" the module as per the normal Drupal procedures to do so.

If you want to also enable the module using Drush, then there is no more need to specify the version of the module. To continue the above example, to enable the 7.x-1.3 version of it (after you down;oaded it), use a command like so:

```
drush en og

```
> 8 votes

# Answer
If you don't know the specific version that you want to download, you can use the `--select` option, and Drush will prompt you with all of the most recent available versions:

`drush dl devel --select`

Add the `--all` option for a comprehensive list.

You can also see this list without downloading via `drush pm-releases devel`.
> 5 votes

---
Tags: drush
---


# Question
Title: How to use db_select and apply a condition for another table's data?
I know this is probably the dumbest question ever but I'm just not getting warm with SQL.

I am writing this function which loads all users that have a role assigned:

```
function mymodule_get_users_by_role($rolename) {
  $role = user_role_load_by_name($rolename);
  $uids = db_select('users_roles', 'ur')
      ->fields('ur', array('uid'))
      ->condition('ur.rid', $role->rid, '=')
      // ->leftJoin('users', 'us', '(us.uid = ur.uid AND us.status = 1)')
      ->execute()
      ->fetchCol();
  return user_load_multiple($uids);
}

```

But I only want those users which's `status = 1`. I could do it afterwards but I really hope there is a way within the QuerySelect to add this filter beforehands. The commented line just produces a white screen of death so I'ma go with a nope. I dont even know if leftJoin is the right thing to do.

Thanks!

# Answer
The following query should be self-explanatory.

```
$query=db_select('table1','t1');
$query->join('table2','t2','t1.nid = t2.nid');

$query->condition('t1.uid','1')
      ->condition('t2.uid','3')
      ->fields('t1',array('uid','nid'))
      ->fields('t2',array('date'));

```
> 2 votes

---
Tags: 7, database
---


# Question
Title: A question about performance with Form API and Ajax callbacks
Im creating a dynamic form, using FORM API. Several lines of results, fetched from DB, and several functionnalities like deleting a row, adding a row, modifying quantites and calculating total prices.

I did everything using ajax callback, but Im not sure this is the best way of doing it, especially with the 'change quantities' and 'calculating prices' functionnalities.

What I understand about AJAX Callbacks is that a full refresh of the form is done during callback (using cache if possible), and that alony a certain part of the form is returned (using `return $form[XXXX]`).

So when I change a quantity input field, the form is rebuild, and Im updating the price col and total.

The question im asking to myself is : should I use simple javascript to manage my prices when quantities change ? For me its seems more logical, avoiding by the way useless PHP requests.

As Im not sure about it, likely to forget something important, I prefer asking it to you guys. Thx !

# Answer
> 1 votes
I build such a dynamic form recently and asked me the same question. I did go with the Drupal-way and only used the Form API with zero lines of custom JavaScript. In general you have to weigh the pros and cons of server-side vs. client-side processing. For me these are:

**Form API approach**

* (+) No custom JavaScript/jQuery code neccessary.
* (+) You have the full power of the Form API including validation and storing of data inside `$form_state` (This was one of the main reasons for me since I was using this inside a multi-step form).
* (+) Logic stays on the server. You probably need some server-side functions or do not want to expose your logic to everyone.
* (-) It will be slower then a JS approach (depends on your server's performance).

**JavaScript approach**

* (+) Fast. Since you do all processing on the client, you can update values instantly.
* (+) May be easier to implement. It can be more straight-forward since you don't need any deep Form API knowledge.
* (-) You have to fiddle around with jQuery selectors to somehow pass data to Drupal (maybe using hidden fields). This is not always nice and things can break if the HTML structure changes.

Normally I would prefer a JavaScript approach since the user experience can be much better. But in my recent case I really liked it to not have to write any custom JS code and let Drupal handle all the AJAX stuff. I was really impressed by the capabilities of the Form API.

---
Tags: forms
---


# Question
Title: Multiple field value amount based on role
I am looking to add a single image field to a content type, and allow a different amount of images based on a users role.

* Business Free User can upload 1 image (as profile pic)
* Business Silver User can upload 3 images
* Business Gold Users can upload 9 images

I've been searching high and low for a module to swoop in and save the day, but im not having much luck. Has anyone found something that can do this for me?

I'm using the field permissions modules to hide fields based on role. The fall back here would be to have 3 images fields, one for logo, one for 2 more images (to make 3) and one for 6 more images (to make 9) but I'm building a pretty big site here and would like to reduce the amount of fields where I can.

# Answer
> 0 votes
I would take a look at this question: Specific number of values in field setting per role. The hook\_form\_alter method is the way I would approach it.

---
Tags: users, entities
---


# Question
Title: how to add color field after Commerce Fancy Attributes has been installed?
In my website I used drupal commerce, and I would like to display product my its color in product display page. This is the link I reference https://www.drupal.org/project/commerce\_fancy\_attributes, I have successfully installed that module. That guide said create a 'Color' vocabulary, add a text field called "Color" that will hold hex values. But I can't find the 'hex' in field type. So I can't continue the next step. I would appreciate any suggestion you could give me.

Thanks

# Answer
You should create a simple "text field".
> 0 votes

---
Tags: commerce
---


title: Add class to image field

text:
# Question
Title: Add class to image field
I'm looking for a way to add a class field to Drupal's image field (field\_image). At the moment my images are displayed using code like this:

```
<img alt="Alternate text here" src="/path/to/image" />

```

I'd like to add a class field so that the code would be like so:

```
<img alt="Alternate text here" class="portrait floatLeft" src="/path/to/image" />

```

I think I could achieve this by adding a field to the content type to store the class name - I could then use views to add the class value to the image's parent DIV. However, I suspect there's a way to add a class field to the image field itself - it's not uncommon for images to have classes ;)

I've tried the File Entity module, which according to the documentation allows you to create custom file types. Sadly it doesn't explain how.

Any pointers / suggestions would be much appreciated.

**Edit:** To clarify, I'd like to be able to add classes on a per image basis. Some images might need the classes *portrait floatLeft*, others might need *landscape floatNone* and so forth.

# Answer
> 1 votes
Consider looking at the Image Class module, which extends the Image formatter by adding an option to add an element class.

It requires the Field formatter settings module (dependency).

---
Tags: 7, media
---


# Question
Title: Using Rules to create an Entity Reference if two fields in different entities match?
I'm attempting to use a "registration code" entered during a user's registration to create an entity reference to a node with a corresponding code.

Any help is greatly appreciated.

Specific use case:

"Professor" (users) have "Classes" (nodes) that contain a text-field with a unique 5-digit code (created with Computed Field).

"Students" have a "Registration Code" field on their registration & user profile page (aka a text field on the user entity) for manually entering a 5-digit code that should "assign" them to a "Class" that has the same registration code.

I'm not a programmer, but this might make more sense:

**if** \[*Student user's 5-digit registration code*\] **=** \[*"Class" node's 5-digit registration code*\] **then** an entity reference is created between \[*student user*\] and \[*"class" node*\]

I'd like the rule to trigger when a user updates the registration code field.

Essentially, I'm attempting to avoid displaying Entity Reference's autocomplete widget to users.

# Answer
I don't think I would start with Rules, especially from a performance standpoint. I would first try something like this:

* in the Student content type, create an Entity Reference field for the reference, making sure it has a default value, say 0 for ease of access later
* Using Field Permissions, hide that field to everyone but admin

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

* create a custom module
* using hook\_node\_validate(), check the list of Classes for the existence of the correct code
* using hook\_node\_presave(), update the hidden reference field once it is validated

Now you have something that allows the Student to enter a value, have it validated, and then copy that value into a proper reference field for later use

**EDIT**

I was curious if I was correct in my initial answer, so I figured it out to check, and it worked - for this example:

* Create a content type Class, using the title field as the Class Code
* Create a content type Student
* Add field to Student content type: `field_student_class_code`, entity reference to Class content type
* use Field Permissions to hide `field_student_class_code` to everyone but Admin
* Add field to Student content type: `field_student_visible_class_code`, text field
* Create a new module called custom\_node\_reference, and include this code:

```
function custom_node_reference_node_validate($node, $form, &$form_state)
{
  if($node->type == 'student')
  {
    $lang = $form['field_student_visible_class_code']['#language'];
    $class_value = check_plain($form['field_student_visible_class_code'][$lang][0]['value']['#value']);

    $result = db_select('node', 'table_alias')
        ->condition('type', 'class', '=')
        ->condition('title', $class_value, '=')
        ->fields('table_alias')
        ->execute();

    if($result->rowCount() <= 0)
    {
      form_set_error('field_student_visible_class_code', 'That class code does not exist, please re-enter a valid class code');
    }
  }
}

function custom_node_reference_node_presave($node)
{
  if($node->type == 'student')
  {
    $lang = $node->language;

    // get entity_id for current class code
    $val = db_select('node', 'n')
      ->fields('n', array('nid'))
      ->condition('type', 'class', '=')
      ->condition('title', $node->field_student_visible_class_code[$lang][0]['value'], '=')
      ->execute()
      ->fetchField();

      $node->field_student_class_code[$lang][0]['target_id'] = $val;
    }
  }

```

If you change the machine names of the fields, you will need to adjust the code to suit
> 0 votes

---
Tags: rules, entities
---


# Question
Title: Is there an easy way to serve low quality images for low-bandwidth users?
I'm designing a site that wants to use lots of images, but while some users will be on broadband, other user groups will be on dial up or similar.

Is there some trick/module that can serve lower quality images based on a cookie, for example?

I guess I'm thinking perhaps a parallel set of image styles that uses a lower quality (these could be provided by image style quality module) and something that detects when one style is requested and switches it for the lower quality version?

Long shot asking for a technical solution to a design-based problem, but thought I'd ask in case anyone else has come upon this problem.

# Answer
> 0 votes
I don't know that there's a way to determine benchmark throughput performance on the fly without wasting a lot of the users time running a test, on every login. You could do something like:

* add a field to the user profile that the user can change which dictates the speed they use
* use a custom style or set of styles for all images
* create a custom module to override hook\_image\_styles\_alter() to adjust (if necessary, based on the user field value) the style to suit

> This hook allows modules to modify, add, or remove image styles. This may be useful to modify default styles provided by other modules or enforce that a specific effect is always enabled on a style. Note that modifications to these styles may negatively affect the user experience, such as if an effect is added to a style through this hook, the user may attempt to remove the effect but it will be immediately be re-added.

This way the user can determine which speed they are using, and the system should adjust the images on all subsequent logins to fit their choice

---
Tags: 7, media
---


title: Allowing a user to edit ONE view

text:
# Question
Title: Allowing a user to edit ONE view
I have a staff member that needs to be able to update a View in the drupal admin area...specifically they need to be able to change the node id displaying in a block.

Is there a way to allow this person to edit just this view?

And if that's not possible what permission do I need to give them?

Thanks!

# Answer
I don't know that that's possible as described, but you could do something like this:

* create a content type with only one field, accessible to the staff member
* add an entity reference to the content type housed in the view

> Provides a field type that can reference arbitrary entities

* create a relationship to the staff member content type

This would allow the Staff member to change the value in the content to which they have access, which would affect the View, but not directly have admin access to the View or the Admin sections of the Views UI
> 1 votes

---
Tags: views
---


# Question
Title: Remove inline JS from specific page type?
This is an answer how to unset js from specific page types: https://stackoverflow.com/questions/10138660/how-to-remove-css-and-js-from-a-certain-content-type-in-drupal-7 And I've made it for Syntax Highlighter module's js:

```
function tlito_theme_js_alter(&$js) {
  if (arg(0) != 'node') {
    unset($js['sites/all/libraries/syntaxhighlighter/scripts/shCore.js']);
    unset($js['sites/all/libraries/syntaxhighlighter/scripts/shAutoloader.js']);
    unset($js['sites/all/modules/syntaxhighlighter/syntaxhighlighter.min.js']);
    unset($js['images/syntaxhighlighter.autoloader.js']);
  }
}

```

And everything is ok but also module adds inline JS that gives error on pages where js ar removed. Inline js is this:

```
<script type="text/javascript">
<!--//--><![CDATA[//><!--
SyntaxHighlighter.defaults.toolbar = false;
//--><!]]>
</script>

```

**How can I remove inline js from $scripts in my template.php ?**

# Answer
> 1 votes
Put this inside tlito\_theme\_js\_alter().

```
foreach ($js as $key => $value) {
  // Skip if data is not a string or is not inline.
  if (!is_string($value['data']) || $value['type'] !== 'inline') {
    continue;
  }
  // Remove SyntaxHighlighter.defaults.toolbar inline js.
  if (strpos($value['data'], 'SyntaxHighlighter.defaults.toolbar') !== FALSE) {
    // Remove from the js array & exit loop.
    unset($js[$key]);
    break;
  }
}

```

---
Tags: javascript
---


title: Stop autosubmit on textfield

text:
# Question
Title: Stop autosubmit on textfield
I have tree element exposed on a View, two Select Box and a custom filter (textfield). I set up the View for Autosubmit (Automatically submit the form once an element is changed). For the two Select Box is OK but for the textfield is a problem because the page is submitting after every key up.

There is any options to do the textfiel stop the autosubmit behaviour on Drupal 7?

# Answer
> 3 votes
Views depends of ctools and this is the cause of autosubmit.

On do: https://www.drupal.org/node/1735254

This is the feature what I need.

> If you want to exclude a field from the ctool-auto-submit-full-form auto submission, add the class ctools-auto-submit-exclude to the form element. With FAPI, add:
>
> ```
> '#attributes' => array('class' => array('ctools-auto-submit-exclude')),
>
> ```

# Answer
> 0 votes
I don't believe that you can do this through an existing Drupal configuration but it would be fairly simple to do with jQuery or JS.

**Remove the existing keyup event:**

```
$('.textfield').unbind('keyup');

```

**Modify it to submit on enter key instead:**

```
$('.textfield').keypress(function(e) {
  if (e.which == 13) {
    $('.your-filter-form').submit();
    return false;
  }
});

```

---
Tags: 7, views
---


# Question
Title: When using Entity Translation and the Title module, how can I get the translated term from the term ID programmatically?
I have a term ID and I want to programmatically get the translated term name (via Entity Translation and the Title module) for the logged-in user's language. How can I do this?

This similar question asks about how to get the translated name programmatically when using i18n taxonomy translation (the other major approach besides Entity Translation).

# Answer
The proper way to do this without circumventing the core API would be:

```
$tid = 322; // put here your term id
$term = taxonomy_term_load($tid);
$langcode = $GLOBALS['user']->language;
$translated_term = $term->name_field[$langcode][0]['value'];

```
> 1 votes

# Answer
I resolved using this module that extends EntityFieldQuery

After installing it, you are able to extend EntityFieldQuery in the following way:

```
global $language;

$langcode = $language->language; // current site language
$tid = 322; // put here your term id

$query = new EntityFieldQueryExtraFields();
$query->entityCondition('entity_type', 'taxonomy_term')
      ->entityCondition('bundle', 'your_vocabulary_machine_name')
      ->entityCondition('entity_id', $tid, '=')
      ->addExtraField('name_field', 'value', 'value')
      ->fieldLanguageCondition('name_field', $langcode, '=');

$results = $query->execute();

if (isset($results['taxonomy_term'])) {
  $translated_term = $results['taxonomy_term'][$tid]->extraFields->name_field_value;
  // do what you want with $translated_term
}

```

Hope this help.

MXT
> 0 votes

# Answer
@plach's answer should technically work, but it has two problems:

1. It unnecessarily handles the language.
2. It's using an unsafe value, which is a security risk.

I recommend to instead use field\_get\_items() along with the safe value.

```
$term = taxonomy_term_load($tid);
$titles = field_get_items('taxonomy_term', $term, 'name_field');
if (!is_array($titles) || !isset($titles[0]) || !isset($titles[0]['safe_value'])) {
  $term_translated = 'Invalid or untranslated taxonomy term / tag!';
}
$term_translated = $titles[0]['safe_value'];

```
> 0 votes

---
Tags: taxonomy-terms, i18n-l10n
---


# Question
Title: Calling Jquery function from link onClick attribute
I'm trying to call a jQuery function from a link's onClick attribute but I get the following error: Uncaught TypeError: Drupal.behaviors.main.test is not a function.

I created a simple module that will create a block displaying a list of events. The block template will output the following HTML code:

```
<ul id="events">
    <li><a href="#" onclick="Drupal.behaviors.main.test(1)">Event1</a></li>
    <li><a href="#" onclick="Drupal.behaviors.main.test(2)">Event2</a></li>
</ul>

```

Each link has a onClick attribute calling Drupal.behaviors.main.test($id).

On my theme's info file, I include a test.js file with the following code:

```
(function ($) {
    Drupal.behaviors.main = {

        attach: function(context, settings) {

            $(function test() {
                console.log('yo')
            });

            $('#home').slick({
             //init slick
            });

       }
    }
})(jQuery);

```

When the document is ready, slick plugin is well initialized and test() is called so I get 'yo' on the console. It's when I click the links that I get the error, so I'm thinking about a scope problem since the function is called from a module but is defined on my theme. Does anyone have any idea?

Thanks in advance!

--EDIT-- Thank to rémy, I managed to resolve my issue, here's what I did: My block outputs the following HTML:

```
<ul id="events">
    <li>
        <a href="#" id="1" class="whatever">Event1</a>
    </li>
    <li>
        <a href="#" id="2" class="whatever">Event2</a>
    </li>
</ul>

```

And on my test.js file:

```
(function ($) {
    Drupal.behaviors.main = {

        attach: function(context, settings) {

            $('.whatever').click(function() {
              console.log(this.id);
            });

            $('#home').slick({
             //init slick
            });

       }
    }
})(jQuery);

```

# Answer
use an id on your anchors, no onclick:

```
<li><a href="#" id="whatever">Event2</a></li>

```

then use the click event on it in the behavoir:

```
(function ($) {
    Drupal.behaviors.someClicks = {
        attach: function(context, settings) {
            $('#whatever').click(function() {
               console.log('vamoooh');
            });
       }
    }
})(jQuery);

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How to resolve my Fatal Error after uninstalling Views Chart Tools and Google Chart Tools
I'm getting the below Fatal Error after I uninstalled the Views Chart Tools and the Google Chart Tools modules.

> Fatal error: views\_plugin\_display::destroy(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "views\_chart\_tools\_plugin\_display\_dashboard" of the object you are trying to operate on was loaded *before* unserialize() gets called or provide a \__autoload() function to load the class definition in /home/XXXX/XXXX/sites/all/modules/views/plugins/views\_plugin\_display.inc on line 272

I was working with them but they did not serve my purpose. After uninstalling them I started getting the above error.

I can't clear cache or even view the block admin page. Can anyone tell me what I can do to resolve this?

# Answer
> 0 votes
I would use Drush to clear the cache. If the cache still will not clear, do a registry rebuild.

If after all that you still have the error, use Drush to enable, disable and uninstall the module again. Sometimes a full cycle can clean up gremlins like this.

# Answer
> 1 votes
SOLVED - Used phpMyadmin and selected all cache tables then using the Empty option from the dropdown performed TRUNCATE on all cache fields. At this point cleared the cache that was throwing the error.

---
Tags: views, charts
---


# Question
Title: Authenticated users must be able to flag webform submissions
Authenticated users must be able to flag webform submissions.

How can I make this work?

# Answer
Navigate to `/admin/structure/flags/add/node` and create a flag (do not check the "global" checkbox). For "Bundles" (on the same form, check "webform").

On that same form, review any of the various other options available to define/refine the flag to be created, such as: \- Flag Access, \- Display options, \- Link type, \- Etc.

Then use the "Save Flag" button.

A few other questions that may help to get you going (which are like variations of this question):

**Note**: The Webform Flag Submissions sandbox is for D6 only (I'm assuming this question is about D7, is it?).
> 0 votes

# Answer
There is a sandbox project Webform Flag Submission that you can probably use as a starting point
> 0 votes

# Answer
Thank you for your reactions.

Yes, this is indeed a question for D7.

Also: I in fact can make a flag-link in a table to flag the user. But I want the authenticated users to be able to view the webform submission and make a flag-possibility on that page (the page that the user gets when he watches the webform).
> 0 votes

---
Tags: webforms, forms, flags, users
---


title: Update a record in custom module

text:
# Question
Title: Update a record in custom module
I've read several custom module tutorials but none seem to show how to edit a record. My module does not use node but has a custom table. So, I think I ought to be able to drupal\_get\_form and populate the #value with the fields. But to set up the menu to get the parameter in the URL and my page callback is not working.

Looking around I found this answer and modeled the below after it but I get a default page instead of my expected form.

```
$items['redashboard/project/%/edit'] = array(
  'title' => (t('Edit project')),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('re_dashboard_edit_project_form', 2),
  'access callback' => TRUE,
);

function re_dashboard_edit_project_form($form, $form_state, $projectid) {
  $project = pull_project($projectid);
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Research Project Name/Question'),
    '#value' => $project->projectName,
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Create',
  );
  return $form;
}

function pull_project($projectid) {
  $query = db_select('Projects', 'p');
  $query->fields('p', array('ProjectID', 'residentID', 'projectName', 'projectMentor', 'projectStatus', 'citation', 'lastUpdated'));
  $query->condition('ProjectID', $projectid);
  $result = $query->execute();
  return $result->fetch();
}

```

So, how should I set up a page to edit this record if not this way? Or to the point how should I set up the menu so that this callback gets rendered? thx, sam

# Answer
The `$items['redashboard/project/%/edit']` declaration needs to be made inside of `re_dashboard_menu()`, and there needs to be a `re_dashboard_edit_project_form_submit()` function to pipe `$form_state['values']` into `db_update()`.

Other than that, it looks like it will get the job done. You could use `db_query()` instead of `db_select()`, since it's faster, and the query conditions are static. Also, make sure you have a way to handle `db_select()` not returning any results, since `fetch()` will return `FALSE` in that case.
> 1 votes

---
Tags: 7
---


# Question
Title: Using Entity reference + Views to create members select list
How can I use VIEWS + ENTITY REFERENCE to get list of active members specific to the CURRENT GROUP \[created via organic groups\].

I have created a view that list active members belonging to the group.

I have seen Restricting selectable entities with Views

But my question is, that is it possible with entity reference too ?

If yes how can I achieve this case ?

# Answer
The view will need to know which group, which means a Context Filter. So options there are usually the current url or the current signed in user. Depending on where your entity reference is, and how you are getting to it, there might be a context available to fill your filter. Then the view will be usable to limit the options in your reference field. The more details you can provide about the use case, the better I can make this answer.
> 0 votes

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


# Question
Title: Why is the recommended release of my module not proposed in Drupal updates?
For my contributed module I've previously published several releases without any issue.

Most recent releases were successively `7.x-2.0rc2` then `7.x-2.0` and `7.x-2.1`.

As of `7.x-2.1` the following happens:

* for all Drupal sites having this module installed with an older release, the `admin/reports/updates` list doesn't mention the newest release (even after refreshing):
+ for a site currently in `7.x-2.0rc2` it proposes `7x-2.0`
    + for a site currently in `7.x-2.0` it tells it's up to date
* (may be not related but) simultaneously I noticed that the git repository summary doesn't show the labels for the tags corresponding to the 2 new releases, in its **Age** list

However at the same time:

* the project page shows the right last release in **Recommended releases** (and downloading it gives the right content too)
* the git repository summary shows the involved releases in its **Tag** list

BTW I noticed that some other older releases are also shown in **Tag** list while missing in **Age** list, so the git behaviour might not be relevant for this issue

Anynay keep wondering why the recommended release of my module is not proposed in Drupal updates?

# Answer
> 2 votes
Immediately after posting my question, I'd pushed a new `7.x-2.2` release, and it didn't change anything: all involved sites keeped reporting `7.x-2.0` as the most recent release.

But today I noticed that it suddenly changed (without any intervention in `git` nor in my module's page): now the sites correctly report `7.x-2.2` as the most recent release.

So I tend to think that the response to my question is merely: there is some *variable* latency in the way Drupal.org makes the information available for the `admin/reports/updates/check` page underlying mechanism to work.

Moreover it worth mention that also the `git` **Age** list now shows all release tags, while some of them were previously missing.

# Answer
> 1 votes
I just installed/enabled your 7.x-2.1 version of your module in a multilanguage D7 site (3 languages, 'en' is the default), in which I have never installed any earlier version of your module.

After doing so, I received a (red) Drupal error message (actually 2 identical ones) like so:

> Notice: Use of undefined constant \_MULBASE\_PATH - assumed '\_MULBASE\_PATH' in \_multilang\_install() (line 22 of .../sites/all/modules/multilang/multilang.data.inc).

And I also get an informational (green) message like so:

> NOTE: in order to use the advanced features available with CKEditor, you must install the Widget plugin.

The 'advanced features' in it is a hyperlink, pointing to `.../en/_MULBASE_PATH/en/admin/help/multilang#ckeditor`. Obviously following that link returns a page not found (because of the \_MULBASE\_PATH in it.

And within `admin/reports/updates` there is now (also) the yellow update message shown, from 7.x-2.1 to 7.x-2.0 (similar to your update messages).

Within `admin/reports/dblog`, there is now also a message like so:

> Warning: Invalid argument supplied for foreach() in multilang\_exit() (line 240 of .../sites/all/modules/multilang/multilang.module).

So could it be that it is somehow related to that **\_MULBASE\_PATH**, which I assume is a variable that has not receive an appropriate value yet?

Haven't done any other debugging or research so far, but I wouldn't be surprised if that could be what is causing your issue ...

PS: in the meantime I have discovered that, in the site where I did my experiment earlier today, my "module list" (at 'admin/modules') isn't working anymore (I'm using 'module filter' module also). When I visit that link, not even 1 module is shown anymore. Not sure yet if it is a memory issue (pretty sure it is not), because I added 1 more module. But since the only thing I did in this site today is my experiment with that 2.1-version of your module, I suspect that to be the culprit ... I can't even simply disable the module again by using the 'admin/modules' link (no modules are shown to enable/disable). So I'm planning to go edit the system table via PhpMyAdmin soon. I'll update my answer after I have more details on that.

---
Tags: 7, community-official-site
---


# Question
Title: Upgraded Drupal 7.37 to 7.38 using Drush and its not working. update needs a higher bootstrap level to run - Error
I am new to Drupal. I am reading a book called Definitive Guide to Drupal 7. I had installed Drush on Windows 7 with Git as well. It was working last week. Since 7.38 is released I tried to update my localhost website for this particular book and I am getting an error. I have googled this problem and I am coming up with some solutions but they are not working for me. I have navigated to the root folder of the Drupal installation in Git before using Drush Up. I have also changed the 'host' value in settings.php to '127.0.0.1'. It was 'localhost' before. I don't know how to fix this. Does anyone know?

```
Anthony@ANTHONY-PC ~
$ cd c:/wamp/www/definitiveguided7

Anthony@ANTHONY-PC /c/wamp/www/definitiveguided7 (master)
$ drush up
Command pm-update needs a higher bootstrap level to run - you will       [error]

need to invoke drush from a more functional Drupal environment to run
this command.
The drush command 'up' could not be executed.                            [error]

Drush was not able to start (bootstrap) the Drupal database.             [error]

Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.37
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  127.0.0.1
 Database port          :
 Database username      :  root
 Database name          :  definitiveguided7
 PHP executable         :  php
 PHP configuration      :  C:\wamp\bin\php\php5.5.12\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:\Users\Anthony\AppData\Roaming\Compose
                       r\vendor\drush\drush\drush.php
 Drush version          :  8.0-dev
 Drush temp directory   :  C:/Users/Anthony/AppData/Local/Temp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  C:\wamp\www\DefinitiveGuideD7
 Site path              :  sites/default

```

# Answer
Make sure your Drush commands are issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

So try navigating to the sites/default folder (assuming this is NOT a multi-site, is it?), and then retry your Drush comand ... Seems that is what is causing your problem ...

If that doesn't help, it could well be an issue with the version of Drush that you are using. Would it be an option to downgrade to a lower version of Drush? FYI: Drush 6.x does support D7 also ...
> 0 votes

# Answer
I got it working. I was able to update my local website to version 7.38. I did delete my drush directory and unzipped the download into a new directory and then I re-typed the environment variables. This time I used the "Copy address" command in the search browser to copy and paste the locations into the environment variables values so I didn't have any errors. Its working now. Thanks helping Pierre.
> 0 votes

---
Tags: drush
---


# Question
Title: Send an email when the roles are changed
I'm trying to send an email to users after their role has changed. So far, the rule is triggered every time the profile is saved (even without role change); I suspect that the data comparison is not handling the array correctly?!

Any help to improve the following rule or to achieve the same feature with a different condition will be very much appreciated.

```
{ "rules_role_changed" : {
    "LABEL" : "Role changed",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "NOT data_is" : { "data" : [ "account:roles" ], "value" : [ "account-unchanged:roles" ] } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "account:mail" ],
          "subject" : "Role change for [account:name-raw]"
        }
      }
    ]
  }
}

```

# Answer
To detect 'any' change to the users roles, you can use the following PHP via the condition "Use PHP code"

```
return (count(array_diff_key($account->roles, $account_unchanged->roles)) + count(array_diff_key($account_unchanged->roles, $account->roles))) <> 0;

```

The other PHP answers will not necessarily fire when a user has been 'removed' from a role.
> 0 votes

# Answer
You always need to check the state of both unchanged and changed account, something like this:

```
{ "rules_role_changed" : {
"LABEL" : "Role changed",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "user_update" : [] },
"IF" : [
  { "NOT user_has_role" : {
      "account" : [ "account-unchanged" ],
      "roles" : { "value" : { "4" : "4" } }
    }
  },
  { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
],
"DO" : [
  { "mail" : {
      "to" : "lorem",
      "subject" : "ipsum",
      "message" : "dolor",
      "language" : [ "" ]
    }
  }
]
}
}

```

What this does is it checks if the user had the role before it was saved, and if the role has been added on the update - this means that user did not have the role before but does have it now. Here is a screenshot of the config:
> -1 votes

# Answer
Thanks to this old revision of an answer to a similar question, I figured out that you can achieve the expected behaviour by comparing the array in plain php: https://drupal.stackexchange.com/revisions/52790/2

Select condition "Use PhP code" with e.g. the following snippet:

```
// keys only must be compared since values are different (!). testing using empty() produces an error, hence the comparison of count() to 0:
return count(array_diff_key($account->roles, $account_unchanged->roles)) <> 0;

```
> -1 votes

---
Tags: rules, users
---


# Question
Title: Add a module dependency to a sandboxed project
I am developing custom module which requires the use of the Entity Construction Kit (ECK) and the ECK Extend module. The problem is that the ECK Extend module is a sandboxed module.

I want to add the ECK Extend module as a dependency for my custom module.

How would one do this in the Drupal ecosystem? If I add the sandboxed module as a dependency, will drush recognise it and download it for me when I enable my custom module like drush would normally do with module dependencies?

# Answer
I am afraid that is not possible.

One dirt-fix would be to add the following in your info file.

```
dependencies[] = sandbox/mihai_brb/2254845

```

This will make sure that users will not be able to enable this module by default and cause issues. And then you can add the instructions in your module page and README.txt you can add the instructions about the dependencies and how to download them and then remove the line from the info file.

A better approach would be to use hook\_requirements and in `phase = "install"` you can check for the presence of a function that is present in the sandbox module. If that function is not present, you can block the module installation and show a message to the user to download the sandbox module and then try installing again.
> 1 votes

---
Tags: entities
---


# Question
Title: Why am I getting a PDO Exception error when I try to run Drupal Console inside the root directory?
I've installed Drupal Console and can confirm it is in the proper directory, etc.

I run the command "Drupal" from my home directory and I see a Drupal Console help list of commands, but when I run it inside my site root directory, I get a PDO Exception error. I can't figure this one out. Should I move Drupal Console into my Drupal site directory? Thanks for the help.

# Answer
> 3 votes
Try to update below in your `php.ini`. You need to define php for correct location for `.sock` file.

```
mysql.default_socket = /tmp/mysql.sock
mysqli.default_socket = /tmp/mysql.sock

```

**OR**

If you will not getting result then try to replace below in your `settings.php` file.

**Replace** `'host' => 'localhost'`,

**With** `'host' => '127.0.0.1'`,

---
Tags: 8
---


# Question
Title: Need to override page/meta title on views page
I have installed meta tag modules,then enable the meta:views mudule for meta tags. After that i have added meta tags from views interface. Now I need to override these value on the basis of exposed filter dropdown.I mean when i change filter,then meta values should be changed.

# Answer
> 1 votes
You can use hook\_metatag\_metatags\_view\_alter

```
/**
 * Implements hook_metatag_metatags_view_alter().
 */
 function mymodule_metatag_metatags_view_alter(&$output, $instance, $options) {
   if (isset($_GET['some_filter']) && $_GET['some_filter'] == 'some value') {
     $output['title']['#attached']['metatag_set_preprocess_variable'][0][2] = t('New meta title');
    $output['description']['#attached']['drupal_add_html_head'][0][0]['#value'] = t('New meta description');
   }
 }

```

---
Tags: 7, views, meta-tags
---


title: How to hide path location in drupal 7?

text:
# Question
Title: How to hide path location in drupal 7?
How to hide path file in drupal? Now it looks like this:

```
http://localhost/drupal/sites/default/files/document.pdf

```

I want to change to look something like this:

```
http://localhost/drupal/media/view.php?id=6445

```

# Answer
> 0 votes
It can be done by implementing custom menu callback

```
/**
 * Implementation of hook_menu()
 */
 function mymodule_menu() {
   $items['media/view/%file'] = array(
     'page callback' => 'mymodule_download_file',
     'page arguments' => array(2),
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );
   return $items;
}

/**
 * Page callback for a file to download
 */
 function mymodule_download_file($file) {
   if($file) {
    file_transfer($file->uri, array('Content-disposition', 'attachment; filename='.$file->filename));
   }
   else {
    return drupal_access_denied();
   }
 }

```

---
Tags: uri, files
---


# Question
Title: How to associate User data with custom module?
I'm thinking about a custom module where I need to save additional data (like user logs from other software, customer data, etc.) that'd go into a custom module user table.
How would I associate that with the user? Just the user ID?
Or is there anything else that I might want to save for uses that I might not yet know (Views, Domain Acess, Panels, Context, ...) or can I get all required data just be joining the UserID everywhere?

# Answer
As usual there are plenty of ways to do something with Drupal.
Of course it would be possible to create a content type and import it via Feeds but sometimes (in case it might become plenty of data) it could be better to use a different approach.

So far it seems I'd go with MongoDB, the appropriate module and get the data into the DB using JSON and try to relate that to the current user if or where needed. Due to the amount of data and the visualisation it seems to be better to go the Document DB way.
> 0 votes

---
Tags: users
---


# Question
Title: Webform: send uploaded files as attachments
> Hi i'm using SMTP module to send uploaded inforamation into mail using webforms.so i'm getting below information to my mail fine but in place of upload Your Cv link i need attachment .

## The following application was received from the website.

==Contact details== Title: demo1 First name: demo Surname / Family Name: demo Tel (Daytime): xxxxxxxxxx Email address: demo@gmail.com Currently living in: london Prepared to relocate: Yes

==Career choices== Job type: Permanent Current salary: 200 Min. salary required: 200 Were you referred by a friend? Upload your CV:http://xxxxx/system/files/webform/uploaded\_cvs/demoresume\_4.doc

This requirement cab be done using MIME module and Mail System but it's take more time to submit form.

Please help me i'm new to drupal.

Thanks in advance.

# Answer
* All sorted in the end with host entries on the server,I have updated host entries for sending email and added domain name as host entry then webform very fast to submited .it's works for me
> 0 votes

---
Tags: webforms, emails
---


# Question
Title: unable to get webform submissions into our mail
> I'm unable to get webform submissions data into my default mail,but when submitting form i have received mail.getting below Body in my mail

Submitted on

Submitted by user:

Submitted values are:

The results of this submission may be viewed at:

Above name's comming from webform-mail.tpl.php file in webform module

```
<?php print ($email['html'] ? '<p>' : '') . t('Submitted on [submission:date:long]'). ($email['html'] ? '</p>' : ''); ?>

<?php if ($user->uid): ?>
<?php print ($email['html'] ? '<p>' : '') . t('Submitted by user: [submission:user]') . ($email['html'] ? '</p>' : ''); ?>
<?php else: ?>
<?php print ($email['html'] ? '<p>' : '') . t('Submitted by anonymous user: [submission:ip-address]') . ($email['html'] ? '</p>' : ''); ?>
<?php endif; ?>

<?php print ($email['html'] ? '<p>' : '') . t('Submitted values are') . ':' . ($email['html'] ? '</p>' : ''); ?>

[submission:values]

<?php print ($email['html'] ? '<p>' : '') . t('The results of this submission may be viewed at:') . ($email['html'] ? '</p>' : '') ?>

<?php print ($email['html'] ? '<p>' : ''); ?>[submission:url]<?php print ($email['html'] ? '</p>' : ''); ?>

```

Please help me I'm new to drupal

# Answer
I have disabled all dependent modules for token and then disabled token module also again enabled all modules now working fine.
> 1 votes

---
Tags: webforms, emails
---


# Question
Title: How to solve the "No file was uploaded." when trying to use custom form field?
I get "No file uploaded" when I try to use a custom form in drupal .Below is the code which I have used to upload a file in drupal custom form.

```
    function mobiae_custom_purchase_order_form(&$form,&$form_state) {
      // Merge default values into the default array.
        $form = array();
          $form['#attributes']['enctype'] = 'multipart/form-data';

          $form['file'] = array(
            '#type' => 'file',
            '#title' => t('Image'),
            '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
          );

      return $form;
    }

function mobiae_custom_submit_form($payment_method, $pane_values, $checkout_pane, $order) {
  module_load_include('inc', 'mobiae_custom', 'mobiae_custom.purchase_order');
$form = array();
$form_state = array();
  // Default to a known test credit card number. For valid numbers of other card
  // types see: http://www.rimmkaufman.com/blog/credit-card-test-numbers/09112007/
//$form['#submit'][] = 'mobiae_custom_submit_form_validate';
  return mobiae_custom_purchase_order_form(&$form, &$form_state,$order);
}

/**
 * Payment method callback: submit form validation.
 */
function mobiae_custom_submit_form_validate($payment_method, $pane_form, $pane_values, $order, $form_parents = array()) {
  // Validate the credit card fields.file_save
 drupal_set_message('fgh');
 $file = file_save_upload('file', array(
      'file_validate_is_image' => array(),
      'file_validate_extensions' => array('png gif jpg jpeg'),
  ));

  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $pane_values['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }

//  module_load_include('inc', 'commerce_payment', 'includes/commerce_payment.credit_card');
  if (form_get_errors()){
    return false;
  }
}

```

# Answer
> 1 votes
For saving file u can use

```
    $form['test_picture']['file'] = array(
        '#type' => 'managed_file',
        '#title' => t('Test Picture'),
        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => variable_get('picture_upload_location'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('pdf'),
            'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
        ),
    );

```

---
Tags: 7, files
---


title: How do I catch 502 exceptions?

text:
# Question
Title: How do I catch 502 exceptions?
While running the batch process, it takes more than 5 hours to complete; before that, it returns a 502 error. How do I handle it?

# Answer
*HTTP 502 Bad Gateway* is, as its name says, something that happened on your gateway, not on your server. Since the error is between you and your server, Drupal can't really know it happened unless, of course, you are talking about a job that connects to a remote server and the error happens between your site and that remote server. If so, you can either ask admins to fix gateways, or file a bugreports: one to service provider, and the other to the author of the module you are using.
> 1 votes

---
Tags: 6
---


# Question
Title: How to update non-property value with entity_metadata_wrapper?
I wish to update values in commerce\_payment\_transaction entity. I am using such code:

```
<?php
$transaction = commerce_payment_transaction_load(58);
 $digests = array(
'DIGEST' => '456',
'DIGEST2' => '478'
);

$transaction_wrapper = entity_metadata_wrapper('commerce_payment_transaction', $transaction);
$transaction_wrapper->payload->set($digests);
$transaction_wrapper->field_my_custom_field->set(1458);
$transaction_wrapper->save();

```

The problem is, that such code throws me error, that payload is not property of commerce\_payment\_transaction entity. Although "payload" is column in database table of this entity type. But it is not set as property.

When I don't use entity\_metadata\_wrapper, this code works for me:

```
<?php
$transaction = commerce_payment_transaction_load(58);
$digests = array(
'DIGEST' => '456',
'DIGEST2' => '478'
);
$transaction->payload = $digests;
commerce_payment_transaction_save($transaction);
?>

```

But is it possible to use also entity\_metadata\_wrapper to update data of entity, that are neither properties nor fields, like payload in commerce\_payment\_transaction?

# Answer
> 0 votes
The `payload` column *is* a property of the commerce payment transaction type already (property is a Drupal core term for any base fields on an entity), but for whatever reason the authors of the module have chosen not to expose it to the Entity API module through `commerce_payment_entity_property_info()`.

Fortunately you can just use `hook_entity_property_info_alter()` in a custom module to provide the metadata on its behalf. See `hook_entity_property_info()` for details of the options available.

---
Tags: 7, commerce, entities
---


# Question
Title: How to sort in accordance to best match on the results returned by a views filter?
I have a search functionality which lets user search for people based on their names. To achieve this I am using a view with an exposed filter on the field and the operator being "Contains any word". Now I want to sort the results with the best matched result appearing first. Say I am searching "Amy Jackson", I get all the users with "Amy" first and then the results with "Jackson", thus Amy Jackson does not appear first.

# Answer
> 2 votes
You can do this if you have the core search module installed. For your filter use "Search terms" (exposed), and for sort use "Search score" (descending).

You'll be able to influence what factors are dominant in the ordering of results by adjusting the settings at admin/config/search/settings.

If you want more control over the ordering then it could be worth looking into the Search API module but setting this up is a lot more involved.

---
Tags: search, views
---


# Question
Title: how to filter nodes that match url of current node or particular field of current node
For my contenttype 'cars' i use a panel node-view.

Each 'car' node has fields 'categorie' and 'type' Each 'car' node has url 'categorie/type/model' e.g. 'car/toyota/yaris'

In my 'car' panel node-view i like to insert a view. This view should filter nodes that match the field 'type' or part of the url 'type'

Without succes i have tried to pass the node id as an argument from my view (master) to my panel. Then using node id as a contextual filter.

# Answer
> 0 votes
Ok managed to create a working view:

Under contextual filter: -Content: Has taxonomy term ID

Configured:

Provide default value - Type:

Taxonomy term from url - load default filter from term page (checked)

Specify validation criteria (checked)

Validator: taxonomy term (selected)

Check term in vocabulary list

Filter type: term name converted to term id (selected)

---
Tags: views, entities, uri
---


# Question
Title: Can I call menu_rebuild() only for one module or specific hook_menu?
Is there a way to call menu\_rebuild so it will only update items in selected module and / or hook\_menu ?

I need it to update links ( if they are already existing ) and add new ( if they are now ).

Don't want the menu\_rebuild to clear the menu\_router.

# Answer
I am afraid that's what the function does. From Drupal docs:

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

I guess you could try to reimplement the function into your own custom one and modify its source according to your needs. It looks like a lot of work though. You'd probably have to reimplement more functions.

Source: https://api.drupal.org/api/drupal/includes!menu.inc/function/menu\_rebuild/7
> 2 votes

---
Tags: 7, routes
---


# Question
Title: CSS aggregates generating but not loading (core and AdvAgg), but JS aggregates load fine
I'm trying to set up aggregation and compression on my site, but am having problems. When I enable aggregation, either through core or through AdvAgg, it seems that aggregates are being generated for both CSS/JS files when I check sites/default/files, but only the JS aggregates are actually being loaded. When I check my page sources, the browser is displaying all of the original CSS files as though an aggregate had not been generated/enabled. I'm running Omega and a sub-theme, if that's a possible issue. Any suggestions on what to try?

EDIT: As per my comment below, the only theme option I see relating to aggregation is "Rebuild CSS and JS aggregates on every page load", and checking/unchecking it doesn't seem to have any effect. I can't seem to find anything else relating to aggregation within the theme settings.

# Answer
It turns out that there is a "Development Extension" that is a part of the Omega theme settings. I had it enabled for a couple of the features it provides, but unchecking it caused the aggregates to start loading like normal. Guess having that enabled is what broke the aggregation. Hopefully this ends up helping somebody else eventually.
> 1 votes

---
Tags: 7, css-js-aggregation
---


# Question
Title: D7, AmazonS3, composer_manager and awssdk libraries understanding
I have been struggling with the installation of amazonS3. Although I was finally able to have it working pretty well, I would like to confirm with experts my understanding of the problem, and check that I got it right.

This is what I did :

* installed composer\_manager
* installed with drush awssdk and awssdk\_ui.
* installed amazons3 module
* while composer\_manager states that all required libraries were installed, drupal status report still says that awssdk fails to load.
* S3 is working fine and stores files attached to a node.

I think I understand my mistake: with Composer Manager installed and all requirements met, I don't need awssdk and awssdk\_ui modules.

These modules check that the libraries/awssdk/sdk.class.php is present, but composer\_manager install the required library in vendor directory.

With this understanding, I disabled AWS SDK for PHP and awssdk\_ui, and it seems to work well.

I believe that i have read to much docs on the Net, and mix two incompatible ways to install amazonS3.

Do I have the right understanding?

# Answer
In the last days, I have repeated the painful procedure many times on different AWS EC2 instances to be sure to have a precise and repeatable procedure. I am thus very confident about my understanding of it today. I have written a step-by-step procedure to deploy amazonS3, with the main encountered problems and how I dealt with them. I believe that such a document would have helped me a lot some days ago (and back then, I didn't found any), so here is my proposal. I would appreciate some real experts validation there !

1) install Drush or update to get 5+ version

2) apply all valid patches from the amazonS3 README (https://www.drupal.org/project/amazons3), mainly to allow S3 generated URI s3:///filename.ext" to be supported by media and fileentity related modules

3) Install composer (goes without saying, but I missed it at first!) with :

```
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
alias composer='/usr/local/bin/composer.phar'

```

composer command should return usage tips

4) Install PHP's cURL extention. On Ubuntu, sudo apt-get install php5-curl is sometimes not enough. (See "cURL library required to enable drupal ...")

```
sudo apt-get update
sudo apt-get install curl libcurl3 libcurl3-dev php5-curl
sudo /etc/init.d/apache2 restart

```

5) From the drupal\_root folder, launch amazons3 download and install

```
drush  dl composer_manager
drush  en composer_manager

```

6) Configure the directory where to put vendor and composer.json files. The default directory are outside of Drupal's directory (vendor : "../vendor", composer: "../") Once the composer\_manager is enabled, I went admin/config/system/composer-manager/settings and set the fields as follows (again, refer to best practices for RW permissions of Drupal folders).

7) Be sure to give write permissions to www-data to the folder. Especially with the folder being outside of the drupal\_root folder.

8) Download and install amazonS3 using Drush and composer, since AWSSDK libraries will be automatically installed with all dependencies.

```
drush dl amazons3
drush en amazons3

```

These commands should automatically generate composer.json in the previously indicated folder. You can check that all the dependencies were correctly gathered from amazonS3 and other modules requirements. In my case, composer.json contains :

```
{
"require": {
    "aws/aws-sdk-php": "2.8.5-p1",
    "capgemini/drupal_doctrine_cache": "0.0.1-p1",
    "doctrine/cache": "~1.4",
    "php": ">=5.3.0"
},
"config": {
    "autoloader-suffix": "ComposerManager"
},
"require-dev": {
    "phpunit/phpunit": "~4.6",
    "satooshi/php-coveralls": "0.6.*"
},
"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/deviantintegral/drupal-doctrine-cache.git"
    },
    {
        "type": "vcs",
        "url": "https://github.com/deviantintegral/aws-sdk-php.git"
    }
],
"autoload": {
    "psr-4": {
        "Drupal\\amazons3\\": [
            "../../modules/contrib/amazons3/src/"
        ]
    }
}

```

}

9) I can't explain why, but the first install generated an incomplete composer.json . You can regenerate the file using by accessing /admin/config/system/composer-manager and click regenerate, or running from drupal\_root folder the following drush command :

```
composer-json-rebuild

```

9bis) You can also, directly from the composer folder (which location was set previously) and run : `composer install`. The command will download all required PHP libraries in composer vendor's folder.

I personally found it very confusing all the locations on my server where composer files where located :

* Some docs advise to put composer folder in a **~/.composer/vendor** folder in user's home directory. - - Drupal created a .composer in a **.drush/composer** (to indicate that Drush is required for that user)
* I found a **~/.composer** in my root folder. It contains users's credentials to access github repository to load the required packages
* Most of the docs recommend to store a composer folder just above the drupal\_root
* I choose to follow these last recommendations to put it in the sites/all/libraries/composer in order to commit the code. But I can't say whether this is the right way to proceed.

10) Finally, retrieve you AWS API KEY and AWS SECRET KEY from console.aws.amazon.com and configure amazonS3 in /admin/config/media/amazons3, by setting your Security Credentials: Access Key ID and Secret Access Key, and S3 Bucketname. You can also put the values in the settings configuration file, by adding the following lines to your settings.php :

```
$conf['amazons3_key'] = "<AWS API KEY>";
$conf['amazons3_secret']="<AWS SECRET KEY>";
$conf['amazons3_bucket']="<bucketname>";

```

11) AmazonS3 should be working : create a file field on a content type, select Amazon S3 as the location to save to. Create a node, attach a file,Save and view the node. The attached file should be displayed as a link to you S3 bucket.

During my last install, I was able to avoid most of the problems encountered in my previous tries : cURL, read/write permissions, composer unable to parse version requirements, etc. The last error I was confronted to, was a composer out of memory problem, which I fixed with the following :

```
sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo /sbin/swapon /var/swap.1

```

I hope this note will help someone, since S3 really worth a few headaches with the installation. Besides, the last release of the module is only two months old.
> 2 votes

---
Tags: composer
---


# Question
Title: Counter is always set to 1 and not incrementing
I want Anonymous users to redirect to login page if they have read three articles as trail. I wrote this code but the counter on any article is always set to one.I guess its initializing again and again. Can anybody please help with code.

```
<?php
function track_node_view($node, $view_mode) {
if (user_is_anonymous()) {
  if($node->type == 'article' && $view_mode=='full'){
      static $counter = 0;
      if($counter <= 3) {
        $counter += 1;
        dsm($counter);
        drupal_set_message($counter);
      }
      else {
        drupal_goto("user/login");
      }
   }
  }

```

# Answer
> 0 votes
In my mind your code does the following:

An anonymous user shows an article. Then (why static, makes no sense) a counter is declared with 0. Then the counter increments to 1.

Then any other or the same user (because there's no saving in user session) clicks anywhere and looks an article. The counter is again set to 0, then to 1 etc...

I assume you want the following scenario:

An anonymous user comes to your site, clicks 3 articles, and when clicking to the 4th he shall be redirected to the login site.

So what do you need:

You need a session handler for anonymous user. But Drupal haven't got sessions for them. So here are the drupal functions for sessions: drupal user session

To start a session for anonymous user:

```
if(session_id() == '') {
  session_start();
}

```

Then in your module your counter comes to play a role, so start with your hook\_node\_view:

```
function track_node_view($node, $view_mode) {
if (user_is_anonymous()) {
//Look if the counter is already set, if not create it
  if(!isset($_SESSION['track'])){
    $_SESSION['track'] = array();
  }
//Then look if the counter is in the session array(defaults to NULL)
  $tracker = track_session_get('track');
// if $tracker isn't available initialise your $counter
  if($tracker == NULL){
    $counter = 0;
  }
 // if session track is set and tracker != NULL you have to get the variable for counter
  if($tracker != NULL){
    $counter = $_SESSION['track']['counter'];
  }
 //now you should have a number between 1-3
  if($counter <= 3){
    $counter = ++$counter;
    //store this new value in session
    track_session_set('track',$counter);
  }
  else{
   //set the $counter to 0 and redirect
   $counter = 0;
   track_session_set('track',$counter);
   drupal_goto("user/login");
  }
 }
}

function track_session_get($session_name, $default = NULL) {
  if (isset($_SESSION[$session_name])) {
    return $_SESSION[$session_name];
  }
  return $default;
}

function track_session_set($session_name, $session_value) {
  $_SESSION[$session_name] = $session_value;
}

```

I did not tested this code, so this is only an advise, not a howto;)

# Answer
> 2 votes
The problem is that you failed to grasp how HTTP is basically stateless.

```
static $counter = 0;

```

This value will be kept during one run. But one run is one page load. Obviously, it will be fresh and new at all page loads - ie all article reads.

If you need to keep value in one user session, see Session API, that's what it is for.

If you don't need any extra functionalities, just use `$_SESSION['mymodule_counter']`. If you want to make sure session is started, use `drupal_session_start()`

# Answer
> 0 votes
It is not working because that hook is normally invoked once for each page request, and at each page request, Drupal is getting bootstrapped; that means that once Drupal served the page request, every static variable is reset to its default value (in your case, 0). In your case, you should use `variable_set()` to set a Drupal persistent variable, and `variable_get()` to get its value.

Notice also that `hook_node_view()` should not redirect users like your code does; it is going to give you troubles with cron tasks. In fact, that hook is invoked even when a module is calling `node_view()` without any user watching a node page.

---
Tags: nodes
---


title: Can't uninstall module from Drupal 7

text:
# Question
Title: Can't uninstall module from Drupal 7
I'm running Drupal 7 from 2011-01-05 and I'm trying to uninstall Views Slideshow: Cycle (7.x-3.0 alpha1) and Views Slideshow(7.x-3.0-alpha1). I disabled them in the modules list then go to the uninstall list and uninstall them there but they still show up in the modules list and I can't re-install it because it says the modules are already installed.

I've tried clearing the cache.

Any ideas?

# Answer
To remove modules, you have to remove them from your server's modules directory (usually `sites/all/modules/`). Uninstalling through the interface runs the uninstall code provided in the module, typically to remove custom database data and tables that the module may have created.
> 11 votes

# Answer
1. Uncheck the module from your sites

go to uninstall tab & check the modules you want to uninstall -\>uninstall

2. go to sites/all/modules delete the module

3. go to the "database"-\> "system" table -\> search for that module row & delete (if the row exists)

4. clear the cache

Now it will be removed properly.
> 1 votes

---
Tags: 7
---


# Question
Title: How to display translated options for list(text) fields with field_view_field()?
I have set up a list(text) field with translated content.

In display admin interface (admin/structure/types/manage/\***/display), I have set up it to "Default translated" in "format" column. Then if I display the node, the options are well translated.

But when I try to load this field programmatically, I have always the main language displayed (instead the translation).

Here is the way I proceed.

```
$specialisations = field_view_field('node', $node_object, 'field_sp_cialisations_liste', array('type' => 'i18n_list_default','label' => 'hidden'));

render($specialisations)

```

# Answer
You can pass $langcode parameter in field\_view\_field function
> 0 votes

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


title: Display a block on front page only

text:
# Question
Title: Display a block on front page only
How do I only show a block on the front page. I have on only listed pages under block settings and it won't disappear on the second page. I've also added

```
$is_front
drupal_is_front_page

```

around the block and those don't work either. Renaming page to page--front.tpl.php didn't work either. Any suggestions on how to fix this? Also please be specific with your answers as I have no idea what to do and I hope this doesn't need a moldule as I'm trying to run a site with little running modules as possible.

Thanks, Gregory S.

# Answer
> 0 votes
Danno solution is good to go On visibility settings \> Show block on specific pages. Selected: Only the listed pages:

this is the best way. Are you sure you have checked the only listed pages or you can slect the php checkbox and write some php code.

# Answer
> 1 votes
Your setup is correct. On visibility settings \> Show block on specific pages. Selected: Only the listed pages:

```
<front>

```

Your problem might be that the second page is caching. And it is still showing on that page. Or you have another module conflicting and displaying the blocks. Is your site publicly visible. Can you provide a URL?

# Answer
> 0 votes
You can render the drupal block programmatically by using block\_load() function. If you want to render any block in tpl file you can use the below snippet.

```
$block = block_load('MODULENAME', 'delta');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
print $output;

```

---
Tags: views, theming, blocks
---


# Question
Title: Is displaying a working Field Widget Form on its own possible?
I'm interested in embedding a Field Widget Form out side the context of the whole node edit form.

I have displayed full forms in the past using drupal\_get\_form but that doesn't seem to apply for solitary Field Forms.

Is displaying a working Field Widget Form possible? What would be the best way to do so?

Both field widgets and "normal" forms seem very alike, so if this is not possible, what would be required to "change" a widget form into a normal form?

This question appears to be asking for something similar but I don't understand the answer. That answer specifies using hook\_field\_widget\_form\_alter; what I don't understand is how to get the Field Form to be displayed not how to hook it once it is being created.

# Answer
VBO does something like this in modify.action.inc:

```
$form_key = 'bundle_' . $bundle_name;
$form[$form_key] = array(
  '#type' => 'fieldset',
  '#title' => $label,
  '#parents' => array($form_key),
);
field_attach_form($context['entity_type'], $entity, $form[$form_key], $form_state, LANGUAGE_NONE);

```

So, you need the entity type, the entity (which can be a blank object with just the bundle key set, that's what's actually used), the form where the widgets are added, and the language. If you want to embed the widgets deeper into the form (not in $form, but in $form\[$form\_key\] as I did, or even deeper), then that form array needs to have #parents set.

Of course, notice that this will embed the widgets of all fields belonging to that entity type & bundle. This is how the attach functions were written. Going around that would require you to reinvent quite a lot of code; see the actual code that does the heavy lifting. What I do is go through field instances, get each $field\_name, and if that field type doesn't interest me, I set `$form[$form_key][$field_name]['#access'] = FALSE;` which hides those widgets from sight.

EDIT: Okay, ctools has ctools\_field\_invoke\_field() which could in theory allow you to work on a per-field basis. I've never used it though. The text above is my direct experience.
> 18 votes

# Answer
I was intensively using the function suggested by ttk, but I think that a recent update messed things up...

Here is a new version of the previous solution that works well with Drupal 7.22 and ctools 7.x-1.3.

So, like in the previous post, you call your custom function like this:

```
my_field_attach_form('field_body', 'node', 'blog',  $node, $form, $form_state, LANGUAGE_NONE);

```

Notice that the entity *bundle* is now a parameter. I did this because I was also using this function to edit users. This way, it can also be used for taxonomy term, or any other entity.

And the `my_field_attach_form` is defined as:

```
function my_field_attach_form($field_name, $entity_type, $bundle, $entity, &$form, &$form_state, $langcode = NULL) {

  // Set #parents to 'top-level' if it doesn't exist.
  $form += array('#parents' => array());

  // If no language is provided use the default site language.
  $options = array(
    'language' => field_valid_language($langcode),
    'default' => TRUE,
  );

  // Append to the form
  ctools_include('fields');
  $field_instance = field_info_instance($entity_type, $field_name, $bundle);
  $form += (array) ctools_field_invoke_field($field_instance, 'form', $entity_type, $entity, $form, $form_state, $options);
}

```

This function saved me a lot of time, hope it will for you too!
> 7 votes

# Answer
Here is the solution using the `ctools_field_invoke_field()` method. In your custom form function, add:

```
$form = array();
$node = new stdClass();
$node->type = 'blog';
my_field_attach_form('field_body', 'node', $node, $form, $form_state, LANGUAGE_NONE);

```

where the `my_field_attach_form` function is defined as

```
function my_field_attach_form($field_name, $entity_type, $entity, &$form, &$form_state, $langcode = NULL) {
  // Set #parents to 'top-level' if it doesn't exist.
  $form += array('#parents' => array());

  // If no language is provided use the default site language.
  $options = array(
    'language' => field_valid_language($langcode),
    'default' => TRUE,
  );
  module_load_include("inc","ctools","includes/fields");
  $form += (array) ctools_field_invoke_field($field_name, 'form', $entity_type, $entity, $form, $form_state, $options);
}

```

Note, that your site need to have ctools enabled. It's too bad that Drupal doesn't include a helper function like this by default.
> 5 votes

# Answer
I was unable to get the ctools method working and decided to do it this way instead.

This code would be inside of a form function, so $form and $form\_state would be passed in already.

```
function form_function($form, &$form_state) {

```

First create an empty node of a type that has the field that you're looking to render.

```
    $entity = new stdClass();
    $entity->title = "Temp Object";
    $entity->type = "node_type";
    node_object_prepare($entity);

```

I duplicated the form variables so I wouldn't clobber the original.

```
    $temp_form       = $form;
    $temp_form_state = $form_state;
    field_attach_form("node", $entity, $temp_form, $temp_form_state);

```

Pull out the field you are looking for and add it to the form.

```
    $form["field"] = $temp_form["existing_field"];
}

```

I used this method to render the taxonomy select widget, taxonomy checkboxes widget and the Hierarchical Select widget on a custom form. (Taxonomy Autocomplete widget renders but throws an error on submit)

Finally render and print

```
drupal_render(drupal_get_form("form_function"))

```
> 2 votes

# Answer
I have created forms from indivisual fields using

```
field_default_form('entity_type', $entity, $field,$field_instance,LANGUAGE_NONE,$default_value, $form, $form_state);

```

this should return the required widget form which can be used in any form like

```
 $custom_form['form_element_to_display'] = field_default_form('entity_type', $entity, $field,$field_instance,LANGUAGE_NONE,$default_value, $custom_form, $custom_form_state);

```

To get the values for the 2 parameter above use:

```
$field = field_info_field($field_name);
$field_instance = field_info_instance('node', $field_name, $node_type);

```

For other parameters you can check the api link here

This returns the default widget form defined on the content types field.

Hope this helps someone :)
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to properly test access permissions when generating links?
I have a page that is only accessible by some people. It's entry in `hook_menu` contains following:

```
$items['mymodule/mypage'] = array(
  'title' => 'Edit Product',
  'page callback' => 'mymodule_mypage',
  'access arguments' => array('view mypage'),
  'file' => 'pages/mypage.inc',
);

```

It works all right, it shows page when it should and throws 403 when needed. Now I need a link to it on some other page. Usually I would just use:

```
<div class="links">
  <?php echo l('My Page', 'mymodule/mypage'); ?>
</div>

```

in tpl.php file where I need it. But I don't want it to be visible for people who will get 403 if they will click it. `l()` does not test for permissions on it's own. And I feel reluctant about using logic in templates like this:

```
<?php if ( user_access('view mypage') ) : ?>
  <div class="links">
    <?php echo l('My Page', 'mymodule/mypage'); ?>
  </div>
<?php endif; ?>

```

I always believed than if's in templates are only to provide things like odd/even, marking visible tabs and deciding if markup should be outputted, like `if(!empty($header))`.

On the other hand, building this in the module and passing to the template seems like an overkill for such a simple task.

So what is the "canonical", cache-safe way to achieve this?

Additional information about **what this link really is** in this case:

Link is related to the page it is presented on, so block does not make sense.

Leaving it to the user to add link to the menu, so that menu system will take care about permissions, is not applicable, as it violates the "if something have to be done during install, always the same way, and requires no user input of any kind, don't leave it to the user" rule. If there is a way to *automatically* place it in menu in a way similar to `node/%/edit` links shown on `node/%` pages, all right. I'll be happy to accept that as an answer. But my question is general, *without* assumption that links share front part. In my exact case, they actually do not.

# Answer
You can check the access for any url-path in your module using menu\_get\_item():

```
$menu_item = menu_get_item('mymodule/mypage');
$access = $menu_item['access'];
if ($access) {
    $mylink = l('My Page', 'mymodule/mypage');
} else {
    $mylink = '';
}

```

Put this code e.g. in some preprocess function in your module, change $mylink variable to sg that is available in your .tpl.php, so you only need to print this variable in your tpl.php.
> 2 votes

---
Tags: users, navigation
---


title: Adding script conditionally

text:
# Question
Title: Adding script conditionally
In the module I am developing I need to add script which require jQuery.The will be added depending on configuration settings. Hence I am using `template_preprocess_module(&$variables)` where I am trying to add script by doing something like this:

```
function template_preprocess_module(&$variables) {
  if (TRUE) {
    $variables['jquery'] = ?;
    $variables['script'] = 'path to script in module';
  }
}

```

Then in the template I will simply be rendering these variable in the head section. But I am facing trouble in adding jQuery, because I don't know its source (obviously I know its source in core but I need something over here which automates path). Can the source be known by using something like `drupal_get_path()` ? I am also not sure if this is the best way to add script conditionally, any suggestion regarding this? Thanks.

# Answer
> 5 votes
To attach a script in Drupal 8 you need to define a library first in your modules `*.libraries.yml` (replace * with your modules machine name). The file should look as follows:

```
libraryname:
  version: 1.x
  js:
    js/script.js: {}
  dependencies:
    - core/jquery

```

After that you have the possibilities to attach a script through a preprocess function or directly in the template with a twig function. I believe you are trying to achieve the first. In that case you need to modify the render array, like in this example:

```
<?php
function modulename_element_info_alter(array &$types) {
  if (isset($types['table'])) {
    $types['table']['#attached']['library'][] = 'modulename/libraryname';
  }
}
?>

```

If you want to append a script to every page depending if a custom setting is activated in your module, you should do as follows:

```
function modulename_page_attachments_alter(array &$page) {
  if ($settingIsTrue) {
    $page['#attached']['library'][] = 'modulename/libraryname';
  }
}

```

You can read more about it in the manual.

# Answer
> 1 votes
You can add jQuery directly in a twig template using the new Drupal 8 `attach_library()` twig function:

```
{# my_template.html.twig #}
<div>
{# This will add jQuery to this template only #}
{{ attach_library('core/jquery') }}
</div>

```

---
Tags: theming, 8, configuration
---


title: How do i pass 2 values to a view?

text:
# Question
Title: How do i pass 2 values to a view?
I have a Drupal View that displays the 2 most recent articles from our db. How do i allow a user to select which article they would like to display. And, if the user does not choose the 2 articles then the 2 most recent will be shown.

I tried to use filters and the "Expose this filter to visitors, to allow them to change it" option. But I cant seem to figure out how this would be done.

Thanks.

# Answer
I would pass the argument in via the URL, you can pass multiple args in using '+'. So http://example.com/my-view/\[nid1\]+\[nid2\]
> 0 votes

---
Tags: views
---


# Question
Title: How to remove markups of 'div' and 'span' from the billing info displayed through token
I am trying to add token for billing information in order confirmation email . The token does its job but also displays markups of 'div' and 'span'. Whats surprises me is all the other tokens in the same email works fine and doesn't display any mark ups, however the issue is only with the token of field type: 'Postal Address' within the billing information profile

These are the two tokens I have used:

\[message:message-commerce-order:commerce\_customer\_billing\]

\[message:message-commerce-order:commerce-customer-billing:commerce\_customer\_address\]

I added these tokens to email through admin-\>structure-\>message type, since I am also using the following three modules: Commerce Message, Message Notify and Message

Any help on how to display complete billing info without markups, as entered in the built in field: 'Postal address' will be highly appreciated. Tried all the checklists in admin-\>configuration-\>text format, but no luck

# Answer
If you want to alter the content of tokens you could try using the Token Function module: http://www.drupal.org/project/token\_function

With this module you can write a simple function to alter the content of a token (or use one of the few existing functions).

I hope this helps.
> 1 votes

---
Tags: rules, commerce, tokens
---


# Question
Title: Converting and save images as JPG in IMCE module during uploading?
How to convert PNG to JPG when user upload images with IMCE ? This is neccessary for disk space optimization. If it is possible to convert with any module or to execute Image Style tell me please.

# Answer
It can be done in this way:

* download ImageCache Actions module and enable Color Actions module
* create image style "Change file format Convert to: jpg"
* download and install IMCE Image Style module
* on the IMCE Image Style administration page select necessary style

And we need to add custom submit function

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
 function mymodule_form_imce_upload_form_alter(&$form, &$form_state, $form_id) {
   array_unshift($form['fset_upload']['upload']['#submit'], "mymodule_upload_form_submit");
 }

/**
 * Change uploaded image extension.
 */
 function mymodule_upload_form_submit($form, &$form_state) {
   if ($_FILES['files']['type']['imce'] == 'image/png' &&    $form_state['values']['imce_image_style']['optimize_image'] != '0') {
      $_FILES['files']['name']['imce'] = str_replace('.png', '.jpg', $_FILES['files']['name']['imce']);
   }
 }

```
> 1 votes

---
Tags: media, files, performance
---


# Question
Title: Is there a nodequeue module for ordering and selcting taxonomy terms instead of nodes for used in a view?
Currently I want to make a curated slideshow of taxonomy terms displaying the name of the term with an image field thats attached to the term. Typically this is easily done with a basic node and the module nodequeue. The thing is I want to be able to do this with taxonomy terms.

I found entityqueue module that could work, but its crashing on my site for some reason. It works on a new install and I cannot pin point the issue since the site is fully built out already. I was wondering what other ways or possible modules I can do this with?

What I'm building is just a curated slideshow view of taxonomy terms.

\*edit -- found the culprit module that was conflicting with the entityqueue module. whenever i turn on the entityqueue module the entire site would crash and i would end up having to do a DB restore. The module that was causing this conflict was "admin\_menu"! O\_O

# Answer
> 1 votes
You can try out Flag module, which supports flagging entities, combined with flag\_weights and draggableviews you can create ordered slideshows of flagged taxonomy terms.

> Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

If you want to use Flag-3.x with flag\_weights you will have to apply this patch: https://drupal.org/node/1877304 works for me so far.

# Answer
> 0 votes
Entityqueue is a great module for this purpose. Draggable Views is a great alternative. You can also check out the Comparison of Node/Entity Ordering Modules page on Drupal.org for other options.

**Sidenote:**

The issue mentioned with Entityqueue and Admin Menu was fixed.

This patch was committed to Entityqueue about the time this question was asked, to avoid problems like the one caused by Admin Menu: https://www.drupal.org/node/2167037#comment-8361729

A patch was later committed to Admin Menu to fix the root cause.

---
Tags: views, taxonomy-terms, javascript, nodes
---


title: Load PDF through colorbox

text:
# Question
Title: Load PDF through colorbox
I am trying to load a PDF from a link using colorbox but although the colorbox window opens the pdf is just text characters. This is what the link looks like:

This is what my link looks like:

```
<a href="http://example.com/sites/default/files/menus/menu.pdf?width=500&height=500&iframe=false" class="colorbox colorbox-load">View</a>

```

and when it's rendered out it looks like this:

```
<a href="http://example.com/sites/default/files/menus/menu.pdf?width=500&height=500&iframe=true" class="colorbox colorbox-load init-colorbox-processed cboxElement">View</a>

```

which looks right to me but the pdf is just text characters. The pdf loads fine just as a link opened in your browser.

# Answer
I suggest you, use this module https://www.drupal.org/project/pdf\_to\_imagefield since colorbox is designed to display images.

If you still want to show the complete pdf. You could embed it in a basic page:

Download file

You can then reference the page by node id.

Link name
> 1 votes

---
Tags: javascript
---


# Question
Title: Having Problem editing product displays created by Commerce Feeds to add product flag link
Hi all and I apologize in advance for what seems like a rudimentary question.

I have a drupal commerce site (drupal 7.38, commerce 7.1.11, Commerce Feeds 7.1.3) and I have a very basic flag set on my custom products. The issue is I have is that I cannot seem to be able to add the flagging fields to the products displays generated from the templates imported with commerce feeds. I use a template very similar to the attribute/taxonomy terms I import via feeds. The problem is that there doesn't seem to be an obvious way to do this through the UI when editing the Content Type for my custom product display.

I can confirm that there is a flag field listed for the custom product type, but it doesn't show up in the fields available in either the Manage Fields or Manage Display tabs of my product display. The field is visible in the Manage Display tab of the product type, but is not in the manage fields list and isn't obviously manageable in some other way.

Is this commerce feeds that's tying my hands, or how do I edit these?

# Answer
As pointed out in the comments, this was resolved by using commerce reference flag and adjusting my flag and displays.
> 0 votes

---
Tags: commerce, feeds
---