title: Loop setting on video module?

text:
# Question
Title: Loop setting on video module?
This seems like it should be simple, but: How do I make loop true on videos uploaded with D7's video module (HTML 5 Player)? The setting is no where on the front end, and when I dive into the module's theme options, 'loop' doesn't even seem to be a variable? The only variables seem to be:

```
 * $item
 * $width
 * $height
 * $autoplay
 * $autobuffering

```

Placing loop="true" inline would be the obvious option, but this also doesn't seem to be do-able via the D7 module.

# Answer
> 3 votes
You could try to override this in your theme. The video module provides the video-play-html5.tpl.php file. You can copy this file to your active theme (copy it to all if your site supports more themes) and add the `loop="true"` setting to the following line:

```
<video width="<?php echo $width; ?>" height="<?php echo $height; ?>" preload="<?php echo $preload; ?>" controls="controls" poster="<?php echo $poster; ?>"<?php echo $autoplayattr; ?>>

```

Clear the cache to have Drupal detect your template override. That should make the video loop. However this would make every video always loop. If you need control per video, you will have to patch bigger portions of the module, add variables etc. It should be handled in the feature request instead. (It would be out of scope here.)

---
Tags: 7
---


# Question
Title: Implement Twig format in view exposed filter
I have search view UI with two filter criteria.

Basically, to output contents in the page we write `{{ page.content }}`, which I currently used.

What I want is to slice the `page.content` in divs. Search filter will be displayed in, say `<div class="search"></div>` and its result will be on `<div class="results"></div>`.

I found this: Twig Field Value, but confused how to implement it the right way.

In the image below, they are in called in `{{ page.content }}`, so I want to separate the search filter and its result.

Anyone knows how to properly write search UI and its specific fields(as an output) with twig format?

# Answer
For example if you use the preinstalled view *Search Content*, then put the file `views-view--search-content.html.twig` in the template folder of your theme and add the div containers:

```
{%
  set classes = [
    dom_id ? 'js-view-dom-id-' ~ dom_id,
  ]
%}
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}
    <header>
      {{ header }}
    </header>
  {% endif %}

  <div class="search">
    {{ exposed }}
    {{ attachment_before }}
  </div>

  <div class="results">
    {{ rows }}
    {{ empty }}
    {{ pager }}
  </div>

  {{ attachment_after }}
  {{ more }}

  {% if footer %}
    <footer>
      {{ footer }}
    </footer>
  {% endif %}

  {{ feed_icons }}
</div>

```
> 2 votes

---
Tags: theming, 8, views
---


title: Wrong time value in a date field

text:
# Question
Title: Wrong time value in a date field
I've got a Date field in Drupal that I want to preprocess. Unfortunately

```
$node->field_date_time->value;

```

Gives me a value off by one hour (8:00 when expected is 9:00). I believe the issue has something to do with the way Drupal stores the date vs how it displays it later (taking into account Timezones). I tried passing in the default timezone to the DateTime object but that didn't help. I also tried using the `\Drupal::service('date.formatter')` to format the date but the result is still off.

When debugging I found that by using:

```
$node->field_date_time->date

```

I can see the expected date under a protected `DateTimeObject` property (see screenshot).

Does anyone know how to extract it or maybe there's something else that I'm missing? I'm running Drupal 8.1.9

# Answer
> 2 votes
When displaying a date field, Drupal typically converts it to the timezone of the currently logged in user. If no user is logged in, the site's default timezone is used. Perhaps you're logged in as a user that has a different timezone set?

Also, note that the time is internally stored as UTC, so you'll see a time that is off by an hour when simply printing the date's value or using a debugger. If you want to print the time in the user's timezone, try something like:

```
\Drupal::service('date.formatter')->format($date->getTimestamp());

```

This will use the user's timezone, or fall back to the site's default timezone.

# Answer
> 1 votes
The value get with `$value = $node->field_date_time->value;` is the datetime value stored in UTC.

If your convert this string to a DateTime object

$date = new DrupalDateTime($value)

Then you've got a Datetime object with the default Timezone set on the site (Europe/Dublin). To be sure to have the the correct datetime object, you should create a DateTime object with the UTC TimeZone

$date = new DrupalDateTime($value, new DateTimeZone('UTC'));

And then your date object could be format correctly by the date.formatter service which will convert the datetime to the Default TimeZone site.

---
Tags: nodes, 8, entities, datetime
---


# Question
Title: access callback admin permission is not working
This is a follow up to drupal.stackexchange.com/q/228722/9921

I have an api that I creates that I would like to restrict access to users with administrator role. But for some reason the `'administrator permission'` is not working. And the api returns an error when I add this restriction. To clearify the use of language here:

```
    User : admin
    Role : Administrator
if you go to people permissions, Administrator has a permission of type administer permissions

```

I am 100% certain the user is an administrator

```
function mymodule_menu() {
/**
 * Create api callback to return list of users in a give site
*/
  $items['api/v1/userslist'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'mymodule_api_userslist',
    //'access callback' => array('administer permissions'), // tried both and they don't work
    'access arguments' => array('administer permissions'),
    'delivery callback' => 'mymodule_json',
  );
  return $items;
}

function mymodule_api_userslist() {
  // code not included since I know it works if the permission are just all permisions
  $data = Do an entityfieldquery to fetch users and return them
  return $data;
}

function mymodule_json($data) {
  if (is_int($data)) {
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}

```

The above code is being called via

```
  $users = drupal_http_request('http://'.$domain.'/api/v1/userslist');

```

Any ideas?

\____EDIT

```
<?php

/**
 * Implements hook_menu().
 *
 * */
function data_export_menu() {
/**
 * Create api callback to return list of users in a give site
*/
  $items['api/v1/userslist'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'data_export_api_userslist',
    'access arguments' => TRUE,
    'delivery callback' => 'data_export_json',
  );
  return $items;
}

function data_export_api_userslist() {

  $data = data_export_process_users();
  // Do an entityfieldquery (or some other query) to fetch users and return them
  // as an array, not HTML or json. Json encoding will happen in the delivery callback.
  return $data;
}

/**
 * Delivers JSON. Used as a deliver callback for api menu items.
 *
 * @param array $data
 *   An array to be encoded as json.
 */
function data_export_json($data) {
  if (is_int($data)) { //https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_deliver_html_page/7.x
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}

function data_export_process_users () {

  $results = array();

  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'user')
    ->addTag('role_filter');

  $results = $query->execute();

  $users_node_list = entity_load('user', array_keys($results['user']));

  $return_results = array();

  foreach ($users_node_list as $key => $value) {
    $output = array();
    $output['name'] = $value->name;
    $output['email'] = $value->mail;
    $output['init'] = $value->init;
    $output['role'] = array_slice($value->roles, 1, 1)[0];
    $output['status'] = ($value->status) ? 'active' : 'blocked';
    $output['last_access'] = format_date($value->access,'small');
    $return_results[] = $output;
  }

  return $return_results;
}

function data_export_query_role_filter_alter(QueryAlterableInterface $query) {
  $query->innerJoin('users_roles', 'ur', 'users.uid = ur.uid');
  $query->innerJoin('role', 'r', 'r.rid = ur.rid');
  $query->condition('r.name', ['administrator', 'contributor', 'publisher'], 'IN');
  $query->condition('users.init', '', '<>');
}

```

# Answer
Your latest edit clears up where the problem is likely to be:

> The above code is being called via
>
> ```
> $users = drupal_http_request('http://'.$domain.'/api/v1/userslist');
>
> ```

You're probably under the impression that the active user session from the calling site will somehow be passed through to and become valid for the API site? That won't happen, even if it's the same site - you're making a completely new request which doesn't share anything with the request you're making it from.

If you're building a secured API, you need to provide an authentication method that integrates with Drupal's login system, while still handling tokens etc for the API communication itself. That can be a fair amount of work, so people tend to use existing solutions like the Services module.

That module has an authentication layer for the core Drupal user login built in, and provides hooks for you to register your own resources. It will probably take less time to build your API using Services than building and testing your own authentication, so it's worth a look.
> 0 votes

---
Tags: hooks, users
---


# Question
Title: Is it possible to accidentally enable all views at once?
I found all views enabled on a client site. Is it possible to enable all views at once?

Disclaimer: I did a module and core update with drush two days ago, but didn't look at the views list.

# Answer
Accidentally? Possible, but not likely. But I guess it depends what you mean by "accidentally" exactly...

