# Question
Title: Web forms senders to make their email secure
Make Web forms secure- can we have an option for senders to make their email secure when sending private information back like account numbers, is there an option for this in Drupal or is it possible to create something,

# Answer
> 0 votes
You can use the SMTP Authentication Support which allows you to send your e-mail via port 587 (TLS), which means your e-mail gets encrypted.

---
Tags: views, forms, emails, security
---


# Question
Title: How to restore $form_state when rebuilding a form after a redirect
We have a site where either authenticated or unauthenticated users can submit a form. When the form is validated, we check whether they are logged-in, and if not, we redirect them to authenticate, with a destination parameter of the original page. At this point, we cache the `$form` and `$form_state` in `$_SESSION`.

After authentication and redirection the form is redisplayed on the page (by retrieving the `$form` from `$_SESSION`) and ask them to confirm the submit. Note the form is dynamically-generated which is why we have to store it.

What I can't seem to do on redisplay is set the form values to the choices that the user previously made, even though these are stored in the cached `$form_state`. What is the best way to do this?

# Answer
I got this working in the end. The solution was:

```
$form_array = drupal_retrieve_form($cached_form, $cached_form_state);
$form = $form_array['#form_id'];
$block['content'] = drupal_render($form);

```

where `$cached_form` and `$cached_form_state` were the `$form` and `$form_state` values that had been stored in `$_SESSION`. Note that `'#form_id'` is a literal string, I've no idea why `drupal_retrieve_form` returns an array with that string as a key.

This redisplayed the form in the block after the authentication challenge, with the user's pre-challenge selections populated into the form elements. I couldn't get it to work with either `drupal_get_form()` or `drupal_build_form()`.
> 0 votes

---
Tags: 7, forms, hooks, sessions
---


# Question
Title: Missing bottom level item when a node is linked to two menu objects
I have been trying to create a custom menu block which shows a number of menu items with images on the current level.

I am having an issue where the active trail array doesn't return an menu item for the active node on level 4 of my menu. Here is an example of how I get the active trail:

```
$menu_tree = \Drupal::menuTree();
$menu_parent_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

foreach($parameters->activeTrail as $active_menu_link) {
  if($active_menu_link !== '') {
    $active_menu_id = explode(':', $active_menu_link);
    $entity = \Drupal::entityManager()->loadEntityByUuid($active_menu_id[0], $active_menu_id[1]);

    kint($entity->getTitle());
  }
}

```

It seems that the issue is mostly related to the fact that the same node is linked to both a child menu item and a parent menu item. If I remove this then the function works as expected. This is the my menu structure.

The two menu items highlighted in red are both linked to the same node since I want it to act as an overview page for the category. It could be that theres something else I can do to structure the menu differently. I am open to any alternatives on how I can get around this.

# Answer
I resolved this by manipulating the tree object manually further down my module. I checked if the url of the parent object matched any of the child objects via a loop.

```
$menu_tree = \Drupal::menuTree();
$menu_parent_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

// Setup current link
$currentLinkId = reset($parameters->activeTrail);
$parameters->setRoot($currentLinkId);

// Load the tree based on this set of parameters.
$tree = $menu_tree->load($menu_name, $parameters);

// Get the parent of current menu so we can use its
// children as the links
$parameters->setRoot(reset($tree)->link->getParent());
$tree = $menu_parent_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_parent_tree->transform($tree, $manipulators);

foreach($tree as $key => $menu_item) {
  // Check if the link is the current page?
  $current_internal_path = $menu_item->link->getUrlObject()->toString();
  foreach($menu_item->subtree as $sub_key => $sub_link) {
    $sub_internal_path = $sub_link->link->getUrlObject()->toString();

    if($current_internal_path == $sub_internal_path) {
      unset($tree[$key]->subtree[$sub_key]);
    }

    // Check if we have another sub tree (we are not the parent). This can happen when a parent
    // link is attached to the same node as a child one.
    if($sub_link->subtree && count($sub_link->subtree)) {
      $lower_level_links = $sub_link->subtree;

      foreach($lower_level_links as $lower_link_key => $lower_level_link) {
        $lower_level_url = $lower_level_link->link->getUrlObject()->toString();
        if($sub_internal_path == $lower_level_url) {
          // Set the active menu level as this.
          $tree = array($sub_link);
        }
      }
    }
  }
}

// Build up our menu
$menu = $menu_tree->build($tree);

```

This is perhaps not the cleanest solution with a lot of extra processing required but seems to work in this instance.
> 0 votes

---
Tags: 8, navigation
---


title: Update a module and "is outside" error

text:
# Question
Title: Update a module and "is outside" error
I have a new installation of Drupal 7.52 on a Windows server and during the update of some modules I receive that `/websites/mydrupalroot/....` is outside from `/website/mydrupalroot`!

I found this question:

https://stackoverflow.com/questions/28701991/drupal-module-installation-error-file-transfer-failed-reason-mysite-com-site

but the solution didn't work for me! What could be the problem? Could it be the directories privileges?

# Answer
> 3 votes
Apart from the solution mentioned in the link included in your question, here are a few other things you may want to try:

* Temporary change the configuration of the file system used by Drupal, to use a relative path to the temp folder (eg `..\temp`) instead of a full path (eg `C:\path\to\your\webroot\temp`).
* In your question it says "*... during the update of some modules...*", but nowhere you explained HOW you're performing this update. Are you using the update tool within Drupal? Are you using Drush? Are you performing this update using FTP or something like that? Whichever method you use, try to use any of the other typical approaches for updating modules. While doing so, you may run into some other unexpected problem/message, which may actually give you a clue about what your real problem is. E.g. some problem with a tmp-like folder to just unpack the new version of the module.
* Try to disable *all* your modules first, then re-enable one of them again, and apply all updates, if any, related to that module you just enabled. If for this first module the error doesn't come back, you've reduced the list of modules that cause your proble with one. If the error does come back, disable that module again (to be investigated in more detail afterwards). Repeat for each of your other modules. This approach should help you to find/identify the problem module (and either leave that disabled, or start in depth debugging of that module).

---
Tags: 7, updating
---


# Question
Title: Why hook_preprocess_html() isn't working?
Why `hook_preprocess_html()` isn't firing in my module file? Is it only works in theme\_hook?

EDIT:

```
function my_module_preprocess_html(&$variables) {
  if (current_path() == 'user') {
    $variables['head_title'] = implode(' | ', array(drupal_get_title(),  variable_get('site_name')));
  }
}

```

# Answer
> 1 votes
Try the general preprocess hook, like:

```
/**
 * Implements hook_preprocess().
 */
function my_module_preprocess(&$variables, $hook) {
  if ($hook == 'html') {}
}

```

---
Tags: 7, hooks
---


# Question
Title: How to email the results of a filtered view to a user?
Required functionality (Drupal 7):

* User filters a view to desired results
* User enters email address in a webform block
* User is emailed the filtered list of results

I'm using Views (7.x-3.14), Webform (7.x-4.14) and Rules (7.x-2.9)

I've looked at a few modules surrounding saving your search results, but nothing I've found seems to help very much. Are there a combination of modules that I might be able to use (Rules, Cron etc.) that will achieve this or do you think I'll need to write something custom?

I'm still learning how to write custom Drupal modules so if anyone can point me in the right direction, that would be appreciated !

# Answer
> 0 votes
If your view is a page, should be as easy as grabbing the page url when the form gets submitted and based on the url (if statement) you attach a view that has a filter of "X". (slight chance that it is doable with rules and webform module)

If it's a block, gets a bit more complex. You would have to check what the filter is set to using jQuery, and then pass that variable to a custom module when the form is submitted. Then module triggers `x` function based on the view filter value that sends e-mail with view `x`.

---

Actually, an even more simpler option, have a hidden field of checkboxes (hide it with css) on your webform that has a box for each filter. Then with jQuery you can autocheck option `x` if filter is set to `x`.

Now since your webform contains field of checkboxes with value `x`, with conditional rules hopefully you can do an if statement on your field of checkboxes and attach view `x` to your e-mail. (I'm making a lot of assumptions here, as I've never used webform + rules, or maybe I did once... Anyhow, hopefully this will work with Rules)

---
Tags: 7, views, webforms, emails
---


# Question
Title: Specifying a custom node id when creating new content
I want to prevent merge conflicts caused by POST requests on the API at a later stage. Is it possible to specify a custom node id when creating new content in the Drupal user interface or database? What's the fastest, most efficient way to do this?

# Answer
> 1 votes
In the UI no, and you should never interact with the database directly.

But you can do this with the API easily:

```
$node = Node::create(['type' => 'article', 'nid' => 5]);
$node->enforceIsNew(TRUE);
$node->save();

```

---
Tags: nodes, 8, database
---


# Question
Title: modules_install hook causes constraint violation: 1048 Column 'module' cannot be null: INSERT INTO {role_permission} (rid, permission, module)
I am trying to set several permissions when a feature is being enabled (a new content type). By default this content type is disabled, and an admin can go to `structure/features` and enable it

under `docroot/profile/my_profile/features/foo` I created the following `foo.install` file

```
function foo_modules_installed($modules) {
 if (in_array('foo', $modules)) {
  $perms = array(
    'create foo content',
    'edit own foo content',
    );
      user_role_grant_permissions(user_role_load_by_name('publisher')->rid, $perms);
      user_role_grant_permissions(user_role_load_by_name('administrator')->rid, $perms);
}
}

```

