# Question
Title: What are the recommended directory permissions?
I'm gearing up to deploy a Drupal 7 site and I can't find any documentation. What are the recommended security-conscious permissions for files and directories?

I am specifically interested to the *default/files/* directory, the *settings.php* and *.htaccess* files.

# Answer
> 73 votes
Your web server should be able to read all of the files but **not** write to them. If your site involves uploading files then give the server permission to write to that one folder only.

More information on how to set that up, as well as some things that can happen if you don't, is available in the Drupal docs.

# Answer
> 103 votes
That drupal page like so many is very long and confusing. But it contains this post by Jason, who hit the nail on the head:

> Posted by Jason Sale on November 1, 2010 at 12:40pm
>
> Thanks for writing this and everything, but all that I and 99% of people reading this page really want is a list of numbers next to a list of folders.
>
> * `/default` on 755
> * `/default/files` including all subfolders and files on 744 (or 755)
> * `/default/themes` including all subfolders and files on 755
> * `/default/modules` including all subfolders and files on 755
> * `/default/settings.php` and `/default/default.settings.php` on 444

# Answer
> 86 votes
My practice around creating a new Drupal site on a server is to have a user that is a part of the web server (typically Apache) group, and have that user own all the Drupal files. On Ubuntu, these are the commands to get that set up:

```
# Create a new example user, setting up /var/www/example as their home dir.
useradd -s /bin/bash -d /var/www/example -m example

# Now add that user to the Apache group. On Ubuntu/Debian this group is usually
# called www-data, on CentOS it's usually apache.
usermod -a -G www-data example

# Set up a password for this user.
passwd example

```

Once I have that set up, I'll log in as that user and install Drupal at /var/www/example/docroot or similar, and then create the files directory by hand and copy over the settings.php file. Since we log in as our example user before copying in Drupal, our file ownership and permissions should automatically be properly configured on all the core Drupal files and scripts (including .htaccess files).

```
su - example
cd docroot
cp sites/default/default.settings.php sites/default/settings.php

# Temporarily give the web server write permissions to settings.php
chgrp www-data sites/default/settings.php
chmod g+w sites/default/settings.php

```

Now let's set up the files directory.

```
# Create the directory.
mkdir sites/default/files

# Now set the group to the Apache group. -R means recursive, and -v means
# verbose mode.
chgrp -Rv www-data sites/default/files

```

Next we'll set up permissions so that the web server can always write to any file that is in this directory. We do this by using 2775 in our chmod command. The 2 means that the group id will be preserved for any new files created in this directory. What that means is that www--data will always be the group on any files, thereby ensuring that web server and the user will both always have write permissions to any new files that are placed in this directory. The first 7 means that the owner (example) can R (Read) W (Write) and X (Execute) any files in here. The second 7 means that group (www-data) can also R W and X any files in this directory. Finally, the 5 means that other users can R and X files, but not write.

```
 chmod 2775 sites/default/files

```

If there are any existing files in this directory, be sure the web server has write perms on them.

```
 chmod g+w -R sites/default/files

```

Now Drupal is ready to be installed. When finished, it is **VERY** important to come back to settings.php and ensure that all users only have read permissions.

```
 chmod 444 sites/default/settings.php

```

That's it! This set up ensures you avoid any situations where either the user that owns the directory or the web server can't write/change/remove files in the files directory.

# Answer
> 35 votes
The Drupal files folder should be writable by the webserver. The safest way to do that is to change the group and make it group writable, like this:

```
chgrp www-data sites/default/files
chmod g+w sites/default/files

```

The file upload folder aside, the safest is chmod 644 for all files, 755 for directories.

This could be accomplished like this (when run in the Drupal-site folder, the `.` is for current path):

```
find . -type f | xargs chmod 644
find . -type d | xargs chmod 755

```

Remember that you will need to set `chmod g+w` again after running the above command, since those will reset the chmod on all files and folders.

# Answer
> 22 votes
Any advice to "chmod blah" or "chown X" is meaningless without knowing: what the default user:group is on the files and what user and groups your webserver runs as.

The Drupal Docs others have linked to are quite good on the topic but one other resource is the Security Review Module which helps ensure you've got everything set properly.

**Feature of Security Review Module**

* Safe file system permissions (protecting against arbitrary code execution)
* Text formats don't allow dangerous tags (protecting against XSS)
* PHP or Javascript in content (nodes and comments and fields in Drupal 7)
* Safe error reporting (avoiding information disclosure)
* Secure private files
* Only safe upload extensions
* Large amount of database errors (could be sign of SQLi attempts)
* Large amount of failed logins (could be sign of brute-force attempts)
* Responsible Drupal admin permissions (protecting against access misconfiguration)
* Username as password (protecting against brute-force)
* Password included in user emails (avoiding information disclosure)
* PHP execution (protecting against arbitrary code execution)
* Base URL set / D8 Trusted hosts (protecting against some phishing attempts)
* Views access controlled (protecting against information disclosure)

# Answer
> 11 votes
I will reply considering the case the files are created on the server using FTP, using credentials different from the one under which is the web server runs (normally, Apache runs as nobody/nobody). This means that the user who owns the files manually created before running the Drupal installer (which includes also the files uploaded on the server from the Drupal archive) is not the user used to run the web server (neither the username or the group matches). This scenario applies also to the case where those files are created using SSH.

* The settings.php file must be writable from the Drupal installer, but once the installation is done it is suggested to make it read-only (the installer suggest that, and Drupal will periodically check if the file is really read-only). In the scenario I am describing, the permission of this file should at least be 644.
* The .htaccess files (which are present in at least two places) should have the permission 644. The user who created the file should still be able to overwrite the file, in the case a next version of Drupal comes with an .htaccess file that has been updated (it happened already once, when it has been added a line to that file to avoid a security issue). It is also possible to set the permissions to 444, but in that case, the permissions should be changed back to 644 when the file needs to be updated.
* The directory containing the files created by the modules (the `default/files` directory) must be (for the user that is assigned to the web server processes, which is then the user assigned to to the PHP scripts running on that web server):
    + readable
    + writable
    + traversable (the modules must be able to reach `default/files/<directory-used-by-the-module>/<sub-directory-used-by-the-module>`)

# Answer
> 11 votes
Recommended file/directory permissions:

* Drupal webroot should be world readable (see: updater.inc): 0755
* for public upload directories: 0755 or 0775
* for private upload directories: 0750 or 0770
* for public uploaded files: 0644 or 0664
* for private uploaded files: 0640 or 0660
* for .htaccess within upload directories (see: file\_create\_htaccess()): 0444 (default) or 0644
* for settings.php read-only for all (and other confidential files): 0440
* for all other web directories: 0755
* for all other web files: 0644

Recommended file/directory ownership:

* owner of all upload directories/files should be set to Apache user,
* owner of all web/sources directories/files should be set to non-Apache user,
* (optionally) group of all sources should be set to Apache group,

Here are the variables which control default dir/file permissions for new items:

```
file_chmod_directory: 0775
file_chmod_file: 0664

```

Here is some script for fixing permissions: fix-permissions.sh

---

Read more:

---

Here is script which I'm using to fix permissions on remote host for public/private directories:

```
#!/bin/sh -e
# Script to correct public/private directory and files permissions.
[ -z "$1" ] && { echo Usage: $0 @remote.dst; exit 1; }

DST="$1" && shift
GET_HTTP_GROUP='ps axo user,group,comm | egrep "(apache|httpd)" | grep -v ^root | uniq | cut -d\  -f 1'

drush $* $DST ssh 'PUB=$(drush dd %files) && PRIV=$(drush dd %private) && AGROUP=$('"$GET_HTTP_GROUP"') && chgrp -vR $AGROUP $PUB $PRIV && chmod -vR u+rwX,g+rwX,o+rX $PUB $PRIV'

```

Note: Above code will try to retrieve Apache group and set it to `GET_HTTP_GROUP` variable.

# Answer
> 5 votes
This shell script is found at the bottom of this page: https://www.drupal.org/node/244924

I run it occasionally to ensure that my permissions are set up correctly.

```
#!/bin/bash
# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:
1) Path to your Drupal installation.
2) Username of the user that you want to give files/directories ownership.
3) HTTPD group name (defaults to www-data for Apache).
Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}
if [ $(id -u) != 0 ]; then
  printf "**************************************\n"
  printf "* Error: You must run this with sudo. *\n"
  printf "**************************************\n"
  print_help
  exit 1
fi
drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"
# Parse Command Line Arguments
while [ $# -gt 0 ]; do
  case "$1" in
    --drupal_path=*)
      drupal_path="${1#*=}"
      ;;
    --drupal_user=*)
      drupal_user="${1#*=}"
      ;;
    --httpd_group=*)
      httpd_group="${1#*=}"
      ;;
    --help) print_help;;
    *)
      printf "***********************************************************\n"
      printf "* Error: Invalid argument, run --help for valid arguments. *\n"
      printf "***********************************************************\n"
      exit 1
  esac
  shift
done
if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
  printf "*********************************************\n"
  printf "* Error: Please provide a valid Drupal path. *\n"
  printf "*********************************************\n"
  print_help
  exit 1
fi
if [ -z "${drupal_user}" ] || [[ $(id -un "${drupal_user}" 2> /dev/null) != "${drupal_user}" ]]; then
  printf "*************************************\n"
  printf "* Error: Please provide a valid user. *\n"
  printf "*************************************\n"
  print_help
  exit 1
fi
cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .
printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;
printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;
printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
    find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
    find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done setting proper permissions on files and directories"
Copy the code above to a file, name it "fix-permissions.sh" and run it as follows:
sudo bash fix-permissions.sh --drupal_path=your/drupal/path --drupal_user=your_user_name

Note: The server group name is assumed "www-data", if it differs use the --httpd_group=GROUP argument.

```

# Answer
> 4 votes
Also if you are running fastcgi, the php runs AS the user, and will have access to all files that the user has access to unless you deliberately try to avoid this.

# Answer
> 2 votes
This helped me with my OSX Permission issues. I found it in https://www.drupal.org/node/244924#comment-3741738 by protoplasm user. I was like him having issues after a migration.

```
[root@localhost]cd /path_to_drupal_installation/sites
[root@localhost]find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
[root@localhost]find . -name files -type d -exec find '{}' -type f \; | while read FILE; do chmod ug=rw,o= "$FILE"; done
[root@localhost]find . -name files -type d -exec find '{}' -type d \; | while read DIR; do chmod ug=rwx,o= "$DIR"; done

```

---
Tags: 7, files, security
---


# Question
Title: Contextual Filter based on internal link
I have two content types: „projects“ and „press articles“. The „press article“ has a link internal link field to the related „project“.

How can I create a view, which only displays the „press articles“ which have a link to a certain project? In the end there should be a link on the „project“ site to it’s related articles, if there a any press article with a link to this project.

It seems that I need to set up a view with a contextual filter, which shows all nodes who have a link to the current node. I have a contextual filter for field\_press\_related\_project:uri, but how do I provide the uri from the current node? „Content ID from url“ does not work.

(It works when i provide a fixed value for the contextual filter field\_press\_related\_project:title)

(I already achieved to have a general press section view, which includes all articles by year.) Now this should be filtered to only the related articles to one project.

thank you very much for any hint.

# Answer
> 0 votes
By having an internal link field type, you're not going to be able to easily pass the right value to your contextual filter as the stored value would be something like `[uri] => entity:node/1`

In order to achieve your goal, I suggest you to replace your "Link" field type with a "Content Reference". In this way you can: 1. Add your field as a contextual filter; 2. Then "Provide default value" as "Content ID from url".

---
Tags: views
---


# Question
Title: Aggregator module block shows up only to registered users
I am using the aggregator module for D8, I have created a few blocks with feeds from various media outlets. The problem is that the blocks show up only to registered users of the site. How can everybody see them?

Thank you.

# Answer
Have you checked the role permissions on the blocks? On block layout, you should be able to click on Configure. This should take you to the administration screen for the block in question. There you should see a tab layout with an option for Roles. Do you have items there checked?
> 0 votes

---
Tags: blocks
---


# Question
Title: Create taxonomy terms from content type field
I'm looking to add a taxonomy term to a vocabulary upon the creation of content type.

For example I have a taxonomy vocabulary called "Widget Type".

I have a content type of Product. When I create an instance of product I would like the title (product.title\_1) to be added as a taxonomy term to Widget Type.

Then every time a new product is created a term is added. Widget Type would then contain the terms... title\_1 title\_2...etc.

Does this require a custom module or is there an easier way to do this that I'm not aware of?

Thanks

# Answer
You can trigger this behavior by implementing the hook\_entity\_presave on a custom module. Inside of this hook, you will call a function which creates each time the taxonomy term using the title of the node created. Here is my example:

File: test.module

use Drupal\Core\Entity\EntityInterface;

/\** * Implements hook\_entity\_presave(). \*/ function test\_entity\_presave(EntityInterface $entity) { if ($entity-\>bundle() == 'product') { if ($entity-\>isNew()) { $title = $entity-\>get('title')-\>getValue(); \Drupal\test\Test::createTerm($title\[0\]\['value'\]); } } }

