# Question
Title: How to send email to multiple recipients using drupal_mail?
I am using drupal\_mail to send email,

```
$to = 'email@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

```

I want to send email to multiple email addresses at once. Should I be doing this?

```
$to  = array('one@email.com', 'two@email.com', 'three@email.com',);
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

```

# Answer
The to-parameter to `drupal_mail` is a string, not an array. But you can have as many receipent as you like in the the e-mails "to" string, provided they're separated by commas.

So to send the same mail to multiple recipients, do the following:

```
$to  = 'one@email.com,two@email.com,three@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

```

Se also API documentation for `drupal_mail`
> 26 votes

# Answer
According to PHP doc you can send only one letter via one call of function drupal\_mail. So, you should use cycle. Example

```
$to  = array('one@email.com', 'two@email.com', 'three@email.com',);
foreach ($to as $email) {
  drupal_mail('$module_name', $key, $email, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);
}

```
> 1 votes

# Answer
Use hook\_mail to send multiple receipients by passing:

```
$params = array();
$params['cc'][] = 'abc@ex.org'
drupal_mail('$module_name', 'custom_key', $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

//hook will be the module name

function hook_mail($key,&$message,$params) {

  if ($key == 'custom_key') {
    $message['headers']['cc'] = $params['cc'];
    //.
    //.
    //.
    //.
  }
}

```
> 1 votes

# Answer
If you read drupal\_mail function documentation then you'd see '$to' param accepts string not an array in certain formats like:

1. user@example.com
2. user@example.com, anotheruser@example.com
3. User
4. User , Another User

So, we can easily convert your $to array into required format using implode function and hence you'll be to send email to multiple recipients in one go. Here's the code:

```
$to  = array('one@email.com', 'two@email.com', 'three@email.com',);

//To change array('one@email.com', 'two@email.com', 'three@email.com',)  -> 'one@email.com, two@email.com, three@email.com' use implode

$to_str = implode(",", $to);

drupal_mail('$module_name', $key, $to_str, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

```
> 0 votes

---
Tags: emails
---


# Question
Title: What causes 'sites/default/files is not writable' during Drupal 7 Install on Redhat w/ Apache?
I am attempting to install Drupal on Linux Redhat using Apache, but it will not allow me to pass step 3 due to the fact that sites/default/files is not writable.

I have followed the instructions on Drupal.org, in their install.txt file as well as the instructions from others who have had the same error with no success.

I have granted permissions **access all** different ways, i.e.: root:root 777, root:apache 777.

I have also verified that Apache is the user running the Apache process, but I am still stuck.

Notes:

* I have granted the user 'apache' 777 rights to the files folder with no luck.
* I verified the user 'apache' is in fact the user running apache.
* I was able to complete the installation of Drupal on Windows.

Any new ideas?

# Answer
> 5 votes
I thought this would be a SElinux issue with security and I am a bit surprised that your solution worked.

For users with the "common" error, use the following command to provide apache with access despite SElinux security.

```
chcon -R -t httpd_sys_content_rw_t yoursite/sites/default/files/

```

# Answer
> 2 votes
Okay, so after following directions from both official and non-official web sources, the one thing that was never instructed to do or try was to reboot the application AFTER making permission changes to the *files* directory. I tried it, and this solved the issue.

This is weird because I've never had to reboot an OS after making permission changes on a directory. Additionally I did restart httpd after each change thinking that would be sufficient. Hopefully this can help anyone else running Redhat 7 with the same issue.

Thanks, TH

# Answer
> 1 votes
Have you checked to see if one the parent dirs of sites/default/files is restricting write access to Apache? That's my guess of what the problem is.

If you have sudoers access, you can use this command to test write access for the apache user when you're in the Drupal root directory:

```
sudo -u apache touch sites/default/files/test.txt

```

# Answer
> 0 votes
Likewise, this happened to me as well on redhat/Centos 7.3. Sys admining for years and NEVER have had to reboot for such an issue. I hope this helps someone else that's going crazy.

Drupal says sites/default/files is not writable but it really is.

---
Tags: installation, files
---


title: why can't I create comment using rules?

text:
# Question
Title: why can't I create comment using rules?
Simple rule:

after update node: create new entity with type: "comment"

but after update node, nothing happens...

why that?

UPD, added screenshots of my rule:

UPD2: i can create node by creating entity, but not a comment o\_O

UPD3: **ok understand what is the problem: i called the content type(machine name) 'task'** =)

UPD4: errors while updating node and creating comment:  full error message: "Unable to get variable entity\_created, it is not defined."

# Answer
> 2 votes
Because you did not save it.

Add action of `Save Entity`.

---
Tags: 7, rules, comments
---


# Question
Title: Get a module version for a list of modules
## Context

* Drush version 8.x
* Drupal 7 site

## Problem

* Mr. HtraenuRekaos has a text file with a list of Drupal contrib modules.
* He wants to get the recommended-install version of all the modules in the list.
* This list is not associated with any pre-existing site, and none of the modules are currently installed.

## Non-solutions

* Mr. H has already looked at this SO post: Using wget to get the latest module version, but he does not want to use wget, he wants to use drush
* Mr. H does not want to actually *download or install* the relevant modules, he only wants to get a list with the latest recommended D7.x version.

## Question(s)

* Is there a drush command that will turn *before* into *after*?

### Before

`MODULE_NAME_HERE ;; RECCO_VERSION_HERE
contrib_module_001 ;; __blank__
foobar_module ;; __blank__
htraenurekaos ;; __blank__`

### After

`MODULE_NAME_HERE ;; RECCO_VERSION_HERE
contrib_module_001 ;; 7.x-1.6
foobar_module ;; 7.x-2.2
htraenurekaos ;; 7.x-3.6`

# Answer
> Mr. H does not want to actually download or install the relevant modules, he only wants to get a list with the latest recommended D7.x version.

Well, at the very least, you can do:

`drush @site.env up module_name --select` for individual modules, you can also do:

`drush @site.env pm-releases` which has a load of options for output.

https://drushcommands.com/drush-8x/pm/pm-releases/

It has format options.
> 1 votes

---
Tags: 7, drush
---


# Question
Title: Migrate import with authentication onto external site
What configuration is needed in to use the MigratePlus authentication plugin. I need to authenticate the migrate import requests so that I can successfully import files behind a login.

# Answer
Can you provide a little more detail? What sort of authentication do you need? The migrate\_plus module has three authentication plugins - basic, digest, and oauth2. The first two take 'username' and 'password' in their configuration - oauth2, naturally, is quite a bit more complex.
> 0 votes

---
Tags: 8, migrations
---


# Question
Title: How can I use Metatag Module to set specific tags on specific nodes?
I'm using the Metatag module to set tags on content generally throughout my project. But there is one group of content where I want to be able to set the metatags for specific nodes. Because these nodes have unique specific tags, I want to be able to set them at the node level.

Is there a way to do this?

# Answer
**In Drupal 7**

When you configure Metatag, you can click on `+ Add default meta tags` and this will allow you to **set them up by Content Type**.

If you need to alter **only specific nodes**, edit your node and scroll down to the end and select the Meta tags Tab
> 2 votes

---
Tags: meta-tags
---


# Question
Title: Automatically import data from Google spreadsheet using feeds module
I have data in a Google docs spreadsheet. To import that data I currently have to download the spreadsheet as a csv file and then import using the Feeds module.

What I am trying to work out is if there is someway to automate the process? Is there some way to have feeds access the spreadsheet directly from Google docs?

Would appreciate some step by step instructions on how to set this up. Note that I already have feeds setup to manually import a csv file, so the issue at hand is how can I set it up so that feeds can retrieve the data directly from Google docs at regular intervals?

Note that the data is stored as regular Google doc spreadsheet, so solution needs to make sure that the document retrieved is in CSV format (is that possible by using a certain URLs structure?)

# Answer
Sorry, bit late to the party. How I solved this was:

* Publish the file to the web using the option in Google Sheets' file menu. This gets you a special link to an always up-to-date version with the format of your choice. I used CSV.
* Select HTTP fetcher as fetcher.
* Select appropriate parser (CSV in my case) and set up mapping
* Set up periodical imports.
* Enter the URL you got from Google Sheets as source when importing.

Your updates to the Google Sheets file will be imported with the periodical imports.
> 6 votes

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: How to make a change that affect several site at once?
We have two Drupal 7 and two Drupal 8 website for an airline company. We want the staff at the airport to upload a flight schedule in such a way that it will get displayed in all the four sites at once. How can I achieve this?

# Answer
> 1 votes
You should be able to do this by uploading the schedule to one site and then exposing an RSS feed for the other sites to pull it down.

---
Tags: database, multi-sites
---


# Question
Title: Am I missing a step with using Features?
I've made changes to a Panel variant on my local site and wish to push it to the remote site, but I am having trouble doing this - the changes to the variant are not appearing on my remote site.

Here's what I am doing:

