title: composer won't update 8.6.13

text:
# Question
Title: composer won't update 8.6.13
I can't update Drupal 8 from 8.6.10 to 8.6.13 -- please help!

composer.json -- partial

```
    "require": {
        "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "^1.4",
        "drupal/core": "^8.6.0",
        "drupal/bootstrap": "^3.11",
        "drupal/views_accordion": "^1.1",
        "drupal/token": "^1.1",
        "drupal/pdf": "1.x-dev",
        "drupal/pathauto": "^1.1",
        "drupal/contact_block": "^1.4",
        "drupal/blocktabs": "^1.0@alpha",
        "drupal/smtp": "^1.0@beta",
        "drupal/viewerjs": "1.x-dev",
        "drupal/group": "^1.0@RC",
        "drupal/field_permissions": "^1.0@RC",
        "drupal/libraries": "^3.0@alpha",
        "drupal/admin_toolbar_tools": "^1.23",
        "drupal/admin_toolbar": "^1.23",
        "drupal/alertbox": "^1.0@beta",
        "drupal/ctools": "^3.0",
        "drupal/login_emailusername": "^1.1",
        "drupal/anchor_link": "^1.6",
        "drupal/download_count": "1.x-dev",
        "drupal/views_data_export": "^1.0@alpha",
        "cweagans/composer-patches": "^1.6",
        "drupal/google_analytics": "^2.3"
    },

```

composer outdated "drupal/\*"

```
drupal/admin_toolbar       1.23.0       1.26.0      Admin Toolbar improve the default Drupal Toolbar, it lets the hover of sub menus.
drupal/admin_toolbar_tools 1.23.0       1.26.0      Adds menu links to the Admin Toolbar.
drupal/blocktabs           1.0.0-alpha6 1.0.0-beta3 Block Tabs.
drupal/bootstrap           3.11.0       3.17.0      Built to use Bootstrap, a sleek, intuitive, and powerful front-end framework for faster and easier web development.
drupal/coder               8.2.12       8.3.1       Coder is a library to review Drupal code.
drupal/core                8.6.10       8.6.13      Drupal is an open source content management platform powering millions of websites and applications.
drupal/csv_serialization   1.3.0        1.4.0       Provides CSV as a serialization format.
drupal/ctools              3.0.0        3.2.0       Provides a number of utility and helper APIs for Drupal developers and site builders.
drupal/field_permissions   1.0.0-rc1    1.0.0-rc2   The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
drupal/google_analytics    2.3.0        3.0.0       Allows your site to be tracked by Google Analytics by adding a Javascript tracking code to every page.
drupal/pathauto            1.2.0        1.3.0       Provides a mechanism for modules to automatically generate aliases for the content they manage.
drupal/smtp                1.0.0-beta3  1.0.0-beta4 Allow for site emails to be sent through an SMTP server of your choice.
drupal/token               1.1.0        1.5.0       Provides a user interface for the Token API and some missing core tokens.
drupal/views_accordion     1.1.0        1.2.0       Provides an accordion views display plugin.

```

composer update drupal/core --with-dependencies

```
Dependency "asm89/stack-cors" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "composer/semver" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "doctrine/annotations" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "doctrine/common" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "easyrdf/easyrdf" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "egulias/email-validator" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "guzzlehttp/guzzle" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "masterminds/html5" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "paragonie/random_compat" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "stack/builder" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony-cmf/routing" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/class-loader" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/console" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/dependency-injection" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/event-dispatcher" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/http-foundation" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/http-kernel" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/polyfill-iconv" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/process" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/psr-http-message-bridge" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/routing" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/serializer" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/translation" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/validator" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "symfony/yaml" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "twig/twig" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "typo3/phar-stream-wrapper" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "zendframework/zend-diactoros" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "zendframework/zend-feed" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update

```

# Answer
> 2 votes
```
option 1. composer update drupal/core --with-dependencies
option 2. composer remove drupal/core; composer require drupal/core:8.6.13 webflo/drupal-core-strict:8.6.13
option 3. (if all else fails) remove composer.lock and vendor directories, and then run composer require drupal/core:8.6.13

```

Pulled from comments so other ppl can read answers instead of looking through comments.

# Answer
> 0 votes
Updating drupal core is a little different on pantheon. Usually you would apply the update to core via the pantheon ui as seen here. See Drupal Security patches for an alternative method.

---
Tags: updating, composer
---


title: How to install drush properly

text:
# Question
Title: How to install drush properly
I am trying to install drush on my new computer and it's a mess
I'm on Mac Os High Sierra, with Mamp 5.3, PHP 7.2.14

I'm mainly interested in Drupal 7
On my previous computer, it was simple i just had to be on the htdocs folder and type : `drush dl` to download the latest Drupal 7 release

Now i had to install composer (v1.8.4) and then installed drush using this command : `composer require drush/drush:dev-master`
I ended up with this version of drush (v9.7.0-dev)
When i type drush dl i get this message :

```
dl has been deprecated. Please build your site using Composer. Add new projects with composer require drupal/[project-name]. Use https://www.drupal.org/project/composer_generate to build a composer.json which represents the enabled modules on your site.

```

I'm no advanced user (obviously), i just need drush to have persmission to execute basic commands to install a new drupal 7, install, enable, disable modules..

Here's the result of $PATH

```
Mac:htdocs Mac$ $PATH
-bash: /Users/Mac/.composer/vendor/bin:/Applications/MAMP/bin/php/php7.2.14/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin: No such file or directory

```

Thanks

# Answer
> 1 votes
If you read the Drupal compatibility table in the docs, you'll see that the correct version for Drupal 7 is Drush 8. The installation instructions for Drush 8 are simple and clear, no Composer required - just download a phar file.

PS! If you are planning on maintaining Drupal 8 sites (with Drush 9) too, I recommend getting Drush Launcher.

---
Tags: 7, drush
---


title: Shared Multisite Settings

text:
# Question
Title: Shared Multisite Settings
Using a Drupal Multisite system, is it possible to have a base set of configuration settings shared across multiple sites?

That is, each site in Drupal has a `settings.php` file

```
default/settings.php
site1/settings.php
site2/settings.php
anothersite/settings.php

```

Is there a master `settings.php` where I could set a configuration value once and have it apply to **all** my sites?

Or is this normally handled at the deployment level?

# Answer
> 2 votes
so for what it's worth using the `default/settings.php` as the master and then having each of the sites do a PHP include (as @Alan mentions) does work well! (*I know this is an old question but I am working through multisite issues with Drupal 8 (8.6.13) and have come across this very thing...*)

a couple of caveats:

1) I am managing the multisite installation and config manually so am creating *my own* `settings.php` files, not using `drush site-install` which will auto-generate the `settings.php`

2) you must do the include at the top of the site's `settings.php` and ensure that you are overriding only what you need to. (...or the inverse, that you are okay using the config in the default settings file)

I have this at the top of the `settings.php` for each site:

```
$default_path = "sites/default";
include $app_root . '/' . $default_path . '/settings.php';

```

and then override the database settings - setting the prefix etc:

```
$databases['default']['default'] = array (
  'database' => 'this_is_the_database',
  'username' => 'username',
  'password' => 'password',
  'prefix' => array(
    'default'         => 'site1_prefix_',
  ... etc

```

and the site name:

```
$config['system.site']['name'] = 'Site 1 Name will override default site name';

```

of course YMMV

tl;dr - yes you can, but be aware of the order in which your PHP will execute and apply the settings

# Answer
> 1 votes
The general consensus seems to be

> No, you can't do that

without resorting to a raw PHP include.

---
Tags: configuration
---


# Question
Title: AJAX button - HTML in #value causes problems
i have an Ajax button, the code looks like this:

```
class coolButtons {
  public function getFormFieldAjaxButton() {
    return [
      '#type' => 'submit',
      '#value' => t('<i class="  glyphicon glyphicon-refresh"></i> Ajax Button'),
      '#name' => 'ButtonAjax',
      '#submit' => ['ajax_submit'],
      '#ajax' => [
        'callback' => 'ajax_callback',
        'wrapper' => 'button-fieldset-wrapper',
      ],
      '#attributes' => ['class' => ['btn-primary btn-sm']],
    ];
  }
}

function cool_form ($form, &$form_state) {
  $buttons = new coolButtons();
  $form['fieldset-buttons'] = [
    '#type' => 'fieldset',
    '#title' => t('Buttons'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#prefix' => '<div id="button-fieldset-wrapper">',
    '#suffix' => ' </div>',
  ];

  $form['fieldset-buttons']['button_ajax'] =
        $buttons->getFormFieldAjaxButton();
}

function ajax_callback($form, $form_state) {
  if ($form_state['triggering_element']['#name'] == 'ButtonAjax') {
    return $form['fieldset-buttons'];
  }
}

function ajax_submit($form, &$form_state) {
  if ($form_state['triggering_element']['#name'] == 'ButtonAjax') {
    drupal_set_message('You clicked a very cool ajax button!');
  }
}

```

The value of the button has HTML in it, which causes problems.

1.) I can't have more than one of these buttons with html in the #value in one form, because then every button will perform the first defined statement in ajax\_callback and ajax\_submit regardless of the if statements (and thus, regardless of fieldset, #name etc.).

2.) At the bottom of the form, text will appear in the following form:

Ajax Button" /\>

Is there a way around it, or is the only solution to not use HTML in the #value of the buttons?

I am using Drupal 7.

---

Edit:

The slightly altered functions in `rdp_cellmodel.module`:

