# Question
Title: How would you assign a taxonomy term on user registration programmatically?
I'm struggling to figure out how to programmatically assign a taxonomy term to a user in Drupal 7.

I have a term reference field \[field\_event\_location\] on the user registration screen. What I want to occur is to have an Administrator (role) create a new user and assign the meeting manager (role) to a set term.

Once the meeting manager(role) creates a new customer(role) through the user registration form, the term reference field will be automatically set to the term associated with the meeting manager user that was previously set by the Administrator.

I haven't found a contrib module that does this, so I was starting down the path of creating my own module using HOOK\_user\_presave

```
 /**
  * Implements hook_user_presave
  */

  function mycustommodule_user_presave(&$edit, $account, $category) {
    global $user;
      if(isset($account ->is_new) && !empty($account -> is_new)) {
        $roles = user_roles(TRUE);
         if(in_array('meeting manager', $user->roles)) {
          //set user they are creating to the role of 'customer'
             $rid = array_search('customer', $roles);
             $role = user_role_load_by_name('customer');
             $edit['roles'][$rid] = 1;
         //assign the customer to the same location as the venue admin
           $edit['field_event_location'][LANGUAGE_NONE][0]['target_id'] =  field_get_items('user', $user, 'field_event_location', LANGUAGE_NONE);
      }
    }
 }

```

# Answer
Have you considered using Rules?

You could have it react on updating an After saving a new user account,

check for the role being set,

Click on **Add Action**, select Set Data Value

### For DATA Data Selector put `account:field-[name]` In mine I named/called the term reference field `test`

### For VALUE Data Selector put `site:current-user:field-[name]`

We use site current user, because the current logged in user is the Meeting Manager, so we use their term ref field value.

### Result:

This is how it should look like for you. Except for you the `authenticated user` in condition should be `customer` and in Action the test should be your term ref field name.
> 1 votes

# Answer
To programmatically do something when a user register, right before the user is actually saved to the database you can implement `hook_user_presave()`.

```
function MODULE_user_presave(&$edit, $account, $category) {
  global $user;
  $manager_role = user_role_load_by_name('meeting manager');
  $customer_role = user_role_load_by_name('customer');
  if ($account->is_new && user_has_role($manager_role->rid, $user) && user_has_role($customer_role->rid, $account)) {
    $edit['field_FIELD_NAME'][LANGUAGE_NONE][0]['target_id'] = MODULE_get_manager_term($user)->tid;
  }
}

```
> 0 votes

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


# Question
Title: How do I do a regex query in reverse in entity query?
I have a config entity with a row of regex strings, and I want to query which one of them matches a provided string; this stackoverflow question (https://stackoverflow.com/questions/12044628/searching-mysql-database-by-a-regex-match-in-reverse) describes how this could be done in mysql. What's the best way to do this using entity query?

# Answer
> 2 votes
Okay, is seems like this is in fact impossible to do right now with config entities.

If you look at \Drupal\Core\Config\Entity\Query\Condition, and into the function match, it shows what operators are available for config entity queries. REGEXP isn't even an option. Nor is there anyway to query a value against a field, instead of a field against a value.

The only way to really do this seems to be to load all of the config entity records into memory, then do the comparison with php.

---
Tags: 8, database
---


# Question
Title: Field API field_schema for text field error
I've built a custom field using the Field API. I've defined the following element:

```
  $element['tabcontent'] = array(
    '#title' => t('Tab content'),
    '#type' => 'text_format',
    '#required' => $required,
    // use #default_value to prepopulate the element
    // with the current saved value
    '#default_value' => isset($item['tabcontent']) ? $item['tabcontent'] : '',
    '#tree' => true,
    '#rows' => 10,
    '#format' => 'full_html',
    '#base_type' => 'textarea',
  );

```

I've got the following code in the install file:

```
function tabfield_field_schema($field)
{

  $columns = array(
    'tabtitle' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE),
    'tabcontent' => array('type' => 'text','not null' => TRUE,'size' => 'normal','description' => 'Question prompt','length' => '1000'  ),
  );

  return array(
    'columns' => $columns,
    'indexes' => array(),
  );
}

```

However, I get the following error when saving a new node:

> Warning: preg\_match\_all() expects parameter 2 to be string, array given in \_media\_generate\_tagMap() (line 186 of C:\Workspace\RnD\drupal1\sites\all\modules\media\includes\media.filter.inc).
>
> Warning: Invalid argument supplied for foreach() in \_media\_generate\_tagMap() (line 187 of C:\Workspace\RnD\drupal1\sites\all\modules\media\includes\media.filter.inc).
>
> Warning: htmlspecialchars() expects parameter 1 to be string, array given in check\_plain() (line 1572 of C:\Workspace\RnD\drupal1\includes\bootstrap.inc).
>
> PDOException: SQLSTATE\[21S01\]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1: INSERT INTO {field\_data\_field\_tab} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_tab\_tabtitle, field\_tab\_tabcontent) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7\_value, :db\_insert\_placeholder\_7\_format); Array ( \[:db\_insert\_placeholder\_0\] =\> node \[:db\_insert\_placeholder\_1\] =\> 17 \[:db\_insert\_placeholder\_2\] =\> 17 \[:db\_insert\_placeholder\_3\] =\> tabbed\_page \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> ss \[:db\_insert\_placeholder\_7\_value\] =\> ss \[:db\_insert\_placeholder\_7\_format\] =\> full\_html ) in field\_sql\_storage\_field\_storage\_write() (line 448 of C:\Workspace\RnD\drupal1\modules\field\modules\field\_sql\_storage\field\_sql\_storage.module).

# Answer
> 1 votes
This is because your value suppose to be `string`, however you given `array` as per these errors:

> Warning: preg\_match\_all() expects parameter 2 to be string, array given in \_media\_generate\_tagMap()
>
> Warning: htmlspecialchars() expects parameter 1 to be string, array given in check\_plain()

Since you're sending array, the **column count doesn't match** in your SQL query.

This is what you're sending:

```
INSERT INTO {field_data_field_tab} (entity_type, entity_id, revision_id, bundle, delta, language, field_tab_tabtitle, field_tab_tabcontent)
VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7_value, :db_insert_placeholder_7_format);
Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 17 [:db_insert_placeholder_2] => 17 [:db_insert_placeholder_3] => tabbed_page [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => ss [:db_insert_placeholder_7_value] => ss [:db_insert_placeholder_7_format] => full_html )

```

which can be broke down into:

* Fields: *entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_tab\_tabtitle, field\_tab\_tabcontent*
* Placeholders: *:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7\_value, :db\_insert\_placeholder\_7\_format*

So you've 8 fields, but 9 placeholders.

### Fix

To fix it, you've to check passed value of `$item['tabcontent']` and make it a string. For example:

```
'#default_value' => !empty($item['tabcontent']['value']) ? $item['tabcontent']['value'] : '',

```

---

See also:

# Answer
> 0 votes
I only got it to work by using a combination of this approach + the variable\_get() method.

---
Tags: 7, entities
---


title: Views Megarow refresh code example

text:
# Question
Title: Views Megarow refresh code example
I am trying to use Views Megarow to update my entities inline. My problem is how to refresh the view after I save an entity. This is important especially in a case where the view outputs the title of the node and I update the title, for instance, or in the case where I delete the node and want it removed from the view listing.

The Views Megarow readme refers me to Commerce Backoffice for an example. I see that there is a menu entry as follows:

```
$items['commerce_backoffice/order/%commerce_order/%'] = array(
  'title callback' => 'commerce_order_ui_order_title',
  'title arguments' => array(2),
  'page callback' => 'commerce_backoffice_order_view',
  'page arguments' => array(2, 3),
  'delivery callback' => 'ajax_deliver',
  'access callback' => 'commerce_order_access',
  'access arguments' => array('view', 2),
);

```

And then the callback:

```
function commerce_backoffice_order_view($order, $display_id) {
  $title = commerce_order_ui_order_title($order);
  $view = entity_view('commerce_order', array($order->order_id => $order), 'backoffice');
  $view = $view['commerce_order'][$order->order_id];
  $output = drupal_render($view);

  $return = views_megarow_display($title, $output, $order->order_id);
  if (!empty($view['#megarow_refresh_parent'])) {
    $return['#commands'][] = views_megarow_command_refresh_parent($order->order_id, $display_id);
  }

  return $return;
}

```

So the commerce order is loaded, then passed with a display id to that callback function. The entity is then created and rendered, and displayed in the megarow, and an Ajax command is returned.

What exactly is the `$display_id`, and how do I structure the megarow link so that jQuery does the substitution?

I would appreciate it if someone could share a working code example and a conceptual walk-through.

# Answer
> 0 votes
I found a quiet simple solution for this "recalculate-confirm-inline-update" UI pattern in Views Megarow forms.

Implemented scenario : Step1:  Step2:  Step3:

Custom module approach :

```
function some_form_alter(&$form, &$form_state, &$product) {
 ...
 $form['#submit'][] = 'some_form_submit';
 $form['#validate'][] = 'some_form_validate';
 ...
}
function some_form_validate(&$form, &$form_state) {
 ...
 $field1_changed = (!empty($form['field1']['#value']) && $form['field1']['#value'] != $form['field1']['#default_value']);
 $field2_changed = (!empty($form['field2']['#value']) && $form['field2']['#value'] != $form['field2']['#default_value']);
 if($field1_changed || $field2_changed) {
  $result = _calculate_field3();
  if($result == $form['field3']['#value']) {
   return;
  }
  $form['field3']['#value'] = $result;
  $form['field3']['#default_value'] = $result;
  form_set_error('field3', t('Field3 has been recalculated. Please confirm with [SAVE]'));
  return;
 }
}
function some_form_submit(&$form, &$form_state) {
 $product = $form_state['product'];
 //apply $product changes
 commerce_product_save($product);
}

```

