# Question
Title: How to show a block only if a specific user is logged in?
I have a block which act as a menu. And the block is created dynamically like that:

```
$menu_block = array(
    'module' => 'menu',
    'delta' => 'clientmenu' . $account->uid, // the id of the block
    'theme' => 'MYTHEME', // the current theme
    'title' => '<none>', // dispaly no title
    'visibility' => 1, // it is displayed only on those pages listed in $block->pages.
    'region' => 'menu',
    'status' => 1,
    'pages' => $onlythispages, // display the menu only for this client
);

drupal_write_record('block', $menu_block);

```

And content of the variable `$onlythispages` is:

```
// page to display the menu
$onlythispages = 'client/' . $account->name . '
client/' . $account->name . '/*' . '
all-products
product/*';

```

I created one menu for each created user. Each user has personal (only he can access) pages like:

```
client/' . $account->name
client/' . $account->name . '/*'

```

And each user has some common pages which share with all users, pages like:

```
all-products
product/*

```

So the problem is that when I go to common pages I see all the "menu blocks" from all the users. So is there a way to show a block only if a specific user id, which actually is the currently logged in user?

I use `hook_node_access` to handle the access to a node but, how can I do it handle the access to block?

# Answer
If only a block needs to be shown for each user, then what I would do is to implement the block in a module that changes the content of the block basing on the currently logged-in user. The visibility settings are also used for blocks implemented by third-party modules.
> 1 votes

# Answer
Below is an answer to what I think this question is really about, i.e. "***So is there a way to show a block only if a specific user id, which actually is the currently logged in user?***".

# Part 1: Rules block visibility

You should be able to get this to work using the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the actual user who's using the site, i.e. if it is **YES** or **NO** (a boolean, right?) the user with a specific `uid`. What follows details the steps for a block to only be shown to the user with `uid = 1` (replace the `1` in it for any other value for `uid`).

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components. By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_block_visibility_show_block_for_user_1" : {
    "LABEL" : "Show block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user's uid is YES or NO equal to `1`.

With that, we're coming close to an actual answer to your question.

# Part 3:

Head over to the "Block" settings for the block you want to hide for the user with `uid = 1`. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

And guess what, in my case I just selected my Rules Component from Part 2

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.
> 0 votes

---
Tags: 7, users, blocks
---


# Question
Title: How to translate plural strings with Drush?
If we want to translate a plural string in Drupal we can use the `format_plural()` function.

If you are programming drush commands you can use the `dt()` function to translate strings, but if you want to translate plural strings in drush wich is the function to accomplish this?

# Answer
Between the Drush functions that process text, there isn't such a function, but you can implement one using the code from format\_plural(), replacing any call to `t()` with calls to `dt()`.

```
function drush_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
  $args['@count'] = $count;
  if ($count == 1) {
    return dt($singular, $args, $options);
  }

  // Get the plural index through the gettext formula.
  $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
  // If the index cannot be computed, use the plural as a fallback (which
  // allows for most flexiblity with the replaceable @count value).
  if ($index < 0) {
    return dt($plural, $args, $options);
  }
  else {
    switch ($index) {
      case "0":
        return dt($singular, $args, $options);
      case "1":
        return dt($plural, $args, $options);
      default:
        unset($args['@count']);
        $args['@count[' . $index . ']'] = $count;
        return dt(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
    }
  }
}

```
> 8 votes

---
Tags: i18n-l10n, drush
---


# Question
Title: Displaying content type as a field in a page
I am stuck with this architectural design for a client of mine. I am trying to create a testimonial block in 3 different pages, that client can pick any testimonial and I will create simple bootstrap carousel system for that.

So I created a custom content type name testimonial which has 3 fields, body, client name, and client title. This is the point I get stuck, I have no clue what would be the next? I tried to create that block via views slideshow but then client won't be to pick testimonials that they want, it will display all the testimonials.

I wonder if there is a way that I can add this content type as a field at that page? Or am I going to create a custom page(as a module) and create a custom field for this testimonial content type? If I have to do so, is there anyone who encountered this and completed something like this, can direct me to a sample of this?

# Answer
> 0 votes
Create a custom block type "Testimonial slideshow" or so (Accessible through local tasks on the block overview page), add a reference field and allow nodes of your given type. Set the cardinality to exactly 3.

Then you can create a block of that type and select 3 testimonials (with select or autocomplete, depending on what you configure on manage display).

That's it, now you just have to implement the necessary templates to show it as a slideshow.

---
Tags: entities, 8
---


title: Getting the name of a tag

text:
# Question
Title: Getting the name of a tag
I've noticed that in using the default Drupal 8 API to get a feed of articles (using the REST View) the Tags field is returned as the following:

```
"field_tags" : [{
  "target_id" : "1",
   "target_type" : "taxonomy_term",
   "target_uuid" : "4d2cac04-a0a6-4c0a-8c13-34ba44a474f0",
   "url" : "\/site\/taxonomy\/term\/1"
}]

```

This returns an entity reference, but you never get the actual name of the tag. In the above instance, the name of that tag is actually *Lorem*. I can't seem to find a way of adding a property into the `field_tags` object to include the actual name of the tag. Is there a way?

# Answer
> 1 votes
What @Clive said is the right answer as far as core goes. You have to make another request.

There are some contrib projects that provide more flexible interfaces. One of them is https://www.drupal.org/project/graphql, which allows you to execute a query and specify what data you want to have shown. I believe it's still fairly experimental though.

---
Tags: views, 8, nodes
---


# Question
Title: Which Drupal versions are affected by the vulnerabilities in advisory PSA-2016-001?
There is an PSA about the 2016-July-13 Security Advisory of several critical updates:

> View online: https://www.drupal.org/node/2764899
>
> * Advisory ID: DRUPAL-PSA-2016-001
> * Project: Drupal contributed modules
> * Version: 7.x
> * Date: 2016-July-12
> * Security risk: 22/25 ( Highly Critical)
> * AC:None/A:None/CI:All/II:All/E:Theoretical/TD:All
> * Vulnerability: Arbitrary PHP code execution
>
> **DESCRIPTION**
>
> There will be multiple releases of Drupal contributed modules on Wednesday July 13th 2016 16:00 UTC that will fix highly critical remote code execution vulnerabilities (risk scores up to 22/25 \[2\]). The Drupal Security Team urges you to reserve time for module updates at that time because exploits are expected to be developed within hours/days. Release announcements will appear at the standard announcement locations. \[3\]
>
> Drupal core is not affected. Not all sites will be affected. You should review the published advisories on July 13th 2016 to see if any modules you use are affected.

The advisory only mentions version 7.x as vulnerable, but I realized that I'm not entirely sure how I can interpret that. My interpretation is that Drupal 8.x should not be affected by these issues. But I'm really not sure about Drupal 6.x.

Drupal 6 is no longer supported. Does that mean that this kind of advisory won't even mention if it is still vulnerable? Or can I interpret this one as only version 7 is affected?

Which versions exactly are potentially affected by this advisory?

# Answer
The security team is intentionally a bit circumspect with these warnings. They either have to catch us all flat-footed or give potential attackers a heads up that something worth their time is coming. Currently they are siding with the latter method (and as much as I hated seeing that message today I agree with them).

For the most part it will not be clear until they release the news what modules will be covered. There is already speculation in some circles, but there isn't likely anything to be done before the announcement. Clearly from their announcement multiple modules are effected, and likely at least one is something very common.

Depending on the number of sites you support you should block off enough time to do updates for ***all*** of them.

These advisories will no longer cover Drupal 6. There is no formal way to know if Drupal 6 is effected (there will probably twitter comments, blog posts, etc about it after the release of the updates). If D6 is effected the only solution may be to take them offline.
> 2 votes

# Answer
That security advisory is about third-party modules made for Drupal 7. If also Drupal 8 were affected, then the advisory would report *Version: 7.x, 8.x*.
It doesn't report if Drupal 6 is affected, since that is a unsupported version, and the Drupal.org security team doesn't fix security issues on unsupported Drupal versions. Probably, once the involved third-party modules get a security release, it will be possible to see the change done in the code, and if the same security issue is present in the equivalent module for Drupal 6, but that will not be covered from any security advisory done from the security team.

Drupal 7 core is not involved, and I take the security team didn't want to reveal the third-party modules affected to avoid some hackers try to attach Drupal sites. When the security team gives those advisories, there is already a new version available that fixed the security issue; probably, since there are more modules involved, they could not be get a new version for all the modules.

Since the advisory doesn't say which modules are affected, it is not possible to say which version.

That advisory seems more a note to let users know new releases are expected in the next days, and avoid that is missed. They are not still giving a list of modules to update; note the following sentence:

> Release announcements will appear at the standard announcement locations.

The linked page is for releases containing security fixes, and the most recent one was made on July 6, 2016.
> 0 votes

---
Tags: security
---


# Question
Title: What is the template suggestion for node 'teaser' view mode?
**node--\[type|nodeid\].tpl.php** targets to node's default view mode. However I want to override the template for teaser view mode.

What is the template suggestion (.tpl.php file) for 'teaser' view mode?

# Answer
> 59 votes
I don't think there is one by default but you can easily add one in your template.php file:

```
function MYTHEME_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__teaser';
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->nid . '__teaser';
  }
}

```

That will let you use a template file like: `node--[type|nodeid]--teaser.tpl.php`

# Answer
> 1 votes
Clive's solution is correct. But if you want the new suggestions are evalueated after default suggestions, you must add them in the last positions of the array:

```
function MYTHEME_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'teaser') {
    array_unshift($vars['theme_hook_suggestions'], 'node__' . $vars['node']->type . '__teaser');
    array_unshift($vars['theme_hook_suggestions'], 'node__' . $vars['node']->nid . '__teaser');
  }
}

```

In this way you avoid that your teaser node matches (and uses, if it exists) node--\[type\].tpl.php before node--\[type\]--teaser.tpl.php