There are perhaps 3 obvious ways to programmatically enable/disable a view (see https://drupal.org/node/820110), plus I'd imagine a few derivatives and/or lower level methods. But enabling a View isn't that straightforward, some manipulation of serialised PHP vars needs to happen somewhere, so I'd say the chances of it being done accidentally are slim at best.

But yes, it's possible to programatically enable all Views at once. It's also technically possible for it to be done via a DB query (i.e. outside PHP), but it would be messing with a serialised PHP array, which MySQL et al don't know how to process, so you can probably rule that out.

Now, if there's a legitimate code/process in your site that intentionally enables one or more Views in certain contexts, and it's being *called* accidentally, or without your knowledge, that's a different story. If that's the case you're probably in audit mode; get a backup of the site from before the update running, switch off modules until the problem disappears, and when you find the culprit, dig into the code to see what's happening.
> 1 votes

---
Tags: views
---


title: How does drupal set user cookie

text:
# Question
Title: How does drupal set user cookie
The following code, let's login any user programmatically.

```
global $user;
$user = user_load(<any_uid>);

```

My question is how does the above code triggers to set new user cookies on browser, at this point we are not even regenerating session.

# Answer
> 7 votes
> The following code, let's login any user programmatically.

Not exactly; it sets the current global user object to an instance of a user, but it doesn't log the account in or touch the session. Many things that happen in that request that rely on the global user object will behave the same as if the account *was* logged in, but it won't be, and they won't have a session tied to the account (not yet anyway).

Cookies are added at the end of the request, in `drupal_session_commit`:

```
if (!drupal_session_started()) {
  drupal_session_start();
  if ($is_https && variable_get('https', FALSE)) {
    $insecure_session_name = substr(session_name(), 1);
    $params = session_get_cookie_params();
    $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
    setcookie($insecure_session_name, $_COOKIE[$insecure_session_name], $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);
  }
}

```

As a by-product of the way Drupal initialises sessions (lazily in an exit hook), if the call to `$user = user_load(<any_uid>);` happens before the first session has been initialised, the session will be initialised for that user and they will appear "logged in" for their next request, even if the `user_load` line doesn't execute.

But, `hook_user_login` won't have been invoked, the last login column in the user table won't be updated, and so on. It's not a full-on "login", just initialising the session for a particular user.

Incidentally, if you call `$user = user_load(<any_uid>);` when a session already exists for another user, the session for the next request will still be for that other user. It won't be overridden with a session for `<any_uid>`.

---
Tags: users, sessions, cookies
---


# Question
Title: Taxonomy terms not mapping in D6>D7 migrate_d2d node migration
I'm using migrate\_d2d to migrate content from Drupal 6 to 7. I have a taxonomy term migration and a node migration. The taxonomy term migration runs correctly and creates 11 taxonomy terms, but when the node migration runs, the terms are not being mapped.

My migration code can be reviewed here: https://gist.github.com/vinmassaro/a7bce8175aa3cafffc2035092b0fe7be

It doesn't seem to be finding anything, because when I examine the output of of `$row` from `prepareRow`, there is no `[1]` element in the object coming from the source. What am I missing here?

Migrate documentation says say the taxonomy terms are mapped this way, which is the format I have it in:

```
$this->addFieldMapping('field_taxonomy_reference', 'legacytermid')
     ->sourceMigration('LegacyTermMigration');
$this->addFieldMapping('field_taxonomy_reference:source_type')
     ->defaultValue('tid');

```

Thanks in advance!

# Answer
> 0 votes
I was not properly implementing the `prepareRow()` method, missing this part:

```
if (parent::prepareRow($row) === FALSE) {
  return FALSE;
}

```

---
Tags: taxonomy-terms, migrations
---


# Question
Title: Service event_subscribe before path_processor_inbound
I have ha service with tag: event\_subscribe (KernelEvents::REQUEST) with priority 30 and in the same module a service path\_processor\_inbound with priority 29

The problem is: in event\_subscribe Service creo a Constant but the service path\_processor\_inbound is called before. I tried all the variants of priority, but it is not the problem.

# Answer
> 2 votes
Both priorities are for different queues. If you set a priority for an event subscriber this is only for the specific event you subscribe to. In this example you subscribe to KernelEvents::REQUEST. Then you can only move up and down in the list of all other subscribers to this event.

You can find more information and a list of the D8 events here:

https://api.drupal.org/api/drupal/core!core.api.php/group/events/8.2.x

Path inbound/outbound processors are not even events. These are handled by the PathProcessor Manager and the priority set here is again only for the list of all other path processors.

---
Tags: 8, symfony-services
---


title: add form to the cart page

text:
# Question
Title: add form to the cart page
Is there a way to add another form to the /cart page in Drupal commerce?

I need to show another view with operations on the cart page for stored shopping carts and quotes. I don't want to change the existing cart view, but add another view to that page.

Is there a way to make this into a panel page and still integrate with the rest of checkout?

Do you have any suggestion?

# Answer
The way I did it was I implemented my own menu item for 'cart' and embedded the cart view on the page where I wanted it, while implementing other things I needed on the page. Definitely not for the faint of heart, though.

In this approach, your page callback is building the elements to be rendered, so you could use views\_embed\_view with the appropriate args if needed, pass them as variables, and render your page template where you want them.

Note: this is for Drupal Commerce in Drupal 7.
> 1 votes

---
Tags: commerce
---


title: Ajax button doesn't work

text:
# Question
Title: Ajax button doesn't work
I followed this tutorial: https://rapiddg.com/blog/creating-ajax-callback-user-reference-fields

to create a button to fill some field in a form with the values of the current user.

Here the cose I added to my hoo\_form\_alter:

```
if ($form_id == 'datore_node_form')
{
global $user;
  $form['title']['#type'] = 'hidden';
  $form['title']['#value'] = 'test';

$form['user_replace'] = array(
    '#title' => t("User Information"),
    '#prefix' => '<div id="datore_node_form_group_cs">',
    //name of the node form (already existing, if you're modifying an existing node form)
    '#suffix' =>'</div>',

    $form['user_replace']['user_copy'] = array(
      '#type' => 'button',
      '#value' => 'Sono io il datore!',
      '#ajax' => array(
        'event'=>'click',
        'callback' =>'user_replace_ajax_callback',
        'wrapper' => 'datore_node_form_group_cs',
      ),
    ),
  );

 $form['user_replace']['field_cognome'] = $form['field_cognome'];
  unset($form['field_cognome']);

  $user = user_load($user->uid);
  dpm($user);
  dpm($user->field_cognome['und'][0]['value']);
  dpm($form);
  dpm($form_state);

  if (!empty($form_state['values']['field_cognome']))
  {
    unset($form_state['input']['field_cognome']['und'][0]['value']);
    $form_state['input']['field_cognome']['und'][0]['value'] = $user->field_cognome['und'][0]['value'];
    return $form;
  }

  function user_replace_ajax_callback($form, &$form_state)
  {
    ajax_command_alert("hello"); // doesn't work
    return $form['user_replace'];
  }

```

but if I click the button nothing happen. Any advise?

# Answer
The only thing you are doing with your code is replacing the button that you are clicking. It's probably getting replaced, but visually will look exactly the same as it did before, which is why it appears nothing is happening.
> 0 votes

---
Tags: 7, hooks, ajax
---


# Question
Title: URL with "en" for english language does not work
I did implement the multilingual. I have successfully translated the content and interface in multiple languages. But when I try to use "/en" in URL for the English language which is the default. It does not work and shows me "404 Page" for default language only.

Can anyone please help me to fix it?

Thanks

# Answer
> 0 votes
I found the solution. Default language "English" requires the code to be enabled like the way when we add/change the code for new languages.

1. Go to configuration click languages.
2. Click "edit" for default language "English".
3. Now put code language code "en" in "path prefix language code" text field."
4. Save changes and access Url with/without "en" code. It will work in both cases for default language.

Thanks.

---
Tags: 7, i18n-l10n, transliteration
---


title: Limit address field postcode and city

text:
# Question
Title: Limit address field postcode and city
I need to limit the commerce\_customer\_address field to 10 cities. You should be able to choose a city from a select list and this should then set the correct postcode. It also needs to be ajaxified so that the postcode updates dynamically. Possible? How?

# Answer
The commerce\_customer\_address is an Address field. You can add your behavior by implementing a custom format plugin, like the one in the addressfield\_example submodule.
> 0 votes

---
Tags: commerce, ajax, entities
---


# Question
Title: Using Migrate API with a multi-page / paginated source
I have a working module pulling a JSON feed into Drupal 8 using the Migrate API. However, the feed is paginated, and I am only getting the first page of results.

For example:

```
{
    "meta": {
        "count": 58964,
        "next": "http://api.example.com/endpoint/?page=2",
        "previous": null
    },
    "data": [
        {
            "id": "id:1",
            ...
        },
        {
            "id": "id:2",
            ...
        },
...

```

I need to go through all pages import them all, but I can't see how to tell Migrate to iterate through the pages.

One option is to use a two-step process: first download all the data to a local file and then import that into Drupal. It would be nicer if Drupal 8 Migrate API could fetch and import all the pages itself.

# Answer
https://www.drupal.org/node/2640516 is the issue to add this support to migrate\_plus.

In the meantime, in a case where I knew up front how many pages there were, I simply listed the pages in the urls configuration:

```
source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls:
    - http://www.example.com/api/search?query=blahblahblah&rowlimit=500
    - http://www.example.com/api/search?query=blahblahblah&rowlimit=500&startrow=501
    - http://www.example.com/api/search?query=blahblahblah&rowlimit=500&startrow=1001
...

```
> 3 votes

---
Tags: migrations, paging, 8
---


# Question
Title: How can I change the page title for user/login for unauthenticated users?
In D7, we need to modify the page title for the user login page (shown when users have not yet authenticated).

The default value is 'User account', and it is set in 'user.module' line 1965: return user\_is\_logged\_in() ? t('My account') : t('User account');

It appears as the page title for the paths: user/register user/password user/login

This is how it is eventually rendered: User Account

To override the value for an authenticated user, we can simply implement

```
function MODULE_username_alter(&$name, $account) {
 $name = 'New Name!';
}

```

But how to override that value for unauthenticated users?

It seems like it should be done in THEME\_preprocess, but I can't seem to find the attribute to set.

I implemented page--user--login.tpl.php, and see there that it is somehow part of $page\['content'\], but can't find the attribute to set.

# Answer
You have alot of good information there (seriously). What you want to do is probably use hook\_form\_FORM\_ID\_alter() on the user form.

You want to set the #title attribute of the form element for the `name` element of the login form.

Some example code:

```
function MYMODULE_user_login_form_alter(&$form, &$form_state) {
  $form['name']['#title'] = 'Your Nickname:';
}

```

You'll probably want to check that a user is not logged in yet with something like user\_is\_logged\_in() or your own custom logic.
> 0 votes

# Answer
I'm working on a group project, and somehow the title of my /user page was something completely unrelated to logging in. I thought I was going to have to create a module as described in the answer just to edit the page title, all the while I was bewildered at how someone in my group had managed to edit the page title without committing any code changes to the project.

I finally discovered that if you create a menu link in a menu to the path /user and you give the link a title, that title will be used as the page title for the login page. At least that's how it's working with the theme I'm using.

So, before you create an entire module to change your /user page's title, just try creating a menu link in any menu and giving that the title you want. Might save you some time.
> 0 votes

---
Tags: theming
---


# Question
Title: Trouble saving canvas as image to the public file directory
I've created a canvas via jQuery and need to save it back to the public file directory as an image, so I can access it like any other image.

I can create the file and save it, into the same file location as my save.php script, but unable to save it to the public file directory...

```
var canvas = document.getElementById('myCanvas');
var dataURL = canvas.toDataURL("image/png");

$.ajax({
  type: "POST",
  url:  Drupal.settings.basePath + "mypath/save.php",
  data: {
     imgBase64: dataURL
  }
})

```

Then the following php as called in save.php:

```
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
$fileName = 'public://' . uniqid() . 'myCanvas.png';
file_put_contents($fileName, $fileData);

```

excluding `'public://' .` will happily save to the location specified in `Drupal.settings.basePath + "mypath/..."`, but I'm unable to tell it to save to the public directory or even any directory structure...

# Answer
You need to create a module, and define a menu path in it using hook\_menu(), and the page callback for that script will be your upload script.

```
function hook_menu()
{
  $menu['mymodule/upload'] = array
  (
    'title' => 'upload',
    'page callback' => 'mymodule_upload_callback',
    'access callback' => TRUE
  );

  return $menu;
}

```

Note that you'll need to name your hook in line with Drupal hook naming conventions: https://www.drupal.org/docs/7/creating-custom-modules/understanding-the-hook-system-for-drupal-modules

Then your upload callback:

```
function mymodule_upload_callback()
{
  // Handle your upload here. You will have
  // access to public:// and the rest of the Drupal API.

  // call drupal_exit at the end() to prevent your
  // script from going past this point.
  drupal_exit();
}

```
> 0 votes

---
Tags: 7, files
---


# Question
Title: How to theme a paragraph bundle with a template file?
I am using the Paragraphs module version `7.x-1.0-beta6` I have a bundle with the machine name: `text_buttons`

In the paragraphs module there are two theme suggestions:

```
 paragraphs-items.tpl.php
 paragraphs-item.tpl.php

```

if I copy `paragraphs-items.tpl.php` to my template folder under my theme, i can modify the code and see the changes reflect site wide wherever there is a paragraph bundle.

Now when I go to target a specific `paragraph bundle` nothing happens at all. I've followed the solutions in the following threads:

Nothing seems to work. Is the module currently broken? do I have to implement some sort of theme hook? I've made sure to flush caches on every change just to ensure I would be seeing the template file but it doesn't work, I've never had a problem with finding theme names before.. The documentation is non-existent for this module, and i really don't want to dig into the module code right now.

Another thing to note is that `paragraphs-item.tpl.php` does nothing on my website from either the module or my theme directory. it seems only `paragraphs-items.tpl.php` works out of the box.

I've tried:

```
paragraphs-items--text-buttons.tpl.php
paragraphs-items--text_buttons.tpl.php
paragraphs-items-text-buttons.tpl.php
paragraphs-items-text_buttons.tpl.php

field--paragraphs-items--text-buttons.tpl.php
field-paragraphs-items--text-buttons.tpl.php
field--paragraphs-items--text_buttons.tpl.php
field-paragraphs-items--text_buttons.tpl.php

field--paragraphs-items-text-buttons.tpl.php
field-paragraphs-items-text-buttons.tpl.php
field--paragraphs-items-text_buttons.tpl.php
field-paragraphs-items-text_buttons.tpl.php

```

**Anyone have an idea why I can't theme my paragraph bundles?**

# Answer
> 9 votes
I had the same question. Here's what worked for me with: Drupal 7.41, Paragraphs 7.x-1.0-rc4.

1. Go to the end of your settings.php file and remove the hash sign to enable "$conf\['theme\_debug'\] = TRUE;" Or add the line if not present.
2. Flush your cache.
3. With your favorite browser, inspect the Paragraph output that you want to override. You should now have HTML comments, just before the actual markup, with template filename suggestions that you can use in your theme.

With my setup, the template filename suggestions are:

```
paragraphs-items--{field name}--{view mode}.tpl.php
paragraphs-items--{field name}.tpl.php
paragraphs-items.tpl.php

```

Where field name is the name of the field you use when you assign the paragraph field to a content type (**not the Paragraph bundle name**).

So in your particular case, if the paragraph field happened to be named "text-buttons" (machine name "field\_text\_buttons"), the filename suggestions are:

```
paragraphs-items--field-text-buttons--full.tpl.php
paragraphs-items--field-text-buttons.tpl.php
paragraphs-items.tpl.php

```

Don't forget to turn off theme debugging on your production site.

Best of luck.

# Answer
> 3 votes
You were soo close, but there is no `s` in `item` when using bundle.

**paragraphs-item--\[bundle-name\].tpl.php**

so for you:

paragraphs-item--text-buttons.tpl.php

---

You can add the view mode if you want:

paragraphs-item--\[bundle-name\]--\[view-mode\].tpl.php

# Answer
> 2 votes
If you have the Edgy module installed the template prefix is `edgy-`.

So in your case it would be `edgy-paragraphs-item--text-buttons.tpl.php`

**Edgy:**

> Edgy allows site builders to display Paragraph items edge-to-edge. It does this by controlling the placement of the .container Bootstrap class.
>
> Using a combination of Paragraphs, Panelizer and Edgy, site builders can create powerful edge-to-edge landing pages. Bootstrap is not a requirement and any theme can be used, however, just make sure you have a container class which centers content.

# Answer
> 2 votes
I believe that theming paragraphs-item does not work as the theming function for a paragraph\_item is never actually called:

> Paragraphs includes a theme template declaration for paragraphs-item, however the ParagraphItemEntity class never uses this, instead it passes the rendering to EntityAPIController, which uses #theme = 'entity'.
>
> This is probably acceptable, but the theme declaration should be removed if that is the case.

from bug in paragraphs module: Paragraphs never calls #theme paragraph\_item

---
Tags: 7, theming, paragraphs
---


title: How to always show "read more..." link?

text:
# Question
Title: How to always show "read more..." link?
Is there an easy way to always show the "read more..." link when text is trimmed in a view?

Was looking for an "Always show read-more link" option for cases when the text is not long enough to be trimmed, but there is none unfortunately. :(

Any suggestions?

Thanks!

# Answer
> 2 votes
1. Add the trim limit for the content field what you want.
2. Add the link to content field in the view and put the display content.

---
Tags: views, 8
---


# Question
Title: Submitting a form with ajax, when multiple instances of the same form are on a page
I am battling with D8 ajax right now, hoping someone can shed some light on where I'm badgering this implementation.

The goal is to update a value based on the on the state of a checkbox. The issue seems to be that there are multiple instances of this same form on the page. However, I've confirmed they all have unique build ids. They *do* have the same `$form['#form_id']`, but I think that's to be expected, `$form['#id']` is different.

Here is the code:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $widget = $form_state->getBuildInfo();
  /* @var $widget Factorywidget */
  $widget = current($widget['args']);

  if ($form_state->has('widget_id')) {
    $widget_id = $form_state->get('widget_id');
  }
  else {
    $form_state->set('widget_id', $widget->id());
  }

  $ajax = [
    'wrapper' => 'widget-toggle-status-wrapper',
    'callback' => '::ajaxRebuildForm'
  ];

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

  $form['toggle_widget_status'] = [
    '#type' => 'checkbox',
    '#title' => 'Toggle Status',
    '#default_value' => $widget->field_widget_status->value,
    '#ajax' => $ajax + ['trigger_as' => ['name' => 'widget_toggle_submit']],
  ];
  $form['widget_id'] = [
    '#type' => 'textfield',
    '#default_value' => $form_state->get('widget_id'),
    '#title' => 'widget ID is',
    '#size' => 10,
    '#disabled' => TRUE,
  ];

  $form['widget_toggle_submit'] = [
    '#type' => 'submit',
    '#name' => 'widget_toggle_submit',
    '#value' => $this->t('Submit'),
    '#submit' => ['::widgetToggleSubmit'],
    '#limit_validation_errors' => [],
    '#ajax' => $ajax,
    '#attributes' => [
      'class' => ['js-hide']
    ]
  ];

  return $form;
}

/**
 * Ajax submit handler that will return the whole form structure.
 *
 * @param array $form
 *   An associative array containing the structure of the form.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *     The current state of the form.
 *
 * @return array
 *   The form structure.
 */
public function ajaxRebuildForm(array &$form, FormStateInterface $form_state) {
  return $form;
}

public function widgetToggleSubmit($form, FormStateInterface $form_state) {
  $widget = $form_state->get('widget_id');
  $form_state->setRebuild();
  /* @var $widget Factorywidget */
  //$widget = FactorywidgetService::toggleFactorywidgetwidgetStatus($widget);

  //return new AjaxResponse();
}

```

Again, there are multiple instances of this form on the page. I added in `widget_id` as a textfield just to see if the widget Id was correct. When *viewing* the page, widget ID in the textfield is correct:

The problem is, no matter what toggle I click, the `widget_id` in `$widget = $form_state->get('widget_id');` in `widgetToggleSubmit` is always the widget Id for the first form on the page. I added a shuffle to the render array which displays these to confirm - it's always set to the first form on the page.

To, hopefully illustrate, this screenshot shows the Debugger for a breakpoint I put in `widgetToggleSubmit` at `$form_state->setRebuild()`:

The toggle has been triggered for the widget with id 3, but `$form_state->get('widget_id')` will only return the value for the first form on the page.

# Answer
> 5 votes
You can do this by setting a custom form ID for each form. So you define your form like this:

```
class MyForm {
  protected $formId;

  public function __construct($formId) {
    $this->formId = $formId;
  }

  public function getFormId() {
    return 'my_form-' . $formId;
  }
}

```

Then, when you call your form, you pass a unique Form ID for each form:

```
$my_form = new MyForm('some-unique-id');
$form = \Drupal::formBuilder()->getForm($my_form);

```

Pass a different ID for each form on the page.

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


# Question
Title: Customizing Search File Attachments result page
I'm using search\_file\_attachments module for my search, And also `Search combine` module to show all the results in one page. In the search results page, I like to maintain a structure. I need to show the `node title` instead of `attached file name`, and redirect to `node url` instead of `attached file path` when a user click on a result. So implement the `template_preprocess_search_results()` in my module overwrite the results. I tried to figure out the array result using `devel`.

```
function template_preprocess_search_result(&$variables) {
  dpm($variables);
}

```

And this my Devel results:

I cannot see any node details here, I guess this module only searching files in the folders. I'm finding a way to get the node details related to this results. Hope you guys got my question, Thanks in advance,

# Answer
> 1 votes
Finally I ended up with some advanced search modules, Which made the search so much better. I used Apache solr and Apache solr attachments modules. This gave me ability to make my search results in a customized way via hooks. I use `hook_apachesolr_process_results()` to change my results.

First I add a extra field to the file type entities in the solr index, which contain the node title.

```
/**
 * Implements hook_apachesolr_index_document_build().
 */
function mymodule_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
    //dsm($entity_type);
    //if the type is file
    if($entity_type == 'file'){
        //add a field node title
        $title = code for getting the node tile of this file
        $document->addField('ts_field_node_title', $title);
    }
}