The idea is to simulate an update confirm with form\_set\_error(), which will be skipped on the second validation run when calculation equals previous calculation, saved in $form\['field3\].

My client needed a flexible solution allowing him to either enter net sale price or have sale price determined by wholesale price + profit margin + VAT.

---
Tags: views, commerce, ajax
---


# Question
Title: Import CSV, converting repetitive fields to taxonomy terms
Let's say I have a CSV file like this:

```
NAME, TYPE, COLOR
apple, fruit, green
banana, fruit, yellow
kiwi, fruit, brown
carrot, vegetable, orange
potato, vegetable, brown

```

You get the idea. Is it possible to import this CSV file such that specified fields (in this case TYPE and COLOR) are taxonomies, and new taxonomy terms are created automatically?

I really want to do this in Drupal 8, but perhaps a method would be to do it in Drupal 7 and then migrate the data.

# Answer
> 1 votes
It's not clear whether you're looking for a front-end tool, or help with implementing this using the migration APIs. If the latter, in Drupal 8 you can use the migrate\_source\_csv source plugin with the entity\_generate process plugin provided in migrate\_plus. Your migration YAML file might look something like

```
id: food
label: 'Import food nodes'
source:
  plugin: csv
  path: directory/my_csv_file.csv
  header_row_count: 1
  keys:
    - NAME
process:
  type:
    plugin: default_value
    default_value: food
  title: NAME
  field_type:
    plugin: entity_generate
    source: TYPE
  field_color:
    plugin: entity_generate
    source: COLOR
destination:
  plugin: 'entity:node'

```

The entity\_generate plugin will lookup the incoming value in the appropriate vocabulary, create it if it doesn't already exist, and return a reference to the (possibly new) term.

# Answer
> 0 votes
Sure, this is possible, but there are many, many ways of going about it depending on your use case.

The simplest way would be to add a route item and menu link in the admin area (wherever you feel appropriate) which has a form, containing an upload field.

The validation of that form ensures the file is a CSV, then the submission function processes that file, iterates the row, and checks that the term exists and if not, creates it.

This can be done in 7 or 8.

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


# Question
Title: Problem with displaying field using Views
My goal is to use Search API so that I can create a custom search page using Views. I want to add the "rating" widget (rate module), but there is no way to include it in the Search API fields. Thus, I tried to fix it by adding custom field to Search API index.

```
function rate_entity_property_info_alter(&$info) {
  $info['node']['properties']['widget'] = array(
    'label' => t('Rating widget'),
    'description' => t('Rating widget'),
    'getter callback' => 'display_widget',
  );
}
function display_widget($node) {
     print rate_generate_widget('1', 'node', $node->nid);
}

```

However, I am getting AJAX errors

and problems with displaying widgets.

Please can someone help me to solve this problem.

Thanks

# Answer
> 0 votes
If this is a Solr/ElasticDB search backend under Search API, you could try this approach.

Create a view mode on the node type (ex. Search Result), then create a template with the html markup when rendered for it. Include all the fields in the display and configure the formatters as you want them.

Next, install Search API View Modes, and configure that view mode to be indexed. It will render that node before indexing it into a new field (search server side). Then, you can create a view display that shows that field, which is just HTML, and bypass some of these issues.

I use this method in every Search API based search I encounter. You're basically storing the rendered HTML on the search server, then printing that as the result.

I can't tell if you are on Drupal 7 or 8. Note that the 8.x branch 'works' but may have some bugs. I have only been able to test simple setups and not use it on production like the 7.x branch.

---
Tags: views, search, rating
---


# Question
Title: Native Android app with Drupal backend and Login
I need to create a native Android app, this app will use Drupal as a back end.

The app must be native. All the back end functionality, will be taken care of in Drupal, even the login credentials. I will use JSON to get the data from Drupal

I have a few questions on what is possible. Login credentials are stored in Drupal DB. How can i login to Android with these credentials? Can i use JSON and what about the password? The password need to be encrypted.

Is there something like a password protected JSON url? I don't want anyone not authorized to see the JSON url.

If you have any advice or suggestion please let me know. I am new to Android and not an experienced programmer. Thanks in advance

# Answer
> 1 votes
You didn't mention your version of Drupal, and I cannot speak for D8. But D7 has the Services module, and this provides all the functionality you will need. We use the Oauth2 module (that ties in with Services) to provide the authentication mechanism for the apps we build. With this, the user will first log in with their credentials, from which they will receive an authentication token. This token is then used for all further communication between the app and the server.

The Services module is highly customizable, and can be used to code your own resoures that can be called through the API from the app. You can choose the output format, of which JSON is one option.

Shawn answered your questions regarding protection of the user's credentials. This is the same as with a browser - use HTTPS (SSL certificate) and the credentials will be protected. If you don't use HTTPS, the credentials will be there for anyone who looks.

---
Tags: users, 8
---


# Question
Title: Rules: Display Message every first login per day; reset day 12:00am
I am trying to create a rule that will display a message to the user when (s)he logs in for the first time that day. Reset has to be per day at 12:00am.

**Notice: not the first time in 24 hours but the first time that day.**

So if user logs in 8/30/2016 11:59 and then 8/31/2016 12:01am then both times (s)he will see message.

I tried to achieve this using event 'User has logged in' and condition: **data comparison** and comparing last login date with current date and time and offset 1 day. But it's not workings. It might be possible to do this with the custom php?

Thanks God Bless.

**------------------------------------------Update------------------------------------------**

9/1/2016

I need help creating the following rule:

**Trigger:** User logs in

**Condition:** User hasn't logged in this today(since 12:00AM)

**Action:** Display message to user

Am I doing something wrong, or can this be achieved with custom Php? My attempt is described in first update. Can't seem to make this work. The message should only appear every day.

**Day = 12:00:00AM - 11:59:59PM**

# Answer
> 1 votes
There's a few things to mention here.

* Using the `[account:last-login]` token won't work here; Drupal's login process updates the user account `login` timestamp before *User logs in* event.
* Using the `[account:last-access]` token will work however because the *User logs in* event triggers before Drupal updates the `access` timestamp.
* PHP's `strtotime()` has a special keyword for the significant time you're looking for; `strtotime('midnight')` produces the timestamp of when the current day started.

Putting that together, you can create your own custom rules condition via `hook_rules_condition_info()` and using it compare against the `[account:last-access]` token in the *User logs in* event to produce the effect you're looking for:

```
/**
 * implementation of hook_rules_condition_info()
 */
function MYMODULE_rules_condition_info() {
  return array(
    'MYMODULE_condition_before_midnight' => array(
      'label' => t('Before Midnight'),
      'arguments' => array(
        'last_login' => array('type' => 'date', 'label' => t('The date to compare.')),
      ),
      'module' => 'MYMODULE',
      'group' => t('MYMODULE'),
    ),
  );
}

/**
 * Condition MYMODULE_condition_before_midnight
 */
function MYMODULE_condition_before_midnight($last_login) {
  return ($last_login < strtotime('midnight'));
}

```

# Answer
> 1 votes
No problems, here's a basic tutorial. The code goes in your .module file and the functions must have MYMODULE renamed to whatever you name your module.

---
Tags: users, rules, datetime, status-messages
---


# Question
Title: How to combine values of same field in a single column of a chart created with Charts?
My question is about merging values for both the title field (= the company name) and various fields. I'm currently using the Charts module.

In the picture below, it shows a column chart that displays a content type with a field of title, integer field (labeled 2017), and another integer field (labeled 2018). In this view, I have a chart (showing title and 2017) and a chart add-on (title and 2018).

The graph looks like this:

Here is how the table about these data looks like:

```
  Company   ! 2017 ! 2018
  ----------+------+-----
  Company A ! 5    ! 6
  Company B ! 2    ! 3

```

What I want to do is SUM all the values of the 2017 field into one column and values of 2018 into one column.

I tried using the Views Merge Rows module and configured the option to SUM all the values of 2017 and 2018 into one column, but it's not working for me. The chart (showing title and 2017) works since it combines all values, but the chart add-on splits apart and I don't know why.

This is what I get:

Is there a way to combine all values of 2017 and 2018 into one column for each year? "Combine" means that I want to sum all values from a field into one column, so for (e.g.) 2017, it should be 7 (=5+2).

Note: I'd prefer to not Use the Charts API, but I will if I have to.

# Answer
*Edit: The module now shows individual values for each company and takes the company's latest published version's vales. So, if I made another entry for Company A and it's published, the chart will only show the latest version's values. I've also edited the body and included a picture of the final result.*

It looks like building a custom module answered my own question. I had to code a module with the charts API and create a custom block to show the data (it was a huge pain writing the functions and retrieving the data).

Instead of adding all the values into one column, what I've done is take a company's values for each year, place it on the chart, and other company values stacked on the previous company values as shown here:

To anyone else now or in the future with the same problem as me, here's a code snippet that I used:

$chart = array( '#type' =\> 'chart', '#chart\_type' =\> 'column', '#stacking' =\> TRUE, );

Include the code ^above in your function that displays the block/module.

You will need to make your own functions and may be you'll need to implement some of the functions as shown in WD Tutorials for Drupal.

Also, for getting the field data, I made a function that shows all the years (in sequential order). I made several variables: holding a result of an array to store the years, counters (for an array counter, year counter, etc.), an offset for the current year, and a variable for a hard limit (having an arbitrary hard limit is bad). I made use of two while loops that checked to see if the data field (e.g. field\_data\_field\_(insert name of field)) to check if it exists and to see that year contained any rows (indicating that having any values in the table shows that it exists).

As for the other functions, I made separate functions such as filtering duplicates, retrieving all node IDs that are Company content type, and getting each of the node's ID values.

For anyone that's stuck on Drupal's PHP syntax, I would suggest looking at PHP first and then comparing it to Drupal's PHP documentation (confused me at first).

Thanks to all that offered me help during the process. It got me thinking better.
> 2 votes

# Answer
Years ago I was asked to make a usage statistics report for the workflow tool that we had cast in drupal. This report showed tables of workflow requests by type by client by month, with sub totals for each and exposed filters and a csv export. Once it finally worked it was a thing of beauty, but it sure was a pain to build.

The way I accomplished this was with some extra processing in a hook\_views\_pre\_render and then some empty Markup fields with specific names. The view queries the data in the most exposed way possible, lots of fields for my use. Then the pre\_render loops through all of that data with an extra array doing the sums and tallies. Then I inject those values in the appropriate markup fields for each row. The column subtotals meant I added an extra row to the bottom of the table in the pre\_render. Because all of this number manipulation happens in pre\_render, the fields are then handed off to the chart display processor to make your bar graph without fuss.

I would include code examples, but this was back in drupal 6.
> 0 votes

# Answer
To "***sum all values from a field (e.g. 2017) into one column, so 5+2=7***" (as in your comment), you need to tune your view (tabular display) first, similar to what is described also in Steps to create charts using the views UI. Looking at your current (tabular) display of your data, it is not yet showing the **SUM** of the data for which you want to create a chart.

Typically this is done using the Views aggregation of Charts, whereas you use **SUM** (instead of **COUNT** which is used in, eg, the delivered Views examples that come with the Charts module, as shown also in the demo site). For that you don't need Views Merge Rows to get it to work.

If you would only have 1 field that contains a year as value, and another field with some integer value, then you could use aggregation to group each year together, and use "sum" as aggregation function for the other field with the integer value. You however have a 1st integer field (labeled 2017) and a 2nd integer field (labeled 2018). That's different of course. A possible solution could be to think of a way to combine your 2 fields in a single.

# Workaround

Another solution to visualize those data with a single column (for each year), is to create a stacked column chart of it, similar to this demo example. Notice that by such stacking, automagically the height of each column corresponds to the "sum" of all its values of course.

However, that's something you can only do (for now) using the Charts API. For more details on that, refer to the issue about Stacking column/bar charts. With comment nr 3 of it, there is a code snippet that will help to get you going. This is how it looks like:

```
function MYMODULE_chart_alter(&$chart, $chart_id) {
  dsm($chart_id); // Need Developer module enabled for dsm to work
  if ($chart_id == 'MYCHARTVIEW__DISPLAY') { // Watch out for those double underscores
    $chart['#stacking'] = TRUE;
  }
}

```

Note the test about `$chart_id` in it, to only enable stacking for those charts that you really want to be stacked.

And if you would use the same color for all companies (which you can also specify via the Charts API), you would end up with 1 column for each year, showing the total only (since you cannot make a distinction between the various companies if you'd use the same color).
> 0 votes

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


title: Sync Drupal commerce order information

text:
# Question
Title: Sync Drupal commerce order information
Sync Drupal commerce order information between several drupal instances.

Here is my use case.

A business has a Drupal commerce website. It also has several internal commerce sites.

Each of these has to have the ability to work independently of each other for certain periods of time. At a later date there will be a mobile app doing the same thing. So any sales information or orders need to be synced at later points throughout the day.

What is the recommended way to do that securely and also avoid and order related conflicts such as order number customer name changes etc?

I realize this is a fairly broad question but Im not looking for a specific answer, Any general information or recommendations would be great.

# Answer
> 0 votes
Some general advice:

I had a similar situation on a project. I first tried various options for importing orders from the separate sites into a central site using modules like:

1. commerce\_order\_ftp\_export
2. commerce\_export
3. commerce\_export\_csv
4. commerce\_feeds with patch for orders

But you will need custom code to resolve order IDs etc. Depending on the number of sites, this may be workable.

However, I eventually opted for a solution as follows:

1. Using a mobile POS app for sales
2. Sending sales from each instance of the app into a central drupal installation running maceij’s version of commerce\_marketplace
3. This way,sales can be separated and/or aggregated by location, POS, etc.

---
Tags: commerce, 8
---


# Question
Title: How to get all Fields of specific FieldType?
What I'm trying to do is -\>

```
 $fields = [];
  $fields = $entity->getFieldDefinitions();
  foreach ($fields as $field) {
    if ($field->field_type == 'type') {
      $test = $field->field_type;
    }
  }

```

Unfortunately I couldn't find a neat method to select my fields by type, so I thought unless Drupal won't give me one I write my own. But Drupal restrict me on that also with this -\> Fatal error: Cannot access protected property

> Fatal error: Cannot access protected property Drupal\field\Entity\FieldConfig::$field\_type

# Answer
> 3 votes
You code is OK, only that you are trying to read the protected property `field_type`. Instead use the method:

```
$field->getType()

```

Reference: public function FieldDefinitionInterface::getType()

# Answer
> 3 votes
Here is a quick rundown how I retrieved this information:

* Opened up FieldConfig (`core/modules/field/src/Entity/FieldConfig.php`)
* Searched for `$field_type`
* Nothing useful
* Went to the base class FieldConfigBase (`core/lib/Drupal/Core/Field/FieldConfigBase.php`)
* Search results:

+ First one: `protected $field_type;` (okay protected, as expected. This is why it doesn't work)
    + Second result `public function getType() {
    return $this->field_type;
    }`

    This seems to be what we want.
    + Let's see which interface defines this method: My IDE tells me: `\Drupal\Core\Field\FieldDefinitionInterface::getType`

For a little bit nicer code, here is a function which returns all field definitions (note: this are not the fields actually having the values) by field type:

```
function getFieldDefinitionsByType(FieldableEntityInterface $entity, $field_type) {
  $fields = $entity->getFieldDefinitions();
  $fields_by_type = array_filter($fields, function (FieldDefinitionInterface $field_definition) use ($field_type) {
    return $field_definition->getType() == $field_type;
  });
  return $fields_by_type;
}

```

---
Tags: entities, 8
---


# Question
Title: Which tokens can I use in a rule to email all suppliers mentioned in an entity reference field?
In my website, I need to send a notification email to suppliers. I’ve created a content type supplier with email, warehouse 1 and warehouse 2 as fields.

In commerce product, I’ve created a supplier field (entity reference). Now, I need to send an email on the rule event ‘completing the checkout process’ to those suppliers for them to start preparing the products for pickup and I can’t find any related tokens on the Rules Action ‘*Send email*’.

Any suggestions?

# Answer
Assuming your question is about D7, you could try to create a view (using the Views module) of those suppliers that you want to send an eMail to.

After you succeeded in creating such view, you can *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions (in the rule you already have in place related to your Rules Event about "*completing the checkout process*":

* load the VBO list of those suppliers.
* add a loop to perform a Rules Action "send an eMail", for each supplier contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
> 0 votes

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


# Question
Title: node access not taken in account in views
using the hook\_node\_access, i can restrict access to content by role.

If the boolean field\_private\_only is selected , only the user with the role private can view it, fine.

```
 my_module_node_access(NodeInterface $node, $op, AccountInterface $account) {

  global $user;
  if ($node->bundle() == 'my_content_type') {
      if ($op == 'view') {
          if ($node->field_private_only->getString()) {
            $user = \Drupal\user\Entity\User::load($account->id());
            if($user->hasRole('private'))
               return \Drupal\Core\Access\AccessResult::allowed();
          }
      }
   }
 return \Drupal\Core\Access\AccessResult::forbidden();
}

```

When creating a view displaying these contents, the restriction does not occur .

How can i Make it happen in views?

how can i make it happens in search\_api index ?

# Answer
> 0 votes
For doing access control on views, i used the hook\_views\_post\_execute.

For nodes with a restricted\_content field set to true, the content is shown or not depending on roles

```
 function my module_views_post_execute(ViewExecutable $view)
 {
$VIP_member=false;
$user=\Drupal::currentUser();
$userRole=$user->getAccount()->getRoles();

if (( $user!=null )&&(in_array('VIP_member',$userRole))){
    $VIP_member=true;
}

if ($view->id() == 'articles_list') {
    foreach ($view->result as  $elementKey => $result ) {
        $node=$result->_entity;

        $VIP_restricted=$node->field_VIP_only->getValue();

        // Remove node if no rights
        if (($VIP_restricted[0]['value'] == true) && ($VIP_member==false) ){
              unset($view->result[$elementKey]);
        }
    }
}
 }

```

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


# Question
Title: Alter menu title or add menu item programmatically?
I want to create link to user from the menu created by UI. I tried with hook\_menu but the link is 'user', but it doesn't work, because don't want to create new page. I would like to alter title or add menu item programmicaly to use First name in the the menu title.

What i know is the 'mlid' = '3228' and menu name is 'menu-user-links-top'

PS. I also tried with hook\_menu\_link\_alter but it doesn't work, for all users (the first name appears after pressing edit menu and uses only admin's first name).

# Answer
For example, if I take the `User-Menu` in bartik theme, and I want to change the `My Account` menu-title with `Username`, So whenever, the user logged in, instead of `My Account` that menu-item shown the `Username`.

**Image-1: Default menu-item**

>

**Image-2: After the code**

```
function YOURTHEMENAME_translated_menu_link_alter(&$item, $map) {
    global $user;
    if ($item['href'] == 'user') {
      $item['title'] = t($user->name);
    }
}

```

Now, same way as shown in the above code, you can change the apply the `href` of any particular menu-item and there it will show the `user-name` instead of the menu-title.

I am not sure are you looking for this or other, but this is the straight code to change the men-item with username.
> 2 votes

---
Tags: 7, navigation
---


# Question
Title: Hide certain nodes in view listing for anonymous users
I am trying to restrict node access for anonymous users based on a custom field. I got it working for accessing the node directly like this:

```
$country = "GB";
if ($node->hasField('field_country_hide')) {
  $country_code = $node->field_country_hide->value;

  if ($country_code == $country) {
    // this user should not be allowed to see this article
    return AccessResult::forbidden();
  }
} else {
  return AccessResult::neutral();
}

```

But this doesn't restrict access for the node in a view listing. What is the best way to go about hiding a node in a view listing?

# Answer
Drupal doesn't evoke `hook_node_access()` when executing a view; it's querying the DB directly to get the data. As such, you're not going to be able evoke the same PHP snippet to have Views filter the result.

The "best" way (read: simple) is to have views create a query filter that does the same thing; you can add a *Content: Country Hide* filter (or whatever your custom field is named) with the **Operator** set to *Is equal to* and the **Value** set to *GB*.

That will filter the nodes as you need, but you'll still need to provide the *context* (i.e. is the user anonymous or not). Here it's unclear. There's no "best" because there's not one way to provide context and it will depend on your needs.

One idea that comes to mind is to add 2 View blocks, one with the *GB* filter and one without, and set the block to display depending on the user role. But again, this will depend on your requirements. There's always custom Views integration or, if you want to go the site builder route, other modules that provide context like Context, Panels, etc.
> 3 votes

# Answer
For doing access control on views, i used the hook\_views\_post\_execute.

To hide certain nodes for anonymous user, it can be something like this

```
 function my module_views_post_execute(ViewExecutable $view)
 {

$user=\Drupal::currentUser();
$userRole=$user->getAccount()->getRoles();
$anonymous=$user->isAnonymous();

if ($view->id() == 'your_view_machine_name') {
foreach ($view->result as  $elementKey => $result ) {
    $node=$result->_entity;
    $anonymous_hidden=$node->field_intranet_only->getValue();

    // Remove node if no rights
    if (($anonymous_hidden[0]['value'] == true) && ($anonymous==true) ){
          unset($view->result[$elementKey]);
    }
}
}
 }

```
> 0 votes

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


# Question
Title: How to avoid custom module hook_node_presave being overriden by a profile module node_presave
I'm willing to override a value before it get saved in database. The same value is already overriden by commons\_trusted\_contacts module using hook\_node\_presave.

So my custom module hook\_node\_presave get overriden by commons\_trusted\_contacts\_node\_presave.
How do I let drupal know that he need to run my custom hook\_node\_presave after other hook node presave or to not override that single field value.

Below line being overridden :

`$wrapper->group_content_access->set(OG_CONTENT_ACCESS_PUBLIC);`

# Answer
> 1 votes
The order of a module's hook invocation is determined by its weight. In Drupal 7 this set in the `weight` column in the system `table`.

This can be updated through SQL query by setting your module's weight to the heaviest (last) value.

```
# Update with the appropriate values for your install
drush sqlq "UPDATE {system} SET weight = [your_preferred_weight] WHERE type = 'module' AND name = '[your_module_name]"'

```

Or using a module like Modules weight if you need a UI.

See the Drupal.org documentation for more info..

# Answer
> 0 votes
Thanks for pointing drupal.org documentation, It's was helpfull.

I ended up using `hook_module_implements_alter` which better suited to my situation than changing the module weight.

So I've changed the order in which my hooks are triggered than changing module weight.

`/**
* Implements hook_module_implements_alter
*/
function glue_site_module_implements_alter(&$implementations, $hook) {
 if (($hook == 'node_presave') && isset($implementations['my_module'])) {
 //dpm($implementations, 'before');
 $module = 'my_module';
 $group = array($module => $implementations[$module]);
 unset($implementations[$module]);
 $implementations = $implementations + $group;
 }
}`

Reading Adjusting module weight: what are the risks and things to look out for? also helped me to understand behavior of changing module weight.

---
Tags: entities, hooks, 7
---


# Question
Title: Login Users sessions persistence using Services and Rest Server modules
I'm having a heck of a time creating drupal services from angular hitting the rest server. I created a rest end point for all my authentication needs, configured in the Service module. When I use POSTMAN plugin to send json data to the endpoints, the register, login, and logout all works correctly. On POSTMAN, I'm able to send the logout endpoint an X-CSRF-Token to force the logout and it's successful. But when I try to recreate this from my Angular app, it discontinues the workflow from login to logout. Here is the following code:

```
//Called from this.Login success callback, so after you log in,
//this is called to see if I can fetch the same token I logged in with,
//then I'll compare that fetched token with the one created from login
//if they are different, session is not being kept on the server
//if they are the same, drupal is aware that a session is happening
var TokenCompare = function (tokenToCompareFromLogin) {
     return $http({
            method: 'POST',
            url: restAuthConfig.root + '/1.0/user/token',
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(function(response) {
             if (response.data.token == tokenToCompareFromLogin) {
                        $log.log ("We are finally logged in","");
                    } else {
                        $log.log ("We are not logged in", "");
                    }
            $log.log('$membership.Token', response.data.token);
            $log.log('$membership.Login', tokenToCompareFromLogin);
        }, function(error) {
            _isAuthenticated = false;
            $log.log('$membership.IsAuthenticated - Error', error);
            throw error;
    });
}

this.Login = function ($userCreds) {
    $log.log('$membership.Login()', "");
     var _requestObject = {
        "username" : $userCreds.email,
        "password" : $userCreds.password
    };
     return $http({
                    method: 'POST',
                    url: restAuthConfig.root + '/1.0/user/login',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    data: _requestObject
                }).then(function(response) {
                    TokenCompare(response.data.token)
                    var sessId = response.data.sessid;
                    var sessName = response.data.session_name;
                    $cookies.put(sessName, sessId);
                    $cookies.put("X-CSRF-Token",response.data.token);
                    $cookies.put("CSRF-Token",response.data.token);
                    _isAuthenticated = true;
                    return {
                        data: response.data,
                        status: response.status,
                        raw: response
                    };
                }, function(error) {
                    _isAuthenticated = false;
                    $log.log('$membership.Login - Error', error);
                    throw error;
                });
}

this.Logout = function () {
    _isAuthenticated = false;
        return $http({
                    method: 'POST',
                    url: restAuthConfig.root + '/1.0/user/logout',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-Token': $cookies.get('X-CSRF-Token')
                    }
                }).then(function(response) {
                    deleteCookie("X-CSRF-Token");
                    return {
                        data: response.data,
                        status: response.status,
                        raw: response
                    };
                }, function(error) {
                    $log.log('$membership.Logout - Error', error);
                    throw error;
                });
}

```

Then from my controller I have the following lines:

```
$membership.Login({ email : "user104@abc.com", password: "1234" });
$membership.Logout();

```

$membership is the angular service containing the above endpoints.

I was able to register new users, and after calling $membership.Login, I was able to receive a csrf token, and a sessid and sessname, and the response was a 200OK. But when I execute the $membership.Logout(), I get a 406 Not acceptable: User is not logged in. When I look at the TokenCompare function, the token received from api\_auth/1.0/token is different than the token received from api\_auth/1.0/login endpoint. So I have every reason to believe that a session is started from the login endpoint, is ends as soon as the $http finishes its functionality.

It's a bit difficult to find out that cause, as I mentioned, it works in POSTMAN.

# Answer
> 1 votes
This took me roughly 14 hours to figure out. But I finally was able to get it done.

I downloaded the CORS module so I can modify the headers and I added the following lines to the configuration

```
*|http://localhost:3000|GET,POST,DELETE,PUT,OPTIONS,HEAD|Content-Type,Accept,X-CSRF-Token,Cookie|true
#!/*||GET,POST,DELETE,PUT,OPTIONS,HEAD|Content-Type,Accept,X-CSRF-Token,Cookie|true
api/*/*||GET,POST,DELETE,PUT,OPTIONS,HEAD|Content-Type,Accept,X-CSRF-Token,Cookie|true

```
* the first line is from any connections coming from the root site.
* the second line beginnging with #!/\* is an appended entry point from the root site, which hits some my own internal services
* the third line is my api defined from my services module, here is where my authentication happens

The situation that was happening was that I needed to add "withCredentials : true" to the above services. In order to do that, I needed to modify two things

* Access-Control-Allow-Origin must not contain a wild card, it must have the origin, which is localhost:3000
* Access-Control-Allow-Credentials must be set to true

Both of those above lines are configured in the CORS module. This is great, because this is configurable from the CORS drupal module UI, rather than editing any php code. After I did that, I added "withCredentials:true" to every single api call I made, and it worked like a charm!

---
Tags: sessions, csrf
---


# Question
Title: Passing dates or date ranges into a view as arguments
Drupal 7, Views and Date modules installed.

I have a view on a content type with a date field (timestamp, but I can change it if necessary)

When I use it in filter criteria, I have no problem to use criteria like Mydate greater than, less than, between, not between etc. But if I try to do the same thing using contextual filters I have only the "equal" criteria. I need to do this, so i can call the view from code passing arguments to it.

I found some pages about Drupal 6 where is written that i can pass parameter to the filter in format: `2008-11-12--2010-11-12`, but when i try to make it and hit 'update preview', i obtain: `(field_data_field_test_date.field_test_date_value = '2008-01-01--2010-12-31')` in the query.

I need to:

* use criteria greater than, less than, between
* pass date range to the view

Does anybody have some suggestion on how I can do it?

# Answer
> 0 votes
Please refer below URL and check the answer given by @Dmitriy

How to implement less than / greater than in views contextual filters

This may help you.

# Answer
> 0 votes
Use Views Contextual Range Filter module

> Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range.
>
> Numeric, alphabetical and list ranges are all supported. Node ids, user ids and even taxonomy term ids are all special cases of numbers so will work also. Range-filtering on dates is also supported. For this you may use either the absolute date format as dictated by Views, YYYYMMDD, or the relative format, which supports natural language phrases like six months ago, today noon and even first Tuesday of November

---
Tags: 7, views, datetime
---


title: /current/ date range contextual filter

text:
# Question
Title: /current/ date range contextual filter
I have a view `/widgets` with a couple of optional contextual filters of type "Has taxonomy term converted to ID", so the url can look like this:

* `/widgets/blue`
* `/widgets/big`
* `/widgets/small/green`

And so on.

But there should also be a "current" contextual filter on the date field defined as such:

Currently, we used exposed date filters as such:

But for "current" widgets, my urls look like this:

`/widgets/blue/small?field_date_value_op=<%3D&field_date_value%5Bvalue%5D%5Bdate%5D=2013-05-17&field_date_value2_op=>%3D&field_date_value2%5Bvalue%5D%5Bdate%5D=2013-05-17`

How to make:

* `/widgets/blue/small/current` do a filtering like `field_date_value<=today && field_date_value2>=today` ?
* `/widgets/past` do a filtering like `field_date_value2<today`
* `/widgets/future` to `field_date_value>today`

# Answer
> 0 votes
Use Views Contextual Range Filter module

> Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range.
>
> Numeric, alphabetical and list ranges are all supported. Node ids, user ids and even taxonomy term ids are all special cases of numbers so will work also. Range-filtering on dates is also supported. For this you may use either the absolute date format as dictated by Views, YYYYMMDD, or the relative format, which supports natural language phrases like six months ago, today noon and even first Tuesday of November

# Answer
> 0 votes
I decided to create 3 sub-pages with normal filters, /widgets/all /widgets/past /widgets/current and /widgets/future.

---
Tags: views
---


# Question
Title: How do I display all available field types?
I want generate an new form in a custom module via the `generate:form` command.

In this step, I must enter a field type.

How can I get all available field types?

# Answer
With the term "field type" you probably don't find what you are looking for. Better search for "form and render elements". You can find a list of all available elements here:

https://api.drupal.org/api/drupal/elements/8.2.x

You can use all elements of the type "FormElement".
> 3 votes

---
Tags: forms, console
---


# Question
Title: How to restrict entity reference displaying values?
I have a requirement which I feel quiet complex. I am using Entity reference in X content type to reference a content type(assume Y). This works fine by displaying all the values of Y in X.
Y content type is having one field that is true or false type. So I want to display values in select list of X content type only which is having true value in the Y content type.So how can I achieve that, any suggestions will be appreciated.

# Answer
You'll have to dynamically create that select list based on the field's values which are `TRUE` from the CT Y. I suppose that this select list belongs to a from, and what a convenient hook hook\_form\_alter is!

```
/**
 * Implements hook_form_alter.
 */
function module_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_xyz_form_id') {
    // Find all referenced items
    $target_ids = $form['field_reference_to_ct_y'][LANGUAGE_NONE][0]['#options'];
    // Load all referenced items
    $nodes = node_load_multiple(array_keys($target_ids));
    foreach ($nodes as $node) {
      if ($node->field_to_check_if_true[LANGUAGE_NODE][0]['value']) {
         // Alter the select list options
         $form[field_select_list][LANGUAGE_NONE]['#options'][$node->nid] = $node->title;
       }
    }
  }
}

```
> 0 votes

---
Tags: 7, nodes
---


title: How do I load a JavaScript file?

text:
# Question
Title: How do I load a JavaScript file?
I used the following code.

### libraries.yml

```
    my_module.admin:
  version: VERSION
  js:
    js/my-module.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

```

### my\_module.module

```
 /**
 * Implements hook_page_attachments().
 */
function my_module_page_attachments_alter(array &$attachments) {

$attachments['#attached']['library'][] = 'js/my_module';
  // $attachments['#attached']['library'][] = array('my_module', 'admin');
}

```

### my\_module/js/my\_module.js

```
(function($, Drupal, drupalSettings) {
    Drupal.behaviors.my_module = {
      attach: function(context, settings) {
        $(document).ready(function() {
            alert("hello");
            console.log('Loaded');
          }
        };
      })(jQuery, Drupal, drupalSettings);

```

I have tried many other changes, but the JavaScript file is not used.

I have ported Drupal 7 code that implements `hook_boot()` and includes that JavaScript file, to Drupal 8.

# Answer
> 2 votes
See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme. In your case, the library name is wrong. The right format for the name is *module\_name/libraries\_name*.

```
/**
 * Implements hook_page_attachments().
 */
function my_module_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'my_module/my_module.admin';
}

```

# Answer
> 0 votes
Following changes worked for me :

```
$attachments['#attached']['library'][] = 'my_module/my_module.admin';

```

and

```
my_module.admin:
  version: VERSION
  js:
    js/my_module.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

```

---
Tags: 8, javascript
---


# Question
Title: How to load webform results using EntityFieldQuery
I have a webform and I need to read its results/submissions using **EntityFieldQuery**.

I need to load all the results of a specific webform having a field value. ( load all the submissions of webform node where age = 25 )

Can EntityFieldQuery do that ?

Thanks in advance.

# Answer
Webform results aren't entities, so you can't use an `EntityFieldQuery`.

You'll need standard db queries to get that data.
> 0 votes

---
Tags: database, webforms
---


# Question
Title: D8: Replacing Contact Form Title With Label
I've searched around for this answer but to no avail.

All I want to do is with any contact form I create I want to replace its default title (usually "contact") with the form's label.

So instead of {{ title }} something like {{page.label}}.

I need more descriptive titles for my forms.

# Answer
`{{ page['#title'] }}` seems to work consistently and accesses the form's label.
> 0 votes

---
Tags: theming, 8, emails
---


# Question
Title: Running drush up to several sites folders at once
In my server's root folder I have the folder `www` that contains sites of all my websites. All of these are Drupal.

Navigating into each folder and doing `drush --no-backup up -y` each time, can be both time consuming and tiring.

Is there a way to update all sites at once, with drush, instead of installing third-party software (like Ansible, IINW).

The command `drush --no-backup up -y @sites` won't help in this case, as it is aimed for multisites, and I don't work with multisites at all.

Update 1 - Note (might not be relevant when you read this question):

```
<?php
$aliases['mine'] = array(
'site-list' => array('@site1', '@site2')
);

```

The file containing it should be putted under public\_html (or www) with permissions as 755 or 644.

# Answer
First off, look to the trivial solution:

```
#!/bin/bash
drush @site1 up -y --no-backup
drush @site2 up -y --no-backup

```

You don't need to install Ansible to start automating; simple bash scripts can be used to combine repetitive tasks very easily. If you are on Windows, you can install Git for Windows, which includes a Bash shell, or, if you really don't want to install anything at all, use a .bat file.

There is also a Drush solution: Drush can run the same command on multiple sites if you give it a list of aliases:

```
drush @site1,@site2 up -y --no-backup

```

If you have a lot of sites, you can make a site alias that is a list of site aliases:

```
<?php
$aliases['mine'] = array(
  'site-list' => array('@site1', '@site2')
);

```

Then:

```
drush @mine up -y --no-backup

```
> 5 votes

---
Tags: drush, updating
---


# Question
Title: User logout automatically when the browser is closed
I need to logout a user if the browser is closed. I'm using Drupal 8. I tried setting a session cookie in php. But the problem is the cookie should be '**httponly**' and '**secure**'.

Please suggest me the right method or is Drupal having such settings to achieve this.

Thanks.

# Answer
Okay, I changed the **cookie\_lifetime: 2000000** to **0** in *local.services.yml* file.

Then set the cookie in php by giving the last 2 arguments as 'true' ,this makes the cookie to be httponly and secure.

Thanks for your reference.
> 1 votes

---
Tags: 8, cookies
---


title: syntax error, unexpected '['

text:
# Question
Title: syntax error, unexpected '['
I am tring to get DRUSH (drush-master) up and running on a CentOS release 6.8 (Final) virtual server using PHP version 5.6.22. I will copy the php & DRUSH outputs below including the final error message:

Looking through the forums there is mention of the cause being an outdated version of PHP. However, I've checked the requirements and am pretty sure these versions should be compatible.

```
[server2 drush]# which drush
/usr/bin/drush
[server2 drush]# ls -lart /usr/bin/drush
lrwxrwxrwx 1 root root 35 Sep  2 16:05 /usr/bin/drush -> /usr/local/drush/drush-master/drush*
[server2 drush]# /usr/bin/php56 --version
PHP 5.6.22 (cli) (built: Jul  5 2016 15:31:36)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
[server2 drush]# /usr/bin/php56 /usr/bin/drush

```

> Parse error: syntax error, unexpected '\[' in /usr/local/drush/drush-master/includes/preflight.inc on line 248

# Answer
> 2 votes
The syntax error you are seeing implies that you are actually running php 5.3. I can see that /usr/bin/php56 is version 5.6.22, but does `$(which php)` really point to /usr/bin/php56? Double-check your $PATH.

---
Tags: drush
---


# Question
Title: Users can rate product after their order status changed to completed
I want to give permission to user to rate a product when their order status set to completed. For that I've tried using rules but in action i was not able to set permission for particular user whose order completed.

I'm using five star drupal module which is using voting api. Need help to implement this feature.

# Answer
What I am suggesting is to create a new node type "review" and referenced this to product with references module. Create one view to display reviews or rating on product page. Create one permission or need to hook for permission to access already purchase of same product.
> 0 votes

# Answer
I followed all the steps from this link https://www.drupal.org/node/1308114 . Which helped me to get the required result.

Then for anonymous user I just made them to login before give review by writing some code inside template.
> 0 votes

---
Tags: commerce, rating
---


# Question
Title: Get user account content object loaded in node.tpl.php
By default `$account->content` object is loaded only on user page.

I want to print `$account->content` in node.tpl.php.

In `user-profile.tpl.php`, I tried echo `"<pre>"; print_r($account);` and `$account->content` is fully loaded.

How would I do the the same in `node.tpl.php` ? I tried with `user_load(1);` but `account->content` is not built.

# Answer
> 1 votes
You have to explicitly build the account content since it is not done automatically outside the context of *user\_view* operation. I would do it this way :

```
/**
 * Implementation of hook_preprocess_HOOK().
 */
function yourmodule_preprocess_node(&$variables) {
  global $user;
  $account = user_load($user->uid);
  user_build_content($account);
  $variables['account'] = $account;
}

```

Then, just print `$account->content` in *node.tpl.php*.

The key is to call `user_build_content($account)` where `$account` is passed by reference, it also returns the fully-built account content (more commonly known as profile).

# Answer
> 1 votes
try this

```
global $user;
$account = user_load($user->uid);

```

# Answer
> 1 votes
If you want to add account of site visitor use this code in the beginning of your tpl file :

```
<?php
  global $user;
  $account = user_load($user->uid);
?>

```

else if you want to add account of node author, then try this:

```
<?php
  $account = user_load($node->uid);
?>

```

the reason is that in node tpl files drupal does not provide user information by default.

---
Tags: theming, users, 6
---


# Question
Title: Drupal 8 cron not running from external source (as anonymous)
Running cron with crontab is not working on our Drupal 8 website if the user is anonymous. If I'm logged in as admin, I can run cron with the button or the url with key. If I'm not logged in, cron doesn't run with url with key.

Running from crontab is of course anonymous and so cron is not running.

Any ideas?

Version: Drupal 8 beta 4

Line in crontab:

```
*/5 * * * * wget -O - -q -t 1 http://www.entityone.be/nl/cron/theactualcronkeyhere

```

# Answer
I know the question is old, but I faced a similar problem and would like to help people coming from google.

I assume you have a function in one of your specific cron hooks which needs extra permissions to run which won't work because Drupal runs cron as an anonymous user.

What helps is to identify which hook\_cron needs elevated rights and switch to e.g. the admin account before the affected code runs:

```
use Drupal\Core\Session\UserSession;

// call the account switcher service
$accountSwitcher = \Drupal::service('account_switcher');
// switch to the admin user
$accountSwitcher->switchTo(new UserSession(['uid' => 1]));

// run your code here

// switch back to old session
$accountSwitcher->switchBack();

```
> 2 votes

# Answer
I use following line and it works pretty well on drupal 8.0.5

```
wget -q http://domain/cron/theactualcronkeyhere -O /dev/null

```
> 0 votes

---
Tags: 8, cron
---


# Question
Title: How to visit a specific node using behat
I am doing some work that requires customization of a breadcrumb for only one content type. I'm trying to write a behat test to verify it.

My Given is successfully creating the nodes, and I can verify that they are there if I tell behat to look at them in the admin content view:

```
Scenario:
  Given "partner_accomodation" content:
    |title            | body         | status|
    |Accomodation Foo | Test content | 1     |
  And I am logged in as a user with the "administrator" role
  When I go to "admin/content"
  Then I should see "Accomodation Foo"

```

What I can't figure out though is how to tell it visit that specific page. I would assume if I have pathauto configured correctly, that I should be able to go something like

```
When I go to "accomodation-foo"

```

Is there a way to know the node id or the URL alias of the content it created?

# Answer
You can do two things in this scenario:

You can instruct it to click on "Accomodation Foo" (which should be the linked node title) on this page, to go to the node when the path is unknown.

If you have pathauto installed and configured, you can assume the path, so if it is \[node:title\], the path in this case is likely 'accomodation-foo'.

I use both in different cases, depending on the scenario. I keep the test node titles small and predictable so I know what the path (should) be. If the path isn't found, it is also a good way to test if Pathauto is creating the URLs you expect.

Here is an example one I wrote not too long ago:

```
Feature: Page Content Type (Anonymous)
  When I view the website
  As an anonymous user
  I should be able to view basic page content and its fields

  Background:
    Given "page" content:
      | title                     | status  | body             |  field_subtitle       |  field_summary            |
      | Published page            |       1 | PLACEHOLDER BODY |  This is the subtitle |  This is the page summary |
      | Unpublished page          |       0 | PLACEHOLDER BODY |  This is the subtitle |  This is the page summary |
    And I am on "published-page"

  Scenario: An anonymous user should be able access published basic page content
    Then I should not see "You are not authorized to access this page."

  Scenario: An anonymous user should be able to view the title
    Then I should see "Published page" in the summary region

  Scenario: An anonymous user should be able to view the subtitle
    Then I should see "This is the subtitle" in the summary region

  Scenario: An anonymous user should be able to view the page summary
    Then I should see "This is the page summary" in the summary region

  Scenario: An anonymous user should not be able access unpublished basic page content
    When I go to "unpublished-page"
    Then I should see "You are not authorized to access this page."

```
> 5 votes

---
Tags: testing
---


# Question
Title: How to access an entity loaded out of the cache
I am working on a Drupal 8 modules which should push a http response header based on a value stored in an entity or a list of entities.

The module was originally done for D7 and now is in porting up to D8.

The main problem is that by using the Entity Cache in D8 any hooks are bypassed, which had been working in still in D7. So nor hook\_entity\_load or hook\_entity\_view are fired but only a single time before the entity is placed into the cache.

We might need to create an extra entity/node to a list and this should then eventually change the pages html-head section and the http response header.

So is there any chance to get informed (by a hook or event) for ALL entities be shown on a page (details or list/teaser)? Or can we store some information to a "cached" page (so a page that was assembled only out of cached entities) ?

# Answer
Although the questions is not so clear I will try to give you some directions. I think it is time to dive into the new Cache API (I haven't done it so far!)

First of all, to get the "*information*" for a cached page you need to deal with the contexts and the cache tags.

To invalidate the tags you may need to use function **invalidateTags(array $tags)** (here is an example of using this class).

On the other hand if you want to invalidate cache of each node while loading the node you can set this option to the node\_load($nid = NULL, $reset = FALSE) function by using `$reset = TRUE`.
> 0 votes

---
Tags: 8, caching
---


# Question
Title: Custom language that displays content from two languages
This is a rehashing of a question I asked previously, but maybe asked the wrong way.

I have a multilingual Drupal 7 site - there are 13 different languages and those sites all have unique translated content on them.

However, there are an additional 5 "languages" we need to account for - an example of this would be Australia. Australia speaks English so we'd like it to display English content, but there is also content that is unique to Australia (which can't display on the English site), so that should be displayed on the Australian site as well.

I'm curious if we can define a custom language (Australia) that can display multiple types of language content (English and Australian).

For example:

**Australian Website**

* Home (English)
* About (English)
* Products (English)
    + Product One (English)
    + Product Two (English)
    + Product Three (Australian)
    + Product Four (Australian)
* Resources (English)
* Contact (English)

Hopefully this makes sense. Any insight is appreciated.

# Answer
> 0 votes
The whole idea of linking language with country falls apart when you consider countries like Canada. You could separate language and applicable country since they're not really the same thing. In your example:

**Australian Website**

* Home (Lang: English - Country: UK, US, Canada, Australia)
* About (Lang: English - Country: UK, US, Canada, Australia)
* Products (Lang: English - Country: UK, US, Canada, Australia)
    + Product One (Lang: English - Country: UK, US, Canada, Australia)
    + Product Two (Lang: English - Country: UK, US, Canada, Australia)
    + Product Three (Lang: English - Country: Australia)
    + Product Four (Lang: English - Country: Australia)
* Resources (Lang: English - Country: UK, US, Canada, Australia)
* Contact (Lang: English - Country: UK, US, Canada, Australia)

# Answer
> 0 votes
What you need is to manage translations per locales. Drupal's language could be used as locales. For instances, you can have two English language (`en` for "English US" and `en-au` for "English Australia"). Drupal already take care of not displaying translations other languages, so "English Australia" content should not be visible by "English US" users.

You then need a way to fallback to another language when a translation is missing in the wanted language (eg. fallback to the "English US" translation of a content when it has no "English Australia" translation). It seems like the Language fallback is made specifically for this use case.

---
Tags: 7
---


# Question
Title: Give permissions to a specific role to edit specific terms
I have a vocabulary (*Foods*) with these terms.

* Meet
* Fruits

I want every user with the *Gardner* role to be able to edit the description of *Fruits* only. How can I do that?

This is just an example, on my site I have several terms, and I need specific users roles to edit specific term descriptions.

https://www.drupal.org/project/private\_taxonomy does what I need, but I already have the taxonomy terms and I don't know how to change the ownership.

# Answer
The access callback for a term edit page is `taxonomy_term_edit_access($term)`. You need to replace it with a custom one in order to allow gardeners to access the page for fruit terms.

```
/**
 * Implements hook_menu_alter().
 */
function MODULE_menu_alter(&$items) {
  $items['taxonomy/term/%taxonomy_term/edit']['access callback']
    = 'MODULE_term_edit_access';
}

/**
 * Access callback for taxonomy edit term page.
 */
public function MODULE_term_edit_access($term) {
  if (MODULE_term_is_fruit($term) && user_access('edit fruits terms')) {
    return TRUE;
  }
  return taxonomy_term_edit_access($term);
}

/**
 * Returns whether or not a term is a fruit.
 */
function MODULE_term_is_fruit($term) {
  // ... implement fruit detection here ...
  foreach (taxonomy_get_parents_all($term->tid) as $parent) {
    if ($parent->name == 'Fruit') {
      return TRUE;
    }
  }
  return FALSE.
}

/**
 * Implement hook_permissions().
 */
function MODULE_permissions() {
  $permissions['edit fruits terms'] = array(
      'title' => t('Edit fruits terms'),
      'description' => t('Allows the user to edit Fruits terms.'),
  );
}

```
> 2 votes

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


title: How to generate an XML feed?

text:
# Question
Title: How to generate an XML feed?
I am creating an XML feed (`domain.com/content_type/feed`).

I looked into **RSS Publishing** and have turned it off, but do see where I can generate an XML feed: `Home » Administration » Configuration » Web services`

Is this the correct way?

# Answer
> 3 votes
You can do it using the Views Data Export module (Most popular)

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV
> * Microsoft XLS (or really simple HTML understood by Excel)
> * Microsoft DOC
> * Basic TXT
> * **XML**

Example:

Alternatively, you can also do it using the Views Datasource module

> Views Datasource is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on **XML**, JSON and XHTML. These formats allow content in a Drupal site to be easily used as data sources for Semantic Web clients and web mash-ups. Views Datasource plugins output content from node lists created in the Drupal Views interface in a variety of formats - XML data documents using schemas like OPML and Atom, RDF data documents using a vocabulary like FOAF, JSON data documents in a format like Exhibit JSON, and XHTML data documents using a microformat like hCard.

---
Tags: 7, feeds
---


# Question
Title: How to delete all data when uninstalling a module without going in manually in PHPmy Admin?
Whenever I have a troublesome module, I have to uninstall it, then delete the folder, then go play around PhpMyAdmin to delete junk it left in my database.

This is prone to causing errors and breaking stuff...

Is there a way to uninstall modules cleanly, to delete ALL data?

I have no access to Drush on the server also...

# Answer
> 1 votes
Modules should clean up after themselves. If they aren't, you should report it in the module's issue queue.

But, at least with D7, there isn't really much that should be left in the database. Most modules that create tables delete them when they are finished. The biggest area where things are left behind is in the variables table - many modules don't clean these out. You can safely delete them after module uninstall though.

---
Tags: database
---


# Question
Title: How to create test users on the localhost?
I would like to make test users on my localhost (in my case I am using WAMP). Since I need to be able to authenticate them via email. I am not getting it to work what can I do?

# Answer
To add new user you can go to `admin/people/create` (*localhost/YOUR-SITE/admin/people/create*) and create the user, you don't need to enter a real email. And if you want to test the site with different users you can use the Masquerade module.

> The Masquerade module allows site administrators (or anyone with enough permissions) to switch users and surf the site as that user (no password required). That person can switch back to their own user account at any time.
>
> This is helpful for site developers when trying to determine what a client, logged in as themselves, might see when logged into the site.
> 2 votes

# Answer
very easy, go to people section and add a new account manually. and change user state to active
> 0 votes

# Answer
I don't know whether there is a generic alternative, but I used the Test Mail Server Tool when I built my Drupal website on a localhost. Also, if you need to create a lot of test users, the Devel module can come in handy. After installing it, you can automatically create any number of users with randomly filled in user fields. I am not sure whether the authentication via email will still work in that way, but you can give it a try.
> 0 votes

# Answer
If you use something like Mailcatcher/Mailhog on your local dev stack, it will catch all outgoing mail instead of actually allow it to be sent to users. You can then log into its admin, and view the emails, and obtain the content/link within.

Dev stacks like drupalvm.com come with this option and is an easy switch on. Test emails to your hearts content.

You don't want to test with a module that does any sort of mail rerouting (all mail goes to user 1 for example) because that isn't really testing in near - real world conditions.
> 0 votes

---
Tags: users
---


# Question
Title: Create a sample HTML select of taxonomy terms
I created a custom form in a custom module. (in a class that extends FormBase) I want to add a (very) simple html select element, this select must contains all taxonomy elements of a specific vocabulary, like this, where the integers are the taxonomy term IDs.

```
<select id="...>
    <option value="4">tutu</option>
    <option value="15">toto</option>
    <option value="61">tata</option>
    ...
    <option value="48">titi</option>
</select>

```

How can I create this `<select>` tag using the taxonomy term ID and the taxonomy term name? The users would not see the taxonomy term ID, but only the taxonomy term name.

With a vocabulary name, how can I generate the good structure (an array?) that allows me create the `<select>` tag?

# Answer
> 6 votes
You will need to get your terms (with a query or load the vocab), loop over them and create an array of term tid and term label. Set that array as the #options property on the select field in your form code.

---
Tags: 8, forms, taxonomy-terms
---


title: Views show empty fields

text:
# Question
Title: Views show empty fields
How to use Views to list all empty apartments, which do not have any tenant? So basically I have two content type: Apartment and Tenant as below.

Apartment content type:

* Room
* Tenant (entity reference to Tenant content type)

Tenant content type:

* Name
* Phone

Do you guys have any suggestion?

# Answer
> 1 votes
It's simple in Filter Criteria, click add and add your entity reference field.

When you are adding your field, for **Operator**, select `Is Empty (Null)`

Drupal 8 Example:

Drupal 7 Example:

---
Tags: views, nodes
---


title: How to require a password when login in

text:
# Question
Title: How to require a password when login in
I'm making a CMS for my job on Drupal 7. when i go onto the login page I'm able to access the content on the site without having to enter the password. how do i change this?

# Answer
Content created with drupal UI:

You need to configure proper user permissions for content. e.g. If you don't want to show content from Content type "Article" to anonymous user, Go to the permissions page (Administer \> People \> Permissions) and remove content view permissions for anonymous user.

Content Created programmatically :

1) Menu page : While you register your custom menu with hook\_menu, you should assign proper value to "access arguments". e.g.

```
/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items['example'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}

```

2) Custom block:

For custom blocks, you need to define your access by user role. You can assign role visibility either by drupal UI(block configuration page) or you can do same thing programmatically. Please refer below reference.

https://drupal.stackexchange.com/a/69897/57643

After configuring user permissions over content, drupal will show access denied page if user don't have permission to view content. Its drupal's default behavior. If you want to override this behavior, you can use contributed module Redirect 403 to User Login. This will redirect user to login page instead of just showing access denied page.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Add comment with Inline Entity Form while adding content
I'm creating a content type. and want to add comment for the same content on same form of add content.

I've installed Entity Reference, and selected *Entity reference* as **Field type** & selected *Inline entity form - multiple values* as the widget. I've chosen **Selected Target** type *Comment* under **FIELD SETTINGS** and I'm still not getting the comment section on content addition form.

Why is it not showing? Is there another way to show comment on content addition form?

# Answer
Inline Entity Form doesn't support Comment forms out of the box.

Part of the process of building the IEF widget is a call to `inline_entity_form_get_controller()` which will retrieve a controller class from the entity metadata. As you can see in IEF's `hook_entity_info_alter()` invocation, it only adds this controller metadata for node, taxonomy, commerce product, & commerce line item entities.

Theoretically, you could build your own custom module that could:

1. Invoke `hook_entity_info_alter()` to add support for comment entities.
2. Build your own custom class that extends `EntityInlineEntityFormController`(e.g. `CommentInlineEntityFormController`) to be evoked for form processing.

Keep in mind this is an unusual use case, a comment entity is predicated on a *its parent entity pre-existing before it's created*; you're likely to run against logic that might prevent this (e.g. database integrity checks) .

It might be easier just to create your own custom node type entity that's configured just to appear like comments on your nodes.
> 1 votes

---
Tags: 7, entities
---


title: How do I get a multi-field values?

text:
# Question
Title: How do I get a multi-field values?
I have content type called "sample", where i have field called 'user detail' which is a multifield. I'm using multifield module to get this. I'm creating a view for display sample content type contents, but i'm not able to fetch multifield fields in view table.Can anybody help me in fetching multifield values?

# Answer
> 0 votes
By default this puppy does not come with Views integration, perhaps it will soon in the near future.

For now, you will need to patch it, with this patch.

---
Tags: 7
---


# Question
Title: Render one Paragraphs Module field value inside another Paragraph field's .html.twig template
This question is for the Paragraphs module for Drupal 8.

I've created a Paragraph Type with 4 fields: Title, URL, Image, and Description.

I want to take the value from the URL field, and use it with the Title and Image fields, so that my title and image have a link wrapped around it with the href getting the value from the URL field.

My idea was to use Twig template suggestions for the Title and Image fields, but I can't figure out how to render the value of the URL field in those .html.twig files....

For example, I have a twig suggestion template for the title, called:

```
field--paragraph--field-list-item-title.html.twig

```

My idea was to render the value of the URL paragraph field with this:

```
{{ paragraph.field_list_item_link_url }}

```

so that the code inside my `field--paragraph--field-list-item-title.html.twig` file looks like this:

```
  {% else %}
{% for item in items %}
  <div{{ attributes }}><h3><a href="{{ paragraph.field_list_item_link_url }}">{{ item.content }}</a></h3></div>
{% endfor %}{% endif %}

```

But its not rendering anything.

Is there a way to accomplish this? Is there another way instead?

# Answer
You could try a template for the paragraph itself, rather than the individual fields. If you look in the modules/paragraphs/templates you'll see the default template used to render paragraphs. Copy this into your theme and rename it to paragraph--XXXXXX--default.html.twig replacing XXXXXX with the machine name of the paragraph.

You can then access the values of your fields using {{ content.XXXX }} where XXXX is the machine name of the field, e.g. {{ content.field\_list\_item\_link\_url }}
> 1 votes

---
Tags: theming, 8
---


# Question
Title: How to optimise views with multiple field collection?
I created a views reports page with multiple field collections (10), I added the field collection in relationships in advanced option to get the fields inside the field collection. this works great I get all the data that I need. but here's the problem. If the page have the data on it, it takes time to load the page.

Example: If I have thousands of data in views reports page, it takes time to load the page, almost 1 minute(some times it keeps on loading). though I only display 10 items on each row using pagination/views lightpager but stills the page loading is slow,

My question: is how can I optimise my views reports page with multiple field collection relationships in my current setup, any suggestions will be appreciated.

Note: The data should always up to date. that's why I don't cache the views.

Thank you!

# Answer
> 1 votes
As per your reply, you dont want to use Cache, so I can suggest a module for this, Views Accelerator. It increases the performance of the view.

> Views Accelerator can bring about significant speed improvements on sites with views that cannot be cached normally, for instance because the views depend on an aspect of the visitor's session, like their location. Views Accelerator serves up two modes of operation.
>
> Analysis mode: Switched on from the module's configuration page, admin/config/system/views-accelerator, this displays at the top of the screen a performance summary for each view on the page. If performance is already great, tell your boss or customer. If it isn't, take a screenshot of the performance summary and proceed with the Accelerator mode: On views that could do with a boost, find and click the Caching option link in the Advanced section of the Views UI. It will reveal a new pseudo-caching option: None. Post-execution optimized by Views Accelerator. Select that. Revisit the page with the view(s) and compare performance stats to the screenshot you took earlier. Win? Then tell your boss or customer.

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


# Question
Title: How to show data of user that flagged a content(2 flag types)?
I have 2 flag types for a content type. both flags have flag field. consider the user flagged a content by both flags. I want to show user data. I have problems in this situation. I add flag A and flag B in relationship part of views, after that I add "username of user" and "flag field" in fields part. but unfortunately I should add 2 "username" field, one of them should relation to flag A and other should relation to flag B(relation part in field setting). this is problem. because I want one field of "username", not 2 "username" fields. What should I do?

# Answer
> 4 votes
Add a filter for the whole view that checks username in both fields as not null, and set the operator to 'And'.

In your view under 'Filter Criteria' do the following:

1. Add user name with the first relationship and set the operator to 'is not empty (NULL).
2. Do the same for the second username field.
3. Click the dropdown arrow next to add for 'Filter Criteria'. Select And/OR, Rearrange and add an 'AND' operator between the two filter.
4. Hide the second username from display.

That way you can filter for users with both flags.

# Answer
> 1 votes
It seems that the crucial part of your (updated) question (as in revision 3 of it) is that you need use filters that are related to "either of your 5 flags", which means that Views should use an "**OR**" (instead of "**AND**", which is the default) in its query.

To make that possible, you can use the Views Contextual Filters OR module (which only has a dev version today, though close to 2K sites are using it).

Excerpt from its project page:

> ... provides a views plugin which modify query to support OR conditions for contextual filters.
>
> ... A new option will appear in settings page query. If the option is enabled the query will be rewritten using operator OR.

Have a look at the image below (also from the project page), near the bottom of it there is a checkbox titled "***Contextual filters OR***":

So after you enable this module and check this checkbox, you may get it to work. To actually do so, you need to enhance/correct the view you already seem to have, similar to what is detailed already in the answer from balmong. But for the filter criteria make sure to use "**OR**" (instead of "**AND**"), and make sure you do so for all your 5 flags (as in your updated question, so not just for the 2 you originally mentioned).

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


title: How to use rules to store field value?

text:
# Question
Title: How to use rules to store field value?
I am writing a rule to store Tenant field's value to Previous tenant field whenever the Tenant field is updated and saved. The following are apartment and tenant content types.

Apartment content type:

* Room
* Tenant (entity reference to Tenant content type)
* Previous Tenant (unlimited number of values is set for this field)

Tenant content type:

* Name
* Phone

And this is my rule:

```
{ "rules_tenant_records" : {
"LABEL" : "Tenant records",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--apartment" : { "bundle" : "apartment" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "node-unchanged:field-tenant" ], "field" : "field_tenant" } }
],
"DO" : [
  { "data_set" : {
      "data" : [ "node:field-previous-tenant" ],
      "value" : { "value" : [ "[node:field-tenant]" ] }
    }
  }
]

```

} }