but when I go to `structure/features` and enable it, I get the following error

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'module' cannot be null: INSERT INTO {role_permission} (rid, permission, module

```

I tried different hooks, like enabled and so forth and all have the same issue.

How can I have a feature disabled by default, but still grant permissions to some users? What am I doing wrong

# Answer
Seems like a `hook_install()` in the .install file for the feature will work if called with

```
drupal_flush_all_caches();

```

I am not sure if this is the best solution, but it seems to work for me
> 0 votes

---
Tags: hooks, users, features, installation
---


title: Proper URI path for views render array

text:
# Question
Title: Proper URI path for views render array
I'm fairly new to Drupal and Drupalgap.

My Drupal site has a view/content called "donations".

In admin/structure/views, there are two PATHs: /current-donations and /available-donations. And of course, this URL works fine: http://127.0.0.1:8083/current-donations

Now I'd like to render this view in drupalgap using a views render array.

My first attempt looked like:

```
function mobile_donor_donations_page() {
try {
    console.log('mobile_donor_donations_list_page()-e');
    var content = {};
    content['avail_donations_list'] = {
        theme: 'view',
        format: 'ul',
        path: '/available-donations', /* the path to the view in Drupal */
        row_callback: 'mobile_donor_donations_list_row',
        empty_callback: 'mobile_donor_donations_list_empty',
        attributes: {
            id: 'avail_donations_list_view'
        }
    };
    return content;
}
catch (error) { console.log(':ER:mobile_donor_donations_page: ' + error); };
}

```

The above function gets called fine -- on my console (chrome, Ripple) I see

```
GET: http://127.0.0.1:8083/?q=/available-donations&page=0
200 - OK
views_embed_view - success - TypeError: Cannot read    property 'count' of undefined

```

Looking at the views\_embed\_view() code below, it is throwing an exception because results.view is undefined:

```
// Render the view if there are some results, or if there are no results and an
// empty_callback has been specified. Otherwise remove the empty div container for
// the view from the DOM.
if (results.view.count != 0 || results.view.count == 0 && options.empty_callback) {

```

I tried http://127.0.0.1:8083/?q=/available-donations&page=0 from my browser, it returns html, not JSON.

To force JSON returned, I tried

```
path: 'drupalgap/node.json&parameters[type]=donation', /* the path to the view in Drupal */

```

This PATH does indeed return my content as JSON, however the error remains, since the JSON doesn't contain a "view" element.

```
GET: http://127.0.0.1:8083/?q=drupalgap/node.json&parameters[type]=donation&page=0
200 - OK
views_embed_view - success - TypeError: Cannot read property 'count' of undefined

```

What PATH do I need to supply, or do I need to change structure of my content in Drupal to get the view to render?

Thanks!

# Answer
> 0 votes
Be sure to create a `JSON Data Document` display for your View with a unique page path, then you can use that `path` in your DrupalGap Views Render Array. More documentation and examples are available here: http://docs.drupalgap.org/7/Views/Displaying\_a\_View/Views\_Render\_Array

---
Tags: javascript
---


title: Count the number of Flagged users

text:
# Question
Title: Count the number of Flagged users
I'm running a D7 site and need some help with a view.

I've a 'Follow' Flag on every user profile which users can use to follow each other.

I'm trying to build a view where I want to see the list of users who have followed less than 5 other users.

Is this possible?

# Answer
Well, actually it's not too late to implement if you do the following:

1) Add a `following count` (integer) field as a user field.

2) Go to `/user/1/edit` and put any number other than 1, inside of this field. (this is just a temporary place holder).

3) With PHPMyAdmin or a DB viewer program, export the `following count` field as a CSV file.

4) The 1 is where the USER ID goes, and the other random number is the actual following count.

So with views, create a view that shows the user ID and the following flag count number.

Then you open the exported .csv file on Excel and paste these data in the proper columns.

5) Import back into your Drupal DB and clear flush cache.

**\*Note:** Instead of doing steps 3, 4 and 5, you could just do this with Views Bulk Operations \+ Rules.

6) Using the Rules module, create a rule that +1's the user `following count` field, when a user flags the follow flag and -1's it when they unfollow.

7) In views, in your List of Users View, for Filter, simply add the `following count` field and put less than 5.

8) Use the Field Permissions module to hide the `following count` field, that way when they edit their profile, the user cannot insert/modify the number.
> 1 votes

# Answer
You need to create a view of users (base table: user) with the following settings:

* Relationships:

+ Flags: User flag

    - Identifier: a meaningful name
        - Include only flagged content: checked
        - Flag: Your existing flag
        - By: Any user
    + Flags: User flag counter

    - Identifier: a meaningful name
        - Include only flagged content: checked
        - Flag: Your existing flag
* Filter:

+ Flags: Flag counter
        - Relationship: the created flag relationship from above
        - Operator: Is less or equal to
        - Value: 5
* Sort criteria:

+ Flags: Flag counter
        - Relationship: the created flag relationship from above
        - Sort descending: selected
* Field:

+ Flags: Flag counter
        - Relationship: the created flag relationship from above

You can select from the "Flags: User flag" relationship between "Any user" or "Current user" to view flagged content for any user or the logged in user respectively. Basic theory on flags and views.
> 1 votes

---
Tags: 7, views, flags
---


# Question
Title: How to create a view for logged in user?
In user account (`/admin/config/people/accounts/fields`) I have a field that references to an entity: company.

I have a node-type, **dossier**, with a field that references the same entity as in user account: company.

How can I make a view where the logged in user only sees the user's own *dossiers*?

I tried a lot of things but nothing works. Sometimes the view is empty, sometimes the logged in user sees all the dossiers of the website.

# Answer
I added an extra reference field to dossiers which refers to an user. In the view: add relationship to the referenced field and make it mandatory. Now it works. The logged in user sees only his files.
> 1 votes

# Answer
You will need to create a view to display dossiers when the company's NID is the contextual filter.

The below is for a module called "custom\_views\_args" and it's the custom\_views\_args.module file. You need to change the field name, view name and display name. It should work fine.

```
<?php

function custom_views_args_views_pre_view(&$view, &$display_id, &$args){

// Load User - This is done and held in memory on every page load so don't worry about performance.
    global $user;
    $user_company = user_load($user->uid);

// Get the Company's NID
    $company_nid = 0; // Might stop errors
    if (!empty($user_company->field_COMPANY['und'][0]['value']) or isset($user_company->field_COMPANY['und'][0]['value'])) {
    $company_nid = $user_company->field_COMPANY['und'][0]['value'];
}

// Hook Views Pre View
    if($view->name == 'VIEW_NAME' and $display_id == 'DISPLAY_NAME') {
        $args[0] = $company_nid;
    }
}

```

Works for me.

By the way, this question title isn't relevant to the question really.
> 1 votes

---
Tags: 7, views
---


title: Restore a revision order

text:
# Question
Title: Restore a revision order
in a command I have the 1288 revision, 1498, 1499, 1500 I want to restore the 1288 revision and remove the 1498 revision, in 1499, 1500 can I do this in my database?

Thank you

# Answer
> 1 votes
By looking at the database *commerce\_order* and *commerce\_order\_revision* I don't think order revision is implemented in a way that is revertible. Probably that is the reason we can't find revision revert functionality either in commerce core or as a contributed module.

---
Tags: commerce
---


# Question
Title: How to create a rule to compare an order total with a custom field in a content type?
I have multiple restaurants with each another value for minimum order price, this is a custom price field in the content type "Restaurants".

I would need to make a rule where the total order amount is compared to this custom price field. If the total from the order is lower, it should redirect and throw a message.

The problem here is that I don't know what entities to use to get access to the custom price field named "field\_leveringsprijs".

The event is on payment selection or checkout completion. The actions would be a page redirect and a message which isn't hard to do. I'm just stuck with the conditions 'Entity has field' and 'Data comparison'.

Any suggestions?

# Answer
I'm assuming that your `field_leveringsprijs` (with "levering" = delivery, and "prijs" = price) corresponds to your *minimum order price* of your Restaurants content type.

If such field is not available as a token to use it in a Rules Condition, then the typical approach/solution is to use the Rules *Action* (not Rules Condition ...) "***Fetch entity by id***". So if you do have the id of the Retaurant available, just fetch the Restaurant (=some node of content type Restaurants). That will make all its fields, such as your `field_leveringsprijs` field, available for *subsequent* processing.

***But***, such *Fetch entity by id* is a Rules Action, so that's like you're too late to use the result of that Rules Action within the typical Rules Conditions (as you are trying to do in the data comparison shown in your question). The way to get around that, is to use either of following approaches:

* Use the Conditional Rules module, which basically allows you to add a Rules Condition as part of the Rules Actions you want to perform. So using this module/technique, you'd specify something equivalent to "if order total is below `field_leveringsprijs`". And then add the actual Rules Actions you want to perform in that case (= perform a redirect, and show some message).
* Create a Rules Component in which you execute (as Rules Actions) those actions such as that redirect and display a message). But which also includes a Rules Condition equivalent to "if order total is below `field_leveringsprijs`". **And** (this is crucial!) make sure to pass a "parameter" to this Rules Component, which will reprezent your `field_leveringsprijs` (with same data type). After you QA-tested your Rules Component, go back to your original Rule, and simply execute that Rules Component, by passing the appropriate value of the Rules Component parameter, using ... indeed ... your `field_leveringsprijs` (which you got via that "Fetch entity by id", remember?).
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: Drupal_get_title() but for another field by name?
If I use `drupal_get_title()` I can print the title of the page to the page body. Custom content types that I'm using have many fields like subtitle, url redirects, etc. How would I go about printing those to the page body just like `drupal_get_title()` allows me to do for the page title?

I've reviewed the forum for other solutions. `field_get_items()` and `$content['field_name']` aren't working for me. I think what I want to do is simple but most of the examples pertain to database manipulation.

# Answer
Maybe `print $content['field_MACHINE_NAME']['und'][0][taxonomy_term]->name;`? That should print the field without the HTML

If you want the HTML, trying using `print render($content['field_review_nationality'][0]);`

Source
> 0 votes

---
Tags: 7, entities
---


# Question
Title: VBO calls entity_save after custom action is triggered. How to stop that?
I have VBO custom actions defined and it gets triggered. Also, I do NOT have 'behavior' =\> array('changes\_property') defined in my hook\_actions\_info() as described in How to create custom VBO action?

I see that my custom action is getting triggered and does custom operations and finally saves by creating new node revision. Weird part is that entity\_save operation is being called after this and it is updating node table with older version of node rather than new vesrion created by custom funtion.

How can I stop or prevent vbo to call entity\_save and just perform custom action?

Any insights will be greatly helpful.

Thanks!

# Answer
This is an old issue, but I literally just had the same problem and after banging my head off of it all day I found upon a solution through the d.o issue queue.

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

I applied the patch from #42 and it solved it right away after setting `'behavior' => array()`.

Hope this helps someone else.
> 1 votes

# Answer
I was running into the same type of issue where I had removed

> 'behavior' =\> array('changes\_property')

from my custom action's definition. However on digging in, I found in plugins/operation\_types/action.class.php lines 22-25 that if you don't specify the 'behavior' attribute in your definition it gets set to

> array('changes\_property')

by default. To prevent entity\_save from running, set it to an empty array as in:

> 'behavior' =\> array()

then it should start working as you expect.
> 0 votes

---
Tags: views, actions
---


# Question
Title: AJAX form submit by clicking on any element with the #ajax property
I have been searching for this a lot but all the tutorial on the net only show how to create an ajax form with `#ajax` on the submit button if you want to submit the whole form.

What I am trying to achieve is this: I've got a custom form with lots of checkboxes, all of which set values in an array stored in `$_SESSION`. When I attach `#ajax` to a checkbox the form gets replaced, but the `$_SESSION` array does not change as if the form as a whole has not been submitted.

How can I achieve that when I click on a checkbox the form submits as if I clicked on the submit button and the `$_SESSION` array is set correctly?

Thanks a lot in advance.

# Answer
> 0 votes
Maybe this code:

```
$( "[type="checkbox"]' ).change(function() {
  $( "form" ).submit();
});

```

When a checkbox is change, it submits the form.

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


# Question
Title: How can I auto-populate fields with Ajax?
How do I autopopulate fields in a node form in drupal 8?

Basically, what I'm trying to do is create an ajax callback to autopopulate fields based on a call to a 3rd party service.

So I'm using hook\_form\_alter and a custom validate function, and I'm trying to update form values.

```
function mymodule_validate($form, FormStateInterface &$form_state) {

  $form_state->setValue('title', [['value' => 'testing 123']]);

  $form_state->setRebuild();

}

```

But this doesn't update the node title.

What's the correct way to alter values in a node form in an ajax callback?

# Answer
> 2 votes
I was able to get a basic autopopulation callback working based on this question:

How do I modify a core field to use Ajax and add markup?

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

/**
 * Implements hook_form_alter() on behalf of mymodule.module.
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_publication_form') {

    $form['title']['widget'][0]['value']['#value'] = 'enter title here';

    $form['import_from_third_party_service_id'] = [
      '#type' => 'textfield',
      '#title' => t('Import from third_party_service Id'),
      '#description' => t('To autopopulate fields from third_party_service, enter the third_party_service ID above in the textfield above and hit the import key below'),
      '#maxlength' => 64,
      '#size' => 8,
      '#weight' => '-10',
    ];

    $form['import_from_third_party_service_submit'] = array(
      '#name' => 'custom',
      '#type' => 'submit',
      '#value' => t('Import'),
      '#weight' => -9,
      '#ajax' => [
        'callback' => 'mymodule_import_ajax_callback',
        'wrapper' => 'import-wrapper',
      ],
    );

    $form['#prefix'] = '<div id="import-wrapper">';
    $form['#suffix'] = '</div>';

  }
}

function mymodule_import_ajax_callback($form, &$form_state) {

  // replace with code to get value from third party service
  $new_title = 'hello world';

  $form['title']['widget'][0]['value']['#value'] = $new_title;

  return $form;
}

```

# Answer
> 0 votes
You can hide the field\_teaser\_title from the node from (set its widget to hidden) then use hook\_entity\_presave to update its value. Finally show this field in teaser mode.

---
Tags: 8, nodes, forms, ajax
---


# Question
Title: Update query not working for db_update and db_query("update
I'm trying to update a field using the Drupal's bootstrapped db\_update or db\_query library functions for PHP. However, neither of them are working. IF I RUN THE QUERYS MANUALLY, THEY WORK.

These two queries are the exact same. They are equivalent to doing

```
update field_data_field_department set delta = 4 where entity_id = 10568 and delta = 0;

```

Please tell me what I need to do to execute this query from PHP and make it work.

```
db_query("update field_data_field_department set delta = $highest_delta where entity_id = $entityID and delta = $i");

```

OR

```
            $num_affected = db_update('field_data_field_department')
              ->fields(array(
                'delta' => $highest_delta
              ))
              ->condition('entity_id', $entityID)
              ->condition('delta', $i)
              ->execute();
            echo "num_affected: $num_affected\n";

```

num\_affected returns 1 every time.

Here is the state of the database before the query is executed.

```
MariaDB [db]> explain field_data_field_department;
+----------------------+------------------+------+-----+---------+-------+
| Field                | Type             | Null | Key | Default | Extra |
+----------------------+------------------+------+-----+---------+-------+
| entity_type          | varchar(128)     | NO   | PRI |         |       |
| bundle               | varchar(128)     | NO   | MUL |         |       |
| deleted              | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id            | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id          | int(10) unsigned | YES  | MUL | NULL    |       |
| language             | varchar(32)      | NO   | PRI |         |       |
| delta                | int(10) unsigned | NO   | PRI | NULL    |       |
| field_department_tid | int(10) unsigned | YES  | MUL | NULL    |       |
+----------------------+------------------+------+-----+---------+-------+
8 rows in set (0.08 sec)

MariaDB [db]> select * from field_data_field_department where entity_id = 10568;
+-------------+--------+---------+-----------+-------------+----------+-------+----------------------+
| entity_type | bundle | deleted | entity_id | revision_id | language | delta | field_department_tid |
+-------------+--------+---------+-----------+-------------+----------+-------+----------------------+
| node        | person |       0 |     10568 |       25093 | und      |     0 |                   39 |
| node        | person |       0 |     10568 |       25093 | und      |     1 |                   30 |
| node        | person |       0 |     10568 |       25093 | und      |     2 |                   41 |
| node        | person |       0 |     10568 |       25093 | und      |     3 |                   38 |
+-------------+--------+---------+-----------+-------------+----------+-------+----------------------+
4 rows in set (0.00 sec)

```

# Answer
The queries were written correctly. The problem was that there was a $node = node\_load($entity\_id) before the queries and that there was a node\_save($node) after the queries. The node save overwrote the changes that the queries had made to the database.

```
$node = node_load($entity_id);
...
db_query("update field_data_field_department set delta = $highest_delta where entity_id = $entityID and delta = $i");
...
node_save($node)

```

When $node = node\_load($entity\_id) is called, the tables from Drupal pertaining to that entity are stored in an array in $node. As the php programmer changes items in $node (or node\_wrapper) they are changed in the array. When node\_save($node) is called, those array items are sent to the database so that the database will now match what was stored in the array $node.

To solve the problem, we moved node\_save($node) before the queries so that our db\_query("update...") changes wouldn't get overwritten.

**Corrected Solution:**

```
$node = node_load($entity_id);
...
node_save($node)
...
db_query("update field_data_field_department set delta = $highest_delta where entity_id = $entityID and delta = $i");
...

```

Don't call node\_save($node) again unless you update $node using $node = node\_load($entity\_id) again to get a new copy of the database.
> 0 votes

# Answer
Try something like this, It should work.

```
$num_affected = db_query("UPDATE {field_data_field_department}
SET delta=:highest_delta
WHERE entity_id=:entity_id AND delta=:delta
", array(":highest_delta" => $highest_delta,":entity_id" => $entityID,":delta" => $delta))->fetchAll();

```
> 0 votes

---
Tags: database, updating
---


# Question
Title: How to remove a Views row if field equals value?
In my view I have a made a customised global field that returns a boolean result.

What I now need to do is if this field equals zero then the whole row should be ignored/removed from the view.

The issue here is that I cannot see this field in `Filter Criteria` to add as a filter. I have also looked into a programmatical solution but have looked at `hook_views_post_render` and `hook_views_pre_render` but cannot see how I can achieve this.

Any help, module suggestions or push in the right direction would be very much welcome.

# Answer
> 3 votes
I would use a views row template override for this. Do the following in a Development site first.

1) In the view, expand the Advanced options and click on the Theme: Information link. This displays all the available theme template suggestions.

2) Under the heading "Row style output" you will see all the possible template suggestions. Which one you override depends on your needs, but the last listed is the most specific so I would start there. Select it with your cursor and copy the file name.

3) Open this file in your code editor: sites/all/modules/views/theme/views-view-fields.tpl.php

4)Save it as the most-specific suggestion (the value you copied in step 2) and save it to your theme's template directory (e.g., sites/all/themes/yourtheme/templates or sites/all/themes/yourtheme/templates/views)

5) Now you can edit the template (the one we just saved to your theme). You can use a combination of html and PHP to achieve the exact markup and logic you want. Generally it's best practice to not code a lot of logic into your templates (use preprocess functions instead), but simple logic like checking if a field is present or has certain values is fine to include in the template.

There are many different ways to do this, but here is an example (change field\_custom\_boolean to the machine name of your custom global field ...

```
 <?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>
  <?php
  /* if custom field is present and set to 1 */
  if (isset($content['field_custom_boolean']) && $fields['field_custom_boolean'] == '1'): ?>
    <?php print $field->wrapper_prefix; ?>
      <?php print $field->label_html; ?>
      <?php print $field->content; ?>
    <?php print $field->wrapper_suffix; ?>
  <?php endif; ?>
<?php endforeach; ?>

```

6) Save file and flush all caches. Now when you check the view Advance:theme information settings, you should see your template override listed in boldtype. When you load your view it should only display rows for records where the custom global field is set to 1.

Good luck.

For more info on Views templates, see:

https://api.drupal.org/api/views/theme%21theme.inc/group/views\_templates/7.x-3.x

https://www.drupal.org/docs/7/modules/views

# Answer
> 1 votes
If I was trying to quickly achieve this frontend, I would use JS/jQuery.

```
$(".view-name .boolean").each(function() {
    $this = $(this);
    $this.addClass("value-" + parseInt( $this.text() ) );
});

```

Then, I would just use CSS to hide it:

```
.value-0 {
  display: none;
}

```

JSfiddle

**Update**: It looks like Views has a new filter called the "Global: Combine fields filter". Might be worth checking out.

---
Tags: 7, views
---


title: Render menu separately within admin

text:
# Question
Title: Render menu separately within admin
I need to render the main menu within the admin section of my website. I am setting up a module to do this on a new page. I need to theme this menu custom for just the admin, and leave it as it typically would be on the front-end of the site.

How can do do this?

```
$menu = menu_tree_all_data('main-menu');
// ...customize template/output for this menu and render from my module...

```

# Answer
> 0 votes
You can use one of these method.

Below method is used to print Main Menu in page.tpl.php file:

```
$main_menu = menu_navigation_links('main-menu');
$output = '<div id="main-menu" class="navigation">';
$output .= theme('links__system_main_menu', array(
    'links' => $main_menu,
    'attributes' => array(
      'id' => 'main-menu-links',
      'class' => array('links', 'clearfix'),
    ),
    'heading' => array(
      'text' => t('Main menu'),
      'level' => 'h2',
      'class' => array('element-invisible'),
    ),
  ));
$output .= '</div>';
print $output;

```

Or the example provided here:

```
$tree = menu_tree_all_data('main-menu');
menu_tree_add_active_path($tree);
print drupal_render(menu_tree_output($tree));

```

---
Tags: 7, theming, navigation
---


# Question
Title: Load multiple entities with entity_metadata_wrapper
It's very easy to load entities with `entity_metadata_wrapper('node', $nid)` \- but is there any way to load multiple entities, similar to `node_load_multiple()`?

I've tried passing in an array instead of a single id, but it gives the error: *Invalid data value given*.

If there isn't a function for this, is there an efficient way of doing this, or is a looping the only way?

# Answer
> 2 votes
There isn't, but you can just combine the two to get the same effect:

```
foreach (node_load_multiple($nids) as $node) {
  $wrapper = entity_metadata_wrapper('node', $node);
}

```

---
Tags: 7, entities
---


# Question
Title: The correct way to change the name of the language in the language switch
I try to change the name of language in language switcher from *Chinese, Simplified(简体中文)* to *中文*. Changing name in admin/config/regional/language/edit/zh-hans affects only English. So the language switcher looks like this:

> en/Chinese, Simplified(简体中文)

I created a function, but on some pages (e.g. node/1), it causes errors.

```
function theme_preprocess_block(&$variables) {
   $variables['content']['#links']['zh-hans']['title'] = '中文';
}

```

The error I get is the following one.

> Fatal error: Call to a member function getText() on array in /var/www/mysite/core/includes/theme.inc on line 1697

How can I fix this?

# Answer
Check, if the variable is set, to avoid the error:

```
function theme_preprocess_block(&$variables) {
  if (isset($variables['content']['#links']['zh-hans']['title'])) {
    $variables['content']['#links']['zh-hans']['title'] = '中文';
  }
}

```
> 1 votes

# Answer
Use this code for language switcher block with Language Icons module:

```
function THEMENAME_preprocess_block(&$variables) {
  if (isset($variables['content']['#links']['zh-hans']['title'])) {
    $variables['content']['#links']['zh-hans']['title']['#text'] = '中文';
    $variables['content']['#links']['zh-hans']['title']['#title'] = '中文';
  }
}

```

It just replaces language name and saves country flag. Insert this code in .theme file of your theme and change THEMENAME with name of your theme.
> 1 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: Allow view access to current user and admin
I'm creating a view to list user sessions statistics. (Data selected from table myuserstat, there is UID field, myuserstat rows is not a Content Type, just table)

I want to make access url like /mystat/{user}, to list data of specified user.

How can I allow users to see their own stat, and admins see all users stat? For now i only found how to limit to the current user: contextual filter-\>UID-\>Provide default value-\>logged user id. But in that case, how to allow admins to view all users?

# Answer
> 1 votes
Create another view or a page within same view with path /mystat or path can be different without using contextual filters. And in page seetting option in view choose access from none to role and select admin role.

---
Tags: views, 8, users
---


# Question
Title: Remove Welcome message and "No front page content has been created yet."
The home page of my website contains `blocks` and `views` only. Hence, I want to remove both of the following message-

1. Welcome to my web
2. No front page content has been created yet.

I tried to add following code as described here but I can still see the message `Welcome to my web`

```
unset($page['content']['system_main']['default_message']);

```

# Answer
Both are displayed by the different code, hence you need to unset/remove both.

**1. Create a separate front page template:** In your theme's tempaltes folder make a duplicated of `page.tpl.php` and rename the dulpicate one as `page--front.tpl.php`. Now your all other pages will be handeled by `page.tpl.php` and the only front-page will be handeled by `page--front.tpl.php`.

**2. Edit the `page--front.tpl.php` template:** Now, as you said you are able to remove the message using the code which is in your Question, so go ahead with that.

Secondly, remove the following code from your `page--front.tpl.php`, which will remove the `Welcome......` part.

```
<?php if ($title): ?>
   <h1 id="page-title">
     <?php print $title; ?>
   </h1>
<?php endif; ?>

```
> 4 votes

---
Tags: 7
---


# Question
Title: How to get content type data on basis of assigned taxonomy?
I want to get the data of particular content type on the basis of taxonomy assigned to it. How can I get this using query.

```
$bloglist = db_select('node', 'n')
                    ->fields('n', array('nid'))
                    ->condition('type', 'product_list', '=')
                    ->condition('status', 1, '=')
                    ->orderBy('created', 'DESC')
                    ->execute()
                    ->fetchCol();

        // Get all of the article nodes.
        $bloglists2 = node_load_multiple($bloglist);

```

I have this query to get the data for `product_list` content type. Now I want to add one more condition of taxonomy to get data on basis of taxonomy and content type. How can I do that?

# Answer
> 2 votes
The `EntityFieldQuery` class was built to do pretty much exactly that:

```
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'product_list')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_foo', 'tid', $term_id)
  ->propertyOrderBy('created', 'DESC')
  ->execute();

if (isset($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

```

# Answer
> 0 votes
You have to use the Join statement; what you basically need to do is joining your query with another from another table.

Here is an example that you can use.

`$query = db_select('file_managed', 'fm');
$query->join('field_data_field_image', 'fi', 'fm.fid = fi.field_image_fid');
$query->groupBy('fm.fid');
$query->fields('fm', array('filename', 'uri'));
$query->fields('fi', array('field_image_width', 'field_image_height'));
$query->condition('fi.bundle','image_for_slider','=');
$result = $query->execute()->fetchAssoc();` In this example, the file\_managed table is joined with field\_data\_field\_image; you have to switch those with node and field\_tags.

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


# Question
Title: Is there any way to add the css class to tinymce inside wysiwyg editor
I have several classes defined inside `style.css`, I want `tinymce` to recognize these classes. Below is the popup to configure hyperlinks. It also provide a way to use `css` styles defined already.

I am looking for a way to add the `css` class to `tinymce` inside `wysiwyg` editor in Drupal 7.

# Answer
As you are using wysiwyg module with tinymce library. You should implement the alter function provided by wysiwyg module to add the editor settings.

For tinymce 4.x:

```
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['link_class_list'] = array(
      "Class Example" => "class-example",
    );
  }
}

```

For tinymce 3.x:

```
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['theme_advanced_styles'] = array(
      "Class Example" => "class-example",
    );
  }
}