1. In Features I find the Page Manger section with my variants. I check them all, increment the version number and hit download.
2. I unzip the downloaded .tar file and place the Feature files within my folder structure: modules\>\>features\>\>module\_name. I overwrite the existing files in there.
3. Using Git, I push these to my remote site (all's good with this step - I see the CSS changes I pushed as well)
4. On the remote site I access features and see that my module's features are overwritten. I check it's check box and hit Save Settings.

But nothing changes when I look at my variants - my changes do not appear.

Is there a step I am missing here?

# Answer
> 0 votes
Features can sometimes be finicky. Often times, just clearing caches after reverting will cause your changes to go into effect. In other cases, it can be necessary to revert the specific item (such as views or rules).

Personally, I haven't used Page Manager with features, but the general concepts apply consistently across the board.

---
Tags: 7, panels, features
---


title: Display batch operations messages

text:
# Question
Title: Display batch operations messages
I have defined a batch, everything works ok, but I want to understand how the messages are displayed. So I have this batch:

```
$batch = array(
  'title' => t('Generate reports'),
  'operations' => array(
    array('create_report_callback', array($time_min, $time_max)),
  ),
  'init_message' => t('Starting report generation...'),
  'progress_message' => t('Generating report. Operation @current out of @total.'),
  'error_message' => t('Error detected. Please try again!'),
  'finished' => 'create_report_finished',
);

```

What I want to know is how to change the `progress_message` to something else than `Operation @current out of @total`. I don't know where the `@current` and `@total` come from

Thank you.

# Answer
The placeholders `@current`, `@total`, etc are described in the file `includes/form.inc` in the description of the `batch_set()` function.

> * progress\_message: Message displayed while processing the batch. Available placeholders are @current, @remaining, @total, @percentage, @estimate and @elapsed. Defaults to t('Completed @current of @total.').

---

You can add custom placeholders by using the t() function like this:

```
$my_custom_variable = 'contents of my custom variable';

$batch = array(
  'title' => t('Generate reports'),
  'operations' => array(
    array('create_report_callback', array($time_min, $time_max)),
  ),
  'init_message' => t('Starting report generation...'),
  'progress_message' => t('Generating @my_custom_placeholder report. Operation @current out of @total.',
     array(
       '@my_custom_placeholder' => $my_custom_variable,
     )
  ),
  'error_message' => t('Error detected. Please try again!'),
  'finished' => 'create_report_finished',
);

```
> 0 votes

---
Tags: 7, batch-operations
---


# Question
Title: How do I use theme('links') with nested arrays?
I want to render the following output:

```
<ul>
  <li><a href='url1'>link 1</a></li>
  <li><a href='url2'>link 2</a>
    <ul>
      <li><a href='url3'>sub-link 3</a></li>
    </ul>
  </li>
  <li><a href='url4'>link 4</a></li>
</ul>

```

I was expecting this to be pretty straightforward:

```
$list = array(
  'item1' => array('title' => 'link 1', 'href' => 'url1'),
  'item2' => array(
    'title' => 'link 2', 'href' => 'url2',
    array(
      'item3' => array('title' => 'sub-link 3', 'href' => 'url3'),
    ),
  ),
  'item4' => array('title' => 'link 4', 'href' => 'url4' ),
);

$output = theme('links', array('links' => $list));

```

This outputs the following however, ignoring `item3`:

```
<ul>
  <li><a href='url1'>link 1</a></li>
  <li><a href='url2'>link 2</a></li>
  <li><a href='url4'>link 4</a></li>
</ul>

```

# Answer
> 5 votes
You need to add the sub items to a 'children' key of the array. Here is an example:

```
$list = array(
  'item1' => t('Item 1'),
  'item2' => array(
    'data' => t('Item 2'),
    'children' => array(
      t('Item 3'),
    ),
  ),
  'item4' => t('Item 4'),
);

return theme('item_list', array('items' =>  $list));

```

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


# Question
Title: Exporting webform information programmatically
I have a Drupal site that uses the Webform module. It has many options for downloading the results via the Drupal interface but it doesn't have anything out the box to get the data programmatically (JSON ect).

Is this possible? Authentication will still be require *i.e* only Drupal users for the site should be able to access this information via the JSON request.

# Answer
> 2 votes
You might have to create your own. It would probably be worth submitting back as a new module too.

All you would have to do is implement hook\_menu() to add your menu callback. In hook menu you can set access arguments to make sure no one case use it unless they have a particular permission.

You can add your own custom permission using hook\_permission().

Then the callback function could use webform\_get\_submissions() to load the submissions for a given webform and return them using drupal\_json\_output()

You could pass in a webform nid argument either via the url, using something like 'get-webform-submissions-json/%node' as your menu path, which would automatically validate the nid and load the node for you. For more information on that see http://drupal.org/node/224170 You could also just pass it in as a query parameter and use $\_GET\['nid'\] in your callback function, however then you need to validate it yourself.

# Answer
> 1 votes
using the accepted answer as a reference i wrote the following piece of code which I know is not perfect but should get you started:

```
/**
 * Implementation of hook_menu().
*/

function survey_json_exporter_menu() {
$items['survey_json_exporter'] = array(
    'access callback'   => true, // available to all
    'page callback' => 'survey_json_exporter',
    'delivery callback' => 'drupal_json_output'
    );

return $items;
}

function survey_json_exporter($form, &$fstate)
{
   module_load_include('inc', 'webform', 'includes/webform.submissions');

   $returningJSON = new stdClass();

   $Surveys = [];

   //TODO - > Loop All Surveys.
   $submissions = webform_get_submissions(70535);

   // Load components for each node.
   $surveycomponents = db_select('webform_component')
     ->fields('webform_component')
     ->condition('nid', 70535)
     ->orderBy('weight')
     ->orderBy('name')
     ->execute()
     ->fetchAllAssoc('cid', PDO::FETCH_ASSOC);

   foreach ($submissions as &$submission) {
       $submissionObj = new stdClass();
       $submissionObj->SubmissionID = $submission->sid;
       $submissionObj->SerialNumber = $submission->serial;
       $submissionObj->DateSubmitted = $submission->submitted;

       $SumbissionQA = [];
      while ($surveyanswer = current($submission->data)) {
        $componentName = $surveycomponents[key($submission->data)]['name'];
        $submissionSurveyAnswers = new stdClass();
        $submissionSurveyAnswers->Question = $componentName;
        $submissionSurveyAnswers->Answer = $surveyanswer[0];
        $SumbissionQA[] = $submissionSurveyAnswers;
        next($submission->data);
    }

    $submissionObj->SubmissionData =$SumbissionQA;
    $Surveys[]=$submissionObj;
}

$returningJSON->Surveys = $Surveys;

return drupal_json_output($returningJSON);
}

```

---
Tags: 7, webforms
---


# Question
Title: Drush command 'omega-wizard' could not be found
I want to create a sub-theme with Omega using drush but I get a couple of errors. I've been trying to solve these problems for a bit now and I need some help. I'm using OS X and XAMPP as my local web server.

When I change directories into my site:

`/Applications/XAMPP/htdocs/joshvocal/sites/all/themes`

and run `drush omega-wizard` I get these errors:

`The drush command 'omega-wizard' could not be found. Run drush cache-clear drush to clear the commandfile cache if you[error]have installed new extensions.
Drush was not able to start (bootstrap) the Drupal database.
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See
drush topic docs-aliases for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.`

I think the problem has something with drush not being able to connect to my database.

I've tried:

* Changing my settings.php file from `host: localhost` to `host: 127.0.0.1`
* Creating a symbolic link with `/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock /var/mysql.sock`

When I run my `drush status` this is what is looks like:

I think this is what it should somewhat look like:

I want to know how to fix these errors and be able to run `drush omega-wizard` to create a sub-theme on omega.

Thank you for your time,

Josh

# Answer
> 3 votes
Add `-d` option so that command looks `drush -d omega-wizard`. You will see debugging information showing what causes problems.

# Answer
> 0 votes
I had this issue, turns out I didn't have the MySQL bin directory in my system path.

This question appears quite high up Google, so for anyone else reading this having the same issue...

Go to `Control Panel » System » Advanced » Environment Variables`, double click on `Path` under `System variables`, click `New` and add the path to your MySQL bin directory.

In my case this was `H:\wamp64\bin\mysql\mysql5.7.11\bin`, but it will depend on the location of your WAMP installation.

---
Tags: drush, theming
---


# Question
Title: How to properly check in entity form validation if field is empty?
I have a content type "A" (Node entity type). In it's node form (new/edit) I need to check if some fields are empty or not (which are not required in general). My first intention was to use FormState "getValue", "isValueEmpty", "hasValue" functions, but I can't figure out how to easily solve this problem:

* Text fields has value: `array("value"=> "")` if they are empty, and it's not considered empty by the functions above (so I can't use them)
* I could check by myself for `isset($field['value'])`, but there are also file fields and entity reference fields which has a whole different "value" structure.

So what would be a clean way to achieve this?

# Answer
I think I found what I was looking for, ContentEntityForm does it like this:

```
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $this->buildEntity($form, $form_state);
$violations = $entity->validate();

```