```
/**
 * Implements @see \hook_theme_registry_alter().
 */
function rdp_cellmodel_theme_registry_alter(&$theme_registry) {
  drupal_set_message('Boop?');
  if (isset($theme_registry['button'])) {
    $theme_registry['button']['function'] = 'rdp_cellmodel_button';
  }
}

/**
 * TODO: Description
 *
 * @param $variables
 *
 * @return string
 */
function rdp_cellmodel_button($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled'])) {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }
  if (!empty($element['#glyphicon'])) {
    $glyph_name = $element['#glyphicon'];
    return '<button' . drupal_attributes($element['#attributes']) . ' /><span
      class="glyphicon glyphicon-' . $glyph_name . '"></span> '.
      $element['#value'] .'</button>';
  }
  else {
    return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
}

```

And here the form field in a class file:

```
/**
   * @return array
   */
  public function getFormFieldGeneratePreview() {
    return [
      '#type' => 'submit',
      '#value' => t('Preview Name'),
      '#name' => 'PreviewButton',
      '#submit' => ['ajax_submit'],
      '#ajax' => [
        'callback' => 'ajax_callback',
        'wrapper' => 'hpscreg-fieldset-wrapper',
      ],
      '#attributes' => ['class' => ['btn-primary btn-sm']],
      '#limit_validation_errors' => [],
      '#glyphicon' => 'refresh',
      '#suffix' => '<div> </div>',
    ];
  }

```

Edit 2:

# Answer
> 2 votes
Here is the proper way of adding glyphicons to your buttons, you alter the button function and use a custom made one.

```
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['button'])) {
    $theme_registry['button']['function'] = 'mymodule_button';
  }
}

function mymodule_button($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled'])) {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }
  if (!empty($element['#glyphicon'])) {
    $glyph_name = $element['#glyphicon'];
    return '<button' . drupal_attributes($element['#attributes']) . ' /><span
      class="glyphicon glyphicon-' . $glyph_name . '"></span> '.
      $element['#value'] .'</button>';
  }
  else {
    return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
}

```

Then all you have to is add `#glyphicon` element to the submit and assign it the glyphicon name:

```
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => 'Send',
    '#glyphicon' => 'envelope', // in your case use "refresh"
  );

```

## Result:

---
Tags: forms, ajax
---


# Question
Title: How to use a contextual filter value in a menu displayed on the same page
I use a view to display a list of books sorted by title. The view has a contextual filter to limit the list by topic. So, a link to the view might be `/books-by-title/34` where 34 is the taxonomy term id for "self-help". The result is a list of self-help books in title order. Works great.

The user may also want to view the same books in popularity order, so I include a menu in the view header, one choice being "By Popularity". The menu link needs to be `/books-by-popularity/34`.

How do I pass the term id (34) from the URL into the menu link?

Seems like this should be easy, but after reading a dozen articles and trying several approaches, no success.

I should note that a given book be assigned more than one topic. For example, a "self-help" book may also be classified as being about "exercise". So I can't get the term id simply by looking at the topic field of the book.

# Answer
> 2 votes
Something about the answer by @No Sssweat got me thinking, so I searched differently and discovered that `arguments.field_topic_target_id` contains the value from the contextual filter. So, the answer is to my question is to use:

```
/books-by-popularity/{{ arguments.field_topic_target_id }}

```

as the Popularity link in the menu. Credit to @No Sssweat for providing the spark!

# Answer
> 1 votes
In Fields, add `field_taxonomy` (the field that references the tax term) and checkmark `☑ Exclude from display`.

In Header, add `Global: Text area (Global: Text area)` and checkmark `☑ Use replacement tokens from the first row` and use the proper replacement pattern.

Something like `/books-by-popularity/{{ field_taxonomy }}`

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


# Question
Title: How to get JSON data from exception in httpClient()
```
  public function myLogin() {
    try {
      $client = \Drupal::httpClient();
      $request = $client->post('https://targetApi.com/auth/login?fx=1', [
             'json' => [
                 'login' => 'demo',
                 'password' => 'demo1234567',
                 'locale' => 'en'
              ]
      ]);
      $response = json_decode($request->getBody());
      return $respone;
    } catch (\Exception $e) {
      \Drupal::logger('autoapp')->error($e->getMessage());
    }
  }

```

When I set wrong password I can catch this in $e-\>getMessage(). The message is:

```
Client error: `POST https://targetApi.com/auth/login?fx=1` resulted in a `404 Not Found` response:
{"error":"auth.user.notfound"}

```

So I can catch error, this is fine. But I'd like to get JSON data from It. And if in the `try` part I have it in `$request->getBody()`, how can I get it from $e ?

# Answer
This should work

```
if ($e->hasResponse()) {
    $response = $e->getResponse()->getBody()->getContents();
}

```
> 2 votes

---
Tags: 8
---


# Question
Title: Drupal website goes offline every 2 days for 15 minutes
We provide hosting services (Dedicated Server) to a client whose website is based on drupal. This month, his website goes offline for 15 minutes every 2 days.

We already have monitoring tools (i.e pinguzo) showing that the server never went down. And the log files show nothing that is related to this issue. Also, there is no crontab entry executing every 2 days.

And we already checked the website many times at the same hour, but we never encountered the website while offline.

Nevertheless, the client still sends reports about this issue, and we do not know what could be the culprit.

Where should I look? Is there anything in drupal that can cause this?

Thank you.

# Answer
Drupal can be configured to use a "poor man's cron" (exectuting jobs after a normal visitor's HTTP request). If you have access to the Drupal Admin UI, check `Admin > Reports > Recent log messages`, this is a core module helpful for debugging (it might be disabled though)
> 2 votes

---
Tags: cron
---


# Question
Title: Select list set default value does not work
I have referenced filed, which works like select list, I want first value be always default value in content edit page. Now N/A is always selected.

```
function theme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form['field_my_name']['und']['#default_value'] = 1;
}

```

This is my code, but it does not work

# Answer
To set the default value of field change the default value inside the widget like the following :

```
 $form['field_my_name']['widget']['#default_value'] = 1;

```
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Add preview button on Taxonomy add/edit term form
As we know that **entity type node** has **preview** button option which can be used during adding or editing of a node, to preview content.

Same feature is missing in case of **Taxonomy entity**.

If I want to add this feature where should I look into or is there any module available to achieve this?

# Answer
Preview button added by node module in NodeForm as `action` in actions method:

```
$element['preview'] = [
      '#type' => 'submit',
      '#access' => $preview_mode != DRUPAL_DISABLED && ($node->access('create') || $node->access('update')),
      '#value' => t('Preview'),
      '#weight' => 20,
      '#submit' => ['::submitForm', '::preview'],
    ];

```

The `Taxonomy entity` form created by TermForm.php so i think you should:

1. Extends `TermForm.php` in another Class.
2. Add `actions` method.
3. Create a `preview` method like the node preview method but for the term.
4. Add a route subscriber to tell drupal to load your form not the default.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Can I handle calculating/charging for shipping after order placed?
I am trying to determine if Drupal Commerce is the right ecommerce method to use for my client's project.

The workflow my client is looking for is:

1. Customer place order, and pays nothing for shipping.
2. My client will process order and determine shipping costs.
3. My client will charge customer for shipping, using CC data stored when they placed order.

Is this something that Drupal commerce can handle?

# Answer
Yes, because Drupal Commerce 2.x and most payment gateway modules tokenize credit card details by default for the sake of reusable "stored payment methods." From a customer experience standpoint, you might want to offer some sort of estimated shipping amount, but so long as you're communicating that shipping costs will be calculated and confirmed with the customer prior to charging, there's not technical reason you could not charge the full amount during the fulfillment process.
> 0 votes

---
Tags: commerce
---


title: How can I get flag count of a flag?

text:
# Question
Title: How can I get flag count of a flag?
I see extensive Drupal 7 documentation for the Flags module, but very little for Drupal 8. I have a Signup flag on a Drupal 8 node (which is an event). I need to suppress the Signup link when a number of signups (flags) have been added to this node.

I'm trying with `hook_preprocess_flag()` using the following code.

```
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById('signup');

```

What call gets the flag\_count of that flag?

# Answer
For flag count on entities use:

```
$flag_service = Drupal::service('flag.count');
$counts = $flag_service->getEntityFlagCounts($node);

```

For flag count on flag entity use:

```
$flag_service->getFlagFlaggingCount($flag);

```

You can find all functions from the Service here:

/modules/contrib/flag/src/FlagCountManager.php
> 4 votes

---
Tags: 8, flags
---


# Question
Title: Multisite config directories of subsides
I set up a local Drupal 8 multisite, using Acquia dev desktop. It's working fine. I added all Drupal 8 core files to my local repository and pushed them to a central remote repository.

* in `sites/default/settings.php` I added `$config_directories['staging'] = 'sites/default/config/staging';`to make the configuration directory versionable.
* All sites (main site, subside1 and subside2) has different databases

But what about the `sites/subside1/` and `sites/subside2/` config files? Do I have to add also a different path for those files? Do those have to be versioned or not?

I want to clone my repo to make instances of this multisite for staging and live environments.

# Answer
It's a little bit up to you how you manage your config. In my multisites I have a `../config` directory outside the web root. Each site instance then has it's own folder in there. And inside each one I split the config per environment.

`shared/` holds the config that is similar on all environments. `local/` holds all the extra config for local development. And `live/` holds the extra config for the live site. This can be achieved using the Config Split module.

```
project/
├── config/
│   ├── bar/
│   │   ├── live/
│   │   ├── local/
│   │   └── shared/
│   └── foo/
│       ├── live/
│       ├── local/
│       └── shared/
└── web/
    └── sites/
        ├── bar/
        └── foo/

```

The `settings.php` config for the `foo/` instance then looks like this:

```
$config_directories['sync'] = '../config/foo/shared';

```

And the Git-ignored `settings.local.php` on my local machine looks like this:

```
$config['config_split.config_split.local']['status'] = TRUE;
$config['config_split.config_split.live']['status'] = FALSE;