```

# References
> 1 votes

---
Tags: 7, wysiwyg
---


title: hook_page_alter in Drupal 8

text:
# Question
Title: hook_page_alter in Drupal 8
I am trying to append a twig template on every page . In drupal 7, we basically append it using `hook_page_alter`

```
      function hook_page_alter(&$page) {
      $page['page_bottom']['devel']= array(
            '#type' => 'markup',
            '#markup' => '<div style="clear:both;">' . theme('TEST') . '</div>', );  //add test template on every page at bottom position
 }

```

but in drupal 8 there is no `hook_page_alter` i think.

How to do this??

# Answer
> 10 votes
hook\_page\_alter in Drupal 8:

According to the change record Added hook\_page\_attachments(\_alter)() and removed hook\_page\_build/alter() you should use hook\_page\_bottom:

```
function hook_page_bottom(array &$page_bottom) {
  $page_bottom['mymodule'] = ['#markup' => 'This is the bottom.'];
}

```

You have another issue, theme() is no longer available. But this is another question as it is unclear what you are trying to do with it. Probably you should use the template in a render array `$page_bottom['mymodule'] = ['#theme' => 'TEST'];`.

In D8 all page elements are in blocks now. The best approach would be to provide the extra content in a custom block and place it in the block layout in the bottom of the page. See comment from @Kevin.

---
Tags: 8
---


# Question
Title: Drush on distributed server architecture
We have distributed cloud server architecture - storage, database and webserver. We have installed drush 8 on storage server, as there are project files. We do not have direct ssh to the database or webserver.

When I try to run e.g. `drush cc all` on this storage server, response is error: `PDOException: could not find driver`.

I suppose that problem is, that database server is remote (database is not on storage server), so drush cannot find SQL driver. Settings.php is configured correctly, site is running, only drush has problems.

I read more about drush aliases, or syncing, but I do not think, that this is the solution for my problem. Do you know how to solve this problem and how to use drush on this type of server infrastructure?

Thanks for your help.

# Answer
> 3 votes
If it is possible for your Drupal site to access the database, then it is possible for Drush to access the database. In fact, Drush uses Drupal code to bootstrap, so it should really work the same.

What appears to be the issue here is that you do not have all of the same extensions (esp. the PDO extension) available in php-cli as you do in php-cgi or php-fpm or whatever you are using for your web server. Another issue that can sometimes come up is permissions, if you are running Drush under a different user than the web server.

Finally, it is also worth noting that not all Drush commands go through the Drupal bootstrap to access the database. The sql-\* commands use the database commandline tools (mysql, psql, etc.), so these Drush commands may not work (e.g. if the database commandline tools are not installed).

---
Tags: 8, drush, files
---


title: cache set in custom table not working?

text:
# Question
Title: cache set in custom table not working?
I am trying to set cache with in my custom created cache table which is created with below code:

```
function custom_activity_dashboard_schema() {
  $schema = array();
  $schema['activity_dashboard_cache'] = drupal_get_schema_unprocessed('system', 'cache');
  return $schema;
}