All I have to do is building the entity, after that I have to just check the right field, which has already the ability to tell per fields if they are empty or not. (since each field is knowing it's type and also how to check if there is a value or not)
> 0 votes

---
Tags: 8, entities, forms
---


# Question
Title: How do i change the visibility of an existing block programmatically?
How do i change the visibility of an existing block programmatically?

I created the block using yml, here's the configuration:

```
uuid: 67105709-2648-445e-9ddd-8b830a854d8d
langcode: en
status: true
dependencies:
  module:
    - pixelpin_openid_connect
    - system
  theme:
    - bartik
id: openidconnectlogin
theme: bartik
region: content
weight: 0
provider: null
plugin: pixelpin_openid_connect_login
settings:
  id: pixelpin_openid_connect_login
  label: 'PixelPin OpenID Connect Login'
  provider: pixelpin_openid_connect
  label_display: visible
visibility:
  request_path:
    id: request_path
    pages: /user/login
    negate: false
    context_mapping: {  }

```

The block visibility will change depending on whether a checkbox is checked so i cannot modify the existing block using yml (if that's even possible) unless you can call it in code.

# Answer
You can load the block and modify the visibility settings:

```
$block = \Drupal\block\Entity\Block::load('openidconnectlogin');
$visibility = $block->getVisibility();
if (isset($visibility['request_path']['pages'])) {
  $visibility['request_path']['pages'] = '/new/path';
  $block->setVisibilityConfig('request_path', $visibility['request_path']);
  $block->save();
}

```
> 9 votes

# Answer
You can use the hook\_block\_view\_alter or hook\_block\_access.

```
function your_module_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account) {
  // Update your condition according to your requirement.
  if ($operation == 'view' && $block->getPluginId() == 'system_powered_by_block' && $xyz_config == 'xyz') {
    return AccessResult::forbidden()->addCacheableDependency($xyz_config);
  }

  return AccessResult::neutral()->addCacheableDependency($xyz_config);
}

```

You implement `addCacheableDependency` method to avoid caching. Suppose you want to forbid the access if `$xyz_config` is set to "xyz" value. After some time `$xyz_config` variable is changed so access should be allowed in that case. But it won't happen until you add `addCacheableDependency` method and pass the variable.

You can read more about Cache API in D8: https://www.drupal.org/docs/8/api/cache-api/cache-api
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: Webform multiple files with descriptions
D7: I am looking at building a competition section on a site I'm working on. Originally I started looking at Webforms to do this, but there are requirements I have that Webform doesn't solve (as far as I can tell).

What I need is to allow entrants to submit images. There must be at least 5 and no more than 12. Each image submitted should have a title, a caption and a date (dd/mm/yyyy). This is a big problem because I can only find two modules that allow for multiple file uploads in Webforms, neither allow specifying a minimum number of files and neither allow text fields and a date to be entered with each image.

Does anyone know a way I can solve this in Webform or do I need to look at building something custom? It's a pain that I can meet 80% of the requirements out of the box (kinda).

# Answer
You can allow node submission for users. Create a content type, go to permissions tab and allow content type to be submitted by particular user role. Under content type go to manage fields and create an image field by allowing multiple images to be uploaded. Now use Form block module to display node form on front end for users. This will be easy for you as well as you can get the submitted content easily in views to display them as per your requirement.
> 0 votes

---
Tags: forms, webforms, files
---


title: CKEditor - Alignment

text:
# Question
Title: CKEditor - Alignment
I' trying to set up CKEditor options as in the following screenshoot:

Everythings works fine except the alignment buttons:

I saw that an issue (2649546) about this has been created but it seems that is still pending.

Any suggestions about how I could solve this?

# Answer
> 0 votes
You need to download the Full Package of the CKEditor library.

You can download it at the official website.

---
Tags: 8, wysiwyg
---


# Question
Title: How to access library version details in JavaScript
I have a theme with library file looks like this:

```
global:
  version: 1.0.0
  js:
    js/global.js: {}

```

global.js has some functionality specific to version 1.0.0.

Is there anyway to get this version number? Is it available in JS?

# Answer
Library definitions can be accessed via the `library.discovery` service (LibraryDiscovery).

```
$libraryDiscovery = \Drupal::get('library.discovery');
// Where mytheme is the name of your theme.
$definition = $libraryDiscovery->getLibraryByName('mytheme/global');

```

Then you would need to pull out `$definition['version']` into a JavaScript settings or do something with it in your theme.
> 2 votes

---
Tags: 8, javascript
---


# Question
Title: How can I create a view showing count of users by birth year?
I want to create a table showing a count of number of users by birth year. Right now I've done the following:

1. Create a view of profiles rendered as a table (no grouping fields, though I've tried grouping to no avail)
2. Create two fields:
    1. Birth date, rendered as four digit year, aggregated as "Group results together"
    2. Profile ID, aggregated as COUNT DISTINCT
3. Sorted these by descending birth date

The problem is that this does not group the dates by year - it still groups the dates by day. Right now, rather than one line in my table for each year, I'm getting something like this:

```
2017 | 1
2017 | 2
2017 | 1
2017 | 1
2017 | 3
2017 | 1

```

...the left column being the four digit year and the right column being the number of users born on a particular day in 2017. The above should have rendered as:

```
2017 | 9

```

How can I get my table to show a count of users by birth year?

# Answer
> 0 votes
You could try out the following module which enables aggregation on your chosen granularity: https://www.drupal.org/project/views\_date\_format\_sql

After enabling, a checkbox will appear in the Date field setting of the view, called 'Use SQL to format date'.

---
Tags: 7, views
---


# Question
Title: How to solve this PHP fatal error after installing module?
> PHP Fatal error: Cannot redeclare \_field\_info\_field\_cache() (previously declared in C:\xxxx\wwwroot\xxxxx\modules\field\field.info.inc:16) in C:\xxxxx\wwwroot\xxxxxxx\sites\all\modules\easy\_booking-7.x-2.4\modules\field\field.info.inc on line 32

So I got this error notification after turning on Error debug in my IIS Server because previously it only showed a 500 page error.

It seems it's calling two times the same function? Anyone can help?

Edit: I guess it's better I just delete the module but then I get a `require_once` error:

> PHP Fatal error: require\_once(): Failed opening required '

# Answer
Okay, I found the solution.

1. I run `update.php` as in typing `www.yourwebsite.com/update.php` in the browser
2. I upgraded my php version on my IIS Server from `PHP 5.3` to `PHP 5.5` (For Windows users, install `PHP upgrade manager` for IIS and follow instructions)

While doing this it still gave me a fatal PHP error about my elfinder module but I deleted a function in the given line code and after runing `update.php`, my admin page worked again.
> 1 votes

# Answer
Put the module back. Check its code. Delete the problematic function named in the corresponding error message from it. Go to admin page. Uninstall the module.

Try to reinstall the module in a proper location. Don't name the folder `easy_booking-7.x-2.4`. Simply name it `easy_booking`. If the error still occurs, file a bug at https://www.drupal.org/project/issues/easy\_booking?status=All&categories=All
> 2 votes

---
Tags: 7
---


# Question
Title: What stops the import of the rule contained in my custom module?
I have exported rules from the existing rules and I wanted to import rule using custom module. But when I enable this module. Rules weren't imported in rules list.

I created 3 files:

1) `my_module.INFO` file:

```
name = My module example
description = My module for import rules
core = 7.x
package = My module

```

2) `my_module.MODULE` file (blank file):

```
<?php

```

3) `my_module.rules_defaults.INC` file:

```
<?php
     function rules_example_default_rules_configuration() {
      $configs = array();
      $rule = '{ "rules_final_save_pdfs" : {
        "LABEL" : "final save pdfs",
        "PLUGIN" : "reaction rule",
        "ACTIVE" : false,
        "OWNER" : "rules",
        "REQUIRES" : [ "rules", "views_pdf", "entityform" ],
        "ON" : { "entityform_insert" : [] },
        "IF" : [
          { "entity_has_field" : { "entity" : [ "entityform" ], "field" : "field_test_pdf_form" } }
        ],
        "DO" : [
          { "views_pdf_rules_action_save" : {
              "views_pdf" : "test_new_view:pdf_1",
              "path" : "\/workout\/sites\/default\/files\/test_pdfs\/[entityform:field-date]"
            }
          }
        ]
      }
    }';
      $configs['rules_final_save_pdfs'] = rules_import($rule);
      return $configs;
    }
?>

```

Please let me know if there any changes to do.

# Answer
Assuming this is for D7, try this variation of the your code in your item "3)":

```
<?php
     function my_module_default_rules_configuration() {
      $configs = array();
      $rule = '{ "rules_final_save_pdfs" : {
        "LABEL" : "final save pdfs",
        "PLUGIN" : "reaction rule",
        "ACTIVE" : false,
        "OWNER" : "rules",
        "REQUIRES" : [ "rules", "views_pdf", "entityform" ],
        "ON" : { "entityform_insert" : [] },
        "IF" : [
          { "entity_has_field" : { "entity" : [ "entityform" ], "field" : "field_test_pdf_form" } }
        ],
        "DO" : [
          { "views_pdf_rules_action_save" : {
              "views_pdf" : "test_new_view:pdf_1",
              "path" : "\/workout\/sites\/default\/files\/test_pdfs\/[entityform:field-date]"
            }
          }
        ]
      }
    }';
      $configs['rules_final_save_pdfs'] = entity_import('rules_config', $rule);
      return $configs;
    }
?>

```

Note the changes in the line with ***function ...*** (near the top) and the line with ***entity\_import*** (near the end).