Assuming you have defined the createTerm function into Class Test:

File Test.php(Include this file in src folder)

namespace Drupal\test;

/\** * Test class. \*/ class Test { public static function createTerm($title) { $term = \[ 'name' =\> $title, 'vid' =\> 'widget\_type', 'langcode' =\> 'en', \]; $term = \Drupal::entityTypeManager()-\>getStorage('taxonomy\_term')-\>create($term); $term-\>save(); } }
> 0 votes

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


# Question
Title: empty page creation and filling it with blocks
I need to create a custom page which content region can be nicely presented as a set of views blocks. I don't know whether it's possible. So the question is:

Is there any possible way to create an empty page with certain url , e.g. "mysite.org/news", and fill its 'content' variable with some blocks without writing a module and declaring the page with php and hooks? Just from the admin interface.

# Answer
> 2 votes
This sounds like you need the panels module. It is quite a complex module so you could check out this learning series from node one.

# Answer
> 2 votes
Seems like Panels would be good for this. You'd create a panels Page and then assign the relevant blocks.

# Answer
> 1 votes
I have a slightly different solution that I use. As Splatio pointed out, it is somewhat of a complex module, and for me, most of what I need to accomplish can be done without panels, which saves the extra overhead of an extra module.

So,

1. Create your page something.com/mypage. Give it a title, but make sure the body is blank when you save it.
2. Create your views blocks. Now that you have blocks, you can configure them to show up on any one page you want. Configure them to show up on something.com/mypage, and then put them in the Content regions.
3. Voila, the page is created with any number of blocks you need, and, without the body having any content, the illusion is complete.

3a. I have also used this technique to give the block views some context by adding a short paragraph. "See the newest entries for each category today" or something.

# Answer
> 1 votes
You could do this all in views without any futzing with templates or knowing node/### by creating a page display in addition to all your block displays. For example, if you created a view with a page display with a path of `news`, it would define `www.yousite.com/news` for you and populate your theme's content region with its output. If you then created, either in the same or any other view, block displays, they could then be added to the content region as well and would follow that first view's output.

# Answer
> 1 votes
```
 <?php
 /**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  $items['path/to/page'] = array(
    'title' => 'Title',
    'page callback' => 'my_module_empty',
    'access callback' => TRUE,
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}

/**
 * An Empty Page callback's empty content.
 *
 * @return string $output
 */
function my_module_empty() {
  return '';
}
?>

```

# Answer
> 0 votes
Easy, clean, simple: use empty\_page module.

.. and to place blocks you can use context instead of the drupal blocks interface.

# Answer
> 0 votes
I have a workaround for this.

Create a text field in your content type that only allows 1 letter value. Give it a value of "don't fill in this field, it's used to create the page"

In your view, set your format to show fields. In the fields section, add the newly created content type field and set it's CSS class to hidden (display none).

Set your filter criteria to Content: Type(your content type).

Then configure your blocks to only appear on that page.