```

Now this extra field will be available in your search results. So you can directly use the title instead of file name.

```
/**
* Implements hook_apachesolr_process_results().
*/
function mymodule_apachesolr_process_results(&$arg) {

    for($i = 0, $l = count($arg); $i < $l; $i++) {
        //if entity type is file change the title
        if($arg[$i]['node']->entity_type != 'node'){
           $arg[$i]['title'] = $arg[$i]['fields']['ts_field_node_title'];
        }
    }

}

```

Peace! :)

---
Tags: theming, search
---


# Question
Title: {500 service unavailable (with message)} error when trying to register a user with API
I want to register a user on drupal site through REST, I read this article, and implemented the instructtins exactly the same using Postman on `drupal 8.3`.

specially when I send this specification :

```
POST: http://example.com/user/register
Content-type: application/json
Data: { "name": [
  {
    "value": "test"
  }
],
"mail": [
  {
    "value": "aa@bb.com"
  }
],
"pass": [
  {
    "value": "test"
  }
]  }

```

Response is: 500 service unavailable (with message)

What should I do to solve the problem?

# Answer
> 1 votes
Just a stab in the dark here.

It seems that you have extra square brackets. I think this is why your error message refers to field 0 -- you're sending it an array. Try it exactly as the article displays, with no square brackets?

For example: "pass": { "value": "test" }

Good luck.

## Update

To enable setting a password, you need to change a setting which is default in the install.

Go to admin/config/people/accounts (Configuration \> People \> Account Settings) and **uncheck** "Require email verification when a visitor creates an account":

Granted you are allowing POST to Anonymous users as described in the article above, you should be good to go and get a response such as the following in PostMan:

```
{
  "uid": [
    {
      "value": "5"
    }
  ],
  "uuid": [
    {
      "value": "70738718-d4e9-455e-a1f6-cf95df613507"
    }
  ],
  "langcode": [
    {
      "value": "en"
    }
  ],
  "name": [
    {
      "value": "ac@bb.com"
    }
  ],
  "created": [
    {
      "value": 1487319576
    }
  ],
  "changed": [
    {
      "value": 1487319576
    }
  ],
  "default_langcode": [
    {
      "value": true
    }
  ],
  "user_picture": []
}