**Be aware**: if I try to import your rule (= the string contained in `$rule`) in a site of mine (where I don't have `views_pdf` module enabled), and using the Rules UI, I get an import error like so:

> Import failed.
>
> Missing the required module views\_pdf.

That makes sense of course (since I don't have that module). So check that that is not the case why your rule isn't imported (same for `entityform`). A possible technique to prevent this issue, is to declare those 2 modules as a dependency in your `my_module.info` file.

PS: have a look at the code of the Answers Userpoints module for an example where this technique is used also.
> 0 votes

---
Tags: rules
---


# Question
Title: How do I stop automatic double break tags in ckeditor?
After updating the ckeditor module i find that saving existing content results in adding another break tag following existing break tags. When i create new content and press enter and save the final result has an additional break tags.

This is what i should be seeing according to the source button on the editor:

```
<p>The quick brown fox jumps over the lazy dog. The five boxing wizards jump quickly.<br>
Pack my box with five dozen liquor jugs. Jackdaws love my big sphinx of quartz.<br>
<br>
This is a second paragraphs made with two line breaks. Lets see if the editor decides to use two break tags or 4 break tags. These should also be enclosed with a paragraph tag instead of separated by two break tags.<br>
<br>
<br>
This third paragraph is now being separated by three break tags. Lets see if the editor decides to make this as size break tags instead of just three break tags. This Should be wrapped around a paragraph but also have a break tag above it.</p>

```

However what i see when i save the page ends up being:

```
<p>The quick brown fox jumps over the lazy dog. The five boxing wizards jump quickly.<br><br>
Pack my box with five dozen liquor jugs. Jackdaws love my big sphinx of quartz.<br><br><br><br>
This is a second paragraphs made with two line breaks. Lets see if the editor decides to use two break tags or 4 break tags. These should also be enclosed with a paragraph tag instead of separated by two break tags.<br><br><br><br><br><br>
This third paragraph is now being separated by three break tags. Lets see if the editor decides to make this as size break tags instead of just three break tags. This Should be wrapped around a paragraph but also have a break tag above it.</p>

```

# Answer
The answer in this post helped me out: CKeditor adding an extra \<br/\> tag when a \<br/\> tag is encountered

basically go into administration \> configuration \> content authoring \> text formats.

then select the text format that's causing problems and unselect "convert line breaks into html" and save configuration.

Then clear all caches on Drupal and browser. The content should go back to normal just by visiting the page while you are signed in otherwise saving over it should fix the problem.
> 1 votes

---
Tags: 7, wysiwyg, input-formats
---


# Question
Title: Why in node.tpl.php $content is different from $node?
I'm creating a custom template file for a specific content type. I'm printing most of values with

```
<?php print render($content['field_blabla']); ?>

```

As some of them didn't show up and they are not empty I tried

```
dpm($content);

```

Indeed they aren't in the array printed, but if try

```
$node = node_load($node->nid, NULL, TRUE);
dpm($node->field_blabla['und'][0]['value']);

```

I can see the value!

What's the problem? Why are they missing?

Thanks

# Answer
Sounds like their field display settings are hidden, which is one reason it would not be in the `$content` renderable array.

Check the display settings for the applicable view mode for this content type on the "Manage Display" tab.
> 4 votes

---
Tags: 7, theming, entities
---


# Question
Title: Output different menus based on site section (URL)
I'm working on a Drupal 8 site that's divided up into sections that correspond to projects. So URL aliases will be `/project-a/some-content`, `/project-b/some-content`, etc.

I'd like to support creating menus—for each section—in the admin, and to render those in the primary navigation region based on which section you're in.

My assumption is that somewhere I need a `switch` statement that uses URL segment 1 for `case` and specifies a configured menu to load for each case, or a default.

Is this the best approach? Where would I do that, if so?

# Answer
> 1 votes
You should be able to use standard path based visibility conditions.

Just put both menu blocks into the same region, and configure each to only be shown on paths like /project-a/\* and the other on /project-b/\* and so on.

---
Tags: 8, navigation
---


title: Authenticate using OAuth

text:
# Question
Title: Authenticate using OAuth
I'm working on wrapping my mind around decoupled Drupal 8 while using an AngularJS app for the frontend. What I am trying to do is to allow a user to authenticate with my D8 site using their username and password, and then provide them with an OAuth token which will allow them to continue to make requests.

What is the correct flow in order to allow this type of authentication? Is this the correct way to go about things? From what I understand basic auth isn't nearly as secure as OAuth, so I'd rather stay away from that.

I've been messing around with the simple\_oath module and jDrupal, but they don't seem like they are quite "there" yet. Any suggestions?

Part of the problem I'm having, is figuring out where the OAuth modules end, and where my module needs to begin.

**\[Edit\]** I've heard conflicting things about cookie/session authentication. My end goal is to turn this into an app. Does cookie/session storage work with a mobile environment?

Thanks!

# Answer
I think you're desire to use Oauth is justified. However, if you have no other options, you can use Cookie authentication. I have used it before and have heard of people using it as well. Here are some things to keep in mind and you'd be good to go with Cookie auth with your mobile application:

* You will have to increase the session timeout time to a long period, say, 1 year or more. This means that after the period, the user would have to be asked to login again. Alternatively, you can refresh the Cookie with each request. You will need to:
    1. Change session settings in PHP settings
    2. Change session settings in Drupal settings
* You will have to authenticate the user and then have a mechanism to persist the user's Session ID using a `Set-Cookie` header.
* You will need to have a mechanism to handle sign-in failure when the session cookie has expired. When the session expires, you can send the user to the sign-in page again (maybe with the username field pre-populated) and ask then to sign-in again.
* Since leaving a session long open poses to be a security threat, you might consider using other mechanisms like CSRF tokens.

**Note:** If you are in the mood for experimentation, you can also look into JWT authentication. Also, if you expect to have a huge user-base, you might consider a service like Firebase for storage.

Hope it helps. Happy coding!
> 6 votes

---
Tags: 8, cookies, authentication-authorization
---


# Question
Title: Entity form with pre-populated entity reference from URL
I have two entities which are in a parent/child relationship. Now I want to add a operations link in the parent's list view so that I can show the child's entity form with the reference to the parent pre-populated.

Ideally, the URL would look something like /admin/myparent/123/mychild/add, where 123 is the ID of the parent entity to which the new child should have a reference. I have the link in place in the operations menu, but I can't figure out how to have my ChildEntityForm load in the parent entity based on the URL parameter. How do I do this in Drupal 8?

I found a couple of questions regarding this here on SO, but they were all about Drupal 7. In addition, the documentation (Using parameters in routes) regarding upcasting url parameters states this:

> Note that this method of providing the entity data to a form is not used for entity forms, such as forms to add/edit/delete entity data.

So is there a solution to this, preferably one that would not require installing a third-party module?

# Answer
> 1 votes
The prepopulate module is now able to handle this in the usual way like

http://www.example.com/node/add/child?edit\[field\_parent\_ref\]=17

# Answer
> 0 votes
This is how i work for done that :

my ajax form call on my parent entity form :

```
 $form['bouton'] = array(

          '#type' => 'link',

          '#title' => $this->t('Ajouter un produit'),

          '#url' => Url::fromUri($base_url.'/admin/boutique/commandesLignes/add',array('query'=>array('idCommande'=>$entity->get('id')->value))),

          '#attributes' => [

              'class' => ['use-ajax'],

              'data-dialog-type' => 'modal',

              'data-dialog-options' => Json::encode([

                  'width' => 700,

              ]),

          ],

      );

```

Then in my commandesLignesAdd form (modal open with the link into parent entity), i get the parameter like this :

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    /* @var $entity \Drupal\boutique\Entity\CommandesLignesEntity */
    $form = parent::buildForm($form, $form_state);
      $entity = $this->entity;

      $idCommande=\Drupal::request()->query->get('idCommande');

      $form_state->setTemporary(array('idCommandes'=>$idCommande));

    return $form;
  }

```

I set a temporary value into my $form\_state and i use it into the submit call :

```
public function submitForm(array &$form, FormStateInterface $form_state)
{
    $commandes_id=(int)$form_state->getTemporaryValue('idCommandes');
    $form_state->setValue(array('commandes_id'),array('value'=>$commandes_id));

    parent::submitForm($form, $form_state);
}

```

My field reference name is commandes\_id, and you need this field on your modal form, i use css for hidden it.

---
Tags: forms, 8, entities
---


title: Generate https image URL

text:
# Question
Title: Generate https image URL
In order to generate full path of images(URL) on views for rest endpoint on my decoupled Drupal project I'm using Image Url Formatter module, everything works correctly until I decide to put the website on HTTPS, In console I see
`Loading mixed (insecure) display content
“http://core.domain.com/sites/default/files/styles/874x492/public/gallery/2017-01/1-907331.JPG?itok=MKfQSWFh” on a secure page`

it's because this formatter return *HTTP* Instead *HTTPS* for image URLs.

**In the situation like this that the websites should work on HTTPS and HTTP both, I advise my team using `//domain.com` instead of `http://domain.com` or `https://domain.com` in all endpoint URLS**

Now I looking for a solution to return all images URL from `http://....` to `//...` . if I had few views I could benefit REWRITE feature of view but I have a lot of views rest export endpoint.

What is your solution for this requirement?

# Answer
Doing a quick test, works fine with HTTPS

Views REST XML

Views REST Json

All of the above is using FULL URL

Perhaps someone set it to Absolute file path, which will give you `/path/image.jpg` (with out the $base\_url). Then in some template file they did `http://example.com{{ field.image.content }}`

**update**

using `template_preprocess_image_formatter()` is another solution to change the template formatter of the image.
> 1 votes

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


# Question
Title: What may cause my fatal error Call to undefined function _menu_target_edit_form_extra_elements_submit()?
I'm running Drupal 7.53 and all my modules are up to date. I suddenly started having this error on my Drupal site.

> Fatal error: Call to undefined function \_menu\_target\_edit\_form\_extra\_elements\_submit() in /home/portal/public\_html/includes/form.inc on line 1520

This error happens when I try to add a new content type or edit a content type that includes a media or image field. It doesn't matter if the field is empty or contains content. However, if I remove the field from the content type, it saves just fine.

Since my site is very event driven, I am unable to edit events until the problem is fixed. I've run registry update, flushed caches, run cron... you name it. I did not update any modules since it was working on Tuesday to when it stopped working this morning. I did update the media module on Tuesday but I am pretty sure I did this before I added a few events.

Any ideas?

# Answer
Hey I just had this issue this morning too. In my case it was being caused by the module **menu\_target** I disabled it and the issue disappeared.
> 2 votes

---
Tags: 7, media
---


# Question
Title: how to value from one view to another view filter in drupal
I want to pass the value from one view to another view's filter I have view 'filter' which is having the select box with taxonomy list as option 'category\_taxonomy' having fruits,vegetables. I want to pass the taxonomy value to next view in on change event to filter the value in view 2.My both 'view1' and 'view2' are in same tpl.If I select the value from view1 I wat to send the argument to the second view and and filter the result and then reload only the second view(view2).

```
$vocabulary = taxonomy_vocabulary_machine_name_load('service_line');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));
// print_r($terms);
echo '<select class="filter"><option value="">select</option>';
foreach($terms as $data){
  echo '<option value='.$data -> name.'>'. $data -> name.'</option>';
 }
echo '</select>';

```

# Answer
One way to do it is to create a jumpmenu in your view's template and add it to the page that way instead of trying to do it with filters.

So in your view's Advanced tab, click on "theming" option, and a dialog box will open with your view's template name. Copy the views.tpl from the views module to your theme and name it that template name. Inside this template you can now find the place you want to output this jumpmenu and add the tax\_terms code you have above. Only instead of outputting the options as a form field, convert them to links using JS here's one example. Or you can also create the jumpmenu as ctools like here.
> 0 votes

---
Tags: 7, views
---


title: Add image styles with images

text:
# Question
Title: Add image styles with images
I am trying to print an image using an image style that I've created in my drupal 8 theme.

I'm implementing a field template for the field collection. I have an image in my field collection, So i need a way to get the URL for a different image style of the same image.

Any effort will be appreciated.

# Answer
**mythemename.theme**

```
use Drupal\image\Entity\ImageStyle;
use Drupal\file\Entity\File;

function mythemename_preprocess_page(&$variables) {
// change _page to _node or _html depending on the template you are targetting.

  if (isset($variables['node'])) {
    $node = $variables['node'];
    // now you can use $node->field_something

    // Since I have yet to use field collection in D8, I'll let you figure this part out.
    // So all you gotta do is get the fid from your image field.

    // Once you get the FID
    $file = File::load($fid);
    $uri = $file->getFileUri();
    $url_large = ImageStyle::load('large')->buildUrl($uri);
    $url_medium = ImageStyle::load('medium')->buildUrl($uri);
    $variables['large_image_style_url'] = url_large;
    $variables['medium_image_style_url'] = url_medium;
  }
}

```

Then in twig you can do `{{ large_image_style_url }}` and `{{ medium_image_style_url }}`

I had to do it like this, since I needed to print the image in page.html.twig. If you need yours in node.html.twig you could try the answers to How to use an image style in a Drupal 8 twig template?
> 2 votes

# Answer
This post describes how to render images with image styles in Drupal 8 programmatically: https://stackoverflow.com/questions/24754661/drupal-8-images-with-image-style

If you want to do it in a twig file here is another example: https://stackoverflow.com/questions/33510051/how-to-use-an-image-style-in-a-drupal-8-twig-template
> 1 votes

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


# Question
Title: How can I use Twig Tweak to show a token in a Webform template in Drupal 8
I have a Webform form (formerly the YAMLForm module) on which I need to show the title of the form. The template I am using is based on page.html.twig (because of twig debug suggestion) page--webform--stories-submission.html.twig.

According to the tokens listed in both in the form creation area and in admin/help/token, I have several tokens available including \[webform:title\], \[webform:url\], and \[webform:id\] to name a few.

When I use

```
    {{ drupal_token('webform:title') }}

```

on my template, all that prints out on the page is **\[webform:title\]**.

Just to make sure I'm doing it right, I put all of the following smack into the middle of my template:

```
    {{ drupal_token('current-date:long') }}
    {{ drupal_token('site:name') }}
    {{ drupal_token('webform:title') }}
    {{ drupal_token('webform:id') }}

```

I get this in return:

**Wednesday, January 18, 2017 - 09:00 ECLKC \[webform:title\] \[webform:id\]**

The first two prove that Twig Tweak is a wonderful thing, and the second two prove that I'm still not doing it right.

Can anyone recommend a next step for me?

If I can't get Tweak working, I guess I might need to preprocess myself a variable? Kint says that my title is right there as a page variable:

```
'page' => array(25)
~
  '#title' => string(29) "Submit your Head Start Story!"

```

In that case, I think I would need to follow this advice: How do I add a variable for a Twig template in my preprocess function?

To sum up:

1. Can I get Twig Tweak to show my title for me?
2. If not, should I use that advice about adding a variable to my template preprocess?

# Answer
> 2 votes
Currently, it looks like the Twig Tweak module's drupal\_token Twig function does not support passing in the $data argument, which would contain the webform entity.

You might want to create an issue in the Twig Tweak module's issue queue.

# Answer
> 1 votes
Can I get Twig Tweak to show my title for me?

Tokens don't work that way. The only tokens available in all places are the global ones, like the examples you have in your question. The specific tokens work only in their own environment and it would be impossible for twig tweak to provide all of these environments.

If not, should I use that advice about adding a variable to my template preprocess?

In D7 the title was a variable in the page template. This has changed in D8. See Page title is now a block

---
Tags: theming, 8, webforms, tokens
---


# Question
Title: How do I change the node view mode before rendering?
I have a content type with a custom view mode. How do I make sure node always get rendered with my custom view mode?

What would be the right way to programmatically change the node view mode before rendering?

# Answer
If you want to make sure that a content type is *always* rendered with a custom view mode, use the following hook in a module. (I assume the module machine name is mymodule.)

*mymodule.module*

```
/**
 * Implements hook_entity_view_mode_alter().
 */
function mymodule_entity_view_mode_alter(&$view_mode, $entity, $context) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'my_content_type') {
    $view_mode = 'my_custom_view_mode';
  }
}

```
> 4 votes

---
Tags: 8, nodes
---


# Question
Title: Content type adding page is not displaying properly
I have a content type and added fields to that . But when try to add a content (the page url is **`base_url/node/add/content_type`**) it appear as an **administral adding option** (Means its not showing the **`main navigation`** and **`side navigation`** and **`header images`**) . Why is it like that ? One thing i noticed that its breadcrumb appear as **`Home >> Add content`**, but in real it should be ( that appear in my staging server as **`Home >> Node >> Add content`** and **`appearing the side navigation and main navigation menus`** ) . I installed **`node`** **`module`** too . How could achieve that ?

# Answer
For admin users you can change this at the bottom of theme settings:

**/admin/appearance**

☑ Use the administration theme when editing or creating content

On the staging server you probably testing this with a non admin user account, so you won't see a difference there.
> 1 votes

---
Tags: 8, nodes
---


title: cant reach content in block--views

text:
# Question
Title: cant reach content in block--views
I am new to Drupal8. How can i get the content ? I call a view in page.html.twig like:

> {{ page.content.views\_block\__serviceboxen\_block\_1 }}

and created a template with name:

> block--views-block--serviceboxen-block-1.html.twig

How can i access to the content from my view in this template ? I have no idea when i use

```
{% for row in rows %}

```

and

```
{% for item in items %}

```

thanks a lot.

# Answer
> 0 votes
solution: you can access the fields with 'content'

e.g. content.body or content.your\_field\_name.value

in a iteration it looks like:

```
<ul>
  {% for item in content['#view'].result %}
      {% set topic = item._entity %} {# just for shorter writing #}

       <li>{{ topic.title.value }}</li> {# or topic.yourFieldName.value #}

  {% endfor %}
</ul>

```

Hope it'll help

---
Tags: views, theming
---


title: Data not being saved on user_save

text:
# Question
Title: Data not being saved on user_save
I having a problem saving user data to the database. Everything is being saved apart from 'street\_address', 'town\_city', 'region' 'postal\_code' and 'country'.

full module\_create\_user:

```
function openid_connect_create_user($sub, $userinfo, $client_name) {

  $address = $userinfo['address'];
  $decodeAddress = json_decode($address);

  $firstName = $userinfo['given_name'];
  $lastName = $userinfo['family_name'];

  $streetAddress2 = $decodeAddress->{"street_address"};
  $townCity2 = $decodeAddress->{"locality"};
  $region2 = $decodeAddress->{"region"};
  $postalCode2 = $decodeAddress->{"postal_code"};
  $country2 = $decodeAddress->{"country"};

  $streetAddress = (string)$streetAddress2;
  $townCity = (string)$townCity2;
  $region = (string)$region2;
  $postalCode = (string)$postalCode2;
  $country = (string)$country2;

  $edit = array(
    'name' => $firstName.$lastName.$sub, //works
    'pass' => user_password(), //works
    'mail' => $userinfo['email'], //works
    'init' => $userinfo['email'], //works
    'family_name' => $userinfo['family_name'], //works
    'given_name' => $userinfo['given_name'], //works
    'nickname' => $userinfo['nickname'], //works
    'gender' => $userinfo['gender'], //works
    'birthdate' => $userinfo['birthdate'], //works
    'phone_number' => $userinfo['phone_number'], //works
    'street_address' => $streetAddress, //doesn't work
    'town_city' => $townCity, //doesn't work
    'region' => $region, //doesn't work
    'postal_code' => $postalCode, //doesn't work
    'country' => $country, //doesn't work
    'status' => 1, //works
    'openid_connect_client' => $client_name, //works
    'openid_connect_sub' => $sub, //works
  );

  return user_save(NULL, $edit);
}

```

different $edit i've tried:

```
$edit = array(
    'name' => $firstName.$lastName.$sub, //works
    'pass' => user_password(), //works
    'mail' => $userinfo['email'], //works
    'init' => $userinfo['email'], //works
    'family_name' => $userinfo['family_name'], //works
    'given_name' => $userinfo['given_name'], //works
    'nickname' => $userinfo['nickname'], //works
    'gender' => $userinfo['gender'], //works
    'birthdate' => $userinfo['birthdate'], //works
    'phone_number' => $userinfo['phone_number'], //works
    'field_street_address_pixelpin' => $streetAddress, //doesn't work
    'field_town_city_pixelpin' => $townCity, //doesn't work
    'field_region_pixelpin' => $region, //doesn't work
    'field_postal_code_pixelpin' => $postalCode, //doesn't work
    'field_country_pixelpin' => $country, //doesn't work
    'status' => 1, //works
    'openid_connect_client' => $client_name, //works
    'openid_connect_sub' => $sub, //works
  );

```

examples of the fields which are being programmability created:

Family name (works):

```
if (!field_info_field('field_family_name_pixelpin')) {
    $field = array(
        'field_name' => 'field_family_name_pixelpin',
        'type' => 'text',
    );
    field_create_field($field);

    $instance = array(
        'field_name' => 'field_family_name_pixelpin',
        'entity_type' => 'user',
        'label' => 'Family Name',
        'bundle' => 'user',
        // If you don't set the "required" property then the field wont be required by default.
        'required' => FALSE,
        'settings' => array(
           // Here you inform either or not you want this field showing up on the registration form.
            'user_register_form' => 1,
        ),
        'widget' => array(
            'type' => 'textfield',
        ),
        'display' => array(
          'default' => array('label' => 'above'),
      ),
    );
    field_create_instance($instance);
  }

```

postal code (doesn't work):

```
if(!field_info_field('field_postal_code_pixelpin')) {
    $field = array(
        'field_name' => 'field_postal_code_pixelpin',
        'type' => 'text',
    );
    field_create_field($field);
    $instance = array(
        'field_name' => 'field_postal_code_pixelpin',
        'entity_type' => 'user',
        'label' => 'Postal Code',
        'bundle' => 'user',
        // If you don't set the "required" property then the field wont be required by default.
        'required' => FALSE,
        'settings' => array(
           // Here you inform either or not you want this field showing up on the registration form.
            'user_register_form' => 1,
        ),
        'widget' => array(
            'type' => 'textfield',
        ),
        'display' => array(
          'default' => array('label' => 'above'),
      ),
    );
    field_create_instance($instance);
  }

```

# Answer
> 1 votes
In general, for custom user fields, `user_save` requires the field values to be provided as an array. An example would be the following:

```
 $edit['field_yourfield'] = array(
   LANGUAGE_NONE => array(
     0 => array('value' => $yourValue),
   ),
 );

```

---
Tags: 7, entities, database
---


# Question
Title: Contextual filter that lists users who share a taxonomy term with current user?
I have a view that lists all user profiles. At registration, every user selects, from a 'sector' taxonomy, the sector they themselves do business in. They also select from the same 'sector' taxonomy to record what sectors they want to do business with. So their user profiles may look like this:

```
uid: 1
name: fred
sector in: arts
sectors to do business with: tech

uid: 2
name: alex
sector in: tech
sectors to do business with: design

```

I want a view to list all the users that do business in the sectors that the current user wants to do business in.

So, using the above profiles, if Fred was looking at the view, Alex's profile would be displayed because the filter would be:

```
sector == tech

```

Obviously, the filter needs to be dynamic. It needs to grab the 'sectors to do business with' field from Fred's user profile. I think I need a contextual filter, but how do I configure it?

Thanks

# Answer
> 0 votes
Provided you have two fields on your user profile called **field\_working\_in** and **field\_want\_to\_work\_with** execute the following steps:

* Add a **Users** view at admin/structure/views/add and set Display Format as **Table**
* Add two fields **User: Name** and **User: Working in**
* Add relationship with **User: Working in**
* Add relationship with **Taxonomy term: User using Want to work with**
* Add a contextual filter: **User: uid** with *Provide Default Value* and *Type:* **User ID form logged in User** and set a relationship with **field\_want\_to\_work\_with** (see screenshot)
* Under **FILTER CRITERIA** Add the following filter to exclude the current user from the results: `User: Current (No)`

Export of view:

```
$view = new view();
$view->name = 'user_sections';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'User sections';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'User sections';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: User: Working in (field_working_in) */
$handler->display->display_options['relationships']['field_working_in_tid']['id'] = 'field_working_in_tid';
$handler->display->display_options['relationships']['field_working_in_tid']['table'] = 'field_data_field_working_in';
$handler->display->display_options['relationships']['field_working_in_tid']['field'] = 'field_working_in_tid';
/* Relationship: Taxonomy term: User using Want to work with */
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['id'] = 'reverse_field_want_to_work_with_user';
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['field'] = 'reverse_field_want_to_work_with_user';
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['relationship'] = 'field_working_in_tid';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: User: Working in */
$handler->display->display_options['fields']['field_working_in']['id'] = 'field_working_in';
$handler->display->display_options['fields']['field_working_in']['table'] = 'field_data_field_working_in';
$handler->display->display_options['fields']['field_working_in']['field'] = 'field_working_in';
$handler->display->display_options['fields']['field_working_in']['label'] = '';
$handler->display->display_options['fields']['field_working_in']['element_type'] = '0';
$handler->display->display_options['fields']['field_working_in']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_working_in']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['field_working_in']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_working_in']['delta_offset'] = '0';
$handler->display->display_options['fields']['field_working_in']['field_api_classes'] = TRUE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'reverse_field_want_to_work_with_user';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: User: Current */
$handler->display->display_options['filters']['uid_current']['id'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['table'] = 'users';
$handler->display->display_options['filters']['uid_current']['field'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['value'] = '0';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user-sections';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'User sections';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['name'] = 'main-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$translatables['user_sections'] = array(
  t('Master'),
  t('User sections'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('term from field_working_in'),
  t('field_want_to_work_with'),
  t('Name'),
  t('All'),
  t('Page'),
);

```

---
Tags: views, 8
---


# Question
Title: Where are the RESTful module permissions other than `Administer REST resource configuration`?
According to the tutorial An Introduction to RESTful Web Services in Drupal 8, the `admin/people/permissions` path should contain the following permissions:

But now that I installed the latest version of Drupal, the big surprise is on my website there are no other RESTful module permissions than `Administer REST resource configuration`, no permissions to grant DELETE, GET, PATCH or POST to each role.

I have Enabled all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization) + REST UI module.

Are those permissions removed from Drupal 8.2.5?

# Answer
> 7 votes
This was introduced since 8.2.0

Accessing entities via REST no longer requires additional REST-specific permissions

> **This was actually only meant to be a temporary measure**, because we already have an Entity Access API that governs access/operations to/on those entities. And in fact, Entity Access is respected when accessing entities via REST. So, there was no more reason for this to exist in Drupal 8.0.x and Drupal 8.1.x, but it was simply forgotten to be removed before Drupal 8.0.0's release. The fact that you needed to grant both those permissions as well as Entity Access needing to grant you access, was a source of confusion and frustration with Drupal 8's REST API, which has now been fixed.
>
> **So, as of Drupal 8.2.0, new installations no longer need those permissions to access entities via REST**. Existing installations continue to have the old behavior. Existing sites can opt out of that behavior, and opt in to the new behavior, by modifying the rest.settings configuration from
>
> `bc_entity_resource_permissions: true`
>
> to
>
> `bc_entity_resource_permissions: false`
>
> (The latter is the default on new Drupal 8.2 installations.)

---
Tags: users, 8
---


# Question
Title: How do I redirect anonymous users before saving a node?
I need to redirect anonymous user before saving a node in Drupal 7.

For this I created a rule which redirects anonymous users to perform a login/register, but it's creating a node. How can I prevent the node creation before registering?

# Answer
Here are some solutions you can follow :

1. As Kiamlaluno mentioned the first solution and the most regular one is to force user to register before being able to see node creation form . you can use Always visible module to make node creation view visible to anonymous users , then in site information part, redirect access denied errors to user login form . in this part modules like logintobaggan or User registration password will become useful for fast registration .After registration user will redirected to node creation form.
2. Create your own form. In this situation a multi-step form is needed which in the first steps node creation form is implemented and in second step user creation. off course it is not an easy solution and needs information about module development in Drupal.
> 1 votes

# Answer
If you want to do this with Rules (as in your question), then it's crucial to use Rules Event "***Drupal is initialiazing***" (otherwise you're too late, which also explains your "*But it's creating a node*").