Alternately (I don't know if this is just on mine or what) but your fields section can also have the field, Content: Page. This sets a new page for me as well. But the above works fine too.

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


# Question
Title: Loading more content in mobile (Slider) - Views core module
I am using the view core module to view the featured articles, latest articles and more stuff in my project, it is rendering 3 articles and the load more button to load more content using ajax, This is working great in Desktop, However in Mobile, the load more button doesn't exist (As per website design) and the articles are displayed in a slider. I am hiding load more button using CSS, the user has no way of loading more content!!

---

**1st Approach:** Load more content using ajax.

How can I automatically load more content after the user slides 2 or more slides ? I can easily detect when the user slides to the 2nd slide using jquery but how can I load more slides dynamically using ajax? Do I have to load more content by myself or does Drupal 8 have a way of doing this?

---

**2nd Approach:** Make 2 blocks, one for desktop, one for mobile.

I thought of doing 2 separate views blocks:

**Desktop view block:** 3 items and load more button

**Mobile view block:** all items

But this doesn't feel right, and I will have to toggle between them using CSS which means the content will be fetched by network anyway, So this approach is not correct.

I could not find how to hide or show a block depending on view width without CSS.

---

If there is another approach please tell me.

# Answer
> 0 votes
Maybe can you detect with jQuery that the user's screen is near the bottom of the page (or with your 1st approach), then you use an .click() on your invisible "load more" button ? In that way, user will scroll and more content will appear each time ?

# Answer
> 0 votes
You should look at the views\_infinite\_scroll project. It has the option to not display a Load More button and just autopage when the end of the list is reached. Just specify it as the pager in your view and select options from there.

You could either have two different views or maybe just refactor the desktop to not have a load more button and use the auto load like the mobile display.

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


# Question
Title: How to show authorized users a link for relevant Views results using the Rules Link module?
Assume a list of entities, created by the Views module. For example a list of "All blocked/active users" which looks like so:

```
User name      Active  Created date        Last login
Hillary.Trump  No      06/18/2016 - 13:45
Donald.Clinton No      06/18/2016 - 13:42
Someone.Else   Yes     05/12/2016 - 12:09  09/17/2017 - 11:18
Pierre.Vriens  Yes     03/11/2016 - 21:05  10/06/2017 - 16:04
Dries.Buytaert Yes     11/23/2015 - 10:11  09/17/2017 - 10:38
Anonymous      No

```

The goal is to use the Rules module to change the status for selected users from `blocked` to `active`. This should be possible by also using the Rules Link module, based on what's mentioned on the project page of this module, i.e.:

> *Features*: ... The links are usually displayed using Views...
>
> *Usages*: ... The Rules Link module will create a Views field for each link, which can be hidden, using the visibility conditions ...

My question: How to show **authorized users** a link for **relevant** Views results using the Rules Link module? Some more details about my question:

* The links should be shown within an extra column, (say) as last column to the right.
* **Authorized users**: the extra column should only be shown to users with permission to use (click) the link, say to users with role "Administrator".
* **Relevant**: the link should only be shown for users for which the value of the *Active* column is `No`. Obviously, for *Anonymous* it doesn't make sense to show that link (since you cannot change the status for *Anonymous* to `active`.

For the sake of completeness, here is an export of my (extremely basic) view related to the sample above (also note the `view_of_users` path in it):

```
$view = new view();
$view->name = 'view_of_users';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'View of Users';
$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'] = 'All blocked/active Users';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'administer users';
$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';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'rid' => 'rid',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'rid' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* 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']['label'] = 'User name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: User: Active */
$handler->display->display_options['fields']['status']['id'] = 'status';
$handler->display->display_options['fields']['status']['table'] = 'users';
$handler->display->display_options['fields']['status']['field'] = 'status';
$handler->display->display_options['fields']['status']['not'] = 0;
/* Field: User: Created date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'users';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['date_format'] = 'short';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Field: User: Last login */
$handler->display->display_options['fields']['login']['id'] = 'login';
$handler->display->display_options['fields']['login']['table'] = 'users';
$handler->display->display_options['fields']['login']['field'] = 'login';
$handler->display->display_options['fields']['login']['date_format'] = 'short';
$handler->display->display_options['fields']['login']['second_date_format'] = 'long';
/* 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';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'view_of_users';

```

# Answer
Below are the steps I used to get this to work ...

### Step 1: Add a Rules Link

Enable the Rules Link module, and navigate to `admin/config/workflow/rules_links` where you can use the link to relative path `admin/config/workflow/rules_links/add` to perform an *Add rules link*. Enter these values on the various form fields:

* Label: *Unblock a blocked user*, with related machine name `unblock_a_blocked_user` (change to whatever you like, but better don't change it afterwards or strange things may happen, so make sure to pick the right label/name from the start).
* Entity type: *User* (change to whatever entity that fits your needs). I did not check the related checkbox "Show link when entity is rendered" (pick what fits for you).
* Link text: *Unblock user* (change to whatever you like).
* Link type: *Normal* (though *Confirmation* could be a valid alternative).
* Path: `unblock_user` (change to whatever you like).
* Additional Variables: no need for additional variables, except the "User" variable already shown with Data type = User, Label = User, Machine name = user and Usage = Parameter (too bad you cannot adapt its Label / Machine name to something more self explaining, like "User to unblock").

Use the `Continue` button to continue, after which you'll get an informational message like so:

> Your Rules Link has been created along with the required components. Please remember to set the permissions for your link and to add actions to your reactions rule.

Note that an extra tab is added also, labeled "Configure Rules" (to the right of the tab labeled "Edit").

Use the `Save Rules Link` button at the bottom to move on, which will then show the screen again located at `admin/config/workflow/rules_links`. It will now show an extra entry with a label like `Unblock a blocked user (Machine name: unblock_a_blocked_user)` (or whatever values you used to create the Rules Link).

Here is an export of the Rules Link described above:

```
{
  "settings" : {
    "text" : "Unblock user",
    "link_type" : "token",
    "bundles" : [],
    "entity_link" : 0,
    "view_mode" : []
  },
  "name" : "unblock_a_blocked_user",
  "label" : "Unblock a blocked user",
  "path" : "unblock_user",
  "entity_type" : "user",
  "rdf_mapping" : []
}

```

### Step 2: Configure permissions

Navigate to `/admin/people/permissions` and move on to the "Rules Link" section of it (located at `admin/people/permissions#module-rules_link`). There should be an entry like "*Unblock a blocked user: Execute rules link*", for which you can specify the roles that should be allowed to use this Rules Link.

As per the **Authorized users** part of my question, I granted the permission to role *Administrator* (only). That will ensure that for any user who does not have the role Administrator, but who does have access to the views results (as in the question), the Rules Link is hidden for such user.

### Step 3: Configure Access Conditions of the Rules Link

Head back to `admin/config/workflow/rules_links/` and click the `edit` link of the Rules Link you created before (in my case located at `admin/config/workflow/rules_links/manage/unblock_a_blocked_user/components`). Then use the "Configure Rules" tab to specify the relevant "Access Conditions". Don't be confused ... 'Access' here is not about permissions! Instead they are like an extra refinement of the permissions: they can be used to specify when to show the Rules Links.

As per the **Relevant** part of my question, I specified these Rules Conditions (which must both be satisfied), using the `Add condition` link (right above "Reactions"):

1. Data comparison, with:

* Data to compare: `[user:uid]`
    * Operator: `is greater than`
    * Data value: `0`
2. Data comparison, with:

* Data to compare: `[user:status]`
    * Data value: `Blocked`

The 1st condition will ensure the link is NOT shown for *Anonymous*. And the 2nd condition will ensure the link is only shown for users for which the value of the Active column is `No`.

These *Access Conditions of the Rules Link* are actually saved as a regular Rules Component (using a Component Plugin type of "Condition set (AND)" and with machine name `rules_link_condition_unblock_a_blocked_user`). Here is how it looks like (in Rules Export format):

```
{ "rules_link_condition_unblock_a_blocked_user" : {
    "LABEL" : "Rules link: Unblock a blocked user condition",
    "PLUGIN" : "and",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "user", "type" : "user" } },
    "AND" : [
      { "data_is" : { "data" : [ "user:uid" ], "op" : "\u003E", "value" : "0" } },
      { "data_is" : { "data" : [ "user:status" ], "value" : "0" } }
    ]
  }
}

```

### Step 4: Configure Reactions of the Rules Link

The bottom part of the "Configure Rules" tab, below the label *Reactions*, is used to specify the relevant set of rules (1 or more) to be performed when the Rules Link is actually used (clicked). As per my question, I need to create a rule here to "*change the status for selected users from `blocked` to `active`*". To do so, I used the `Add rule` link (right above "Settings") to add a new rule (I only need 1) with name "*Make user active*".

Use the `Save changes` button, which will then show the screen to create the actual rule. For my case, this is how the actual rule looks like:

* Rules Conditions: none (I don't need any extra validations).
* Rules Actions:

+ Unblock a user, for User: `[user]`
    + Page redirect, with URL = `view_of_users` **(** * **)**

Use the `Save changes` button at the bottom to move on.

**(** * **)**: this page redirect (to path `view_of_users`) is actually a work around for the outstanding Rules Link feature request Stay on current page. It ensures the same views result is displayed again and avoids that after using the link, the site's homepage is shown. Adapt this path to the path of your own views result.

These *Reactions of the Rules Link* are actually saved as a regular Rules Component (using a Component Plugin type of "Rule set" and with machine name `rules_link_set_unblock_a_blocked_user`). Here is how it looks like (in Rules Export format):

```
{ "rules_link_set_unblock_a_blocked_user" : {
    "LABEL" : "Rules link: Unblock a blocked user rules set",
    "PLUGIN" : "rule set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "type" : "user", "label" : "user" } },
    "RULES" : [
      { "RULE" : {
          "DO" : [
            { "user_unblock" : { "account" : [ "user" ] } },
            { "redirect" : { "url" : "view_of_users" } }
          ],
          "LABEL" : "Make user active"
        }
      }
    ]
  }
}

```

### Step 5: Add the links as extra Views column

With everything as described in the previous steps in place, the finishing touch is to have the links produced by the Rules Link module actually show up in an extra column added to the View results.

However, assuming you're familiar with the basics of Views, it isn't obvious at first about how to actually add that extra column. The clue to get it to work, can be found in this part of the module's README.txt:

> Rules Links link will create a Views field for each link, using the title of the link as title for the field. So if you have link for nodes with the delete 'Delete node', you'll find the Views field under name 'Content: Delete node'.

In my case my entities are `Users` instead of `Nodes`. And the Views field I'm looking for is 'User: Unblock a blocked user' (whereas the 'Unblock a blocked user'-part of it equals the label of the Rules Link I added, as explained in Step 1). So that is the field I added as extra (last) field.

### Final result

After completing the previous Steps, the updated list of "All blocked/active users" looks like so for a user with role Administrator:

```
User name      Active  Created date        Last login
Hillary.Trump  No      06/18/2016 - 13:45                      Unblock user
Donald.Clinton No      06/18/2016 - 13:42                      Unblock user
Someone.Else   Yes     05/12/2016 - 12:09  09/17/2017 - 11:18
Pierre.Vriens  Yes     03/11/2016 - 21:05  10/06/2017 - 16:04
Dries.Buytaert Yes     11/23/2015 - 10:11  09/17/2017 - 10:38
Anonymous      No

```

Note the extra column added (to the right), with links labeled `Unblock user` which are only shown for the blocked users, and not for Anonymous. After using (clicking) that link, for some user with `Active=No`, the user's status becomes `Active`, and the link is no longer shown for that user.
> 1 votes

---
Tags: 7, views, rules, navigation
---


# Question
Title: reCaptcha is not display correctly in the Bootstrap Login Modal registration form
I am using the Bootstrap Login Modal module release 7.x-3.2 to create a modal registration form. Unfortunately, the reCaptcha does not display on the registration form until the registration button is clicked. Afterwards the form will close. When you reopen it, reCaptcha will be displayed. It looks like it is incorrectly added to the form. If I switch to using default Math captcha it loads first time without problems.

Does someone know how to solve this problem?

reCaptcha doesn't display on the registration form

reopened form reCaptcha is dispayed

# Answer
> 1 votes
This helps me adding recaptcha in modal forms.

Check this patch. https://www.drupal.org/node/1463768 in thread number 21.

---
Tags: 7, bootstrap-theme
---


# Question
Title: How do I set descriptions to each checkbox option
Is there a way to set descriptions to each checkbox option? What I would like is for Option #1 to display and then directly below it a description for it, then Option #2 along with its description. I have:

```
 $form['field_options'] = array(
                    '#type' => 'checkboxes',
                    '#options' => array(
                        0 => t('Option #1'),
                        1 => t('Option #2')),
                    '#title' => t('Select Options'),
                    '#description' => t('Entering a description here will display below the last item in the array'),
                    '#default_value' => array(0)
            );

```

Also, for some reason `$form_state['values']['field_options']` in function `hook_node_submit()` shows

```
Array
(
    [0] => 0
    [1] => 0
)

```

shouldnt it show what the states of the checkboxes are like this?:

```
Array
(
    [0] => 1
    [1] => 0
)

```

Thanks

# Answer
Got it!

```
function MYMODULE_process_checkbox_descriptions($element) {
foreach (element_children($element['#options']) as $key) {
    if (!empty($element['#checkbox_descriptions'][$key])) {
        $element[$key]= array(
            '#type' => 'checkbox',
            '#title' => $element['#options'][$key],
            '#description' => $element['#checkbox_descriptions'][$key]
            ) ;
    }
}
return $element;
}

```

And

```
function MYMODULE_form_alter($form, &$form_state,$form_id) {
  $form['field_options'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
            1 => t('Option #1'),
            2 => t('Option #2')),
    '#checkbox_descriptions' => array(
            1=> t('Description #1'),
            2=> t('Description #2')),
    '#title' => t('Select Options'),
    '#description' => t('Entering a description here will display below the last item in the array'),
    '#default_value' => array(1),
    '#process' => array('MYMODULE_process_checkbox_descriptions'),
  );

  return $form;
}

```

Worked nicely!! thanks @Clive and @Marcel !
> 1 votes

# Answer
The #title will be displayed as a description next to the checkbox, description below it if you use single checkboxes in a for-loop.

You need to change it a bit:

```
$options = array('Option 1' => t('Description1'), 'Option2' => t('Description 2');
$i = 1;
foreach ($options as $title => $description) {
    $form['field_options']['option_' . $i]= array(
      '#type' => 'checkbox',
      '#title' => $title,
      '#description' => $description,
      '#default_value' => 0,
    );
  $i++;
}

```

Set the value with #default\_value = 0; (not an array).

About the 0 value in the array: From drupal.org Form API about checkboxes: Description: Format a set of checkboxes. #options is an associative array, where the key is the #return\_value of the checkbox and the value is displayed. The #options array cannot have a 0 key, as it would not be possible to discern checked and unchecked states.
> 1 votes

# Answer
The individual checkboxes are extracted in `form_process_checkboxes()`, so I guess something like this would work (un-tested):

```
function MYMODULE_form($form, &$form_state) {
  $options = array(1 => t('Option #1'), 2 => t('Option #2'));

  // Keyed the same as $options
  $descs = array(1 => t('Desc #1'), 2 => t('Desc #2'));

  $form['field_options'] = array(
    '#type' => 'checkboxes',
    '#options' => $options
    '#title' => t('Select Options'),
    '#description' => t('Entering a description here will display below the last item in the array'),
    '#default_value' => array(1),
    '#checkbox_descriptions' => $descriptions,
    '#process' => array('MYMODULE_process_checkbox_descriptions'),
  );

  return $form;
}

function MYMODULE_process_checkbox_descriptions($element) {
  foreach (element_children($element) as $key) {
    if (!empty($element['#checkbox_descriptions'][$element[$key]['#return_value']])) {
      $element[$key]['#description'] = $element['#checkbox_descriptions'][$element[$key]['#return_value']];
    }
  }

  return $element;
}

```
> 1 votes

# Answer
I came across this and the Accepted answer doesn't seem correct. It may work, but there is a much simpler approach. To set an individual `#description` per checkbox, you'll want to add a new item(s) to the `$form` array, using the array key you want to set the description for.

So given the original example where the array keys are `0` and `1`...

```
$form['field_options'] = array(
  '#type' => 'checkboxes',
  '#options' => array(
    0 => t('Option #1'),
    1 => t('Option #2')),
  '#title' => t('Select Options'),
  '#description' => t('Entering a description here will display below the last item in the array'),
  '#default_value' => array(0),
);

```

You will want to add the following to your `$form` array to set a description for each checkbox...

```
$form['field_options'][0]['#description'] = 'Custom description for option one (array key 0)';
$form['field_options'][1]['#description'] = 'Custom description for option two (array key 1)';

```
> 1 votes

---
Tags: forms
---


# Question
Title: Add a custom attribute to the main div of a node only on teaser view mode
I want to add a custom attribute to the main div of a node only on teaser view mode. e-g

```
<div class="node" tarbot="left"> </div>

```

I need to add **tarbot** attribute to the main div of a node to apply a JS function. I want to affect only teaser view mode with my Function, not Full content display.

# Answer
> 1 votes
We can use preprocess function to change OR add an attribute to our node main div.

```
function MYMODULE_preprocess_node(&$variables){

  // Array of aatributes which we want to pass to the node div.
  $attr_array = ['tarbot' => 'value'];

  // Condition for teaser format.
  if ($variables['teaser'] == TRUE) {

    $variables['attributes_array'] = $attr_array;
  }
}

```

by using this function we will get our node div in this form

```
<div class="node" tarbot="value"> </div>

```

# Answer
> 0 votes
In `{THEMENAME}.theme` file(d8) or `template.php` file(d7) under your theme, you can use `template_preprocess_node` function and add the extra attributes to node by checking the view mode.

Thanks

---
Tags: 7, theming
---


# Question
Title: Migrate user passwords from drupal 6 to already existing drupal 8 site
I have a drupal 6 site and a drupal 8 site. The drupal 8 site already exists and I do not want to do this on an empty drupal 8 install. Also I only want to migrate passwords. The users with their corresponding UIDs have already been brought over, and they do appear in the list of users, however their old passwords do not work on the new site. I'm assuming because drupal 8 uses a different encryption system.

I looked into using this method https://www.drupal.org/docs/8/upgrade/upgrading-from-drupal-6-or-7-to-drupal-8 based on the answers provided for this question How do I migrate user passwords? But that seems to only apply to situations when the site does not exist and I want to perform a brand new install of Drupal 8. And it supposes that I want to migrate all data when I only want to migrate the users.

Upgrading and moving over all data (nodes, block layouts, etc.) is not an option. I do not want that data in the existing drupal 8 site. I need only the users (preferably just the user passwords).

I'm willing to make a custom module to perform this import. Is there a way to migrate only the user passwords from a drupal 6 site into a drupal 8 site?

# Answer
> 2 votes
If you only want to migrate users and their passwords then you can do the same by using drush commands. Firstly you have to install certain modules: 1.Migrate Upgrade 2.Migrate Plus 3.Migrate Tools

Then you have to create a manifest.yml file at the root of your d8 site. The manifest.yml must look like this:

```
# user
- d6_user
- d6_user_profile_field
- d6_user_profile_field_instance
- d6_user_profile_entity_display
- d6_user_profile_entity_form_display
- d6_profile_values:user
- d6_filter_format
- d6_user_role
- d6_user_picture_entity_display
- d6_user_picture_entity_form_display
- d6_user_picture_file
- d6_user_picture_field
- d6_user_picture_field_instance

```

Then run the following drush command:

```
drush migrate-manifest --legacy-db url=mysql://d6user:d6pass@localhost/drupal_6 manifest.yml

```

For further information follow the following page:https://www.drupal.org/docs/8/upgrade/upgrade-using-drush

---
Tags: users, migrations
---


# Question
Title: Add Option to Centre Images on Content Pages
Currently, to align images only Right & Left options are available as shown in below image:

How to Enable full-width images similar to the link which is displaying images: https://medium.com/perspectives-from-the-economist-intelligence-unit/lake-chads-twofold-crisis-27545789e9d7

# Answer
> 0 votes
With CK Editor Module. Install CK EDITOR Image module, which enables the third alignment option to center the image also.

Here is the link to download the Module. https://www.drupal.org/project/ckeditor\_image

***Note:*** *CK EditorImage only supports for Drupal 7 and its previous versions.*

---
Tags: 7, nodes, media
---


# Question
Title: How to run jquery codes before and after ajax call?
I want to create a *loading code while the ajax call is not yet complete*, AND enable my jquery code *after calling the ajax of drupal form*. The **ajax** I'm referring to is the "**Add new field/Add more**" of unlimited field. I don't have a custom module for that. I'm just using what drupal already has.

This is the code that triggers the Ajax of the form:

```
$('input[name="field_collection_add_more"]').mousedown();

```

I can't use the `$(document).ajaxComplete(function(){}); nor ajaxStart` function of the jquery because I only want my functions to run on that specific ajax call for that specific field.

How can I use the **beforeSend:** and **success:** when the ajax **add new field** is running?

Thank you in advance for the help!

# Answer
```
/**
 * Special Effects AJAX framework command.
 */
Drupal.ajax.prototype.commands.nameOfCommand =  function(ajax, response, status) {
  alert("Hello I'm Maged Eladawy...")  ; // this will be executed after the ajax call
}

```

More details
> 0 votes

# Answer
There is a `beforeSubmit` function available on the button that fires the ajax call. The `beforeSubmit` function will fire before the ajax.

```
Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {

    // ELEMENT_ID must not include the #
    Drupal.ajax['ELEMENT_ID'].options.beforeSubmit = function(form_values, element_settings, options) {
      // code here
    };
  }
};

```

If you `console.log` your `Drupal.ajax['ELEMENT_ID'].options` you'll see there is a `success` function and a `complete` function that you can also hook into.

Try to keep everything in a Drupal behavior if possible.
> 0 votes

# Answer
You mentioned that you can't use `$(document).ajaxComplete(function(){}); nor ajaxStart`. However, I think this would be the right approach but, intead selecting the `document` you have to pass in your unique selector for desired field.

```
$('input[name="field_collection_add_more"]', context).ajaxStart(function () {
  // ...
});
$('input[name="field_collection_add_more"]', context).ajaxSuccess(function () {
  // ...
});

```

See Fade views content on views ajax pager action in Drupal 7 for a real example.
> 0 votes

# Answer
You can read that article Understanding JavaScript behaviors in Drupal. And if you want your code run after ajax call back, you need write code same example

```
Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    // Code here.
  }
};

```

> Here are some examples:
>
> * CTools calls it after a modal has been loaded.
> * Media calls it after the media browser has been loaded.
> * Panels calls it after in-placeediting has been completed.
> * Views calls it after loading a new page that uses AJAX.
> * Views Load More calls it after loading the next chunk of items.
> * JavaScript from custom modules may call Drupal.attachBehaviors() when they add or change parts of the page.
> -1 votes

---
Tags: 7, entities, javascript, ajax
---


# Question
Title: Which Rules Event in the Rules module gets triggered after clicking on a link?
If I click on a link in a node, I want to know which Rules Event in Rules gets triggered that I can use.

**Notes**:

* On the home page, there are a lot of views blocks. So in that node title (or image or whatever is being clicked), in that link, I want to use some Rules Event.
* I want to know if I click on that link, which event in Rules can be used in order to invoke. I tried Rules Event `Content is viewed`, but it didn't work.

# Answer
> 1 votes
Whatever you want to happen via Rules module when some link is clicked, if you're using Rules Event '`Content is viewed`', you'll probably be too late:

* the content (or whatever the clicked link is about) is already being shown, so if the Rules Conditions are satisfied, the Rules Actions will be performed. That is what 'Content is viewed' is all about.
* if you didn't want to content (or whatever the clicked link is about) to be visible at all, well sorry, but you're too late.

If however you did want something to happen BEFORE showing the content (or whatever the clicked link leads to), then you should use Rules Event '`Drupal is initializing`'. Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for way more details on this.

**Attention**: Rules Event '`Drupal is initializing`' gets triggered on every (repeat: every) page load in a Drupal site. So for performance reasons, you really want to limit the number of active Rules that use this Rules Event to an absolute minimum, i.e. as your last resort (if anything else fails).

# Answer
> 0 votes
Rules are invoked on the *server* side...links are clicked on the *client* side. There's a gap there that you'll need to bridge.

Two options come to mind

1. Fire your events based on the *path* that the link resolves to. This will obviously fire the event whenever the URL is visited, not necessarily just when it's been clicked through from your site.
2. Write some JS that sends an AJAX request to a custom path, and have the callback for that path invoke the event. Attach that JS to the click event handler for the links you want to track. This is probably your only option if you need to respond to a click, rather than just a certain path being visited.

---
Tags: 7, rules, navigation, subsites
---


title: Programmatically updating a node

text:
# Question
Title: Programmatically updating a node
I can create a node using the following code:

```
$node = \Drupal::entityTypeManager()->getStorage('node')->create($array);

```

But if I have the node ID, how can I *edit* a node?

# Answer
> 32 votes
You can try this code

```
<?php
use Drupal\node\Entity\Node;

$node = Node::load($nid);
//set value for field
$node->body->value = 'body';
$node->body->format = 'full_html';
//field tag
$node->field_tags = [1];
//field image
$field_image = array(
    'target_id' => $fileID,
    'alt' => "My 'alt'",
    'title' => "My 'title'",
);
$node->field_image = $field_image;

//save to update node
$node->save();

```

# Answer
> 8 votes
```
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

```

# Answer
> 8 votes
You can use the Entity's API to perform the updates.

```
$node = Node::load($id);

if ($node instanceof NodeInterface) {
  try {
    $node->set('title', 'My Title');
    $node->set('field_textfield', 'My textfield value');
    $node->save();
  }
  catch (\Exception $e) {
    watchdog_exception('myerrorid', $e);
  }
}

```

# Answer
> 1 votes
Old method works too for me:

```
$node=node_load($nid);
print_r($node->body->format);
$node->body->format='full_html';
print_r($node->body->format);
$node->save();

```

---
Tags: 8, nodes
---


title: Installing a site with composer

text:
# Question
Title: Installing a site with composer
I installed and created a Drupal site using Composer and the template in https://github.com/drupal-composer/drupal-project. I put everything I'd done in a git repository.

On a another machine, I cloned the repository and used `composer install`. It seems Composer doesn't copy the files in the web/core directory.

What am I doing wrong?

# Answer
I think there was just something strange about the directory I was using. When I swapped to a different directory and did a fresh clone and did composer install it all worked as expected. Very strange.
> 0 votes

# Answer
Maybe core is not in you `composer.json` file? So under the require section in your `composer.json` you should add: `"drupal/core": "8.4",`

Another option would be to run `composer require drupal/core` in CLI (Command Line Interface)
> 0 votes

---
Tags: composer
---


title: Export Content from Drupal to WordPress

text:
# Question
Title: Export Content from Drupal to WordPress
We're not Drupal developers and need to move the content from a Drupal site to a WordPress site.

We've already tried a plugin to help with this but it only imports a limited amount of content.

We then investigated it a little further and managed to find the Views module to export the content.

It is possible to duplicate Views which we will then rename Export To WordPress but it is not possible to convert those Views from the existing Table Format to RSS which we need to be able to import back into WordPress.

If there is a better way to do this, we would appreciate the help.

# Answer
I eventually used the Views Data Export (https://www.drupal.org/project/views\_data\_export) module and created a CSV View which I could export and then used WP All Import to import all the posts into WordPress.
> 0 votes

# Answer
You may want to try the Forena module (disclosure: I'm a co-maintainer of it) to create a "report" that includes the data that you're interested in. As part of the report design, indicate which export formats you want to allow for exporting the data included in it. Typical export formats that are supported are CSV, XML, HTML, XLS, etc.

Have a look at the Simple Table of States example, and think of it as the equivalent of your "content to be exported". And note the hyperlinks in the upper right, which are:

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).

Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.
> 0 votes

---
Tags: importing-exporting
---


# Question
Title: How to get uuid from block_content in twig template
For custom block theming I need the uuid of the `block_content`. I created the variable uuid in `mytheme.theme`:

```
function mytheme_preprocess_block(&$variables) {
   $variables['uuid'] = $variables['elements']['content']['#block_content']->uuid();
}

```

Now I get the uuid by calling `{{ uuid }}` in my `block.html.twig`. But I also get the error:

> Notice: Undefined index: #block\_content in mytheme\_preprocess\_block() AND the html is broken, it only includes the output of block.html.twig.

Is something wrong with my function. Or is there another approach?

# Answer
```
function mytheme_preprocess_block(&$variables) {
    if ( isset($variables['elements']['content']['#block_content'])) {
       $block_content = $variables['elements']['content']['#block_content'];
       $variables['uuid'] = $variables['elements']['content']['#block_content']->uuid();
    }
}

```

Now it works!

When I want to get the uuid of my custom block referenced by entity reference:

```
function mytheme_preprocess_block(&$variables) {
if ( isset($variables['elements']['content']['#block_content']))
{
    $block_content = $variables['elements']['content']['#block_content'];
    $variables['uuid'] = $variables['elements']['content']['#block_content']->uuid();
}
elseif ( isset($variables['elements']['content']['field']['0']['#block_content']))
{
    $block_content = $variables['elements']['content']['field']['0']['#block_content'];
    $variables['uuid'] = $variables['elements']['content']['field']['0']['#block_content']->uuid();
}
}

```
> 0 votes

---
Tags: hooks, theming
---


# Question
Title: Trigger download after clicking on submit on webform
I'm looking for a way on how I could download an uploaded file from the node once the user has click submit on the webform.

Here is a sample of the webform

Confirmation settings doesn't offer a setting that can download a file after trigger. I can attach link to download the file but I would like the file to trigger automatically once user submits the form

# Answer
> 1 votes
I see two ways of achieving your goal.

1. On after submit page, add a link to your file by adding the `download` attribute.

`<a href="https://i.stack.imgur.com/SUohe.png" download>Download the file</a>`

Then, add some JS to force the download.
2. You can create a webform submit Handler where you can implement advanced stuff.

# Answer
> 1 votes
May you could inject a little JavaScript into the Webform and redirect the user to the file download.

Or set the webform's confirmation redirect to point to the uploaded file.

---
Tags: 8, webforms
---


# Question
Title: How to list all the commands in Drush 9 (aka: drush help)?
I'm trying to list all the available commands by `drush help`, however I've the error:

```
$ drush help
  [Symfony\Component\Console\Exception\CommandNotFoundException]
  Command  was not found. Pass --root or a @siteAlias in order to run Drupal-specific commands.

```

It was working in Drush 8, what's the equivalent command in Drush 9?

# Answer
> 3 votes
It is clearly a bug that `drush help` is printing a meaningless error message. Instead, it should tell you how to get the list of available commands.

`drush list` is the way to do that.

---
Tags: 8, drush
---


# Question
Title: Using Entity Reference to show a view within a node
I have a content type of Authors that I want to attach to the bottom of article content type. One person will be entering all the content and they need to be able to select which author box will show at the bottom of the article.

I have been able to do this with entity reference and the display shows the rendered entity. But I have a view I would like shown instead of the rendered entity and I can not make that happen. I was able to associate the author view using the Entity Views Attachment but it associated with the UID of the account signed in when the post was created how can I instead associate it with the entity reference select list field?

# Answer
Assuming there is an entity reference field in articles that points to the content type "authors", and the view will be show on the article content type..

In your view, you should be able to add the relationship "Entity Reference: ReferencED entity" for that field name.

Then you can add your fields from the authors content type and make sure you point to the referenced entity in the field's settings.

You'll also need a contextual filter for NID "Provide default: Current Node".
> 0 votes

---
Tags: views, entities
---


# Question
Title: Errors when running Drush 9 on shared server
I'm attempting to to install Drush 9 on Media Temple (shared hosting). We have a number of Drupal 7 (D7) sites on the server, and we've just recently started to migrate them to Drupal 8 (D8). Drush is already installed globally for the D7 sites, so I created the alias "drush9" for the D8 sites, using the following line in my .bash\_profile:

```
alias drush9="~/domains/sitename.com/vendor/bin/drush"

```

But when I ran drush9 it returned this error:

```
Failed loading /usr/local/php-5.6.21/lib/php/20131226/php_opcache.so:  /usr/local/php-5.6.21/lib/php/20131226/php_opcache.so: cannot open shared object file: No such file or directory
The following restricted PHP modes have non-empty values:            [error]
open_basedir. This configuration is incompatible with drush.  Please
check your configuration settings in /home/999/etc/php.ini or in
your drush.ini file; see examples/example.drush.ini for details.
Execute a drush command. Run `drush help [command]` to view command-specific help.  Run `drush
topic` to read even more documentation.

```

I had tried to enable opcache a while ago, but apparently that library doesn't exist on the server. So, in order to eliminate this error, I disabled opcache in the php.ini.

Once disabled, I ran drush9 again, and got the following error:

```
The following restricted PHP modes have non-empty values: {open_basedir}. This configuration is incompatible with drush.  {Please check your configuration settings in /home/999/etc/php.ini or in your drush.ini file; see examples/example.drush.ini for details.}

```

After searching Stack Exchange, I found a solution to this error: Drush Open\_BaseDir Error Thus, I altered my drush9 alias as such:

```
alias drush9="/usr/bin/php5 -c ~/domains/sitename.com/vendor/bin/drush"

```

Now when I run drush9, it barks about PHP deprecations:

```
PHP Deprecated:  Comments starting with '#' are deprecated in /nfs/c11/h04/mnt/999/domains/sitename.com/vendor/drush/drush/drush on line 1 in Unknown on line 0

```

This error doesn't seem right to me. I haven't altered any of the drush files, so there shouldn't be anything wrong with them. Also, drush works perfectly in my local environment. Nonetheless, I tried replacing the "#" with a ";" and the deprecation error went away, but the drush9 command wont execute. It doesn't throw any errors, it just idles.

Is there something I'm missing? Is there a best practice for installing drush 9 on a production server? Any tips are appreciated.

In case it's useful, I'm using drupalvm on my local. Drush is installed automatically with composer when the vm is spun up. I then transported the generated drush files onto the server via git.

**Edit:** Following Greg's advice, I corrected my drush alias. It's now entered as `alias drush9='/usr/bin/php5-latest -c /home/###/etc/php.ini /home/###/domains/sitename/vendor/bin/drush`. Unfortunately, it did not solve my issue. Running drush9 now throws no errors, but the command does not successfully execute. It spins endlessly.

I've also tried installing the drush launcher. I did a wget on my server, and then I pointed the alias "drush90" to the file drush.phar file location. Running drush90 outside of site directories returns:

```
    The Drush launcher could not find a Drupal site to operate on. Please do *one* of the following:
  - Navigate to any where within your Drupal project and try again.
  - Add --root=/path/to/drupal so Drush knows where your site is located.
  - Add a site alias so Drush knows where your site is located.

```

It seems to be hooked up properly, given what it returns, but running it in a site directory doesn't work. Similar to my drush9 alias, running drush90 does not successfully run drush. It spins endlessly, failing to execute, and does not throw errors.

**Edit:** Running `drush9 -vvv -d status` outside of the website directory returns:

```
    [bootstrap] Drush bootstrap phase: bootstrapDrupalDatabase() [0.41 sec, 9.89 MB]
 [bootstrap] Successfully connected to the Drupal database. [0.41 sec, 9.89 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalFull() [0.41 sec, 9.89 MB]
 [debug] Start bootstrap of the Drupal Kernel. [0.41 sec, 9.89 MB]
 [debug] Finished bootstrap of the Drupal Kernel. [0.57 sec, 14.94 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\config\ConfigCommands [0.68 sec, 17.47 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\config\ConfigExportCommands [0.69 sec, 17.53 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\config\ConfigImportCommands [0.7 sec, 17.56 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\BatchCommands [0.7 sec, 17.59 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\CliCommands [0.7 sec, 17.6 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\DrupalCommands [0.71 sec, 17.61 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\ImageCommands [0.71 sec, 17.64 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\LocaleCommands [0.71 sec, 17.66 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\QueueCommands [0.72 sec, 17.68 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\RoleCommands [0.72 sec, 17.71 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\StateCommands [0.73 sec, 17.76 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\UserCommands [0.73 sec, 17.79 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\ViewsCommands [0.74 sec, 17.86 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\core\WatchdogCommands [0.74 sec, 17.92 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\pm\PmCommands [0.75 sec, 17.97 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\pm\ThemeCommands [0.76 sec, 18.01 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\sql\SanitizeCommands [0.76 sec, 18.02 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\sql\SanitizeCommentsCommands [0.76 sec, 18.03 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\sql\SanitizeSessionsCommands [0.76 sec, 18.05 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\sql\SanitizeUserFieldsCommands [0.77 sec, 18.06 MB]
 [debugnotify] Add a commandfile class: Drush\Drupal\Commands\sql\SanitizeUserTableCommands [0.77 sec, 18.07 MB]
 Drupal version   : 8.4.2
 Site URI         : default
 DB driver        : mysql
 DB hostname      : internal-db.s###.gridserver.com
 DB port          :
 DB username      : db###
 DB name          : db###_analytics
 Database         : Connected
 Drupal bootstrap : Successful
 Default theme    : nellek
 Admin theme      : seven
 PHP binary       : /usr/local/php-7.0.6/bin/php
 PHP config       : /nfs/c11/h04/mnt/###/etc/php.ini
                    /nfs/c11/h04/mnt/###/users/.home/.drush/drush.ini
 PHP OS           : Linux
 Drush script     : /home/###/domains/sitename/vendor/bin/drush
 Drush version    : 9.0.0-beta7
 Drush temp       : /tmp
 Drush configs    : /nfs/c11/h04/mnt/###/domains/sitename/vendor/
                    drush/drush/drush.yml
 Drush aliases    :
 Install profile  : standard
 Drupal root      : /nfs/c11/h04/mnt/###/domains/sitename/web
 Site path        : sites/default
 Files, Public    : sites/default/files
 Files, Temp      : /tmp

```

Running `drush9 cr` outside of the website directory errors out:

```
    drush9 cr

Fatal error: Uncaught TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::reset() must be an instance of Doctrine\Common\Annotations\void, none returned in /nfs/c11/h04/mnt/###/domains/sitename/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php:55
Stack trace:
#0 /nfs/c11/h04/mnt/###/domains/sitename/web/core/lib/Drupal/Component/Annotation/Plugin/Discovery/AnnotatedClassDiscovery.php(113): Doctrine\Common\Annotations\AnnotationRegistry::reset()
#1 /nfs/c11/h04/mnt/###/domains/sitename/web/core/lib/Drupal/Core/Entity/EntityTypeManager.php(106): Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions()
#2 /nfs/c11/h04/mnt/###/domains/sitename/web/core/lib/Drupal/Core/Plugin/DefaultPluginManager.php(174): Drupal\Core\Entity\EntityTypeManager->findDefinitions()
#3 /nfs/c11/h04/mnt/###/domains/sitename/web/core/lib/Drupal/Componen in /nfs/c11/h04/mnt/###/domains/sitename/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php on line 55
 [error]  Drush command terminated abnormally due to an unrecoverable error.
Error: Uncaught TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::reset() must be an instance of Doctrine\Common\Annotations\void, none returned in /nfs/c11/h04/mnt/###/domains/sitename/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php:55
Stack trace:
#0 /nfs/c11/h04/mnt/###/domains/sitename/web/core/lib/Drupal/Component/Annotation/Plugin/Discovery/AnnotatedClassDiscovery.php(113): Doctrine\Common\Annotations\AnnotationRegistry::reset()
#1 /nfs/c11/h04/mnt/###/domains/sitename/web/core/lib/Drupal/Core/Entity/EntityTypeManager.php(106): Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions()
#2 /nfs/c11/h04/mnt/###/domains/sitename/web/core/lib/Drupal/Core/Plugin/DefaultPluginManager.php(174): Drupal\Core\Entity\EntityTypeManager->findDefinitions()
#3 /nfs/c11/h04/mnt/###/domains/sitename/web/core/lib/Drupal/Componen in /nfs/c11/h04/mnt/###/domains/sitename/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php, line 55

```

# Answer
> 2 votes
You've multiple configuration issues which you should solve them one by one.

---

> ERROR 2002 (HY000): Can't connect to local MySQL server through socket `/var/run/mysqld/mysqld.sock`.

Make sure your MySQL server is up-and-running and that your socket file exists at `/var/run/mysqld/mysqld.sock`. If the service is running correctly, but your socket path is not correct, you can either change it in `php.ini` or in your settings file.

Check your SQL connection by:

```
drush sql-connect

```

and make sure you're using the right details.

Also make sure that MySQL and PHP are using the same socket file. Check by these commands:

```
mysql_config --socket
php -i | grep -w default_socket # Use /usr/bin/php5 in your case.

```

See also: I've got \`PDOException: SQLSTATE\[HY000\] \[2002\] No such file or directory\` when using drush

---

> Fatal error: Uncaught TypeError: Return value of Doctrine...

This is related that you're running your Drush under PHP 7.0.x where `Doctrine\Common\Annotations` uses syntax introduced in PHP 7.1.source

This also shows that your alias actually doesn't run Drush under PHP5.6 as you would expect.

---

> The `drush` process remains stuck.

You should run `drush` with `-vvv` (verbose) and `-d` (debug) flags to check for any issues.

If the process is still completely stuck, you can use debugger such as `strace` on Linux to find more details about it, e.g.

```
strace -f /path/to/php drush status

```

# Answer
> 3 votes
You have a typo in your alias above. The `-c` flag should be followed by the path to your php.ini file.

```
alias drush9='/usr/bin/php5 -c /path/to/php.ini ~/domains/sitename.com/vendor/bin/drush

```

---
Tags: 8, drush, installation, composer
---


# Question
Title: Installed Revisioning Module, how do you make it default to create new revision?
I just installed the Revisioning module, but all my existing nodes are set to: "Modify current revision, no moderation", but I would like it to be set as *create new revision* by default. I don't want my users to manually click this when they are editing a node.

How do I make it by default to create a new revision for *existing* nodes?

Creating *new* nodes is not an issue as its already set by default to create a new revision.

# Answer
You can alter the node edit form following the Revisioning's implementation.

```
/**
 * Implements hook_form_alter().
 */
function myModule_form_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['#node_edit_form'])) {
    if (isset($form['revision_information']['revision_operation'])) {
      $form['revision_information']['revision_operation']['#default_value'] = REVISIONING_NEW_REVISION_NO_MODERATION;
    }
  }
}

/**
 * Implements HOOK_module_implements_alter().
 *
 * Ensure our hook runs after revisioning_form_alter().
 */
function myModule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    $group = $implementations['myModule'];
    unset($implementations['myModule']);
    $implementations['myModule'] = $group;
  }
}

```
> 1 votes

---
Tags: 7, nodes
---


title: How do I set up this view?

text:
# Question
Title: How do I set up this view?
I'm using the https://www.drupal.org/project/views\_field\_view module on my Drupal 8 installation, and my current setup consists of:

* **Products** (Content Type - has an entity reference to the Product Availability taxonomy)
* **Product Availability** (Taxonomy)
* **All Products** (View - with the Product Availability view as a field)
* **Product Availability** (View)

Now, for each product displayed on my Products view I'd like to show the 'Product Availability' view fields, only for that product. For example, Product A might have the availability 1 and 2, whilst Product B may have only the availability 3. So I only want to show the availability for each product. I'm not sure how I'm supposed to set up a contextual filter for this, or if even that's the right way of doing this.

I somehow need to pass reference to my child view, Product Availability, the node ID of the product I would imagine.

Any suggestions?

**EDIT:** I've managed to get the result I wanted by going at this in a bit of a backward way. Instead of trying to configure the filter at the level of each product, I've set it up to be on the level of the Product Availability content type. Obviously this isn't as user-friendly, as to relate a 'Product Availability' to a 'Product' this way, you'll need to go into the 'Product Availability' content type and then select the products individually.

# Answer
Follow the following steps: Part one: 1. Install Views field view module and REST Export Nested (https://www.drupal.org/project/rest\_export\_nested) 2. First Create a View filtered by the content type mentioned, selecting Rest Export View. 3. Then Add nid, title and the special field Called "View" https://screencast.com/t/3la2zG6llfi 4. Duplicate this view as Rest Export Nested.

Part two:

1. Go and create another view filtered by taxonomy terms of your type(Product Availability), selecting Rest Export View.
2. Add as fields what you want to display for each term. For example, you can add the title of the term, and other fields.

I added 2 fields for example. 3. Add as the relationship the field name which is referenced to the taxonomy (Product Availability) from your content type(Products). My content type is article and it has field\_taxonomy which is a reference to the taxonomy term. 4. The last step on configuring this view is to add a contextual filter: Add "ID" and select to use the relationship created before, selecting the "Provide default value" and choosing "Content id from URL".  5. Save this view.

Return to the first view created and configure the "View" field as the print screen is showed: Choose the second view created in the "View " drop-down and o display "rest export". For contextual fields write the {{ raw\_fields.nid }} . It will work only if you were added the node id as a field in this view above the "View" field.

The result will be the following:  Node id 1 has 2 field taxonomy terms assigned: "term 1" and "term 2", and in the view object, you can see that there 2 arrays, each array represents a taxonomy term with the fields values.
> 0 votes

---
Tags: 8, views
---


# Question
Title: How to clone an existing View and change the format from table to CSV?
I have managed to figure out how to Install the Views data export module and create a View in order to export to CSV so that I can import this into WordPress.

Someone else has already created all the Views. Here is a screenprint of how the view looks like:

What I want to achieve next is to clone these views and then convert them to CSV format from a Table format. I simply cannot see how or where this can be done.

What I am trying to do is click on the "Working Papers Other" and then clone this View. Once it is cloned I am trying to change the Format from Table to CSV.

There surely has to be a way to do this easily, else it will take an eternity to do all of these Views.

# Answer
> 0 votes
Here are the steps to get you going (referring to the screenprint you added):

1. Click the drop-down list in the upper-right that says `view Working Papers Other`, where you should then see another list item with label `clone Working Papers Other`.
2. Select (click) on that list item with label `clone Working Papers Other`.
3. Note that you'll then have an extra (and same named!) button to the right (or below) the 8 buttons you already have, with the very same label `Working Papers Other`, and the newly added one will be highlighted (grey / black), and selected.
4. To improve readability, hurry to go change the line (upper-left) that says "Display name: `Working Papers Other`" (by clicking on that `Working Papers Other` link). I suggest you change the Display name to (eg) `Working Papers Other (CSV)`.
5. Change the line (upper-left) that says "Format: `Table | Settings`" (by clicking on that `Table` link). At this point you should be able to change the *style* of the view from `Table` to the Views display offered by the Views data export module, with label "`Data export`".
6. Tune (refine) the "`Settings`" of the `Data export` views display to fit your needs, whereas you can see how the result will look like in the *preview* near the bottom of your page.
7. Change the line (upper-middle) that says "Path: `/publications/working-pa..." (by clicking on that`Path`link). I suggest you change the path by only adding some suffix such as`-csv\`.
8. Don't forget to use the `Save` button (upper-left) to permanently store the updated configuration of your view.
9. Click the button (upper-right) that says `view Working Papers Other (CSV)` (if you used my suggestiuon in item "4.") to actually view (browse) the Views result produced by the various changes described above ... *Is it a CSV file that fits your requirements?* If not: must be that you did something wrong in the steps described above ...

**Note**: If you want to become more familiar with Views, checkout the (free) set of 30 video tutorials about the Views module.

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


# Question
Title: Drush 9 command equivalent to core-quick-drupal (qd)?
In Drush 8, there is a `core-quick-drupal` (`qd`) command, however, it's missing in Drush 9.

Is there any equivalent command in Drush 9 which allows to download, install and serve Drupal with minimal configuration and dependencies?

# Answer
> 3 votes
`drush qd` is not currently available in Drush 9. It would be easy enough to make a short shell script to call `composer create-project` followed by `drush site-install` and `drush uli`.

This command will probably reappear in a later release, sometime after 9.0.0 stable. A pull request that implemented `qd` would also be welcome.

---
Tags: drush, installation
---


# Question
Title: Schedule an email to be sent to new users a week after registration
I am creating a site in Drupal 8 and would like to be able to schedule an email to be sent to new users. The email should be sent automatically one week after they have registered.

In Drupal 7, I would have used Rules Scheduler to do this, but this doesn't appear to have been ported to Drupal 8 yet. Could you suggest another way that I could do this?

# Answer
> 1 votes
My way to do this is to schedule a cron job at X time. You can check here how to do this https://www.drupal.org/node/23714 or use Ultimate Cron (https://www.drupal.org/project/ultimate\_cron).

If you choose to use the Drupal core, implement hook\_cron() where you will check the users that are registered by one week ago( table users\_field\_data, column "created"). Getting all the users then it only remains to send the email. Here is an example of sending email using mail Manager:

```
$mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'module-name';
  $key = 'key1'; // Replace with Your key
  $to = \Drupal::currentUser()->getEmail();
  $params['message'] = $message; // Create this variable $message with the concret meesage.
  $params['title'] = 'Title example'; // Replace with a title.
  $langcode = \Drupal::currentUser()->getPreferredLangcode();
  $send = true;

  $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
  if ($result['result'] != true) {
    $message = t('There was a problem sending your email notification to @email.', array('@email' => $to));
    drupal_set_message($message, 'error');
    \Drupal::logger('mail-log')->error($message);
    return;
  }

  $message = t('An email notification has been sent to @email ', array('@email' => $to));
  drupal_set_message($message);
  \Drupal::logger('mail-log')->notice($message);

```

All these need to be integrated into hook\_cron() function.

---
Tags: 8, rules
---


title: Delete a file uploaded via field?

text:
# Question
Title: Delete a file uploaded via field?
Is it possible to delete a file not in usage outside of the context of a field widget in Drupal 8?

I tried to find a route like `admin/file/{file}/delete` but don't really see anything in the file module to do this operation.

I found this issue, which I assume is related. So the question remains: How can you delete files? I've set "delete orphaned files after" to **Never** in the admin so that files are not *mistakenly* deleted, which has happened to me a few months ago.

# Answer
> 0 votes
I wound up creating a solution so I wouldn't have to worry about file paths anymore, which removed the need to explicitly control the file being deleted.

Media Entity Download

Now I can set the system back to deleting orphaned files, my *actual* drive here was to preserve the file url (sites/default/files/foo.pdf) from ever changing, which introduces this conundrum.

# Answer
> 4 votes
There is no functionality for this in core in the UI. You could do a entity load + delete with drush ev/core-cli or console, but that's basically your only option.

File entity does offer a UI for this, but you possibly don't want to use it anymore.

That said, setting that setting to Never is IMHO the wrong solution, as it also doesn't delete files that were only uploaded but then for example removed again or never really submitted. See https://www.drupal.org/node/2801777 for more information and another solution for that.

That said, when using media\_entity, it should be save to configure Drupal to delete unused files as the media entity itself will always count as a usage of the file, so it will only ever get deleted if you manually delete a media entity.

# Answer
> 0 votes
Contributed Drupal module Views Bulk Operations has D8 Beta release which can help.

Install the module, edit Files view, add "Views bulk operations" global field and configure it to include "Delete selected entities" action.

The module is currently limited from an Admin point of view as it only allows the person that uploaded the file to execute the delete. Trying to do it as anyone else (including user-1) will fail (with log error message). Hopefully this limitation will be fixed in releases to come.

---
Tags: 8, entities, files
---


title: Edit the display of view on drupal 8

text:
# Question
Title: Edit the display of view on drupal 8
Currently working on theming with Twig I created a region called 'Blog Content' I placed under it a view that i recently created Called 'Blog' with a display Block to display just the 3 last article\**

for each field I specified the wrapper around it and the CSS class used by my theme and I have this output:

But i want it to be just like this:

**My questions:**

1. How to specify the tag (html) to be used to display my field with specific css class : in my case i want to display the title with
2. What field should i add to add the date of post

# Answer
1. Edit your field on which you want to add an HTML tag to a specific class.(Style settings category) See screenshot.
2. You need to add "Authored on" field and configure the display as you want to be shown.
> 1 votes

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


# Question
Title: Using Drupal to authenticate user on a remote web site
I have a custom php web site on which I need to authenticate users based on their credentials in a Drupal site. I am not very experienced with Drupal but am (mostly) finding my way. It is a Drupal 7 site.

I have found that I need the Services, Rest Server and Libraries module and they are all installed. I am using this tutorial for setting up Drupal: https://www.drupal.org/node/2424977

and this code for my remote site: Using drupal login system for another platform

I am stuck on the tutorial where I am trying to get a user token from the Drupal site. I have set up an endpoint ("rest", and when I go to it in a browser I get: "Services Endpoint "remotetest" has been setup successfully." However in the Firefox RESTClient when I try to post to https://sub.domain.org/rest/user/login.json I get:

```
Status Code: 404 Not found : Could not find resource user.
Cache-Control: no-cache, must-revalidate
Connection: Keep-Alive
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 Nov 2017 18:55:24 GMT
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.18 (Ubuntu)
X-Content-Type-Options: nosniff

```

I have tried a few things like enabling Drupal permissions for the Services module for anonymous users (all items except manage Services) but don't know what else to do. I have also tried the login directly (why would I need a token?) but I get an error "The requested URL returned error: 404 Not found : Could not find resource user." It seems like steps are missing in the tutorial.

Suggestions?

# Answer
> 0 votes
The tutorial does not indicate that you must enable the user resource in the rest service you set up. Doing so allows it to work.

---
Tags: users, services
---


# Question
Title: Programmatically append values to entity reference field of node with a dynamic field name
I understand that I can append values to an entity reference field to a node normally with this method

```
$node->field_tags[] = [
    'target_id' => $my_id,
  ];

```

However I have a function like so

```
function addTag($node,$field,$id){
$node->set($field,[
    'target_id' => $id,
  ]);
}

```

In other words I have to anticipate any field the user supplies. Looking at the node class here

https://api.drupal.org/api/drupal/core!modules!node!src!Entity!Node.php/class/Node/8.2.x

I did discover the set function that lets me specify a field and a value but I don't believe that this would append to an array of entities in a field.

How would I append to an entity reference field to a node if the field name is supplied in a variable?

# Answer
Yes, the class Node is a good starting point to look for an OOP way:

Click on get(), which returns a field object FieldItemList, where you can use the method appendItem():

```
$node->get($field)->appendItem([
  'target_id' => $id,
]);

```

Replace `->get()` with `{}` and `->appendItem()` with `[]` and you get the shorter version which @Clive mentioned in the comment:

```
$node->{$field}[] = $id;

```

This is possible because of the magic method ContentEntityBase::\__get and the ArrayAccess interface the field implements. I've also dropped `target_id`, because you don't need this for the main property of a field.
> 18 votes

---
Tags: 8, nodes
---


# Question
Title: Commerce/Feeds - Update Line Item Fields
We are attempting to add order reconciliation functionality to a Drupal Commerce site: distributors can download orders placed for their products, they update in a CSV with status of those line items, then upload that CSV again to fill in the new information (fulfillment date, quantity fulfilled, etc) on the existing line items.

Unfortunately, Feeds doesn't seem to be able to update existing line items. I have the mapping set so the line item is my unique field, which means it should update when the line item ID matches (I've used Feeds a few times before and it always works well for that). If the settings allow for creating new items, it will make new ones with new line items rather than matching. If the settings are clear to only update existing items, it will say there is nothing new so doesn't do anything.

It is relying on a dev module Feeds Entity Processor, so it might be as simple as that module being buggy, or it might be something about how line items work which doesn't allow updating.

I appreciate any help that you can give, either along this approach or if you know of a completely different way.

# Answer
Turned out to be a silly mistake on my part caused by the way Excel determined width of my CSV file. The export function was exporting with the header Line item ID, but Excel's automatic sizing cut it exactly at Line item and so I ended up filling in the mapping wrong. Sometimes you need an extra pair of eyes to help you see a simple mistake like that.

The module works with line items.
> 0 votes

---
Tags: commerce, feeds
---


# Question
Title: How is a field's value (rather than its key) obtained?
In Drupal 7, I have a page content type that has a field called **group** (so the machine name is **field\_group**). The field is a **List (integer)** field type.

This field might have allowed values as follows:

```
0|Description 1
1|Description 2
2|Description 3

```

If I want to return the key of this field for the current page, the following code correctly works:

```
field_get_items('node', $node, 'field_group')[0]['value']

```

If the key were set to 1 for this page, the above code would return 1.

However, is there a way to instead return the associated *value* (e.g., "Description 1," "Description 2," etc.)?

I thought I had a way to return the value already, but I was told yesterday that my previous method was not a good way to get the value (or key) because my previous method may return extraneous data (such as unwanted HTML), when I really just want the raw key/value itself: How is a field's key (rather than value) obtained?

# Answer
> 0 votes
As you can see, you pass to `field_get_items()` the $node parameter. This should tell you that this function will return you a value stored in this Entity. The values of your field are stored in the field itself. You can get your options array as following.

```
$fieldData = field_info_field('field_group');
$options = $fieldData['settings']['allowed_values'];

```

# Answer
> 0 votes
You can also use something like this:

```
$key = field_get_items('node', $node, 'field_group')[0]['value'];
$field = field_info_field('field_group');
$allowed_values = list_allowed_values($field);
$value = isset($allowed_values[$key]) ? $allowed_values[$key] : $key;

```

# Answer
> 0 votes
You can use `field_view_value()` for that.

```
$items = field_get_items('node', $node, 'field_group');
$value = field_view_value('node', $node, 'field_group', $items[0]);

```

---
Tags: theming, entities
---


# Question
Title: Perform action once a form has been validated
On Drupal 7, I would like to execute some code once a form has been validated.

I have seen many usage of `hook_form_FORM_ID_alter` : implementing this hook and adding a custom callback to `$form['#validate']` I could perform action *on validation*.

But I need to be absolutely sure the form ***has been validated*** to perform my actions.

Is there some other hook to do so ? Or something I could do in `hook_form_alter` to ensure that ?

# Answer
You should add a submit callback instead of a validation callback. Submit callbacks are called after the form has been validated.

```
function yourmodule_form_FORM_ID_alter(&$form, &$form_state) {
  $form['#submit'][] = 'yourmodule_custom_submit_callback';
}

function yourmodule_custom_submit_callback($form, &$form_state) {
  // Execute here your code
}

```
> 0 votes

---
Tags: 7, forms, hooks
---


title: Stemmer processor not working

text:
# Question
Title: Stemmer processor not working
I have configured Search api module in my Drupal 8 search. This is the first time I am configuring search api. I am using database search and not solr. My problem is stemmer processor is not working properly. I am not getting intended result for keywords due to stemmer processor issue. Stemmer processor is not stemming the words while indexing but is stemming while search query is executed. For example the word 'cars' is stored in the database as 'cars' itself while indexing but when a search query for 'cars' is executed it stem the word to 'car' and I am not getting the result. How can I fix this.

# Answer
> 0 votes
It seem to be a bug. I run into the same problem today, so I created an issue on the search api queue Stemmer is not working properly on indexing or on search. Please check that issue and elaborate if necessary.

---
Tags: 8, search
---


# Question
Title: jquery integration issue when attempted to execute on load
It may just my limited js experience but until recently I had some js attached to the drupal context on one of my sites to produce some small animation/style effects that took the form:

```
$(window).on("load",function() {
    //do something
})

```

This worked great until recently then suddenly stopped working with no errors or messages. Eventually I got it working by changing the above to:

```
$(document).ready(function() {
    //do something
})

```

Did something change in core or jquery that caused this? Why would there be no errors? I use the first `$(window).on()` successfully on at least two other sites but have not been able to figure out why it stopped working on this one.

Some of the js I wish to run relies on the entire page being fully loaded so I really would rather use `$(window).on()`\- which I believe triggers later.

I am using the latest release version of drupal 8

# Answer
> 2 votes
After reviewing @hugronaphor's answer. In particular this link along with some jQuery 3.x discussions regarding changes to the ready and load events my final solution was in fact to remove my code from `Drupal.behaviours`.

In the end I have implemented code in the following style:

```
(function ($, Drupal){
    $(window).on("load",function() {
        //Do something
    });
})(jQuery, Drupal);

```

This gave me reliable access to the `.on("load")` event again which is what I was after as I need the entire page to be loaded before I trigger the script.

As my script is relatively simple and doesn't need further context information I think this is fine for my use case.

I "think" the issue is related to the following change in jQuery 3.x where `on("load")` is not guaranteed to fire inside a `$(Document).ready` state any more - which is what `Drupal.behaviours` is giving you. I am something of a js noob though so will leave it to smarter people to explain why this may or may not be the case. If there is a better answer I would like to hear it.

For my simple case not being in the `Drupal.behaviour` has solved my issue.

# Answer
> 2 votes
As @Kevin mentioned

> Drupal 8.4 introduced jQuery 3.x

And according to jQuery Core 3.0 Upgrade Guide the "ready" event has been removed.

What you should do is to implement your functional code in `Drupal.behaviours`. This would have the similar effect as `$(document).ready()` but with more benefits.

```
(function ($, Drupal) {

  Drupal.behaviors.myHandler = {
    attach: function (context, settings) {
      // do something
    }
  };

})(jQuery, Drupal);

```

---
Tags: 8, javascript
---


# Question
Title: full html and ckeditor strip some meta tags
I have this code in the *field\_data\_body* table in Drupal 7 in the database:

```
<div itemprop="image" itemscope itemtype="https://schema.org/ImageObject" class="ioc" style="width: 276px; margin-right: 272px;">
 <img alt="alt" src="http://sitename.com/images/picture01/art-cinema1.jpg" title="title" />
 <meta itemprop="url" content="http://sitename.com/images/picture01/art-cinema1.jpg" />
 <meta itemprop="width" content="252" />
 <meta itemprop="height" content="190" />
</div>

```

But when I edit the content I have just this code in the body field:

```
<div class="ioc" style="width: 276px; margin-right: 272px;">
       <img alt="alt" src="http://sitename.com/images/picture01/art-cinema1.jpg" title="title" />
</div>

```

When I copy the code from database and paste it again into the editor, it shows the correct form of code but when I click the source key in CKEditor the code will change to the short form again.

In addition, when I save the content and use inspect element of Chrome browser it shows me the complete form of the code!!

So the problem is just the edit node page which just shows me a short form of code and removes all the meta tags!! How can I fix this problem?

# Answer
Please add following code in Ckeditor Javascript Settings,

```
config.allowedContent = true

```

Thanks
> 0 votes

---
Tags: 7, nodes, wysiwyg, meta-tags
---