function custom_activity_dashboard_update_7021(){
  $schema = custom_activity_dashboard_schema();
  if(!db_table_exists('activity_dashboard_cache')) {
    db_create_table('activity_dashboard_cache', $schema['activity_dashboard_cache']);
  }
}

```

Table created looks like screenshot :

Just added simplly this code to test if cache entry get created or not :

```
   $cache_time = '+10 minutes';
   $expire = strtotime($cache_time);

  $t_revisions = total_revisions();

  // set cache
  cache_set("total_revisions", $t_revisions, 'activity_dashboard_cache', $expire);

  // get and print cache value
  $cache = cache_get("total_revisions",'activity_dashboard_cache');
  echo $cache->data;

```

with above code there is no entry in database table when I run query to see :

But when I print value by cache get it prints value that was cached on my page.

I am not able to figure out what I am doing wrong and why cacnot I see entires in database table but the value after cache get is printed.

Please suggest what I am doing worng.

With same code I can see entires in database table on my loacl environment.

**UPDATE :**

We are using redis and entity\_cache for full site.

Thanks!

# Answer
> 1 votes
If you are using redis, wouldn't your cache bins not be controlled in the Drupal database anymore? You would therefore need to explicitly set the cache bin to use DrupalDatabaseCache so that it uses the Drupal database in settings.php.

Example:

```
$conf['cache_class_activity_dashboard_cache'] = 'DrupalDatabaseCache';