For an example rule (in rules export format) that uses this technique (and also intercepts using a path like `/node/add`), refer to my answer to "Is there a way to restrict some pages like node/add, /user/login and more?". Just adapt the Rules Conditions in it to fit your needs, i.e:

* Use role id = 0 instead of 1.
* Tune the list of paths to be checked.
* Adapt the message in the Rules Action to fit your needs.

After you do, you should end up with a rule that looks close to this one:

```
{ "rules_limit_access_to_some_urls_" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "0" : "0" } }
        }
      },
      { "data_is" : {
          "data" : [ "site:current-page:path" ],
          "op" : "IN",
          "value" : { "value" : [
              "node\/add",
              "node\/add\/article",
              "node\/add\/book"
            ]
          }
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : {
          "message" : "Access to the path you tried to use is not allowed.\r\n\u003Cbr \/\u003E\r\nIf you think this is an error, please contact us.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

That's really it.
> 1 votes

---
Tags: 7, rules
---


# Question
Title: Bootstrap sub-theme with responsive and off-canvas menu module
I've created a custom Bootstrap sub-theme and am replacing the default Bootstrap menu with the Responsive and Off-Canvas Menu Module but seem to be running into a string of problems.

1. No matter what settings I select, the Mobile "Burger" icon is always showing on the page. I thought it would hide depending on whether the horizontal menu was being shown or not by default. I know I can manually hide this with media queries in my CSS but just not sure if that's the optimal method.
2. I have no idea where the Off-Canvas portion of my menu is coming from? There doesn't seem to be a twig template for it. How is this being generated?
3. Also, when the off-canvas menu is being used, for some reason it's placing carats next to each link as well as the default arrow to show there is a sub-menu. Is this carat coming from the Bootstrap theme template files? Also, when I click to view the sub-menu items in the off-canvas view, none of the sub-menu items are listed at all like they are on the default horizontal view. Why is this? The off-canvas menu doesn't seem to be able to locate any sub links for some reason.

Has anyone used both Bootstrap and this Module together to shed some light on this for me and if there were any complications that you encountered as well, if any?

# Answer
Turns out the Bootstrap menu--main.html.twig file was causing the issue. I just created a theme override for it and made it just the default Drupal menu code and all is working properly now.
> 1 votes

---
Tags: theming, 8
---


title: Cache context drupal don't work

text:
# Question
Title: Cache context drupal don't work
I changed services.yml file (i use dynamic cache):

```
renderer.config:
required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions', 'cookies:Drupal.visitor.Country']