# Answer
> 1 votes
There is a easier way to to this, through the Entity view modes module.

https://www.drupal.org/project/entity\_view\_mode

```
The Drupal 7 successor to Build modes which will allow administrators to
define custom view modes for entities. Custom entities are added to the
entity registry via hook_entity_info_alter() so they are available to any code
that uses entity_get_info() to provide a list of view modes for an entity.
This includes node and user reference fields, Views, etc.

It also ensures consistency for template suggestions for all entity types,
so that you can use any of the template patterns, in order of most specific
to least specific:

entity-type__id__view-mode
entity-type__id
entity-type__bundle__view-mode
entity-type__bundle
entity-type

```

# Answer
> 1 votes
The template suggestion for a "teaser" view mode is:

```
node--[type]--teaser.tpl.php

```

By default the "teaser" view mode uses the regular `node.tpl.php` template, so you can copy that file to get started.

You can see all template suggestions by turning on `theme_debug` mode, https://www.drupal.org/node/223440#theme-debug

When you *view-source:* on the page you should see HTML comments that shows the entire list of template suggestions Drupal considered.

---
Tags: 7, theming
---


# Question
Title: Understanding $variables preprocess_views_view_field()
According to this description of `hook_preprocess_views_view_field()`, `$variables` contains, among other things, `$variables['field']`.

However, if I do `print_r($variables['field'])` just to inspect the object it prints the entire object (to include my username and password!) and even causes the browser to crash.

I am trying to figure out how to check the field name but it is proving to be strangely non-straightforward.

How can I properly index `$variables`?

# Answer
> 3 votes
The browser is likely crashing because most of the views objects have circular references in them, and the output can be huge.

`$variables['field']` is the field handler object for the field being rendered. I am 97% sure these are all derived from `\Drupal\views\Plugin\views\field\FieldPluginBase()` (3% uncertainty because it is the end of the day and I am really tired).

You best bet is to do a `debug(get_class($variables['field']))` to get the fully qualified class name, and then typehint in your preprocess, eg:

```
function MYMODULE_preprocess_views_view_field(&$variables) {
  /** @var \Drupal\views\Plugin\views\field\Boolean $field */
  $field = $variables['field'];
}

```

and then use your IDE to navigate through what you need to do.

To see what is in `$variables`, just do a

```
debug(array_keys($variables));

```

and go through a similar exercise to get the types; it's just a boring associative array where the keys are all strings.

# Answer
> 1 votes
With this code you will get the field name:

```
$variables['field']->field

```

or you could also want

```
$variables['field']->realField

```

---
Tags: views, entities, 8
---


# Question
Title: How to change value a field of preproces
I am new to PHP and Drupal. I have content type with a type list text field "Infraestructura". The values and labels are these:

* agua | Agua de pozo
* incendios | sistema contra incendios
* electricidad |Electricidad

The quantity options is unlimited, is to say, the user can select unlimited options (Checkbox)

How I do to change the output for this field as image?

I need that output for this field show an image , example:

* for: agua | agua =\> `<img src ="images/agua.jpg">`
* for: incendios | sistema contra incendios =\> `<img src ="images/incendios.jpg">`
* for: electricidad |Electricidad =\> `<img src ="images/electricidad.jpg">`

I'm thinking to do this using preprocess, but I not have idea. Could anyone help me please?

Here is another way to explain what I want to do:

# Answer
I found the solution, adding html in the same key / value field.

Regards!
> 0 votes

# Answer
You should preprocess the field output and add a class based on the value. Then to theme in css. It's a good idea to keep the images separate and business logic separate.

```
<?php

/**
 * Implements template_preprocess_field().
 */
function acTheme_preprocess_field(&$vars) {
  $element = &$vars['element'];
  if ($element['#field_infraestructura'] == 'field_infraestructura') {
    $value = $vars['element']['#items'][0]['value'];
    $vars['classes_array'][] = 'type-' . drupal_clean_css_identifier($value);
  }
}

?>

```

Take this qwith a grain of salt - I don't see the actual code and values in my debugger, but if you replace `myfield_name` with the name of the field, and `mytheme` with the theme name (all these machine names), then it should assign the classes based on the values.

Sadly, there may be some need of tweaking this code if some mapping does not fit - so, I hope you know at least some PHP to do that.

The output classes should be somehting like `class="type-agua"`, and then you can theme it. You need to know css, of course - there are samples in the comments under your question.
> 0 votes

---
Tags: views, entities, theming
---


# Question
Title: "Term reference" for two language versions
I'm currently working on a Drupal's website for my client. We have a small issue related to new fields in "content types".

I've created a new field with field type "Term reference". We're using terms for isotpe grid, and it should work in both language versions - NL and EN.

That field only displays a single language version (default one), even when we change thhe language.

Here is an example - "field\_thema\[nl\]\[8\]", it supposed to be:

```
"field_thema[nl][8]"

```

and

```
"field_thema[en][8]"

```

Is there any way we could fix this?

# Answer
> 0 votes
is this a Drupal 7 or Drupal 8 question ?

in Drupal 7 you can use i18n\_taxonomy submodule of i18n module.

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


title: Twig template for search results page

text:
# Question
Title: Twig template for search results page
I'm attempting to create a custom template for the search page located at

```
127.0.0.1/search/node

```

I've created a template called search-result.html.twig in my theme/templates folder which allows me to modify each search result but I'd like to actually modify the buttons and text fields at the top of the search page.

Is there a specific template that affects the search button and fields?

# Answer
> 2 votes
> but I'd like to actually modify the buttons and text fields at the top of the search page.

They do not have templates by default, because they are forms. You could create a twig template for the search form by follow this tutorial: How to manipulate forms in Drupal 8

But in my opinion, it is easier to use hook\_form\_alter on your **.theme** file and add the classes here.

This is how, the drupal default theme, Bartik changes the search button to a magnifying glass icon by adding a custom class to the submit button in **bartik.theme**

```
/**
 * Implements hook_form_alter() to add classes to the search form.
 */
function bartik_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, ['search_block_form', 'search_form'])) {
    $key = ($form_id == 'search_block_form') ? 'actions' : 'basic';
    if (!isset($form[$key]['submit']['#attributes'])) {
      $form[$key]['submit']['#attributes'] = new Attribute();
    }
    $form[$key]['submit']['#attributes']->addClass('search-form__submit');
  }
}

```

You can use Devel and use `dpm($form)` to see what's inside the $form array.

Example:

```
/**
 * Implements hook_form_alter() to add classes to the search form.
 */
function bartik_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, ['search_block_form', 'search_form'])) {
    $key = ($form_id == 'search_block_form') ? 'actions' : 'basic';
        drupal_set_message(dpm($form));
  }
}

```

Make sure you don't have the search block on the search page, other wise it will print the array for both forms and might confuse you which one is which.

---
Tags: theming, 8, search
---


# Question
Title: Give permission to manage users but not permissions
We have setup a site in Drupal 7 on which we would like certain users to have access to the user management page, and be able to create new users, assign roles, etc., but we don't want to give them access to the Roles and Permission pages.

Currently Drupal only has 2 permissions `Administer Permissions` and `Administer users`.

With the `Administer users` permission, the user has access to the User Management page, and can create new users but cannot assign roles to users.

If the user has the `Administer permissions` permission, he can assign roles to users and also access to the permission and role management pages.

How would you grant a user the right to assign roles to users, but prevent him from accessing the permission page?

# Answer
> 16 votes
I had the exact same requirement, and I was able to use the Roles Delegation module to build it to perfection :-)

Here is my scenario to give you more context -

1. I had a drupal site with roles - A, B, C, Admin, Maint
2. I wanted users with role Maint to be able to create new users and also assign them roles while doing so
3. I also wanted to limit Maint users to be able to assign only roles A, B, C to the new users and not the role Admin
4. All of it was just a few clicks with the Roles Delegation module

Hope this helps.

# Answer
> 2 votes
Hmmm... Interesting that there does not seem to be a clear cut way to do this. This seems like it could be a common feature for people. I found a couple solutions:

http://drupal.org/project/protect\_permissions \- However, this is not yet ready for production use.

However, I think you can accomplish what you want with: http://drupal.org/project/permissions\_lock

You will also need: http://drupal.org/project/user\_permissions

The later seems to do the opposite of what you want but the former seems to do exactly what you want. I have not tested either of these on my dev site to ensure 100% this is what will work for you. If I come across anything else I will update this answer.

# Answer
> 2 votes
Roles delegation leaves a security hole. You need to assign people the **administer users** for them to be able to use the administration page and the tools it has.

But if you do so, then that role will be able to edit even superadmin. Check Beware of Drupal's Administer users permission for a full description.

My solution is roles delegation + this hook

```

function hook_user_presave(&$edit, $account, $category) {
    if( $account->uid == 1 || in_array('adminrole',$account->roles)){ //trying to edit an admin
        global $user;
        if($user->uid != 1){//only super admin can do that
            drupal_set_message( "You attempted to edit an admin or dev user name and you are not allowed, this attempt was logged." ,'error');
            watchdog('permissions_extra','Logged in user %user tried to edit account %account', array('%user' => $user->uid, '%account' => $account->uid), WATCHDOG_ERROR);
            drupal_goto('/admin/people');
        }
    }
}

```

# Answer
> 0 votes
Lately we've been using the roleassign module, which does exactly what you're asking. It's fundamentally identical to the role\_delegation module, but could be an alternative if you needed something slightly different.

One key difference is how you decide which roles are available to be assigned. With roleassign, you just select which ones you want to make available, and it only adds a single new permission to assign those roles:

The role\_delegation module appears to give a new permission for each role that exists on the site:

The role\_delegation module also seems to have nearly triple the number of installs, and a "recommended" Drupal 8 release. The issue queue also seems to be in better shape, so it's *probably* the better option?

---
Tags: 7, users
---