```

Whereas on the live server it looks like this:

```
$config['config_split.config_split.local']['status'] = FALSE;
$config['config_split.config_split.live']['status'] = TRUE;

```
> 2 votes

# Answer
if you are okay with the configs for the subsites mixing with the default site then you can set the config directory to be the same as is in `default/settings.php` by adding to the `sites/subsite1/settings.php` and `sites/subsite2/settings.php`

```
$config_directories['sync'] = '../config/sync';

```

(relative to the site root, not subsite root)

if you want to manage the subsite configs completely separate from the default site then you could in theory set these unique to each site - so in `sites/subsite1/settings.php`

```
$config_directories['sync'] = '../config/subsite1_sync';

```

... this possibly might be more problematic since you now have as many discrete configs as you do subsites, but it depends on what config settings you need to sync I suppose.

this is also explained more by @AjitS here: https://drupal.stackexchange.com/a/271321/91863 \- where it is also recommended to explore the `config_split` and `config_filter` contrib modules
> 1 votes

---
Tags: 8, configuration
---


# Question
Title: Contextual filter "Allow multiple values" is gone
Why can't I see the "More - Allow multiple values" option on my contextual filter product view?

This is my view:

This is what should appear:

# Answer
> 1 votes
Found the reason: My site was in maintenance mode and the green message was preventing the block to appear... So it's a matter of css. Super stupid, but it took me a while to figure that out. Might be useful to someone having the same issue.

---
Tags: views, 8
---


# Question
Title: Views with tables have different column width with same setting
I'm having problems with drupal views. I used a table to make a list of items with an image, a title and a body each. The first time I tried it it worked perfectly, each column only taking the necessary space but when I tried to recreate it, the title column is very wide. I check all the settings in both the views and the content and they are the exact same.

Here is the first table  And this is what the new ones look like  Do you know why that could be?

Thanks in advance!

# Answer
I think it is html table generic behaviour, as browser's determining widths of individual table cells are a complicated matter. You would get the same widths if your columns had the same contents inside but since some columns are different you are getting different column widths.

Drupal views *table display style* outputs generic tables without any width specified. You can influence widths by using something like the following in your theme's css

```
table.views-table td:nth-child(2) {
  width: 150px;
}

```

Above specifies width for the 2nd `TD` tag of a views table. Change position of TD and width to your liking.
> 0 votes

---
Tags: views
---


title: What does this error message mean?

text:
# Question
Title: What does this error message mean?
My website is getting too slow. When I checked the journal entries, I found many errors like the following.

>

What is it? What are they trying to do?

# Answer
Those are probably bots trying to find security holes to exploit on your server/website.

The best way to prevent them is with firewall and other security measures on your server. Most control panels have firewalls included but might need a little configuration before they run properly. Firewalls usually ban IPs depending on their bad behaviour.

This subject is probably off-topic for the Drupal forums but if you want an extra measure blocking IPs within Drupal you can consider using AutoBan IP here is a basic setup.
> 3 votes

# Answer
It's a tentative to detect which software is used to build the site; in the specific, they are trying to understand if the site is built with Visual DataFlex, a forth generation programming language geared towards creating database and client/server type applications. The .dfr extension is used for the Visual DataFlex license file.
It's similar to those attempts to access a URL used from WordPress to understand if the site is built with WordPress.

Once they know what is used to built the site, they can take advantage of specific vulnerabilities to get access to reserved information or cause denial of service.
> 3 votes

---
Tags: security
---


title: Filter upon paste in CKEditor

text:
# Question
Title: Filter upon paste in CKEditor
My stakeholders encountering a situation where they have to do finagling in the CKEditor window when they copy and paste from Google Docs, which they do often.

Ideally, what would happen is that inline styling information is stripped out from pasted tags, while preserving other styling information. For instance, here's the tag for some large-sized text, copied from Google Doc's resume template, and pasted in to CKEditor in Drupal 8.6.13:

```
<span style="font-size:36pt;font-family:Merriweather;color:#000000;background-color:transparent;font-weight:700;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;">Your Name</span></p>

```

Is there a way to strip out the `font-style` and `font-size` attributes on page? I've googled for information on the Drupal side, and also on the CKEditor site, but I haven't found positive confirmation that this is possible.

I see that there are modules for CKEditor that provide a "Paste from Google Docs" button, but my team doesn't want another button they have to remember to use when they are pasting from Google Docs -- they want this to work with the default paste functionality. We will never be using the source font-size and font-family, because we have a style guide for our entire site which is standardized.

I am aware that typeface can be handled differently (e.g. styling tags as bold instead of using font-weight:bold, etc), but we can deal with that. What I am looking for is how to get rid of the font family and font size.

As regarding custom text filters, I looked at this tutorial and downloaded and installed the sample celebrate custom text filter module. Upon testing, I confirmed that it only changed text when I saved the node, not when I pasted into the CKEditor textarea widget. So a custom text filter module does not do what I want.

# Answer
> 0 votes
I found the CKEditor custom config module. This allows one to specify arguments to ckeditor's config object. This module provides me as much configuration as CKEditor allows.

I am still testing if I can filter specific inline styles, but if I can't do that, then that's an inability of CKEditor, not Drupal's ability to interact with it.

---
Tags: wysiwyg
---


# Question
Title: Disable (or workaround) form rebuild with managed_file field
I'm using the Form API to create a custom form. It has a `managed_file` field and some other fields, some of which are required. If *any* of the required fields are not filled in, the file upload for the `managed_file` field doesn't work, and produces an error informing the user to fill out the required field first before the image upload can process.

I'm assuming this is because the form is being rebuilt when the form uploads, but is there a way to stop it from checking for required fields? Surely there is a way, as node edit forms have this functionality working.

Here is my form code (simplified):

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

  $form['event_image'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array(
      'file_validate_extensions' => array('jpg jpeg gif png')
    ),
    '#upload_location' => 'public://event_images/',
    '#required' => FALSE,
  );

  $form['event_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Event Name'),
    '#required' => TRUE,
  );

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

  return $form;
}

```

If `event_name` field is empty when attempting to upload a file, the upload will not process.

# Answer
> 0 votes
This was happening due to the Clientside Validation module being enabled.

For anyone having this issue, I had to override the form settings in Clientside Validation for this particular form, setting "Validate fields on submit" to "No".

---
Tags: 7, forms
---


# Question
Title: Can I still share data tables with multisite, using shared database, in Drupal 8 or do I need to use 'Domains' contrib module?
I have a multi-site setup that is working in Drupal 8 (8.6.13) - all of the sites share the code-base and database happily but I cannot seem to share ***data*** tables between the sites using the prefix array method - has this changed in Drupal 8 since older versions?

... I start off asking this since **most of the data I am finding is for Drupal 7 or older** and the solutions given seem valid but are not fully working when I try to implement them.

For example - I want a base (default) site to handle taxonomy, content types, and some admin functions like REST APIs. Each site can handle it's own content and theme (there are no users to worry about) and the `sites/multi-site-1/settings.php` is configured to handle this properly (I think).

in the base `settings.php`:

```
$databases['default']['default'] = array(
  'database' => 'base_database',
  'username' => 'db_user',
  'password' => 'db_password',
  'prefix' => array(
    'default'             => 'base_',
// ** content type and fields seem to share okay!
    'content_type_' => 'shared_',
    'content_field_' => 'shared_',

// ** the other tables with 'shared_' prefix that do not work shown below

```

and in the `sites/multi-site-1/settings.php`:

```
$databases['default']['default'] = array (
  'database' => 'base_database',
  'username' => 'db_user',
  'password' => 'db_password',
  'prefix' => array(
    'default'         => 'site_1_',

// ** can these even be shared?
    // 'config'              => 'shared_',
    // 'config_snapshot'     => 'shared_',

// ** users related things have errors when installing multi-site-1
    //'authmap' => 'shared_',
    //'profile_fields' => 'shared_',
    //'profile_values' => 'shared_',
    //'permission' => 'shared_',
    //'role' => 'shared_',
    //'sessions' => 'shared_',    //1. error - if sharing site won't even start install
    //'user' => 'shared_',        //3. error - "EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY': "
    //'users' => 'shared_',
    //'users_roles' => 'shared_', //2. error - "The "user_role" entity type does not exist."
    //'users_data' => 'shared_',  //2. error - "Table users_data already exists"
    //'users_field_data' => 'shared_',

// ** taxonomy related share seems okay but not working?
    //'taxonomy_index' => 'shared_',
    //'taxonomy_term_data' => 'shared_',
    //'taxonomy_term_field_data' => 'shared_',
    //'taxonomy_term__parent' => 'shared_',
    //'vocabulary' => 'shared_',       // 1. install error - not present in D8 db?
    //'vocabulary_node_types' => 'shared_',
    //'term_data' => 'shared_', // not present in D8?
    //'term_hierarchy' => 'shared_', // not present in D8?
    //'term_image' => 'shared_', // not present - n/a?
    //'term_lineage' => 'shared_', // not present - n/a?
    //'term_node' => 'shared_', // not present - n/a?
    //'term_relation' => 'shared_', // not present - n/a?
    //'term_synonym' => 'shared_', // not present - n/a?
  ),
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
  'collation' => 'utf8mb4_unicode_ci',
);

```
1. Should I abandon the multi-site config in this manner and rely on a contrib module like Domain Access? (I have tried to set this up but cannot seem to get it configured properly - or am not even sure what it is supposed to be doing for me).
2. Is this still a good way to share data in the database in Drupal 8 or am I missing something?
3. Am I adding in too much of the old v7 and v6 multi-site logic and Drupal 8 handles this differently?

any insights into how to do this better would be greatly appreciated!

---

some answers already read and referenced:

# Answer
> 2 votes
posting my own answer with a brief explanation...

I have investigated the Config Split and Features modules and found that they are not providing what we need for this instance of Drupal running a set of sites.

The shared data and other interoperability that I need to be common between sites is not handled as I expect it to be... so my solution will be to have the Drupal instance direct users to the appropriate content on the site via redirects at the web server and then appropriate usage of paths and contextual filters.

If any other people find themselves here trying to answer similar questions with regards to Drupal 8 please take these into consideration:

```
    ## multi-site-1 ==> _workspace/base-site/web/sites/multi-site-1
       <VirtualHost *:80>
          DocumentRoot "/var/www/base-site.com/web"
          ServerName multi-site-1.com
          ServerAlias www.multi-site-1.com

          <Directory />
            Options FollowSymLinks
            AllowOverride None
          </Directory>

          <Directory "/var/www/base-site.com/web">
              Options FollowSymLinks Multiviews Indexes
              AllowOverride All
              Order allow,deny
              Allow from all
              Require all granted
              MultiviewsMatch Any
          </Directory>

          ErrorLog "/private/var/log/apache2/multi-site-1.com-error_log"
          CustomLog "/private/var/log/apache2/multi-site-1.com-access_log" common
      </VirtualHost>

```

and maybe something like this in `.htaccess`:

```
RewriteCond %{HTTP_HOST} ^(?:www\.)?multi-site-1\.com(.*)$ [NC]
RewriteRule ^(.*)$ https://www.base-site.com/multi-site-1/$1 [L]

```

and thanks again to @leymannx for your help on this!

---
Tags: 8, multi-sites, domain-access
---


# Question
Title: Is this acceptable for passing data from a module to a template?
I'm attempting to pass some data from a block module into a template. I've found that I can make up a render array property and then access it in the template. Here is an example of my code:

```
class MyBlock extends BlockBase {
      return [
        '#firstname' => 'John',
        '#lastname' => 'Doe',
      ];
    }

```

I can access this data in the twig templeate by using:

```
{{ elements.myblock.content['#firstname'] }}
{{ elements.myblock.content['#lastname'] }}

```

Is this an acceptable means for passing data into a template? All the other examples I've found have the render arrays being picked up by a hook\_theme function and then getting passed to the template. The method I show above seems simpler and I'm wondering if there is something problematic with doing it this way.

Thanks!

# Answer
If you pass the variables like the following:

```
class MyBlock extends BlockBase {
  public function build() {
    return [
      '#firstname' => 'John',
      '#lastname' => 'Doe',
    ];
  }
}

```

You can access to your variables `#firstname` and `#lastname` like:

```
{{ content['#firstname'] }}
{{ content['#lastname'] }}

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Change target type of entity reference field in update hook
In an update function, I'm trying to change the `target_type` of an entity reference field, following the approach outlined on https://www.drupal.org/node/2535476). The previously used target entity type (its class) has been removed from my site (I'm removing it as part of the update).

Something like this in the update function:

```
$field_storage_config = FieldStorageConfig::loadByName('entity_type', 'field_name');
$field_storage_config->setSetting('target_type', 'new_entity_type');
$field_storage_config->save();

```

When I call `$field_storage_config->save()`, I get a fatal error saying the previously used target type (the one that's been removed) no longer exists. It seems that the `save()` method eventually calls `\Drupal\Core\Entity\EntityTypeManager::getDefinition` for the removed entity type, leading to the fatal error.

Any way to get around this, so I can switch the target type from the removed entity type to an existing one in my update function?

# Answer
> 1 votes
I dealt with this issue a few months back in the jQuery Colorpicker module. I was converting all fields of one type (jquery\_colorpicker), to fields of an entirely different type (colorapi\_color). With the update of the module from 8.x-1.x to 8.x-2.x, I intended to remove the the original type/plugin (jquery\_colorpicker). Then in the update script I intended to loop through each field on every entity type, and if it was jquery\_colorpicker, change it to colorapi\_color. However deleting the plugin led to the same issue you are running into, where I was getting an error about mistting the field type that I had removed.

In the end to get around this problem, I took a different approach altogether. I left the definition plugin file for the jquery\_colorpicker field in the file system, but marked it as deprecated:

```
/**
 * Provides the Color field.
 *
 * @FieldType(
 *   id = "jquery_colorpicker",
 *   label = @Translation("Color (deprecated)"),
 *   default_formatter = "colorapi_color_display",
 *   default_widget = "colorapi_color_widget",
 * )
 *
 * @deprecated as of Jquery Colorpicker update 8200. Will be removed in Jquery
 *   Colorpicker 8.x-3.x, and/or 9.x-1.x. Running
 *   jquery_colorpicker_update_8200() requires the existence of this field type,
 *   however the field type is obsolete after that update has been run. As such,
 *   if the schema version is equal to or above 8200, the field type is removed
 *   from the list of field types in jquery_colorpicker_field_info_alter().
 */

```

Link: https://cgit.drupalcode.org/jquery\_colorpicker/tree/src/Plugin/Field/FieldType/JqueryColorpickerColorItem.php#n9

Then I set the system to remove the field type from Drupal's list of field types when the current installed version of the module is 8200+:

```
/**
 * Implements hook_field_info_alter().
 *
 * @deprecated as of Jquery Colorpicker update 8200. Will be removed in Jquery
 *   Colorpicker 8.x-3.x, and/or 9.x-1.x.
 *
 * @see jquery_colorpicker_update_8200()
 */
function jquery_colorpicker_field_info_alter(&$info) {
  // Running jquery_colorpicker_update_8200() requires the existence of the
  // jquery_colorpicker field type, however the field type is obsolete after
  // that update has been run. As such, if the schema version is equal to or
  // above 8200, the field type is removed from the list of field types.
  if (drupal_get_installed_schema_version('jquery_colorpicker') >= 8200) {
    unset($info['jquery_colorpicker']);
  }
}

```

Link: https://cgit.drupalcode.org/jquery\_colorpicker/tree/jquery\_colorpicker.module#n45

With the above code, before the update is run, the version will be less than 8200. Any time the system builds the list of field types, the jquery\_colorpicker field type is available, meaning that when the update script is run, the field type is still available, so you won't get the error about it missing.

After the update has been run, the version will be 8200 (or greater), and therefore the jquery\_colorpicker field type should no longer be available. Therefore it is removed from the list of field types.

If/when version 8.x-3.x of the module is released, I will remove the jquery\_colorpicker plugin file altogether. For now, it's still in the codebase, but deprecated and unused.

---
Tags: 8, entities, updating
---


# Question
Title: File to media migration: use node title for media title
I have my files migrated from D7 to D8 (using `d7_file` source plugin to an `entity:file` destination).

I then migrated those files to media (using `file_entity` source plugin to an `entity:media` destination), based off this post.

However, the images in my Drupal 7 nodes of which I'm migrating never had alt text. Therefore, I would like to use the Drupal 7 node title as both (a) the Media title and (b) its image alt text.

My files to media migration looks like this (a portion of it):

```
source:
  plugin: file_entity
  type: image
  constants:
    bundle: 'image'
process:
  mid: fid
  bundle: 'constants/bundle'
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  # name: filename
  uid:
    plugin: default_value
    default_value: 1
  status: status
  created: timestamp
  changed: timestamp
  field_media_image/target_id: fid
  # field_media_image/alt: field_file_image_alt_text/0/value
destination:
  plugin: entity:media

```

The commented out lines are what I'd like to use the node title (`name` and `field_media_image/alt`), but I'm not sure how to pull in the original Drupal 7 node title. Any suggestions are appreciated.

# Answer
Without knowing your content model, you can't answer this question directly, but what you'll need to do is query your node title for every `fid` entry for your source file entities table. You can do that in many places (e.g. source/process plugin) with your existing source plugin being a good place.

Using your custom `file_entity` source plugin as an example, you'll need to update the `query()` method so its DB query joins the `node` table based on how you're content is modeled (e.g. entity/paragraph references) then selects the `title` column so it's included in the row data. You can follow that up with updating the `fields()` method so your source plugin will provide the `title` field you need.
> 0 votes

---
Tags: migrations
---


# Question
Title: How to get current product id from custom block?
I've problem to get current product id from custom block displayed on product page. Here my code :

```
class TestBlock extends BlockBase {

  public function build() {

$product = \Drupal::routeMatch()->getParameter('node');

$productid = $product->product_id();

return array(
 '#markup' => $this->t('Product ID : ') . '<h2>' . $productid . '</h2>',

    );
  }

}

```

Do you have any idea to get the current ID from product ?

Thank you for your help.

# Answer
Use this below code to get product ID

```
$product_id = \Drupal::routeMatch()->getParameter('commerce_product')->id();

```

and then return the value in custom block,

```
return [
      '#product_id' =>  $product_id,
    ];

```
> 0 votes

# Answer
Like, such code should work:

```
$product_id = \Drupal::routeMatch()->getRawParameter('commerce_product');