```

This is how it used to be done with Memcache... Redis should be the same, but check the README:

http://cgit.drupalcode.org/redis/tree/README.txt?h=7.x-3.x

It would explain why you can query this on your local machine, if you only have Redis configuration set for the remote environments running it. You are querying the database, but the cache is pulling from Redis.

This is for Memcache, but sheds more light on excluding certain cache, like cache\_form - which remains in the database. https://www.drupal.org/node/1131468

---
Tags: 7, caching
---


title: YAML Form Conditional Page

text:
# Question
Title: YAML Form Conditional Page
Is there any option in YAML Form to create conditional page? There is already conditional fields option. But I can not find conditional page option.

What actually I want to do is to take some additional information on another page of the form if there some specific value is selected.

# Answer
I was recently at the NYC Drupal meetup where the maintainer mentioned this exact feature. He said that it is on the road map, but it does not exist yet. That said, he is *very* open to patches :)

Incidentally, please note that the YAML form module was renamed to Webform.
> 1 votes

---
Tags: forms, 8
---


title: File Upload Field not working

text:
# Question
Title: File Upload Field not working
I just tried to create a simple **mandatory** file upload field in a custom form like this:

```
public function buildForm(array $form, FormStateInterface $form_state) {

  $form['#attributes'] = array('enctype' => "multipart/form-data");

  $form['pdf_file'] = array(
    '#type' => 'file',
    '#title' => $this->t('PDF File'),
    '#description' => $this->t('PDF files only'),
    //'#multiple' => TRUE,
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
  );

  return $form;
}

```

And that did not work.

When submitting a file (no matter what kind of), i get this error all the time:

"PDF File field is required."

Does anybody have an idea what I am doing wrong?

I am using Drupal 8.2

# Answer
Try removing the required line. Updated code:

```
public function buildForm(array $form, FormStateInterface $form_state) {

  $form['#attributes'] = array('enctype' => "multipart/form-data");

  $form['pdf_file'] = array(
    '#type' => 'file',
    '#title' => $this->t('PDF File'),
    '#description' => $this->t('PDF files only'),
    //'#multiple' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
  );

  return $form;
}

```

**Update**: As upload fields can not be required in PHP, just make it required in JS/jQuery

Add this code to a JS file:

```
$( "#target" ).submit(function( event ) {
  if( $(".pdf-file-field").files.length == 0 ){
    alert("Please add a file");
    event.preventDefault();
  }
});

```

Note: Instead of "event.preventDefault()", you should also be able to use return false.
> 0 votes

# Answer
Try using 'file\_managed' instead of 'file':

```
namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class ExampleFileManagedForm.
 *
 * @package Drupal\mymodule\Form
 */
class ExampleFileManagedForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'example_file_managed_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['pdf'] = array(
      '#type' => 'managed_file',
      '#title' => $this->t('Image'),
      '#upload_location' => 'public://pdf/',
      '#upload_validators' => array(
        'file_validate_extensions' => array('pdf'),
      ),
      '#required' => TRUE,
    );

    $form['submit'] = [
        '#type' => 'submit',
        '#value' => t('Submit'),
    ];

    return $form;
  }

  /**
    * {@inheritdoc}
    */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    dump($form_state->getValue('pdf')); die();

  }

}

```

This will output an array holding the newly created file id:

```
array:1 [▼
  0 => "467"
]

```

and I have tested that the required feature works as expected.
> 0 votes

---
Tags: forms, 8
---


# Question
Title: PHP Snippet: If node is specific node-type and current logged in user is node author
I would like to combine these two php codes to display a block only on nodes of a special node-type and when the current logged in user is the author of the node. Any help very much appreciated!

```
$types = array('middle_content' => 1);
if ($node = menu_get_object()) {
  if (isset($types[$node->type])) {
    return TRUE;
  }
}

```

as found on Block on specific pages and node types

```
global $user;
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

if($node->uid == $user->uid){
return TRUE;
} else {
return FALSE;
}

```

as found on How can I check if the author of the current node is the current logged in user?

# Answer
> 0 votes
Assuming Drupal 7, if you're using PHP Filter, go to the block's settings -\> Visibility settings -\> Pages -\> Show block on specific pages. Select "Pages on which this PHP code returns TRUE (experts only)." Use the following code replacing `my_content_type` with the machine name of your content type.

```
<?php
  $node = menu_get_object();
  global $user;
  if (isset($node) && $node->type == 'my_content_type' && $node->uid == $user->uid) {
    return TRUE;
  }
?>

```

Alternatively, you can select one or more content types under Visibility settings -\> Content types. Then you'd only need to check for the node's author, thusly:

```
<?php
  $node = menu_get_object();
  global $user;
  if (isset($node) && $node->uid == $user->uid) {
    return TRUE;
  }
?>

```

Note the security issues presented by the PHP filter module.

---
Tags: theming, blocks
---


# Question
Title: How can I get pragmatically all certain actions from Rules and Components?
On rules settings page (admin/config/workflow/rules) and components page (admin/config/workflow/rules/components) you can specify action (like 'send e-mail') for each of rule or component.

How can I get pragmatically all certain (e.g.: 'send e-mail') actions from Rules and Components?

# Answer
> 0 votes
This function should do the trick:

```
/**
 * Find all rules with action name matching a string pattern
 *
 * @param $pattern
 *  String pattern to check action names
 *
 * @param $active
 *  Boolean whether to limit the search to active rules only
 *
 * @return
 *  Array with rule names with actions matching the pattern as keys and arrays of rule
 *  action names as values
 */
function search_rules_for_action($pattern, $active_only = TRUE) {
  $active_only = ($active_only) ? array('active' => 1) : array();
  $rules = rules_config_load_multiple(FALSE, $active_only);
  $matching_rules = array();
  foreach ($rules AS $rule_name => $rule) {
    if (method_exists($rule, 'actions') === TRUE) {
      foreach ($rule->actions() as $action) {
        if (method_exists($action, 'getElementName') == TRUE) {
          $action_name = $action->getElementName();
          if (stripos($action_name, $pattern) !== FALSE) {
            $matching_rules[$rule_name][] = $action_name;
          }
        }
      }
    }
  }
  return $matching_rules;
}

```

---
Tags: 7, rules
---


# Question
Title: How to remove title 'Navigation' from Navigation menu in Drupal 7?
How to remove title 'Navigation' from Navigation menu in the left column?

# Answer
You can click "edit block" or go to the Blocks administration page and enter '\<none\>' for block title for the Navigation block.
> 5 votes

# Answer
Drupal 8 has a check box right under Block title, allowing you deselect it and not show the block title.
> 1 votes

---
Tags: theming, routes
---


# Question
Title: Bootstrap subtheme does not apply to main menu
After adding the "html.tpl.php" and "page.tpl.html" to my bootstrap subtheme the layout of my main menu disappeard as you can see in the screenshot below:

As you can see; no bootstrap classes are applied to the menu:

```
<h2 class="block-title">Main menu</h2>
    <div class="contextual-links-wrapper"><ul class="contextual-links"><li class="menu-list first"><a href="/drupal/admin/structure/menu/manage/main-menu/list?destination=node">List links</a></li>
<li class="menu-edit"><a href="/drupal/admin/structure/menu/manage/main-menu/edit?destination=node">Edit menu</a></li>
<li class="block-configure last"><a href="/drupal/admin/structure/block/manage/system/main-menu/configure?destination=node">Configure block</a></li>
</ul></div>
  <ul class="menu nav"><li class="first leaf"><a href="/drupal/lessenrooster">Lessenrooster</a></li>
<li class="collapsed"><a href="/drupal/over-ons">Over ons</a></li>
<li class="leaf"><a href="/drupal/contact" title="">Contact</a></li>
<li class="last leaf"><a href="/drupal/fotogallerij">Fotogallerij</a></li>
</ul>
</section>

```

The bootstrap subtheme however is active:

**EDIT 1**

I indeed did use the wrong .tpl files. I now have copied the correct files to the subtheme (which included the correct .info file). However the .info file does not include the main\_menu region.

```
regions[navigation]     = 'Navigation'
regions[header]         = 'Top Bar'
regions[highlighted]    = 'Highlighted'
regions[help]           = 'Help'
regions[content]        = 'Content'
regions[sidebar_first]  = 'Primary'
regions[sidebar_second] = 'Secondary'
regions[footer]         = 'Footer'
regions[page_top]       = 'Page top'
regions[page_bottom]    = 'Page bottom'