# Question
Title: Adding functionality to a form button that would load user details / corresponding field data for "autofill"
I have a form that has a address field holding inputs for: name address phone etc.

I've added a button on this form/field: `Load my data` which I would like to load user details/data. On click it should load a corresponding address field from user's profile by ajax and use it to fill in form fields.

Form can have multiple address fields so it should know which address field needs to filled with user data.

Button isn't shown to anonymous users of course.

# Answer
Take a look at how Commerce Addressbook solves these same requirements: https://www.drupal.org/project/commerce\_addressbook.

There is a demo video on the project page: https://commerceguys.com/blog/commerce-module-tuesday-commerce-addressbook.

I think if you dig through the module code of that module, you'll find all the logic and code examples you'll need to pull off a similar solution on your custom form.

If you want to see this in action on a local setup, I recommend installing commerce kickstart with commerce addressbook to see how the addresses are organized.

Good luck, Jason
> 1 votes

---
Tags: forms, users, ajax
---


# Question
Title: Getting user photo url and profile url using views_json
I'm using the views\_json module in Views Datasource to send some information in JSON format to a related website. I've got a bunch of content views built, but now I'm trying to build staff pages. I've got most of it working fine, but when I try to add the user picture I end up with an empty field, When trying to find a url for the user's profile page (using User: Link), I got the text "view", leading me to believe that when drupal tries to output the content as a link, views\_json returns the link text. I just want the url in plaintext, I don't need the html for a link. How can I get the user picture, and the absolute url to the user profile in views\_json?

Image fields for my node views work just fine, I get field\_image.src and field\_image.alt elements in the JSON that is returned, with the Use picture I get a blank field or a series of `\n`´s

# Answer
**UPDATE**: There was a follow up comment on the drupal.org thread where someone suggested using Views User Picture URL. Since the solution below already works for me I haven't tried it, but this solution seems easier and reasonable. **/UPDATE**

@no-sssweat provided a superb answer, but it turned out that my problem was the result of a bug in views\_datasource in that thread, @tyler-frankenstein provides a really useful solution. Based on that I was able to get both the url path and profile link issues resolved:

```
/**
 * Implements hook_preprocess_views_views_json_style_simple().
 * solution for user pictures not showing up properly in views_json
 * via https://www.drupal.org/node/2396813#comment-10461959
 */
function MY_MODULE_preprocess_views_views_json_style_simple(&$vars) {
    $views_to_process = array(
        'user_view' => array(
            'uid_column_name' => 'uid',
            'picture_column_name' => 'picture',
            'image_style' => 'medium',
            'url_column_name' => 'url',
        ),
        'my_other_user_view' => array(
            'uid_column_name' => 'uid',
            'picture_column_name' => 'picture',
            'image_style' => 'medium',
            'url_column_name' => 'url',
        )
    );
    if (!in_array($vars['view']->name, array_keys($views_to_process))) { return; }
    $uids = array();
    $uid_column_name = $views_to_process[$vars['view']->name]['uid_column_name'];
    $picture_column_name = $views_to_process[$vars['view']->name]['picture_column_name'];
    $image_style = $views_to_process[$vars['view']->name]['image_style'];
    $url_column_name = $views_to_process[$vars['view']->name]['url_column_name'];
    foreach ($vars['rows'] as $i => $row) {
        $uid = $row[$uid_column_name];
        $uids[] = $uid;
    }
    $users = user_load_multiple($uids);
    foreach ($vars['rows'] as $i => $row) {
        $uid = $row[$uid_column_name];
        $vars['rows'][$i][$url_column_name] = url(drupal_get_path_alias('user/' . $uid), array('absolute' => TRUE));
        if (!$users[$uid]->picture) { continue; }
        $vars['rows'][$i][$picture_column_name] = array(
            'src' => image_style_url($image_style, $users[$uid]->picture->uri)
        );
    }
}

```

replacing `user_view` and `my_other_user_view` with the names of views this needs to work on and putting the label names in the `uid_column_name`, `picture_column_name` and `url_column_name` as well as filling in the value for the image style you've chosen for your picture field will result in your picture and url fields being filled with data like so:

```
"url" : "http://link.to.the/users/profile",
"photo" : {
  "src" : "http://link.to.the/users/profile/picture/with/styles/applied/properly.jpg?itok=ipLMAws_"
},

```
> 1 votes

# Answer
To get the user pic url, you can do it using Image URL Formatter. Once enabled, when you click on the user picture field, you will now see a formatter option, select image url.

For the user, assuming this is a user view, in FIELDS add the **User: Uid** as a field and checkmark ☑ exclude from display.

Now, add **Global: Custom text** as a field. In the text box, put `http://ultrabob.com/user/[uid]`

I got `[uid]` from replacement patterns. Side note, in order for fields to appear as a replacement pattern, they must be above the current field.

Else, if you're using pathauto so the user pages are /user/\[username\] then add the **User: Name** field instead and use the `[name]` token.

Now, if your view is a content view, ex: shows articles, then you will need to add a relationship of node author first, once you do that, the user fields will become available to be added as a field.

---

> OK, that issue got me sorted with the pictures, I'm now working on the solution for profile page link. Can you think of a good way to get the domain part of the url (http://ultrabob.com/) in your example dynamically in views from the site configuration. I would like this to continue to work without modification as it is deployed across test servers and onto production

You can using php. Ex: `<?php echo $_SERVER['HTTP_HOST']; ?>`

Either you could enable the Views PHP module, but remember to turn it off on production, or use a template file.

views-view-field--\[view-name\]--views-data-export--\[field-name\].tpl.php

```
<?php

$fields["field_name"]->content = 'http://' . $_SERVER['HTTP_HOST'] . '/user/' . $fields["field_name"]->content;

echo $fields["field_name"]->content;

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: Can't update hook_theme after clearing the cache
I have a hook\_theme instance in my template.php which outputs various components in my theme. I want to add an extra argument to one of the templates but no matter what I do it doesn't update. I have cleared the cache (using drush and not), removed the theme array, cleared cache and added back in. I have even truncated all the cache tables - but somehow it's still picking up the old function. Is there something stupid I have missed?

**template.php**

```
function MYTHEME_theme() {
  return array(

    'featured_blocks' => array(
      'arguments' => array(
        'blocks' => NULL,
        'image_format' => 'test!',
      ),
      'template' => 'featured-blocks',
      'path' => drupal_get_path('theme', 'MYTHEME') . '/templates/other'
    ),

  );
}

```

**featured-blocks.tpl.php**

```
<?php

printr($blocks); // blocks are all here
print $image_format; // this is undefined!!!

```

**Calling the hook theme**

```
<?php print theme('featured_blocks', array(
            'blocks' => $wrap->field_my_blocks,
            'image_format' => 'this is a test'
          )) ?>

```

# Answer
> 0 votes
After doing a bit more reading I restarted my MAMP server and switched themes, then back again. I'm not sure which did it but it's working now...

---
Tags: 7, hooks
---


# Question
Title: how to correctly chain multiple files in '$settings['container_yamls'][]'?
In the settings.php file, I have the following line, to use a local service.yml.

```
$settings['container_yamls'][] = __DIR__ . '/services.yml';

```

I need to install the Redis module, which instructs to put the following line in the settings.php file.

```
$settings['container_yamls'][] = 'modules/redis/example.services.yml';

```

I'm not sure how the settings array works. I think that just adding that statement will overwrite the existing one.

I want to add the array item as suggested in the documentation for that module.

Should I use these lines?

```
$settings['container_yamls'][] = __DIR__ . '/services.yml';
$settings['container_yamls'][] = 'modules/redis/example.services.yml';

```

Or should I use these lines?

```
$settings['container_yamls'] = array(
  __DIR__ . '/services.yml',
  'modules/redis/example.services.yml',
);

```

# Answer
> 2 votes
The settings.php file already contains the following line.

```
$settings['container_yamls'][] = __DIR__ . '/services.yml';

```

It is much easier to add the following one at the bottom of the settings.php file.

```
$settings['container_yamls'][] = 'modules/redis/example.services.yml';

```

Since it is added on the bottom of the file, it is easier to find and remove it, in the case you decide not to use that module anymore. In this case, you just remove a single line, and Drupal doesn't use that module's services anymore.

Also, if you install another module that requires to add a similar line, you just need to add a `$settings['container_yamls'][]` which can be easily removed without touching the other lines.

Those are the only considerations I could make about which code snippet I would use. Otherwise, for PHP 5.5 (and Drupal), the following code snippets are perfectly equivalent.

```
$settings['container_yamls'][] = __DIR__ . '/services.yml';
$settings['container_yamls'][] = 'modules/redis/example.services.yml';

```

```
$settings['container_yamls'] = array(
  __DIR__ . '/services.yml',
  'modules/redis/example.services.yml',
);

```

```
$settings['container_yamls'] = [
  __DIR__ . '/services.yml',
  'modules/redis/example.services.yml',
];

```

# Answer
> 0 votes
The correct method is:

```
$settings['container_yamls'][] = __DIR__ . '/services.yml';
$settings['container_yamls'][] = 'modules/redis/example.services.yml';

```

---
Tags: installation, configuration
---


# Question
Title: Config Entity list_builder controller path throws Route Does Not Exist error
I have created a custom config entity, which declares a list\_builder controller to return a list of the created entities. Before creating a config entity, it renders as expected. Once I create a config entity via its add form, which redirects back to the list\_builder controller, the error is thrown. The config entity is saved, but the redirect fails.

Here's the redirect in the config entity form class's ::save() method.

```
$form_state->setRedirect('my_module.entity.list');

```

Also, navigating directly to the list\_builder controller path throws the same error.

> Symfony\Component\Routing\Exception\RouteNotFoundException: Route "entity.config\_entity\_id.edit\_form" does not exist. in Drupal\Core\Routing\RouteProvider-\>getRouteByName() (line 187 of /home/vagrant/docroot/core/lib/Drupal/Core/Routing/RouteProvider.php)

I have no idea where the route entity.config\_entity\_id.edit\_form is coming from. How to resolve the thrown error?

# Answer
You have somewhere in your code the wrong route.

Probably your route in \*.routing.yml is:

```
entity.my_new_entity.edit_form