```

But in my case it is not working. But it work:

```
$paramList = \Drupal::routeMatch()->getRawParameters();
foreach($paramList as $paramName=>$paramVal) {
    // save params to any variables...
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: search_update_totals() is not invoked / or search_cron() is not invoked
I don't know when, but this is new: in my Drupal 7 installation the indexing of search terms doesn't work anymore.

Here is a trace, but don't know how to solve it: it seems that in /modules/search/search.module the search\_cron() is not invoked anymore. And that is why necessary inserts in the database table search\_total are ommitted.

Any ideas?

Thanks Selim

# Answer
In some circunstances, you need to call `search_update_totals()` after indexing. The reason is that you need to make sure that it runs from the same location that you ran search\_index, and after it.

In theory it is always called when you index using a cron job, but I am indexing with a drush command and I had to call it manually at the end. If the cron run failed it won't be called.
> 0 votes

---
Tags: search
---


# Question
Title: How do I use a views data with a paragraph?
I have a content type with dynamic content block section. Each block section is managed by paragraph bundle.

Let's explain using an example to make more clear-

1. Content type name is Employee.
2. A paragraph field is added in the employee content type. Field machine name is **field\_body\_contents**
3. All paragraph bundle is showing in dropdown and admin can select the paragraph bundle to add content with the employee.
4. We have created the template for each paragraph bundle and these are rendering perfectly on the template file.

Now there is a new case that we need to embed the views data with the **field\_body\_contents** dropdown so that admin can section views from the dropdown to inject views data between paragraph bundle.

# Answer
The way I've done this is to preprocess the paragraph and alter the $variables\['content'\] to contain the views data/render array you've retrieved programatically:

```
function HOOK_preprocess_paragraph(&$variables) {
  if ($variables['paragraph']->type->target_id == 'yourparagraph') {
     //code to get the view you want
     ...
     ...
     $variables['content']['view_content'] = $theviewdata;

  }
}

```
> 0 votes

---
Tags: 7, views, paragraphs
---


title: Template page for specific node

text:
# Question
Title: Template page for specific node
I have seen a ton of examples on how to do this and I must just be fundamentally confused. I want to modify one node, in my case nid 302998. I have tried:

```
node-302998.tpl.php
page-node-302998.tpl.php
node--302998.tpl.php
page--node--302998.tpl.php

```

All to no avail. I am placing them in my templates folder. In that folder I see a few working examples of tpl files, such as `node--glove.tpl.php`, glove being one of my content types, but I see no examples of specific nodes/pages. I have tried clearing caches as well. I am out of ideas.

# Answer
You can override every single node with its node id, as per your nid it should work with node--302998.tpl.php then also if its not working just enable debug mode so you can get idea how many template name available.

To enalbe debug mode open setting.php `$conf['theme_debug'] = TRUE;`
refresh page again and press `ctrl + U` for view source.
you will get all the name those are possible with your page.
> 1 votes

# Answer
Have you added a copy of the standard node.tpl.php file into your theme folder as well? It's required if you want to override the node template.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How do I move a site from a server to another one?
I am trying to move a Drupal 8 site, but I get the following error:

> The website encountered an unexpected error. Please try again later.
>
> InvalidArgumentException: Class "\Drupal\system\Controller\Http4xxController" does not exist. in Drupal\Core\DependencyInjection\ClassResolver-\>getInstanceFromDefinition() (line 29 of core/lib/Drupal/Core/DependencyInjection/ClassResolver.php).

How do I properly move a Drupal 8 site from a server to another one?

What I did was importing the database, moving the files, and changing the database connection settings.

# Answer
In a nutshell, moving a Drupal website from one host to another is just a matter of moving the files and the database, and then connecting the two.

However, there are several things you need to consider:

1. Server environment should be as close as possible to each other. This way you will avoid any errors that are a result of having different software/configuration on production and development servers. Compare PHP version, MySQL version, Apache modules, and setup of all of these components.
2. File permissions need to be set up properly. I've seen problems caused by this dozens of times. In short, the Apache user needs to have enough permissions to access and work with your Drupal website. Otherwise, it won't be able to write and even read files in some cases. Read more about how to secure correct file permissions here.
3. If you do this manually via FTP, make sure that all files are transferred. It often happens that one of the files wasn't uploaded completely. This usually results in broken Drupal site and random errors. Other ways to migrate a D8 website are Drush, Git or simply zipping the whole directory and using `wget` on the other server to transfer it directly from server to server.
4. You will need to clear all caches. Preferrably you won't have CSS/JS aggregation and page caching turned on when you migrate the database. You can do this through SQL/phpMyAdmin. See this answer for more information.
5. Update trusted hosts in `/sites/default/settings.php` file.
6. Once you can access your website, update the temporary directory path at `/admin/config/media/file-system`, as well as any other settings (e.g. of contrib modules) that store server paths/domain name.

See also docs on migrating a D7 site. Most items are still applicable for D8.

---

If you follow the guidelines above, you will avoid most issues. If you still have problems after migration, post here the exact log messages you're receiving.

Regarding the error you already posted: I'd make sure that all files are there, and that your cache is cleared before doing anything else.

Hope this helps.
> 10 votes

# Answer
I got the same error when porting Drupal 8 to localhost.

In my case I found a solution visiting **mysite/core/install.php** location.

There I saw a detailed error: when backing up from /admin/config/development/backup\_migrate some tables were missing. So I backed up full database from phpmyadmin, and problem was solved.
> 1 votes

---
Tags: 8, migrations
---


# Question
Title: Is there a way to to allow webforms accept case sensitive keys?
I've been using the webform module for Drupal 8, and initially it appears as though the webform submission handlers only send through submission keys as all lowercase.

Is there any way to get around this? I need case sensitive keys in order for the webform submissions to interface with another platform, which is case sensitive.

# Answer
> 0 votes
For that you may have to create handler and activate that handler after the webform submission, get the keys as a simple text field perform the hash operation on it and then save to database. webform supports this -

---
Tags: webforms
---


title: Jquery and Drupal Autocomplete

text:
# Question
Title: Jquery and Drupal Autocomplete
I have an autocomplete field in a custom form which works and returns a pipe-seperated value which I want to then split up and insert into the appropriate form fields. For example, the autocomplete field returns 'Last|First|ID' such as 'Smith|John|123456789' and I want to assign these values to other form fields and replace the current value of the auto complete field with the last name.

I have successfully gotten the ID and the First Name to be populated using jquery, but the last name in the auto complete field WILL NOT CHANGE.

Some observations: if I first alert the value of the field, it changes. It's as if the script is running too fast and skips over the step to set the value of the autocomplete field. It also appears to work with other event firings instead of .change, such as .blur, or .keyup - but the thing is I need it to be .change or else it won't work for all cases.

Here's my jquery code:

```
$('#edit-emp-lname').change( function () {
    var empName = $(this).val();
    //alert($(this).val());
    var empArray = empName.split("|");

 //The following line is basically ignored. All other following lines work successfully.
    $(this).val(empArray[0]);
    $('input[name="emp_fname"]').val(empArray[1]);
    $('input[name="emp_uid"]').val(empArray[2]);
});

```

**Update** In order to make this work properly and in IE to boot I had to do some extra code, shown below:

```
$('#edit-emp-lname').change(function() { doChange(); }).attr("onchange", function() { doChange(); }).blur( function() { doChange(); });
function doChange() {
    var empName = $('#edit-emp-lname').val();
    var empArray = empName.split("|");
    setTimeout( function () {
        $('#edit-emp-lname').val(empArray[0]);
        }, 10);
    $('#edit-emp-fname').val(empArray[1]);
    $('#edit-emp-uid').val(empArray[2]);
}

```

# Answer
> 0 votes
In order to make this work properly as well as in IE, I had to trigger a function onChange rather than calling it in the closure directly.

```
$('#edit-emp-lname').change(function() { doChange(); }).attr("onchange", function() { doChange(); }).blur( function() { doChange(); });
function doChange() {
    var empName = $('#edit-emp-lname').val();
    var empArray = empName.split("|");
    setTimeout( function () {
        $('#edit-emp-lname').val(empArray[0]);
        }, 10);
    $('#edit-emp-fname').val(empArray[1]);
    $('#edit-emp-uid').val(empArray[2]);
}

```

# Answer
> 1 votes
If I want to display in autocomplete all this field I will use hook\_form\_alter I will change the value of autocomplete with another function so this is what i will do

```
function hook_form_alter() {
  $form['field_selectedarticles']['und'][0]['nid']['#autocomplete_path'] = 'autocomplete/filteration';
}

function autocomplete_filteration($string) {
  //select * fields I want
  print drupal_json_output($items);
}

```

# Answer
> 0 votes
Make the following changes in the file at /misc/autocomplete.js

change:

```
Drupal.jsAC.prototype.select = function (node) {
  this.input.value = $(node).data('autocompleteValue');
};

```

to:

```
Drupal.jsAC.prototype.select = function (node) {
  this.input.value = $(node).data('autocompleteValue');
  $(this.input).trigger('change');
};

```

this will allow the change trigger to work when the choice in the autocomplete list is clicked.

In order for the change to trigger when it is selected with arrow keys and pressing enter, you need to add the trigger in the hidePopup function changing:

```
Drupal.jsAC.prototype.hidePopup = function (keycode) {
  // Select item if the right key or mousebutton was pressed.
  if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) {
    this.input.value = $(this.selected).data('autocompleteValue');
  }
  // Hide popup.
  var popup = this.popup;
  if (popup) {
    this.popup = null;
    $(popup).fadeOut('fast', function () { $(popup).remove(); });
  }
  this.selected = false;
  $(this.ariaLive).empty();

};

```

to:

```
Drupal.jsAC.prototype.hidePopup = function (keycode) {
  // Select item if the right key or mousebutton was pressed.
  if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) {
    this.input.value = $(this.selected).data('autocompleteValue');
    $(this.input).trigger('change');
  }
  // Hide popup.
  var popup = this.popup;
  if (popup) {
    this.popup = null;
    $(popup).fadeOut('fast', function () { $(popup).remove(); });
  }
  this.selected = false;
  $(this.ariaLive).empty();

};

```

Once you make these changes to the autocomplete.js file, you should be able to call the .change trigger like normal.

---
Tags: javascript, ajax
---


# Question
Title: How to print the 'authored on' date in the template (twig file)?
I looked at the solutions provided for similar questions but they all post the date the article was updated on.

This is what I use: `<h2>{{ post.getCreatedTime|date("Y") }}</h2>`

I just want to print the year.

# Answer
The variable name is not 'post', it should be 'node' and the filter is `format_date`:

`{{ node.getCreatedTime|format_date('date_format_machine_name') }}`
> 1 votes

# Answer
You can use {{ date }}.

Just leave editing of the altered on no content type enabled. Which case is changed will be displayed in this same variable
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: index.php is added in front of paths for anonymous users
I have a new Drupal 8.0.4 site running on Nginx, and I just noticed that the paths for anonymous users have a superfluous `index.php` in front of them.

So instead of

```
mysite.com/node/123

```

I get the following when not logged in

```
mysite.com/index.php/node/123

```

I'm not entirely sure if it was this way since I started building the site, because I was usually logged in I might not have noticed it. But it could also have happened only since I upgraded Drupal core to the latest minor version.

My Nginx configuration is based on the official Nginx recipe for Drupal, with some small differences in the php-fpm configuration for PHP 7.

As mentioned in the comment by Sachbearbeiter, this seems to be an intermittent issue. I don't see it anymore now on my site, some days later.

Any idea what is causing the index.php to be inserted and how I can get rid of it at all times?

# Answer
> 2 votes
This is mainly an SEO issue. Search engines seem to like unclean URLs with index.php. Once they found one all internal links on your site also contain index.php and so they sometimes crawl the entire site in this namespace.

You have to return a 301 redirect for any unclean URL to stop this. Install the module Redirect and go to the module settings */admin/config/search/redirect/settings*:

> **GLOBAL REDIRECTS**
>
> \[x\] Enforce clean and canonical URLs.
>
> *Enabling this will automatically redirect to the canonical URL of any page. That includes redirecting to an alias if existing, removing trailing slashes, ensure the language prefix is set and similar clean-up.*

# Answer
> 0 votes
To me this is happening when using path `‹front›` which is used in `block--system-branding-block.html.twig`. I just fixed it like this:

old:

```
{{ path('‹front›') }}

```

fix:

```
{{ path('‹front›')|replace({'index.php/': ''}) }}

```

---
Tags: uri, 8
---


title: Add HTML Tags for all the site pages

text:
# Question
Title: Add HTML Tags for all the site pages
I was searching around but with no clear solution for me!

I would like to add the below HTML code for all my Drupal 8 website pages:

```
<meta name="viewport" content="width=device-width, user-scalable=no" />

```

How can I do that, is there a contributed module for it ?

Thank you,

# Answer
> 4 votes
# 1. Using metatag module

If you want to do it without custom coding you can try metatag module

* enable *MOBILE & UI ADJUSTMENTS* submodule
* go to metatag settings *admin/config/search/metatag*
* edit the *GLOBAL* settings
* under *MOBILE & UI ADJUSTMENTS* fill in *viewport* input box

# 2. Using viewport module

There is also a dedicated module called viewport which will allow you to do just that.

# 3. In your custom theme

But can be easily done in your custom theme. Put the following code inside the `THEMENAME_preprocess_html` function in your `THEMENAME.theme`

```
function THEMENAME_preprocess_html(&$variables) {
  $viewport = [
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => [
      'name' => 'viewport',
      'content' => 'width=device-width, user-scalable=no',
    ],
  ];
  $variables['page']['#attached']['html_head'][] = [$viewport, 'viewport'];
}

```

**NOTE:** if `THEMENAME_preprocess_html` function does not exist you can create it and put the code inside. You can't redeclare it otherwise you will end up with WSOD.

```
function THEMENAME_preprocess_html(&$variables) {
  //...
}

```

# Answer
> 4 votes
## A) Theme Template

Probably the simplest way to add a `viewport` metatag is to edit your site theme's `html.html.twig` template.

If you don't yet have a custom theme for your site, and are only using a builtin or contributed theme, you can read the Drupal 8 Themeing Guide to find out more about how the theme system works, and how to create a sub-theme for your site.

## B) Page Attachments

Another way to add additional metatags is by implementing hook\_page\_attachments() in a module. This is usually done when the value of the metatag may change, but works fine with a constant value as well.

```
function MY_MODULE_page_attachments(array &$attachments) {
  $attachments['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'viewport',
        'content' => 'width=device-width, user-scalable=no',
      ],
    ],
    'meta-viewport',
  ];
}

```

---
Tags: 8, theming
---


# Question
Title: updates page shows an error for a mystery module 'standard 8.6.12'
on the updates page `/admin/reports/updates` under Modules there is a module called **standard 8.6.12** as and it is highlighted with a warning `No available releases found (Warning)`

this module does not appear when running `$ composer outdated`

is there any idea where this module is coming from, if it is in fact needing an update, or if this is just a typo in one of the site's config files somewhere?

this is what I see:

I have recently updated to Drupal 8.6.12 (using `$ composer update`)

# Answer
> 0 votes
going to mark this as answered so I can close it...

I removed a contrib module that we are no longer using and the mystery module "**standard 8.6.12**" no longer appears.

I cannot say for certain which module it was - but I am 99.78% certain it was from a contrib module, not from a core one.

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


title: Organic Groups vs Group - on D7 vs D8?

text:
# Question
Title: Organic Groups vs Group - on D7 vs D8?
I've done some research on this question, posted it here without any feedback, and have left messages for OG owner (amitaibu) without any response, so hopefully I can solicit useful feedback here.

I'm building a story telling platform that combines passions for genealogy, family photography, and social media, and brings them to a whole new and integrated level of telling stories about your ancestors, and celebrating the life of an individual who has just passed away. I'm building this on Drupal with Organic Groups as the main organizing construct. Every Album - whether it's a family tree, a single individual, or even a photo album - is instantiated as an OG. I'm writing about it and will launch it at www.greatalbum.net.

Right now, I'm building the prototype on D7+OG because it's stable and it's essential that any piece of content (family/individual/event/place/story/media/etc.) be allowed to exist in more than Album. The goal is to launch the prototype in April, and then launch the production v1 site in June or July. I'd love the public launch to be on D8+OG, but I'm not sure how realistic that is, since OG v8.x is currently 1.0-alpha2.

So, my questions are:

1. Am I correct to understand that Group module does not allow content to exist in more than one group at a time, and hence based on my requirement OG is the better choice?
2. Should I assume that OG 8.x-1.0-alpha2 is not stable enough to use for a production site, and that I should stick with OG 7.x-2.10 on Drupal7 for now, and wait on the benefits of Drupal8 until OG matures at least to RC1?

Any guidance?

# Answer
> ... Am I correct to understand that Group module does not allow content to exist in more than one group at a time ...

Yes that is correct, but you seem to not take into consideration that the Group module has the notion of ***Group Types***, and when you create "a" Group, you have to specify which its Group type is (compare to creating *nodes*, which you can only do if you first specify the content type for that node).

Moreover, a user can:

* have multiple levels of access (none, read, update) to some group (outsider, member, etc).
* be member of multiple Groups.

> ... and hence based on my requirement OG is the better choice?

That's a matter of preference (opinion based), e.g. if you prefer to go for D8, at this time, IMO, the Group module is way more stable ...

> 2. Should I assume that OG 8.x-1.0-alpha2 is not stable enough to use for a production site, and that I should stick with OG 7.x-2.10 on Drupal7 for now, and wait on the benefits of Drupal8 until OG matures at least to RC1?

If you do decide to go for OG, then for the sake of stability, at this time, D7 seems to be the way to go.

**Read more**: What are the features of the Group module versus Organic Group module?
> 1 votes

---
Tags: organic-groups, group
---


# Question
Title: How to condition output based on a URL query string
In my node preprocess function I check the value of a query param...

```
$variables['exclude_urls'] = \Drupal::request()->get('exclude_urls');

```

And in my template, I have...

```
{% if not exclude_urls %}
  <div class="gr-url">{{ url }}</div>
{% endif %}

```

However, this approach doesn't work because the node preprocess function does not fire if nothing in the URL changes besides the value for the 'exclude\_urls' param.

I have tried various methods to disable caching for the page. Adding this to the route doesn't work...

```
  options:
    no_cache: 'TRUE'

```

I also tried using the page\_cache\_kill\_switch in my controller, but it doesn't work...

```
\Drupal::service("page_cache_kill_switch")->trigger();

```

Neither does adding the query parameter to cache contexts...

```
$element['#cache']['contexts'][] = 'url.query_args:exclude_urls';

```

Instead of using hook\_preprocess\_node, is there some other way I should be checking the value of $\_GET\['exclude\_urls'\] and passing that to the template? Do I add code to the twig template itself to check the value of 'exclude\_urls'? Is there any sure way to force hook\_preprocess\_node to fire every time? What is the usual approach to conditioning display of content based on a URL query param so that caching won't interfere?

**Update**: To be clear, I have also tried the above approaches in combination, with no success. For example, the end of my page function in my controller looks like this...

```
\Drupal::service("page_cache_kill_switch")->trigger();
$element['#cache']['contexts'][] = 'url.query_args:exclude_urls';
return $element;

```

**Update 2**: In my local dev site, I do not experience this problem, and I've found that this line in my local settings makes it so hook\_preprocess\_node fires every time...

```
$settings['cache']['bins']['render'] = 'cache.backend.null';

```

However, I'm not sure how to take advantage of this in my production site, since I don't want to disable the render cache generally. I can do something like this in settings.php, but it's a hack:

```
$parts = explode('?', $_SERVER['REQUEST_URI'], 2);
if ('/disable/cache/at/this/path' == $parts[0]) {
  $settings['cache']['bins']['render'] = 'cache.backend.null';
}

```

# Answer
> 3 votes
There are three layers where rendered content can be cached:

* The Page Cache, which stores complete pages based on the URL for anonymous users.
* The Dynamic Page Cache, which stores pages with placeholders for dynamic content that is rendered on each request.
* The Render Cache, which stores individual rendered elements.

Each has a corresponding cache bin that can be disabled during development in `settings.php`

---

To set an additional cache context in `hook_preprocess`, so that the Dynamic Page cache knows to re-render that fragment and the render cache stores variants as needed, update the `#cache` variable:

```
function hook_preprocess_HOOK(&$variables) {
  $variables['#cache']['contexts'][] = 'url.query_args:exclude_urls';
}

```

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


title: How do I disable the cache?

text:
# Question
Title: How do I disable the cache?
I have created the settings.local.php file inside the default folder and uncommented the the following lines.

```
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

I also uncommented code in settings.php file, but Drupal is still caching the code. What's the solution for this? I am using Drupal 8.6.10.

I added these parameters in the development.services.yml file.

```
parameters:
  twig.config:
    debug: true
    auto-reload: true
    cashe: false

```

The settings.php file contains the following lines.

```
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
   include $app_root . '/' . $site_path . '/settings.local.php';
}

