# Question
Title: How to make a collapsible fieldset in my theme?
I want to have collapsible fieldsets in my Drupal 7 website in add content. I added this in `html.tpl.php` of my theme:

```
<?php
print $styles;
drupal_add_js('misc/form.js');
    drupal_add_js('misc/collapse.js');

?>

```

But nothing happend to my fieldsets. Here's a sample code of fieldset I have used:

```
<fieldset id="fieldset-id" class="collapsible">
  <legend><span class="fieldset-legend">Fieldset title</span></legend>
  <div class="fieldset-wrapper">
  <div class="fieldset-description">Fieldset description</div>
     Fieldset content
  </div>
</fieldset>

```

What is the problem?

# Answer
> 1 votes
Your theme might include jQuery 1.9. With this, I observed in Drupal 7.34 that fieldsets would not work (always shown collapsed, unclickable). Also CKEditor would not load (using the `ckeditor` module) and there might be other JavaScript related misbehavior.

To solve this, use jQuery 1.8 instead. I recommend the module `jquery_update` to handle jQuery versions in Drupal.

# Answer
> 1 votes
I think that the libraries are others.

This example works for me:

```
$fieldset = array(
        '#type' => 'fieldset',
        '#attached' => array(
          'library' => array(
            array('system', 'drupal.collapse'),
          ),
        ),
        '#attributes' => array(
          'class' => array('collapsible', 'collapsed')
          ),
        ),
     );

```

Read more about this at Fieldsets in D7, collapsed and collapsible not working.

# Answer
> 0 votes
You should do that using the Form API.

Here's an example implementation through a custom module:

```
/**
 * Sample form.
 */
function MYMODULE_sample_form() {
  $form['sample'] = array(
    '#type' => 'fieldset',
    '#title' => t('Sample fieldset'),
    '#description' => t('Sample fieldset description'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['sample']['sample_textfield'] = array(
    '#title' => t('Text field'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Submit the form'));

  return $form;
}

```

To display the form above, use the following code:

```
<?php
$form = drupal_get_form('MYMODULE_sample_form');
print drupal_render($form);
?>

```

However, it's not quite clear where exactly you want to display this. Sounds as if you want to alter some node creation form; if that is the case, post a comment and I'll update the example code.

---
Tags: 7, forms
---


title: Visitor Counter

text:
# Question
Title: Visitor Counter
Is there a way of finding out the number visitors of a drupal website, where they go to and where they are from. Google Analytics come to mind (or if any other module can do a better job).

# Answer
If you also want to track user interactions with forms/nodes/etc you might want to look into Events Log Track - https://www.drupal.org/project/events\_log\_track

With that said adding Google Analytics is also super easy via the module. https://www.drupal.org/project/google\_analytics

*** Edited to comment on Visitors module as there appears to be a bug that was introduced into it in D8\*** You might also want to keep an eye on the visitors module I used it with great success in D7 . It's available in D7 and D8, but there appears to be a bug mentioned with the D8 install that is being worked on. - https://www.drupal.org/project/visitors.
> 0 votes

---
Tags: google-analytics
---


# Question
Title: How can i pass JavaScript variables back to PHP Controller in Drupal 8
I have a custom module which uses a Javascript library called Bootstrap Table. Among other things, this library allows me to create tables with clickable rows. Currently, I can pass variables from the PHP Controller into the Javascript library. These variables are used to feed the fields in the table.

What I want to do next, is to define an event (when a row is clicked) which would then return the value of the row and pass it back to the PHP controller.

The controller would use this returned variable to perform some specific action and update the information displayed in the table.

As far as I know, I should use AJAX, but so far I have not been able to accomplish what I want.

This is some of the info I have found.

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

How do I pass JavaScript variables back to PHP?

controller function use with ajax

# Answer
> 1 votes
You're right, you'll need to create a php controller for this task.

This involves a number of steps

In your custom module you'll need to add your controller in /yourmodules/src/Plugin/rest/resource

In this example I created one called HelloRest.php

```
<?php

namespace Drupal\my_module\Plugin\rest\resource;

use Drupal\Driver\Exception\Exception;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
/**
 * Provides a resource for accepting rest calls
 *
 * @RestResource(
 *   id = "hello_rest",
 *   label = @Translation("Hello Rest Handler"),
 *   uri_paths = {
 *     "canonical" = "/hello/{name}",
 *     "https://www.drupal.org/link-relations/create" = "/hello"
 *   }
 * )
 */

class HelloRest extends ResourceBase {
    /**
     * Responds to GET requests.
     *
     * Returns a watchdog log entry for the specified ID.
     *
     * @param int $id
     *   The ID of the watchdog log entry.
     *
     * @return \Drupal\rest\ResourceResponse
     *   The response.
     */

    public function get($name = '') {
        $response = ['message' => 'Hello '.$name];
        return new ResourceResponse($response);
    }
}

```

Then I enabled the route using the REST UI module here https://www.drupal.org/project/restui to do so. There is probably another way to enable the route but I'm not sure how. Also you want to make sure every role you need has permissions to access the rest call. In my case I wanted everyone that visited the site to have access so I had to make sure that anonymous users had access to that route.

Now that you have that created all you have to do is perform an ajax call to it to get your response back.

```
jQuery.ajax({url: location.protocol + "//" + location.host + "/hello/"+name+ '?_format=json", success: function(result){
        console.log(result.message);
}}

```

---
Tags: 8, javascript, ajax, routes
---


title: Load a full menu with active trail

text:
# Question
Title: Load a full menu with active trail
I need to load a full menu for navigation in a custom theme with active trail, and can't find any way to do it, but that can't be right. I can't imagine such an obvious and widespread use-case having no core support, but I've scoured menu.inc and found nothing. The functions offered range from inadequate (no active trail) to completely unusable (menu is missing children for the CSS dropdowns/submenus outside the active trail, and even empty when needed most, such as on broken links).

I've tried using the following functions in my THEME\_preprocess\_page hook:

* menu\_tree (only renders siblings of the active trail--the navbar can even end up empty)
* menu\_tree\_page\_data (same result)
* menu\_tree\_all\_data (contrary to the documentation--luckily--this method does not return hidden items, but there's no active trail)

So far as I can tell, my only options are to copy and rewrite several functions from menu.inc, or to load two separate menus and apply deep analysis/merging to find and duplicate the active trail from the incomplete menu into the complete one--and this is just as bad because the data structures don't match. Is there no other way to get a full menu with active trail?

Also, what if I do go with the latter option using menu\_tree\_all\_data? Will I end up exposing links that aren't properly going through access checks, or have similar issues? How the heck does Drupal itself load a full menu, like the Navigation menu which doesn't go away while visiting other parts of the site?

I did find another nearly identical question but no one answered it and that was 9 months ago. This is for a project that's already running well behind schedule due pretty much exclusively to unforseen Drupal-related issues, so any pointers are much appreciated.

EDIT: Whoops...tried to be thorough and missed a major detail :P I'm on Drupal 7.

# Answer
> 0 votes
First of all, I have to say, the menu system that is implemented in Drupal is, in my eyes, **really** dodgy. You'll encounter stuff you simply cannot realize with the core implementation, which you would think is basic use cases.

Depending on which Drupal major you are using, I'd suggest taking a look at the Menu Settings per Content Type (CTM) when your at **D6**. This module will enable you to setup menu settings per content-type, which contains an option to "expand items by default".

On D7 this feature is built-in, when you create a menu item under `admin/structure/menu` you will find a checkbox `Show as expanded`, which will do the same.

**Edit:**

# Menu block module

I was just thinking about it again, and remembered that menu\_block module also will help you out in this situation. You can create a block which has a lot more options then al the built-in menu functionalities. Also there is an option: `Expand all children of this tree.`, I think that'll be your ticket out of this problem, and should leave the burdon for your clients to actually manually expand them

# Answer
> 2 votes
I just want to add my experience to the lot. I had similar issues using Drupal menu. The solution I used is:

* Set all menu items with children to "Expanded". This as to be done manually: `Structure > Menus > List links`, edit links which has children, check the `Show as expanded` checkbox.
* Use `menu_tree_page_data` function (example: `$menu_tree = menu_tree_page_data('main-menu')`) to get the menu, with all its children AND with active trail.
* Create a renderable array using `menu_tree_output` function (example: `$renderable_array = menu_tree_output($menu_tree)`) to prepare the menu for rendering.
* Use the renderable array as content for my custom block, but you could call `drupal_render($renderable_array)` to get the rendered HTML representing the menu.

# Answer
> 1 votes
I ended up writing my own "menu\_tree\_full\_data" function that builds the menu, still using all the appropriate cache facilities, etc. Also take note any Drupal Core developers around: this is how you write a function that *isn't* incomprehensibly nested 9 blocks deep.

```
function menu_tree_full_data($menu_name) {
    $tree = &drupal_static(__FUNCTION__, array());

    // Check if the active trail has been overridden for this menu tree.
    $active_path = menu_tree_get_path($menu_name);

    // Generate a cache ID(cid) specific for this page
    $item = menu_get_item($active_path);
    $cid = "links:$menu_name:full:{$item['href']}:{$GLOBALS['language']->language}";

    // Did we already build this menu during this request?
    if(isset($tree[$cid]))
        return $tree[$cid];

    // If the static variable doesn't have the data, check {cache_menu}.
    $cache = cache_get($cid, 'cache_menu');
    if($cache && isset($cache->data)) {
        $tree_params = $cache->data;
        if(isset($tree_params))
            return $tree[$cid] = menu_build_tree($menu_name, $tree_params);
    }

    $tree_params = array(
        'min_depth' => 1,
        'max_depth' => null,
    );
    // Parent mlids; used both as key and value to ensure uniqueness.
    // We always want all the top-level links with plid == 0.
    $active_trail = array(0 => 0);

    // Find a menu link corresponding to the current path. If $active_path
    // is NULL, let menu_link_get_preferred() determine the path.
    $active_link = menu_link_get_preferred($active_path, $menu_name);
    // The active link may only be taken into account to build the
    // active trail, if it resides in the requested menu. Otherwise,
    // we'd needlessly re-run _menu_build_tree() queries for every menu
    // on every page.
    if(@$active_link['menu_name'] == $menu_name) {
        // Use all the coordinates, except the last one because there
        // can be no child beyond the last column.
        for($i = 1; $i < MENU_MAX_DEPTH; $i++) {
            if($active_link['p' . $i])
                $active_trail[$active_link['p' . $i]] = $active_link['p' . $i];
        }
    }

    $parents = $active_trail;
    do {
        $result = db_select('menu_links', NULL, array('fetch' => PDO::FETCH_ASSOC))
            ->fields('menu_links', array('mlid'))
            ->condition('menu_name', $menu_name)
            //->condition('expanded', 1)
            ->condition('has_children', 1)
            ->condition('plid', $parents, 'IN')
            ->condition('mlid', $parents, 'NOT IN')
            ->execute();
        $num_rows = FALSE;
        foreach($result as $item) {
            $parents[$item['mlid']] = $item['mlid'];
            $num_rows = TRUE;
        }
    } while($num_rows);
    $tree_params['expanded'] = $parents;
    $tree_params['active_trail'] = $active_trail;

    // Cache the tree building parameters using the page-specific cid.
    cache_set($cid, $tree_params, 'cache_menu');

    // Build the tree using the parameters; the resulting tree will be cached by _menu_build_tree().
    return $tree[$cid] = menu_build_tree($menu_name, $tree_params);
}

```

Aside from changing the cache key, commenting out the `expanded` condition, dropping the no-longer-relevant `$max_depth` and `$only_active_trail` arguments, and the branching on `$item['access']` (whether the user can access current page), this is logically equivalent to `menu_tree_page_data`. 4 of the extra 5 levels of nested code blocks could be just as easily removed from the original function as well.

Now I can finally just load the menu I need as I need it with no mess or fuss, like so:

```
function THEME_preprocess_page(&$vars) {

    if(@$vars['main_menu']) {
        $menu = variable_get('menu_main_links_source', 'main-menu');
        $vars['main_menu'] = menu_tree_output(menu_tree_full_data($menu));
    }
}

```

And use it in my theme like so:

```
<?= render($main_menu); ?>

```

Or something like so (this is how a lot of other themes seem to handle it, though it just makes a mess for me):

```
<?php if ($main_menu): ?>
    <nav id="primary-menu" role="navigation">
        <?php print theme('links__system_primary_menu', array(
            'links' => $main_menu,
            'attributes' => array(
                'class' => array('links', 'inline', 'clearfix'),
            )
        )); ?>
    </nav>
<?php endif; ?>

```

Of course you still have to define or include the menu\_tree\_full\_data function somewhere as well. For me, it goes in a "Shorthand" module I maintain with various simplified object-oriented API wrappers, where it'll also get turned into a method in SH\_Menu class and get loaded on demand with shorthand\_load\_menu(); (Note you've gotta switch `__FUNCTION__` for `'menu_tree_full_data'` if you do something similar, or the caching won't work correctly.)

---
Tags: theming, navigation
---


# Question
Title: Drupal 7 Webform - Find input regardless of fieldset
I have created a webform hook (using hook\_form\_alter) which searches for a particularly named input and appends an ID for JS code to make changes on the front end.

It works fine however I have come across an issue where if that input is made part of a fieldset, it can no longer find it. This is to do with how the $form array is rearranged to include children inputs in the fieldset array.

My question is: how do I find an element by name regardless of whether it is part of a fieldset or not?

This is the code I'm using, which works fine for parent level inputs but not when it is part of a fieldset. How do I get this to work where I don't need to know what the fieldset is called (because I won't always know).

```
function MODULE_form_alter(&$form, &$form_state, $form_id){
  $form['submitted']["certain_name"]['#default_value'] = '';
  $form['submitted']["certain_name"]['#attributes']['id'] = 'new-id';
  $form['submitted']["certain_name"]['#ajax'] = array(
    'event'    => 'change',
    'callback' => 'module_js_lookup(this.value)'
  );
}

```

# Answer
Unfortunately, to access/modify and form fields in Webform using the form API and hooks, you have to know/include the fieldset hierarchies in the array calls as you observed.

For example:

```
$form['submitted']["fieldset_machine_name"]["certain_name"]

```

or

```
$form['submitted']["outer_fieldset_machine_name"]["inner_fieldset_machine_name"]["certain_name"]

```

Rather than set a callback function on the form element in your hook\_form\_alter, you may just need to find the element type with particular machine name using vanilla javascript or jQuery in either:

* your theme's assorted javascript files as Drupal behavior
* the custom module as a separate script
> 0 votes

---
Tags: 7, webforms
---


title: Read-only email field

text:
# Question
Title: Read-only email field
We would like to add a *readonly* option to a email webform field when the field uses the email address for the logged-in users.

The webform email field has an option to "Set the default value of this field to the user email, if he/she is logged in." and to toggle a "readonly" option.

How would we go about achieving this?

# Answer
There's two possible approaches you could take here:

1. Add a custom hook\_form\_alter to test in php if the user is logged in, and then set the disabled/locked attribute to the field.
2. Add javascript that on page load checks to see if the body has the "logged-in" class and if the field is already populated/has a value; then disable/lock it.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How can I show only webform content by excluding header,footer?
I wan to show only the form elements in an modal(popup), but am not able to achieve that. Along with the form elements header, footer is also showing. So how can I remove those things for specific webform?

I tried by creating a template file with the name `webform-form-162101.tpl.php`. But it doesn't helped me. Please share some other way to achieve this.

# Answer
If your lightbox/modal behavior can target just a section of HTML markup on the page. Some modal plugins only open full webpages, others allow targeting sections of your DOM. It sounds like you're currently using the latter. Here's an example of a lightweight modal plugin that allows targeting html embedded on the page as opposed to an entire webpage (but if you're comfortable with javascript, you could implement this yourself too): https://robinparisi.github.io/tingle/

If you need the webform available on multiple pages, you could set the webform to be available as a block and then target that block to load in the modal.

To enable showing the webfom as a block, go to the Form Settings subtab/page of the webform, scroll down and expand the ADVANCED section and check the checkbox (shown below).
> 0 votes

---
Tags: 7, theming, forms, webforms
---


# Question
Title: Trying to get property of non-object in i18n_langcode() (line 229 of i18n.module) and a bunch of other property of non-object notices
Recent logs lies to me.

I even did a `dpm($node->title);` with devel and indeed it's there.

I have like 6 pages of these notices that appear per page load. They are all different locations but they all have the same error type, property of non object. Has anyone experienced something like this?

I don't think it's a hack, at least not a Core hack, cause Core has been updated several times.

Ugh, soo strange.

---

This is hard to debug, here is another example

As you can see, I created a variable `$test = i18n_language()->language` and xdebug tells me `$test = "en"` yet on line 230 it fails to get the value according to the log.

# Answer
> 1 votes
Finally solved this mystery.

I was able to narrow it down to a bean block in the site's footer. Upon inspecting all of the bean's block display fields

Disabling this field fixed the issue. Where is it coming from? IDK yet. I will update once I know. Seems like custom module.

**Update**

Yep, turns out Featurette image link is coming from a custom module. Notice the big error in line 24 and line 30.

More errors here, what a mess!

# Answer
> 0 votes
Based on the information posed in the question, and your theme switch test- it sounds like you have some custom templates or template.php functions in your theme that call/use a variable (in this case, probably the title field) without first checking if the variable is actually set.

check for any custom php conditionals or processing of your custom fields/entities in your templates. Ideally, you'll want to wrap any operation that does something with them in a conditional. For example:

```
if ( array_key_exists('myCustomVariable',$content) && isset($content['myCustomVariable']) ) {
  print render($content['myCustomVariable'];
}

```

Also worth noting, the *title of your individual node types is **not available** (by default) in the page.tpl.php or html.tpl.php templates* without some modifications and custom hooks in your theme to make the variable available.

---
Tags: 7, debugging
---


# Question
Title: Varnish Cache - Sometime Hit and sometime Miss on the same page
It's from the same page. When I first load the page, it's "MISS" if I refresh the page it will "HIT"

If I go back to my website home page and come back to the same page again it's "MISS" I refresh the page and its "HIT"

Do you know why varnish is behave like that? I'm using varnish 3

Thanks for your help guys.

**HIT**

```
Accept-Ranges:bytes
Age:61
Cache-Control:public, max-age=3600
Connection:keep-alive
Content-Encoding:gzip
Content-Language:en
Content-Type:text/html; charset=utf-8
Date:Wed, 18 Oct 2017 01:14:40 GMT
Etag:"1508289218-0"
Last-Modified:Wed, 18 Oct 2017 01:13:38 GMT
Server:Apache
Vary:Accept-Encoding
Via:1.1 varnish
X-Content-Type-Options:nosniff
X-Drupal-Cache:MISS
X-Frame-Options:SAMEORIGIN
X-Generator:Drupal 7 (http://drupal.org)
X-UA-Compatible:IE=edge,chrome=1
X-Varnish:83548823 83548200
X-Varnish-Cache:HIT

```

**MISS**

```
Accept-Ranges:bytes
Age:0
Cache-Control:public, max-age=3600
Connection:keep-alive
Content-Encoding:gzip
Content-Language:en
Content-Length:22462
Content-Type:text/html; charset=utf-8
Date:Wed, 18 Oct 2017 01:13:39 GMT
Etag:"1508289218-0"
Last-Modified:Wed, 18 Oct 2017 01:13:38 GMT
Server:Apache
Vary:Accept-Encoding
Via:1.1 varnish
X-Content-Type-Options:nosniff
X-Drupal-Cache:MISS
X-Frame-Options:SAMEORIGIN
X-Generator:Drupal 7 (http://drupal.org)
X-UA-Compatible:IE=edge,chrome=1
X-Varnish:83548200
X-Varnish-Cache:MISS

```

# Answer
> 1 votes
What you describe really looks like cache expiration. Note that the default TTL for cache in Varnish is 120 seconds only.

You would need to adjust Varnish TTL to something higher, obviously.

---
Tags: caching, proxies
---


title: CSS styles per page

text:
# Question
Title: CSS styles per page
I'm trying to apply CSS styles to a specific node (all part of the same content type).

I'm using these CSS styles.

```
.page-node-534 .featureWrap article {
  position: relative;
  left: 112px;
}

```

This isn't working. I checked the body and it contains the class .page-node-534.

What am I doing wrong?

# Answer
As a general suggestion, you may want to utilize the following modules on your site to avoid having id specific css:

These modules allow content managers/site builders to apply general classes to menu items, blocks, and nodes that are agnostic to the Drupal assigned IDs. (particularly helpful if a piece of content is manually added on a device environment and manually added on a staging/test environment, and prod environment - since auto assigned IDs will likely be different)

---

If you are trying to apply css to a class using one of these modules, context module, or even the system generated classes or IDs and still do not see your styles, here are some troubleshooting suggestions.

Open the css file being loaded and check for your latest styles. If you see the edits there, there's most likely an error in your css targeting. If you don't see the updates, check the following:

1. Check to make sure your css file is properly being loaded in your theme or module.
2. Clear the Drupal (and possibly Varnish) caches
3. Hard refresh the page in your browser to ensure loading latest copy of css.
> 1 votes

---
Tags: theming, nodes
---


# Question
Title: How can I redirect users upon password reset?
The solution shown in How can I redirect users upon login sometimes but not break the "Forgot password?" function? work for Drupal 7.

In Drupal 6, with the *User:user has logged in* event and the following PHP conditions, nothing happens.

```
if (arg(0) == 'user' && arg(1) == 'reset') {
  return false;
} else {
  return true;
}

```

How can I redirect users upon password reset in Drupal 6?

PS. The only variable for this event is `$account` for the logged-in user.

This is the exported rule I am using.

```
array (
  'rules' =>
  array (
    'rules_passwordreset' =>
    array (
      '#type' => 'rule',
      '#set' => 'event_user_login',
      '#label' => 'passwordreset',
      '#active' => 1,
      '#weight' => '0',
      '#categories' =>
      array (
      ),
      '#status' => 'custom',
      '#conditions' =>
      array (
        0 =>
        array (
          '#weight' => 0,
          '#type' => 'condition',
          '#settings' =>
          array (
            'code' => 'if (arg(0) == \'user\' && arg(1) == \'reset\') {
  return false;
} else {
  return true;
}',
            'vars' =>
            array (
            ),
          ),
          '#name' => 'rules_condition_custom_php',
          '#info' =>
          array (
            'label' => 'Execute custom PHP code',
            'module' => 'PHP',
            'eval input' =>
            array (
              0 => 'code',
            ),
          ),
        ),
      ),
      '#actions' =>
      array (
        0 =>
        array (
          '#weight' => 0,
          '#info' =>
          array (
            'label' => 'Page redirect',
            'module' => 'System',
            'eval input' =>
            array (
              0 => 'path',
              1 => 'query',
              2 => 'fragment',
            ),
          ),
          '#name' => 'rules_action_drupal_goto',
          '#settings' =>
          array (
            'path' => 'http://www.sample.com',
            'query' => '',
            'fragment' => '',
            'force' => 0,
            'immediate' => 0,
          ),
          '#type' => 'action',
        ),
      ),
      '#version' => 6003,
    ),
  ),
)

```

# Answer
> 1 votes
You can define submit function in your password form\_alter and then `$form_state['redirect'] = 'user';` or `'user/register'`

---
Tags: users, 6, rules
---


# Question
Title: Rules: Load List of Entities by Object or Entity ID (Performance)
I'm looking to load a list of Users by an Entity Reference Property within Rules. There may be times when I need to load hundreds or thousands of Users that have a matching Property to update a secondary Property. I'm having a difficult time determining the best performance option.

**Here's my use case:**

Users within our website may be linked to a Company (stored as a Node with Content-Type: `company`). When any user of this Company purchases membership, the `company` Node is updated with a Taxonomy Term Reference "Member." Then, every employee (read: User with entity reference to the same `company` node) of that organization needs to have a Taxonomy Reference field within their account updated to reflect they are a "Member (Corp)."

My Rules Based Solutions (that is executed when the order is first Paid In Full that sets the Data Value for that Property of the Company node, then...):

**Solution A (Rules without VBO View):**

1. Fetch all User Entities By Property: `company`, where `company` = Company node.
2. Loop through User list.
3. Check that Entity has Field: "Membership Status."
4. Set Data Value: "Membership Status" = "Member (Corp)."

**Solution B (Rules with: Load a List of Entities from a VBO View):**

1. Pass `nid` as parameter to view.
2. Loop through returned List.
3. Check that Entity has Field: "Membership Status."
4. Set Data Value: "Membership Status" = "Member (Corp)."

**Solution C (Rules with: Load a List of Entity IDs from a VBO View):**

1. Pass `nid` as parameter to view.
2. Loop through returned List.
3. Fetch User Entity by ID.
4. Check that Entity has Field: "Membership Status."
5. Set Data Value: "Membership Status" = "Member (Corp)."

I'm hesitant to load up every Entity that matches due to Performance implications; however, being fairly new to Drupal, I'm not sure the most efficient method to bulk update all of the affected Users.

Can you help me better understand the performance implications of these solutions? Perhaps, I'm missing a better option that I haven't considered? Thanks in advance for your help!

\*This question is in reference to Drupal 7.

# Answer
Using Solution A will pretty sure have performance implications, so I wouldn't recommend that approach "*to load hundreds or thousands of Users*". Below is a blueprint of yet another approach (another option that you could considered, up to you to decide if it is "*better*"), which will allow you to reduce the performance risk significantly ...

### Step 1 - Refine your view

Adapt the VBO view you already have, by limiting the results of that view to the first X users only. Pick a value for X that fits your needs, to start make it small enough and increase later on as much as you feel comfortable with.

Also adapt the views filter, to no longer include the users that have been processed already (by the Rules Component described in the next steps).

### Step 2 - Create a Rules Component

Create a custom Rules Component which performs the Rules Actions as in your Solution "B" or "C". If the value of X is small enough, you can do some experiments with either of these solutions (B or C), i.e. to find out what happens if you increase the value of X (and based on that decide for yourself which one works best). Note that the list to be processed is limited to "X users" only (i.e. those that are contained in your views results from the previous step).

Add an additional Rules Action in your Rules Component, to actually reschedule the execution of this Rules Component itself after a few seconds or minutes (whatever fits). And trigger the very first execution of this Rules Component via a custom rule that is triggered "*When any user of a Company purchases membership*" (as in your question, I bet you have some appropriate Rules Event for that).

### Step 3 - Stop rescheduling the Rules Component when the time is right

Also add a Rules Condition in the Rules Component of the previous step, to "Check the number of results returned by a VBO view" (using the same VBO view). The actual number of results should be at least 1. If there are zero results, then the Rules Actions of this Rules Component will not be performed, which is what we want. Since it will also prevent the the rules component reschedules itself when all users have been processed.

### Step 4 - Review the frequency of your cron jobs

Make sure your cron job runs frequent enough, because each execution of your scheduled Rules Component will actually only happen when cron runs.

Conclusion: because this approach is based on the Rules Scheduler, the elapsed time will be longer, for sure. But the advantage of it is that, as compared to any of your 3 solutions as in your question, the poor user "*of the Company who purchased the membership*", will not have to wait for the rule to complete execution, before being able to do anything else on the site.

PS: I'm assuming this is about D7 ...
> 1 votes

# Answer
I opted to use a custom module invoking `node_hook_presave()`, rather than Rules as I assumed it would be more efficient. This process checks if the "Membership Status" on the Company node has been changed prior to saving the Company.

```
/**
 * Implements hook_node_presave().
 */
function lia_company_node_presave($node){
    if($node->type=='company'){
        /**
         * If field_membership_status is set and the value has changed, then execute
         * the function  lia_company_update_membership_for_users($node->nid, $membership_status);
         */
        if(isset($node->original->field_membership_status[LANGUAGE_NONE][0]['tid'])
            && isset($node->field_membership_status[LANGUAGE_NONE][0]['tid'])
            && $node->original->field_membership_status[LANGUAGE_NONE][0]['tid'] <> $node->field_membership_status[LANGUAGE_NONE][0]['tid']) {

            $membership_status = $node->field_membership_status[LANGUAGE_NONE][0]['tid'];
            lia_company_update_membership_for_users($node->nid, $membership_status);
        }
    }
}

```

If the original value is set and the new value was not equal to the original value, I call a local method `lia_company_update_membership_for_users($node->nid, $membership_status)`.

That method looks as follows. I'm thinking I probably should refactor this to run as a batch process. But any optimizations/feedback others find would be greatly appreciated.

```
/**
 * Implemented by hook_field_presave on Company node when field_membership_status is updated
 * on a Company node so that all of the Users referencing this Company are
 * updated to Member (Corp) or Non-Member, as appropriate.
 *
 * @param $company_nid
 * @param $membership_status_tid
 */
function lia_company_update_membership_for_users($company_nid, $membership_status_tid){
    $query = new EntityFieldQuery();
    $query
        ->entityCondition('entity_type', 'user')
        ->fieldCondition('field_company','target_id',$company_nid,'=');
    $results = $query->execute();

    $member_tid =  1744; // Taxonomy tid for Member
    $non_member_tid = 1749; // Taxonomy tid for Non-Member
    $member_corp_tid = 1745; // Taxonomy tid for Member (Corp)
    $member_status_excluded = array(
        1744, // Active
        1745, // Active (Corp)
        1748, // Deceased
        1746, // Deleted
    );

    foreach($results['user'] as $user){
        $user_wrapper = entity_metadata_wrapper('user',user_load($user->uid));

        /**
         * If the user is not already in an excluded membership_status, then we should update their status.
         * If the Company is being updated to a Member [TID: 1744] then, let's set all eligible Users to a
         * membership_status of Member (Corp) [TID: 1745]. Otherwise, we need to set them to Non-Member [TID: 1749].
         */
        if(isset($user_wrapper->field_membership_status) && !in_array($user_wrapper->field_membership_status->value()->tid, $member_status_excluded)){
            $user_wrapper->field_membership_status = ($membership_status_tid== $member_tid) ? $member_corp_tid : $non_member_tid;
            $user_wrapper->save();
        }
    }

}

```

Thank you @pierre.vriens for your answer. I'll probably end up refactoring when I have more time.
> 1 votes

---
Tags: 7, rules, performance, views
---


# Question
Title: Programmatically accessing field values for a file in a custom form
I have the `kint()` output below.

How do I get the values for the *destination* index?

# Answer
> 0 votes
I have used the code below and it works.

$destination = $file\[0\]-\>toArray()\['uri'\]\[0\]\['value'\];

# Answer
> 0 votes
Since the `values` array is a protected value, you can only access its value with a method (e.g. a magic method).

The `File` class extends `ContentEntityBase`, from which it gets the `values` property and the magic method that allows to access it. Supposing that `$file` is the variable containing an `\Drupal\file\Entity\File` object, you just need the following code.

```
$destination = $file['destination'];

```

### Longer Explanation

The method that allows to access the content of the `values` array is `ContentEntityBase::__get()` (a magic method) that allows to access the value of an object as it would be an array. `ContentEntityBase::__get()` checks also the content of the `values` array; in fact it contains the following code.

```
  // Else directly read/write plain values. That way, non-field entity
  // properties can always be accessed directly.
  if (!isset($this->values[$name])) {
    $this->values[$name] = NULL;
  }
  return $this->values[$name];

```

So, using `$file['destination']`, that method would return you the value of `$file->values['destination']` you cannot directly access.

---
Tags: entities
---


# Question
Title: Views query alter add orderby function FIELD()
I can't figure out how to add following expression to the views query:

```
ORDER BY FIELD(field_dataid,3,2,1,4)

```

QueryPluginBase only gives the option to add:

```
$query->addOrderBy('node_field_data', 'nid', ASC);

```

But doesn't give the option to add an expression.

The Sql interface has the options to add an expression:

```
  $query->addExpression('FIELD(node_field_data.nid,3,2,1,4)', 'order_field');
  $query->orderBy('order_field', 'ASC');

```

But this doesn't work with the views query object.

So how can i add orderby expression to the views query object?

# Answer
> 3 votes
There is a similar answer here: https://drupal.stackexchange.com/a/200662/79998

You should either use `$query->addField()` to add the expression and then append or unshift in `$query->orderby` array, or you can use directly `$query->addOrderBy()` to add the expression and order, if it's ok to be added last.

```
$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,3,2,1,4)', 'ASC', 'order_field');

```

---
Tags: views, 8, database
---


title: EntityQuery with joins

text:
# Question
Title: EntityQuery with joins
I am trying to get user data by UUID in my custom module and I don't know how to join on *users\_field\_data* table to get user fields (email, username, etc.).

My request for the *users* table works but I don't know how to join.

```
$query = \Drupal::entityQuery('user')
          ->condition('uuid', $uuid)
          ->execute();
$result = User::loadMultiple($query);
dpm($result);

```

How can I execute a join with the *users* table?

# Answer
> 1 votes
The easiest way to load a field from any entity when querying is to use the entityTypeManager:

```
$users = \Drupal::entityTypeManager()->getStorage("user")
        ->loadByProperties(['uuid' => $uuid]); // or any other properties.

foreach ($users as $user) {
    var_dump($user->field_customfield->getValue());
}

```

see: working-with-the-entity-api

Be careful to not use `\Drupal::entityManager`, since it is deprecated.

---
Tags: 8, database
---


# Question
Title: Constructor in a custom entity isn't prior to baseFieldDefinitions
I have a custom entity with a constructor that calls a custom method (generateCharacteristics()) to generate random values for certain fields of my entity :

```
    public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = array()) {

    parent::__construct($values, $entity_type, $bundle = FALSE, $translations = array());

    $values += $this->generateCharacteristics();

    foreach ($values as $key => $value)
    {

        $method = 'set'.ucfirst($key);

        // For two-words attributes
        if( strstr($method, '_') ) {
            $method = explode('_', $method);
            $method[1] = ucfirst($method[1]);
            $method = implode('', $method);
        }

        if (method_exists($this, $method))
        {
          $this->$method($value);
        }
    }

}

```

When I log what occurs in this \__construct method when I create a new entity, all works fine, attributes are well setted, but in my database I have NULL or default values (the ones I declared in baseFieldDefinitions()). That's a shame because I think that baseFieldDefinitions() is put in cache (not good for random values) and that my method using constructor is cleaner.

Maybe my error is to think that $values array is the array we send during the call of Entity::create() method because this $values array seems always empty before I add my own array to $values... Nevertheless I set my attributes correctly in the constructor. The use of a postCreate() method should be more appropriate ?

thanks !

# Answer
`Entity::create` gets the storage for the entity type and calls EntityStorage::create. What you are looking for is probably the method Entity::preCreate, which is the first entity event invoked by `EntityStorage::create`.

Place it as public static function in the custom entity class to change the values before the entity is created:

```
class CustomEntity extends ContentEntityBase {

   /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage, array &$values) {
    // modify $values
  }

}

```
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Views data export only exporting for current page
I have a view which show Tabular data and i have attached data export on this view which should export in CSV format. The problem is if the data is paginated exportation is only downloading the records on the current page, but I want all records. Is there a way of making it to ignore the pagination.

# Answer
In the data export display you need to set the pager to: `Display all items`. This will return you all the data in your file without pagination.
> 0 votes

---
Tags: views, 8
---


title: How to load my Entity in Entity form

text:
# Question
Title: How to load my Entity in Entity form
i have:

```
/**
 * @ContentEntityType(
 *   id = "my_entity",
 *   label = @Translation("drwywr werwer label"),
 *   bundle_label = @Translation("My entity type"),
 *   handlers = {
 *     bla...
 *     "form" = {
 *       "default" = "Drupal\my_entity\Form\MyEntityForm",
 *       "edit" = "Drupal\my_entity\Form\MyEntityForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm"
 *     },
 *     bla...
 *   },
 *   translatable = FALSE,
 *   entity_keys = { bla... },
 *   bundle_entity_type = "my_entity_type",
 *   links = {
 *     "collection" = "/admin/test/entity/collection",
 *     "canonical" = "/admin/test/entity/{my_entity}",
 *     "edit-form" = "/admin/test/entity/{my_entity}/edit",
 *     "delete-form" = "/admin/test/entity/{my_entity}/delete"
 *   }
 * )
 */

```

based on above, how do i load my entity in form below:

```
<?php

namespace Drupal\my_entity\Form;

use bla...

/**
 * Form controller for the node edit forms.
 */
class MyEntityForm extends ContentEntityForm {
 //how to load my entity type here?
}

```

i tried a couple way but i keep receiving:

> Error: Call to a member function getEntityTypeId() on null

mainly because the entity is not loaded (null value)

this is how i create the route:

in my\_entity.routing.yml:

```
route_callbacks:
  - 'entity.my_entity.routes::routes'

```

in routes:

```
public function routes() {
// Build Entity Create Route - CREATE
  $route = new Route(
      (substr($type->getRoute()['path'], -1) == '/' ? $type->getRoute()['path'] . $type->id() : $type->getRoute()['path'] . '/' . $type->id()) . '/create',
      [
        '_form' => '\Drupal\my_entity\Form\MyEntityForm', //TODO : not finish
        'entity_type' => 'my_entity',
        'bundle' => $type->id(),
        '_title' => 'Create ' . $type->getRoute()['label'],
      ],
      ['_permission' => 'entity admin settings']
    );
  $route_collection->add('entity.my_entity.' . $type->id() . '_create', $route);
}

```

if you see in my content entity type config above, i have:

```
 *   links = {
 *     "collection" = "/admin/test/entity/collection",
 *     "canonical" = "/admin/test/entity/{my_entity}",
 *     "edit-form" = "/admin/test/entity/{my_entity}/edit",
 *     "delete-form" = "/admin/test/entity/{my_entity}/delete"
 *   }

```

which i want those: edit, delete to be able to 'link' with my form as well - how to do this?

what i'm trying to achieve is: to generate forms based on field define in `my entity type`

# Answer
Your code currently loads the form with the `_form` routing definition. For classes extending `ContentEntityForm`, you have to use the `_entity_form` notation instead. Here is an example of an '*module\_name*.routing.yml' file:

```
kollektivhampel.pdf_erstellen_form:
  path: '/intranet/{my_entity}/something'
  defaults:
    _entity_form: 'my_entity.default'
    _title: 'Your page title'
  options:
    parameters:
      my_entity:
        type: my_entity
  requirements:
    _permission: 'some permission defined in your module_name.permissions.yml file'

```

The `_entity_form` is composed of two parts: before the dot, you have the entity type id, in this example `my_entity`. Behind the dot, you have the name of the form, defined in the `handlers` section of the `@ContentEntityType` annotation. In this case, the second part is `default`, According to your question's code, this refers to `\Drupal\my_entity\Form\MyEntityForm`. You might not need the `route_callbacks` code, as a static routing directly in the yml file is probably enough.

For more details, see https://www.drupal.org/docs/8/api/routing-system/structure-of-routes.
> 3 votes

# Answer
You can take a look into `core/modules/system/tests/modules/entity_test/src/EntityTestForm.php` file.

And you can see that in the object that is an instance of `ContentEntityForm` it possible to get an entity object using `$entity` property:

```
$entity = $this->entity;
$entity = $this->getEntity();

```
> 1 votes

---
Tags: 8, entities
---


title: Update node revision programmatly

text:
# Question
Title: Update node revision programmatly
If i try to update node revision like this:

```
$node = node_revision_load(59);
$node->set('publish_on', null);
$node->save();

```

or simple save:

```
$node = node_revision_load(59);
$node->save();

```

I have a PHP memory error, (i have 1gb allocated)

# Answer
> 1 votes
When you load a node, you should always check if it exists (is not null) before calling a method:

```
$node = node_revision_load(59);
if ($node) {
  $node->set('publish_on', null);
  $node->save();
}

```

But this is not the cause for the memory error. This is more likely a recursive thing. For example you are saving again and again until the memory is filled up.

---
Tags: 8
---


# Question
Title: Diffrence between path /user and path /admin?
Is there a difference between the path /user and the path /admin? Example: www.page.com/user and www.page.com/admin

I'm asking because I can access the /user page but not the /admin page.

# Answer
If you're logged in and you have no access to the /admin page then you most probably don't have the right permissions to access.

The admin pages should not be accessible for not-logged-in users, they provide access to the administration pages (e.g. Content, Structure, Configuration etc) per default. The /user path provides the settings for your user-account.

If you are logged out, the /user path directs to the login-page per default.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: How to install Social Auth LinkedIn PHP Library with composer for Open Social Drupal module?
How to install Social Auth LinkedIn PHP Library with composer for Open Social Drupal module ?

I try to install Open Social (https://www.drupal.org/project/social) but I can't because I can find how to install the LinkedIn library with Composer.

I already installed successfully Google, Facebook and Twitter library with Composer.

"Social Auth LinkedIn module requirements Not installed Social Auth LinkedIn requires LinkedIn PHP Library. Make sure the library is installed via Composer."

Thanks.

# Answer
According to the composer.json of that module, you need `happyr/linkedin-api-client`. So to install that with Composer, from the root of your Drupal project run:

```
composer require happyr/linkedin-api-client:1.0.0

```

Since that library has dependencies too, you probably need to install them too. Basing on the documentation, you could need to execute the following too.

```
composer require php-http/guzzle6-adapter
composer require guzzlehttp/psr7 php-http/message

```
> 1 votes

# Answer
I installed

```
composer require php-http/guzzle6-adapter
composer require guzzlehttp/psr7 php-http/message

```

and then installed

```
composer require happyr/linkedin-api-client:1.0.0

```

and it worked
> 0 votes

---
Tags: 8, composer
---


# Question
Title: PreExistingConfigException: Configuration objects provided by progweb_migration already exist in active
I'm playing with migrations from D7 to D8 and I've found that, when you register a module with a migration, if you disable it, next time you enable the module gets stuck on this:

```
[vagrant@devbox] /[...]/default $ drush en progweb_migration -y
PHP Warning:  Module 'imagick' already loaded in Unknown on line 0
PHP Warning:  Module 'imagick' already loaded in Unknown on line 0
The following extensions will be enabled: progweb_migration
Do you really want to continue? (y/n): y
exception 'Drupal\Core\Config\PreExistingConfigException' with message 'Configuration objects[error]
(migrate.migration.custom_user) provided by progweb_migration already exist in active
configuration' in /www/drupal8/core/lib/Drupal/Core/Config/PreExistingConfigException.php:70
Stack trace:
#0 /www/drupal8/core/lib/Drupal/Core/Extension/ModuleInstaller.php(162):
Drupal\Core\Config\PreExistingConfigException::create('progweb_migrati...', Array)
#1 /opt/drush7/vendor/drush/drush/commands/core/drupal/environment.inc(129):
Drupal\Core\Extension\ModuleInstaller->install(Array, true)
#2 /opt/drush7/vendor/drush/drush/commands/core/drupal/environment.inc(196):
drush_module_install(Array)
#3 /opt/drush7/vendor/drush/drush/commands/pm/pm.drush.inc(1120): drush_module_enable(Array)
#4 [internal function]: drush_pm_enable('progweb_migrati...')
#5 /opt/drush7/vendor/drush/drush/includes/command.inc(359):
call_user_func_array('drush_pm_enable', Array)
#6 /opt/drush7/vendor/drush/drush/includes/command.inc(210): _drush_invoke_hooks(Array,
Array)
#7 [internal function]: drush_command('progweb_migrati...')
#8 /opt/drush7/vendor/drush/drush/includes/command.inc(178):
call_user_func_array('drush_command', Array)
#9 /opt/drush7/vendor/drush/drush/lib/Drush/Boot/DrupalBoot.php(46): drush_dispatch(Array)
#10 /opt/drush7/vendor/drush/drush/drush.php(76):
Drush\Boot\DrupalBoot->bootstrap_and_dispatch()
#11 /opt/drush7/vendor/drush/drush/drush.php(16): drush_main()
#12 {main}

```

It's like the migration is being registered but not de-registered. In D7 there is a method for that, but no luck so far trying in D8:

```
function progweb_migration_enable() {
  Migration::registerMigration('custom_user');
  Migration::registerMigration('custom_blog');

  Migration::registerMigration('ProgwebBlog');
  Migration::registerMigration('ProgwebUser');
}

function progweb_migration_disable() {
  Migration::deregisterMigration('custom_user');
  Migration::registerMigration('custom_blog');

  Migration::deregisterMigration('ProgwebBlog');
  Migration::registerMigration('ProgwebUser');

}

```

Any ideas?

# Answer
> 4 votes
This is a core issue, not specific to Migrate. The problem is, config entities are copied into the active store when you enable your module but not deleted when you remove your module. This is what causes the errors when re-enabling your module.

I would highly suggest Config Devel for developing migrations. It will allow you to synchronise your migrations back into the active store without re-installing.

# Answer
> 2 votes
in case you need to uninstall the module (Ben answer is good), you'd need to add this to remove the config:

```
/**
 * hook_uninstall.
 */
function progweb_migration_uninstall() {
  db_query("DELETE FROM {config} WHERE name LIKE 'migrate.migration.progweb_custom_blog%'");
  db_query("DELETE FROM {config} WHERE name LIKE 'migrate.migration.progweb_custom_user%'");

  drupal_flush_all_caches();
}

```

# Answer
> 0 votes
You can do this with Drush.

First check the available migrations using: `drush config-list`

Then use `drush config-delete migrate.migration.custom_user` (from your example)

---
Tags: 8, migrations
---


# Question
Title: How to implement hook_field_widget_form() for multiple fields?
In a module I'm going to implement some Field types using Field API. this is how hook\_field\_info() looks like in my module.

```
function myModule_field_info()
{
  return array(
    'type1' => array(
      'label' => t('Custom type 1'),
      'description' => t('Just for test'),
      'default_widget' => 'type1_textbox',
      'default_formatter' => 'type1_rawview',
    ),
    'type2' => array(
      'label' => t('Custom type 2'),
      'description' => t('Just for test'),
      'default_widget' => 'type2_textbox',
      'default_formatter' => 'type2_rawview',
    ),
  );
}

```

and the hook\_field\_widget\_info() implementation is :

```
function myModule_field_widget_info()
{
  return array(
    'type1_textbox' => array(
      'label' => t('Text field'),
      'field types' => array('type1'),
    ),
    'type2_textbox' => array(
      'label' => t('Text field'),
      'field types' => array('type2'),
    ),
  );
}

```

off-course this is just an example and each widget has its especial form . now consider that each of my field types has more than one element .

* Field type 1
    + first name
    + last name
* Field type 2
    + phone number
    + address
    + email

now the question is how should I implement widget form for a multiple field type like this?

I tried this code but no chance :

```
function myModule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
{
  if($field['cardinality'] == 1){
    $element['#type'] = 'fieldset';
  }
  switch ($instance['widget']['type']) {
    case 'type1_textbox' :
      $type1 = array();
      $type1['firstName'] = array(
        '#type' => 'textfield',
        '#field_prefix' => t('First Name : '),
        '#size' => 20,
        '#default_value' => isset($items[$delta]['firstName']) ? $items[$delta]['firstName'] : '',
      );
      $type1['lastName'] = array(
        '#type' => 'textfield',
        '#field_prefix' => t('Last Name : '),
        '#size' => 20,
        '#default_value' => isset($items[$delta]['lastName']) ? $items[$delta]['lastName'] : '',
      );
      $element += $type1;
      break;
    case 'type2_textbox' :
      $type2 = array();
      $type2['phoneNumber'] = array(
        '#type' => 'textfield',
        '#field_prefix' => t('Phone Number : '),
        '#size' => 20,
        '#default_value' => isset($items[$delta]['phoneNumber']) ? $items[$delta]['phoneNumber'] : '',
      );
      $type2['address'] = array(
        '#type' => 'textarea',
        '#field_prefix' => t('Address : '),
        '#size' => 60,
        '#default_value' => isset($items[$delta]['address']) ? $items[$delta]['address'] : '',
      );
      $type2['email'] = array(
        '#type' => 'textfield',
        '#field_prefix' => t('Email : '),
        '#size' => 20,
        '#default_value' => isset($items[$delta]['email']) ? $items[$delta]['type2']['email'] : '',
      );
      $element += $type2;
      break;
  return $element;
}

```

The code was edited and now no widget is shown in node-edit form and when I went to field management section this error is appearing

# Answer
> 0 votes
the name of the form in myModule\_field\_widget\_form must be the same column in your .install file make sure it matches the same column

---
Tags: entities
---


# Question
Title: How to run composer to download google_chart library?
Hi I am trying to install charts module with its Google\_charts library, and I am following the Getting started document for installation. I am stuck in the step of running composer to download and install Google chart library. How is this done? How do I run composer in Drupal?

Please help, thanks

# Answer
> 2 votes
Run this to install on your current project:

```
composer require gufy/google-charts:dev-master;

```

Or you can add this package to your *composer.json* file:

```
"require": {
    "gufy/google-charts": "dev-master"
}

```

Then use composer to install this package:

```
composer update

```

# Answer
> 0 votes
The first answer posted by @Mohammad\_AlQanneh is the right answer, in addition to that, composer.phar file was missing in my project, and so I had to install, create an alias and then followed @Mohammad\_AlQanneh's instructions and it worked.

To install:

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

```

---
Tags: composer, theming
---


title: Attachment pager

text:
# Question
Title: Attachment pager
I have a Drupal 7 page View which returns one result while an attachment View (with offset 1) returns the rest. (First result displays title, body, image, etc. while the following rows only return title and trimmed teaser.) At this point, the View is returning the expected results.

The problem comes in when I wish to add a pager. Desired results would be the initial page returns the first result (styled uniquely) with next nine rendered through the attachment. ?page=1 and following would be the next 10 rows rendered through the attachment.

I am certain this must certainly be possible; but having difficulty achieving it.

# Answer
Don't split them into two views. Use 1 view, without offset.

Simply use your view id followed by the class `.views-row-1` in your CSS.

Ex: `#view-id .views-row-1 .views-field-title { border: solid red };`

If you need to have only certain fields to display on row 1, ex: body field only on row 1, then you'll need to create a template file for your view and just do a conditional.

Add field `Global: View result counter`

**views-view-fields--\[view-name\]--\[machine-name\].tpl.php**

```
<?php

if (strip_tags($fields["counter"]->content) == 1) {
   print $fields["title"]->content;
   print $fields["body"]->content;
}
else {
   print $fields["title"]->content;
}

```
> 0 votes

---
Tags: views, paging
---


# Question
Title: How to add metatags in hook_preproccess_node()?
How to add variable meta tags depending on the node that is loaded?

The node has a picture and custom title field and the need to be variable. What is the best practice to change them in: `hook_preprocess_node()`?

# Answer
I am aware that this does not directly answer the question, which was about adding in a preprocess function, but I would suggest that you also consider the metatag module, which is pretty full featured.

https://www.drupal.org/project/metatag
> 2 votes

# Answer
yes, you can, place this code in template.php in your subtheme folder

```
function yourtheme_preprocess_node(&$vars) {
        $element = array(
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'robots',
            'content' => 'index',
          ),
        );
        drupal_add_html_head($element, 'robots');
 }

```
> 1 votes

# Answer
For me the following worked: I managed to load the current node in the hook\_preprocess\_node(). Based on this answer: How do I get the current node ID?

```
function module_name_page_attachments_alter(array &$page) {

            $node = \Drupal::routeMatch()->getParameter('node');
            if ($node instanceof \Drupal\node\NodeInterface) {
            // You can get nid and anything else you need from the node object.
            $nid = $node->id();
        }

        $ogImage = array(
            '#tag' => 'meta',
            '#attributes' => array(
                'property' => 'og:image',
                'content' => 'location of the image'.$nid.'.png',
    //my picture has the node id before the file format
            ),
        );

        $page['#attached']['html_head'][] = [$ogImage, 'ogImage'];
    }

```
> 0 votes

---
Tags: 8, nodes, hooks, meta-tags
---


# Question
Title: node type not getting in search template
I am referring to document search-result.tpl.php on Drupal.org. Here they say `$info_split['type']` has the node type information, but when I print in the file search-result.tpl.php in my theme folder, it does not print anything, as that key does not exist. So is there something that I should do to get this info?

# Answer
> 1 votes
I took a look into the code and it seems to be that is not implemented. So maybe it's a bug or just mistake in the documentation.

At least, you can reach your goal with the `hook_node_search_result` or even with `template_preprocess_search_result` if you don't want create a module.

For information, the `$info_split` for node is filled by `node_search_execute` that call the hook said above.

# Answer
> 1 votes
$info\_split\['type'\] has been used in Drupal 6. It's gone in Drupal 7 so the documentation is not right.

Below my code for extending the $info\_split array with type. I also extended it with the node revision timestamp to use custom format\_date() in my template.

`function template_preprocess_search_result(&$variables) {
 if (isset($variables['result']['node']->type)) {
 $variables['info_split']['type'] = $variables['result']['node']->type;
 }
 if (isset($variables['result']['node']->revision_timestamp)) {
 $variables['info_split']['revision'] = $variables['result']['node']->revision_timestamp;
 }
}`

# Answer
> 0 votes
This worked for me. I am using Apache Solr. `$variables['result']['node']->type` doesn't exist. `$variables['result']['node']->bundle_name` exists.

```
function my_theme_name_preprocess_search_result(&$variables) {
  if (isset($variables['result']['node']->bundle_name)) {
    $variables['info_split']['type'] = $variables['result']['node']->bundle_name;
  }
}

```

# Answer
> 0 votes
For Drupal 8 :

```
function theme_preprocess_search_result(&$variables) {
  if ($variables['result']['node']->getType()) {
      $variables['info_split']['node_type'] =$variables['result']['node']->getType();
  }
}

```

---
Tags: theming, search
---


# Question
Title: Any way to set Drupal theme settings per page?
I have a theme which has multiple theme options in its settings page. Is there a way to assign particular theme settings to specific Drupal paths?

# Answer
> 0 votes
For Drupal 7, you can do this by taking advantage of the fact that theme settings are cached by drupal\_static(). See theme\_get\_setting(). I think the same approach would work for Drupal 8 too, but haven't tried it.

```
// Implement HOOK_init.
// Here we override one of the Bootstrap theme settings.
function MY_MODULE_init() {
  // Only do this if we're actually on the relevant page.
  if ($_GET['q'] == PATH_TO_THE_PAGE) {
    // Override the Bootstrap theme setting 'Smart form descriptions (via Tooltips)'.
    // This because we want to display form input #description as text, not tooltip.
    // This will also affect any other forms on the current page, no easy solution for that.

    // Set the name of the theme we're interested in (the current theme in this case).
    $theme_name = $GLOBALS['theme_key'];
    // Read the setting first to ensure that the drupal_static cache is populated.
    $setting = theme_get_setting('bootstrap_forms_smart_descriptions', $theme_name);
    // Get a reference to the cached settings.
    $cached_settings = &drupal_static('theme_get_setting');
    // Unset the 'bootstrap_forms_smart_descriptions' setting from the cache.
    unset($cached_settings[$theme_name]['bootstrap_forms_smart_descriptions']);
  }
}

```

I should add, this is arguably a bit of a hack, as it depends on the internals of drupal\_static() and theme\_get\_setting() i.e. not documented API functionality - unless you consider the code to be the documentation :)

# Answer
> -1 votes
You can do this with the ThemeKey Module.

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:
>
> * individually-styled channels
> * a front-page / "splash" screen
> * a date/time-selected Christmas theme
> * mobile themes for different auto-detected mobile devices
> * special themes for "limited" or "old" browsers
> * content, user, or role -specific themes
> * indicating your environment (production, staging, testing, sandbox, … )
> * testing your redesign safely on a live server
>
> And unlike other theme switching modules, ThemeKey should play well with internal and external page caches, like Boost or Varnish, even for anonymous users.

---
Tags: 7, theming
---


title: Random::string deprecated?

text:
# Question
Title: Random::string deprecated?
I'm using *Random* class to generate a password for a new user in my custom module.

I added the namespace in my module controller: `use \Drupal\Component\Utility\Random;`
And I am using it like this:

```
$user = User::create();
$user->setPassword(Random::string());

```

Problem is this function seems to be deprecated, however I found it in the Drupal API documentation.
Here is the error I get:

> Deprecated function: Non-static method Drupal\Component\Utility\Random::string()

Did I use it wrong or do you know a better way to generate a random string ?

*Drupal version: 8.4*

# Answer
> 7 votes
`Random::string` isn't a static function, so you can't call it statically.

Well, you can (PHP is, erm, interesting like that), but it will throw a fatal error in future versions of the language, hence the warning now. To clarify, you're not being warned that `Random::string` itself is deprecated, just the method you're using to invoke it.

Get an instance instead and use that:

```
$random = new \Drupal\Component\Utility\Random();
$string = $random->string();

```

---
Tags: 8
---


# Question
Title: Is there a way to figure out the block machine name?
In Drupal 8, is there a way to figure out what current block or view machine name you should use?

For example, with the following code, I noticed that `'machine_name_to_determine'` could change depending on how many times you have used your block.

```
$block_id = 'machine_name_to_determine';
$block_config = \Drupal\block\Entity\Block::load($block_id);

```

I need a way to retrieve this at run-time. How can I retrieve it?

# Answer
You can query the blocks by the plugin id. This is the id of a block plugin or for derivatives like a view block (which you probably are looking for as you've mentioned a view machine name) with additional parameters:

```
$plugin_id = 'views_block:' . $view_id . '-' . $display_id;

```

Where `$view_id` is the view machine name which you find in the Views UI and `$display_id` is the display machine name, usually `block_1` for the first block of the view.

Then get all blocks placed for this plugin id and print the block machine names or use the loaded blocks in your code:

```
$blocks = \Drupal::entityTypeManager()->getStorage('block')
  ->loadByProperties(['plugin' => $plugin_id]);
foreach ($blocks as $block) {
  echo $block->id();
}

```

Add a theme or region to loadByProperties() if needed:

```
['theme' => 'bartik', 'region' => 'header']

```
> 2 votes

# Answer
This is in accordance to the pointer by @4k4

```
$plugin_id = 'bookingsystem_block';
$block_id = $this->getCurrentBlockId($plugin_id);
protected function getCurrentBlockId($plugin_id)
{
    $block_id = NULL;

    $blocks = \Drupal::entityTypeManager()->getStorage('block')
        ->loadByProperties(['plugin' => $plugin_id]);

    $current_route_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    foreach ($blocks as $block)
    {
        $visibility = $block->getVisibility();
        $request_path = $visibility['request_path'];
        $request_path_url_arr = explode("\r\n", $request_path['pages']);

        $node_url_arr = array();

        foreach ($request_path_url_arr as $path_alias)
        {
            $path = \Drupal::service('path.alias_manager')->getPathByAlias($path_alias);
            if(preg_match('/node\/(\d+)/', $path, $matches)) {
                $node_url_arr[] = $path;
            }
            else if($path_alias=='<front>') {
                $node_url_arr[] = '/';
            }
        }

        $request_path_url_arr = array_merge($request_path_url_arr,$node_url_arr);

        if(in_array($current_route_path,$request_path_url_arr))
        {
            $block_id = $block->id();
            break;
        }
    }

    return $block_id;
}

```
> -2 votes

---
Tags: blocks
---


# Question
Title: How to create access permissions system similar to Organic Groups access, using Eck entities
There currently still is not a working version for Organic Groups access control, compatible with ECK entities.

My current site contains entity type project and entity type project content. The project content references the project through an entityreference field.

I would like to use an access control system that grants access to specific projects, and when that access is granted, the user has also access to specific project content entity types.

I know that Organic groups uses a relationship approach in which the group membership is an entity, and there is a two level deep relationship between group content (or group member) and the group.

In my case I prefer the simple direct entityreference (one level relation) between content and project. This would serve simplicity and performance. If you would advise against that, please let me kow.

I would like to receive guidance on how to set up such permission system, and possibly your suggestions and recomendations based on your experience with a similar setup. Thank you.

# Answer
> 1 votes
If you'd be willing to use the Group module, then you could do like so:

* You can configure a Group Type named "Project", so that this Group Type would replace your ***entity type project***.
* You can create 1 Group (of group type "Project") for each of your Projects (each Group probably labelled with the name of a specific project).
* You can assign nodes to a Group (of group type "Project"), so that these nodes would replace your ***project content entity types***.

Group is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

With the above in place, you also have the permission system you're looking for, out-of-the-Group-box.

### More info:

### Integration with various modules

The Group module integrates with various other (popular) modules, including:

The beauty, IMO, of these integrations are that they are more or less out-of-the box (not dozens of extra modules needed to make those integrations work).

### Resources

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


title: Call AJAX callback on page load

text:
# Question
Title: Call AJAX callback on page load
I've been reading the whole day but I cannot find a complete example for a basic AJAX call on load page.

I followed this tutorial: and this example:

I was able to register the callback, controller and commands but the only way to trigger the ajax call is creating a link and is triggered on click event (as the example does)

```
<a class="use-ajax" href="/ajax/nojs/ajaxload">XXX</a>

```

I need to trigger that ajax call but when the page is loaded, is there any way?

Thanks

# Answer
> 5 votes
Thought I would share this as a slightly more complete solution, this would be your full javascript file:

```
(function ($, Drupal) {
  Drupal.behaviors.myModuleName = {
    attach: function (context, settings) {
      // I am doing a find() but you can do a once() or whatever you like :-)
      $('#element', context).find('.sub-element').each(function () {
        // Do your thing here
      });
    }
  };
})(jQuery, Drupal);

```

Remember that the context returned on ajax event is the element being replaced, and should match your '#element', if it is inside the element being replaced it is not going to fire.

If you put a watch on the `$('#element', context).find...` line in your browser inspector you will see the different contexts being fired.

# Answer
> 4 votes
Funny how those tutorials did not mention Drupal behaviors, which will trigger once the page is loaded. This is a good tutorial on them (Drupal 7, but same principles apply).

Basically all you should do is call your callback function from a behavior to get the same effect as jQuery's document ready callbacks.

```
Drupal.behaviors.myModule = {
  attach: function (context, settings) {
    // Call callback here.
  }
};

```

And while you are at it, I recommend reading up on behaviors as they help to streamline your javascripts and keeps them in closed scopes.

---
Tags: 8, ajax, page-controller
---


title: Run JavaScript after Ajax Call

text:
# Question
Title: Run JavaScript after Ajax Call
I have a form file:

```
namespace Drupal\h_scheduler\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use \Drupal\node\Entity\Node;

class DayAddEntries extends FormBase {

  public counter = 0;

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

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

    $form_state->setCached(FALSE);

    $form['#attached']['library'][] = 'h_scheduler/form_actions';

    /*...More fields....*/

    /* Special */
    $form['specials'] = array(
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#title' => t('Specials'),
      '#prefix' => '<div id="specials">',
      '#suffix' => '</div>',
    );

    if ($this->counter) {
      for ($i = 1; $i <= $this->counter; $i++) {
        $form['specials']['special'.$i] = array(
          '#type' => 'fieldset',
          '#title' => t('Special ') . $i,
          '#tree' => TRUE,
        );
        $form['specials']['special'.$i]['field'] = array(
          '#type' => 'number',
          '#title' => t('Every'),
          '#title_display' => 'before',
        );
        $form['specials']['special'.$i]['field'] = array(
          '#type' => 'textfield',
          '#title' => t('Prefix'),
          '#title_display' => 'after',
        );
      }
    }
    $form['specials']['operations']['#type'] = 'actions';
    $form['specials']['operations']['add_special'] = array(
      '#type' => 'button',
      '#value' => $this->t('Add special'),
      '#ajax' => array(
        'callback' => '::ajaxAddSpecial',
        'wrapper' => 'specials',
      ),
    );

    /* Not working */
    $form['specials']['operations']['remove_special'] = array(
      '#type' => 'button',
      '#value' => $this->t('Remove special'),
      '#ajax' => array(
        'callback' => '::ajaxRemoveSpecial',
        'wrapper' => 'specials',
      ),
    );

    /* Submit */
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    $this->counter++;

    return $form;
  }

  /**
   * Increments the number of specials to have
   */
  public function ajaxAddSpecial($form, FormStateInterface $form_state) {
    return $form['specials'];
  }

  /**
   * Decrements the number of specials to have
   */
  public function ajaxRemoveSpecial($form, $form_state) {
    $this->counter -= 2;
    return $form['specials'];
  }

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

    /* Do stuff */

  }
}

```

jQuery:

```
jQuery(function($) {
  $('#edit-specials .fieldset-wrapper .fieldset-wrapper, #edit-regular .fieldset-wrapper').addClass('entry-wrapper').each(addStyleClasses);

  function addStyleClasses() {
    console.log('hi');
    $(this).children('.form-item')
      .addClass(function() {
        var regex = /form-item-\S+-(\S+)/;
        return regex.exec($(this).attr('class'))[1];
      })
      .not('.every').wrapAll('<div class="item-wrapper">');
  }

```

});

I'm able to add a new "special" item, but when I do it appears wacky.

This is because I've styled the form using a jQuery function that adds classes and wraps elements. However, that function does not run when the `form['specials']` is rebuilt.

My question, how do I run a JS function after an ajax call?

# Answer
> 3 votes
This has a solution on Stackexchange here already, but:

This would be your full javascript file:

```
(function ($, Drupal) {
  Drupal.behaviors.myModuleName = {
    attach: function (context, settings) {
      // I am doing a find() but you can do a once() or whatever you like :-)
      $('#element', context).find('.sub-element').each(function () {
        // Do your thing here
      });
    }
  };
})(jQuery, Drupal);

```

Note on the question's js: I would say when calling a function like your addStyleClasses() it would be more reliable to explicitly pass your target element in the function call than using $(this) in there.

---
Tags: 8, forms, javascript
---


title: left sidebar with menu

text:
# Question
Title: left sidebar with menu
I have cloned bartik so that I can adjust it to my needs. Basically, I want a left sidebar containing the main menu which slides up over the main content if used on a small screen. The "normal" theme has the sidebar sliding down and under, which is no use when the menu is in it.
I've tried editing the page.tpl.php by moving the sidebar statement up above the content, and just below the breadcrumbs. This shows successfully on a mobile screen, however the sidebar disappears on a pc and slides under the main content.
Do I just attempt to fix it all with css now, or is there something else I need to address?

# Answer
> 0 votes
Moving the block in the page.tpl.php was the correct move to make. The layout.css had to be altered by splitting out many of the grouped items to specifically target the blocks wanted before the desktop arrangement was correct. An important thing is to clear the cache after making each correction, otherwise it will appear not to have taken place.

A correction to this is that the change only works for minified screens. The desktop screen was corrupted instead, and a solution is now required for that.

---
Tags: theming
---


# Question
Title: How to make payments on recurring product automatically(RESOLVED)
I have drupal 7 and commerce modules. I'm using Stripe payment system with module commerce\_stripe. Customer's card details are stored in file (commerce card in file). Site sells recurring products.

My question is: can I make payments on recurring products automatically without user agreement? And if I can how should I do it?

Thanks in advance.

# UPDATE

Found how recurring entities and card on file work. After user bought subscription first time his card data saves into file to use it in later payments. When user should pay for subscription again cron `commerce_recurring_cron` should run. This cron checks recurring entities and if it's time to pay creates an order with status pending.

When this cron runs once again it charges payments and necessary amount of money debited from users account.

So everything I need is processed and my customer is happy.

# Answer
If you're using the Card on File module, that means you're storing tokens that point to card data stored securely by the payment gateway itself. What you then need is to combine that with Commerce Recurring or the Commerce License suite to create the schedule for recurring charges and Commerce Dunning to react to payment failures.
> 1 votes

# Answer
Storing credit card details isn't very safe and allowed unless you have an application which is PCI complied and as well the hosting.

Anyway, as you are using Stripe, you should have a look at this: https://stripe.com/subscriptions
> -1 votes

---
Tags: 7, commerce
---


# Question
Title: Commerce 2.0: How can multiple email addresses receive copies of orders?
If I understand the configuration correctly, only one email address can be specified when defining a Store (the text under the field says "Store email notifications are sent from this address".

When a person places an order, they will receive an email confirmation showing as being sent from that Store owner's email address. No one else - not even the store owner - gets an email copy of the order.

I am converting a client's website from Wordpress to Drupal 8. Their current configuration is that four different people in the office all receive email copies whenever an order is placed. How can the same be implemented in Commerce 2.0? (They don't want to log into the site and check the database for new orders - they want the email notifications sent to them if and when orders are actually placed.)

Has anyone already implemented something similar?

# Answer
> Their current configuration is that four different people in the office all receive email copies whenever an order is placed.

See our documentation for order receipt emails: https://docs.drupalcommerce.org/commerce2/user-guide/orders/customer-emails

I think you'll be fine adding those four emails separated by commas.

EDIT: Also see our docs for setting up HTML emails https://docs.drupalcommerce.org/commerce2/developer-guide/core/html-emails
> 1 votes

---
Tags: commerce
---


# Question
Title: Drupal.settings.mymodule is not an object
I have implemented a hook\_menu() with a callback to check user's privileges and a page callback to create the html. When I am in page\_callback(), I retrieve a JSON string from a db and I'd like to pass this string to a JS script that will do some visualization.

```
function page_callback( $id ){
    $myjson = mymodule_query($id);
    $vars = array('key' => $myjson);
    drupal_add_js(array('mymodule', $vars), 'setting');
    drupal_add_js(drupal_get_path('module', 'mymodule').'/js/myjs.js');
    return '<div id="graph-data"></div>';
}

```

In the JS file, I have:

```
(function($){
    Drupal.behaviors.mymodule = {
        attach : function(context, settings) {
            if(Drupal.settings.mymodule.key !== ''){
                alert('Got it!');
            }
        }
    };
}(jQuery));

```

When I try to execute this code, I get:

```
TypeError: undefined is not an object (evaluating 'Drupal.settings.mymodule.key')

```

Is there any other way in D7 to pass a php variable at runtime to a JS script?

EDIT: trying to follow the advice using render arrays, what is the best way to translate my code? Here's what I have:

```
function page_callback( $id ){
    $output_data = array(
      '#theme' => 'graph_data', // not sure here...
      '#vars' => array('key' => mymodule_query($id)),
      '#attached' => array(
         'js' => array(
              drupal_get_path('module', 'mymodule') .'/js/myjs.js',
         ),
         'css' => array(
              drupal_get_path('module', 'mymodule') . '/css/graph_data.css',
         ),
      )
    );
    return $output_data;
}

```

# Answer
It should be:

```
drupal_add_js(array('mymodule' => $vars), 'setting');

```

But ideally you'd be using a render array instead, and loading the settings/files into the page with the `#attached` method.
> 1 votes

# Answer
To use a render array instead (according to Clive's suggestion):

```
function page_callback( $id ){
  $setting = mymodule_query($id);

  // Ideally you should check if something exists:
  // This example returns 404 if no settings found for $id.
  if (empty($setting)) {
    return MENU_NOT_FOUND;
  }

  return array(
    // You can also convert this markup to a theme and use #theme,
    // or you can also return an empty #markup
    // and use #prefix and #suffix to supply the wrapper.
    '#markup' => '<div id="graph-data"></div>',
    '#attached' => array(
      'js' => array(
        array(
          'type' => 'setting',
          'data' => array('mymodule' => array('key' => $setting)),
        ),
        array(
          'type' => 'file',
          'data' => drupal_get_path('module', 'mymodule') .'/js/myjs.js',
        ),
      ),
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/graph_data.css',
      ),
    )
  );
}

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Migrate multiselect taxonomy values from node with csv
I want to import companies with csv into Drupal 8 with `migrate_source_csv` module.

CSV:

```
company_name,company_categories,company_size
"Dummy Name","Category 1";"Category 2","2 people"

```

How to accomplish? Do I need an other plugin: `explode`?

```
    process:
      field_categories:
        plugin: explode
           source: company_categories
           delimiter: ';'
        plugin: entity_generate
        source: company_categories

```

I also found this: https://www.drupal.org/node/2129651#handling\_multiple

# Answer
I found it myself. This is working for me:

```
process:
  title: title
  body: body
  field_company:
    -
      plugin: explode
      source: categories
      limit: 100
      delimiter: ;
    -
      plugin: entity_generate
      ignore_case: true
  type:
    plugin: default_value
    default_value: company

```

and a CSV like this:

```
id,title,body,categories
6,company,body text,"cat1, some text;cat1, some other text"

```
> 0 votes

---
Tags: 8, nodes, taxonomy-terms, migrations
---


# Question
Title: rules_invoke_component() - Getting the value of the Provided Variable
In my code, I am using rules\_invoke\_component() to invoke a Rules Component.

On that Rules Component, have 2 variables.

1. Parameter
2. Provided

I am successfully able to invoke the Rule and send the Parameter Variable to it (In this case it was $node). But I am just confused on how to get the value of the Provided Variable.

Is that possible?

# Answer
From the "Tiny book of Rules":

```
Invoking components programmatically

Rules components are handy tools for allowing site builders to customize their own actions and
conditions. If you are writing a module that allows site builders to set custom conditions (or
actions), you can let them set these up as Rules components and then evaluate selected components
programmatically. This works in a way analogous to invoking events, by using
rules _invoke_component() .

The first argument is the (machine) name of the component, and any subsequent arguments are
variables sent to the component.

// Included somewhere in your custom module.

$component name = $settings [' rules component name'];

// Any variables provided from the component are returned from its evaluation.

$result = rules _invoke_component ( $component_name, $var 1, $var 2 ) ;

```

So the last 2 lines in the quote above should answer your question.
> 1 votes

---
Tags: rules, hooks
---


title: List users/roles who has access to node

text:
# Question
Title: List users/roles who has access to node
Asked this question on Drupal.org also, but i think this place is going faster and better :-)

I've installed Content Access and made a view for a Content Type. In the table, users can see content only for them. An admin is giving the rights to view, edit and delete content.

Is it possible to show to users who else has access to a node?

# Answer
> 0 votes
You've tagged the question with *Views*. Are you asking whether it's possible to build a *View* to do that? If so, then the answer is **no** (unless there's some module or plug-in out there which would add that capability).

Views queries the database, but node access permissions can be set in code via hook\_node\_access(). It's totally possible, for example to write some code that grants a user access to a specific node only if they have the letter 'x' in their name and today is Monday.

You can of course do it with some PHP code, and you could hook that into a View using Views hooks. I'm not sure what the most efficient approach would be, but basically:

* Use hook\_views\_post\_execute to process the list of nodes returned by your View.
* For each node in your View result, you would need to loop through all users, calling node\_access() to test if that user (uid) had access to the node or not.
* From the results, build a list of users who had access, and have Views display that list by modifying the *$view* object that was passed to your hook function.

---
Tags: views, users
---


# Question
Title: entity_query: sort: Column not found: Unknown column 'membership__field_year.field_year_value'
I am using a entity\_query, where I get a fatal error because the sort field is not found. The integer field (*field\_year exists*) and exists in the database in the *membership\__field\_year* table in the *field\_year\_value* row.

```
query = $this->entity_query->get('membership');
$query->condition('field_membership_member', $this->member->id());
$query->condition('status', 1);
$query->sort('field_year' , 'DESC');

```

This is the error I get:

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'membership\__field\_year.field\_year\_value' in 'field list'

How do I sort on an integer field?

# Answer
> 0 votes
Found the culprit. Apparently I was calling `$query->execute()` twice.

---
Tags: 8, entities, database
---


title: Turn off webform preview message

text:
# Question
Title: Turn off webform preview message
Before submitting a webform a warning is displayed:

> Here are the details you are about to report.

It appears the default text may be altered in:

*Home \> Administration \> Structure \> Webforms \> Preview settings*

However, can the message be turned off, completely, via the user interface?

# Answer
Fixed! Issue #2917263 There is no way of turning off the preview message
> 1 votes

---
Tags: webforms
---


# Question
Title: Why don't {{ product.body }} and {{ product.field_specifications }} return values in custom commerce-product.html.twig file
I am using Commerce 2.0 on Drupal 8.4.

I have sub-themed Bartik and placed a commerce-product.html.twig file in the sub-theme's /templates folder to experiment with theming a Commerce2 product page.

My product-type has a custom field called 'specifications'. The Manage-display for the product-type places both 'body' and 'specifications' in the Content portion (not disabled).

An example product of this product type was given the following values.

```
title = "Product 1 title"
body = "Product 1 body"
specifications = "Product 1 specifications"

```

The product-display page for Product 1 displays the following for the corresponding twig commands:

```
{{ product.title }} displays "Product 1 title"
{{ product.body }} displays nothing
{{ product.field_specifications }} displays nothing

{{ product_entity.title.value }} displays "Product 1 title"
{{ product_entity.body.value }} displays "<p>Product 1 body</p>"
{{ product_entity.field_specifications.value }} displays "<p>Product 1 specifications</p>"

```

Seeing that

```
{{ product.title }} and {{ product_entity.title.value }} agree.

```

why does

```
{{ product.body }} display nothing while {{ product_entity.body.value }} displays something.

```

and

```
{{ product.field_specifications }} display nothing while {{ product_entity.field_specifications.value }} displays something.

```

(An informative discussion of the field variables available in commerce-product.html.twig is here)

# Answer
> why does
>
> {{ product.body }} display nothing while {{ product\_entity.body.value }} displays something.

This is because {{ product.body }} returns an array not a single value. Body has other properties such as summary so you need to specify what you want from that field.

> why does
>
> {{ product.field\_specifications }} display nothing while {{ product\_entity.field\_specifications.value }} displays something.

I'm not sure what field type you set field\_specifications to, but I'm guessing you set it to a formatted text field. If that's the case it would return an array just like Body would. If field\_specifications was simply a textfield, {{product.field\_specifications}} would have worked.
> 1 votes

---
Tags: theming, 8, commerce
---


# Question
Title: How add markup and prefix / suffix for computed field
I want to add wrapper element to CCK computed field in a content type.

I could calculate the value of field but when I use HTML tags in Display Code section the result is not rendered properly.

for example I use this code in Display Code.

```
$display_output =  '<div class="row">' . $entity_field_item['value'] . ' <span class="suffix">Count</span></div>';

```

But the result is not corrected HTML . it seems it is encoded !!

```
<div class="row"> <span class="suffix">Count</span></div>

```

Can you tell me what should I do to repair this problem ?

# Answer
> 15 votes
I don't know where your variable `$entity_field_item` comes from, but you can generally add additional markup in at least three different ways:

**1. Adding `#prefix` and `#suffix` to the fields render array using a preprocess function:**

```
function mytheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  if ($element['#field_name'] == 'field_myfield') {
    $variables['items'][0]['#prefix'] = '<div class="row">';
    $variables['items'][0]['#suffix'] = '<span class="suffix">Count</span></div>';
  }
}

```

**2. Adding `#prefix` and `#suffix` in `hook_node_view()`:**

```
$node->content['field_myfield'][0]['#prefix'] = '<div class="row">';
$node->content['field_myfield'][0]['#suffix'] = '<span class="suffix">Count</span></div>';

```

**3. Adding a new item to the `$content` array:**

```
$node->content['my_custom_output'] = array(
  '#type' => 'markup',
  '#markup' => $entity_field_item['value'],
  '#prefix' => '<div class="row">',
  '#suffix' => '<span class="suffix">Count</span></div>',
);

```

# Answer
> 7 votes
# Drupal 8

This example simply creates a new markup object from the original text value:

```
use Drupal\Core\Render\Markup;

/**
 * Implements template_preprocess_field__FIELD_NAME().
 */
function MYTHEME_preprocess_field__MYFIELD(&$variables) {

  $original_value = $variables['items'][0]['content']['#text'];
  $variables['items'][0]['content'] = Markup::create('<h1>' . $original_value . '</h1>');
}

```

You may want to check what's inside `$variables['items'][0]['content']` first. As it absolutely depends on the field type and its formatter where the original value can be found:

* maybe `$variables['items'][0]['content']['#text']`
* maybe `$variables['items'][0]['content']['#markup']`
* maybe `$variables['items'][0]['content']['#template']`
* ...

---

This example simply adds some markup on top of the field output:

```
/**
 * Implements template_preprocess_field__FIELD_NAME().
 */
function MYTHEME_preprocess_field__MYFIELD(&$variables) {

  $variables['content']['#prefix'] = '<div class="linkbox-title"><span></span>' . t('Links') . '</div>';
}

```

---

This example wraps the output of every item of a multi-value field:

```
use Drupal\Core\Render\Element;

/**
 * Implements template_preprocess_field__FIELD_NAME().
 */
function MYTHEME_preprocess_field__MYFIELD(&$variables) {

  $element = $variables['element'];
  $items = Element::children($element);

  foreach ($items as $key) {
    $variables['items'][$key]['content']['#prefix'] = '<div class="MYCLASS item-' . $key . '">';
    $variables['items'][$key]['content']['#suffix'] = '</div>';
  };
}

```

# Answer
> 4 votes
If you are using a preprocess function (which would be my choice), you will want to account for the possibility of more than one item in the field:

```
  function mytheme_preprocess_field(&$variables) {
    if($variables['element']['#field_name'] == 'field_my_field'){
      foreach($variables['items'] as $key => $item){
        $variables['items'][ $key ]['#prefix'] = '<div class="row">';
        $variables['items'][ $key ]['#prefix'] = '<span class="suffix">Count</span></div>';
      }
    }
  }

```

# Answer
> 3 votes
I had this problem as well. With the default computed field configuration on a new drupal install, all HTML markup is encoded and printed as clear text. i.e., instead of '**Hello World**' you get '`<b>Hello World</b>`'. This is because the default filter for computed fields in the CCK 'manage display' tab is set to 'plain text'. Change it to 'filtered markup' or 'unsanitized' (use with caution) to get the markup displayed.

Go to Structure =\> Content Types (your type with the computed field) =\> 'Manage Display'.

Make sure the display formatter is set to something other than 'plain text'. i.e. 'unsanitized' or 'filtered markup' generally works well for me.

---
Tags: 7, entities
---