```

But now you are redirecting to

```
entity.config_entity_id.edit_form

```

where there is still the placeholder from some example code.
> 1 votes

---
Tags: 8, entities, routes
---


# Question
Title: How to allow each company section to manage their own content on the Intranet?
I have a simple problem of permissions. I work in a company which is divided into different sections. I have to make a Drupal intranet for them.

Each section must be able to manage their own content on the Intranet. The contents of the intranet are always the same, ie the same "content type" with the same "fields". It is necessary that a section could only edit the contents within its section. Thus, "computer" could only create / edit / delete content of "computer". The section of "press" could only create / edit / delete content of "press". All sections can view all content.

I tried different modules. "Field permissions", which lets you field level permissions, is interesting but does not help in this case. "Content Access" allows me to level management content type, but I can do what necesito.Con "Taxanomy Access Control" can define visibility rules, editing and deletion according to the presence or absence of one or more terms a taxonomy. It could be interesting, was not that "computer" should not be able to create content "press", for example.

You could create a content type for each section equal, and each give the required roles. The problem is that they are over 15 and does not seem the most optimal way to do this, because if I have to add a field so I have to do in the 15 (DRY).

I sense that Drupal has a more efficient way of doing this, but as I am new to this CMS I can not find it.

# Answer
The thing you are looking for is Organic groups. It does exactly what you need. Further more you may be interested in some solutions already made on drupal. Like Open Atrium or Drupal Commons

Hope it helps.
> 1 votes

# Answer
The Group module allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For this specific question, you'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

For more details about the various types of roles used by the Group module, refer to my answer to "What are the various roles supported by the Group module?".

# Resources
> 1 votes

---
Tags: 7, users
---


# Question
Title: Print Media CKeditor images correctly custom code
How can I show an image that I uploaded with de CKeditor Media browser on my page? Now I use this code:

```
    case 'black_box_with_image':
        $black_box_with_image_image = '';
        if (!empty($content['settings']['black_box_with_image_image'])) {
            $fid = $content['settings']['black_box_with_image_image'];
            $file = file_load($fid);
            if ($file) {
                $image = array(
                    'path' => $file->uri
                );
                $black_box_with_image_image = theme('image', $image);
            }
        }

        $black_box_with_image_title = !empty($content['settings']['black_box_with_image_title']) ? $content['settings']['black_box_with_image_title'] : '';
        $black_box_with_image_link_name = !empty($content['settings']['black_box_with_image_link_name']) ? $content['settings']['black_box_with_image_link_name'] : '';
        $black_box_with_image_link = !empty($content['settings']['black_box_with_image_link']) ? $content['settings']['black_box_with_image_link'] : '';
        $black_box_with_image_description = isset($content['settings']['black_box_with_image_description']['value']) ? $content['settings']['black_box_with_image_description']['value'] : '';

        $black_box_with_image = '
            <div class="black_box_with_image col-md-12">
                <div class="pull-left col-md-7">
                    <h2 class="titel">' . $black_box_with_image_title . '</h2>
                    <p class="beschrijving">' . $black_box_with_image_description . '</p>
                    <a href="' . $black_box_with_image_link . '">' . $black_box_with_image_link_name . '</a>
                </div>
                <div class="pull-right col-md-5">
                    ' . $black_box_with_image_image . '
                </div>
            </div>
        ';

        $content['content'] = $black_box_with_image;
    break;

```

The variable `$black_box_with_image_description` is the field with the CKeditor Media browser image.

Now it shows like this:

> \[\[{"fid":"8","view\_mode":"default","fields":{"format":"default","field\_file\_image\_alt\_text\[und\]\[0\]\[value\]":"field\_file\_image\_title\_text\[und\]\[0\]\[value\]":"","field\_folder\[und\]":"6"},"type":"media","attributes":{"height":"480","width":"388","style":"width: 150px; height: 186px;","class":"media-element file-default"}}\]\]

In the editor, the image is displayed, but when I save the node it shows the plain HTML.

> Convert Media tags to markup

I checked the covert media tags to markup in the format section. When I use a default CCK field the images shows correctly, but not with my custom code..

# Answer
Problem solved.

```
$black_box_with_image_description = isset($content['settings']['black_box_with_image_description']['value']) ? $content['settings']['black_box_with_image_description']['value'] : '';
if (isset($content['settings']['black_box_with_image_description']['format'])) {
    $black_box_with_image_description = check_markup($black_box_with_image_description, $content['settings']['black_box_with_image_description']['format']);
}

```
> 0 votes

---
Tags: media
---


# Question
Title: Custom pseudo field not rendered when no other field has content
**Usecase:** I want to have a title field in view mode administration to be able to place it between some other fields. This field has different content depending on node type, view mode and some other fields which is handled by a custom function.

**Solution so far:**

```
 /**
 * Implements hook_entity_extra_field_info().
 */
function mymodule_entity_extra_field_info() {
  $extra = array();

  foreach (NodeType::loadMultiple() as $bundle) {
    $extra['node'][$bundle->Id()]['display']['mymdoule_title'] = array(
      'label' => t('Extra title'),
      'description' => t('Display the title of the node e.g. in teaser'),
      'weight' => 100,
      'visible' => TRUE,
    );
  }

  return $extra;
}

```

And then

```
/**
 * Implements hook_ENTITY_TYPE_view for nodes
 *
 *  - render our pseudo fields
 */
function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  // if our pseudo field is used we use our costum class to build the render array
  if ($display->getComponent('mymodule_title')) {
    $nodeCustomisation = new NodeCustomisation($entity);
    $nodeCustomisation->titleExtraField($build, $view_mode);
  }
}

```

It is working as I can see my pseudo field when I go to the view mode administration page of any content type. I can place the field somewhere and it is rendered.

**Problem:** As soon as the pseudo field is the only field with content when viewing a node in this view mode nothing is rendered but the node wrapping `<article>`-tag from node.html.twig. The array `{{ content }}` in this twig template is empty although the pseudo field should have content for sure - when I add a node field to the view mode which has content I see my pseudo field again.

# Answer
So I found my fault - when you describe a field the render array needs to have an array of field items. So the $build-array needs to look like this:

```
$build['igb_title'][] = array(
      '#type' => 'html_tag',
      '#tag' => 'h2,
      '#value' => $entity->label()
    );

```

In `field_group_remove_empty_display_groups` it is checked if a field as at least one item:

```
$has_items = isset($element[$name][0]);

```

If `$has_items` is false the field group is emptied if there is no other field with a value. I think I might need to go deeper into this render array thing...

Best, Tobias
> 1 votes

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


# Question
Title: Images are refering wrong path on node import
i import a node in my site using paste code method. after imported some images are refering wrong path ("https://www.example.com/sites/default/files/styles/large/public/test.png?itok=a2KPyReV"). but the image is inside of the below path ("https://www.example.com/sites/default/files/test.png")

# Answer
The wrong path belongs to an image derived from image cache. It's the default "large" image style defined in admin/config/media/image-styles. You can try to rebuild the image cache, but success depends a bit on your "paste code method" which i'm unfamiliar with...
> 1 votes

---
Tags: importing-exporting, nodes
---


# Question
Title: How to use traditional (national/native) dates and calendars?
How can use non-Gregorian dates and calendars?

I adjust Drupal setting to my native language (fa) and native location (Asia/Theran) but month name and number of years also in Gregorian yet (however there are translated to my native language-persian).

I already use `format_date()` or `date()` in theme files, but this function is not locale-aware, which means that it always outputs English language data, such as day and month names and ordinal number suffixes.

I want to show the month names in the native language (e.g. Chinese, Islamic, Hebrew, Farsi/Persian) and use the national calendar (e.g. Irani, Shamsi, Jalali).

I want to understand is there any module or hardcoding solution in Drupal to show dates and calendars in other non-Gregorian calendars.

Any suggestions?

# Answer
> 8 votes
I'm hoping that someone else can Optimize this solution and make it better.
I'm ready to receive Any suggestion or criticism or any Other solution for this Challenge.

## Features:

* Does not requires any hacking or patching core /frontend solution ,display when dates are rendered
* Does not change any date in database
* Compatible and tested with PHP versions 5.3 and hereinafter
* Supports Iranian/Persian/Shamsi/Jalali , Arabic/Hijri/Islamic, Thai, Hebrew... Calendar systems
* Better Performance becuse Doesn't outbreak the drupal core

## **Method 1, Using "IntelDateFormatter" Class:**

First of all you must be sure that version of your php that installed is Newer than 5.3 and **'IntlDateFormatter'** Extension was exist.
For use Traditional(National/Native) Date/Calender in **Drupal 8** in nodes and Posted Comments with use of IntlDateFormatter class, add below codes to "THEME\_NAME.theme":

For Nodes:

```
function THEME_NAME_preprocess_node(&$variables) {
    $locale = "fa_IR@calendar=persian";
    $dateType = IntlDateFormatter::NONE;//type of date formatting.
    $timeType = IntlDateFormatter::NONE;//if time format setting to none, will give you date itself
    $timezone = 'Asia/Tehran';
    $calendar = IntlDateFormatter::TRADITIONAL;//Non-Gregorian Calendar
    $pattern = 'y/M/d';

    $fmt = new IntlDateFormatter($locale, $dateType, $timeType, $timezone, $calendar, $pattern);
    $date = $variables['node']->getCreatedTime();
    $variables['date'] = $fmt->format($date);
}