It does not work, any suggestion?

# Answer
> 1 votes
### Tenant:

### Appartment:

### Rule:

### Result:

### Rules Export:

```
{ "rules_store_tenant_name" : {
    "LABEL" : "Store Tenant Name",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--appartment" : { "bundle" : "appartment" },
      "node_update--appartment" : { "bundle" : "appartment" }
    },
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "node", "id" : [ "node:field-tenant:nid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "list_add" : {
          "list" : [ "node:field-previous-tentant" ],
          "item" : "[entity-fetched:field-name] [entity-fetched:field-phone]",
          "unique" : "1",
          "pos" : "start"
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
Do following steps:

Instead of **Set data value** use **Add an item to a list** in action. In **List** field select `node:field-previous-tenant`, in **Item to add** field select `node-unchanged:field-tenant`. At last add an action **Save entity** and select `node` in Entity field.

---
Tags: 7, entities, rules
---


title: Views block element with Panels viewes

text:
# Question
Title: Views block element with Panels viewes
I have a content type **foo**, that has a media field and a body with text. I want to list the most resent **foo** on whit a specific visualization: double column layout for a foo that has media which is previewed left and on the right is a summery of the body. If there is no media then simply show the summary of the body.

I can create a block **bar** in *Views* module, that list all the **foo** and show this block on . I can create a Node template of type **foo** with *Panels* module that has the required layout but I don't know how to apply that on the list of **foos** in **bar**.

Do I need to use in Panels *Node template*? My selection rule is: `This panel will be selected if NOT (media is set to ""), and Current path is "front".` (not working).

# Answer
> 1 votes
If you use a special layout only here, maybe the display suite module is enough for you. The main part of the solution is you have to create a view mode for the node, that you will use to display a media/description in the views. You have to set the proper layout here, so something 50/50 and the two fields. If you are done with this new view mode, you have to go into the views. In the **Format** section you will see the **Show** line there you have to change from Field to Content. If you set the Content you will see a second column which is listing the available view modes for your content, here you need to select the recently created view mode.

---
Tags: views, blocks, panels
---


# Question
Title: Drupal 8, very simple hierarchical form doesn't work
In a custom module, I create a new form. In the buildForm function, I define my form :

```
$form["planet"] = array(
  '#type' => 'textfield',
  '#title' => '1 : '.$this->t('planet'),
  '#maxlength' => 64,
  '#size' => 64,
  '#tree' => TRUE,
);