```

Hope this helps!!

---
Tags: 8
---


# Question
Title: /index.php/ appearing in generated clean URIs
I have a Drupal 8 site with clean URLs. Recently, URLs are similar to example.com/index.php/page-url-alias. The page still loads correctly, but I don't want the `index.php` part to be indexed.

If I empty the cache, the URLs are shown correctly.

How can I force Drupal not to add index.php in the URLs it generates?

# Answer
In D7 Global Redirect was used for clean urls. In D8 this was moved to the module Redirect.

The global redirect options in Redirect are set by default to avoid unclean urls:
> 2 votes

# Answer
Might not be a clean way but you could do this via your .htaccess, Something along the lines of this:

```
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

```

Not sure if this works in drupal, i have used this on other CMS.
> 1 votes

---
Tags: 8, uri
---


# Question
Title: How should I add multiple markers using geofield module?
Whenever I set the module with unlimited values there are more the one maps with location. However they show the location which I want, but in two or more different maps.

My problem is I want to integrate multiple location with a single map. My project is kind of setting the route for people.

How do I do that? Should I create a hook for the Geofield module?

# Answer
> 1 votes
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.

**Note**: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.

PS: I'm assuming this question is about D7 ...

---
Tags: google-maps
---


# Question
Title: How to plot a chart from CSV uploaded in a content type?
I am uploading TXT and CSV files in a content type. While displaying it, I have to show that as a chart when users viewing the content of that content type.

I have tried using the Charts module, etc. Though I am able to plot the chart reading from a file by giving absolute path, I am not able to do it dynamically. Is there a better way of doing this (using Drupal 7)?

# Answer
> 0 votes
The Easychart module may be close to what you're looking for. It comes with these facilities:

* Pasting of CSV data to create charts from it.
* Entering an URL pointing to a CSV file containing the data to be charted.

For an extremely short demo of these facilities, have a look at this video.

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

* It defines a new content type (= *Chart*) used to add charts to your site.
* It creates a chart widget that can be used in your own content types.
* It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (*CKeditor* and *TinyMCE* are supported).
* It provides an intuitive interface to configure charts through the Easychart plugin.
* The Government of Flanders contains some real world examples of a Drupal website with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

If you're using an URL pointing to a CSV file with data to be charted, then be aware of what's mentioned in comment nr 5 of the issue about "EasyChart data doesn't update unless I edit and save the chart node", i.e.:

> For performance reasons, the external csv data is only updated when cron runs.

# Resources:

# Notes:

**(1)**: To resolve an error like "*Highcharts not defined*" (as per your comment below this answer, you may want to have a look at the issue titled "Highcharts is not defined". Comment # 2 in it includes a possible explanation for that error, ie:

> It was a permissions issue on the library. For some reason the highcharts library had permissions set to: drwx------@
>
> This worked fine on my local machine, but not on shared hosting. I changed them to: drwxr-xr-x to match all the other libraries.

**(2)**: From the Easychart project page:

> Make sure to clear the website's css-js cache after installing the javascript dependencies

**(3)**: The Highcharts library needs to be placed in `/sites/all/libraries/highcharts` (as mentioned also in the README.txt)

---
Tags: 7, importing-exporting, charts
---


# Question
Title: How can I alter the inline entity fields on a node edit form?
I want to hide some fields of product reference on node edit. My purpose is to unset or set access to false for colors or price field of line item included in node as inline entity from in a content type. I am using hook as

```
$form_state){
dsm($entity_form);
unset($entity_form['field_product_colors']); // remove "colors" field from inline entity form
 }

```

but hook is not called at this screen when user edit a product on node edit i have shared a node edit screen where product is edited by click on edit link and then update some thing but dont want colors and price to be shown there

# Answer
Actually documentation of module in readme file the hook was written and i was using that hook but only problem was the custom module name. if your custom module name is two parts like custom\_websitename then this hook did not work in my case, so after one day i changed module name to single word and hook worked.. I am sharing code incase someone need to update lineitemform in node edit for drupal commerce.

```
function customruba_inline_entity_form_entity_form_alter(&$entity_form,   $form_state){
$entity_form['commerce_price']['#access']=false;
$entity_form['field_commerce_saleprice_on_sale']['#access']=false;
$entity_form['field_commerce_saleprice']['#access']=false;
$entity_form['status']['#access']=false;
}

```

this worked for me to hide some information on inline entity form
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: LogicException: The controller must return a response (Object(Drupal\Core\Render\Markup) given)
I'm getting this error:

> LogicException: The controller must return a response (Object(Drupal\Core\Render\Markup) given). in Symfony\Component\HttpKernel\HttpKernel-\>handleRaw() (line 157 of C:\xampp\htdocs\drupal-8.1.10\vendor\symfony\http-kernel\HttpKernel.php).

Below is the code that I'm trying to execute:

```
<?php
/**
 * @file
 * Contains \Drupal\my_module\Controller\DefaultController.
 */

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Default controller for the my_module module.
 */