```

For Comments:

```
function THEME_NAME_preprocess_comment(&$variables) {
    $fmt = new IntlDateFormatter(
    "fa_IR@calendar=persian",
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    'Asia/Tehran',
    IntlDateFormatter::TRADITIONAL,
    'y/M/d'
    );

    // Getting the node creation time stamp from the comment object.
    $date = $variables['comment']->getCreatedTime();
    $variables['created'] = $fmt->format($date);
}

```

Information about "IntlDateFormatter" Parameters:
**locale:**
Locale to use when formatting or parsing or NULL to use the value specified in the ini setting, Link:http://www.w3.org/International/articles/language-tags

**datetype:**
Date type to use (NONE, FULL, LONG, MEDIUM, SHORT). This is one of the IntlDateFormatter constants.

**timetype:**
Time type to use (NONE, FULL, LONG, MEDIUM, SHORT). This is one of the IntlDateFormatter constants.

**timezone:**
Time zone ID, default is system default,
Link:http://www.php.net/manual/en/timezones.php.

**calendar:**
Calendar to use for formatting or parsing; default is Gregorian. This is one of the IntlDateFormatter calendar constants.
The calendars ICU allows you to play with include:

* Japanese (@calendar=japanese)
* Buddhist (@calendar=buddhist)
* Chinese (@calendar=chinese)
* Persian (@calendar=persian)
* Indian (@calendar=indian)
* Islamic (@calendar=islamic)
* Hebrew (@calendar=hebrew)
* Coptic (@calendar=coptic)
* Ethiopic (@calendar=ethiopic)

Link:http://userguide.icu-project.org/datetime/calendar

**pattern:**
Optional pattern to use when formatting or parsing. Possible patterns are documented at: http://userguide.icu-project.org/formatparse/datetime

---

## **METHOD 2,Using External Functions (like "jdf" for persian language):**

First download this function form: http://jdf.scr.ir/download/
and then put downloaded file to your theme folder and add this code to above of "Theme\_Name.theme"

```
include ('jdf.php');

```

and then add below code to appropriate place:

```
function Theme_Name_preprocess_node(&$variables) {
   $date = $variables['node']->getCreatedTime();
   $variables['date'] = jdate("l j F Y", strtotime($date));
}

```

I'm hoping that someone else can build on this and make it better.

# Answer
> 2 votes
Taarikh module will help you use the Islamic calendar as a field formatter and widget for display with the ability to translate month names, I used it and works very well, it's the best for Islamic calendar.

You could patch the module to add support for other calendars "i could help"

# Answer
> 1 votes
You can use this Modules:

## **Calendar Systems**

**Module page:** Calendar Systems
**Support:** Iranian (jalali) , Arabic/Islamic/Hijri , Thai and Gregorian (Using PHP's built-in)
**Version:** Drupal 7
**BY:** Sina Salek
**Description:**

> Advances Drupal's already awesome localization support one more big step ahead by Adding support for different calendar systems like Iranian , Jalali , Hijir , Thai , Hebrew etc. This support is currently limited to display and data entry for date fields and the back-end date is always Gregorian (Timestamp).

---

## **Datex**

**Module page:** Datex
**Support:** only Iranian (Hijri Shamsi/ jalali)
**Version:** Drupal 7
**By:** Drupalion
**Description:**

> Datex and related module will help to create a better multilingual website for languages needing a Jalali (Or in near feature of datex, any) calendar instead of default Gregorian calendar.

---

## **Hijri**

**Module page:** Hijri
**Support:** Only Hijri Date (Islamic, Hijri Ghamari)
**Version:** Drupal 7, Drupal 8 (Development releases)
**By:** Abdullah Bamelhes
**Description:**

> This is a smart module that basically extends Drupal's display date to provide Hijri Date integration with Drupal core date field and with other Drupal contributions.
>
> This module is integrated very well with Views module

---

## Taarikh

**Module page:**Taarikh
**Support:** Only Hijri Date (Islamic, Hijri Ghamari)
**Version:** Drupal 7, Drupal 8 (Development releases)
**By:** Husain Inad
**Description:**

> Taarikh is a field formatter and widget module to display and input hijri dates using the fields defined by the date module. The formatter can work with all the fields defined by the date module, i.e., Date, Date (ISO format) and Date (Unix timestamp). The widget, however, does not work with Date (Unix timestamp).

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


# Question
Title: Ajax form submit - how to recognize if form contains errors in ajax callback?
I have a simple form with ajax submit:

```
function activit_registration_form($form, $state) {

  $form["ajax-start"] = array("#markup" => "<div id='registration-form-ajax'>");

  // ... some form elements are here

  $form["submit"] = array(
      "#type" => "submit",
      "#value" => t("Odoslať"),
      "#ajax" => array(
          "callback" => "activit_registration_form_ajax",
          "wrapper" => "registration-form-ajax",
          "effect" => "fade"));

  $form["ajax-end"] = array("#markup" => "</div>");

  return $form;

}

```

Ajax callback:

```
function activit_registration_form_ajax($form, $state) {

  return $form;
}

```

Validation:

```
function activit_registration_form_validate($form, $state) {

  if(!valid_email_address($state['input']['email'])) { form_set_error('email', 'email'); }
  if(strlen(strval($state['input']['name']))<3) { form_set_error('name', 'meno'); }
  if(strlen(strval($state['input']['tel']))<6) { form_set_error('tel', 'tel'); }

}

```

Ajax callback is now returning the same form, but I would like to achieve returning just a simple string instead of the form when form does not contain any errors.

What is the best way to recognize if a form contains errors or not in ajax callback?

# Answer
> 0 votes
You can define the form status in `$form_state` and check the status during rebuilding form.

Example code:

```
function activit_registration_form($form, $state) {

  if (isset($state['submit_success'])) {
    $form['ajax_form']['message'] = array("#markup" => t('Thanks for your submission.'));
  }
  else {

    $form["ajax_form"] = array(
      "#prefix" => "<div id='registration-form-ajax'>",
      "#suffix" => "</div>",
    );

    // define form elements under 'ajax_form', such as
    // $form["ajax_form"]["element_1"] = array( ... );

    $form['ajax_form']["submit"] = array(
      "#type" => "submit",
      "#value" => t("Odoslať"),
      "#ajax" => array(
        "callback" => "activit_registration_form_ajax",
        "wrapper" => "registration-form-ajax",
        "effect" => "fade",
      ),
    );
  }

  return $form;
}

function activit_registration_form_ajax($form, $state) {
     return $form['ajax_form'];
}

function activit_registration_form_validate($form, &$state) {
  $has_error = FALSE;

  if (!valid_email_address($state['input']['email'])) {
    form_set_error('email', 'email');
    $has_error = TRUE;
  }
  if (strlen(strval($state['input']['name']))<3) {
    form_set_error('name', 'meno');
    $has_error = TRUE;
  }
  if (strlen(strval($state['input']['tel']))<6) {
    form_set_error('tel', 'tel');
    $has_error = TRUE;
  }

  $state['submit_success'] = !$has_error;

  $state['rebuild'] = TRUE;
}

```

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


# Question
Title: How can i get prepared for DRUPAL-PSA-2016-001?
The PSA for tomorrow left me a bit uncomfortable. Quote:

> The Drupal Security Team urges you to reserve time for module updates at that time because exploits are expected to be developed within hours/days.

Does it make sense to put all sites in maintenance mode or take them offline precautionary? Maybe creating database backups before the announcement takes place isn't a bad idea?

Is there a Drupal way of responding such a pending threat? Or should we just sit and wait what's coming?

# Answer
Taking a backup before the security release is a good idea.

Most people can't take their site offline unless completely necessary, but if you have that option then taking it offline at 16:00 UTC while you review and apply the updates would be the very safe way of doing it.

In summary, take a backup now and make yourself available after 16:00 UTC to review which of your modules need to be updated and then apply those updates asap.
> 1 votes

# Answer
1) List all the Drupal 7 projects you maintain. 2) Have a list of used modules by project, you can use fllowing command

```
 drush pml --no-core --type=module --status=enabled > mylist.txt

```

3) Once the updates announced, you can search your modules lists to detect which project you really need to update
> 3 votes

# Answer
The important is being reactive in updating the modules when the security issue is made public, which normally is not done before the new security releases for the affected modules are made available.

The new releases will be available on on Wednesday July 13, 2016 16:00 UTC; until then, you could put the site in maintenance mode, or also temporary disable the modules that aren't strictly necessary. This could avoid possible exploits, but the majority of exploits happens when the security issues are made public, which is moment when you should updated the installed modules.
> 2 votes

---
Tags: 7, security
---


# Question
Title: How to use tokens in data selectors in Rules and how to get autocomplete to work?
In Drupal 7, the Rules module was quite simple to use. You create a rule, define it's action and done. In Drupal 8 version of Rules however, i.e the alfa1 version (which is what I'm using), I see some weird behavior.

I am not able to use tokens in data selectors (also autocomplete won't work).

**What I want to accomplish**: I have two roles: admin and non-admin.

*When a user assigned with the role as `admin` log in, he should be redirected to his dashboard (url: /admin/dashboard) When a user assigned with the role of `non-admin`, he should be redirected to his particular page (url: /non-admin/dashboard)*

There are 2 Rules Conditions related to **User Roles**:

* one is under "Others" tab (= *User Role*).
* one is under "User" tab (= *User has role(s)*).

Both are shown in the image below:

When I choose the 2nd one, I always get an php error (issue already posted on Rules on that).

When I choose the 1st one, no matter what I pass in the Rules Condition, it always returns true and performs the Rules Action.

Am I missing something?

# Answer
> 0 votes
Note: This is not an accurate answer of this problem, as by this time, the Rules module is still in development. This is what I did to solve my problem:

Download PHP Module, as it is removed from Drupal core and is a contrib module now. In Rules, create a new condition known as "PHP execute" and write a php segment which checks user role.

This is probably the easiest way around this problem and will work fine if you are trying to fiddle around. But for production site, I won't recommend this.

---
Tags: 8, rules, actions
---


title: Feed Import (Twitter) via Cron

text:
# Question
Title: Feed Import (Twitter) via Cron
I'm using the Feeds Module to import Twitter Tweets as Nodes. As long as I start the import manually via www.yourdrupal.com/import everything works fine. But I want the Feed importer to start automatically every hour. Cron is activated, but nothing gets imported. I get an error on the statuspage "Token and secret MUST be string values."

My Feed import settings:

Protokoll Log:

Feeds Log:

Debugging Info: "No channels ready to be executed, skipping cron."

# Answer
I would recommend using this sandbox (Twitter Pull) for retrieving tweets instead. I've set it up before and it works quite well. You can see the relevant discussion below.

Errors occured while trying to retrieve tweets
> 1 votes

# Answer
The error:

> No channels ready to be executed, skipping cron

sounds like it's related to Elysia Cron module.

So please double check that you've followed the installation process (`INSTALL.txt`), especially this part:

> To do this refer to the section "Configuring cron jobs" of drupal documentation: http://drupal.org/cron
>
> The only difference is that you should use the `* * * * *` rule part instead of `0 * * * *` or `45 * * * *` as described in the guide.
>
> While you're editing the system crontab, it's also recommended to replace the `/cron.php` part with `/sites/modules/elysia_cron/cron.php` (if you have installed elysia\_cron in `sites/modules` directory). This is an optional step (you can leave `/cron.php` if you want), doing it will result in a better performance in bigger sites (elysia\_cron's `cron.php` handles cache in a better way).
>
> For example:
>
> `* * * * * wget -O- -q -t 1 http://example.com/sites/all/modules/elysia_cron/cron.php`