```

# Answer
> 1 votes
The Page Cache and Dynamic Page Cache store complete pages, but Drupal also uses the Render Cache to store page fragments (e.g. the teaser display of each node).

To disable the render cache, set it to use the null backend as well:

```
$settings['cache']['bins']['render'] = 'cache.backend.null';

```

---
Tags: caching
---


title: No default value for '#type' => 'date'?

text:
# Question
Title: No default value for '#type' => 'date'?
is there a way to configure a date form so it has no default value? Setting the default value to NULL sets the default value automatically to the current date.

```
  /**
   * @return array
   */
  public function getFormFieldSampDate() {
    return [
      '#type' => 'date',
      '#title' => t('Date of Sampling '),
      '#default_value' => self::dateStringToArray($this->sampling_date),
    ];
  }

```

Thanks

# Answer
> 2 votes
Step 1) Install Date module.

Step 2) Enable the **Date Popup** module (comes with the Date module).

Step 3) Add code like the following:

```
  $form['date'] = [
    '#date_label' => 'above',
    '#type' => 'date_popup',
    '#date_format' => 'm/d/Y',
    '#datepicker_options' => [
      // limits date picker so no future date can be picked.
      // remove this section if you want to allow future dates.
      'maxDate' => "+0D",
    ],
    '#required' => TRUE,
    '#attributes' => [
      'autocomplete' => 'off',
    ],
  ];

