title: Disable register email notification

text:
# Question
Title: Disable register email notification
I have made a deep research over the web and I also tried a lot of alternative solutions, but I didn't find any solution to disable the email notification for new users.

In my User Settings, I have the option "Visitors can create accounts but administrator approval is required" checked, and the option "Require e-mail verification when a visitor creates an account" not checked.

Do you have any idea?

# Answer
If you look at the function \_user\_email\_notify(), it checks the variable `'user_mail_' . $op . '_notify'` if it should send an email or not. Assuming that you have disabled email confirmation (otherwise, disabling mail notifications would be weird ;)), the $op is `'register_no_approval_required'`. So the full variable name is `'user_mail_register_no_approval_required_notify'`.

There doesn't seem to be a User Interface for that variable. However, you can set it in your settings.php, adding the following line at the end of settings.php (probably inside sites/default).

```
$conf['user_mail_register_no_approval_required_notify'] = FALSE;

```

You can do the same for other mail notifications too; the other possible `$op` values are listed on the linked page.
> 30 votes

# Answer
You can use the Mailcontrol module.

It allows you to turn on/off any standard Drupal mail you wish right from the UI.

> Have full control over the default mails sent by Drupal 7 out of the box.
>
> ### Description
>
> This small module extends original Drupal 7 account settings page with the ability to globally turn ON/OFF all standard mails. By default Drupal 7 provides no option to globally disable the following mails:
>
> * Welcome (new user created by administrator)
> * Welcome (awaiting approval)
> * Welcome (no approval required)
> * Password recovery
> 8 votes

# Answer
In Drupal 8, the the equivalent of the code given from Berdir for the settings.php file is the following one.

```
$config['user.settings']['notify.register_no_approval_required'] = FALSE;

```
> 5 votes

# Answer
You can use this in a custom module to add the settings in a checkbox as it is done in account activation settings.

```
function your_module_form_user_admin_settings_alter(&$form, &$form_state) {

  // allow admin to choose if a notification mail is sent to no approval required users
  form['email_no_approval_required']['user_mail_register_no_approval_required_notify'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user when account is created.'),
    '#default_value' => variable_get('user_mail_register_no_approval_required_notify', FALSE),
  );
}

```
> 4 votes

# Answer
In Drupal 7:

You can edit the variable table directly: name: user\_mail\_status\_activated\_notify value: i:0;

or in your template.php file:

```
if(variable_get('user_mail_status_activated_notify') == 1){
    variable_set('user_mail_status_activated_notify', 0);
}

```
> 4 votes

# Answer
There is a checkbox to disable at admin/user/user/create. For me, it's disabled by default.
> 1 votes

# Answer
**For Drupal 8 following work for me.**

The following code does not send an email after registration.

```
/**
 * Implements hook_mail_alter().
 *
 * Don't send any mail during registration.
 */
function mymodule_mail_alter(&$message) {
  if ($message['id'] == 'user_register_no_approval_required' && $message['key'] == 'register_no_approval_required') {
      $message['send'] = FALSE;
      return;
  }
}

```
> 1 votes

---
Tags: users
---


# Question
Title: How to delete all nodes referencing a given one?
I'm working on a catalog based on Drupal Commerce. I have a product display content type referencing product entities. I'm thinking about the ways to make life of a content manager easier.

I made a rule which fires when product is created and creates a corresponding Product display. But I can't figure out the best way to delete a product display nodes when the product is deleted.

Till now I've tried VBO, but seems in Drupal 7 rules2 lacks the ability to run VBO actions.

I guess a quick and dirty solution is to write a module for this task, but I'm looking for something more elegant. Any ideas?

# Answer
I think a "quick and dirty" module would be the more elegant way. I did something similar recently in drupal 6 with ubercart. I have a content type that sometimes needs to be associated with a product and sometimes doesn't. When one of the custom nodes is deleted, if it has a product associated with it, that needs to be removed as well:

```
your_module_nodeapi(&$node, $op) {
  if($op == 'delete') {
    $product_nid = db_result(db_query('SELECT nid FROM {content_type_product} WHERE field_product_list = %d', $node->nid));
    if(!empty($product_nid)) {
      node_delete($product_nid);
    }
  }
}

```

In this case, field\_product\_list was a node reference field added to the product. I'm sure something similar would work in your case.
> 4 votes

# Answer
Just to add to @David\_L's answer, and extending the scenario of the problem.

* The example below makes use of EntityFieldQuery.
* I point out that nested entity references can be handled hook\_node\_delete() by simply adding another IF, there is no need to write a sub-loop as the hook is called for each deletion.

```
<?php
function mymodule_node_delete($node) {
    if ($node->type == 'product'){// if a product is being deleted

        $query = new EntityFieldQuery();
        $result = $query->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'product_display')
                        ->fieldCondition('field_product', 'target_id', $node->nid)
                        ->execute();
        if(!empty($result['node'])){
            $nids = array_keys($result['node']);
            node_delete_multiple($nids);
        }
    }

    if ($node->type == 'product_display'){// if a product's display is being deleted

        $query = new EntityFieldQuery();
        $result = $query->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'product_display_child')
                        ->fieldCondition('field_product_display', 'target_id', $node->nid)
                        ->execute();
        if(!empty($result['node'])){
            $nids = array_keys($result['node']);
            node_delete_multiple($nids);
        }
    }
}
?>

```
> 0 votes

# Answer
This might not be the best solution but I am using the below: Also, you can do delete mutiple.

```
    /**
     * Implements hook_node_delete().
     */
    function my_module_node_delete($node) {
      // Gets the node type for the newly deleted node.
      $node_type = $node->type;
      $node_id = $node->nid;
      // Everything happens only if the node is
      // of type mytype.
      if ($node_type == 'mytype') {
        // Find all nodes that reference this node in the custom import reference field.
        // the table name is for the field that keeps the reference.

        $find_nodes = db_select('field_data_field_import_reference', 'f')
          ->fields('f', array('entity_id'))
          ->condition('f.bundle', 'myotherbundle', '=')
          ->condition('f.field_import_reference_target_id', $node_id, '=');

        try {
          // Execute query.
          $resulting_nodes = $find_nodes->execute()->fetchAll();
        }
        catch (Exception $e) {
          // Or catch exception.
          $error_message = $e->getMessage();
          watchdog('mymodule', $error_message);
        }
        // If we have nodes to delete.
        if (isset($resulting_nodes)) {
          // Get the nid for each.
          foreach ($resulting_nodes as $delete_node) {
            // Delete by nid.
            node_delete($delete_node->entity_id);
          }
        }
      }
    }

```
> 0 votes

# Answer
The following has been borrowed from here.

Insert the following into your custom module.

```
/**
 * Implements hook_node_delete().
 */
function mymodule_node_delete($node) {
  if ($node->type == 'mynodetype'){
    $nids = db_query('SELECT entity_id FROM {field_data_field_review_reference} WHERE field_review_reference_nid = :nid', array(':nid' => $node->nid))->fetchCol();
    node_delete_multiple($nids);
  }
}

```
> -1 votes

---
Tags: 7, nodes, rules, commerce
---


# Question
Title: Drush does not run command, but prints the php script
We have a special server that runs php5.x and relies on drush 5.x. PHP 7.0 is installed, but the sites on the server all run PHP5, because PHP7 breaks them.

We have previously had drush 5 on it, but it didn't work anymore for some reason. So what I did was download drush 5, and and made an alias like so:

`alias drush5="/usr/bin/php5 /home/user/drush/drush5/drush"`

Running `drush5` does result in listing the commands, so I have done something right. But whenever I run `drush5 up module_name`, instead of actually running the update php script, it prints its code out. Example below.

Instead of returning with an error or actually running the script, it just prints out the code. What do I do in this case? I cannot find anything on this on neither google nor duckduckgo.