```

And sey the cookie properly with an event:

```
$events[KernelEvents::REQUEST][] = ['checkCountry', 30];
...
 user_cookie_save(['Country' => $country]);

```

I checked and the cookie is saved correctly. But the cache does not work...

# Answer
Anonymous page cache does not respect cache contexts, I'm guessing that is your problem.

To get that working, you need to switch out the PageCache service in a custom module with a ServiceProvider and override the getCacheId() method.
> 2 votes

---
Tags: 8, caching
---


# Question
Title: Book navigation pager is moved under the comments
For some reason, if I change the display order of any field in *Manage display* for the *Article* content type, the *Book navigation pager* is moved to the far bottom under the comments.

>

If I check the template output, it is showing under the comments, which was not the case when everything was right. Even reordering the fields in *Manage display* to where they were before fixes this.

>

Is there any reason for what happens? Is it a bug?

I am using the Bootstrap theme, if this makes any difference.

# Answer
This sounds like a weight issue.

First: Try actually setting the field display weights.

1) Click the "Show row weights" button.

2) This will replace the drag and drop interface with an integer weight field. Set the weights to be lower (more negative) for all of your field items. Hopefully, this will allow them to float above the comments field.

Second: If the above doesn't work, then you might have to manually set the weight of the elements by altering the form.

You will need to place your code in a custom module. And then using hook\_ENTITY\_TYPE\_view() alter the weight of the comments form.

Your code would look something like this:

```
// This part would go at the top of your mymodule.module file.
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