```

### Result:

---
Tags: forms, datetime
---


# Question
Title: Group By Taxonomy term on view but show all articles containing it
I am trying to generate a view that groups nodes by a taxonomy attached to them but only shows the Taxonomy term once then all the titles under it.

Term 1 Article Article Article Article

Term 2 Article Article

Term 3 Article Article Article

An example of what im trying to solve.

# Answer
> 0 votes
In my example I have *Article* with *taxonomy term reference field* **tags** and have create following content/terms

* 2 Tags: test1, test2
* 4 articles (2 including test1, 2 including test2)

Create a view of content displaying fields and filter to display articles only

* add title field
* add tag field (can exclude it from display)
* format settings \> choose grouping field Nr 1. \> tags

---
Tags: 7, views
---


# Question
Title: How to override theme for quicktabs which actually renders a view
In D8, I want to display a view through quicktabs. For this, at first I have created a view file and call the view through QT. The view is displays well through QT. Now, I want to change the look & feel of the view. Please look into the screen of view which I've created before.

Now, based on the below theme suggestions I created the file `block--quicktabs-block--gallery-tab.html.twig` to override and place it under the "templates" folder in my theme.

```
<!-- FILE NAME SUGGESTIONS:
   * block--quicktabsgallerytab.html.twig
   * block--quicktabs-block--gallery-tab.html.twig
   * block--quicktabs-block.html.twig
   * block--quicktabs.html.twig
   x block.html.twig
-->