```
server:/var/www/site/webroot# drush5 up module_name
# $Id$
#
# This script is a simple wrapper that will run Drush with the most appropriate
# php executable it can find.
#
# Solaris users: Add /usr/xpg4/bin to the head of your PATH
#

# Get the absolute path of this executable
SELF_DIRNAME="`dirname -- "$0"`"
SELF_PATH="`cd -P -- "$SELF_DIRNAME" && pwd -P`/`basename -- "$0"`"

# Decide if we are running a Unix shell on Windows
if [ `which uname` ]; then
  case "`uname -a`" in
    CYGWIN*)
      CYGWIN=1 ;;
    MINGW*)
      MINGW=1 ;;
  esac
fi

# Resolve symlinks - this is the equivalent of "readlink -f", but also works with non-standard OS X readlink.
while [ -h "$SELF_PATH" ]; do
    # 1) cd to directory of the symlink
    # 2) cd to the directory of where the symlink points
    # 3) Get the pwd
    # 4) Append the basename
    DIR="`dirname -- "$SELF_PATH"`"
    SYM="`readlink $SELF_PATH`"
    SYM_DIRNAME="`dirname -- "$SYM"`"
    SELF_PATH="`cd "$DIR" && cd "$SYM_DIRNAME" && pwd`/`basename -- "$SYM"`"
done

# Build the path to drush.php.
SCRIPT_PATH="`dirname "$SELF_PATH"`/drush.php"
if [ -n "$CYGWIN" ] ; then
  SCRIPT_PATH="`cygpath -w -a -- "$SCRIPT_PATH"`"
fi

# If not exported, try to determine and export the number of columns.
# We do not want to run `tput cols` if $TERM is empty or "dumb", because
# if we do, tput will output an undesirable error message to stderr.  If
# we redirect stderr in any way, e.g. `tput cols 2>/dev/null`, then the
# error message is suppressed, but tput cols becomes confused about the
# terminal and prints out the default value (80).
if [ -z $COLUMNS ] && [ -n "$TERM" ] && [ "$TERM" != dumb ] && [ -n "`which tput`" ] ; then
  # Note to cygwin/mingw/msys users: install the ncurses package to get tput command.
  # Note to mingw/msys users: there is no precompiled ncurses package.
  if COLUMNS="`tput cols`"; then
    export COLUMNS
  fi
fi

if [ -n "$DRUSH_PHP" ] ; then
  # Use the DRUSH_PHP environment variable if it is available.
  php="$DRUSH_PHP"
else
  # On MSYSGIT, we need to use "php", not the full path to php
  if [ -n "$MINGW" ] ; then
    php="php"
  else
    # Default to using the php that we find on the PATH.
    # We check for a command line (cli) version of php, and if found use that.
    # Note that we need the full path to php here for Dreamhost, which behaves oddly.  See http://drupal.org/node/662926
    php="`which php-cli 2>/dev/null`"

    if [ ! -x "$php" ]; then
      php="`which php 2>/dev/null`"
    fi

    if [ ! -x "$php" ]; then
      echo "ERROR: can't find php."; exit 1
    fi
  fi
fi

# Check to see if the user has provided a php.ini file or drush.ini file in any conf dir
# Last found wins, so search in reverse priority order
for conf_dir in "`dirname "$SELF_PATH"`" /etc/drush "$HOME/.drush" ; do
  if [ ! -d "$conf_dir" ] ; then
    continue
  fi
  # Handle paths that don't start with a drive letter on MinGW shell. Equivalent to cygpath on Cygwin.
  if [ -n "$MINGW" ] ; then
    conf_dir=`sh -c "cd "$conf_dir"; pwd -W"`
  fi
  if [ -f "$conf_dir/php.ini" ] ; then
    drush_php_ini="$conf_dir/php.ini"
  fi
  if [ -f "$conf_dir/drush.ini" ] ; then
    drush_php_override="$conf_dir/drush.ini"
  fi
done
# If the PHP_INI environment variable is specified, then tell
# php to use the php.ini file that it specifies.
if [ -n "$PHP_INI" ] ; then
  drush_php_ini="$PHP_INI"
fi
# If the DRUSH_INI environment variable is specified, then
# extract all ini variable assignments from it and convert
# them into php '-d' options. These will override similarly-named
# options in the php.ini file
if [ -n "$DRUSH_INI" ] ; then
  drush_php_override="$DRUSH_INI"
fi

# Add in the php file location and/or the php override variables as appropriate
if [ -n "$drush_php_ini" ] ; then
  php_options="--php-ini $drush_php_ini"
fi
if [ -n "$drush_php_override" ] ; then
  php_options=`grep '^[a-z_A-Z0-9.]\+ *=' $drush_php_override | sed -e 's|\([^ =]*\) *= *\(.*\)|\1="\2"|' -e 's| ||g' -e 's|^|-d |' | tr '\n\r' '  '`
fi
# If the PHP_OPTIONS environment variable is specified, then
# its contents will be passed to php on the command line as
# additional options to use.
if [ -n "$PHP_OPTIONS" ] ; then
  php_options="$php_options $PHP_OPTIONS"
fi

# Always disable magic_quotes_gpc and friends
php_options="$php_options -d magic_quotes_gpc=Off -d magic_quotes_runtime=Off -d magic_quotes_sybase=Off"

# Pass in the path to php so that drush knows which one to use if it
# re-launches itself to run subcommands.  We will also pass in the php options.
# Important note: Any options added here must be removed  when Drush processes
# a #! (shebang) script.  @see drush_adjust_args_if_shebang_script()
exec "$php" $php_options "$SCRIPT_PATH" --php="$php" --php-options="$php_options" "$@"

```

# Answer
> 1 votes
I found a solution to this.

**NOTE:** This way is ***NOT*** recommended. Get your modules updated to support supported PHP versions!

1. `wget https://github.com/drush-ops/drush/archive/5.10.0.tar.gz` or if you'd rather want a zip file: `wget https://github.com/drush-ops/drush/archive/5.10.0.zip`.
2. Uncompress downloaded file: `tar -zxvf 5.10.0.tar.gz` or with zip `unzip 5.10.0.zip`
3. Move to a drush folder, in case you have multiple versions: `mv 5.10.0 /path/to/drushes/drush5`
4. Make a symlink into your path and name it "drush5" `ln -s /path/to/drushes/drush5/drush /usr/local/bin/drush5`
5. Move to your document root `cd /path/to/docroot/`
6. And run `drush5` there: `drush5 up module_name`

In my case, PHP CLI ran PHP 7.0 which appeared to work for drush5, but apparently not for the sites. I find this very peculiar, but as mentioned in one of the comments, the setup is undesirable.

This should be a *temporary* solution *if* this is strictly needed. Make sure to keep your drupal sites and modules up to date with newer PHP version; not only will this make your site better, but it will make developers and operators happy, because of ease of maintenance.

---
Tags: drush, updating
---


# Question
Title: How to use media field with entity browser widget in a frontend theme?
I have created a media field in my content type. In the `manage form display`, I have selected `entity browser` as display instead of `media library`.

When I open the node form as admin in an admin theme like adminimal or seven, and upload an image to the field, I can see it thumbnail after upload and other information. I can see that its markup comes from the `media.html.twig` file of the `classy` theme.

But when I do the same steps in a frontend theme, I can't see the thumbnails and other information after upload.

What can be the reason? I also copied the `media.html.twig` file from `classy` theme to my custom theme but it did not work.

I am also using the `dropzonejs` module if that help someone.

Here are the screen shots. The first screenshot is from the admin theme, You can see that the admin, the date, the thumbnail and then use selected button.

The 2nd screenshot is from the frontend theme, there is no such markup after uploading an image.

Any one who can help?

# Answer
I found the solution.

I just copied the `media.html.twig` template from classy theme to my custom theme which did not work.

We need to copy this file also `container.html.twig` to our custom theme's templates directory then it will work.
> 1 votes

# Answer
You can configure thoses fields by doing some backend work, as you said you are using dropzone, please have a at their webpage dropzonejs where you can find a documentation and also it gives you link to use it up to your tech! Here an example of I use it in a form :

```
$form['photo_principale'] = [
  '#type' => 'dropzonejs',
  '#title' => $this->t('English title'),
  '#dropzone_description' => $this->t('English deceiption'),
  '#max_filesize' => $this->t("256"),
  '#extension' => $this->t("jpg jpeg png"),
  '#max_files' => 1,
  '#clickable' => TRUE,
  '#clientside_resize' => FALSE,
];

```
> 0 votes

---
Tags: 8, media
---


# Question
Title: Problem w/ Migrate Source CSV importing Body content w/ HTML
I am using migrate\_source\_csv to import node body fields. The header for my CSV file is: "nid, title, body". The body fields contain HTML. My problem is that, on import, the HTML is being encoded into literals. See the screen grab below. Here is my migration YML file:

```
id: news_article_nodes
label: News article data we want.
migration_group: gdg_group
source:
  plugin: csv
  path: 'modules/custom/gdg_migration/import/news_article/news_articles.csv'
  ids: [nid]
  header_row_count: 1
process:
  nid: nid
  title: title
  'body/0/value': body
  'body/0/format':
    plugin: default_value
    default_value: full_html
destination:
   plugin: entity:node
   overwrite_properties:
     - body
   default_bundle: news_article

```

I must be missing something. Is there a plugin that imports the data as plain text?

# Answer
You could try to use PHP's `html_entity_decode()` on the source field:

```
process:
  nid: nid
  title: title
  body/value:
    plugin: callback
    callable: html_entity_decode
    source: body
  body/format:
    plugin: default_value
    default_value: full_html

```

PS: You've written that your source CSV doesn't contain encoded entities... have you checked the display settings for your field? (`Manage > Structure > Content types > NODE_TYPE > Manage display`). It could be that the import is correct, but the render settings are incorrectly set to something like plain text or a `|raw` filter in a Twig template file.
> 2 votes

# Answer
you have just to remove de /0/ from body field

```
 body/value: body
 body/format:
  plugin: default_value
  default_value: full_html

```
> -1 votes

---
Tags: migrations
---


# Question
Title: Warning message and URLs not found on menu items
My question is in relation to a Mamp issue Im having.

Installed Mamp on my MacBook, loaded the database off my live Drupal 7 site, downloaded and copied the Drupal files on the live site to Mamp htdocs, changed the Drupal config settings (db, host, user, password) to use Mamp site, but it displays the home page, with the warning messages below, and if you click on any menu item it displays URL not found. Any ideas what Im doing wrong?

Ive tried using the latest Drupal 7 core, and also using the same Drupal files as the live site, but I get the same result.

Warning message on Home page:

```
Warning: "continue" targeting switch is equivalent to "break".
Did you      mean to use "continue 2"? in require_once()
(line 341 of  /Applications/MAMP/htdocs/rltc/includes/module.inc).

```

# Answer
> 0 votes
The warning looks like a PHP incompatibility. So either fix the code that's been triggering it (and at best provide a patch for it on drupal.org) or change MAMP's PHP version. Probably to something lower as it is now.

The URL not found error looks like as if you misconfigured your `.htaccess` file. Ensure this file exists and maybe uncomment the following line.

```
RewriteBase /

```

---
Tags: 7
---


# Question
Title: How to make expandable text on clicking more button in views?
I have created a views with trimmed fields and displaying more button to show the full content.I want to do something like collapse text ie.,when i click on more button it has to expand and show the full text.Any help will be much appreciated on how to do this.Thanks in advance.

# Answer
This will require some custom theming to accomplish:

1. In your view, don't trim the field, just show it all for now. This will mean if a user has JavaScript disabled they will still have access the all the content.
2. In order to enhance the interface as you've described for users with JavaScript enabled, you should take a look at this tutorial.
3. You will have to tweak things to get it working with your theme. If you're unsure about adding Javascript to a theme, check this out.
> 3 votes

# Answer
You could use CSS :active.

Something like this:

Styles:

```
.more-link p {display: none;}
.more-link:active p {display: block;}

```

HTML:

```
<a href="#" class="more-link">
<p>Hidden text</p>
</a>

```

It is possible to use CSS transition to show text block smoothly.
> 1 votes

# Answer
There's a contributed module that does this, Readmore. The other answers explain how to set this up yourself, but that's no longer necessary.

I've adding feature request to have this functionality added to Drupal Core. See Allow for expandable text with "Read more/less" links in Default field formatter for details. Patches welcome!
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I alter a view query to use "OR"?
The following is the content of the `$query` object that is passed to a view.

```
[where] => Array(
  [0] => Array(
    [clauses] => Array(
      [0] => node.type in ('%s')
      [1] => node.status  0
      [2] => node.promote  0
      [3] => node.sticky  0
    )
    [args] => Array(
      [0] => test
    )
    [type] => AND
  )
)
[having] => Array()
[group_operator] => AND

```