$form["planet"][0] = array(
  '#type' => 'textfield',
  '#title' => '0 : '.$this->t('land'),
  '#maxlength' => 64,
  '#size' => 64,
);

$form["planet"][1] = array(
  '#type' => 'textfield',
  '#title' => '1 : '.$this->t('land'),
  '#maxlength' => 64,
  '#size' => 64,
);

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

```

There are 3 fields, but this is the result :

Why there only first field displayed ?

# Answer
> 3 votes
You need change type **$form\["planet"\]** to **fieldset** or **container**. Don't use text field in this case:

```
$form["planet"] = array(
  '#type' => 'fieldset',
  '#title' => '1 : '.$this->t('planet'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);

```

---
Tags: forms, 8
---


# Question
Title: How to define a new cache context for a node
I am preprocessing a node with some data, i want to define a new cache context based on this data.

```
function hook_preprocess_node(&$variables) {
    $variables['change'] = rand(0,5);
}

```

Once i have defined the new context i think i shuold be able to use it as follows.

```
function  hook_entity_build_defaults_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, $view_mode) {
  if($entity->getType() == 'page'){
    $build['#cache']['contexts'][] = 'change';
  }
}

```

I can't seem to find out how to define a brand new cache context based on the data in my preprocess so that i can use it in hook\_entity\_build\_defaults\_alter();

# Answer
You will need to define a cache context in `yourmodule/src/Context`. This will be a class implementing *CacheContextInterface*, as described in the docs here (see 'How to recognize, discover and create?).

If you search for `implements CacheContextInterface` in your code base you should be able to see some examples. The class will provide `getContext()` and `getCacheableMetadata()` methods.
> 6 votes

---
Tags: 8, caching
---


# Question
Title: Drupal 8: The proper alternative to exit(); for terminating a request
Does anybody know how to avoid the brutal PHP built-in exit(); function and use the "right" Drupal 8 class method to terminate the request? If so: a bit explanation would be appreciated.

# Answer
You would have been looking for drupal\_exit() in the past, but this was removed in D8. It is now advised to use the appropriate HTTP Exception. See the example on the change notice:

https://www.drupal.org/node/2017339
> 1 votes

---
Tags: 8
---


# Question
Title: HTTP ERROR 500 comes on using theme function
I used following code:

Inside a route callback function.

```
 $my_module_form = \Drupal::formBuilder()->getForm('\Drupal\my_module\Form\MyModuleForm');
    $my_module_header_message = "hello;
    $my_module_footer_message = "hello;

 return theme('my_module',
      array(
        'my_module_header_message' => $my_module_header_message,
        'my_module_form' => $my_module_form,
        'my_module_footer_message' => $my_module_footer_message,
      )
    );