```

When I write something fixed like "Hello Test" in the `block--quicktabs-block--gallery-tab.html.twig`, its showing well. However, when I tried to do something dynamic coding like below, nothing appeared.

```
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for key, row in rows %}
  {% if key in rows_with_tabs %}
    {{ tabs }}
    <div class="quicktabs-main" id="quicktabs-container-{{ quicktab_id }}">
  {% endif %}
  {% if key in rows_with_page_starts %}
    {% for page_key, page in rows_with_page_starts %}
      {% if key == page %}
        <div class="quicktabs-tabpage{{ page_key > 0 ? ' quicktabs-hide' : '' }}" id="quicktabs-tabpage-{{ quicktab_id }}-{{ page_key }}"> <!-- start of tbapage -->
        {% set page_number = page_key %}
      {% endif %}
    {% endfor %}
  {% endif %}
  {{ row.content }}
  {% if key in rows_with_page_endings %}
    {# close .quicktabs-tabpage #}
    </div>
  {% endif %}
  {% if key == last_index %}
    {# close .quicktabs-main #}
    </div>
  {% endif %}
{% endfor %}

```

Am I overriding the correct file? Any suggestion?

PS: after implementing the template file as said above, the suggestions looks like:

```
<!-- FILE NAME SUGGESTIONS:
   * block--quicktabsgallerytab.html.twig
   x block--quicktabs-block--gallery-tab.html.twig
   * block--quicktabs-block.html.twig
   * block--quicktabs.html.twig
   * block.html.twig
-->

```

# Answer
As Sunil says you are probably using view variables in your block template

Perhaps look for another template to override further down in order to find a views template to override and use your html/twig code

**Here is what I would do.**

Find the first template inside `views-view.html.twig` in my case it is `views-view-unformatted.html.twig` (red arrow above) and copy it in your theme templates folder. Clear cache and make sure it is used and than explore the possibility of renaming it to be specific and used only for the quicktabs block.

See here for more info on how to name your templates
> 0 votes

---
Tags: views, theming
---


title: Order comments text area in checkout

text:
# Question
Title: Order comments text area in checkout
I need a order comments text area in checkout. How can I do this? I'm using Drupal Commerce 2.

# Answer
> 0 votes
The commerce\_checkout\_order\_fields will allow you to add extra fields in your checkout process

From the module page

> This can be used to collect additional data during the checkout, for example: \- Order comments \- Shipping notes \- ..

---
Tags: 8, commerce
---


title: Count node by taxonomy term

text:
# Question
Title: Count node by taxonomy term
I want to build a statistical of ours projects inside my structure. I have a taxonomy term status with the terms ongoing, achieved, not rated and pending.

An my content type have a relationship to this term. Now I want to show something like this using view and aggregation.

* ongoing (2)
* achieved (2)
* Not rated (12)
* **pending (0)**

But the issue is the last term **"pending"** is not visible because it have **0** attached node.

But I want to show it with the **0**. Please how can I solved this issue.

This is my interface of view. The term with **0** node disappear.

In attached my exporting view. `$view = new view();
$view->name = 'clone_view_for_issue';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'CLONE VIEW FOR ISSUE';
$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'] = 'VIEW DE TEST TAXO';
$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'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
 'thematique' => 'thematique',
);

/* Display: Block test 1 */
$handler = $view->new_display('block', 'Block test 1', 'block_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Nombre total d\'engagement';
$handler->display->display_options['defaults']['use_ajax'] = FALSE;
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['defaults']['group_by'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['defaults']['query'] = FALSE;
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['relationships'] = FALSE;
/* Relationship: Taxonomy term: Content using Note engagement */
$handler->display->display_options['relationships']['reverse_field_note_engagement_node']['id'] = 'reverse_field_note_engagement_node';
$handler->display->display_options['relationships']['reverse_field_note_engagement_node']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_note_engagement_node']['field'] = 'reverse_field_note_engagement_node';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['relationship'] = 'reverse_field_note_engagement_node';
$handler->display->display_options['fields']['nid']['group_type'] = 'count';
$handler->display->display_options['fields']['nid']['label'] = '';
$handler->display->display_options['fields']['nid']['exclude'] = TRUE;
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['nid']['empty'] = '0';
$handler->display->display_options['fields']['nid']['hide_alter_empty'] = FALSE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['text'] = ' **[name] ([nid])***`

---

`*';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['empty'] = '**[view] [name] (0)**

---

';
$handler->display->display_options['fields']['name']['hide_alter_empty'] = FALSE;
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: Content: Has taxonomy term ID */
$handler->display->display_options['arguments']['tid']['id'] = 'tid';
$handler->display->display_options['arguments']['tid']['table'] = 'taxonomy_index';
$handler->display->display_options['arguments']['tid']['field'] = 'tid';
$handler->display->display_options['arguments']['tid']['relationship'] = 'reverse_field_note_engagement_node';
$handler->display->display_options['arguments']['tid']['default_action'] = 'empty';
$handler->display->display_options['arguments']['tid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['tid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['tid']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['tid']['break_phrase'] = TRUE;
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
 'min' => '',
 'max' => '',
 'value' => '',
 'status' => 'status',
);
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['relationship'] = 'reverse_field_note_engagement_node';
$handler->display->display_options['filters']['type']['value'] = array(
 'engagement' => 'engagement',
);`

# Answer
> 0 votes
I am assuming that you are using a "Content" in views, since the taxonomy term is being removed when there are no nodes referenced. I suggest to use the "Taxonomy Terms" instead of the "Content" to display all the terms and just use a relationship to get the nodes attached.

Please see below:

* Create a taxonomy term type views.
* Filter the view to "Status". (Which is your current vocabulary)

* Add to relationship your taxonomy field "Content using Status".

* Turn on aggregation
* Add "NID" field to count nodes associated with the term.

* Save

# Answer
> 0 votes
Here is a simple method available for the same :

```
$tid = 'Enter tid number say 5';
$nids = taxonomy_select_nodes($tid, FALSE);
// count node here
$count = count($nids);
// you can load node content here
$nodes = node_load_multiple($nids);

```

---
Tags: nodes, taxonomy-terms, views
---


# Question
Title: How to save session data in prod server?
I want to save my data in a session: under drupal 8.6

I worked with "**Private tempstore**" it works locally but not in the server prod only if user is ***anonymous***.

```
if ($this->currentUser->isAnonymous()) {
  session_start();
}

```

The same for the **native php session**.

I ask if it can be stored with php **configuration** or how?

thank you

# Answer
Don't use procedural code. Session is now a Symfony object:

```
class MymoduleSessionCounter {
  function increment(Request $request) {
    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);

    return $value;
  }
}

```

Source: https://www.drupal.org/node/2380327

**Edit:**

What you need to do for debugging depends on your dev environment. If for example you have disabled caching you are not able to debug caching issues. In this case enable caching in dev and see what happens if you add cache metadata to the returned result:

```
    return [
      '#markup' => $value,
      '#cache' => ['max-age' => 0],
    ];

```

Cache max-age = 0, because the result in this example changes on each request and is not worth caching.

When this is working the next step is to optimize production performance. Put the code in a #lazy\_builder callback or in a block, which is built lazily by default. In both cases this is then auto-placeholdered for certain cache condition like cache max-age = 0, so that the rest of the page can still be cached.
> 2 votes

# Answer
that also can be resolved with this code in rending controller :

```
$output = [];

$output['#cache']['max-age'] = 0;

```

https://www.drupal8.ovh/en/tutoriels/340/disable-cache-for-a-specific-page
> 0 votes

---
Tags: 8, sessions
---


# Question
Title: How do I change a field with hook_node_presave()?
In Drupal 7, I was using `hook_node_presave()` to update some hidden fields in a node.

```
function mymodule_node_presave($node){
    if ( CONDITIONS ) {
        $node->field_fieldname['und'][0]['value'] = importantfunction();
    }
}

```

In Drupal 8 I cannot do the same thing. Looking into the object I tried this:

```
function mymodule_node_presave($node){
    if ( CONDITIONS ) {
        $node->values['field_fieldname'][0]['value'];
    }
}

```

It won't work though. I am aware that a lot have changed in Drupal 8 and I am studying it, but I did not find an answer to this yet.

# Answer
> 4 votes
A bit outdated but still a great resource:

http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

Also the documentation on drupal.org: https://www.drupal.org/node/1795854

In short, fields are lists of objects that use property and array access magic methods to simplify reading and writing values to them:

```
// Set a value, the field class will decide what to do with it, usually write to the primary property...
$entity->field_fieldname = importantfunction();

// The default property is often called value, but for reference fields, it is target_id, text fields also have a format for example
$entity->field_fieldname->format = 'full_html';

// By default, you access delta 0, you can also set other deltas.
$entity->field_fieldname[1] = importantfunction();

// You can also append a new item, without hardcoding the delta.
$entity->field_fieldname->appendItem(importantfunction());

// Note that when accessing fields, you must always specify the property:
print $entity->field_fieldname->value;
print $entity->field_fieldname[1]->value;

// What basically happens internally for the above is:
$entity->get('field_fieldname')->get(0)->get('value')->getValue();

```

# Answer
> 3 votes
Probably late here but if anyone is still looking then:

```
function mymodule_entity_presave(EntityInterface $entity){
    $entity->set( 'field_fieldname',importantfunction() );
}

```

# Answer
> 0 votes
I don't know if this is a best practice, but I've come to this solution:

```
function mymodule_node_presave(EntityInterface $node){
    $node->field_fieldname->set(0, importantfunction() );
}

```

# Answer
> 0 votes
This is a very late answer.

With \Drupal\node\NodeInterface interface, I'm using that snippet to achieve your needs :

```
/**
 * Implements hook_node_presave();
 *
 * @param \Drupal\node\NodeInterface $node
 */

function module_name_node_presave(\Drupal\node\NodeInterface $node) {
    if($node->get('field_name')->getString() != 'search') {
        $node->set('field_name', 'new field value');
    }
}

```

---
Tags: nodes, hooks, 8
---


title: Custom Access check for module route

text:
# Question
Title: Custom Access check for module route
I'm working on module that should behave as API endpoint.

I created Controller which handler POST & GET requests from external system, but I need to add user authentication so only authenticated user can acccess these endpoints.

My **mymodule.routing.yml**:

```
mymodule.show_content:
  path: 'api/getContent'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ContentController::getContent'
    _format: hal_json
  requirements:
    _method: 'POST'
    _custom_access_check: 'TRUE'

```

My **mymodule/src/Access/CustomAccessCheck.php**:

```
class CustomAccessCheck implements AccessInterface
{
    public function access(AccountInterface $account)
    {
        return ($account->hasPermission('access content')) ? AccessResult::allowed() : AccessResult::forbidden();
    }
}

```

My **mymodule.services.yml**:

```
  mymodule.custom_access_check:
    class: Drupal\mymodule\Access\CustomAccessCheck
    arguments: ['@current_user']
    tags:
      - { name: access_check, applies_to: _custom_access_check }

```

I created a user called REST with `REST` role. I gave him 'access content' permission and tried to make request with Postman using POST method and following headers:

```
{
    Content-Type: application/hal+json,
    Authorization: Basic <base64_encoded user:pass>
    X-CSRF-Token: token obtained from <page_url>/rest/session/token
}

```

When I make request with admin user, I see in recent logs, that admin access the route /api/getContent but access was denied. When I use my REST user it logs as anonymous user. Even when I log the status of authentication inside **CustomAccessCheck::access** function I see that user is authenticated with *TRUE*

I need to keep this authentication separated (out of controller, in service or something) because I need to authenticate every request (re-use auth) so only internal users can use API (and not everyone with URL). I don't understand what is missing and why only my admin user is recognized by drupal and the REST user not.

# Answer
What happens if you replace:

```
requirements:
  _method: 'POST'
  _custom_access_check: 'TRUE'

```

With:

```
requirements:
  _method: 'POST'
  _permission: 'access content'

```

Any then remove your CustomAccessCheck code
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: Let 'web-view' mobile iOS/Android app talk consume/feed site
I have a Drupal 8 site with the following modules:

* HAL.
* HTTP Basic Authentication.
* REST UI.
* RESTful Web Services.
* Serialization.

Using the REST UI module, I configured it as follows.

**Settings for resource User**

**Granularity** \- Resource

**Methods** \- GET \- POST \- PATCH

**Accepted request formats** \- json

**Authentication providers** \- basic\_auth \- cookie

I created an IOS & Android web-view app. I am using the Firebase module to send 'Push Notifications' to registered users on the website on specific events, such as *Send a push notification to the 'node author' whenever his node is updated*.

I know I have to pass a unique token of the mobile device used by the logged in user and store it on my Drupal site. for that, I have created the *field\_user\_push\_token* text field on the user profile page in order to store the token received from the mobile device of the user.

How can I transfer the token from the mobile device to the *field\_user\_push\_token* field?

I believe I should use the PATCH method, but I don't know how.

Am I on the right track by using the RESTful Web Services, or is there a better method?

**UPDATE #1:**

I am the web developer of the website but not the mobile developer, so I asked a mobile developer (Not familiar with Drupal) to create the 'web-view' apps for me... He told me to setup an API for him so he can access the website and he will generate the token and send it to my Drupal website through the provided API...

My skills towards Restful API are very limited so by following some tutorial I have setup the Restful web service API on my website but:

What information I have to give him in order to access my website from the created 'web-view' app ?

is it only `https://example.com/user/{user}?_format=json` or I am missing something here ?

I am a bit confused...

# Answer
> 1 votes
Elie Masaad, You can use PATCH method like this Drupal 8 Android app at https://github.com/onedrupal/One-Drupal-Android.

PATCH related android source code using OkHttpClient https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/activities/ActivityPost.java#L637

```
request = new Request.Builder()
                        .header("Content-Type", "application/json")
                        .url(url)
                        .patch(api_body)
                        .build();
OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .addInterceptor(new AddCookiesInterceptor())
                .build();

```

AddCookiesInterceptor at https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/network/AddCookiesInterceptor.java

You can define your REST endpoint for Android Retrofit at https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/network/GetSiteDataService.java#L31 like

```
@GET("/node/{editNid}?_format=json")
    Call<ModelNodeType> getNode(@Path("editNid") String nid);

```

---
Tags: 8, users, services, tokens
---


# Question
Title: how to add number for every content in views?
i useing drupal 8. i create ResTful export with views. my site have several content type and i use several views for any content type. but in clinet(android) i need have list with specified numbers...so i cant use Nid(Because i have several content type) how i can add number for every content in my views? (such as this pic that firefox add number(0)to my every content) (upside down number this image)

# Answer
> 1 votes
You can add a Field in Views that counts the result rows. The Field is called `View result counter` and you can find it under `Global` Category.

Humans usually prefer to start count at 1, but there is an option in that Field settings to set the `Starting value` so you can use zero.

I haven't tried it with Rest export, grouping like in your screenshot won't work. It will just be one of the fields.

# Answer
> 0 votes
Mahdi Baghery, You can customize the JSON response using views plugin that extends Serializer like https://cgit.drupalcode.org/one\_api/tree/src/Plugin/views/style/SerializerCount.php

The above SerializerCount.php code is used to add pager to ResTful export like http://one-drupal-demo.technikh.com/onedrupal/api/v1/content?page=1

```
{
results: [],
pager: {}
}

```

This JSON is parsed by Drupal 8 Android app at https://github.com/onedrupal/One-Drupal-Android. https://play.google.com/store/apps/details?id=com.technikh.onedrupal

---
Tags: views
---