I want to override it by using `hook_views_query_alter()`. The default operators are all AND, but I want to get the following query

```
[0] => node.type in ('%s') AND
[1] => node.status  0 AND
[2] => node.promote  0  OR
[3] => node.sticky  0

```

How do I make the last operator to use "OR"?

```
db_query("SELECT content_id, count(*) AS cnt FROM {votingapi_vote} WHERE value =1 AND value_type = '%s'" , "option");

```

How do I use the query in hook\_views\_query\_alter()?

# Answer
> 3 votes
This is untested, but I think what you want to do within your alter function is along the lines of this:

```
function mymodule_views_query_alter(&$query) {
  unset($query->where[0]['clauses'][2]);
  unset($query->where[0]['clauses'][3]);

  $query->where[1] = array(
    'clauses' => array(
      0 => 'node.promote <> 0',
      1 => 'node.sticky <> 0',
    ),
    'type' => 'OR',
  );
}

```

This is essentially moving the promote and sticky clauses into a new where grouping, and by setting the type to 'OR', it should work the way you outline in your question.

# Answer
> 2 votes
I think you can use db\_or, for example if you are creating a new where clause you can use something like this

```
function mymodule_views_query_alter(&$query) {
  if ('name' == $view->name && 'page' == $view->current_display) {
    $or = db_or()
    ->condition('table.column', $value, 'NOT IN')
    ->condition('table.column', $value, 'NOT IN');
    $query->add_where(1,$or);
  }
}

```

For your problem you may need to use foreach and find the exact case to use db\_or

# Answer
> 0 votes
I realize this is old but I thought I'd answer it for anyone who needs it.

Views 7.x-3.x. does this through the UI. You simply add the filters and then through the filter UI, you can order the filters and add additional groups of filters that you can arrange in AND or OR relationships.

In this case I would add a second group in an AND relationship with the first group but with an OR relationship with the contents of the group, which would consist of: node.promote \<\> 0 OR node.sticky \<\> 0.

---
Tags: 7, views, hooks, database
---


# Question
Title: Running "composer update" leads to errors with coder
```
...
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating drupal/coder (8.2.12 => 8.3.1)    The package has modified files:
    D coder_sniffer/Drupal/Test/Array/ArrayUnitTest.inc
    D coder_sniffer/Drupal/Test/Array/ArrayUnitTest.inc.fixed
    D coder_sniffer/Drupal/Test/Array/ArrayUnitTest.php
    D coder_sniffer/Drupal/Test/Array/DisallowLongArraySyntaxUnitTest.php
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d7/DisallowLongArraySyntaxUnitTest.1.inc
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d7/disallow_long_array_d7.info
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d8/DisallowLongArraySyntaxUnitTest.2.inc
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d8/DisallowLongArraySyntaxUnitTest.2.inc.fixed
    D coder_sniffer/Drupal/Test/Array/disallow_long_array_d8/disallow_long_array_d8.info.yml
    D coder_sniffer/Drupal/Test/Classes/ClassCreateInstanceUnitTest.inc

  [ErrorException]
  A non-numeric value encountered

```

I have tried with errors

```
$ composer require drupal/coder ^8.3
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package symfony/debug (locked at v4.1.7, required as ^3.4.0) is satisfiable by symfony/debug[v4.1.7] but these conflict with your requirements or minimum-stability.
  Problem 2
    - Conclusion: remove doctrine/annotations v1.6.0
    - Conclusion: don't install doctrine/annotations v1.6.0
    - Can only install one of: doctrine/annotations[v1.2.0, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.1, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.2, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.3, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.4, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.5, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.6, v1.6.0].
    - Can only install one of: doctrine/annotations[v1.2.7, v1.6.0].
    - Installation request for doctrine/annotations (locked at v1.6.0, required as ^1.2) -> satisfiable by doctrine/annotations[v1.6.0].
    - Installation request for doctrine/annotations 1.2.* -> satisfiable by doctrine/annotations[v1.2.0, v1.2.1, v1.2.2, v1.2.3, v1.2.4, v1.2.5, v1.2.6, v1.2.7].

Installation failed, reverting ./composer.json to its original content.

```

Also tried with errors

```
rm vendor/ -rf
composer update
....
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package doctrine/annotations 1.2.* exists as doctrine/annotations[v1.6.0] but these are rejected by your constraint.

```

but always end up with other errors Any thoughts ?

# Answer
> 2 votes
What worked is the following commands

```
rm composer.lock
rm vendor -rf
composer clear-cache
composer require --dev drupal/coder
composer update

```

with last command perhaps not needed as the previous composer command does an implicit `update`

# Answer
> 1 votes
You should not really rm anything it is not required.

> composer remove drupal/coder composer require --dev drupal/coder

Also for a bonus point it's often a good idea to include the hash in the composer file incase an unstable dev is released you won't have to worry about changes that have come after.

---
Tags: 8, updating, composer
---


# Question
Title: In views use the value of a field in next row, in current row
I would like to use the value of a field in row 2 of a views table output, in row 1 so that I can do some basic math on it.

This is what I would like to do:

1. Title | Field\_x | Field\_y+Field\_y(2) | Field\_z
2. Title | Field\_x | Field\_y+Field\_y(3) | Field\_z
3. Title | Field\_x | Field\_y+Field\_y(4) | Field\_z
4. Title | Field\_x | Field\_y+Field\_y(5) | Field\_z
5. Title | Field\_x | Field\_y+Field\_y(6) | Field\_z
6. Title | Field\_x | Field\_y | Field\_z etc.

I've looked at every views solution I could find and every module without any luck.

Any idea how I can achieve this would be amazing.

# Answer
I think you can do this in a hook\_views\_pre\_render function.

I wrote a little code example that I think would solve your problem.

Basically it loops over the rows and sets the value based on the previous row's field and the current row's field.

```
function MY_MODULE_views_pre_render($view) {
  if (
    $view->name == 'YOURVIEW' &&
    $view->current_display == 'YOUR_DISPLAY'
  ) {
    // By default prev. row is the first one.
    $previous_row = $view->result[0];
    // Loop through all rows.
    foreach ($view->result as $row) {
      // Do some calculation based on the current and previous row.
      $row->YOUR_FIELD[...]['value'] = $row->YOUR_FIELD[...]['value'] - $previous_row->YOUR_FIELD[...]['value'];
      // Set the prev. row.
      $previous_row = $row;
    }
  }
}

```

`...` is probably `[LANGUAGE_NONE][0]` (I'm not sure), so you must debug the `$row` variable to see where the values are saved.
> 2 votes

---
Tags: 7, views
---


title: Remove Simplenews Newsletters?

text:
# Question
Title: Remove Simplenews Newsletters?
I had set a content type to allow it to be used as a simplenews newsletter, and then updated the JSON Feeds Processor so that it filled in the simplenews category for all the items.

However after realizing this wasn't what I needed, I removed the field simplenews from the content type and removed the option "use as newsletter" too, but all the newsletters still show up in the admin page.

I want to delete all of these old newsletters but there doesn't seem to be any option in the module to do that ?

# Answer
> 0 votes
Inorder to remove Simple newsletter completely. You need to disable and uninstall the module.

Follow the steps

1. Go to Modules list (`admin/modules`) and uncheck simplenews letter to disable and click 'Save Configuration' to disable the module
2. Then Go to `admin/modules/uninstall` page and select/check the simplenews letter module and click 'Uninstall' to remove all data related to Simplenews letter module from your instance.

# Answer
> 0 votes
To Uninstall Simplenews you must delete Simplenews data first. Go to /admin/config/services/simplenews/settings/uninstall then click "Delete Simplenews data".

---
Tags: 7, emails
---


# Question
Title: Is it possible to get the node ID of the node that will be created?
Trying to pass some information to third party API, every time a new node is created.

So far I have managed to identify the node insert/create when a node is created in `hook_node_presave()`. Done it by using `empty($node->id())`.

Now I want to anticipate what the node ID will be once the node is saved. Is it possible to get the node ID before the node is created?

# Answer
> 2 votes
You can use `hook_ENTITY_TYPE_insert` which is called after the node has been saved.

Function description:

> This hook runs once the entity has been stored. Note that hook implementations may not alter the stored entity data.

---
Tags: 8, nodes
---


# Question
Title: How to set the views exposed filters default value programmatically?
I have a view which has a term reference exposed filter.

I want to set the default values of this exposed filter programmatically based on a certain condition.

I have tried the following code but the values are not selected in the filter.

```
function example_views_pre_build(&$view) {
  if ($view->name == 'events') {
    $tids = array(5, 6);
    foreach (tids as $tid) {
      $view->display[$view->current_display]->handler->handlers['filter']['field_category']->value[$tid] = $tid;
    }
  }
}

```

AND

```
function example_views_pre_view(&$view, &$display_id, &$args) {
      if ($view->name == 'events') {
        $tids = array(5, 6);
        foreach (tids as $tid) {
          $view->display[$view->current_display]->display_options['filters']['field_category']->value[$tid] = $tid;
        }
      }
    }

```

I also tried with `form_alter`, in form alter the values gets selected in the filter but then it does not display correct results after removing/applying again the filter.

# Answer
> 1 votes
```
function example_views_pre_build(&$view) {
    if ($view->name == 'VIEW_NAME') {
        $view->display[$view->current_display]->handler->handlers['filter']['field_country_tid']->value = array(55, 91);
    }
}

```

This code worked for me. Check your views module version as well. I am using Views 7.x-3.14.

# Answer
> 0 votes
I used this for multiple value filter (D7):

```
function MY_MODULE_views_pre_build(&$view) {
  if ($view->name == 'VIEW_NAME') {
    $view->filter['FIELD_NAME']->value = array('nouveau', 'pending', 'complete', 'waitlist', 'held', 'canceled');
  }
}

```

---
Tags: 7, views
---


# Question
Title: How to create a view that shows a Managing User all content of their members?
I want to create a View that lists all content of authors who have the same value (text) as the viewing user. Actually they are members and the viewing user is the manager of the members. I have 2 profile fields that I think could be used to show the desired results:

1) an entity reference field called "field\_ca\_reference" to allow a member to reference a manager