```

After clearing the cache, the main menu did not change.

**EDIT 2**

I started all over again following this guide, but still the main menu looks like crap... and if i copy over the `menu` folder from bootstrap I get an `HTTP ERROR 500` error

# Answer
You must use the template files from bootstrap theme since all those are overridden there. the templates file you should use are under `themes > bootstrap > templates > system`.

copy the page.tpl.php and html.tpl.php from there to your sub-theme.

simply use the same .info file for your sub theme as well. it will give you all the regions. set `"base theme=bootstrap"` in template\_name.info file.

remember to clear the cache
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Views: Multiple Contextual Filters (Taxonomy)
My view should be filtered by multiple taxonomy terms, e.q. : show me all "events" that are tagged by the terms "show", "age over 40" and "outside".

While I can filter by one taxonomy term just fine, it is not working with multiple terms. View Settings:

Relationship: Taxonomy terms on node

Contextual Filters: (term) Taxonomie-Term: Name Allow multiple values is checked!

What am I doing wrong?

I need to filter by the name, not the ID.

# Answer
> 2 votes
I spent lot of time to figure this out, but finally found a solution:

Instead of `Content: The name of Taxonomy (taxonomy_vocabulary_#)` you need to select `Content: Has taxonomy term ID` *Contextual filter* and enable *Allow multiple values* to able to use multiple values in the form of `1+2+3` (for `OR`) or `1,2,3` (for `AND`).

# Answer
> 1 votes
I found the answer: it's not possible :( there's a known bug:

https://drupal.org/node/1762770

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


title: Linkit not working with CkEditor

text:
# Question
Title: Linkit not working with CkEditor
I have installed the Linkit module to a test site.

I have created a profile, set Matchers and created attributes. I have gone into the CKEditor configuration and chosen my Linkit profile, added the Linkit button, saved the configuration and then liberally cleared the cache on my test site (Vagrant running a lamp stack and Drupal 8.)

When I attempt to use the Linkit feature on either a new piece of content, or an existing one, the dialog box appears with all the desired options, however, other than the standard CKEditor link behaviour none of the other attributes work. I cannot set the title, I cannot set the target attribute.

No errors are appearing in the log and I can find no similar problems on line.

Can anyone suggest a reason this is occurring?

# Answer
If the filter not Full HTML, you will need to edit the filter format and enter the attributes on the anchor tag in the settings. If not, they will be stripped out (for security reasons).
> 1 votes

---
Tags: 8, wysiwyg, navigation
---


title: Multiple Contextual Filters

text:
# Question
Title: Multiple Contextual Filters
I am trying to filter views output using Parameters from url with views contextual filter. There are two fields on the content type :

* 1.field\_sku
* 2.field\_width

I simply added the contextual filter for the first one , but as i add the second filter it doesn't work. Is it posibble to add multiple contextual filter to a view?

# Answer
It is because how you get them,contextual filter usually get from url and when you have 2 , you should have 2 parameter in url , as example it should something like "mysite.com/3/reza", this is one step, another step is that you specified in your contextual filter that which arg is for this filter(**put your default value in raw value form url,then you see path componet**), (in my sample 3 is arg(0) and reza is arg(1) ) and if you observe this note it work for you correctly.
> 1 votes

# Answer
The question isn't well described, but i think this is your solution:

Querying the configured multiple contextual filter isn't working as i expected first and I spent lot of time to figure out why, then finally the solution was found:

Instead of `Content: The name of Taxonomy (taxonomy_vocabulary_#)` you need to select `Content: Has taxonomy term ID` *Contextual filter* and enable *Allow multiple values* to able to use multiple values in the form of `1+2+3` (for `OR`) or `1,2,3` (for `AND`). If You have another *Contextual filter* configured, you can separate the query with "/".
> 1 votes

---
Tags: views
---


# Question
Title: Entity View Attachments (EVA) with multiple contextual filters?
I have the following content types which are also organic groups;

Country (group)
Region (subgroup of country)
Area (subgroup of region)
Neighborhood (subgroup of area)
Facilities (subgroup of Neighborhood)

I have a a leaflet map view as an Entity View Attachment with these Entity content settings;

Entity type: Node
Bundles: Country
Arguments: id

I would like create country maps showing all of its corresponding subgroups ie: Regions, Areas, Neighborhoods and Facilities.

Unfortunately I have only managed to get the "Region" content type appearing on the map using the "OG membership: Group ID" as a contextual filter argument and using "current og from context" for "When the filter value is NOT available".

Any ideas for how I can use multiple arguments?

# Answer
> 0 votes
Querying the configured multiple contextual filter isn't working as i expected first and I spent lot of time to figure out why, then finally the solution was found:

Instead of `Content: The name of Taxonomy (taxonomy_vocabulary_#)` you need to select `Content: Has taxonomy term ID` *Contextual filter* and enable *Allow multiple values* to able to use multiple values in the form of `1+2+3` (for `OR`) or `1,2,3` (for `AND`). If You have another *Contextual filter* configured, you can separate the query with "/".

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


# Question
Title: Hide whole edit content link column to users
I'm using drupal 7 and have a view with column edit content link. I want to hide a whole column edit to users and only administrator who can see that column. How can I achieve that without coding since U don't have the permission to access that.

I already tried using Field Permission module but i can't find the solutions either..

# Answer
Set up multiple page views displays with the same path.

You can clone your page views display to accomplish this.

Keep their path settings the same.

In the regular user one, remove the Edit field. Be careful that you are only editing "This page (override)" and NOT "All displays."

In the admin views display, under Page Settings \> Access, restrict your admin view to role=admin.

Re-order the views displays so the most restrictive (admin) views display is first.

To reorder the displays, look for the item "edit view name/description" in the upper-right corner of the screen and expand it to select "reorder displays" - this will take you to a screen where you can drag and drop the views displays. After you put yours in the right order, click "Apply" then save your view.

Hope this helps.
> 2 votes

---
Tags: views, entities, users
---


# Question
Title: How to add a value to an entity reference field set to unlimited values using entity metadata wrapper
Im new to drupal and im trying to perform this operation, can some one help me on how can i add a new value to an entity reference field that its been set to hold unlimited values using the entity metadata wrapper only this is what i have tried

```
$ewrapper->entity-reference-field->set($value);

```

this will overwrite the current value and i want to add to it

# Answer
`$wrapper->field_foobar[] = $additional_value`;

Just change field\_foobar to the machine name of your entity reference field.

The empty brackets insure a new value is added rather than overwriting existing value(s).

Good luck!
> 2 votes

---
Tags: entities
---


# Question
Title: Theme takes different css file from /default/files/css when uploaded to remote server from local
I have zymphonies theme installed in my Drupal 8 website. In my localhost everything was working fine. But when I uploaded the entire files to the remote server the styling of breadcrumbs has gone (it shows as numbered list). As I inspected with the firebug the css file that is taken from default/files/css is different.

There are large number of css files in the default/files/css how does Drupal choose to select a particular css from that set of css files?

# Answer
The location "*default/files/css*" is used to store aggregated CSS files, created by Drupal Core. CSS/JS file aggregation can be enabled/disabled by navigating to *Drupal Performance* settings page, using "***Admin =\> Configure =\> Development =\> Performance***" and enabling checkbox "***Aggregate CSS files***". You can also delete the *.css* files from "*default/files/css*" directory and Drupal will automatically create new one whenever site is visited first time after that. Check the screenshot below:

It is not advisable on production, but if you want to use original files from Theme's CSS directory directly, then uncheck "**Aggregate CSS files**" setting checkbox and Try clearing cache.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: In Drupal 8 i want list my values in new page
I want to display the values of my data from table(**exam\_register**) in the mentioned path.

Listed path how can i bring up values table format. And permission only to admin, i want to setup.

```
 exam_register_list:
 path: 'exam_register/list'
 defaults:
    _form: '\Drupal\exam_register\Form\ListForm'
    _title: 'Exam Page'
 requirements:
    _permission: 'access content'

```

Kindly suggest me sample example of db\_select statement.

# Answer
> 0 votes
Here is the sample code to fetch data from table `node_field_data` and list the data in table format.

```
<?php
/**
 * @file
 * Contains \Drupal\mymodule\Controller\HelloController.
 */
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {
  public function content() {

    $query = \Drupal::database()->select('node_field_data', 'nfd');
    $query->fields('nfd', ['nid','title','type']);
    $result = $query->execute();

    foreach($result as $row) {
      $rows[] = array('data' => (array) $row);
    }

    $build = array(
      '#markup' => t('List of Data')
    );
    $header = array('Nid', 'Title','Type');
    $build['location_table'] = array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows
    );
    $build['pager'] = array(
      '#type' => 'pager'
    );
    return $build;
  }
}

```

The output will be shown as below.

**Updates**

Modify your form to include the result form the controller. Refer the following code.

```
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
# Include controller.
use Drupal\mymodule\Controller\HelloController;

class SampleDataForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'sample_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

$statistics = new HelloController;
$value = $statistics->content();
    $form['table_data'] = array(
      '#markup' => \Drupal::service('renderer')->renderRoot($value['location_table']),
    );
    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }
}

```

---
Tags: 8
---


# Question
Title: Alter a query using hook_views_query_alter() to filter a view by month
I successfully created a view gathering, let's say, events, sorted by date. I also created exposed filters so one could filter the view.

I'm attempting to create another exposed filter that would filter the data on their field\_date, but only by month. I quickly understood that this feature is not provided out of the box, so I managed to implement `hook_views_query_alter()` in the .views\_execution.inc file.

This is what it contains.

```
function djm_views_query_alter(ViewExecutable $view, QueryPluginBase $query){
    if($view->id() == 'calendar'){
        $date_format = $query->getDateFormat("node__field_precise_date.field_precise_date_value", "m");
        $query->addWhere(5, $date_format, 12, "=");
    }
}

```

`$date_format` should return `DATE_FORMAT('node__field_precise_date.field_precise_date_value', '%m')`. The thing is that (I inspected the query my view outputs) the view totally strips my parentheses, percentage signs and, I guess, any special character, so it becomes `DATE_FORMATnode__field_precise_date.field_precise_date_valuem`.

Has anyone ever experience something like this? I can't figure what to do to "fix" this. Am I using the right hook?

# Answer
I managed to get my code working, if anyone is stucked at the same point, you have to use `addWhereExpression` instead of `addWhere`. Here's what it looks like overall.

```
function HOOK_views_query_alter(ViewExecutable $view, QueryPluginBase $query){
    if($view->id() == 'calendar'){
        $definition = array(
            'table' => 'node__field_precise_date',
            'field' => 'entity_id',
            'left_table' => 'node_field_data',
            'left_field' => 'nid',
            'extra' => [ // These are extra conditions views adds by default, I just copied them so it looks like any filter.
                0 =>[
                    'field' => 'deleted',
                    'value' => 0
                ],
                1 => [
                    'left_field' => 'langcode',
                'field' => 'langcode'
                ]
            ]
        );
        $join = Views::pluginManager('join')->createInstance('standard', $definition);

        $query->addRelationship('node__field_precise_date', $join, 'node_field_data');
        // ouptuts "LEFT JOIN {node__field_precise_date} node__field_precise_date ON node_field_data.nid = node__field_precise_date.entity_id AND (node__field_precise_date.deleted = '0' AND node__field_precise_date.langcode = node_field_data.langcode)"

        $date_format = $query->getDateFormat("node__field_precise_date.field_precise_date_value", "m")." = :value";
        $query->addWhereExpression(2, $date_format, [":value" => 12]); // Where 12 is the month I need.
    }
}

```

I'm still opened to better ideas so feel free to share them !
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to fix Zen theme only showing correct breadcrumbs with theme developer module enabled?
I've been going around in circles with trying to get breadcrumbs working as the client wants them on a Drupal 7 site with a custom Zen theme working. I've built the site out and it requires the titles being added to the breadcrumb trail.

The issue is, the crumbs only display correctly with the theme developer module enabled. I know you can set the Zen theme's settings to append content titles to the breadcrumb trail, but this doesn't seem to work (either through specifying through the UI, or by changing the settings in the `MYTHEME.info` file). They do however correctly display with the `theme developer` module enabled. For a host of reasons I can't have a live site with this module enabled.

So,

* 1) How do I get the breadcrumbs working properly and why doesn't it work through the UI or in code?
* 2) How can I resolve this apparent conflict?