You can also try to run cron from UI at `/admin/config/system/cron`.

If you're using drush, try `drush elysia-cron run`, instead of `drush cron`.

Check `elysia_cron_run()` for execution logic.

Also check related Drupal issues: #1748106, #1952624.
> 0 votes

---
Tags: feeds, cron, importing-exporting
---


title: First display promotions in a view

text:
# Question
Title: First display promotions in a view
I use the "discount" module, I created a view to display my products but I can not find how to display the products on sale first in my view

# Answer
> 0 votes
Hi checkout you view setting like this http://prntscr.com/bscbkf then add filter on it http://prntscr.com/bscc0e now you can see result http://prntscr.com/bsccbh Also explain some more details

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


title: view_get_views returns null

text:
# Question
Title: view_get_views returns null
I have a module function which needs to get the raw results of a view, so I use this bit of code:

```
$view = views_get_view('sluitingsuren_bakker');
  $view->preview();

  return $view->result;

```

The views machine name is sluitingsuren\_bakker. I also tried some other views, but it seems the module can't find any of the views.

Also I set my permissions on this view to none, because I thought that was the problem.

# Answer
> 1 votes
You are missing the display name, which is the machine name of the block/page.

You can find the machine name under Advanced settings in the right side of the view.

try:

```
   <?php
    $view = views_get_view(view_name);
    $view->set_display(machine_name);
    $view->preview();
    return $view->result
    ?>

```

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


# Question
Title: Permission to edit orders, but not delete
The title is mostly self-explanatory: I need a user to have permission to edit an order, but not be allowed to delete it. I don't think the currently defined permissions for orders allow this. Am I wrong? Is there a workaround/extra module/hackneyed solution you can think of?

# Answer
> 4 votes
Here's the proper way to do it with

`hook_commerce_entity_access`

> Allows modules to deny or provide access for a user to perform a non-view operation on an entity before any other access check occurs.
>
> Modules implementing this hook can return FALSE to provide a blanket prevention for the user to perform the requested operation on the specified entity. If no modules implementing this hook return FALSE but at least one returns TRUE, then the operation will be allowed, even for a user without role based permission to perform the operation.
>
> If no modules return FALSE but none return TRUE either, normal permission based checking will apply.

**Example**

```
/**
 * Implements hook_commerce_entity_access
 */
function MODULE_commerce_entity_access($op, $entity, $account, $entity_type) {
  if ($entity_type == 'commerce_order' && $op == 'delete') {
    // Require administer orders permission to delete orders
    if (!user_access('administer commerce_order entities', $account)) {
      return FALSE;
    }
  }
}

```

# Answer
> 1 votes
There is a module for that™: https://www.drupal.org/project/commerce\_deletepermissions

Have fun!

# Answer
> -2 votes
In the end I settled on the worst kind of solution. I added a little jquery script that selects the "Delete" link (Drupal commerce helpfully gives it its own css class) and hides it. It's stupid, but the customer is happy.

---
Tags: users, commerce
---


title: Add #ajax to an existing form

text:
# Question
Title: Add #ajax to an existing form
I'm trying to add the `#ajax` property to the add form of a simple existing content type. I thought `hook_form_alter` would be the way to go, but the code below doesn't get me the updated results I'm looking for. I've essentially repurposed this code from a `hook_menu` function that creates the fields manually, attaching the `#ajax` at creation, so I think the code itself is okay. I'm just not sure if I'm using the incorrect hook, or if I'm missing something, or what the problem is.

```
function ajax_test_form_example_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_username']['#ajax'] = array(
        'callback' => 'ajax_test_example_callback',
        'wrapper' => 'ajax-test-example-wrapper'
    );

    $form['text']['#prefix'] = '<div id="ajax-test-example-wrapper">';
    $form['text']['#suffix'] = '</div>';
}

function ajax_test_example_callback($form, &$form_state) {
    if(isset($form_state['values']['username'])) {
        $form['field_number']['#description'] = 'Hi <strong> ' . $form_state['values']['username'] . '!';
    }
    return $form['field_number'];
}

```

# Answer
> 4 votes
Turns out that in order to add to an existing field you have to drill down into the array. The correct place to add the property is

```
$form['field_username']['und'][0]['value']['#ajax']

```

# Answer
> 4 votes
For Drupal 8 use:

```
$form['field_username']['widget'][0]['value']['#ajax']

```

---
Tags: ajax, forms
---


# Question
Title: How to send Private Message using privatemsg_services module?
I am using privatemsg services module to create REST API of privatemsg using Services Module in Drupal 7.

I need to know how to send message and how to reply to a message ? Please tell me URL where i should send POST request and the Body of request ?

# Answer
Here you go

To send new message

**Endpoint:** http://example.com/services/privatemsg

**Content to Send (JSON Format)** :

```
{
   "recipients": "xxx",
   "subject":"xxx",
   "body":"xxxx"
}

```

To reply a message for particular chat thread

**Endpoint:** http://example.com/services/privatemsg

```
{
"thread_id": "xxx",
"subject": "xxx",
"recipients":"xxx",
"body":"xxx"
}

```
> 0 votes

---
Tags: privatemsg
---


# Question
Title: How to add a new user badge after earning a certain number of user points?
I'm using the User Badges and User Points modules. I want that when a user earns a certain number of user points, the user's old badge is replaced by a new one. For this, I have already created a rule with the actions "remove badge" and "add badge". The condition is "execute PHP code" and the code is:

```
$current_points = userpoints_get_current_points($userpoints_transaction->uid, 'all');
if ($current_points >=7) {
  return true;
}

```

I also want to display the badge with the username at the top like StackExchange.

**Note**: Using the above code, it is displaying a message each time when user getting more than 7 user points. I want the message only once.

# Answer
> 0 votes
First of all, add the badge(s) you'd like to use at `Configuration > People > Badges > Add new badge`. Afterwards, create a rule for every badge, similar to the following one:

```
{ "rules_new_badge" : {
    "LABEL" : "Add new badge",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules", "user_badges", "userpoints_rules" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "IF" : [
      { "php_eval" : { "code" : "$current_points = userpoints_get_current_points($userpoints_transaction-\u003Euid, \u0027all\u0027);\r\nif ($current_points \u003E=7) {\r\n  return true;\r\n}" } }
    ],
    "DO" : [
      { "add_badge_by_name" : { "badge" : "1", "user" : [ "userpoints-transaction:user" ] } }
    ]
  }
}

```

Import it and modify it, according to your needs. To delete a badge, you can add another Rule with the action 'Remove badge by name'. Mind that I used a PHP Evaluation condition in order to use your PHP code in the Rule. I would, however, advise against this and use the Conditional Rules module instead.

Displaying the user badges next to the user names can be achieved by theming the comments in the `comments.tpl.php` file. This answer might help.

# Answer
> 0 votes
# Add a new badge

Have a look at this Rules example (in Rules export format), which is a variation of the rule posted by Jeroen:

```
{ "rules_grant_a_new_badge" : {
    "LABEL" : "Grant a new badge",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "user_badges", "rules_conditional" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "7" } },
            "DO" : [
              { "add_badge_by_name" : { "badge" : "1", "user" : [ "userpoints-transaction:user" ] } }
            ]
          }
        ]
      }
    ]
  }
}

```

It does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 7, it will grant the user badge.