class DefaultController extends ControllerBase {

  public function my_module(\Drupal\user\UserInterface $user = NULL) {
    $name = $mail = $roles = $picture = "";

    if (!$user->getUsername() && $user->getUsername()) {
      $name = $user->getUsername();
    }

    if (!$user->getEmail() && $user->getEmail())->get('my_module_user_email_display_status')) {
      $mail = $user->getEmail();
    }

    foreach ($user->getRoles() as $value) {
      $roles = $value;
    }

    $user_data = [
      'name' => \Drupal\Component\Utility\SafeMarkup::checkPlain($name),
      'mail' => \Drupal\Component\Utility\SafeMarkup::checkPlain($mail),
      'roles' => \Drupal\Component\Utility\SafeMarkup::checkPlain($roles),
    ];

    $my_module_template_build = array(
      '#theme' => 'my_module_template',
      '#details' => $user_data,
    );

    $my_module_template = drupal_render($my_module_template_build);

    return $my_module_template;
  }
}

```

# Answer
You can return `$my_module_template_build`, e.g.:

```
$my_module_template = \Drupal::service('renderer')->renderRoot($my_module_template_build);

```
> 2 votes

# Answer
You've to return a response using Response Object, instead of returning rendered HTML as string, check code snippet provided here.
> 1 votes

# Answer
Try

```
return array(
  '#markup' => $my_module_template
);

```

Instead of

`return $my_module_template;`
> 1 votes

---
Tags: theming, 8
---


title: Boost not create cache files

text:
# Question
Title: Boost not create cache files
I have enabled the boost module. It creates a folder till "cache/normal/example.com". But there is no cached html files.

I am struggling with this, any help?

# Answer
Without any further information, I would check the permissions on your directories. In my D7 install, I don't have a 'cache' directory, so it looks like it will need to be created either by Boost itself or by you manually.

Try this on your web server as root user:

```
$DRUPAL_INSTALL=/var/www/path/to/your/drupal
$WEB_USER=apache
mkdir -p $DRUPAL_INSTALL/cache/normal
chown -Rv $WEB_USER:WEB_USER $DRUPAL_INSTALL/cache
chmod 755 -Rv $DRUPAL_INSTALL/cache

```

The above will create your 'cache/normal' directory in the drupal root (where index.php is). Then it transfers ownership of these directories to the web user, assuming apache here. Finally it corrects the permissions.

Be sure to modify the $DRUPAL\_INSTALL and $WEB\_USER variables to match your web server's environment.
> 0 votes

# Answer
If the configuration seems correct, there are still some circumstances, where the page get's not cached by boost.

You can place the boost block (called ***Boost: Pages cache status*** \- that will show you information about the cached page, or tell you that it won't be cached) on every page to start diggin.

Most common causes can be:

* PHP execution in a block (php module enabled ..)

Solution would be to create a custom block in a custom module doing that php

* Authorized user has dependencies on the content shown. The page gets only cached for anonymous users

Solution would be to load that part via AJAX, also consider using authcache, which does that for the most common use cases

* ...
> 0 votes

---
Tags: .htaccess, caching
---


# Question
Title: How to set a new taxonomy term without overwriting an existing one when using Rules?
I'm using the Rules Action **`Set Data Value`** to set a taxonomy term for a specific user (uid= 75). The tag field exists in the user entity, and is set to "Unlimited".

There's nothing complicated about the rule, which looks like so:

```
{ "rules_invited_user" : {
    "LABEL" : "Invited user",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [ { "data_is" : { "data" : [ "account:uid" ], "value" : "75" } } ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-user-tag" ], "value" : "27608" } }
    ]
  }
}

```

I can set the term, but if there's another term set already for that user, it's overwritten.

***How can I set a new term without overwriting an existing one?***

# Answer
The Rules Action **Set a data value** that your Rule uses, can only set 1 value, while you're trying to update something that is a list (or to use your own words: "*... set a new term without overwriting an existing one*").

So try to replace your Rules Action (ie with the `data_set`) with an action "**Add an item to a list**". When doing so, you probably also want to set "ENFORCE UNIQUENESS" to `true`, so that you "*only add the item to the list if it is not yet contained*". Even though for your case it may not make a difference, IMO that is a kind of safety-belt when using this action.

For way more details about this, refer to "How to set multiple values to an unlimited Term Refence field with Rules". While reviewing this, also pay attention to the "Fetch entity by ID" (within the Rules loop): I wouldn't be surprised if you'd also need to add a similar "Fetch entity by ID".

Ps: I'm assuming this question is about D7 ...
> 2 votes

---
Tags: taxonomy-terms, rules, users
---


# Question
Title: Hide node title on front page using template.php not css
I'm building a drupal 7 bootstrap sub theme and want to hide the title of the nodes if there on the home page. I don't want to use css as its only hiding it I want to have the titles not render at all.

i have tried hook\_preprocess\_page() but didnt work:

```
function mytheme_preprocess_page(&$vars) {
    if ($vars['is_front']) {
        $vars['title'] = '';
    }
}

```

# Answer
Your close with `hook_preprocess_page()` but as you want to hide the node title (and not the page title) you need to use `hook_preprocess_node()` instead.
> 4 votes

# Answer
Going via `hook_preprocess_page()` this one worked for me:

```
function MYTHEME_preprocess_page(&$vars) {
  if( drupal_is_front_page() ) drupal_set_title('');
}

```
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: Why this message "You are not authorized to access this page." coming on user edit page?
I am facing a strange behavior today, when I signup via Facebook or twitter and then go to user edit page it show this message:

> You are not authorized to access this page.

Even if try to access this page from admin login the same error is coming. But if in signup via email then everything working fine.

I am using these modules as well LoginToboggan, HybridAuth Social Login.

# Answer
*Ohhhhh,* At last i figured it out. when i signup via Facebook or Twitter , user's language does not save and when i access the user edit page it gives error that you are authorized to access this page, and now i write my own function which set the default language for user and everything working like charm !!! thanks
> 0 votes

---
Tags: 7, users, authentication-authorization
---


title: Get contents of temporary uploaded file

text:
# Question
Title: Get contents of temporary uploaded file
I've uploaded a file in a custom form and I can retrieve the file instance like this:

```
  $fid = $form_state->getValue('file')[0];
  $file = File::load($fid);

```

How can I get the contents of the file?

```
kint(file_get_contents($file->url()));

```

Returns false. If I visit the link manually, it gets downloaded.

# Answer
You can't get the file from `$form_state->getValue()`. You have to upload the file first to the file table as temporary file with `file_save_upload()`. Then you can load the file content locally from `$file->getFileUri()`.

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

    $validators = ['file_validate_extensions' => ['txt']];
    if ($file = file_save_upload('file', $validators, FALSE, 0)) {
      $data = file_get_contents($file->getFileUri());
      drupal_set_message($data);
    }

  }

```
> 9 votes

---
Tags: 8, files
---


# Question
Title: Is there an easy way to move user data between 2 sites?
I am totally new in Drupal, and I am using Drupal 7. I was asked to move data between two sites that don't even have the same structure, and have different fields.

Can anything bei done with a tool like Drush, or with MySQL?

# Answer
> 0 votes
You could possibly use views to output the data you want into a csv file (with views data export module) and then import the data into the destination site using Feeds module. This technique has worked well for me on a number of occasions.

Additionally, you could try the Features module but this is quite complicated and may be difficult to get your head around initially.

# Answer
> 0 votes
Did table download from the old webforms, corrected all field keys and filtered data into a new CSV file, and through "Upload" in the new webform. Not sure why it only accepted 11 rows at a time, but got all transferred. Final tunig was done direct in MySQL database.

---
Tags: 7, drush
---


# Question
Title: Frontpage module redirecting to /user/uid not correct url on login
The frontpage module redirects to `/user/uid` on login, not the specified redirect URL. All config looks correct. I have all redirects set to `node/1` which is where I want it to redirect.

# Answer
You can create a rule for this. when user logged in site then it will redirect on node/1 site.
> 0 votes

# Answer
It was due to a conflict of other modules. The ajax\_register/bootstrap\_login\_modal modules were disrupting normal redirect flow with their config since AJAX redirects in forms are handled differently.
> 0 votes

---
Tags: 7
---


# Question
Title: How to change background image based on current node?
I am trying to change the header background image of my website based on the current node. I have added an image field to my content type, `field_hero_image`, and, in preprocess function `mytheme_preprocess_page(&$variables)`, I get the image url and try to inject it in the page, as inline css:

```
function mytheme_preprocess_page(&$variables) {

    $node = $variables['node'];
    if ($node) {
           $path = file_create_url($node->field_hero_image->entity->getFileUri());
            $variables['page']['#attached']['css'] = array(
                'data' => '.header-wrapper { background:url(' . $path . ') center center no-repeat !important; background-size: cover;}',
                'type' => 'inline',
            );
    }
}

```

or

```
function mytheme_preprocess_page(&$variables) {

    $node = $variables['node'];
    if ($node) {
           $path = file_create_url($node->field_hero_image->entity->getFileUri());
           $variables['#attached']['library'][] = array(
            'data' => '.header-wrapper { background:url(' . $path . ') center center no-repeat !important; background-size: cover;}',
            'type' => 'inline',
        );
    }
}

```

None of this works.

Is there a way to inject css from the preprocess function? I know that I can get the path value, put it in $variables and use it in twig. But this doesn't seem a clean solution to me.