# Answer
So, apparently there is a conflict between the Path Breadcrumb module and zen's built in breadcrumbs. When the Path Breadcrumb module is enabled, the zen breadcrumb doesn't append the title to the path. I'm assuming that Path Breadcrumb hooks into and overrides the drupal\_get\_breadcrumb(), although I haven't been able to demonstrate this myself. When I disable Path Breadcrumb, the zen breadcrumbs behave normally. This leaves me with two viable options: 1) hack the current status of the theme breadcrumbs, 2) or code Path Breadcrumbs for the rest of my pages. Neither options seems particularly palatable.
> 1 votes

---
Tags: 7, breadcrumbs, theming
---


# Question
Title: Using multiple AND/OR operators in contextual filters
I'm trying to query my nodes by using a contextual filter in views, however, I am unable to use multiple AND (+) operators and OR (-) operators at the same time. For example:

This works:

```
mysite.com/json/20
mysite.com/json/19+20

```

This does NOT work:

```
mysite.com/json/21,19+20
mysite.com/json/21+27,19+20
mysite.com/json/21+27/19+20

```

Using the "/" causes the additional arguments to be ignored. What I'm trying to tell the view is to return nodes that have a Term ID equal to either 21 or 27 AND also either have a Term ID equal to 19 or 20.

Here's my view:

Here's the contextual filter:

I have tried checking the "Allow multiple values" box, but it does not affect the filter at all. Does anyone have any suggestions?

# Answer
> 0 votes
As a **workaround** I have second *contextual filter* configured and *arguments* are separated with `"/"`. In this case your `/21+27/19+20` should work fine.

Still searching for the real solution.

---
Tags: views
---


# Question
Title: How to replace flag text with custom icon?
I am using flag and views to show a "like" flag in a view. The machine name of my flag is "like". I want to replace the text of the flag with a heart icon. When it is not flagged, it is empty and when flagged, it is filled with red color as happens generally. I do not want to show icon besides text and neither I want to transform my flag into a button. If you have used instagram, you must know that there is a heart icon for a "like" flag. When someone clicks it, it becomes red. Like when you favorite a tweet on twitter.

I found this code, but do not know how to use it for my case. I am not sure whether it is the right code to use.

```
function Your_theme_preprocess_flag(&$vars) {
  $class = ($vars['action'] == 'flag') ? '<i class="fa fa-heart-o">   </i>' : '<i class="fa fa-heart"></i>';
  $vars['link_text'] = $class;
  $title_wishlist = ($vars['action'] == 'flag') ? 'Add to wishlist' : 'Remove from wishlist';
  $vars['link_title'] = $title_wishlist;
}

```

**Note:** I know I have to put it in template.php file of my theme. If you see the post, I took this code from there, but I have multiple flags on my site for example "like" "follow" "bookmark" etc etc. So I want to use this code for the "like" flag. How can i do that I am also interested in learning how to add any icon other than heart and any flag I want.

# Answer
> 1 votes
This code is needed in your *template.php* and a font-icon lybrary added like this one: http://fontawesome.io/icons/ There is a module for that to

---
Tags: 7, views, media, flags
---


# Question
Title: Overwrite jquery.ui.slider.min.css generated by jQuery Update module
The jQuery Update module generates a css file `jquery.ui.slider.min.css` for my website. I need to overwrite the `jquery.ui.slider.min.css` for this slider field. I don't want to loose my changes when we update the jQuery Update module.

What is the best way to add jquery.ui.slider.min.css into my theme?

# Answer
The solution is to insert in your themes template.php the following:

```
function mytheme_css_alter(&$css) {
  if (isset($css['misc/ui/jquery.ui.theme.css'])) {
    $css['sites/default/modules/jquery_update/replace/ui/themes/base/jquery.ui.theme.css']['data'] = drupal_get_path('theme', 'mytheme') . '/mytheme_jquery_design/jquery.ui.theme.css';
  }
}

```
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: How to sort views table columns alphabetically with exposed filters?
I'm working on a table view that will be populated with five columns and many rows of data. I would like to be able to sort the table by selecting a column and then sorting it alphabetically. Ideally, I should be able to sort the table based on any of the columns. Is this possible with views exposed filters? If so, how would I approach this?

# Answer
> 3 votes
Install and configure DataTable module.

Please follow the steps given below:

* Create a new view at admin/build/views/add
* Add fields to show in the table.
* Select **DataTables** as the view style.

> The DataTables module integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function.

# Answer
> 1 votes
After the DataTables module (***with*** "s" ...) is installed, enabled and configured as described in the previous answer, make sure to also review the `settings` of the DataTables format (in the Views UI).

By using that settings-link, you should at least review these settings specific to sorting of the columns of your view:

* Sortable (check to enable, uncheck to disable).
* Default order (Ascending or Descending).
* Default sort (to select the column to be used for sorting when the Views results are first displayed, select "*none*" if you don't want any sorting to start with).

Refer to the (short) video about Create Powerful Tables with the DataTables jQuery Plugin and Views for an intro about it, and how to use it as a views style plugin. Using the "settings" link for this views style, you can specify all sorts of dataTables options/features. In the above video starting from around 3:00 you see many of them.

### Example

Below is a screenprint of such display using DataTables. It's a display I created using Views (of course) with a table with:

* 8 fields in (defined in my view).
* 5 table columns for the 5 fields I have decided to always show.
* 3 table columns which I defined as "hidden and expandable" (within the DataTables settings after you select DataTables as the Views style).

Here is how the DataTables display looks like:

### Hiding selected columns

If you only have 5 columns, they should easily fit within the width of a screen. But if you have many more (eg 10 or even more), you may want to use ***hide selected columns*** (which is different from "exclude from display" in standard Views!).

This technique is also used in the example above. For each row there is a link '***Show Details***' (in its 1st column). If you click on one (or more) of them, the hidden fields of such row are shown below that row (with grey background here) and the link you clicked changes to '***Hide Details***'. Obviously, I've not done any styling for such expanded row (hence the grey background, etc). But you can see the 3 fields that were initially hidden.

### Bonus

Assume none of the rows are shown expanded, and you type "`Basic`" in the DataTables search box. It will then dynamically (in the browser, no server calls) reduce the table display to only those rows with `Basic Page` as value for "Type". But wait, there is even more: if you'd type a string like part of "`21:15`" instead (hidden in some of the rows), it will also dynamically reduce the table display to only those rows, like the expanded row shown in the screenprint. But wait, there is even (quite) a bit more: a search string like "basic 21:15" will filter the rows to a combination of both search strings. For only this one feature I often recommend the amazing DataTables module, one of Drupal's hidden gems I think. And then there are the other features like pager, sortable columns, etc.

### Remarks

* Make sure to use the 1.9.x version of the DataTables library (not 1.10.x or above), as mentioned also on the project page, which states:

> While there is work in the 7.x-2.x branch to upgrade to the latest DataTables version (1.10.x), the 7.x-1.x branch only works with DataTables \<= 1.9.x. Since it's not listed in the projects download page, you will have to download it directly.
* When creating a view, disable the pager of your view, since DataTables provides its own paging features (the video talks about that starting from 2:05).

---
Tags: 7, views
---


# Question
Title: What is difference between a custom block and a Bean block?
As I am new to Drupal 7, I want to understand the difference between **custom** block and **Bean** block.

Can someone please help me on this?

# Answer
## Custom block

If you'd created/configure a block using the typical Admin UI, located at `admin/structure/block`, you enter configuration options like visibility, block title, etc. That's what I would consider as "an" example of a ***custom block***.

And when some module that you enable causes some block to become available (related to that module), it could be considered as a similar block, though "custom" does not apply to it (maybe call it a ***module delivered block***?).

## Bean block

Bean blocks are (also) blocks, but what is special about them is that you use the Bean module to create such blocks. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Combined with the options available for granting **Bean permissions**, it gives you a lot of flexibility about how exactly you want to use this (great) module.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into ***fieldable entities***.

## A rising star ...

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has about 32K reported installs. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

> **This module has been included with Drupal 8 core**. Refer to this issue for more information.

I'm not aware (yet) of any other contributed module that "only" started in D7, and made it right into core in the very next major Drupal release ... If there are other modules with a similar track record, I doubt there would be many of them ...
> 1 votes

---
Tags: 7, theming, blocks
---


# Question
Title: Replace integer field value with stars in twig template
I have a Drupal 8 site with a node type exposing a "difficulty level" field which is an integer choosen from a list (1 to 5). Current onsite display is : "difficulty: 3". I would like to replace the value "3" by three black stars and two white ones to picture "3/5" (done via CSS background images).

In field--field-difficulty.html.twig I have replaced item.content by:

```
{% for i in range(1, 5) %}
  {% if (loop.index <= item.content) %}
    <span class="active">*</span>
  {% else %}
    <span class="active"> </span>
  {% endif %}
{% endfor %}

```

But this keep giving me five * displayed, just like if the {% if %} statement was always true. Can someone give me a hint on this please ?

# Answer
For the field template there are two approaches to get the integer number from a field:

**Node object**

```
{% set difficulty = element['#object'].field_difficulty.value %}
{% for i in range(1, 5) %}
  {% if i <= difficulty %}

```

**Find the rendered number**

You can try to find the number in #markup:

```
{% if loop.index <= item.content['#markup'] %}

```

The node object is the better approach, because the way how the number is rendered can change when updating the code or changing the configuration.
> 2 votes

# Answer
Maybe add the field value or content to a class, and then use that selector to set a background image.

```
{% for item in items %}
  {# set a new variable #}
  {% set star_class = 'star' ~ item.content %}
  {# add class to attributes for the item, item.content may not be appropriate here. Use kint/dump to see more info on item variable. #}
  <span{{ item.attributes.addClass(star_class)}}>{{ item.content }}</span>
{% endfor %}

```

https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

Then you can apply your `background`, `width`, `text-indent`, `display`, etc... to allow for the additional widths for styles. Probably done in a pseudo-element.
> 1 votes

---
Tags: theming, 8, entities
---


# Question
Title: PCI compliance with authorize.net payment- Drupal7.x
I am looking for a solution where I can collect simple payments from my users but not collect the payment details on drupal server. SO i need to

1. Attach a payment component to a webform
2. User can fill up the details and click on pay
3. On clicking on pay user will be redirected to Authorize.net servers where the user can fill the details and on successful completion return back to Drupal end.

I am using webform\_pay module to achieve this. It satisfies most of the points but only problem with this module is it collects the payment details on drupal server which I dont want. Any suggestion?

# Answer
It's pretty easy to implement Authorize.net PHP SDK for this purpose. I also had started with Webform Pay (6.x) but it was not reliable in the fact that if a payment failed, or you wanted to do different form widgets (radio, select, text) to represent dollar value, it wasn't very feasible.

I wound up creating my own module that implements specialized Form API fields (CC number, CC date, CC cvv): https://www.drupal.org/project/creditfield

If you are comfortable with Form API, it is very easy to construct simple payment forms (simple donations, bill pay), and then handle the payment submission in your form submit handler. This module makes it possible to create one or more standard forms with Form API without having to implement the same validations all the time on the credit card fields.

I never had a need to store any data locally, not even the user information. If the payment did not succeed, the error was caught and logged and the user was asked to try again. If it succeeded, all of the submitted information was visible in the Authorize.net transaction logs. Check the SDK payload information to see what is available. It's been a while since I have done one, but you could use the card authorization method to create a transaction to be validated, and then perform the transaction.

For other methods, like off-site payment on a service like Authorize.net, you will probably need the applicable walkthrough. It also looks like the Webform Pay module has been abandoned with no stable Drupal 7 release, so this could be a good opportunity to roll up your sleeves and learn Form API + menu routes.

https://developer.authorize.net/api/reference/index.html#payment-transactions
> 0 votes

---
Tags: 7, payment-gateways
---


# Question
Title: field_view_value() with product reference field doesn't display attributes
I'm trying to render a product reference field using field\_view\_value() - which works except for the attribute options don't render. If it's rendered normally on a node, or in views then the attributes display as normal. Any ideas how to fix this?

```
$product_obj = node_load($nid);
$product_field = field_get_items('node', $product_obj, 'field_product');
$cart = field_view_value('node', $product_obj, 'field_product', $product_field[0]);

print render($cart);

```

# Answer
Instead of using field\_get\_items/field\_view\_value try field\_view\_field.

```
$product_display = node_load($nid);
$add_to_cart = field_view_field('node', $product_display, 'field_product');
$add_to_cart['#label_display'] = 'hidden';
$cart = drupal_render($add_to_cart);

```
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Views, Taxonomy, multiple parameters using contextual filters
A view has been created to display related content types via their taxonomy terms, using contextual filters. Currently the view is able to display content based on the first param eg. about The goal is to abe to display content based on the second param, being the child term and hide the parent eg. about/meet-the-team.

Here is a break down

Url : page/parent term

parent term Content item referenced to parent term Content item referenced to parent term Content item referenced to parent term Content item referenced to parent term

Url: page/parent term/child term

child term Content item referenced to child term Content item referenced to child term Content item referenced to child term Content item referenced to child term Content item referenced to child term

Url: page/parent term/child term/child child term

```
Content item referenced to child child term
Content item referenced to child child term
Content item referenced to child child term
Content item referenced to child child term
Content item referenced to child child term
Content item referenced to child child term
Content item referenced to child child term

```

And this will continue on

Eg Url: page/parent term/child term/child child term/child child child term/child child child child term.

# Answer
To do like this too much *contextual filters* needed, i think it's better to manage the URL in template.php and/or with hook\_menu and use views\_embed\_view() to pass arguments to Views

```
$arg =array (1,2,3);
print views_embed_view('view_name', 'page_1', implode('+',$arg)); // OR
print views_embed_view('view_name', 'page_1', implode(',',$arg)); //AND

```
> 0 votes

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


title: Rules Invoke Event doesn't work

text:
# Question
Title: Rules Invoke Event doesn't work
My aim is to trigger a rule via Ajax.

Until now I create a custom module called "*iscrizione*"

Here my iscrizione.rules.inc

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

$items['iscrizione_evento'] = array(
  'label' => 'Iscrizione all\'evento',
  'group' => t('Links'),
  'variables' => array(
    'path' => array(
      'type' => 'array',
      'label' => t('Path accessed'),
      'description' => t('The path which has just been accessed.'),
    ),
    'account' => array(
      'type' => 'user',
      'label' => t('updated user'),
    ),
  ),
);

return $items;
}

```

Here my iscrizione.module

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

$items['conferma/%'] = array(
'title' => 'Conferma Iscrizione',
'page callback' => 'iscrizione_evento',
'page arguments' => array(1),
'access arguments' => array('access content'),
);

return $items;
}

function iscrizione_evento($arg) {
echo $arg;
// rules_invoke_component('rules_stampa_messaggio', $arg);
rules_invoke_event('rules_iscrizione_iscrizione_evento', $arg);
}

```

I tried both functions (invoke event and component), but if I type the url I can see only the $arg printed.

No action was fired (as actions I put " Show a message on the site" and a "Create entity")

Any help?

# Answer
> 2 votes
Within `$items` of your `iscrizione_rules_event_info()`, you used `iscrizione_evento`. So in your `iscrizione.module` you should refer to that. Try this variation of it:

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

$items['conferma/%'] = array(
'title' => 'Conferma Iscrizione',
'page callback' => 'iscrizione_evento',
'page arguments' => array(1),
'access arguments' => array('access content'),
);

return $items;
}

function iscrizione_evento($arg) {
echo $arg;
// rules_invoke_component('rules_stampa_messaggio', $arg);
rules_invoke_event('iscrizione_evento', $arg);
}

```

Maybe it would also help if you'd slightly adapt the **readability** of your code, by not using `iscrizione_evento` for different things. How about, eg, these variations of it:

* `menu_iscrizione_evento`.
* `rules_event_iscrizione`.

# Answer
> 2 votes
Using the accepted answer I fixed my code, but then I ran into another problem, i.e.:

> Notice: Undefined index: name in EntityMetadataWrapper-\>debugIdentifierLocation() (linea 246 di /home/contactbologna/public\_html/sites/all/modules/entity/includes/entity.wrapper.inc).

This new problem was around the variables type on event info.

The final version of the code now looks like this:

```
function iscrizione_module_menu() {
  $items['conferma/%'] = array(
  'title' => 'Conferma Iscrizione',
  'page callback' => 'iscrizione_evento_callback',
  'page arguments' => array(1),
  'access arguments' => array('access content'),
);
return $items;
}

function iscrizione_evento_callback($arg) {
//global $user;
if (user_is_logged_in())
{
  $user = user_uid_optional_load();
}
$path[] = $arg;
// rules_invoke_component('rules_stampa_messaggio', $arg);
rules_invoke_event('rules_event_iscrizione', $path, $user);
}

```

and

```
function iscrizione_module_rules_event_info() {
  $items = array();
  $items['rules_event_iscrizione'] = array(
    'label' => 'Iscrizione all\'evento',
    'group' => t('Links'),
    'variables' => array(
      'path' => array(
        'type' => 'array',
        'label' => t('Path accessed'),
        'description' => t('The path which has just been accessed.'),
      ),
      'account' => array(
        'type' => 'user',
        'label' => t('updated user'),
      ),
    ),
  );
return $items;
}

```

---
Tags: rules
---


# Question
Title: What to do when Drupal views module doesn't output what you want?
When a user search for a word the view should output its translation and any other vocabs that might be similar to it ( using Taxonomy terms ).

This works as the following:

The similar vocabs are actually another view that I pass ( Taxonomy ids ) to its URL as a contextual filter and it outputs all words that has the same Taxonomy term or terms. This view a lone by it self works fine when you pass Taxonomy terms manually. It doesn't produce any duplicates since I handled that by choosing 'Query settings: DISTINCT' and using aggregation.

However when I combine it with the other view and pass the Taxonomy terms using the Views UI it produce duplicates.

What should I do? Is there a way to write the view code manually or something like that?

# Answer
> 1 votes
> Is there a way to write the view code manually or something like that?

You could easily setup a menu route and controller (or page callback in D7) to serve the same purpose. The controller would execute the query (provided by you) and return the results / page output as a renderable array.

However, there are many variables in between, so it would be hard to provide all the code.

Here is a walkthrough for D7 to starting to code your own route and callback: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7.x

Here is one for D8: https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

It would be a good opportunity to learn how to extend Drupal and 'take control' when you don't get the result you want with Views, or, just to have more control in general.

---
Tags: views
---