```

This is where you actually set the weight of the comment form.

```
function mymodule_node_view(&$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  // This probably isn't exactly what it will look like for you, but it's close-ish.
  if ($entity->getType() == 'book' && $view_mode == 'full') {
    // Not exact, but this should be pretty close as well.
    $build['comments']['#weight'] = 30;
  }
}

```

Hope this helps!
> 1 votes

---
Tags: theming, 8
---


title: Where are service saved?

text:
# Question
Title: Where are service saved?
Where are services saved? With Drush cr they are read, but I do not understand where they are saved (In non-database I find them)

# Answer
> 4 votes
They are stored in the `{cache_container}` table of the database. The services themselves are declared in `[MODULENAME].services.yml`.

---
Tags: 8
---


title: page.html.twig default regions

text:
# Question
Title: page.html.twig default regions
I'm creating a custom theme with `base theme: stable`. I have copied the `template/layout/page.html.twig` file into my theme. As I am reading the twig file I have noticed that there are some regions that I am not providing but are still being rendered.

Part of the file comment lists the regions available.

```
/*
 * Regions:
 * - page.header: Items for the header region.
 * - page.primary_menu: Items for the primary menu region.
 * - page.secondary_menu: Items for the secondary menu region.
 * - page.highlighted: Items for the highlighted content region.
 * - page.help: Dynamic help text, mostly for admin pages.
 * - page.content: The main content of the current page.
 * - page.sidebar_first: Items for the first sidebar.
 * - page.sidebar_second: Items for the second sidebar.
 * - page.footer: Items for the footer region.
 * - page.breadcrumb: Items for the breadcrumb region.
 */

```

I went looking in the stable.info.yml file and noticed there is not an entry for `regions:` so I am at a loss as how the `page.html.twig` file is able to render regions that are not listed in the `stable.info.yml` file.

**Questions**

* How does this work without being defined in the `stable.info.yml` file.
* Are there any other regions that work like this that are not in the `page.html.twig` file.

# Answer
If no regions are specified in the theme, the core provides defaults itself.

From the docs page: https://www.drupal.org/docs/8/theming-drupal-8/adding-regions-to-a-theme

> **Default Regions**:
>
> `page.header`: Items for the header region.
>
> `page.primary_menu`: Items for the primary menu region.
>
> `page.secondary_menu`: Items for the secondary menu region.
>
> `page.highlighted`: Items for the highlighted content region.
>
> `page.help`: Dynamic help text, mostly for admin pages.
>
> `page.content`: The main content of the current page.
>
> `page.sidebar_first`: Items for the first sidebar.
>
> `page.sidebar_second`: Items for the second sidebar.
>
> `page.footer`: Items for the footer region.
>
> `page.breadcrumb`: Items for the breadcrumb region.
>
> **If your theme does not declare any regions Drupal will assume this set of defaults.** These regions correspond with what the default core/modules/system/templates/page.html.twig file expects, as well as two hidden regions, `page_top`, and `page_bottom` \- you don't need to declare these final two if you override the defaults, however the `{{
>  page_top }}` and `{{ page_bottom }}` Twig variables should be retained in the html.html.twig template.
> 5 votes

# Answer
After some more research I finally found it here. The following is a quote of the section explaining how it works.

> ## Default Regions
>
> See the page.html.twig documentation for a list of default regions.
>
> 1. page.header
> 2. page.primary\_menu
> 3. page.secondary\_menu
> 4. page.highlighted
> 5. page.help (dynamic help text, mostly for admin pages)
> 6. page.content (main content of current page)
> 7. page.sidebar\_first
> 8. page.sidebar\_second
> 9. page.footer
> 10. page.breadcrumb
>
> If your theme does not declare any regions Drupal will assume this set of defaults. These regions correspond with what the default core/modules/system/templates/page.html.twig file expects, as well as two hidden regions, page\_top, and page\_bottom - you don't need to declare these final two if you override the defaults, however the {{ page\_top }} and {{ page\_bottom }} Twig variables should be retained in the html.html.twig template.
> 4 votes

---
Tags: theming, 8
---


# Question
Title: How can I remove items from the allowed values list of a select field that has data for the values?
I've created a content type that has a list / select option field, and I've entered the key|value pairs as necessary for the select list to function.

Data has been entred, and it's been decided that certain terms no longer apply and that they should be deleted.

However, when trying to remove said terms, I get the following error:

`Allowed values list: some values are being removed while currently in use.`

Obviously, in the life of a project, values are going to change. What's a practical way to remove items once nodes are associated with the listed terms?

This is about the closest thing that I could find:

https://drupal.org/node/1653012

It references a d6 plugin and some patch trickery I'd prefer not to have to resort to. If I did have to ultimately resort to using the patch to remove the validation check on that field, is there any harm in leaving those items orphaned on the nodes they were associated with?

Update, I have come accross this issue again with a government client who, for the last 7 years of having a Drupal site has had 50 states and territories in a select list. Now, policy has changed and the territories no longer needed to be included. Being able to remove items from the select lists is important, and thus I'm offering a bounty.

I'm looking for a safe solution to be able to remove items from a select list. What I don't know is if that solution should update any of the nodes as I'm not sure how the field values are stored in relation to a node's total content.

I'm happy with a pure SQL solution to run in MySQL; or, I'm looking for a module.

# Answer
I did something like this recently with the following approach.

1. Add the new allowed values.
2. Add a setting to configure "active" values.
3. Filter out the "inactive" values from display on the form.

e.g:

```
/**
 * Admin settings form
 */
function MODULE_admin_settings(){

  $form = array();

  // Select active preferences for display
  $field = field_info_field('field_preferences');
  $preferences = list_allowed_values($field);
  $form['field_preferences_active'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Active preferences'),
    '#options' => $preferences,
    '#description' => t('Select the preferences available for user selection.'),
    '#default_value' => variable_get('field_preferences_active', array()),
  );

  return system_settings_form($form);

}

/**
 * Implements hook_field_attach_form
 */
function MODULE_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {

  // Filter out inactive preferences
  if(isset($form['field_preferences'])){
    $preferences = variable_get('field_preferences_active', array());
    foreach($preferences as $key => $preference){
      // If this preference isn't checked, but is set in the field values, unset it.
      if(empty($preference) && isset($form['field_preferences'][LANGUAGE_NONE]['#options'][$key])){
        unset($form['field_preferences'][LANGUAGE_NONE]['#options'][$key]);
      }
    }
  }

}

```

This way the legacy data is preserved for reference, the form validates, and the data integrity is intact.
> 8 votes

# Answer
As I know, all fields data is stored in 2 tables: field\_data\_field\_FIELDNAME and field\_revision\_field\_FIELDNAME. And I found confirmation of my thought here: https://stackoverflow.com/a/7773117/1300562

So to remove unnecessary field values you need to delete these values from above-mentioned tables and then remove them from the list of allowed values.

Step 1.

```
$values_to_remove = array('value1', 'value2'); // an array of unnecessary values
$fieldname = 'FIELDNAME'; // name of your field. For example,
                          // 'territory' for field with machine name 'field_territory'
$entity_type = 'node'; // it's 'node' in your case, but it can be 'taxonomy_term' or something else

db_delete('field_data_field_' . $fieldname)
  ->condition('entity_type', $entity_type)
  ->condition('field_' . $fieldname . '_value', $values_to_remove)
  ->execute();

db_delete('field_revision_field_' . $fieldname)
  ->condition('entity_type', $entity_type)
  ->condition('field_' . $fieldname . '_value', $values_to_remove)
  ->execute();

```

Step 2.
Remove unnecessary pairs of key|value on the field settings page and submit the form to save changes.
Cache should be cleared automatically after that, but if you still can see removed field values on node pages, clear the cache manually.

P. S. Recently I faced with similar problem, and now I prefer to use fields of type "Term reference" or (even better) "Entity reference" instead of list of text values. When using reference field, you can create separate vocabulary for each field and simply create/edit/delete terms at any time.
> 3 votes

# Answer
I think you actually can done this by using Views Bulk Operations module.

1. add a new option on that field you would like to replace. for example: na|NA
2. create a View to list node contain with that field
3. add "Bulk operations: Content" fields on that View
4. check "Modify entity values" and "show avaiable tokens"(select All on display values)
5. Add the field you want to change on Filter Criteria and "expose" that filters
6. set url Path on that View
7. Go to that view page and change
8. Now, use the expose and operations features to change the field option
9. Done
> 1 votes

# Answer
First of all check if you have any allowed values specified in the field? If you do, then an other option will not be validated. So try to remove the values from Field Settings tab first.

Alternatively you have 2 options:

---

1.

Remove all values that you've put in the allowed values list that are in-use by user accounts. For example, you can run a SQL query to find these:

```
SELECT * FROM field_data_field_MYFIELDNAME WHERE entity_type = 'user' and value = 'MY VALUE'