# Answer
> 0 votes
You can make a different templete and use, for example, a class and load the different img by css is one of many possible soluctions, I think that is the best practice

You can read more about Drupal 8 Temple in these threads:

https://www.drupal.org/docs/8/theming

https://www.drupal.org/docs/8/theming/twig

Example aplications

```
function YOURTHEMENAME_preprocess_node(&$variables) {
  if ($variables['node']) {
    $node = $variables['node'];
    switch ( $node->nid ) {
    case 'nid1':  // Replace nid1 etc with your nid
    case 'nid2':
      break;
    }
  }
}

```

Template/node/node--full--\[nid\]

```
    <div class="img--hero--image">
    </div>

```

Other solutions it is use a field in the content type and use this field to render in your background.

---
Tags: 8, theming
---


# Question
Title: How to do push data to datalayer after Ajax callback?
I have a view with many elements and use views load more -\> view using views load.

Modules:

Is it possible send datalayer event after load elements with AJAX?

I am tracking with Tag manager (Google).

# Answer
I had the same problem. Events were only sent first time and then never. I solved it purging completely cache, and fixing my google tag.
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: How to make strings from templates translatable on all pages they appear?
I have some calls to `t()` in \*.tpl.php files. For the sake of example, let's say I'm talking about products and product.tpl.php file.

Strings in templates are not recognized until the first time they are actually used. There was a thread on Drupal.org about that and I found it to be accurate. Sadly, if I go to, let's say, http://example.com/pl/product/200, then that string will be saved in `{locales_source}` table with `location` field set to `/pl/product/200`.

I need my users to be able to translate using Localization client module's on-site translation tool, so they can actually see what they are translating, having it in proper context. With source location set to `/pl/product/200`, the product with ID 200 is the only one on which the string is shown to be translated. And far worse, if I may be able to force users to translate on that particular product, I need them also to be able to translate to russian, and there is no product with location set to `/ru/product/PID`.

**Is there a way to re-format location string in database, to make all strings visible on all products, all languages in l10n\_client tool?**

I tried setting it to:

* `; sites/default/themes/mytheme/product.tpl.php`,
* `sites/default/themes/mytheme/product.tpl.php`,
* `sites/default/modules/mymodule/mymodule.module` (module that generates themed data)

But it only made them invisible for the translation tool.

I'm pretty sure it's not a bug in Localization client, it shows the string where it's told this string occurred. And it seems it's "just the way it works" for Drupal 7 translation system, too - was discussed and reported already, and nothing changed. So this isn't a bug report, I just ask how to work with what we have to work with.

---

I'm talking about texts that have **nothing to do with the** data **module** operates on. **I don't want to translate products, just template strings that have nothing to do with product itself, like Previous - Next on product image gallery template.**

For example, module returns 15 thumbnails, and it is a theme's job to show 5 a time. And previous / next links needs `alt` and `title` attributes. Translated. But my module does not know that. And never should need to.

# Answer
**Your requirement:**
*In order for my site to work in multiple languages
as a authenticated user
I need to be able to translate at once any and all translation calls found in my site's codebase that were done with the t() function.*

Is that requirement description even close to what you're asking for?

---

**Crawlers**

Like someone said - a crawler could *theoretically* go through the entire site to force the registration of all t() calls. But 1) the crawler does not know which pages to crawl; 2) we are not looking to maintain a list of pages to crawl, therefore; 3) we don't want to use a crawler, period. Eww. Just, eww. Right?

---

**The problem**

1. We don't have a list of all translation strings.
2. Drupal/PHP is a dynamic language unlike C which is compiled. So we cannot go and say for example: compile this entire codebase, then find me all instances of this function `t()`, then register those instances in the database, then translate all those registered instances of `t()` in one go. I don't think is an option we have on our table.
3. A static code analysis tool would be helpless for the same reason a crawler would be helpless. I found this `t()` in this file. Great! What URL is it used in? What's the context?

Attacking the problem with the current tools (Drupal, and some contrib modules), and with the current constraints (relying on real-time theme calls -\> template files -\> `t()` calls), looks like a no-exit alleyway here. We might need to think a little bit out of the box.

---

**What we need**

1. We need a data source, a model, that tells me which current translation strings we have, and what is their context -
2. Proactive data model. The current data model is reactive (the model gets updated whenever a call to `t()` happens). We need a proactive data model - one in which the application takes care of looking for `t()` instances before they actually get executed by the customer.
3. We need context. `t()` alone does not cut it - because - we do not know we are translating 'foo', but the target language we are translating to depends on the URL of where the `t()` occurs on. Even if we could hardcode the target language into the `t()` call, say, using a wrapper call, it would not work for your purposes.

I have identified some of the tools that - if we had them - would help our problem. With these tools we could go into the data model and say: *give me all the strings wrapped in `t()` that have not been populated yet. Now insert these translations. Thank you.*

And the next time the customer comes, the translations are there in place.

**How would we...build these tools?**

---

**Constraints**

1. The target language cannot be on the template, that is decided by the URL. Assuming the string must support any language.
2. The translated string cannot be on the template. The translation will reside in a database.

---

Now that I've given the problem more thought, and identified some challenges and constraints, I can think about looking at any solutions available out there, or at making any custom solutions.

**Solution brainstorm**

I need something that ties "everything" together. What about...an entity?

* An entity can hold the product that needs to be translated.
* Entities can provide the relation - the glue - between the product that needs to be translated, and it's context.
* The entity can specify say, in a field, the default URL location of the product.
* Tokens can be used to specify alternative locations (languages?) that the product will appear on.
* Entities provide us with the proactive data model that we need, and it's context. Which in turn allows us to do thing such as: go into the database, grab all the product entities, and if the do not have a translation string for fields X, Y, and Z, create those translation strings.

When the customer then grabs `/pl/product/200`, you take a trip to the db, look up product 200, and grab the already existing `pl` translation. You have a title and caption field for that product as well? The translations should be there also.

Note that I'm being very vague and generic here in terms of what translation module you're using. You could very well end up using your own translation module - most likely this is the case. All the translations models I've seen in Drupal so far (as of D7, haven't looked at D8 yet) are reactive, not proactive.

**In a nutshell**

In theory, the tools to build what you need are there, entities being the key component that would tie everything together: \- data (translation string), \- target languages. Don't have to be on the Entity itself, preferably a taxonomy vocabulary, say for product languages. or maybe a generic taxonomy for other entities as well. \- Context. The URL that the entity appears on. The URL would contain a token, and the token in turn would reference the target language taxonomy.

With those three ingredients you can say: *Grab all the `product` entities, go to the `URL alias` field, get the taxonomy token, cycle through all possible term combinations, present all combinations to the current user using either a very large ugly form - or, AJAX - and multi-step forms (something like that), and as the currently logged in user translates the various languages for product 200, save those somewhere into the database*

Somewhere in the database could be a Field API field in the entity, the settings field belonging to each entity (not exactly Field API, but it can still hold data), or a separate table that you use for this. I think saving the data into the Entity would keep both the code and data tidier and easier.

---

**Building It: Possible solutions**

* D8MI (Drupal 8 Multilingual Initiative)
* Custom code: "index" translations made available in templates by t() by programmatically querying and rendering available bundles and their related theme hook implementations.

---

**Pseudocode**

***Foreach entity (of type x),***
*Find all languages (taxonomy or core language associated with product),
Render the entity,
\- in order to detect it’s t() translation strings
\- render calls theme(), which handles the multilingual presentation layer of the product, not the product data model itself.*

**Result:**
*\- First call to render entity template in each language returns the default language implementation for each call.
\- The t() parameters on the template are now cached in Drupal and ready for translation (for each language instance, not each product instance).
\- User with “translator” role can now go to translation interface and translate all available t() parameters, for each language.
\- Site owner does not need to wait for customers to visit each product page, or visit each product page manually, as this was done programmatically for him.*

**Open questions:**
*\- What is the context? If I do a programatic call to theme() for each “product” entity bundle, does it record the location from which the call was made? Does it record the URL of the node? Can the “context” be altered? Where is the context recorded? What happens when you have "dynamic" templates - i.e., when you have more than one template per product and how you go about detecting those variations?*

As always, theorizing and pseudocode is only good for brainstorming. But in development we'll hardly know what we're really up against until we start prototyping. So having drawn up a couple of constraints, possible solutions, and possible problems or questions - I can now proceed to implement a proof of concept or working prototype. Some of the open questions above can only be answered this way, and the earliest we prototype (regardless of success or failure), we can start answering some of those questions - or change the approach altogether. Stay tuned ~
> 6 votes

# Answer
Ok, Spent some more time with Localization client & entity translation module to reproduce the same scenario. Since this answer is totally differnt from my previous one, adding as separate comment:

1. **The translation added for a language in one/first node is available for all nodes.**

Here is an example:

* If I add new product of same type as nid 200 and visit the pl translation the new node(say pl/product/204), I would see the same translation string in pl/product/200.
    * Only difference is it doesn't appear in Localization client. We can ask for this feature in the module's issue queue, however it would introduce more confusion as the translation is not specific to current page and would affect all pages (i.e. both pl/product/200 & pl/product/204).
    * If the two nodes created by two different persons, and the later one wants to change the translation, then they have to use the interface translation.
2. **The string is available in Localization client for the first language you visit for the same node**

Here is an example:

* If I add new product nid 199 and create translation for 'pl' language (nid 200) and translation for 'rs' language (nid 201), you can see the string only on 'pl' page, not on 'rs' page. Again, this looks like a restriction in the Localization client module.
> 2 votes