2) a text field is set upon member verification that has the exact same value on both the member and the manager

How do I set up this view such that the manager sees all content of their members only?

# Answer
First of all create a view of all content.

Next, add a relationship to the author of the content. Call the relationship author. Check 'require this relationship'.

Next, add a contextual filter on the entity reference field to the manager, using the author relationship. Under 'When the filter is not available' select 'Provide a default value', and choose 'User ID from logged in user'.

Let me know if it works for you.

I've added an image of my view for you:

And here is an export of my view - you should be able to import this and it will just work:

```
$view = new view();
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Test';
$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'] = 'Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$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'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: CA reference (field_ca_reference) */
$handler->display->display_options['arguments']['field_ca_reference_target_id']['id'] = 'field_ca_reference_target_id';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['table'] = 'field_data_field_ca_reference';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['field'] = 'field_ca_reference_target_id';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['relationship'] = 'uid';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_ca_reference_target_id']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

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

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: Make a password security check for the register form
I have a register form that is output in a controller using the following code.

```
 $form = $this->getUserProfileForm();

    return [
      '#theme' => 'maubl_user_inscription',
      '#form' => $form,
    ];
  }

  protected function getUserProfileForm() {
    $entity = \Drupal::service('entity.manager')
      ->getStorage('user')
      ->create(array());

    $formObject = \Drupal::service('entity.manager')
      ->getFormObject('user', 'default')
      ->setEntity($entity);

    $form = \Drupal::formBuilder()->getForm($formObject);

    return $form;
  }

```

In a custom module, I'm using the following code to alter the password.

```
function maubl_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $formState) {
  $form['actions']['submit']['#submit'][] = 'maubl_user_form_login_after_registration';
  $form['account']['pass']['#process'][] = 'maubl_user_form_user_register_form_process_pass';
}

function maubl_user_form_user_register_form_process_pass(&$element, \Drupal\Core\Form\FormStateInterface $form_state, &$complete_form) {
  $element = \Drupal\Core\Render\Element\PasswordConfirm::processPasswordConfirm($element, $form_state, $complete_form);
  $element['pass1']['#placeholder'] = t('Password');
  $element['pass2']['#placeholder']= t('Confirm pwd');
}

```

Yet, any password would be accepted as long as they are the same. I want something like password\_confirm to check if there are special characters, special length etc, but I couldn't figure out how to make it works.

When I try to use the following code, nothing happens.

```
function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['account']['pass']['#process'][] = 'mymodule_form_user_register_form_process_pass';
}

```

# Answer
> 5 votes
It seems like you might want to look into the Password Policy module which probably has a lot of the features you are trying to rebuild.

I also wonder whether it makes sense to build your own user inscription form instead of altering the existing core registration form. Altering forms tends to result in easier integrations with existing modules.

---
Tags: 8, forms, security
---


# Question
Title: Mock a service while running a BrowserTest?
I am trying to test the output of a controller that returns some information in a given page. This controller has a custom http client injected into it.

I want to create a BrowserTest that can navigate to a fake node, and then test for certain text or values. I also want to change the mock to return different values, so I can further test the output to account for those cases.

I tried:

```
    $client = $this->getMockBuilder('\Drupal\mymodule\Client\AuthorizeClient')
      ->disableOriginalConstructor()
      ->getMock();
    $client->expects($this->any())
      ->method('request')
      ->with('w12345', FALSE)
      ->willReturn([]);

    $this->container->set('mymodule.auth_client', $client);

```

But I get errors in the test that refer to the original class, and not the one I am trying to replace. I looked around in the core but wasn't really able to find what I was looking for. Does it make sense to do this? Is there a way to do a Kernel test to test responses from the route in question?

# Answer
> 1 votes
I could not quite get my mocked service to be used from the container as per the docs, so I resulted to doing this.

I don't really need a BrowserTest per se, as I just want to ensure the Response object contains what it should. I create a client mock and instantiate the controller object myself:

```
<?php

namespace Drupal\Tests\mymodule\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\mymodule\Controller\AuthorizeController;
use Drupal\node\Entity\Node;
use Drupal\file\Entity\File;
use Drupal\Core\File\FileSystem;

/**
 * Tests the AuthorizeController controller.
 *
 * @group mymodule
 */
class AuthorizeControllerTest extends KernelTestBase {

  /**
   * @var array
   */
  public static $modules = ['system', 'node', 'field', 'mymodule', 'file', 'mymodule_authtest', 'user', 'text'];

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();

    $this->installConfig(['node', 'user', 'mymodule_authtest', 'file']);
    $this->installSchema('file', ['file_usage']);
    $this->installEntitySchema('user');
    $this->installEntitySchema('node');
    $this->installEntitySchema('file');

    $module_path = drupal_get_path('module', 'mymodule_authtest');

    $uri = $this->container->get('file_system')->copy("$module_path/fixtures/pdf/foo.pdf", 'public://foo.pdf', FileSystem::EXISTS_REPLACE);

    $file = File::Create([
      'uri' => $uri,
    ]);
    $file->save();

    $node = Node::create(array(
      'title' => t('Test Paper'),
      'type' => 'working_paper',
      'language' => 'en',
      'field_id' => 'w12345',
      'field_paper_working_paper' => $file->id(),
    ));
    $node->save();
  }

  /**
   * Test different scenarios and responses from our controller.
   */
  public function testControllerResponse() {
    $node = $this->container->get('entity_type.manager')->getStorage('node')->load(1);

    $client = $this->getMockClient(1, 3, 3);
    $controller = $this->getAuthorizeController($client);
    $response = $controller->content($node);
    $this->assertContains('You’ve used 3 of your 3 allowed downloads for the year.', $response->getContent());
    $this->assertContains('Download Paper Anyway', $response->getContent());

    $client = $this->getMockClient(1, 3, 1);
    $controller = $this->getAuthorizeController($client);
    $response = $controller->content($node);
    $this->assertContains('You’ve used 1 of your 3 allowed downloads for the year.', $response->getContent());
    $this->assertContains('Download Paper Anyway', $response->getContent());

    $client = $this->getMockClient(1, 2, 1);
    $controller = $this->getAuthorizeController($client);
    $response = $controller->content($node);
    $this->assertContains('You’ve used 1 of your 2 allowed downloads for the year.', $response->getContent());

    $client = $this->getMockClient(0, 3, 3);
    $controller = $this->getAuthorizeController($client);
    $response = $controller->content($node);
    $this->assertNotContains('Download Paper Anyway', $response->getContent());
    $this->assertContains('<a href="http://example.org?id=w12345" class="btn btn--primary btn--black">Purchase Paper for $5</a>', $response->getContent());
    $this->assertContains('<a href="http://example.org?referer=http%3A//localhost/node/1" class="btn btn--primary btn--black">Have Access? Login to Account</a>', $response->getContent());
  }

  /**
   * Return a mocked client. Allow changing of some values to influence the
   * controllers response object.
   */
  protected function getMockClient(int $allow = 1, int $claims_max = 3, int $claims_used = 1) {
    $client = $this->getMockBuilder('\Drupal\mymodule\Client\AuthorizeClient')
      ->disableOriginalConstructor()
      ->getMock();
    $client->expects($this->any())
      ->method('request')
      ->with('w12345', FALSE)
      ->willReturn(
        [
          'allow' => $allow,
          'claims_max' => $claims_max,
          'claims_used' => $claims_used,
          'failed_reason' => NULL,
          'succeeded_reason' => NULL,
          'subscriber_id' => 12345,
          'subscriber_logo_url' => NULL,
          'subscriber_name' => "Test",
          'subscriber_type' => "SUBS",
        ]
      );

    return $client;
  }

  /**
   * Return a controller with a mocked client.
   */
  protected function getAuthorizeController($client) {
    return new AuthorizeController($client, $this->container->get('renderer'), $this->container->get('entity_type.manager'), $this->container->get('request_stack'), $this->container->get('logger.factory'));
  }

}

```

This seems like a valid approach and the cases are working, and executes much faster than browser tests. The `mymodule_authtest` contains a content type with a couple of field configuration files and example PDF file to use in this test.

---
Tags: 8, testing
---


# Question
Title: How to add class to the options for type radio present under radios?
```
function template_preprocess_bef_radios(&$variables) {
  $variables['children'] = Element::children($variables['element']);
  _bef_preprocess_nested_elements($variables);
    foreach($variables['element'] as $tid => $value) {
        if (is_numeric($tid) || $tid === 'All') {
            $value['#attributes']['class'][] = Html::cleanCssIdentifier($value['#title']);
        }
    }
 }

```

While trying the above does not add class to radio button under radios(which has multiple options) How can I add class to the options ?

# Answer
You are almost there just you should change `$variables['element'][$tid]['#attributes']['class']` instead of `$value['#attributes']['class']` try with:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function template_preprocess_bef_radios(&$variables) {
  // No need to this two lines
//  $variables['children'] = Element::children($variables['element']);
//  _bef_preprocess_nested_elements($variables);
  foreach($variables['element'] as $tid => $value) {
    if (is_numeric($tid) || $tid === 'All') {
      $variables['element'][$tid]['#attributes']['class'][] = Html::cleanCssIdentifier($value['#title']);
    }
  }
}

```
> 1 votes

---
Tags: views, 8, forms
---


# Question
Title: Service to interface with sessions table?
In my module, I need greater session control, beyond simple max\_lifetime and other parameters taken from PHP config. What I did was to add a column to the `sessions` table that gives me the effective session expiration, which I can compare against to know if to revoke the session. (I also want to "cache" this in the local session, but this is unrelated to the question).

The question is, what is the best way to retrieve the new data from the `sessions` table? I can just send a direct DB query, such as:

```
Database::getConnection()->query('SELECT expires_at FROM {sessions} s WHERE s.uid = :uid', [':uid' => $uid]);

```

However, is there a built-in service for accessing this table, for greater abstraction?

# Answer
You can make use of `Dynamic Queries` instead of `Database::getConnection()->query('SELECT expires_at FROM {sessions} s WHERE s.uid = :uid', [':uid' => $uid]);`

You can do:

```
  // Create an object of type Select.
  $database = \Drupal::database();
  $query = $database->select('sessions', 's');
  // Add extra detail to this query object: a condition, fields and a range.
  $query->condition('s.uid', $uid, '=');
  $query->fields('s', ['expires_at']);
  $result = $query->execute();

```
> 1 votes