```

Inside my\_module.module file

```
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_module' => array(
      'template' => 'templates/my-module',
      'variables' => array(
        'my_module_header_message' => NULL,
        'my_module_form' => NULL,
        'my_module_footer_message' => NULL,
      ),
    ),
  );
}

```

I have also create templates/my-module.html.twig file and rendering hello sample content.

This is my MyModuleForm.php file

```
<?php
/**
 * @file
 * Contains \Drupal\example\Form\MyModule.
 */

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
 * Implements an example form.
 */
class MyModuleForm extends FormBase {

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

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

    $form['my_module_error_message'] = array(
      '#type' => 'markup',
      '#markup' => '<div id="my_module_error_message"> </div>',
      '#weight' => 0,
    );

    return $form;
  }

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

  }

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

}

```

I am having problem in defining and calling hook theme for rendering drupal forms.

I think any of these 3 are wrong, a)my form definition, b) theme definition or c) theme call. Please tell me where am i doing wrong?

# Answer
> 1 votes
In D8 controllers return a render array. Put the template name you have defined in `hook_theme()` in `#theme`. Prefix the variable names with a '#':

```
return array(
      '#theme' => 'my_module',
      '#my_module_header_message' => $my_module_header_message,
      '#my_module_form' => $my_module_form,
      '#my_module_footer_message' => $my_module_footer_message,
);

```