# Answer
Your approach to add the translation string on template or module file level may work for interface translation UI, but not Localization client.

Obviously when you have Russian version of the product 200, it will be a new node, say for example /ru/product/201 where you can translate using Localization client.

Just a thought: Look for a string that can be translated for all languages in interface translation UI and ask customer to translate product level when it is really necessary. Here is an example:

"This is product foo of category bar"

and if we are sure that other than 'foo' & 'bar' can be common, the we can add

```
$vars['product_title'] = t('This is product @product of category @category')

```

in preprocess.

and the .tpl.php file will be

```
<?php t($product_title, array('@product' => t('foo'),  '@category' => t('bar')); ?>

```
> 1 votes

# Answer
AFAIK with the Translation template extractor you can extract the string within all your calls to the `t()` function.

> The Translation template extractor provides a web based and a command line Gettext translation template extractor interface for Drupal as well as a reusable API to look for translatable strings and translatability errors. This tool is used under the hood at http://localize.drupal.org/ as well to serve as a parsing machine for Drupal.org project releases.

Read this How to Translate a module?
> 1 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: How to grant access on some functionnalities in system dashboard to a given role
How can I grant access on system dashboard to a given role. Let's assume the role is "Webmaster". So when a user with this role logged in, he will land to the admin page as if he belongs to the "admin" role, but with fewer options available. For example he will not be able to see the "configuration" menu, and so fourth...

Because what I actually have is, when this kind of user logged in, he lands on a user page like other authenticated user (I mean a regular front page).

Thanks for your help

# Answer
By default, when a user logs in on Drupal, they are redirected to /user (the user page). If you want to change that behavior (so they are redirected to a custom dashboard page that you create (ie: /admin/dashboard) you might be able to use Rules (assuming you are on D7 - Rules is not ready for D8 yet as far as I know). You would create a Rule that triggers when a user logs in, add a condition to check there role, and an action to redirect them to another page.

You may also want to read this, because there may be more conditions you want to include, so that they are NOT redirected when they are resetting their password, for example: https://www.drupal.org/node/480584

As for hiding Configuration menu and other things, that is accomplished by assigning (or not assigning) permissions to the user roles. So your admin role should include access to Configuration, but your other roles should not.
> 0 votes

---
Tags: dashboard
---


title: Export Nodes to RSS or CSV

text:
# Question
Title: Export Nodes to RSS or CSV
I need to export blog entries from Drupal to a XML RSS feed or a CSV file. I have spent countless hours trying to export it, however, no results whatsoever. I have created a new view based on the defaults of the Blog node and have set the following parameters:

* Style: RSS Feed
* Row style: node
* Items to display: 25
* Path: latestblogs/feed
* Attach to: Blog page

The feed page does work, however, none of the entries are appearing. What do you think is the issue?

# Answer
> 1 votes
If you want to export a View as XML or CSV, you will want Views Data Export.

Edit: now that I know this is for Drupal 6, you will have to dig to find the releases for 6.x on the project page. Here they are.

---
Tags: views, importing-exporting, feeds
---


# Question
Title: How to get Google Analytics to track progress through a multi-page Drupal Webform?
I've got a couple of complex multipage webforms, and want to track progress through these forms so that I can how much time users are spending on each page, and whether there are particular pages that cause users to drop out altogether. I thought Google Analytics could do the trick, but it seems to require a unique URL for each page, and that's something that the Webform module doesn't provide.

Has anyone got this to work, and if so how?

# Answer
if the url doesn't change, you can use google's single page applications approach to track:

https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

You can set a "virtual" url for each page using javascript. Then create a goal funnel in Google Analytics using these virtual url's. You'll probably need to custom write this js to look for specific fields etc to let it know which page it's on.

I think another way is to use custom fields in the call to ga. Not sure if those are available as goals though.
> 2 votes

---
Tags: webforms, google-analytics
---


# Question
Title: Make all the fields in a form not required
I know that, when I want to run off the `#require` property of a field in `hook_form_alter()`, I just need to set `#require` property of a specific field to `FALSE`.

How can I remove the `#required` property of all the required fields? I want to make the fields not required when the user has a specific role.

Do you have any idea?

# Answer
If you're ok with the risks that this might well pose to the integrity of your content you could probably use a simple recursive script like the following in a form alter function:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'myform_name') {
    $form['#after_build'][] = '_MYMODULE_remove_required';
  }
}

function _MYMODULE_remove_required(&$element) {
  $element['#required'] = FALSE;

  foreach (element_children($element) as $key) {
    _MYMODULE_remove_required($element[$key]);
  }
}

```
> 11 votes

# Answer
```
   function hook_form_alter(&$form, &$form_state, $form_id) {
     if ($form_id == 'myform_name') {
       if (in_array('administrator', $user->roles) {
         $form['#after_build'][] ='mymodule_recursive_unrequired';
       }
     }
   }

   function mymodule_reqursive_unrequired($element) {
     foreach (element_children($element) as $name) {
       $element[$name]['#required'] = FALSE;
     }

     return $element;
   }

```

I didn't test it yet; it is just an idea.
> 3 votes

# Answer
I used this answer and thought I'd share some improvements:

As above, add the following function as an #after\_build callback for the appropriate users.

```
/**
 * Removes "required" from all form elements.
 * Use at your own risk.
 * Use:  in a _form_alter function, $form['#after_build'][] = 'MYMODULE_remove_required';
 * @param array $element
 * @param array $form_state
 * @param int $depth
 * @return mixed
 */
function MYMODULE_remove_required($element, &$form_state, $depth=0) {
  if ( $depth > 6 ) return $element; // put a limit on recursion
  if ( !empty($element['#required']) ) $element['#required'] = FALSE;
  // only iterate over children for likely elements
  if ( empty($element['#type']) || !in_array($element['#type'], array('radios','checkboxes')) ) {
    foreach ( element_children($element) as $name ) {
      $element[$name] = MYMODULE_remove_required($element[$name], $form_state, $depth+1);
    }
  }
  return $element;
}

```
> 2 votes

# Answer
You can also try Required by role module.
> 1 votes

# Answer
UPDATE: The solution I posted seems to be a bad idea. When you reset the $form\_state\['values'\] array, what is actually happening is that you are removing the form token id. You could get the same effect by adding:

```
$form_state['values']['form_token'] = false;

```

This seems like a bad idea especially if you have multiple content editors. This also creates a Drupal error message:

```
The form has become outdated. Copy any unsaved work in the form below and then reload this page.

```

ISSUE: I have an issue with field\_collections (embedded). I am unable to add/remove items.

This worked perfectly: https://drupal.stackexchange.com/a/56350/72908

Basically you just need to reset the $form\_state\['values'\] array in your #after\_build function.

```
    /**
     * Implements hook_form_alter().
     */
    function modulename_form_alter(&$form, &$form_state, $form_id) {
      if ($form['type']['#value'] == 'YOUR FORM TYPE') {
        $form['#after_build'][] = 'custom_function_after_build';
      }
    }

    function custom_function_after_build($form, &$form_state) {
      $form_state['values'] = array();
      return $form;
    }

```
> 1 votes

---
Tags: forms
---


# Question
Title: Create a view/list of pages made with Panels
I know how to view/list particular content types in a View:

I just need to add a "filter criteria" to the View that will display all node belonging to that type.

cool. but, I can't figure out how to view/list particular pages made with Panels.

Pages made with Panels are not selectable from the "filter criteria" box in the View.

# Answer
Try www.yoursite.com/admin/structure/pages

This lists all the system generated & custom panel pages that exist.
> 0 votes

---
Tags: views, panels
---


# Question
Title: Can I remove the "summary" from the "Text (formatted, long, with summary)" widget?
When creating a new content type, by default it has the **Body** field, which has a **Field type** of *Text (formatted, long, with summary)*. For this content type, I don't want authenticated users to see the summary.

What's the proper way to hide the "edit summary" part for non-admin users? Or, am I better off deleting the default **Body** field and creating a new custom field?

# Answer
Well, that was easy. On admin/structure/types/manage/page/fields/mycontenttype, you just have to uncheck the box for "Summary input."
> 3 votes

# Answer
## For those who may be looking for the D7 version of @Patrick Kenny 's answer:

```
https://{{mysite.foobar.com}}/admin/structure/types/manage/{{mycontenttype}}/fields/body

```
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How do I get an image path from field preprocess function
After 3 hours of searching the web for this I gave up...

I have added a "banner image" field to the basic page. I want to use the image as a background. I wanted to capture the image path in a preprocess\_field function but I tried every possible methods on the \Drupal\image\Plugin\Field\FieldType\ImageItem object and can't seem to find the way to get the path.

mytheme.theme:

```
function mytheme_preprocess_field(&$variables){
  if($variables['field_name'] == 'field_banner_image'){
    /** @var \Drupal\image\Plugin\Field\FieldType\ImageItem $field */
    $field = $variables['element']['#items'][0];
    $variables['banner_url'] = $field->getValue(); // not working, tried everything...
  }
}

```

Then in my field--field-banner-image.html.twig:

```
<div class="field--name-field-banner-image" style="background: transparent url({{ banner_url }})"></div>

```

# Answer
I found the answer. One thing weird is that you have to go to the parent entity and from this point go back to the field, only then you can get the url.

```
function mytheme_preprocess_field(&$variables){
  if($variables['field_name'] == 'field_banner_image'){
    /** @var \Drupal\image\Plugin\Field\FieldType\ImageItem $field */
    $field = $variables['element']['#items'][0];
    $field_image_url = get_image_uri($field->getEntity(), 'field_banner_image');
    $variables['banner_url'] = file_create_url($field_image_url);
  }
}

```

with

```
/**
 * Get the set or default image uri for a file image field (if either
 * exist).
 * @param $entity
 * @param $fieldName
 * @return null|string
 */
function get_image_uri($entity, $fieldName){
  $image_uri = NULL;
  if($entity->hasField($fieldName)){
    try{
      $field = $entity->{$fieldName}; // Try loading from field values first.
      if($field && $field->target_id){
        $file = \Drupal\file\Entity\File::load($field->target_id);
        if($file){
          $image_uri = $file->getFileUri();
        }
      }
    } catch(\Exception $e){
      \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
    }
    // If a set value above wasn't found, try the default image.
    if(is_null($image_uri)){
      try{
        $field = $entity->get($fieldName); // Loading from field definition
        if($field){
          // From the image module /core/modules/image/ImageFormatterBase.php
          // $default_image = $test->fieldDefinition->getFieldStorageDefinition()->getSetting('default_image');
          $default_image = $field->getSetting('default_image');
          if($default_image && $default_image['uuid']){
            // $defaultImageFile = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']));
            // See https://www.drupal.org/node/2549139  entityManager is deprecated.
            // Use entity.repository instead.
            $entityrepository = Drupal::service('entity.repository');
            $defaultImageFile = $entityrepository->loadEntityByUuid('file', $default_image['uuid']);
            if($defaultImageFile){
              $image_uri = $defaultImageFile->getFileUri();
            }
          }
        }
      } catch(\Exception $e){
        \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
      }
    }
  }
  return $image_uri;
}

```

Also another weird thing I noticed while trying stuff:

```
$field->entity

```

and

```
$field->getEntity()

```

does not give the same object
> 4 votes

# Answer
You can do this more simply

```
$uri = \Drupal\file\Entity\File::load($variables['items'][0]['content']['#item']->getValue()['target_id'])->getFileUri()

```

Or for a field with multiple items

```
foreach ($variables['items'] as $delta => $item) {
  $uri = \Drupal\file\Entity\File::load($variables['items'][$delta]['content']['#item']->getValue()['target_id'])->getFileUri()
}

```

And then apply an image style to get the url

```
$variables['banner_url'] = ImageStyle::load('image_style_name')->buildUrl($uri);

```
> 5 votes

---
Tags: 8, theming, media
---


# Question
Title: How to disable auto create customer profile after edit order?
When I edit order (at url admin/commerce/orders/1/edit) and save order, a new custom profile will be created. I don't want that. How can I disable that?

# Answer
> 0 votes
This is happening because the inline customer profile form has the country selected, which is all that's required for a field value to be present. I believe we should add a fix to Drupal Commerce core to prevent this, but I don't know off the top of my head if there's already an issue in the queue for it. Feel free to search at https://www.drupal.org/project/issues/commerce and file an issue if you don't see it already. Thanks!

---
Tags: 7, commerce
---


title: Render menu block in twig template

text:
# Question
Title: Render menu block in twig template
* In `page--front.html.twig` I load a nested twig file `{% include
"header.twig" {} %}`
* In `header.twig` I want to render my menu block

I tried the following but no result:

* In `my_theme.theme` I added:

```
function crm_theme_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('crmnavigation');
  $variables['block_output'] = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
}