---
Tags: 8, sessions
---


# Question
Title: Fatal error when using some filters or sorting options in admin/content
Using Drupal 8.8.0, multilingual, on localhost (Windows 10, PHP 7.3.12).

I have a fatal error on the `admin/content` page, but only if I use certain options for sorting or filtering the results.

Available filters:

* title: works fine
* content type: **fatal error**
* published status: works fine
* language: works fine

Available sorting options:

* title: **fatal error**
* content type: **fatal error**
* author: **fatal error**
* status (published/not): works fine
* updated: works fine
* created: works fine

However if a filter is in use (and hasn't caused a crash), then all sorting options work fine, as far as I can tell.

When checking the server log, I find the following error:

```
Error: Call to a member function getId() on null in C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Entity\\Entity\\EntityViewDisplay.php on line 258 #0 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Entity\\Render\\EntityFieldRenderer.php(276): Drupal\\Core\\Entity\\Entity\\EntityViewDisplay->buildMultiple(Array), referer: http://localhost/myproject/www/fr/admin/content
#1 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Entity\\Render\\EntityFieldRenderer.php(163): Drupal\\views\\Entity\\Render\\EntityFieldRenderer->buildFields(Array), referer: http://localhost/myproject/www/fr/admin/content
#2 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Plugin\\views\\field\\EntityField.php(846): Drupal\\views\\Entity\\Render\\EntityFieldRenderer->render(Object(Drupal\\views\\ResultRow), Object(Drupal\\views\\Plugin\\views\\field\\EntityField)), referer: http://localhost/myproject/www/fr/admin/content
#3 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Plugin\\views\\field\\FieldPluginBase.php(1148): Drupal\\views\\Plugin\\views\\field\\EntityField->getItems(Object(Drupal\\views\\ResultRow)), referer: http://localhost/myproject/www/fr/admin/content
#4 C:\\htdocs\\myproject\\www\\core\\modules\\views\\views.theme.inc(236): Drupal\\views\\Plugin\\views\\field\\FieldPluginBase->advancedRender(Object(Drupal\\views\\ResultRow)), referer: http://localhost/myproject/www/fr/admin/content
#5 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Theme\\ThemeManager.php(287): template_preprocess_views_view_field(Array, 'views_view_fiel...', Array), referer: http://localhost/myproject/www/fr/admin/content
#6 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\Renderer.php(431): Drupal\\Core\\Theme\\ThemeManager->render('views_view_fiel...', Array), referer: http://localhost/myproject/www/fr/admin/content
#7 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\Renderer.php(200): Drupal\\Core\\Render\\Renderer->doRender(Array, false), referer: http://localhost/myproject/www/fr/admin/content
#8 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Plugin\\views\\field\\FieldPluginBase.php(1747): Drupal\\Core\\Render\\Renderer->render(Array), referer: http://localhost/myproject/www/fr/admin/content
#9 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Plugin\\views\\style\\StylePluginBase.php(770): Drupal\\views\\Plugin\\views\\field\\FieldPluginBase->theme(Object(Drupal\\views\\ResultRow)), referer: http://localhost/myproject/www/fr/admin/content
#10 [internal function]: Drupal\\views\\Plugin\\views\\style\\StylePluginBase->elementPreRenderRow(Array), referer: http://localhost/myproject/www/fr/admin/content
#11 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Security\\DoTrustedCallbackTrait.php(100): call_user_func_array(Array, Array), referer: http://localhost/myproject/www/fr/admin/content
#12 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\Renderer.php(781): Drupal\\Core\\Render\\Renderer->doTrustedCallback(Array, Array, 'Render #pre_ren...', 'silenced_deprec...', 'Drupal\\\\Core\\\\Ren...'), referer: http://localhost/myproject/www/fr/admin/content
#13 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\Renderer.php(372): Drupal\\Core\\Render\\Renderer->doCallback('#pre_render', Array, Array), referer: http://localhost/myproject/www/fr/admin/content
#14 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\Renderer.php(200): Drupal\\Core\\Render\\Renderer->doRender(Array, false), referer: http://localhost/myproject/www/fr/admin/content
#15 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Plugin\\views\\style\\StylePluginBase.php(709): Drupal\\Core\\Render\\Renderer->render(Array), referer: http://localhost/myproject/www/fr/admin/content
#16 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Plugin\\views\\style\\StylePluginBase.php(576): Drupal\\views\\Plugin\\views\\style\\StylePluginBase->renderFields(Array), referer: http://localhost/myproject/www/fr/admin/content
#17 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Plugin\\views\\style\\StylePluginBase.php(468): Drupal\\views\\Plugin\\views\\style\\StylePluginBase->renderGrouping(Array, Array, true), referer: http://localhost/myproject/www/fr/admin/content
#18 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Plugin\\views\\display\\DisplayPluginBase.php(2140): Drupal\\views\\Plugin\\views\\style\\StylePluginBase->render(Array), referer: http://localhost/myproject/www/fr/admin/content
#19 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\ViewExecutable.php(1533): Drupal\\views\\Plugin\\views\\display\\DisplayPluginBase->render(), referer: http://localhost/myproject/www/fr/admin/content
#20 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Plugin\\views\\display\\Page.php(183): Drupal\\views\\ViewExecutable->render(), referer: http://localhost/myproject/www/fr/admin/content
#21 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\ViewExecutable.php(1630): Drupal\\views\\Plugin\\views\\display\\Page->execute(), referer: http://localhost/myproject/www/fr/admin/content
#22 C:\\htdocs\\myproject\\www\\core\\modules\\views\\src\\Element\\View.php(77): Drupal\\views\\ViewExecutable->executeDisplay('page_1', Array), referer: http://localhost/myproject/www/fr/admin/content
#23 [internal function]: Drupal\\views\\Element\\View::preRenderViewElement(Array), referer: http://localhost/myproject/www/fr/admin/content
#24 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Security\\DoTrustedCallbackTrait.php(100): call_user_func_array(Array, Array), referer: http://localhost/myproject/www/fr/admin/content
#25 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\Renderer.php(781): Drupal\\Core\\Render\\Renderer->doTrustedCallback(Array, Array, 'Render #pre_ren...', 'silenced_deprec...', 'Drupal\\\\Core\\\\Ren...'), referer: http://localhost/myproject/www/fr/admin/content
#26 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\Renderer.php(372): Drupal\\Core\\Render\\Renderer->doCallback('#pre_render', Array, Array), referer: http://localhost/myproject/www/fr/admin/content
#27 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\Renderer.php(200): Drupal\\Core\\Render\\Renderer->doRender(Array, false), referer: http://localhost/myproject/www/fr/admin/content
#28 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\MainContent\\HtmlRenderer.php(226): Drupal\\Core\\Render\\Renderer->render(Array, false), referer: http://localhost/myproject/www/fr/admin/content
#29 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\Renderer.php(573): Drupal\\Core\\Render\\MainContent\\HtmlRenderer->Drupal\\Core\\Render\\MainContent\\{closure}(), referer: http://localhost/myproject/www/fr/admin/content
#30 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\MainContent\\HtmlRenderer.php(227): Drupal\\Core\\Render\\Renderer->executeInRenderContext(Object(Drupal\\Core\\Render\\RenderContext), Object(Closure)), referer: http://localhost/myproject/www/fr/admin/content
#31 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\Render\\MainContent\\HtmlRenderer.php(117): Drupal\\Core\\Render\\MainContent\\HtmlRenderer->prepare(Array, Object(Symfony\\Component\\HttpFoundation\\Request), Object(Drupal\\Core\\Routing\\CurrentRouteMatch)), referer: http://localhost/myproject/www/fr/admin/content
#32 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\EventSubscriber\\MainContentViewSubscriber.php(90): Drupal\\Core\\Render\\MainContent\\HtmlRenderer->renderResponse(Array, Object(Symfony\\Component\\HttpFoundation\\Request), Object(Drupal\\Core\\Routing\\CurrentRouteMatch)), referer: http://localhost/myproject/www/fr/admin/content
#33 [internal function]: Drupal\\Core\\EventSubscriber\\MainContentViewSubscriber->onViewRenderArray(Object(Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\\Component\\EventDispatcher\\ContainerAwareEventDispatcher)), referer: http://localhost/myproject/www/fr/admin/content
#34 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Component\\EventDispatcher\\ContainerAwareEventDispatcher.php(111): call_user_func(Array, Object(Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\\Component\\EventDispatcher\\ContainerAwareEventDispatcher)), referer: http://localhost/myproject/www/fr/admin/content
#35 C:\\htdocs\\myproject\\www\\vendor\\symfony\\http-kernel\\HttpKernel.php(156): Drupal\\Component\\EventDispatcher\\ContainerAwareEventDispatcher->dispatch('kernel.view', Object(Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent)), referer: http://localhost/myproject/www/fr/admin/content
#36 C:\\htdocs\\myproject\\www\\vendor\\symfony\\http-kernel\\HttpKernel.php(68): Symfony\\Component\\HttpKernel\\HttpKernel->handleRaw(Object(Symfony\\Component\\HttpFoundation\\Request), 1), referer: http://localhost/myproject/www/fr/admin/content
#37 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\StackMiddleware\\Session.php(57): Symfony\\Component\\HttpKernel\\HttpKernel->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true), referer: http://localhost/myproject/www/fr/admin/content
#38 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\StackMiddleware\\KernelPreHandle.php(47): Drupal\\Core\\StackMiddleware\\Session->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true), referer: http://localhost/myproject/www/fr/admin/content
#39 C:\\htdocs\\myproject\\www\\core\\modules\\page_cache\\src\\StackMiddleware\\PageCache.php(106): Drupal\\Core\\StackMiddleware\\KernelPreHandle->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true), referer: http://localhost/myproject/www/fr/admin/content
#40 C:\\htdocs\\myproject\\www\\core\\modules\\page_cache\\src\\StackMiddleware\\PageCache.php(85): Drupal\\page_cache\\StackMiddleware\\PageCache->pass(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true), referer: http://localhost/myproject/www/fr/admin/content
#41 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\StackMiddleware\\ReverseProxyMiddleware.php(47): Drupal\\page_cache\\StackMiddleware\\PageCache->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true), referer: http://localhost/myproject/www/fr/admin/content
#42 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\StackMiddleware\\NegotiationMiddleware.php(52): Drupal\\Core\\StackMiddleware\\ReverseProxyMiddleware->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true), referer: http://localhost/myproject/www/fr/admin/content
#43 C:\\htdocs\\myproject\\www\\vendor\\stack\\builder\\src\\Stack\\StackedHttpKernel.php(23): Drupal\\Core\\StackMiddleware\\NegotiationMiddleware->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true), referer: http://localhost/myproject/www/fr/admin/content
#44 C:\\htdocs\\myproject\\www\\core\\lib\\Drupal\\Core\\DrupalKernel.php(694): Stack\\StackedHttpKernel->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, tru, referer: http://localhost/myproject/www/fr/admin/content

(Every line starting with [Fri Dec 06 19:26:08.993106 2019] [fcgid:warn] [pid 16812:tid 1200] [client ::1:64229] mod_fcgid: stderr:)

```

Can anybody help identify what is causing this error? Thanks in advance.

# Answer
I got a similar error on another (custom) views page and it helped me understand the cause of this error. This time, the full error was:

```
Error: Call to a member function getId() on null in Drupal\Core\Entity\EntityViewBuilder->getBuildDefaults() (line 223 of C:\htdocs\myproject\www\core\lib\Drupal\Core\Entity\EntityViewBuilder.php) #0 C:\htdocs\myproject\www\core\modules\node\src\NodeViewBuilder.php(61): Drupal\Core\Entity\EntityViewBuilder->getBuildDefaults(Object(Drupal\node\Entity\Node), 'teaser')
#1 C:\htdocs\myproject\www\core\lib\Drupal\Core\Entity\EntityViewBuilder.php(168): Drupal\node\NodeViewBuilder->getBuildDefaults(Object(Drupal\node\Entity\Node), 'teaser')
#2 C:\htdocs\myproject\www\core\lib\Drupal\Core\Entity\EntityViewBuilder.php(134): Drupal\Core\Entity\EntityViewBuilder->viewMultiple(Array, 'teaser', 'es')
#3 C:\htdocs\myproject\www\core\modules\views\src\Entity\Render\TranslationLanguageRenderer.php(90): Drupal\Core\Entity\EntityViewBuilder->view(Object(Drupal\node\Entity\Node), 'teaser', 'es')
#4 C:\htdocs\myproject\www\core\modules\views\src\Plugin\views\row\EntityRow.php(247): Drupal\views\Entity\Render\TranslationLanguageRenderer->preRender(Array)
#5 C:\htdocs\myproject\www\core\modules\views\src\Plugin\views\style\StylePluginBase.php(434): Drupal\views\Plugin\views\row\EntityRow->preRender(Array)
#6 C:\htdocs\myproject\www\core\modules\views\src\ViewExecutable.php(1508): Drupal\views\Plugin\views\style\StylePluginBase->preRender(Array)
#7 C:\htdocs\myproject\www\core\modules\views\src\Plugin\views\display\Page.php(183): Drupal\views\ViewExecutable->render()
#8 C:\htdocs\myproject\www\core\modules\views\src\ViewExecutable.php(1630): Drupal\views\Plugin\views\display\Page->execute()
#9 C:\htdocs\myproject\www\core\modules\views\src\Element\View.php(77): Drupal\views\ViewExecutable->executeDisplay('page_2', Array)
#10 [internal function]: Drupal\views\Element\View::preRenderViewElement(Array)
#11 C:\htdocs\myproject\www\core\lib\Drupal\Core\Security\DoTrustedCallbackTrait.php(100): call_user_func_array(Array, Array)
#12 C:\htdocs\myproject\www\core\lib\Drupal\Core\Render\Renderer.php(781): Drupal\Core\Render\Renderer->doTrustedCallback(Array, Array, 'Render #pre_ren...', 'silenced_deprec...', 'Drupal\\Core\\Ren...')
#13 C:\htdocs\myproject\www\core\lib\Drupal\Core\Render\Renderer.php(372): Drupal\Core\Render\Renderer->doCallback('#pre_render', Array, Array)
#14 C:\htdocs\myproject\www\core\lib\Drupal\Core\Render\Renderer.php(200): Drupal\Core\Render\Renderer->doRender(Array, false)
#15 C:\htdocs\myproject\www\core\lib\Drupal\Core\Render\MainContent\HtmlRenderer.php(226): Drupal\Core\Render\Renderer->render(Array, false)
#16 C:\htdocs\myproject\www\core\lib\Drupal\Core\Render\Renderer.php(573): Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}()
#17 C:\htdocs\myproject\www\core\lib\Drupal\Core\Render\MainContent\HtmlRenderer.php(227): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#18 C:\htdocs\myproject\www\core\lib\Drupal\Core\Render\MainContent\HtmlRenderer.php(117): Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#19 C:\htdocs\myproject\www\core\lib\Drupal\Core\EventSubscriber\MainContentViewSubscriber.php(90): Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#20 [internal function]: Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#21 C:\htdocs\myproject\www\core\lib\Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher.php(111): call_user_func(Array, Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#22 C:\htdocs\myproject\www\vendor\symfony\http-kernel\HttpKernel.php(156): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent))
#23 C:\htdocs\myproject\www\vendor\symfony\http-kernel\HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#24 C:\htdocs\myproject\www\core\lib\Drupal\Core\StackMiddleware\Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#25 C:\htdocs\myproject\www\core\lib\Drupal\Core\StackMiddleware\KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#26 C:\htdocs\myproject\www\core\modules\page_cache\src\StackMiddleware\PageCache.php(191): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#27 C:\htdocs\myproject\www\core\modules\page_cache\src\StackMiddleware\PageCache.php(128): Drupal\page_cache\StackMiddleware\PageCache->fetch(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#28 C:\htdocs\myproject\www\core\modules\page_cache\src\StackMiddleware\PageCache.php(82): Drupal\page_cache\StackMiddleware\PageCache->lookup(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#29 C:\htdocs\myproject\www\core\lib\Drupal\Core\StackMiddleware\ReverseProxyMiddleware.php(47): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#30 C:\htdocs\myproject\www\core\lib\Drupal\Core\StackMiddleware\NegotiationMiddleware.php(52): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#31 C:\htdocs\myproject\www\vendor\stack\builder\src\Stack\StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#32 C:\htdocs\myproject\www\core\lib\Drupal\Core\DrupalKernel.php(694): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#33 C:\htdocs\myproject\www\index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#34 {main}.

```

The part that caught my eye is on line #2: `viewMultiple(Array, 'teaser', 'es')`

Like I said, this is a multilingual site (it's actually an old D6 site that I'm currently migrating to D8). It used to have 5 languages for content, but at some point the client decided to drop 2 of those languages (Spanish and Italian). But there are still content entries for those languages in the Drupal database.

Up to this point, Drupal was still configured to use the 5 initial languages, but I recently decided to remove the two unused languages in order to simplify the UX. That's where the error started to appear (although I did not run into it immediately).

So in short, **a view trying to display pieces of content in a language that is no longer present in Drupal will cause this error.**

I added Spanish and Italian back in Drupal, and after that the error stopped occurring. I then deleted all contents in Italian and Spanish, then removed those languages from Drupal again: the error hasn't come back.

Problem solved as far as I can tell.
> 0 votes

---
Tags: views, 8
---


# Question
Title: It is correct to change unit_price of commerce_order_item programmatically under several conditions?
I am developing a module that allows you to select additional options for a product that is not a product or a purchase entity. It's like commerce\_option but for D8.

My inspirations come from Product Attributes shipped with Drupal Commerce. So I have mostly the same two entity types:

* Product Option (config entity type) - bundle.
* Product Option Value (content entity type) - the actual option with price field.

The options can be attached to `commerce_order_item` types as entity references. Then add to cart form display them as options to select.

The confusion comes at the part when these options come to `commerce_order_item` and actual order.

At the current moment, I've created a new field type with three properties: option (textfield), option value (textfield), price (commerce\_price). This field automatically filled when `commerce_order_item` added to the cart.

Next, the most obscure part. What's the correct way to handle those additional and their prices?

I see several ways:

1. (current implementation) My current field type + `commerce_order_item` `adjustments`. The problem here I see, there is a bit mess with cart and other stuff. I need manually use `getAdjustedUnitPrice()` to get real product price. It can be affected by tax and other stuff, so this becomes a mess in the future. Plus, in this way I don't see the proper way to add a discount for this line item. Since the promotion applies to `unit_price` or total\_price, but this amounts in adjustments. It can be solved, but may be tricky.
2. My current field type + override of `unit_price`. In this way the discount and tax problem disappear. But rises another problem. The manager, when editing order item, must take product options into account when editing it, since their price will be already included.

Maybe you can advise another approach? I also think about special `commerce_order_item` type + entity\_reference (much complicated I think). But here all the problems of the first approach raise again.

Is it good to edit `unit_price` directly on order\_item save\update? Or it is not expected behavior, when some event will change order\_item price by adding the amounts? Also, how this must work on second and so on saves? E.g. order\_item price $10, and selected option $5. When order\_items saved, the `current_price` will become $15. When some changes are made, how to detect those options already included? The way I see, recalculate the new `unit_price` by grabbing the `price` from `purchased_entity`. But what if this price was manually overridden by the manager from $10, to $8? The only solution I see now, is to store price before it affected by options in the `data` field. Is this also correct or I miss something?

The reason because I create special field to store values is almost the same as order\_item existence. The option prices can be changed, or even deleted, so order\_item doesn't know anything about it and store the raw results values.

# Answer
> 0 votes
As a proof of concept a module with this functionality already exists. Unfortunately, it's not published yet because that requires a couple of final touches with a time frame allocated for this kind of work.

https://github.com/drugan/commerce\_oiaddon

The price adjustment is taken from a pseudo-price field added to some entity type and then the order item price recalculated at the event of an order item added to or removed from a shopping cart. So I am not sure why you can't get the same result as in the commerce\_oiaddon module. Just do the same as it shown in the example and it should work.

---
Tags: 8, commerce
---


# Question
Title: How add a function in a condition method in db api
I am strugginling to find out how to execute the below query using drupal's db api

```
$startdate = '1491001200';
$enddate = '1498690799';
"SELECT * FROM field_data_field_symposium_event_time
    WHERE UNIX_TIMESTAMP(field_symposium_event_time_value) BETWEEN
    $startdate AND $enddate;"

```

I have tried adding 'addExpression' but does not work. I did it like this

```
$query = db_select('node','n');
$query->join('field_data_field_symposium_event_time', 'et', 'et.entity_id = n.nid');
$query->condition('et.field_data_field_symposium_event_time_value',array($day_start, $day_end), 'BETWEEN'));
$query->addExpression('UNIX_TIMESTAMP(et.field_symposium_event_time_value)');
$query->fields('et',array('field_symposium_event_time_value'));
$result = $query->execute()->fetchAll();

```

The `$result` is empty. Is there a way to achieve this as I dont want to write the full query .

# Answer
> 3 votes
I believe the addExpression is for SELECT clause expressions

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Select.php/function/Select%3A%3AaddExpression/8.2.x

For a WHERE clause expression it should be

```
$query->where('UNIX_TIMESTAMP(et.field_symposium_event_time_value) BETWEEN :start AND :end', array(':start' => $day_start, ':end' => $day_end));

```

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21QueryConditionTrait.php/function/QueryConditionTrait%3A%3Awhere/8.2.x

And then of course remove your `$query->condition(...);` line.

# Answer
> 0 votes
I think that -\>addExpression is about adding SQL snippets like yours to modify selected columns right after the SELECT (vs. adding expressions to a WHERE clause).

The -\>where() (and -\>having()) clauses are what you want.

---
Tags: database
---


title: Excerpt of Search API index is cached

text:
# Question
Title: Excerpt of Search API index is cached
I'm using the search\_api extension (V 8.x-1.14) with the Database search (no solr, etc.)

I use the search block which is created by the search view (`/search` path)

I want to show the highlighted excerpts which are setup in the *Manage processors for search index*  (`/admin/config/search/search-api/<x>/content/processors`)

In the view I select *Rendered Entity* as show format and chose *search result hightlighing input* in the settings.

Everything works fine now, but ...

Consifer I have a page *About us* with this sentence written somewhere on the page.

> 'We will deliver your quality product on time and safely at the location of your choice.'

When the user searches for `time`, this page will be hit and the correct highlight will be shown

> We will deliver your quality product on **time** and safely at the location of your choice.

Now this excerpt is cached and when I search for *quality* the excerpt stays the same with the wrong word highlighted.

> We will deliver your quality product on **time** and safely at the location of your choice.

I deactivated the cache of the view, but it didn't change anything

# Answer
Thanks to berramou!

I ended up using this in my theme:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_node(array &$variables) {
  if ($variables['view_mode'] == 'search_result') {
    $variables['#cache']['max-age'] = 0;
  }
}

```
> 0 votes

---
Tags: 8, search, caching
---


# Question
Title: How can I retrieve the current node ID on a custom route?
I have a new route and the yml file looks like this:

```
rsvplist.form:
  path: '/rsvplist'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'

```

From the module root directory, I have src/Form/RSVPForm.php, and inside is where I have the build form function that looks like the following:

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $nid = $node->nid->value;

    $form['email'] = [
        '#title' => t('Email Address'),
        '#type' => 'textfield',
        '#size' => 25,
        '#description' => t('We will send updates to the email you provide.'),
        '#required' => TRUE,
    ];

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

    return $form;
}

```

When I clear the site cache and refresh the page: mylocal.com/rsvplist, I see the following error:

```
Notice: Trying to get property 'nid' of non-object

```

I initially used the following code to get the node

```
$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;

```

If I change the last piece of code to this:

```
$nid = $node->id();

```

I see the following error:

```
Error: Call to a member function id() on null

```

How can I get the node id when am on the new route?

Reference here

# Answer
> 2 votes
Your route doesn't have a parameter called node, so therefore `$node` is null.

In order to make node available as a parameter you have to be on a route that has `node` as a parameter.

So to add the `node` parameter to your route, you can do like this:

```
rsvplist.form:
  path: '/rsvplist/{node}'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'
    _entity_access: 'node.view'
    node: \d+

```

And then you can add the `$node` parameter to your `buildForm` method, like this:

```
public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  // Your form.
}

```

Since I added `node: \d+` to your form, `$node` is now the loaded entity in the `buildForm` method.

# Answer
> -2 votes
You can try code

```
rsvplist.form:
  path: '/rsvplist/{nid}'
  ....

use Drupal\node\NodeInterface;
....
$nid= \Drupal::routeMatch()->getParameter('nid');
$node = Node::load($nid);

```

---
Tags: 8, nodes, routes
---


# Question
Title: Migration from CSV: how to define a default value for autoincremental id field?
I run migrations from CSV using Migrate Source CSV, Migrate Plus and Migrate Tools modules and it works fine.
The result of one of these migration is a custom entity which key is a 'id' field that has the 'AUTO\_INCREMENT' property in the database.
Here is my `migration_contractssubscriptions.yaml`

```
id: migration_contractssubscriptions
migration_group: null
label: 'Contract Subscriptions migration from CSV'
source:
  plugin: csv
  path: /mypathto/migration_ContractsSubscriptions.csv
  delimiter: ';'
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
process:
  id: id
  contract_id: contract_id
  member_id: member_id
  sharedwith_member_id: sharedwith_member_id
  comment: comment
  quantity01: quantity01
  quantity02: quantity02
  quantity03: quantity03
  quantity04: quantity04
  owner_id:
    plugin: default_value
    default_value: 1
destination:
  plugin: 'entity:contract_subscription'

```

I'd like to get rid of 'id' in my csv file and let the migration process handle the value of the resulting id.
I tried to remove `keys: - id` and `id: id` but I get an error...
How can I achieve that?

# Answer
> 0 votes
I finally understood that `keys` in `source` is the way to make each row of the csv file unique. It may be anything.
So I changed to:

```
  keys:
    - contract_id
    - member_id

```

I removed `id: id`from `process`and it works!
The value of `id` field in the database is properly auto-incremented.

---
Tags: 8, migrations
---


title: Sync user roles across websites

text:
# Question
Title: Sync user roles across websites
I am using Drupal 7. I want to sync my Drupal website roles on 2 websites on the same top level domain, as in, one is example.com, the other is other.example.com, how can i achieve this? Bakery module does not seem to share user roles, and i want to avoid sharing databases across my sites since it works but not recommended.

Basically, i want to reduce loading time on my main site and push my payment system (which contains many modules) to a new Drupal install so that when the payment is made on the slave site, the user role is updated on the slave site which is in turn captured on the main site. How can i achieve this?

# Answer
i cannot provide detailed steps to achieve this but there are various alternatives Comparison of Single Sign On (SSO) Modules to the bakery module you mentioned that are capable of sharing users. although you might want to just create those roles via a feature, depending on what you mean by

> sync my drupal website roles.

* Services
* i18n\_sso
* Domainaccess
* CAS
* account\_sync
* simplesamlphp\_auth
* shib\_auth
* Omniauth https://drupal.org/node/2177681
* Oauth Connector
* Bakery 3.x current development effort suggest it might soon support exporting roles in 3.x if you are a developer you can look there. i believe issue 556666 was committed to 2.x already aswell
> 0 votes

# Answer
Typically when staging roles on D7 across multiple environments or sites is tricky since roles are referenced using *rid*, we solved this by using this module since it exports your role definitions and maintain the assigned permissions which can be painful to achieve. Since your sites are "clones" this should work perfectly.

Even though what you want is to *sync* the table like so, perhaps you can opt for a database focused approach like described here and here depending on your server configuration.
> 0 votes

---
Tags: 7, users, migrations
---


# Question
Title: how do I access raw URL from a File Field to render it in twig inside href?
I have a "Our Staff" Content Type, that includes a field for uploading an individual's CV as a PDF:

```
field_cv_file

```

I have created a View for this Content Type, then added it to page via Blocks

The twig file I'm using to render/style this area is:

```
views-view-fields--our-staff-view--block-1.html

```

I'm having trouble with the URL for the File Field

I can render it as a PDF icon link like this:

```
{{ fields.field_cv_file.content }}

```

But I want to obtain the 'raw' URL to apply inside a href, something like this:

```
<a href="{{ fields.field_cv_file.content }}">Download CV</a>

```

This however is not working.

I've tried a few different ways of rewriting the code in href, but none are working.

how would I do this?

# Answer
In my case as I was using a views twig, and required the field's file path to be usable inside a href, I had to write it like this:

```
<a href="{{ fields.field_cv_file.content|striptags }}" target="_blank">Download CV <i class="fal fa-long-arrow-right"></i></a>

```
> 1 votes

---
Tags: theming
---


# Question
Title: Simple way to add a class to the body when creating/editing an entity
In Drupal 8.4, I am trying to add a class to the body (like Drupal 7 had) when the page viewed is a node (or entity for that matter), something like \[entity\]-\[create or edit\], so that, when a user is editing or creating a node, a class like page-node-edit gets added to the body classes array.

# Answer
I couldn't get oknate's solution to work so I modified it. You can add it to your custom module file.

```
/**
 * Implements hook_preprocess_html().
 */
function MYMODULE_preprocess_html(&$variables) {
  // Add node ID
  if ($node = \Drupal::request()->attributes->get('node')) {
   $variables['attributes']['class'][] = 'page-node-' . $node->id();
  }

  // Get route
  $route_name = \Drupal::routeMatch()->getRouteName();

  // Add edit class
  if ($route_name == 'entity.node.edit_form') {
    $variables['attributes']['class'][] = 'entity-edit';
  }

  // Add create class
  if ($route_name == 'node.add') {
    $variables['attributes']['class'][] = 'entity-create';
  }

}

```
> 5 votes

# Answer
I combined @Parag's solution with some extra logic to also handle node type along with the operation.

**UPDATED:** Implemented a switch to allow adding more routes.

```
function MYTHEME_preprocess_html(&$variables) {
  $routeName = \Drupal::routeMatch()->getRouteName();
  switch ($routeName) {
    case 'entity.node.edit_form':
      $entityType = $variables['node_type'];
      $op = 'edit';
      break;
    case 'node.add':
      $entityType = \Drupal::routeMatch()->getParameter('node_type')->id();
      $op = 'add';
      break;
  }

  if (isset($entityType) && isset($op)) {
    $cleanEntityType = Html::cleanCssIdentifier($entityType);
    $prefix = 'entity-form';
    $cssClasses = [
      [$prefix],
      [$prefix, $op],
      [$prefix, $cleanEntityType],
      [$prefix, $cleanEntityType, $op],
    ];
    foreach ($cssClasses as $cssClass) {
      $variables['attributes']['class'][] = implode('-', $cssClass);
    }
  }
}

```
> 3 votes

# Answer
You can use hook\_preprocess\_page and check the current route:

```
function mymodule_preprocess_page(&$vars) {

  $route_name = \Drupal::routeMatch()->getRouteName();

  // This would add a class based on the route.  You'd need the
  // pathauto module enabled.
  $vars['page_classes'][] = \Drupal::service('pathauto.alias_cleaner')->cleanString($route_name);

  // This would add the classes asked for in the question.
  if ($route_name == 'entity.node.edit_form') {
    $vars['page_classes'][] = 'entity-edit';
  }
  elseif ($route_name == 'node.add') {
    $vars['page_classes'][] = 'entity-create';
  }
}

```
> 2 votes

# Answer
After dealing with this for some time, I've found a potential alternative way of approaching this sort of functionality.

For my use case, I was trying to add classes to the body of the node add/edit pages, so I can do things like hide blocks and alter positioning using css.

My new approach to achieve this is to simply override the page.html.twig. So, if I wanted to customize the node edit/add pages for a content type called "Blog Post", I would create two new template files:

1. page--node--add--blogpost.html.twig
2. page--node--edit--blogpost.html.twig

Note that I can create one set template files to cover all content types like so:

1. page--node--add.html.twig
2. page--node--edit.html.twig

I can also override html.html.twig, if I really needed to get my classes into the node add/edit pages. For this approach, I would create two new template pages:

1. html--node--add.html.twig
2. html--node--edit.html.twig

In these template pages, I would simply modify the body\_classes array like so:

```
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    theme.settings.navbar_position ? 'navbar-is-' ~ theme.settings.navbar_position,
    theme.has_glyphicons ? 'has-glyphicons',
    'my-new-class',
    'another-class',
  ]
%}

```
> 0 votes

# Answer
```
function MYTHEME_preprocess_html(&$variables) {
$current_path = \Drupal::service('path.current')->getPath();
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
$is_edit = strpos($path_alias, '/edit');
if ($is_edit !== false) {
  $edit_css_classname = $variables['node_type'].'-edit';
  $variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($edit_css_classname);
  }
}

```

This code snippet adds a MY-NODE-TYPE-edit class to the body tag of a page, if there is "/edit" inside the path.
> 0 votes

# Answer
```
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    user.getRoles()|join(' role-'),
    'edit' in url('<current>')|render|render ? 'page-edit'
  ]
%}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: AJAX callback on form item generated by AJAX
I'm trying to add AJAX callback to form element that was previously rendered by AJAX but with no luck. Code below.

A bit of description. There are three main methods here:

1. `buildForm` \- base form
2. `extraField` \- AJAX callback attached to `['month']`
3. `choosePerson` \- AJAX callback attached to: `['week_day']['hour']`

In the buildForm method I create base form with AJAX callback on 'month' select element. In the AJAX callback you can find an extraField method. This method contains form element called 'hour' (`$form['week_day']['hour']`) and this element renders well. But this element also contains AJAX callback, which doesn't work, it does not generate 'person\_container' element and the 'person' select.

Any idea how to ajaxify elements that previously were rendered by ajax?

```
class ReservationForm extends FormBase {

  public function getFormId() {
    return 'reservation_form';
  }

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

    $form['month'] = array(
      '#type' => 'select',
      '#title' => $this->t('Select month'),
      '#options' => array($this->t('January'), $this->t('February'), $this->t('March')),
      '#ajax' => array(
        'callback' => array($this, 'extraField'),
        'event' => 'change',
        'wrapper' => 'week-day',
      ),
    );

    // Disable caching on this form.
    $form_state->setCached(FALSE);

    $form['week_day'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'week-day'],
    ];
  }

  public function extraField(array &$form, FormStateInterface $form_state) {
    $month = $form_state->getValue('month');

    $hour_options = array();

    if ($month == '0') {
      $hour_options[0] = $this->t('08:00');
      $hour_options[1] = $this->t('09:00');
      $hour_options[2] = $this->t('10:00');
    }

    if ($month == '1') {
      $hour_options[0] = $this->t('12:00');
      $hour_options[1] = $this->t('13:00');
      $hour_options[2] = $this->t('14:00');
    }

    if ($month == '2') {
      $hour_options[0] = $this->t('18:00');
      $hour_options[1] = $this->t('19:00');
      $hour_options[2] = $this->t('20:00');
    }

    $form['week_day']['hour'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose hours @month', array('@month' => $month)),
      '#options' => $hour_options,
      '#ajax' => array(
        // tried with that callback too: [ $this, 'choosePerson']
        'callback' => array($this, 'choosePerson'),
        'event' => 'change',
        'wrapper' => 'person',
      ),
    );

    $form['week_day']['person_container'] = array(
      '#type' => 'container',
      '#attributes' => ['id' => 'person-container'],
    );

    $form['week_day']['person_container']['person'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose person'),
      '#options' => ['John', 'Sarah', 'Peter'],
    );

    return $form['week_day'];
  }

  public function choosePerson(array &$form, FormStateInterface $form_state) {
    $form['week_day']['person_container']['person'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose person'),
      '#options' => ['John', 'Sarah', 'Peter'],
    );

   return $form['week_day']['person_container'];
  }
}