The key difference here is that **you do not need custom PHP code** (in your Rules Condition) to get this to work (and you don't need to enable the PHP filter for this ...). In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?").

However, by using this module, you can consolidate the logic for various user badges in a single rule, e.g bronze for 7 points, silver for 77 points, gold for 777 points.

The clue to make this rule work is the very first Rules Action "***Load user points of a user***". That's the alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user".

# Remove a new badge

If you want "*a user's old badge to be replaced by a new one*" (as in your question), then you should also add a 2nd Rules Action to the rule shown above. The action to be used is `remove_badge_by_name` (instead of `add_badge_by_name`).

# Only grant a new badge once

To avoid "*displaying a message each time when user getting more than 7 user points*" (as in your question), just add a Rules Condition like "NOT `User has badge`". This is one of the Rules Conditions provided by the User badges module.

# Display the badge

To actually "*display the badge with the username at the top*" (as in your question also), you could use what's written in the Community Documentation about User Badges, i.e:

> To display user badges in your theme use:
>
> ```
> <?php
>   if (module_exists('user_badges')) {
>     print user_badges_for_uid($uid);
>   }
> ?>
>
> ```
>
> Note: $uid means 'a user id' here, not the literal use of $uid. Most people will use the uid of the node ($node-\>uid) or comment ($comment-\>uid) author.
>
> In Drupal (and theming), $node is a PHP object that represents the node, and $comment represents the comment. They are not always both available in every template file, so check the comments at the top of the file to see what is available. You may have access to other uids (user ids), and in these cases you can replace $uid with that value.

---
Tags: rules, userpoints, users
---


# Question
Title: Scheduler changes node language on publish
The scheduler changes the node's language to default-language while publishing.

This happens if the scheduler is run by drupal's cron (called by system-cron or manually) and scheduler's lightweight cron (called by system-cron), but if i start the scheduler's lightweight cron manually by admin-interface it's published with the correct language settings...

It happens on both, single nodes and on translated nodes.

I tried for hours with different settings and configurations. The problem occurs on 2 big sites (with 3 languages), but not on 1 low-level site (with 2 languages).

Any idea?

# Answer
Find the difference between your low level site and the big ones. Perhapsyoushouldcompare their node tables once before and once after you have published content onthem. Make shure, that the modules and settings are the same while running these tests.
> 0 votes

# Answer
I recall someone else having this problem. It was not actually caused by scheduler directly, but another module had a problem in `hook_node_load()` or `hook_node_update()` \- both of which are called via `actions_do()` when scheduler runs during cron.

Check to see which modules are enabled on your big sites and not on the small one, then one by one disble the modules and test Scheduler cron, until the problem does not occur.

Jonathan Scheduler module maintainer
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Module version is not available in the list of the installed modules
I was using Drupal 6 and 7 before. I'm now trying with Drupal 8, but in admin/modules I don't see the module version.

>

Why don't I see the module version? Is that information that Drupal doesn't show anymore, do I need to change settings, or is there any other reason?

# Answer
> 4 votes
On admin/modules, I can see the version of Drupal core modules, and third-party modules.

>

>

For third-party modules, Drupal will show the version only if it finds the necessary information in the .info.yml file of the module. In the case of the Honeypot module, this is what Drupal finds.

```
# Information added by Drupal.org packaging script on 2016-03-11
version: '8.x-1.23'
core: '8.x'
project: 'honeypot'
datestamp: 1457671749

```

Without that, Drupal doesn't show the module version. For example, this is what Drupal shows for my custom module, which is not hosted on drupal.org.

>

If you are using modules that aren't hosted on drupal.org, or you don't use Drush to download the modules, you will not see the module version. This also happens if you clone the module repository with Git instead of downloading the module archive from drupal.org.

# Answer
> 1 votes
It's there. You just need to click on expand button (beside the module description). Here is the screenshot.

---
Tags: 8
---


# Question
Title: Create an expiration date field that auto expires
We are currently migrating a Drupal 6 site to Drupal 8. We have a view that shows a table of files uploaded through the file depot. One of the columns on the table was an Expiration Date. In Drupal 6 we had a module called Auto Expire to set a date for a node to expire which we used to create a field on the view showing the number of days until the link to the file expired.

We created a Node view with multiple fields as the column headings (Date Created, Expiration Date, Staff Member, File Name). For the expiration field, we used Auto Expire to create an Expiration Date field set to 7 days after the creation date. After the 7 days, the node (file depot page) and it's attachments would get deleted.

How do I recreate this functionality (whether programmatically or otherwise) in Drupal 8, since Auto Expire is not updated for Drupal 8?

I am currently looking into the Scheduler module as there is a version for Drupal 8.

# Answer
You can use Scheduler to unpublish the node (and then optionally use Scheduler's hooks/events to delete the node). However, to get the date set into the Scheduler unpublish\_on field, you could use Rules (reacting on 'after creating' event) or use your own custom mymodule\_hook\_save() to set the date.

We are also in the process of migrating Scheduler's actions and events for Rules, (see https://www.drupal.org/node/2651348) and I think that Rules would then let you delete the node reacting to being unpublished by Scheduler.
> 0 votes

---
Tags: 8, views, nodes
---


# Question
Title: How to open quicktab tab from external page (after clicking link url)
i have a slider with link field at my front page, and quicktab section on another page. The slides and the quicktabs are connected, so i want when i click on the link at the slider to open the specific tab. The quick tabs in my case use class active for the clicked section to show. How can i make the tab active externally with click on the link at the slider?

Thanks in advance!

# Answer
> 0 votes
right click with mouse on the Quicktab in question, and copy url. Then use that url on your slider.

---
Tags: navigation, blocks
---


title: Roles, Groups or What?

text:
# Question
Title: Roles, Groups or What?
We use Drupal as the basis for a student information website. We have 3 intakes of students a year and I would like to be able to allocate students various rights based on roles, primarily if they are

* a current student,
* an applying student,
* or an alumni.

But I would also like to be able to identify them by what class they did.

* Should I create a new role for each new intake?
* Should I use groups?
* Is there an alternative method I should use?

# Answer
Best and simple way is to assigning Roles.

Users, roles and permissions
> 2 votes

# Answer
I'd probably initially set up the Current Student, Applying Student, and Alumni roles and get that out of the way.

I'd then have a content type called Class, and hold all of the class information you require in here. I'd then use the Entity Reference to create a link between each student, and any classes they take. This will allow you to filter quite easily in Views and such users based on classes.

Alternatively, if the classes are required to have communities (i.e. people from the Biology class have a place to post information etc) I suppose you could use Organic Groups and sign each student up to the relevent classes/groups.

If you need me to expand on anything or if this doesn't fit then please let me know in the comments and I'll see if I can help any more!
> 2 votes

# Answer
You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

Some more details about the various **roles** used by the Group module:

* *Configured Global Roles*: These roles can be configured via the admin interface of the Group module, they are available (to grant permissions) for all individual groups (regardless of the "Group Type"). These roles cannot have permissions that vary per group type (they are all the same). Typical examples of such roles could be "**Group Moderator**" or "**Group Administrator**".
* *Special Global Roles*: These are the special (hardcoded) roles named "**Outsider**" (= a signed in user that did not join a group) and "**Member**" (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. Unlike Configured Global Roles, these roles can have different permissions sets for each group type. Special case: the role "**Anonymous**" is related to a user that is not signed).
* *Group Specific Roles*: These roles can be configured per group type and will only be available on groups of that group type. As an example, for a group type like "Class", you could configure roles such as "**Teacher**", "**Student**", "**Alumni**", etc.

# Integration with various modules

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

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

# Resources
> 1 votes

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


# Question
Title: Showing Taxonomy Terms with Empty Descriptions in Views
I'm trying to display a list of terms from a single vocabulary that have blank descriptions. I'm using views, and I've tried to set up some regexes as filters. A simple: \[\w\] returns all of the non-blank ones. However, when I try to do something like ((?!.\[\w\]).) which should negate the string, I get some sql errors. I tried filtering with not containing certain words (i.e. any words), and I tried "shorter than" 1, but it seems that the truly empty description fields don't show up on any of these.

Any thoughts?

# Answer
Better late than never? The solution is perhaps a bit counter-intuitive, but you actually don't create a view of taxonomy terms:

1. Create a View of \[content-type\] (A content type which uses your desired taxonomy).
2. Add a Relationship to your taxonomy on that content type ("Content:\[field-name-of-your-taxonomy\]").
3. Add a Filter Criterion using the Taxonomy term definition from your relationship and set the operator to "Is empty (NULL)." (At this point, we are seeing what we want, we just need to make it intuitive to view and eliminate duplicates.)
4. Turn aggregation on so that each taxonomy term appears only once, even if used multiple times.
5. Using an unformatted list style with fields, simply add a field for the taxonomy term name from your relationship.
6. (Optional) Add a Sorting Criterion on the taxonomy term name to sort in alphabetical order.

My use case for this was having added taxonomy terms on certain pages and wanting to go back and add descriptions to the terms at a later date, after they were all done. It was helpful to have a page which only listed ones which still needed descriptions added.

**Appendix**

Aggregation is "necessary" if you have taxonomy terms which are used on more than one different node (virtually every case). If you don't turn on aggregation, you will see one instance of the taxonomy term for every time it is used.

Thus, technically, Steps 4-6 are all optional, but the whole point of this exercise is making it *easy* to view taxonomy terms without descriptions.
> 0 votes

# Answer
Try adding this to the filter field for the taxonomy term description in the regex: ^\[\s\]\*$
> 0 votes

---
Tags: views
---


# Question
Title: It is possible to revert a single item of the component programmatically?
I've feature module which have thousands of entries and I'd like to investigate which item is taking the longest time.

Currently all my features takes over 5h to revert, and I assume it's mainly because of rules config components which there are over 700 (10-20sec each rule, so it's like 2-3h for rules alone) in a single module, and over 200 exported entityforms (which also is slow). This is already after fixes, because before it was taking over 8-10h (before the MySQL stopped with *gone away* error), but this was due to the bug with infinite loop (some Entity+Rules conflict), so disabling `entity_rebuild_on_flush` variable at least worked in terms of finishing the process. This is especially trouble when you're reverting your features during each deployment or building your local environment on daily basis which takes 5h.

So my plan is to revert only rules which I need (e.g. via hook\_update).

---

I'm aware that you can use `features_revert` to revert a single component:

```
features_revert(array('module' => array('component')));

```

however it takes forever and I would like to know if it is possible to revert only single entry (e.g. `foo_my_rule_x`) of a component (e.g. `rules_config`), in other words - **a single line of feature module**, for example:

```
features[rules_config][] = foo_my_rule_x

```

and not anything else, using a standalone code or `drush`.

# Answer
In order to revert, you need to remove a single component from the database, so the configuration from the code can be loaded instead.

So to revert a single rule, load the rule and delete it, e.g.

```
$rule = rules_config_load("my_rule");
$rule->delete();

```

This can be placed in hook\_update().

Check *Add drush rules-revert* patch which provides such functionality for the drush command, e.g.

```
drush rules-revert my_rule

```

---

In addition, to revert all rules by not using Features module (which will take much quicker), you can try:

```
if ($rules = rules_config_load_multiple(FALSE)) {
  foreach($rules as $rule) {
    if ($rule->hasStatus(ENTITY_OVERRIDDEN) && !$rule->hasStatus(ENTITY_FIXED)) {
      $rule->delete();
    }
  }
}

```

So by deleting the rules from the database, they're loaded from the code.
> 2 votes

---
Tags: 7, features
---


# Question
Title: How do I create an Events page listing all Event nodes?
I have a Theatre website that I'm creating in Drupal 8, and I need to create an Event content type. This content type will be displayed on an Events page listing all Events in ascending order from closest date to latest. (I'm pretty sure I can get Views to do this.)