---
Tags: forms, 8, theming
---


title: Add new content to an existing view

text:
# Question
Title: Add new content to an existing view
As I have stated in my last few questions, I have almost zero knowledge on Drupal. I have just been given access to a website and told to make changes. So please bare with me and excuse my ignorance. View the below link:

http://www.ascoworld.com/about-us/our-people/leadership-team

The section with the photos and names/titles seems to be a "view"? I have found the edit page (see screenshot). All I am trying to do is add more people. How would I do this? I can seem to add more fields but that just adds to the existing people and not new ones. Any help would be greatly appreciated.

Thanks!

EDIT: Updated the link to live site. Apologies.

# Answer
According to the View, to add more people into this display you need to adhere to the filter criteria the View is filtering on.

So, it looks like you need to:

* Create a new node of Leadership Team
* Fill out the fields
* Set the 'Role' field to Leadership Team
* Set the node to to published

You should now see it show up in the list.
> 1 votes

# Answer
The link you gave is a Admin view only. I can't open it without your login.

But going off of your image here looks like your view settings are set to show the nodes with the role "Leadership Team".

All you have to do is go to the Content tab in administration view, and change existing nodes roles to "Leadership Team" or add new content with role "Leadership Team" this way it will be displayed on this view.

God Bless!
> 0 votes

---
Tags: views
---