```
* In `header.twig` I added `{{ my_navigation }}` but it doesn't show the menu block?

# Answer
> 4 votes
The easiest solution is to make use of twig tweaks module, Install twig tweak

```
drush -y en twig_tweak,
drush cr,

```

now you can place navigation anywhere. In your case inside header.twig file place

```
{{ drupal_block('crmnavigation') }}

```

You can also render entities, views and many other things. well explained here http://www.wdtutorials.com/drupal/theming/drupal-8-tutorial-43-twig-tweak-module-article-video#.WCPOxeErIyk

# Answer
> 1 votes
There is a module that lets you do this called Simplify Menu.

In your Twig template, you make the call for the menu you want to fetch, and then wrap it in markup like so:

```
// Get menu items
{% set items = simplify_menu('main_navigation') %}

// Iterate menu tree
<nav class="navigation__items">
  {% for menu_item in items.menu_tree %}
    <li class="navigation__item">
      <a href="{{ menu_item.url }}">{{ menu_item.text }}</a>
    </li>
  {% endfor %}
</nav>

```

Although, my question still remains..

> Why can't you just create a region to hold navigation, and place the block in there in the block layout?

---
Tags: theming, 8, blocks
---


# Question
Title: Using selected value of Entity Reference as filter for another Entity Reference
Going to try and put this as simple as i can.

Lets say i have 2 Entity Reference Fields A and B.

A) Gives a list of Countries.

B) What ever country was selected in A should only display list of available State/Province's to that country

Example: Lets say i have a content type of Countries where i can save the country name in the title, then i also have a content type of state/province's where the state/province name is saved in the title with entity reference field where a county can be selected for that State/Province.

Lastly i have a content type user information, where a user can enter his/her name in the title, a entity reference field country and another entity reference field state/province. When the user select, lets say, USA as a country in the first entity reference field, the second one should only display a list of sates available in the USA.

Can something like this be done where the option of one Entity Reference field can be used as a filter for another entity reference? and if so, how can something like this be achieved? any and all help is much appreciated.

# Answer
> 0 votes
Found a categorically stunning module that does precisely what i needed over here https://www.drupal.org/project/ddf

Its simple to use as well. Install the module, enable Dynamic dependent fields and DDF Entity Reference modules after that.

Once that is done, go to your content type that contains the two or more enetity reference fields, using the example above that would mean editing content type user information. Now, go to manage fields, select edit on the entity refence field you want to be filtered, going back to the example again that would mean the state/province entity reference field, scroll down to the field settings section and on target type select node, on mode select the option Views: Filtered by an entity reference view with dynamic arguments, on views used to select the entities option choose the view that you have created for that entity reference - make sure that entity reference view has a contextual filter in it.

When all that is done, the last option is view arguments field and just below that the DDF module will give you a list of option that can be used as arguments to be passed to the entity reference views contextual filter... select one of them, in the example again, it would be something like {field\_er\_countries}.

Remember to save all your hard work and you should be good to go...

---
Tags: 7, entities, views
---


# Question
Title: "Unable to send email" error shown to anonymous users in Workflow action
Using the Workflow module, I've got a content type that can be created by anonymous and authenticated users alike, then it goes into a review process. Upon creation, I want to email the user with a confirmation email. You may be asking, "do you want to email anonymous users too?", and that'd be a good question; the answer is "ideally, yes", but the important thing right now is authenticated users.

Ideally, we'd use the email field (field\_email) as an address, but when I try to use \[node:field\_email\] or \[node:field-email\] (the field itself is of type "Email", from the "email" module.), I get the error "Enter a valid email address, or use a token email address such as \[node:author:mail\]"

So, we decided to just use \[node:author:mail\], but, of course, anonymous users don't have an email and it follows that when they save the new node, they get the "Unable to send e-mail. Contact the site administrator if the site persists."

NOTE: This action is being created on the /admin/config/system/actions page, and added as a trigger; not on the "/admin/config/workflow/rules" page. For some reason, it seems like using the actual Rules module itself with workflow breaks; none of the rules we try to set up actually fire.

# Answer
> 0 votes
I'm assuming you're using a Rules Event "Before saving content (optionally limited to selected content types)", or some variation of a node related Rules Event.

Try to add a Rules Condition like "Entity has field" (related to that node:field-email field). After you do, that field will be available as a token you can use in any subsequent Rules Condition and/or Rules Action (where a field of that data type can be used). Your 2nd paragraph appears to me like a confirmation you don't have such Rules Condition yet (so Rules has no clue you're interested in using that eMail field).

With that, you should be able to just get it to work with the Rules module, due to which your "note" probably doesn't apply/matter anymore.

---
Tags: 7, rules, workflows, actions
---


# Question
Title: Why is the Commerce product's price hidden in my view for Anonymous User?
I have a very strange problem with the Views and Drupal Commerce. I would like a list of products and their prices, but in the view - and ONLY in the view, the price is hidden for anonymous users. I can see it when I am logged in, and if I go to the actual product page it is showing for all users, just not on the view! STRANGE! I've made sure that anonymous users can access the checkout, which they can.

I'm using

* Drupal 7.54
* Drupal Commerce 7x 1.13
* Views 7x 3.14

The view is pulling in the price through fields

* Content: Product
* formatter: Rendered Product
* View Mode: Content: Teaser (also tried Commerce Product: Content: Teaser)

If I add a relationship it looks fine when logged in but the whole view completely disappears when not logged in.

I've never run into this issue with views before and I've done quite a few e-commerce sites. I assume that this is a permission problem somewhere, but I can't seem to find it and I'm feeling completely stupid for not being able to trouble shoot this. Can anyone give me any hints?

# Answer
A first possible solution is to ***give the "View any product of any type" permissions to anonymous***. Here is a relevant screenprint about it:

Another solution is to ***disable SQL rewriting within the Advanced \> SQL Settings section of the view***. This can have security implications if your using contextual or exposed filters. So make sure that your filters or contextual filters (i.e. relationships) are properly limiting access.

For more info, refer to comment nr 5 or comment nr 6 of the issue about "Views results empty for unprivileged user when using Relationship: Content: Referenced Product"
> 3 votes

---
Tags: 7, views, commerce, users
---