```

# Answer
> 9 votes
The Link 4k4 posted in the discussion of the question gives the solution:

> Create a callback function (named by the #ajax\['callback'\]). This is generally a very simple function which does nothing but select and return the portion of the form that is to be replaced on the original page. Note, that as part of the Form APIs security system, you cannot create new form elements in the callback function, as they will throw errors upon submission, and any #ajax on elements created in the callback will also not work. **If you need to create new elements on ajax submit, they must be added in the form definition.** You can use the values in $form\_state to determine whether the form build process is the initial form load, or an #ajax initiated load.

So the following code example is working.

```
class ReservationForm extends FormBase {

  public function getFormId() {
    return 'reservation_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['month'] = [
      '#type' => 'select',
      '#title' => $this->t('Select month'),
      '#options' => [
        $this->t('January'),
        $this->t('February'),
        $this->t('March'),
      ],
      '#ajax' => [
        'callback' => [$this, 'extraField'],
        'event' => 'change',
        'wrapper' => 'week-day',
      ],
    ];

    // Disable caching on this form.
    $form_state->setCached(FALSE);

    $form['week_day'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'week-day'],
    ];

    if ($form_state->getUserInput()['_triggering_element_name'] == 'month') {
      $month = $form_state->getValue('month');
      $hour_options = [];

      if ($month == '0') {
        $hour_options[0] = $this->t('08:00');
        $hour_options[1] = $this->t('09:00');
        $hour_options[2] = $this->t('10:00');
      }

      if ($month == '1') {
        $hour_options[0] = $this->t('12:00');
        $hour_options[1] = $this->t('13:00');
        $hour_options[2] = $this->t('14:00');
      }

      if ($month == '2') {
        $hour_options[0] = $this->t('18:00');
        $hour_options[1] = $this->t('19:00');
        $hour_options[2] = $this->t('20:00');
      }

      $form['week_day']['hour'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose hours @month', ['@month' => $month]),
        '#options' => $hour_options,
        '#ajax' => [
          'callback' => [$this, 'choosePerson'],
          'event' => 'change',
          'wrapper' => 'person-container',
        ],
      ];

      $form['week_day']['person_container'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'person-container'],
      ];

      $form['week_day']['person_container']['person'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose person'),
        '#options' => ['John', 'Sarah', 'Peter'],
      ];
    }

    if ($form_state->getUserInput()['_triggering_element_name'] == 'hour') {
      $form['week_day']['person_container']['person'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose person'),
        '#options' => ['Hans', 'Frank', 'Emma'],
      ];
    }

    return $form;
  }

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

  public function extraField(array &$form, FormStateInterface $form_state) {
    return $form['week_day'];
  }

  public function choosePerson(array &$form, FormStateInterface $form_state) {
    return $form['week_day']['person_container'];
  }

}