```

or create a user view that shows you what user accounts have the value you want to remove from the allowed values list.

---

2.

If you don't want to remove values from the fields, this can be achieved by hack.

Warning, this is not suggested solution for production and you should know what you're doing!

1. Find and edit modules/field/field.module
2. Find field\_has\_data() function and add `return TRUE;` in the first line of function.

```
function field_has_data($field) {
  return FALSE; // HACK !!!
  $query = new EntityFieldQuery();

```
3. Re-save the field with values you want.
4. Remove the hack as soon as you do that.
> 1 votes

# Answer
I used kenorb's 2nd suggestion and it worked to update the list of values in a Drupal 7.52, Profile2 7.x-1.3 field. So if you were getting the drupal warning: “Allowed values list: some values are being removed while currently in use.” the following allowed me to remove values from the (profile2) field, without removing or replacing them in the database.

In Drupal core's root directory, there is a folder called modules, and the file to edit is located at: modules/field/field.module. THIS IS A CORE FILE, you must absolutely revert your changes when done updating values. I took the site offline, temporarily replaced the following code block in (drupal root)/modules/field/field.module

```
function field_has_data($field) {
  $query = new EntityFieldQuery();
  $query = $query->fieldCondition($field)
    ->range(0, 1)
    ->count()
    // Neutralize the 'entity_field_access' query tag added by
    // field_sql_storage_field_storage_query(). The result cannot depend on the
    // access grants of the current user.
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');

  return (bool) $query
    ->execute() || (bool) $query
    ->age(FIELD_LOAD_REVISION)
    ->execute();
}

```

WITH EXACTLY

```
function field_has_data($field) {
    return FALSE; // hack
    $query = new EntityFieldQuery();
}

```

And drupal stopped complaining and I was able to alter the list. (In my case, it’s faculty in the list of values that have left the university, but are still associated with a students record, as their advisor, mentor, etc.)
> 1 votes

# Answer
Here comes an improvement for H-L answer which I think is the best:

To sum up, you need to assign new values to content which has "old" values assigned for your select field.

Apart from Views Bulk Operations, you will need to install and enable Administration Views module. With this module, you already have an out-of-the-box view with bulk operations enabled (just see admin/content once enabled). Then:

1) Go to admin/structure/views an edit "Administration: Node" view

2) Add a new page display for the view using button "Add -\> Page" on top

3) Asssign a path to the new display: Example admin/content/custom

4) Add a new filter for your select field: Select operator "is one of" and then select all options you want to delete

5) Save the view

6) Go to admin/content/custom Now you see all content that you need to bulk edit (change value for your select field)

7) Select all rows by clicking first checkbox in the left of the table (if there is more than one page, also select a button which will say "Select all X rows in this view")

8) Select operation "change value" and press "Execute"

9) For your select field, select a new value to overwrite the ones you want to delete

10) Select the checkbox for that select field

11) Click Next and you are done
> 0 votes

# Answer
It sounds like your Drupal problem is based on a deeper data problem: What happens to the entities which are currently using the depreciated list values? This question is at the root of the error message that Drupal is sending you.

Lets take a closer look at your state/territory example. Your client has been using a system that treats states and territories in the same way for years and has build up a huge group of nodes which contain both states and territories. Then one day, the powers that be decide that territories need to be handled differently and that the drop-down for assigning region should no longer contain territories. Great. Simply create a view that uses standard filters to render a list of all the territory nodes and use Views Bulk Operations to change all of their region values to... what... some 51th state called other maybe? The fate of the territories is a very serious question. Your solution must include a method for preserving or relocating the territory status. You may need to create a new list field called 'Territory' which can be used to identify areas that are territories, or create an entirely new data type for them.

You will need to use Rules with View Bulk Operations in order to perform these changes. If you don't know much about rules, please take some time to learn about how they work. Rules gives you the ability to manipulate information based on triggers, conditions and actions. After learning about rules, you may find that the answers you are looking will intuitively present themselves. Basically, You will need to create a rule, which is triggered by a Bulk Operation, that will target all of the territories and remove, reassign, rename or otherwise separate them from the main body of information. The Rule must be able to store the territory state in some way while at the same time, set the state dropdown to 'other' or 'N/A' status. This may be all that is needed. Otherwise...

After the reassignment is done, it should be a simple operation to alter the original list field and remove the territory names. However, if the system still does not allow you to alter the list, you may need to create a new list field, then use Views Bulk Operation and Rules to review all of the current state values and reassign them to the new list. Rules can work with Views Bulk Operations to target all of the relevant nodes and act upon them based on the field values. Setting a the value of a new list field based on the value of an existing list field for a group of nodes is easy when you use Rules.

Also remember, if Drupal gives you trouble with an operation, always flush the cache before considering a difficult alternative.
> 0 votes

# Answer
I would assume your client wants legacy content to hold to it's original value, meaning changing the select list will effectively destroy any previous data. If that's not a concern, then any of the other answers would probably work. If it is however, you can't really change the select list without loosing that data history. I might go a much simpler route, to allow for historical data, while making the site a little more future-proof - I would suggest using field permissions:

\*set up a new field for that select list using a taxonomy instead of static data

\*set the field permission for the existing select list as VIEW, but not EDIT by anyone except admin

With this, the old field should remain viewable and searchable (add a new title reflecting it as legacy only) but not editable. This of course depends heavily on custom searches, views, etc that may need to be adjusted.

I suggest this (as messy as it may sound) because removing that data, removes history, and that may end up being devastating in the long run. You could even use css to hide the old field in the edit node, and a hook to hide it for new content (where it doesn't have a value set). In this way, it would only show for that legacy content.

Of course, you could then take it a step further with a custom one-off module to copy the data from the old select list to the new taxonomy.
> 0 votes

# Answer
A simple drush script to the rescue! We update the field data and field revision tables and replace the old values with new ones before manually changing the field settings.

If we have something like this in our current field settings:

```
&date=today|today
&date=last2days|last2days

```

and want to replace it with the following:

```
date=today|today
date=last2days|last2days

```

We run the drush script first and then change the field settings in admin UI.

**Note:** This code is for a field with machine name `field_foo_bar`.

```
    $field_name = 'foo_bar';

    print "for {$field_name}...\n";

    replace_field("&date=today", "date=today", $field_name);

    replace_field("&date=last2days", "date=last2days", $field_name);

    function replace_field($old_value, $new_value, $field_name, $entity_type='node') {
      print "Replacing {$old_value} with {$new_value}...\n";
      $data_count = replace_options_data_field($field_name, $entity_type, $old_value, $new_value);
      $revision_count = replace_options_revision_field($field_name, $entity_type, $old_value, $new_value);
      print $data_count + $revision_count . " entries replaced.\n";
    }

    function replace_options_data_field($field_name, $entity_type, $old_value, $new_value) {
      $num_updated = db_update('field_data_field_' . $field_name)
        ->fields(array(
                   'field_' . $field_name . '_value' => $new_value,
                 ))
        ->condition('entity_type', $entity_type)
        ->condition('field_' . $field_name . '_value', $old_value)
        ->execute();
      return $num_updated;
    }

function replace_options_revision_field($field_name, $entity_type, $old_value, $new_value) {
  $num_updated = db_update('field_revision_field_' . $field_name)
    ->fields(array(
               'field_' . $field_name . '_value' => $new_value,
             ))
    ->condition('entity_type', $entity_type)
    ->condition('field_' . $field_name . '_value', $old_value)
    ->execute();
  return $num_updated;
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Can I change the location of the cached Twig templates?
By default, the Twig template cache appears to go into /files/php/twig.

I was wondering if it's possible to change this location? I use a shared file mount which is shared between multiple developers and my concern is that the Twig cache will be in competition with another developer.

Alternatively we can disable caching but this is not always appropriate.

# Answer
Yes you can, put this in settings.php or any file loaded by it like settings.local.php:

```
  $settings['php_storage']['twig']['directory'] = '/path/to/tmp/folder';
  $settings['php_storage']['twig']['secret'] = $settings['hash_salt'];

```

Note that the directoy must exist already.
> 20 votes

---
Tags: theming, 8, caching
---


# Question
Title: Commerce Kickstart 2 Display color as visual colour
In the 'Tops' Content type/Product Variation, the color selection in the 'catalog' shows up as multiple color blocks below the 'From $00.00' price information.

I've made up a new Content type and Product Variation, also with color. How do I get *all* the available product variation colors to show up as blocks of color below the price instead of just a single link to the first variations colour?

# Answer
> 0 votes
You go into the Content Type and in the "Manage Display" -\> "Product List" mode, you add a Field Extractor to get the color field and use view mode of 'Add to cart form' for view mode

# Answer
> 0 votes
Go to Store setting -\> Product settings -\> Variation types -\> your content type -\> manage fields -\> edit color(term reference) enable the settings under "ATTRIBUTE FIELD SETTINGS"

# Answer
> 0 votes
**Navigate:** Content \> Content types

**Click Link:** (your type) \> Manage display

**Select Button:** Manage display \> Product list

*If it's not there, be sure to add it to the visible area:*

Product variations

Select: \< Hidden \>

Select: Field Extractor

**Click Button:** Settings

*Enter the following:*

Field: field\_color

Formatter: Rendered entity

View mode: Add to Cart form - Attribute

**Click Button:** Update

**Click Button:** Save

---
Tags: commerce
---


# Question
Title: Is it possible to use different tokens in metatag based on content type
Lets say I have the summary field enabled on article type but not on page type and then I setup meta tag descriptions to use the token \[node:summary\] would is be possible to do something like if \[node:summary\] doesn't exist or is empty than use \[node:body\] ?

Otherwise i was would most likely need to add the summary field to page types and fill the summary field for all the pages that didnt have it.

# Answer
**In Drupal 7**

When you configure Metatag, you can click on `+ Add default meta tags` and this will allow you to **set them up by Content Type**.

You will see this gets added to the config tree. Simply now edit the content type you just added.

# Bonus/Extra Info

If you need to alter **only specific nodes**, edit your node and scroll down to the end and select the Meta tags tab.
> 1 votes

---
Tags: 7, tokens, meta-tags
---