This is how each node should look like when listed on the Events page.

>

I know I need to create fields for:

* Event Poster
* Event Presenter
* Name of the Event (This would be the Title Field)
* Day(s) of the event
* Time(s) of the event
* Event price(s)
* Link to external Ticketmaster-type website to purchase tickets

The problem I have is that not all events are only set up to be on one day or at one time; some events may be listed like the following (Where there are multiple time listings for the day) or some might be where the event is being held for multiple days and may have different times of when it is being held.

>

What field type should I use for the datetime field? Is there a special module I should get for this that allows multiple dates to be listed? Do I even need to worry about a special Time field or do I just keep it as a plain text field for the user to just type in the time(s)?

TL;DR: How do I create a date field that allows to list multiple days *(maybe times)* and then sorting the content type by the days of the event in ascending order?

# Answer
> 1 votes
You can use a Date field with an End Date (I don't have at this moment Drupal 8 installed to show you how)

With Views you can configurate your field to show the Start Date and the End Date. For use the format of Date in one place and Time in another place, you need to create a new Date format.

Maybe this question can be interesting for you: When should I use collect an end date for a field, instead of using 2 separated date fields?. Or have a look at How to Add a Custom Date Format in Drupal 8.

---
Tags: views, entities, 8
---


# Question
Title: Filtering Taxonomy term descriptions in Views
I've created a Taxonomy Vocabulary with the name "Remarque prix". I imported it as a Term reference field to Commerce Product with the aim to be able to give a unique Vocabulary term to each product (SKU).

I want to present the Vocabulary term *description* in the the node by using Views so I created a View showing the Term *description* and took it into the node as a dynamic field, but I can't figure out how to set Contextual filters and maybe Relationships within views so each SKU/Product will have the correct Vocabulary term.

I have spent over a full day on this but can't figure out how to do. Could maybe anyone help me, please?

All the Best

Hans

# Answer
1. Create a block view of Taxonomy terms from your desired vocabulary.
2. Add a Contextual Filter (Taxonomy term: Term ID)
3. Check "Provide Default Value"
4. Select "Taxonomy term ID from URL" from the dropdown.
5. Check "Load default filter from node page, that's good for related taxonomy blocks"
6. Check "Limit terms by vocabulary"
7. Select your vocabulary ("Remarque prix" if I understood your question properly).
8. Add the Taxonomy Term name and description fields.

Now you simply add the block to your product pages (easiest is just using Drupal's blocks, but you may have a different way you want to handle this.

**Appendix**

It doesn't matter if your taxonomy term ID is visible in the URL or not, Drupal understands and will acquire it.

**Note**: If I understand you context accurately, it seems as if your content type for Product has a 1:1 ratio with your SKU vocabulary. At this point, I would consider whether it's actually necessary to have that vocabulary. Generally vocabularies are best used to group content similar in some ways (i.e. the same taxonomy term is used in multiple places). It might be better to make this a text field on the content type rather than a separate vocabulary. But I also don't know your exact situation, you may have good reason for doing it that way. Just some food for though.
> 0 votes

---
Tags: views
---


# Question
Title: Image style is not working for larger size image
I am working on a drupal 7 site http://imgmart.com where I have defined multiple image styles. I have a content type called gallery with image cck field. Everything works fine if I upload image of lower resolution like 800px (around 1 MB) file. When I upload larger resolution image, image style won't work but image file is getting uploaded successfully. I don't see any error reported in log file or log messages page.

What could be the issue?

# Answer
> 0 votes
You are most likely hitting a PHP memory limit. When an image style tried to create a derivative image using the default GD library, the image is processed in the PHP thread and uses the PHP memory. The larger the image, the more memory the process will need. This would make sense why it works with smaller images, but not larger ones.

You could also just be running up against the timeout. The image process for the image could be taking longer then processes are allowed to run, but I'd bet on memory.

Another option is to switch to ImageMagick (https://www.drupal.org/project/imagemagick) to replace GD. I believe this takes the image processing out of the PHP process.

# Answer
> 1 votes
If you allow users to upload large images, you might run into this problem *even after* upping the PHP memory limit. If this happens, I strongly recommend installing this module: Max Image Size.

Suppose you allow users to upload 10mb image files straight from their digital camera, without forcing them to use image editing software.

* Without Max Image Size module, the uncompressed image data for that massive file is held in memory and manipulated multiple times *for each image style*. That consumes a *huge* amount of memory. For many-megabyte "straight from camera" images that'll often exceed any memory limit you could or would want to place on a web server for one user's process.
* With Max Image Size, there's a step *before* that honking great image reaches GD, cleanly scaling it down once to a large-but-reasonable size (2560x1600 by default, this setting can be changed). All the image style manipulations are then done to that image using *much* less memory.

---

This also has the effect of capping the largest possible size another user would get if they click an "original image" link. Very occasionally this might be a problem (e.g. if you're selling professional stock images and need the original monster-sized file - though even then it might be better to upload a raw or tiff file as an untouched plain download alongside the JPG), but usually it's a good thing too. If a user is on mobile data and clicks a full-size image link, they'll normally expect something like a high-quality 2560x1600 wallpaper, not some beast that takes minutes to load and wipes out a substantial chunk of their data allowance.

---
Tags: 7, media
---


# Question
Title: How do I show webform component labels in a chart using Views chart format?
Drupal 7.50, Webform 4.12, Webform Chart 2.0, Views 3.13, Charts 2.0, with Google Charts as the charting engine, so not Highcharts.

I have a webform that collects simple drop down list values for each question. The values are 1, 2, 3, 4 and 5. There are around 10 questions.

The labels for each component are not displayed on the chart. It seems the Label of the very last field added to the list is used for all fields, and they are only shown when the bar is hovered over.

I created a view and added the webform submission data fields then enabled aggregation and set the format to Chart. Limited the number of records in the pager settings to 1 (So we get just one Webform instance). Example below shows how the first series is called "Governance Framework" but when hovered over, the bar shows the last label "Organisational Structure1".

Can anyone advise how I can get the Webform Component Field labels to show up on the left of each of the bars, or fix the hover over issue? Many thanks!

P.s. not sure which module page I should log an issue, so any pointers on how to patch the relevant project would be appreciated.

# Answer
> 0 votes
# Module involved

About your PS:

> ... not sure which module page I should log an issue, so any pointers on how to patch the relevant project would be appreciated.

No doubt possible: Charts.

# Using tooltips

It sounds to me that you should have a look at Pass library-specific options via existing #raw\_options, which already provides a solution (using `#raw_options`) to what you're trying to get to work (ie: "tooltips"). For charting engine *Highcharts* it's already supported (and committed to the most recent ***dev*** version, which is the version I recommend), while for charting engine *Google Charts* (which you are using) you'd need to apply the **RTBC**-patch attached to comment nr 9. Obviously, after that patch is committed, using the *#raw\_options* will continue to work (for either charting engine). And rest assured, this patch ***will*** (not ***might*** ...) make it.

With this **#raw\_options** solution, Charts has a solution for using options that are specific for either of the supported charting engines (Google Charts or Highcharts). While still not deviating from a key design concept of the Charts module, which is that all supported charting options should work for either charting engines (you should be able to easily swap from one to the other charting engine, without your charts being affected).

**Notes**:

1. Apart from Webform Chart (without **s**), there is also Webform Charts (with **s**). The results you'd get are probably going to be similar, because both modules use Charts.
2. Drupal 7.50, which you are using, is the most recent Drupal version, but still your screenprint includes that (red) error msg with "*There is a security update available for your version of Drupal*"... bizarre ...

Disclosure: I'm a co-maintainer of the Charts module.

---
Tags: 7, views, webforms, charts
---


# Question
Title: How to populate field X with value of field Y in Organic Groups?
I want to use rules in order to populate Organic Groups field X value with the value of field Y. Keeping in mind these fields are Organic Group fields.

Field X is a 'long text & summary' field, while field Y is a normal 'text field'.

I'm trying to use Rules Actions to achieve this but no luck so far.

Any suggestions?

# Answer
> 1 votes
Here is a rule (in Rules export format) that should be close to what your question is about:

```
{ "rules_og_populate_fields" : {
    "LABEL" : "OG populate fields",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "og" ],
    "ON" : { "og_user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_x" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_y" } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-y" ],
          "value" : "[node:title-x]"
        }
      }
    ]
  }
}

```

You didn't specify which Rules Event you want to use. In my sample, I used "*User has become a group member*" (adapt the event to fit your own needs).

Notice the "entity has field" conditions, for both fields. Those conditions will make the fields available in the Rules Action ... (so that you can reference field X and set the value of field Y).

If you have the Rules UI enabled, and if the machine names of your fields are indeed "`field_x`" (for field X) and "`field_y`" (for field Y), you should be able to just import this rule in your own site. If you're using other machine names, just adapt the machine names prior to importing this rule (and apply similar changes in the fields mentioned in the Rules Action).

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