```

# Answer
> 1 votes
You can't change elements on callback or validateForm(), you need to put it on buildForm() method.

Here is a full example:

```
    /method buildForm
    $result = \Drupal\my_module\Controller\Contaminante::list(); //database logic
    foreach ($result as $it){
        $arrSelectContaminantes[$it["id_contaminante"]] = t($it["descripcion"]);
    }

    $form['select_contaminantes'] = array(
        '#type' => 'select',
        '#options' => $arrSelectContaminantes,
        '#ajax' => [
            'callback' => '::seleccionContaminantes',
            'disable-refocus' => false,
            'event' => 'change',
            'wrapper' => 'el-select-estaciones',
            'method' => 'replaceWith'
        ]
    );

    $selected_value = $form_state->getValue('select_contaminantes');
    $opciones = array();

    if(isset(selected_value)){
         $resultado;
         if($form_state->getValue("select_contaminantes") != 0){
            $opciones["0"] = t("ALL");
            $resultado = \Drupal\montar_mapa\Controller\Estacion::lista($form_state->getValue("select_contaminantes")); //DB LOGIC
        }else{
            $resultado = \Drupal\montar_mapa\Controller\Estacion::lista(); //DB LOGIC
        }

        foreach ($resultado as $it){
            $opciones[$it["id"]] = t($it["nombre"]);
        }
    }

    $form['select_estaciones'] = array(
        '#type' => 'select',
        '#id' => "el-select-estaciones",
        '#options' => $opciones,
        '#empty_option' => $this->t('-Select contaminante first'),
        '#validated' => TRUE,
    );

```

Really important:

Each time you print the dependent field ($form\['select\_estaciones') in example), must be validated ('#validated' =\> TRUE in options)

You need to compare the selected value of triggering field ($form\['select\_contaminante\] in example) if is null or not, if you compare directly, in case you get 0 value, interpretates as "no selection".

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