# Question
Title: Custom submit handler stops working when checking route
I'm trying to setup a custom submit handler, so I can change the redirect URL after submitting comments. **Edit: I just want to send users back to the page they were viewing to begin with, but it's a webform with a couple of route parameters, so I need to save them somehow.**

**This works** (the function is called and I see the debug messages):

```
function mymodule_form_comment_form_alter(&$form, &$form_state) {
    $form['actions']['submit']['#submit'][] = '_submit_foo';
    kint($form['actions']);
}

function _submit_foo(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    kint('Hello world!');
    \Drupal::logger( 'foo' )->info('hello world');
    exit;
}

```

**This DOESN'T work - i.e. as soon as I add a check on the route:**

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

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

    if ($route_name == 'entity.webform_submission.canonical') {
        // it's DEFINITELY getting this far!

        kint( 'in conditional' );
        kint( $route_name );
        $form['actions']['submit']['#submit'][] = '_submit_foo';
        kint( $form['actions'] );
    }
}

```
* I *know* the conditional is being reached, I'm seeing the debug statements.
* \_submit\_foo() isn't called
* user is sent to `comment.reply` instead

Here's a screenshot of the `kint($form['actions'])`:

**Context:**

* these comments are shown inside a view block (format - show: content, single contextual filter, also generated from URL), which is placed, in block layout, below webform submissions on the standard `entity.webform_submission.canonical` route - e.g. URL like */admin/structure/webform/manage/application/submission/123*
* there's also code in HOOK\_comment\_view\_alter that adds a 'user' cache context to the view (because each user has their comments filtered, so doing it by role is not enough) - *in any case, I've tried disabling that and clearing cache*
* the comments are in a node that has an entity reference to the webform (in case you're wondering how I've managed to combine comments and webform)
* comment previews are disabled, and I assume I can rule out that submit action based on the first piece of code working as designed?

# Answer
The comment form sets an #action to the comment.reply route, which will rebuild the form and no longer go inside your condition as the route there is differdnt.

Whatever you're trying to do exactly, you need to find a different way to do it.
> 1 votes

# Answer
**Solution**: Berdir pointed out I could just use '?destination' - you don't even need a custom handler. Here's what I did if anyone wants the code - you can make this even shorter just using `\Drupal::service('path.current')->getPath();` rather than deconstructing and rebuilding the entire route):

```
/**
 * Implements hook_form_FORM_ID_alter
 *
 * Remove homepage field from comment admin form
 * Change submit button text when adding comments
 */
function mymodule_form_comment_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {

    $valid_routes = [
        'entity.webform_submission.canonical',
        'entity.webform_submission.edit_form'
    ];

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

    if ( in_array( $route_name, $valid_routes ) ) {
        $webform            = \Drupal::routeMatch()->getParameter( 'webform' );
        $webform_submission = \Drupal::routeMatch()
                                     ->getParameter( 'webform_submission' )->id();

        $destination_link = \Drupal\Core\Url::fromRoute(
            $route_name,
            [
                'webform'            => $webform,
                'webform_submission' => $webform_submission
            ] )->toString();

        $form['#action'] .= '?destination='.$destination_link;
    }
}

```

Be aware, as per comments on the API page, if you use the $form\_id parameter, it's different depending on the operation.
> 1 votes

---
Tags: 8, hooks, routes, comments
---


title: Computed Field not showing

text:
# Question
Title: Computed Field not showing
I want to use the computed field in my drupal 8 website to calculate the charges for a parking system where I calculate the charge for a vehicle by taking the date of collection minus the date of parking, multiplying by the charge per day. total-charges=(collection-paking)\*charge-per-day. However, even before I do the calculation, I tested to see if the computed field is working by assigning the `$value='hello'` and the assign the `$disply_output=$value` but its not being displayed in the content of the node together with other fields. Other things done to try to resolve this issue

* Change the data type from varchar to text to int and others
* Change the settings in the 'manage display' option of the content type. From toggling sanitize on an off, change display of the computed field from above to inline, etc
* Resave the node by clicking edit and then saving the node, and even creating a new node of that content type after adding the content field.

Still not working.

After googling, most common solution, which works for drupal 7 guys is to uncheck the option to save the field in the database. But I dont see that option in drupal 8 so that I can uncheck it. Because I do not want to store the value in the database since It changes everyday a vehicle is not collected, so all I want is to calculate the value on the fly and charge the vehicle owner when collecting the vehicle. How do I make the computed field even display a simple 'Hello World'?

# Answer
I think it must be a bug, since the computed module is in alpha for drupal 8 at the time of this writing. With the help of Matt, we were able to print a simple 'hello' message by manually creating a new node. This new node will have access to the new computed field. I was using the devel module to generate content for nodes, which for some reason did not have access to the computed field. So if you are experiencing the same problem, set up your computed field, and then manually create a node, or edit and resave a node your previously created manually. That worked for me.
> 0 votes

# Answer
You just need to resave existing data and computed field value will be shown and saved
> -1 votes

---
Tags: 8, entities
---


# Question
Title: Will there be any unexpected side effects when I upgrade the Zen theme?
I have installed the 7.x-5.6 theme and I want to upgrade to the 7.x-6 version. I have created 2 subthemes from it that I hardly use, and I hardly use the Zen theme itself - it is supposed to be base theme,not actually used in any case.

Is it okay for me just to disable and delete the base theme and the derived themes and install the 7.x-6.4 as though the previous ones were never installed in the first place?

PS. Are there any hidden downsides to uninstalling themes, like some stray database tables etc?

# Answer
> 0 votes
Themes don't create their *own* database tables.

The changes about the theme status (enabled, default, theme settings) are stored in the `system` and `variable` tables, along with many other system settings, it's nothing you should be worried about.

Some themes are accompanied by a special module built especially for them, but Zen isn't one of those.

**Yes, you can disable and delete old Zen and its subthemes without consequences.** Set Bartik as default theme before removing old Zen out of your system.

It's good practice to backup files before deleting, it's up to you, at least check if there are any files you might want to keep, maybe logo images.

Then download and enable the latest Zen. Create the latest Zen subtheme using the latest Zen procedure.

The latest Zen theme structure and procedures are significantly different from the older versions. You'll have to install some bundles and other dependencies and learn how to build Sass through Gulp (if you want Sass)...

You might experience problems if you want to *keep* the old subthemes and make them work with new the Zen, but if you want to *start fresh* there aren't bad consequences if you remove old Zen and its subthemes and then install new Zen.

It's good to remember to clear (theme) cache when changing things like these, even though theme registry is rebuilt on visiting the Appearance page.

---
Tags: 7, upgrading, theming
---


title: Updating core from 8.4.4 to 8.6.1

text:
# Question
Title: Updating core from 8.4.4 to 8.6.1
I want to update Drupal from 8.4.4 to 8.6.1. I've tried to follow the steps from this page, but without success. When I run this command:

```
composer update drupal/core --with-dependencies

```

I get:

```
 Package "drupal/core" listed for update is not installed. Ignoring.
[Composer\DependencyResolver\SolverProblemsException]
  Problem 1
      - The requested package drupal/coder ^8.3 exists as drupal/coder[8.2.12
  ] but these are rejected by your constraint.

```

I've tried with:

```
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

```

But, I get the same error. With composer:

```
>composer outdated
alchemy/zippy                         0.4.3              0.4.9
asm89/stack-cors                      1.1.0              1.2.0
behat/mink                            dev-master 04ab7af dev-master d5ee350
behat/mink-browserkit-driver          v1.3.2             1.3.3
chi-teck/drupal-code-generator        1.23.2             1.26.1
composer/installers                   v1.4.0             v1.6.0
consolidation/annotated-command       2.8.3              2.9.1
consolidation/config                  1.0.9              1.1.0
consolidation/log                     1.0.5              1.0.6
consolidation/output-formatters       3.1.13             3.2.1
consolidation/robo                    1.2.2              1.3.1
dflydev/dot-access-configuration      v1.0.2             v1.0.3
doctrine/annotations                  v1.2.7             v1.4.0
doctrine/cache                        v1.6.1             v1.6.2
doctrine/common                       v2.6.2             v2.7.3
drupal/coder                          8.2.12             8.3.0
drush/drush                           9.2.1              9.4.0
egulias/email-validator               1.2.14             2.1.5
fabpot/goutte                         v3.2.1             v3.2.3
guzzlehttp/guzzle                     6.3.0              6.3.3
jcalderonzumba/gastonjs               v1.0.2             v1.2.0
jcalderonzumba/mink-phantomjs-driver  v0.3.1             v0.3.3
paragonie/random_compat               v2.0.10            v2.0.17
phpdocumentor/reflection-docblock     2.0.4              3.3.2
phpoffice/phpspreadsheet              1.1.0              1.4.0
phpspec/prophecy                      v1.7.0             1.8.0
phpunit/php-code-coverage             2.2.4              4.0.8
phpunit/php-file-iterator             1.4.2              1.4.5
phpunit/php-token-stream              1.4.11             1.4.12
phpunit/phpunit                       4.8.36             5.7.27
phpunit/phpunit-mock-objects          2.3.8              3.4.4
psr/simple-cache                      1.0.0              1.0.1
psy/psysh                             v0.9.5             v0.9.8
sebastian/environment                 1.3.8              2.0.0
sebastian/exporter                    1.2.2              2.0.0
sebastian/recursion-context           1.0.5              2.0.0
sebastian/version                     1.0.6              2.0.1
squizlabs/php_codesniffer             2.8.1              3.3.2
stack/builder                         v1.0.4             v1.0.5
symfony-cmf/routing                   1.4.1              2.0.3
symfony/class-loader                  v3.2.14            v3.4.15
symfony/config                        v3.2.14            v3.4.15
symfony/console                       v3.2.14            v3.4.15
symfony/css-selector                  v3.2.14            v3.4.15
symfony/dependency-injection          v3.2.14            v3.4.15
symfony/event-dispatcher              v3.2.14            v3.4.15
symfony/http-foundation               v3.2.14            v3.4.15
symfony/http-kernel                   v3.2.14            v3.4.15
symfony/phpunit-bridge                v3.2.14            v4.1.4
symfony/process                       v3.2.14            v3.4.15
symfony/psr-http-message-bridge       v1.0.2             v1.1.0
symfony/routing                       v3.2.14            v3.4.15
symfony/serializer                    v3.2.14            v3.4.15
symfony/translation                   v3.2.14            v3.4.15
symfony/validator                     v3.2.14            v3.4.15
symfony/yaml                          v3.2.14            v3.4.15

```

But I tried to update this dependencies but they are locked. I think I have to change composer.json to unlock some configuration, but I'm not sure what should I do. What is the right way to update Drupal Core? Thanks.

# Answer
> 4 votes
Missed the "Package "drupal/core" listed for update is not installed."

What that means is that you did not install this based on https://github.com/drupal-composer/drupal-project, which simply means that these instructions are not for you.

You either need to update that by getting the latest tarball and then re-adding your additional dependencies, or, recommended, switch now to a drupal-project based build, which is the de-facto standard.

I only had a quick look at it, but https://www.jeffgeerling.com/blog/2018/converting-non-composer-drupal-codebase-use-composer looks like a detailed/comprehensive blog post on how to do that.

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


# Question
Title: How to add a default taxonomy term to all nodes in a migration?
For a Drupal 7 to Drupal 8 migration, we're taking what was a Quotation content type and migrating it into an Article content type, joining a ton of nodes that are staying as Articles. To distinguish, I want to add a taxonomy term "Quotation" to the field\_categories (which exists on Articles D7 and D8 but not on Quotation).

So i'm "simply" trying to add a value not from a source, but hard-coded. My source plugin is d7\_node (namespace Drupal\node\Plugin\migrate\source\d7).

I'm flailing a bit; tried entity\_generate but couldn't figure out how to tell it to use a constant and/or default value rather than looking for something from source.

Even this didn't work, when i tried to test the simplest thing i could think of when already knowing the term ID of an existing term:

```
  field_categories:
    plugin: iterator
    source: field_categories
    process:
      target_id:
        -
          plugin: default_value
          default_value: 10838

```

Can one use the default\_value plugin or something like it for the 'source:'?

I'm about to stick my non-source value into what comes from the source with a prepare row hook, but it seems there ought to be an easier way.

Note that in this case there is nothing from field\_categories in the source to worry about, but i'm also interested in the case of *adding* a new, hard-coded-into-the-migration term into a field that will have content, in my case field\_tags.

# Answer
Well, i don't like it, but this works:

```
<?php

use Drupal\migrate\Row;
use Drupal\migrate\Plugin\MigrateSourceInterface;
use Drupal\migrate\Plugin\MigrationInterface;

/**
 * Implements hook_migrate_MIGRATION_ID_prepare_row() for upgrade_d7_node_quote.
 */
function portside_upgrade_migrate_upgrade_d7_node_quote_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
   $term_name = 'Portside Quotation';
   $term_array = \Drupal::database()->select('taxonomy_term_field_data', 't')
     ->fields('t', ['tid'])
     ->condition('vid', 'categories')
     ->condition('name', $term_name)
     ->execute()
     ->fetchCol();
   if (isset($term_array[0])) {
     $row->setSourceProperty('field_categories', [['tid' => $term_array[0]]]);
   }
}

```

I create the taxonomy term with default content, so it's there after site install and ready for the migration.

In the migration's YAML file (for upgrade\_d7\_node\_quote), there's simply a plain mapping as if field\_categories were a real thing:

```
  field_categories:
    plugin: iterator
    source: field_categories
    process:
      target_id: tid

```

And remember, there is no field\_categories in the source. The migration doesn't mind at all and works fine with one inserted into the source in this prepare row hook.
> 0 votes

# Answer
I found the following worked for me...on the first migration I ran:

```
 field_type:
    -
      plugin: default_value
      default_value: 'Hall'
    -
      plugin: entity_generate
      entity_type: taxonomy_term
      value_key: name
      bundle: place_type

```

The second migration I ran, using exactly the same yaml to create the same content type, didn't work. I got a "Missing bundle for entity type taxonomy\_term" error. Adding the bundle key as below fixed it:

```
 field_type:
    -
      plugin: default_value
      default_value: 'Library'
    -
      plugin: entity_generate
      entity_type: taxonomy_term
      value_key: name
      bundle_key: vid
      bundle: place_type

```
> 0 votes

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


# Question
Title: Pass Preprocess Values From Custom Module to Custom Form
My use case:

I would like to create a unique textfield per region in a custom form.

**MYMODULE/MYMODULE.module:**

```
function MYMODULE_preprocess_region(&$variables) {

    foreach (array($variables['elements']['#region']) as $key) {
        drupal_set_message($key);
    }

}

```

**MYMODULE/src/form/MyModuleForm.php:**

```
protected function getEditableConfigNames() {
    return [
        'module_config.module_config_settings',
    ];
}

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

    $config = $this->config('module_config.module_config_settings');

    //build this...
    $form['region_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Form Item Title),
    );

    return parent::buildForm($form, $form_state);

}

```

What is the appropriate way to pass variables/info from the .module file to the .form?

\*Note: I have a fully functioning form, hopefully I am showing enough of it to illustrate my focus.

# Answer
> 2 votes
It seems that you can get the list of blocks from this answer: How do i get the all the regions available in the current theme programatically?

**MYMODULE/src/form/MyModuleForm.php:**

```
protected function getEditableConfigNames() {
    return [
        'module_config.module_config_settings',
    ];
}

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

  // Get the block list based on previous Q/A
  $theme = \Drupal::theme()->getActiveTheme()->getName();
  $system_region = system_region_list($theme, REGIONS_ALL);

  foreach ($system_region as $region) {
    $form[$region . '_title'] = [
      '#type' => 'textfield',
      '#title' => t('Form ' . $region . ' Title'),
    ];
  }

  return parent::buildForm($form, $form_state);
}

```

# Answer
> 1 votes
You try the code

```
function MYMODULE_preprocess_region(&$variables) {
 $regions=[];
 foreach (array($variables['elements']['#region']) as $key) {
  $regions[] =$key;
 }
$config = \Drupal::service('config.factory')->getEditable('module_config.module_config_settings');
$config->set('config_regions', $regions);
$config->save();
}

```

call config:

```
$config = $this->config('module_config.module_config_settings');
$config->get('config_regions');

```

---
Tags: 8, forms, hooks
---


# Question
Title: How to add the paragraph parent field in the theme suggestions alter
I've been spending a couple of hours from debugging the paragraph properties using `kint` and `var_dumper` however, the page is freezing and I'm unable to see what are the properties and methods available. Has anyone tried to add a hook theme suggestion to `paragraph` based on its parent field name?

I have added a paragraph type as well as added the fields, then I created a node and paragraph reference.

Here's a sample code:-

```
function THEMENAME_theme_suggestions_paragraph_alter(&$suggestions, $variables) {
    $paragraph = $variables['elements']['#paragraph'];
    $parent = $paragraph->getParentEntity();

    $suggestions[] = 'paragraph__' . $parent->bundle() . '__' .  $paragraph->bundle();

    // get the parent field of the current paragraph
    // assuming that the parent field name is field_test_paragraph
    $parent_field_name = 'field_test_paragraph';

    // field_test_paragraph should be added to theme suggestions
    $suggestions[] = 'paragraph__' . $parent->bundle() . __ . $parent_field_name . '__' .  $paragraph->bundle();
}

```

Expected output:

```
paragraph--nodetype--field-test-paragraph--paragraph-type-name.html.twig

```

# Answer
> 4 votes
You can get the parent field name directly from the paragraph:

Replace

```
// get the parent field of the current paragraph
// assuming that the parent field name is field_test_paragraph
$parent_field_name = 'field_test_paragraph';

```

with

```
$parent_field_name = $paragraph->parent_field_name->value;

```

---

As a side note, this is an entity base field like `parent_id` and `parent_type` you load the parent entity with in `getParentEntity()`.

---
Tags: 8, theming, hooks
---


# Question
Title: Include a module template into an other module template
I'm working on a Drupal 8 project and in my module X twig template I need to include the template of an other module Y. All what I found in documentation is how to call a template inside other template in theme see here

I've tried in my `twig-of-module-X.html.twig` file:

```
{% include 'modules/Y/templates/twig-of-module-Y.html.twig' %}

```

but doesn't work! Any suggestion please?

# Answer
Include the template file with its namespace:

`{% include '@modulename/template_file.html.twig' %}`

`{# @modulename refers to 'path_to_module/templates' #}`

Drupal provides a `@namespace` for Twig based on the machine name of every module and every theme. The `@namespace` points to the `templates` sub-directory of that module or theme.
> 13 votes

---
Tags: 8, theming
---


# Question
Title: How to get drupal module path in javascript?
I'm trying to use this: `var path = Drupal.settings.mymodule.basePath;`but I'm getting this error: Uncaught TypeError: Cannot read property 'basePath' of undefined.

# Answer
First of all you need to call `drupal_add_js()` with a 'settings' parameter. This will inform your Drupal.settings javascript namespace about the settings/variables you need in this file via drupal. Try the following :

Lets suppose you want to call a specific \*.js file on a nodes' view page, call it as :

```
drupal_add_js(array('myModule' => array('basepath' => '<your-drupal-base-path>')), 'setting');

```

This `basepath` is global and you can get it in any \*.js file called at this point. Next, you can use this `basepath` in your \*.js file as :

```
var path = Drupal.settings.myModule.basepath;

```
> 3 votes

# Answer
1. It starts with adding the following line to your modules .info file (rename MYMODULE to your module name or the name you want to give to your javascript file)

scripts\[\] = MYMODULE.js
2. The next step is to create the MYMODULE.js file. The general template of the javascript file looks like:

```
  (function ($) {
     Drupal.behaviors.MYMODULE = {
     attach: function (context, settings) {
        // Your javascript code here
    }
  };
}(jQuery));

```
3. You can pass variables from your PHP to your Javascript file by adding the following code somewhere in your module.

drupal\_add\_js(array('MYMODULE' =\> array('tax\_rate' =\> '0.06')), 'setting');

You can now access this variable in your JavaScript:

```
(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      // You can access the variable by using Drupal.settings.MYMODULE.tax_rate
      alert(Drupal.settings.MYMODULE.tax_rate);

    }
  };
}(jQuery));

```
> 2 votes

# Answer
At First you need to have a module or create a module

See detailed steps below on adding this condition

* Create a folder called 'custom' in `sites/all/modules`
* Create a folder called 'mycustomjs' in above custom folder
* Create a file called 'mycustomjs.info' inside above folder with

below code

```
name = My Custom JS Alters
description = A custom module to interact with JS
core = 7.x
package = Custom

```

Create a file called mycustomjs.module inside 'mycustomjs' folder with below code

```
<?php

 function mycustomjs_init(){

      global $base_path;
      global $base_url;

     $my_base_path = $GLOBALS['base_url'] . $GLOBALS['base_path'];
    // or $my_base_path = $base_url . $base_path;

       $my_settings = array(
         'basePath' => $base_path,
         'animationEffect' => variable_get('effect', 'none')
       );

      drupal_add_js(array('mycustomjs' => $my_settings), 'setting');

    }
?>

```

For JS side

```
var basePath = Drupal.settings.mycustomjs.basePath;
var effect = Drupal.settings.mycustomjs.animationEffect;

```

For more information See below

Creating Drupal 7.x modules

Drupal 7 global javascript variables

The Drupal JavaScript API

Drupal Base Url

get-complete-base-url-drupal-site
> 1 votes

# Answer
To get the path on js file like following:

```
var path = Drupal.settings.myModule.basepath;

```

First need to initiate add\_drupal\_js() with 'settings' parameter like :

```
drupal_add_js(array('myModule' => array('basepath' => '<the-path>')), 'setting');

```

Example:

```
drupal_add_js( array(
   'myModule' => array(
             'basepath' => drupal_get_path('module', 'myModule')
              )
    ), 'setting'
);

```

Then on any \*.js file you can access this variable as following:

```
 (function ($) {
      Drupal.behaviors.myModule= {
        attach: function (context, settings) {
          // You can access the variable by using var
          path = Drupal.settings.myModule.basepath;
          console.log(Drupal.settings.myModule.basepath);

        }
      };
    }(jQuery));

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How to save datetime field value in config?
I have a custom module (`mymodule`) with a settings form. This form contains a datetime field (`mydate`) which I want to save in my modules config.

When I try to save this form I get an exception:

> Drupal\Core\Config\UnsupportedDataTypeConfigException: Invalid data type for config element mymodule.settings:mydate in Drupal\Core\Config\StorableConfigBase-\>validateValue() (line 160 of core/lib/Drupal/Core/Config/StorableConfigBase.php)

The form field:

```
$form['mydate'] = array(
  '#type' => 'datetime',
  '#title' => t('My date'),
  '#default_value' => $config->get('mydate')
)

```

The form submission handler where the error occures:

```
$config->set('mydate', $form_state->getValue('mydate));

```

I guess I have to set up my config schema to set up the "right type". Currently I have this one but it does not solve my issue:

```
mymodule.settings:
  type: config_object
  label: 'fancy module settings'
  mapping:
    mydate:
      type: datetime
      label: 'My date'

```

Any idea what I'm doing wrong or what is missing?

PS: using Drupal 8.2

# Answer
There is no schema for data type called datetime.

Easiest solution is to store the date as the timestamp string.

Converting a drupal datetime into a timestamp: The datetime form element holds an array value that contains three keys: `date`, `time`, `object`. The `object` holds an instance of the `[\Drupal\Component\Datetime\DateTimePlus][1]` class. It has a \_toString method which means it can be converted to string via normal casting (i.e. `(string) $value`).

Setting a default value on a datetime field: Too do that you will need to create a new `[\Drupal\Component\Datetime\DateTimePlus][1]` object and set it as the value of `$element['#default_value']`
> 2 votes

# Answer
Here's some actual code based on Eyal & Philipp's work in the other answer.

```
use Drupal\Core\Datetime\DrupalDateTime;

```

**Load:**

```
$form['mydate'] = [
    '#type'          => 'datetime',
    '#title'         => t('My date') ,
    '#default_value' => new DrupalDateTime( $config->get( 'mydate' ) ),
];

```

**Save:**

```
$config->set( 'mydate', $values['mydate']->__toString() )->save();

```

**config yaml:**

```
mydate: '2018-09-12 09:00:00 Europe/Berlin'

```

**Play with in console:**

```
$ drush php
Psy Shell v0.9.8 (PHP 7.1.22 — cli) by Justin Hileman
>>> use Drupal\Core\Datetime\DrupalDateTime;
>>> $time = new DrupalDateTime('2018-09-12 09:00:00 Europe/Berlin');
=> Drupal\Core\Datetime\DrupalDateTime {#4897}
>>> $time->getTimestamp();
=> 1536735600

```
> 1 votes

---
Tags: forms, 8, datetime
---


# Question
Title: Basic pages are being rendered incorrectly do they differ at all to the article or custom content types in any fundamental way?
I have a custom theme, all (custom) content types display as expected except basic pages. Is there something fundamentally different to basic pages that explains/ helps me to troubleshoot why the markup is different?

The site has custom theme/child-theme, custom modules, and a heap of contrib modules so I can't really "paste the code", and as it's a development site I can't give access to it.

The problem I'm experiencing *seems* to be HTML markup errors, some missing closing elements etc., but I've stepped through most of the code already and can't see anything. Is it something specific to basic pages that Drupal does differently?

# Answer
> 0 votes
> Is there something fundamentally different to basic pages that explains/ helps me to troubleshoot why the markup is different?

No, content types are completely generic. Drupal core processes them identically, but of course, custom and contrib code can heavily affect how they work.

You're going to need to check your theme, templates and custom modues, and maybe even contrib modules (depending on what you have installed and how you have them configured). The problem is with one or more of them, not with the content type itself.

---
Tags: 7, theming
---


title: Send HTML email from my module

text:
# Question
Title: Send HTML email from my module
I have a problem while sending a HTML email through my module, Here is my code below:

.install file

```
function invite_an_user_enable() {
  $current = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  $addition = array('invite_an_user' => 'invite_an_userMailSystem');
  variable_set('mail_system', array_merge($current, $addition));
}

function invite_an_user_disable() {
  $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  unset($mail_system['invite_an_user']);
  variable_set('mail_system', $mail_system);
}

```

and here is the .module file:

```
class invite_an_userMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

```

Here is the email that I got:

```
<p>Hi <strong>myemail@email.com</strong>, </p>

<p>Your friend <strong>another_email@email.com</strong>, invited you in <strong>My Site Name</strong>. Please cleck on the link to accept the invitation below:</p>

<p>http://something.com/referral/3139323e</p>

<p> </p>

<p>Thanks,<br />
My Site</p>

```

Now the problem is that, when I received the email I can see all the tags in my email. And the header of the email is

```
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes
Content-Transfer-Encoding: 8Bit
X-Mailer: Drupal

```

I believe this should be text/html rather than text/plain. Am I doing something wrong? Is there any different method to send HTML mail? Feel free to ask any questions.

# Answer
Solved that. I added a line on my code i.e `$message['headers']['Content-Type'] = 'text/html; charset=UTF-8;'`

```
class invite_an_userMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

```

This is now working for me.. Yeppi :)
> 0 votes

# Answer
Add your custom module hook\_mail:

```
/**
 * Implements hook_mail().
 */
custom_module_mail($key, &$message, $params) {

    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
}

```

Make the "drupal\_mail" call as follows:

```
drupal_mail('custom_module', 'unique_key_first_arg', $to, user_preferred_language($currentUser), ['body' => 'content goes here', 'subject' => 'SUBJECT LINE goes here'], $from, TRUE);

```
> 0 votes

---
Tags: 7, emails
---


# Question
Title: How to override output (query) for views exposed filter?
I have a views with exposed filter of taxonomy terms (select). It have multiple choice, and nodes output with that terms. But I want to change output of result of views for this filter. How can I do it programmatically?

# Answer
It depends on what exactly you want to accomplish, some commonly used hooks are:

Also there are plenty of Views Plugins like the Row Plugins
> 0 votes

---
Tags: views, 8
---


title: how to add cache tag in custom rss feed

text:
# Question
Title: how to add cache tag in custom rss feed
how to add cache tag in custom RSS feed in Drupal 8
I have tried like this

```
    use Symfony\Component\HttpFoundation\Response;
    $response = new Response();
    $xml_content = '<?xml version="1.0" encoding="UTF-8"?>
     <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
      <channel>
       <title><![CDATA[ Title there ]]></title>
       <link><![CDATA[ siteurl.com ]]></link>
       <description><![CDATA[ description there ]]></description>
      </channel>
     </rss>';
    $cacheTags = ['node:nid', 'node:nid']
    $response->setContent($xml_content);
    $response->setCache(['etag' => $cacheTags]);
    $response->headers->set('Content-Type', 'xml');

```

but it not working

# Answer
Add the cache tags to the cacheable metadata of a cacheable response:

```
use Drupal\Core\Cache\CacheableResponse;

  $response = new CacheableResponse();
  // ...
  $response->getCacheableMetadata()->addCacheTags(['node:nid', 'node:nid']);

```
> 3 votes

---
Tags: 8, feeds
---


# Question
Title: Field definition in custom field and varchar_ascii
When making custom field and doing field definitions for string I came upon this setting.

```
  'type' => $field_definition->getSetting('is_ascii') === TRUE ? 'varchar_ascii' : 'varchar',

```

I just cant find a reference what would it be if a field definition is set to "varchar\_ascii" is it something to do with "Collation" ?

# Answer
> 4 votes
The doc block of database.api.php/Schema API state:

> A special `varchar_ascii` type is also available for limiting machine name field to US ASCII characters.

You can see its implementation in Schema::createFieldSql() of the MySQL abstraction layer.

So yes, it changes the default UTF-8 character set/collation to ASCII.

---
Tags: 8
---


# Question
Title: How can I create a custom user profile page without overlapping the registration and login pages?
I'd like to create a custom user profile page, but if I use `/user/%` path then it will also overlap `/user/registration`, `/user/login` and so on...

Is there any ways to avoid it?

# Answer
> 0 votes
You can:

* customize the user profile page at `/admin/config/people/accounts/display`
* Change anything if you implement the hook\_preprocess\_user().
* Add blocks at `admin/structure/block`.

# Answer
> 2 votes
One approach is to create a custom template file for the user.

add a bit of code to your .theme file:

**MYTHEME.theme:**

```
function MYTHEME_theme_suggestions_user(&$suggestions, $variables, $hook) {

  // Define the view mode.
  $mode = $variables['elements']['#view_mode'];
  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;

}

```

The above tells Drupal to look for template files that fit the new naming conventions.

Then create a twig template file in `MYTHEME/templates`:

**user--full.html.twig**

```
<div class="user-full-wrapper">

    {% if content.user_picture | render %}
          {{ content.user_picture }}
    {% endif %}

    {% if content.field_name | render %}
          <p>{{ content.field_name }}</p>
    {% endif %}

</div>

```

The above html is just an example.

Now you have unique markup for just the user profile page in Drupal. From there it's just a matter of choosing fields, and adding styling.

Make sure to clear cache so Drupal will register your new twig file!

---
Tags: views, 8
---


# Question
Title: Wave tool used to evaluate web content for accessibility issues giving Broken ARIA reference errors
I am trying to fix Broken ARIA reference errors notified by Wave tool in chrome for my custom module web pages and Drupal 8 core login form. Sample error in login form is mentioned below for username field. How to fix these issues. For every user control I have this site wide.

Error at username text box:

\*aria-describedby="edit-name--description", aria-required="true"

(An aria-labelledby or aria-describedby reference exists, but the target for the reference does not exist.)

I am not able to find aria-describedby attribute itself in the code for the controls. So, I am not sure how to fix them.

# Answer
The attribute is only added if the element has a description. This is the code from the `FormBuilder` that does it:

```
// Add the aria-describedby attribute to associate the form control with its
// description.
if (!empty($element['#description'])) {
  $element['#attributes']['aria-describedby'] = $element['#id'] . '--description';
}

```

The idea being that when the input is rendered in form-element.html.twig, the description is rendered alongside it with a matching ID. For example this is how the core stable theme handles it:

```
{% if description_display in ['after', 'invisible'] and description.content %}
  <div{{ description.attributes.addClass(description_classes) }}>
    {{ description.content }}
  </div>
{% endif %}

```

So it seems likely there aren't that many possible sources for the problem. These are the only ones I could come up with:

1. You're using a core theme, or a derivative of one which still renders the description in form-element.html.twig, and something in the system is setting the description display to a value other than 'after' and 'invisible', causing it not to be rendered.
2. You're using a non-core theme, which overrides form-element.html.twig, and doesn't render the description.
3. Something in the system is changing either the value in the input's `aria-describedby` attribute, or the ID of the description element in the element template, causing them not to match.
4. Some combination of the above.

Hopefully that's enough to go on.
> 1 votes

---
Tags: 8
---


# Question
Title: Hook name in module doesn't seem to work
I've been at this for days, but I finally think I maybe kinda sorta found part of the problem, maybe...but I don't know how to fix it.

I'm working on a Drupal site with the CiviCRM module running. I have a form on which I'd like to alter the data before saving it to the database. As a result, I've been struggling with getting ANY of the available CiviCRM hooks to fire.

I installed the *civicrm\_developer* module, which is sort of a complement to Devel, in that it is used to help see into objects and other variables. Looking in the module's .module file, you see all of the CiviCRM hook functions, which are being used in the module to `dpm()` whatever variables were passed to them.

```
function civicrm_developer_civicrm_buildForm($formName, &$form){
  drupal_set_message("hook_civicrm_buildForm called: formName is $formName");
  dpm($form);
  dpm($formName);
}

```

There are no includes or anything else, just hooks and printing variables, for each and every hook available in CiviCRM. The *civicrm\_developer* module indeed works as intended. On the specific page I'm working with, there is a CiviCRM form and this module prints a populated Krumo above that form, as would be expected when `dpm()`-ing a variable in Drupal.

However, attempts at making a custom module which uses one or two of those same hooks, can never seem to get to that same data. I've gone far as copying the code from that module (just one .module and .info file) to my custom module and changed the hook nomenclature from "civicrm\_developer" to, let's say, "mymodule".

So, my module, which is practically an exact copy of that module, with the exception of the hook name, will not generate a Krumo above the form as the *civicrm\_developer* module did when it was enabled. Yes, I've made sure that my module was enabled.

For example, this is the same function from earlier as written in my custom module.

```
function mymodule_buildForm($formName, &$form){
  drupal_set_message("mymodule_buildForm called: formName is $formName");
  dpm($form);
  dpm($formName);
}

```

It might also be worth mentioning that the *mymodule* name in use is unique to that module. It doesn't match the theme name or anything else that would cause a name collision, at least that I know of.

I can't figure out why the same hooks work in a module but not the other. It just doesn't make any sense.

# Answer
there is no `hook_buildForm()` hook in Drupal. The hook you are trying to implement is `hook_civicrm_buildForm()`, so to get it work you should use `mymodule_civicrm_buildForm()`.

You can always use `hook_form_alter()` or, more specifically, `hook_form_FORM_ID_alter()` to make changes on any Drupal form.
> 5 votes

---
Tags: hooks, civicrm
---


# Question
Title: Ignore Special Characters from Expose Filter
How I can ignore special characters from expose filter.for example: I have a view with expose filter ( Title ) but if I write the text without special characters it returns ( No Result ) & if write the text with those special characters I have resulted.

Note: When I created the node I wrote the Title with special characters

Example: I created a node with Title (i'ts) if I searched in expose filter by using (its) it returns(No Result) but if I wrote (i'ts) it works fine

# Answer
in hook\_form\_alter function you can check the expose form and write your below function.

function clean($string) { $string = str\_replace(' ', '-', $string); // Replaces all spaces with hyphens.

return preg\_replace('/\[^A-Za-z0-9-\]/', '', $string); // Removes special chars. }

assign value to form value array.
> 0 votes

---
Tags: views
---


# Question
Title: Display User Author Details in Block UserProfile
I am looking to display my own block on user profile page. The block will to display the username of the user whom profile we are viewing.

I went ahead and created a view, show users, block.

Added contextual filter for UIID, Raw value from URL. Path component 2

User profile and a user sub-pages have this structure: domain.com/u/username (user main profile page) domain.com/user/845/posts (user posts, where 845 is uid)

How can I add a contextual filter that will work on both cases? The username is changed a little by path auto. Dashes, commas, uppercases and such are removed so that may be why raw value from URL is not working.

Btw, I am open to creating a custom user profile by creating user/% view for user profile.

# Answer
> 1 votes
The alias doesn't matter, you get the argument for a contextual filter from the internal path, no matter if the URL in the browser was aliased (unless you enable the option "Use path alias"). For a user profile the internal path is /user/\[uid\].

For the user ID there is also a contextual filter "User ID from route context", this filter is able to get the user without specifying in which path position it is.

---
Tags: views, 8, users
---


# Question
Title: How do we make the date field default to today's date?
We want the date field to default to today's date when creating a new article. In the node edit form it defaults to the date set in the content type field settings. In the field settings form, it says "leave blank to use the time of form submission". If we leave it blank, it saves the form submission time which is then the new default for the node edit form.

How do we make the date field in the node edit form always show today's date for new content?

# Answer
If already date field created follow the below steps to change the date formate:

1. Goto particular Content type, which you have created.

admin/structure/types/manage/{CONTENTTYPE\_MAHINE\_NAME}

2. click on the 'Manage Fields' form the tab menu
3. click on the 'edit' button on the date field of the content type. The field settings will open, the link will be

/admin/structure/types/manage/{CONTENTTYPE\_MAHINE\_NAME}/fields/node.{CONTENTTYPE\_MAHINE\_NAME}.field\_{FIELD\_MACHINE\_NAME}

Goto bottom of the page

4. Select the 'Current date' option from the drop down at the section of 'default value'.
5. To display only the date without time, goto 'Field settings' and select the 'date only' option from the drop down of 'Date type'.
> 1 votes

# Answer
you can set it by code just implement `form alter hook` in your `custom module` and set your date like,

```
function example_form_alter(&$form, &$form_state, $form_id) {
  dsm($form_id);  // print form ID to messages
  if($form_id == "your contentype form-id"){
  if(!isset($form['your field name']){
  //set your field value as default current time
    $today = date('d/m/Y');
    $form['your field name']["und"][0]['value']['#default_value']['value'] = $today;
  }
  }
}

```
> 0 votes

# Answer
You can setting config field `{example.com}/admin/structure/types/manage/event/fields/{field_date}`
> 0 votes

---
Tags: 8, datetime
---


# Question
Title: How to check in Twig file whether node has a field?
In my twig file i try to override the field. In the {% if %} clause I need to check whether a field has particular value, if yes then assign the value as a class.

```
{% for item in items %}
  {% if node.language.value == "English"  %}
    {% set example_classes = 'english' %}
   {% else %}
    {% set example_classes = node.language.value %}
  {% endif %}
  <div{{ attributes.addClass('field', field_name, example_classes) }}>
    {{ item.content }}
  </div>
{% endfor %}

```

the line {% if node.language.value == "English" %} brings nothing, how can I get the value of the node's field\_language in twig file?

In the field.html.twig a list of available variables is specified:

```
Available variables:
* - attributes: HTML attributes for the containing element.
* - label_hidden: Whether to show the field label or not.
* - title_attributes: HTML attributes for the title.
* - label: The label for the field.
* - multiple: TRUE if a field can contain multiple items.
* - items: List of all the field items. Each item contains:
*   - attributes: List of HTML attributes for each item.
*   - content: The field item's content.
* - entity_type: The entity type to which the field belongs.
* - field_name: The name of the field.
* - field_type: The type of the field.
* - label_display: The display settings for the label.

```

# Answer
> 0 votes
I'm a friend of template pre-processing, in order to keep presentation logic separated from (advanced) field processing.

Therefore, I suggest a hook\_preprocess\_HOOK() implementation in your theme's `*.theme` file and outline this approach:

```
/**
 * Implements hook_preprocess_HOOK() for nodes.
 */
mytheme_preprocess_node(array &$variables) {
  $node = $variables['node'];
  $example_class = '';
  if (
    $node->hasField('field_language')
    && !$node->field_language->isEmpty()
  ) {
    $variables['example_class'] = strtolower($node->field_language->value);
  }
  $variables['example_class'] = $example_class;
}

```

So you could access the newly added template variable `{{ example_class }}` within your node template:

```
{% for item in items %}
  {%
    set field_classes = [
      'field',
      field_name,
      example_class,
    ]
  %}
  <div{{ attributes.addClass(field_classes) }}>
    {{ item.content }}
  </div>
{% endfor %}

```

If you'd like to stick to just altering your template, you can also access all fields of a `node` entity within its templates by using the `{{ node }}` variable.

Keep in mind, that unrendered/preprocessed fields of the original entity usually are FieldItemLists. So you'll access an array of field item instances keyed by their delta:

```
{% if node.field_language and node.field_language[0].value == 'English' %}
...
{% endif %}

```

The `{{ dump() }}` Twig function can help you to debug your available values.

---
Tags: 8, theming
---


title: Does Drush 8.x work with core 7.x?

text:
# Question
Title: Does Drush 8.x work with core 7.x?
With the major changes to Drupal with version 8, it seems I would need Drush 7.x or earlier to work with Drupal 7.x. I tried to rebuild the cache and I got errors related to namespaces in PHP. It seemed to be looking for features that were not part of Drupal 7.x.

Are there different commands to clear the cache for a Drupal 7.x site?
I tried `drush cr` and it came back with errors indicating it was trying to find code using namespaces, but Drupal 7.x core doesn't use namespaces in the code.

I tried it on Ubuntu and on Windows.

# Answer
Yes, Drush 8 works with Drupal 6, 7 and -8.3. I just tested Drush 8.1.17 against a Drupal 7.58 site: worked a charm to clear cache, generate a login URL and download a module.

This is the compatibility table from their site for reference:

> I mean are there different commands to clear the cache for a Drupal 7.x site?

Yes, it was *cache-clear*, or *cc* for short in Drupal 7, e.g.

```
drush cc all

```
> 5 votes

# Answer
The current way of installing Drush is to add the version you need on a per-project basis, using `composer require drush/drush`. Then you install Drush Launcher, which will use the drush in the directory of whatever site you are working on.
> 1 votes

# Answer
It's better to use the both of drush with different aliases, for example use drush8 for drush core 8.x and drush7 for drush core 7.x. To do that install the both drush version and use two symbolic links (for Mac):

```
ln -sv path_to_drush7_installation_folder/drush /usr/local/bin/drush7
ln -sv path_to_drush8_installation_folder/drush /usr/local/bin/drush8

```

And then to clear cache for example you can use :

* For a Druapl 8 project:

`drush8 cr`
* for a Drupal 7 project:

`drush7 cc all`
> 0 votes

---
Tags: drush
---


# Question
Title: Why is my view not displaying Solr index results?
I have a multilingual site and I created a Solr server, created an index (for all content types), added fields, generated the search (it displayed that all my nodes were succcessfully indexed 8/8), then created a view using that index and selected render entity and the view has no results. I tried fiddling about with every setting in the search\_api options/index, rebuilding the index, clearing the cache, and the view results is always empty. Ideas?

# Answer
> 0 votes
The problem was i forgot to look at the php-error log/watchdog. There was a custom module which had some code which was causing a fatal error on all links being generated. Fixed that issue, all was working after.

---
Tags: views, search
---


# Question
Title: Alter the access of menu links before rendering
I need to alter the access of menu links before being rendered. In Drupal 7, we used `hook_translated_menu_link_alter()` for it. Drupal 8 change records show that there are no direct replacement for that hook.

Is there any other hook or controller to alter the access of the menu link before it is rendered?

# Answer
> 7 votes
After some trial and error an researching and researching I found out how to get it done.

**Case:** The aim is to avoid that any other user than the admin can access administration pages starting with path "/admin/config/\*". The point is that we have a administrator role in our project who should have access to the menu administration pages (they need the permission "Use the administration pages and help" to get to this administration page). With this permission they also see the "Configuration" menu item in toolbar and all sub menu items like "System" but these pages are empty.

**How to achive that by altering the access checks**

First define your own RouteSubscribe class in folder/file your\_module/src/Routing/AdminRouteSubscriber.php:

```
namespace Drupal\your_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class AdminRouteSubscriber extends RouteSubscriberBase  {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    $path = '/admin/config';
    foreach ($collection->all() as $routename => $route) {
      if (substr($route->getPath(), 0, 13) == $path) {
        $route->setRequirement(
          '_custom_access',
          '\Drupal\your_module\AccessChecks\CustomAccessChecks::access'
        );
      }
    }
  }
}

```

What we did here is to check the path of every route and if it starts with "/admin/config" it gets added our custom AccessCheck class defining the method "admimAccess" to be called.

Than go ahead and define your own access check class in folder/file your\_module/src/AccessChecks/CustomAccessChecks.php:

```
namespace Drupal\your_module\AccessChecks;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResultAllowed;
use Symfony\Component\Routing\Route;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAccessChecks implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
    return AccessResultAllowed::allowedIf((int) $account->id() === 1);
  }
}

```

This access method has to return an implementation of AccessResultInterface. We say that access is allowed if the current user has the id 1.

Lastly you need to add these classes to the service container by defining your your\_module.services.yml in your module's root folder:

```
services:
  your_module.route_subscriber:
    class: Drupal\your_module\Routing\AdminRouteSubscriber
    tags:
      - { name: event_subscriber }
  your_module.access_checker:
      class: Drupal\your_module\AccessChecks\CustomAccessChecks
      tags:
        - { name: access_check }

```

After rebuilding your cache it works.

# Answer
> 4 votes
When having slugs in routes, for eg: **block\_content.add\_form** from core block content has {block\_content\_type} as slug. Following example can help.

**example.services.yml**

```
access_check.block.add:
  class: Drupal\example\Access\ExampleAccessCheck
  arguments: ['@current_user']
  tags:
    - { name: access_check, applies_to: _example_access_check }

```

**RouteSubscriber.php**

```
<?php

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    $route = $collection->get('block_content.add_form');
    if ($route) {
      $route->setRequirements([
        '_example_access_check' => 'TRUE',
      ]);
    }
  }

}

```

**ExampleAccessCheck.php**

```
<?php

namespace Drupal\example\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Determines access to for block add pages.
 */
class ExampleAccessCheck implements AccessInterface {

  /**
   * Checks access to the block add page for the block type.
   */
  public function access($block_content_type, AccountInterface $account) {
    return AccessResult::allowedIf($account->hasPermission("some permission"));
  }

}

```

**$block\_content\_type** is available which can be used to alter menu links for specific block type.

# Answer
> 0 votes
If you have a route as input of your menu link (you usually do), you may use custom\_access checks like here:

```
example:
  path: '/example'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _custom_access:  '\Drupal\example\Controller\ExampleController::access'

```

(Taken from https://www.drupal.org/node/2122195)

---
Tags: 8, navigation
---


# Question
Title: How do I get at the raw file name of a File entity in a Twig field override?
This is my first effort at Twig development so please bear with me. I have a vanilla Drupal 8.1 site with a content type that contains just the body and a File type field called field\_fichier\_svg. This will contain SVG files (surprise!) and I want to override the Twig field rendering so that I can get the raw file name and wrap an "img" HTML tag around it.

I have successfully installed kint, and have overridden the field template with one called field--node--field-fichier-svg--icon.html.twig (the field is used in a content type called "icon") and this works.

I have also succeeded in running kint() and getting the output.

But none of the attempts I have made at getting the value of the field function. In the snippets below you can see the three different attempts I have made.

1) Try to identify the class that handles file entities and use that:

```
{%
  set classes = [
    'file'
  ]
%}
<img id="entity" src="{{file.label}}" />

```

2 & 3) Loop round "items" and try different things which I have tried to interpret from the kint output (kint does work by the way)

```
{% for item in items %}
  <img id="label" src="{{ item.label }}"/>
  <img id="array" src="{{item.content['#file'].values['filename']['x-default']}}" />
  {{kint(item.content)}}
{% endfor %}

```

In all cases the "src" attribute is just blank.

To make it a bit more manageable I tried putting

```
{{dump(item.content|keys)}}

```

and I get this:

```
array(5) { [0]=> string(6) "#theme" [1]=> string(5) "#file" [2]=> string(12) "#description" [3]=> string(6) "#cache" [4]=> string(11) "#attributes" }

```

Then I tried

```
{{dump(item.content['#file']|keys)}}

```

and I get this:

```
array(11) { [0]=> string(3) "fid" [1]=> string(4) "uuid" [2]=> string(8) "langcode" [3]=> string(3) "uid" [4]=> string(8) "filename" [5]=> string(3) "uri" [6]=> string(8) "filemime" [7]=> string(8) "filesize" [8]=> string(6) "status" [9]=> string(7) "created" [10]=> string(7) "changed" }

```

but if I try

```
 {{item.content['#file']['filename']}}

```

I just get nothing

# Answer
to get the filename you can use this:

```
{{ item.content['#file'].filename.value }}

```
> 5 votes

---
Tags: theming
---


# Question
Title: Class not found for a new module/service I am building. I am not sure how to debug
I am building a new service, an event subscriber in a custom module. My class which extends EventSubscriberInterface is not being found.

> \[error\] Class Drupal\fivewire\_commerce\EventSubscriber\fivewire\_commerce\_orderStateSubscriber does not exist

I am not sure why and am struggling to debug what I have done wrong.

My module is 'fivewire\_commerce'.

/modules/custom/fivewire\_commerce

I have created a file to delare my service.

/modules/custom/fivewire\_commerce/fivewire\_commerce.services.yml

```
services:
  fivewire_commerce.order_subscriber:
    class: Drupal\fivewire_commerce\EventSubscriber\fivewire_commerce_orderStateSubscriber
    tags:
      - { name: 'event_subscriber' }

```

And this is my class

/modules/custom/fivewire\_commerce/EventSubscriber/fivewire\_commerce\_orderStateSubscriber.php

```
<?php

/**
 * @file
 * Contains \Drupal\fivewire_commerce\EventSubscriber\fivewire_commerce_orderStateSubscriber
 */

namespace Drupal\fivewire_commerce\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;

/**
 * Event Subscriber MyEventSubscriber.
 */
class fivewire_commerce_orderStateSubscriber implements EventSubscriberInterface {

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        // Trigger after an order is made
        $events['commerce_order.place.post_transition'][] = ['onCompletedOrders'];
        return $events;
    }

    /**
     * Code that should be triggered when an order is placed.
     * This is the order state 'validation' according to our chosen workflow.
     */
    public function onCompletedOrders(WorkflowTransitionEvent $event) {
        $test =true;
//        if ($event->getToState()->getId() == 'validation') {
//
//        }
    }

}

```

And if I try to rebuild my cache I get:

> \[error\] Class Drupal\fivewire\_commerce\EventSubscriber\fivewire\_commerce\_orderStateSubscriber does not exist

# Answer
> And this is my class
>
> /modules/custom/fivewire\_commerce/EventSubscriber/fivewire\_commerce\_orderStateSubscriber.php

Autoloading relies on your classes being in a root /src folder for the module.

So move the file to

> /modules/custom/fivewire\_commerce/src/EventSubscriber/fivewire\_commerce\_orderStateSubscriber.php

And PHP will be able to find it.
> 3 votes

---
Tags: event-subscribers
---


# Question
Title: Accessing a FieldItemList value within Twig
I've tried several different ways to try access the value of a field item list value without success.

The item in question within Drupal 8 is a float text field and I need the unmodified number from this. The value gained from the standard `content.field_latitude[0]['#markup']` call is rounded in some manner so I want to grab the one located in the `#items` object as shown in the screen shot below.

I can get this via a preprocessor in the theme file but want to avoid using a preprocess if I can and want to gain access directly in the twig file.

# Answer
To get the value you've highlighted in the debug output in Twig:

```
{{ content.field_latitude['#items'].0.value }}

```

You can see this follows the path you've shown in the screenshot, but missing the protected values array. Instead it uses `.value` on the field item, which calls a magic method `__get('value')` to retrieve the protected property.

But as @MarioSteinitz commented it's better to use the `node` object:

```
{{ node.field_latitude.value }}

```

Because `content` is not an API like the methods of the node object. It is a render array which can change when you configure the field display differently or install a layout module.

And never use the `|raw` filter on user input!
> 5 votes

# Answer
Use the `raw` filter:

```
{{ content.field_latitude[0]|raw }}

```
> 0 votes

---
Tags: 8, theming
---


title: Unable to use Node::load

text:
# Question
Title: Unable to use Node::load
Fatal error: Class 'EntityInterface' not found in /cptestd8/modules/custom/custom-autofill-reference/custom\_autofill\_reference.module on line 13

```
use Drupal\node\Entity\Node;
    function custom_autofill_reference_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

      drupal_set_message($form_id);

      if($form_id =='node_monitoring_report_form'){
        $field_school_information =  \Drupal::request()->query->get('field_school_information');
        $node_details = Node::load($field_school_information);
        $node = $node_details->field_FIELD_NAME->value;
        $form['field_school_information']['widget'][0]['target_id']['#default_value']=  $node;

      }
    }

```

While trying to load the node I get error as shown below:

> Fatal error: Class 'EntityInterface' not found in /modules/custom/custom-autofill-reference/custom\_autofill\_reference.module on line 13

And line 13 is:

```
$form['field_school_information']['widget'][0]['target_id']['#default_value'] = $node;

```

Drupal Version: 8.6.x

# Answer
> 3 votes
```
use Drupal\node\Entity\Node;

function custom_autofill_reference_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id =='node_monitoring_report_form'){
    $field_school_information =  \Drupal::request()->query->get('field_school_information');
    $node_details = \Drupal\node\Entity\Node::load($field_school_information);
    $form['field_school_information']['widget'][0]['target_id']['#default_value'] = $node_details;
  }

}

```

Above code worked finally and it was showing error as I did not clear the cache while trying to check it out.

---
Tags: 8, nodes
---


# Question
Title: Update user profile picture using entity_metadata_wrapper
I am trying to update the user profile picture using entity\_metadata\_wrapper. But I am getting

> "Unknown data property picture." error.

When I check the user property info, I cant see the picture field as well. Below is my example code:

```
$user = entity_metadata_wrapper('user', $form_state['entity_id']);
if (isset($form_state['values']['user_profile_pic'])) {
   $file = file_load($form_state['values']['user_profile_pic']);
   $file->status = FILE_STATUS_PERMANENT;
   file_save($file);
$user->picture = $file;
}

```

Thanks in advance.

# Answer
> 0 votes
Try this out :

```

  $wrapper = entity_metadata_wrapper('user', $form_state['entity_id']);
//- Get the user object.
  $user = $wrapper->value();
  if (isset($form_state['values']['user_profile_pic'])) {
    $file = file_load($form_state['values']['user_profile_pic']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    $edit = array(
      'picture' => $file,
    );
    user_save($user, $edit);
  }

```

---
Tags: 7, entities, users
---


# Question
Title: Theme hook_menu_alter not being called (create theme only page)
It has been quite a while since I worked on Drupal 7, but I'm hitting a snag.

First please understand I only have access to the theme, I cannot create a bunch of custom modules.

Now, I want to add a page, on the URL `my.domain.com/authorization`, this page should only be available for administrators and I want to provide some custom markup for the "innards" of the page.

Since I know my theme's template.php can implement `hook_theme()`, I declare my route and template.

```
function mytheme_theme() {
  return array(
    'authorization' => array(
      'variables' => array('var' => null),
      'template' => 'my_authorization'
    )
  );
}

```

I can easily add my markup the *my\_authorization.tpl.php* file, which exists.

However, when I navigate to my URL, I get a *Page not found* error.

I figured I need to add a MENU\_CALLBACK to the menu for my route; I understand I cannot use `hook_menu()` from a theme, but I can use `hook_menu_alter()`, so I write this function (which also takes care of my access issue).

```
function mytheme_menu_alter(&$items) {
  $items['authorization'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => t('Authorization'),
    'page callback' => 'page_callback',
    'access callback' => TRUE,
  );

  return $items;
}

```

It never hits this function! What have I done wrong?

The page callback exists (it returns a test string) but it is never called, because `mytheme_menu_alter()` doesn't seem to be invoked.

To be clear, my outcome is simply, for the theme I am working on (only), if the URL is my.domain.com/authorization, and the logged in user is an administrator, display a link on the page (to an oauth endpoint).

# Answer
> 0 votes
I solved this as so (for info).

First a bit more background. This is basically a REST/SOAP Web Service that integrates some business info into some pages on the specific theme, part of the service is an OAuth2 layer that authenticates the server/site with the Web Service.

The Web service is not available in any other theme (indeed there are no other themes), obviously the OAuth requires exchange of secret keys and ID's so should not be exposed to the front of the site (unless the user is an authenticated admin).

My solution, firstly due to the poor coding the previous freelancer put down (he left the API and secret keys exposed, hard coded domains, no "Service Unavailable" messages, ect) I implemented a simple "Service Unavailable, please contact us or come back later" message should the web service be unavailable.

Because all this happens on specific pages of the site, I also put a block under the code that is displayed if the logged in user is an administrator.

Originally I wanted this to be a link to this supposed page that explains the Web Service is not authorized and offer the link to auth it. As this is not possible I skipped this step, shortened the explanation and present the link and explanation under the "Service is Unavailable" message, thus the admin can visit any page with the Web Service on it, see the "Unavailable" message and as an admin initialize the auth process from there.

Definitely the path of least resistance!

That solves the issue, now all that remains is for me to dig into the core for a better understanding of the way the routing table and page callbacks are built. After all, the more you know....

Finally, big thanks to everyone who took the time to stop by, read and/or comment on my query. I and SE appreciate it!

---
Tags: 7, hooks
---


# Question
Title: How to use Composer to install third party libraries
All I thought Composer takes care of any external library a contrib module requires automatically. I tried installing one, Composer took care of all its dependency modules, but not so much with the external library.

How do I use Composer to install external libraries that any module depends on?

# Answer
> 4 votes
It is not recommended to installing JavaScript libraries using `composer.json`, but it is possible.

> Note: This repository type has a few limitations and should be avoided whenever possible:
>
> Composer will not update the package unless you change the versionfield.Composer will not update the commit references, so if you use master as reference you will have to delete the package to force an update, and will have to deal with an unstable lock file.

(Composer docs)

If your package is available for download at an external source, e.g. as an archive, you could add it as custom package with type `drupal-library` to the `repositories` section of your Drupal project's `composer.json`, and then require this package accordingly:

```
"repositories": {
  "drupal": {
    "type": "composer",
    "url": "https://packages.drupal.org/8"
  },
  "mypackage": {
    "type": "package",
    "package": {
      "name": "myvendor/mypackage",
      "version": "1.0.0",
      "type": "drupal-library",
      "dist": {
        "url": "https://example.com/mypackage.zip",
        "type": "zip"
      }
    }
  }
},
"require": {
  ...
  "composer/installers": "^1.2",
  "myvendor/mypackage": "1.0.0"
},
"extra": {
  "installer-paths": {
    "public/core": ["type:drupal-core"],
    "public/libraries/{$name}": ["type:drupal-library"],
    "public/modules/contrib/{$name}": ["type:drupal-module"],
    "public/profiles/contrib/{$name}": ["type:drupal-profile"],
    "public/themes/contrib/{$name}": ["type:drupal-theme"],
    "drush/contrib/{$name}": ["type:drupal-drush"]
  },
  ...
}

```

Check the Repositories documentation for Composer for more details or other source types.

# Answer
> 3 votes
Definitly https://asset-packagist.org/

Minor annoyance is the incosistent naming, depending on the module, you have to use either `composer require npm-asset/js-lib` or `composer require bower-asset/js-lib`

Add the settings to composer.json as documented on asset packagist (see Installing to a custom path), and set the drupal-specific installer-path, e.g. something like

```
"extra": {
    "installer-types": ["bower-asset", "npm-asset"],
    "installer-paths": {
        ....
        "web/libraries/{$name}": ["type:drupal-library", "type:bower-asset", "type:npm-asset"],
        ...
    }
}

```

---
Tags: 8, composer
---


title: Drupal 8 variable_get

text:
# Question
Title: Drupal 8 variable_get
I have some code in Drupal 7 what are using variable\_get. Now I would like to write the code in Drupal 8. So I was reading this but its didn't help me a lot.

How to write this code in Drupal 8 from code in Drupal 7?

```
$types = array_values(variable_get('test_content_types', array()));

```

or this

```
'#default_value' => variable_get('test_content_types', array()),

```

Some suggestion.

# Answer
In Drupal 7

```
 $data =  variable_get('test_content_types');

```

In Drupal 8

```
 $data = \Drupal::state()->get('test_content_types');

```

For more information about about "get", "set", "delete" visit - Step 5: How to upgrade D7 variables to D8's state system.
> 22 votes

# Answer
The accepted answer is half the answer. As marcvangend notes, there are two options in Drupal 8 for what used to be stored in the variables table and was stored and retrieved with `variable_set()` and `variable_get()`. The first, documented in darol100's answer, is the State API.

The second is the Configuration API and should be used in most cases where you have a configuration form. It requires at minimum in your module a configuration installation file, for example `config/install/example.settings.yml`. For a single piece of configuration (with multiple potential values), that file could just contain for example:

`test_content_types:
 - article`

And then use the value with:

```
$types = \Drupal::config('example.settings')->get('test_content_types');

```

Or change the stored values with:

```
\Drupal::service('config.factory')
  ->getEditable('example.settings')
  ->set('test_content_types', ['article', 'page'])
  ->save();

```

See also the the Drupal 8 documentation for D7 to D8 configuration upgrades and using configuration in modules.
> 10 votes

---
Tags: 8, configuration
---


title: Print image from filepath in Twig

text:
# Question
Title: Print image from filepath in Twig
I have a paragraph with an image field. If the image field is empty, I want to display a default value. I do *not* want to just set the default image because an editor could remove that. Here is my code so far:

```
{% if content.field_image|render = true %}
    {{ content.field_image }}
{% else %}
    {% include "/themes/mytheme/img/my_img.png” %}
{% endif %}

```

How can I get the image at that filepath to show up in the template?

# Answer
For example if your default image called `default_img.png` inside `images` folder inside your theme `MyTheme`.

You can try the following:

1. implement hook\_preprocess\_HOOK

```

/**
 2. Implements hook_preprocess_HOOK().
 */
function extended_url_preprocess_paragraph(&$variables) {
  $variables['theme_path'] = drupal_get_path('theme', 'MyTheme');
}

```
3. In your twig you can do something like:

```
{% if content.field_image|render = true %}
    {{ content.field_image }}
{% else %}
<img src="{{ theme_path ~ directory }}/images/default_img.png"/>
{% endif %}

```
> 1 votes

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


# Question
Title: What makes a maintenance mode message display, when a site is not in maintenance mode?
What makes a maintenance mode message display, when a site is not in maintenance mode? In this instance, it appears that it was because a contrib module was throwing a recoverable fatal error. So there was no WSOD/ general crash but because there was an error, the maintenance mode message was being displayed. Is this possible? I suppose it's too localised to really be sure.

This question is for Drupal 6 (it can't connect to the database) is the same true for Drupal 7?

Maintenance mode is not turned on, yet I'm getting a maintenance mode message. What's more it's being displayed as a second HTML page rendered fully marked up, beneath the target page which is also rendered fully marked up: Maintenance page being rendered as an entire page load after the main page load

# Answer
> 0 votes
If not in Maintenance it could also be an uncaught PHP exception as suggested here: "The website encountered an unexpected error. Please try again later." so check your Drupal logs (`Reports > Recent log messages`), or a problem with your database service.

You can test whether it's a database offline situation by using a special theme template based off of `maintenance-page.tpl.php` called `maintenance-page--offline.tpl.php` where you put your own HTML and text instead of printing the `$content` variable:

```
<h2>Connection to database lost!</h2>
<p>[Suggestions about what to do...]</p>

```

You can test what the page looks like (on your local dev environment) by disabling the mysqld temporarily and visiting your local site. Don't forget to clear the cache to get the new template to register before trying to test it.

---
Tags: 7, maintenance-mode
---


# Question
Title: Changing Twig template of form items through the theme
I have a block, which renders out a form using code that looks like this:

```
{{ attribute(form.facets, 'filter_' ~ filter.name) }}

```

I'd like to amend the markup and CSS classes for the various elements that are output, including fieldset, input, label etc. I appreciate that I can override the template files for fieldset for example, by creating a `fieldset.html.twig` file in my theme, but I don't want to change the markup for every fieldset element. I only want to apply my custom templates to form elements which are rendered out from a specific block.

I know that I can use a 'suggestion' (`mytheme_theme_suggestions_alter`) to alter the template for any element, but I can't see a way of determining if an 'input' for example, is an input within my block, or some other block on the site. Does anyone know how I'd identify this?

# Answer
> 1 votes
You can use `drupal_static()` together with the following two hooks in your module or your theme to add template suggestions for input elements based on the block ID where the input element is used in (same would work with fieldsets or any other form/render element):

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_block(&$variables) {

  $bid = &drupal_static('block_id', TRUE);
  $bid = $variables['elements']['#id'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME/MYMODULE_theme_suggestions_input_alter(array &$suggestions, array $variables) {

  $bid = &drupal_static('block_id', FALSE);

  if ($bid) {
    $suggestions[] = 'input__block__' . $bid;
    $suggestions[] = $variables['theme_hook_original'] . '__block__' . $bid;
  };
}

```

For example the search form textfield:

```
<!-- FILE NAME SUGGESTIONS:
   * input--search.html.twig
   * input--search--block--neato-search.html.twig
   * input--block--neato-search.html.twig
   x input.html.twig
-->

```

For example the password textfield:

```
<!-- FILE NAME SUGGESTIONS:
   * input--password.html.twig
   * input--password--block--userlogin.html.twig
   * input--block--userlogin.html.twig
   x input.html.twig
-->

```

---
Tags: 8, theming
---


title: Print taxonomy term for theming nodes

text:
# Question
Title: Print taxonomy term for theming nodes
I'm not a PHP developer, so I have a problem with customizing a theme.

I create a vocabulary "City" and a term "Shiraz", then a field "field\_city" as a taxonomy term in my content type.

Now I want to print this field, so in the tpl file I write the following code:

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

```

but nothing happens. What am I missing?

# Answer
> 1 votes
Try this out :

1. Make sure you set the right display of the field, like the following picture.
2. loop through `Items` and render vocab fields.

```
<?php foreach ($content['field_city']['#items'] as $item): ?>
   <?php print render($item['taxonomy_term']->name); ?>
<?php endforeach; ?>

```

**Note** : print only `name` field, if you have another fields in your vocabulary add them, like `$item['taxonomy_term']->some_field`

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


# Question
Title: Link to content within node, from CKEditor WYSIWYG
This seems like it should be fairly simple, but I'm having trouble getting off the ground.

I have a content type "Document". This content type has a field of type File, which allows for uploading PDF's. This content type also has a title, such as "My User Manual".

I want to create a simple CKEditor plugin, similar to LinkIt that will allow a content editor to highlight a piece of text, click a button in CKEditor, search for and select Document content types.

The result will be that the highlighted text will be wrapped in an anchor tag with an href to the file (which comes from the Document \> File field).

I know there are modules link IMCE which I can use to link to a file in the sites files, but I'm trying to simplify this a bit, as well as maintain only one file(s). I have also tried Entity Embed, unfortunately, this module embeds content, and doesn't necessarily allow for inline linking.

Thank you in advance for any insight you can provide.

# Answer
There's an option, under "Url Substitution" for linkit Media matchers that allows exactly this, but for Media entities. It should be fairly straightforward to create a new plugin using `Drupal\linkit\Plugin\Linkit\Substitution\Media` as a reference. (You should just have to update the plugin definition annotation as well as the `getUrl()` and `isApplicable()` methods. Then you can exclude your Document content type from any previous linkit matcher and add a new linkit matcher to your profile that uses your new plugin for Url Substitution type to link to Documents.
> 1 votes

---
Tags: 8, files, wysiwyg
---


# Question
Title: Maximum on date field and Views aggregation issue
I am running a Drupal 8.0.5, I have a content type called show which has fields title, an entity referenced called movie and a date time. I am trying to create a view of the latest shows of each movie. The initial view is like this which shows the movie and show time

I enabled aggregation. Aggregation functions i used are For movie - group results together and for datetime - maximum. The result is as follows

it just gives 2,016 as date time field where i was expecting Mon 03/21/2016 15:00:00. Are we not supposed to aggregate on date field? I thought since MAX usually works in database for timestamp, it is valid here also. Can anything be done to achieve this result?

# Answer
> 2 votes
1. First of all, select "None" for "Thousands marker" to have a properly formatted timestamp value;
2. In the "REWRITE RESULTS" section you can override the output of the field. Given I have the aggregated field "created" overriding the field would look as following:

{{ created |timestamp\_format('Y-m-d') }}

# Answer
> 0 votes
Yes, the issue should be addressed in the views module. You can use hook\_views\_pre\_render or (hook\_views\_post\_execute) to modify the values example:

```
YOUR_MODULE_views_pre_render(ViewExecutable $view) {
    if ($view->id() == 'YOUR_VIEW_ID'){
        $format = "d/m/Y H:i";
        foreach($view->result as $key => $result){
            $result->STRING_FIELD = date($format, result->TIMESTAMP_FIELD);
        }
    }
}

```

WARNING: the destination field must be a string, so you have to add a mock string field to the view (STRING\_FIELD).

```
$result->TIMESTAMP_FIELD = date($format, result->TIMESTAMP_FIELD);

```

will not work

# Answer
> 0 votes
The easiest way to correct the output of this field (show the full date instead of just the year) seems to be creating a Twig template file for the field, then calling the value directly; you can use twig filters to modify the format as needed.

For example:

* **View**: safety\_reports
* **Display**: page\_2
* **Date field**: field\_safetyrpt\_mailing\_date
* **Aggregation type**: Maximum
* **Template file name**: views-view-field--safety-reports--page-2--field-safetyrpt-mailing-date.html.twig
* **Template file contents**:

{{ row.node\__field\_safetyrpt\_mailing\_date\_field\_safetyrpt\_mailing\_d }}

or

{{ row.node\__field\_safetyrpt\_mailing\_date\_field\_safetyrpt\_mailing\_d | date('F j, Y') }}

---
Tags: views, 8, datetime
---


# Question
Title: How to print the product variation separately from the submit/pay button in a Commerce add to cart form?
I want to put the calculated product price between the "product variation" select widget and the "pay" button.

In `commerce-product.html.twig` (my products display an add to cart form on the product itself), I have this code:

```
<article{{ attributes }}>
  <h2>{{ product.title }}</h2>
  {{ product|without('title', 'variation_price' }}
  {{ product.variation_price }}
</article>

```

`variation_price` is the calculated price.

1. What is the name of the variable that contains the product variation select widget? **Answer: product.variations**
2. How can I place the submit/pay button separately from the variation type selection widget? **Answer: ??**

I tried using kint to debug but it broke my site. (And then people on this site kindly explained how to fix it.) So I now understand that the variable containing the widget that shows the variations is named **product.variations**, and this is actually the "Add to cart" form (since that is what I set the display widget to in the UI).

So I guess I need to print the "Add to cart" form twice, and in one instance show the submit button, and in the other instance show the select widget... But how do I do that?

I looked at the twig debug theme suggestions but they don't give me a template for the "Add to cart" form:

```
<!-- FILE NAME SUGGESTIONS:
   * field--commerce-product--variations--contenttype.html.twig
   * field--commerce-product--variations.html.twig
   * field--commerce-product--contenttype.html.twig
   * field--variations.html.twig
   * field--entity-reference.html.twig
   x field.html.twig

```

# Answer
This is how I fixed this issue:

Added this preprocess function in my .theme file

```
function YOURTHEME_preprocess_commerce_product(&$variables) {

   // Get the commerce product.
   $product = $variables['elements']['#commerce_product'];
   // Pass the price.
   $variables['price'] = $product->variations->entity->getPrice();
}

```

And in my twig file I print the price like this:

```
{{ price|commerce_price_format }}

```
> 6 votes

# Answer
Since the add to cart form is bundled with the product variations I have it working using the following in my commerce-product.html.twig template.

```
<article{{ attributes }}>
      {{ product.title }}
      {{ product.body }}
      {{ product.variation_price }}
      {{ product.variations }}  // show the add to cart button
</article>

```
> 1 votes

# Answer
I would further add that if you are adding custom attributes and wish to access those values in twig, follow the accepted answer and debug with kint like this from your theme/module\_preprocess\_template:

```
  ksm($product,'shows that we have one product to examine - notice array (1)');
  ksm($product->getVariationIds(),'this is $product->getVariationIds()');
  ksm($product->getVariations()[0]->getAttributeValues(),'this is $product->getVariations()[0]->getAttributeValues()');
  ksm($product->getVariations()[0]->getAttributeFieldNames(),' this is $product->getVariations()[0]->getAttributeFieldNames()');
  ksm($product->getVariations()[0]->getAttributeValue('my_target_attribute')->getName(),"found value at \$product->getVariations)[0]->getAttributeValue('my_target_attribute')->getName()");

```

Then proceed with assigning value to variables:

```
$variables['my_target_attribute'] = $product->getVariations()[0]->getAttributeValue('my_target_attribute')->getName();

```

You'd then be able to print my\_target\_attribute in your twig/template as:

```
{{ my_target_attribute }}

```
> 1 votes

# Answer
I couldn't figure out how to do this in a twig template, but it can be done in `hook_form_alter()`:

```
/**
 * Implements hook_form_FORM_ID_alter().
 * If necessary, you can target specific products like this:
 * (product with ID of 2)
 * function MYMODULE_form_commerce_order_item_add_to_cart_form_commerce_product_2_alter(array &$form, FormStateInterface $form_state, $form_id) {
 */
function MYMODULE_form_commerce_order_item_add_to_cart_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  // Text shown between variations widget and submit buttons.
  $form['placeholder']['#markup'] = '<p>' . t('This is my message.') . '</p>';
}

```
> 0 votes

---
Tags: theming, 8, commerce
---


title: Create entity view block

text:
# Question
Title: Create entity view block
I have 2 content types: schools and courses.

On the schools content type, I created a field called 'Courses At This School' which is an entity reference field to the courses content type.

So, I edit a school and then I can add which courses the schools runs based on nodes I created on courses.

I now need to create a block view but cannot get my head around how to do this. This block will be placed on the schools node pages and will show which courses the schools run so I'll need a contextual filter too.

I have tried playing around with this but I am getting nowhere. Do I create a view and filter by courses or schools?

# Answer
Please follow the below steps. You will achieve what you have asked.

```
1. Go to Structures > Views > Add a New View (named Courses)> Select Type as Courses > Create a Block

2. Enter the Block Title as Courses > Continue and Edit

3.  Under the Advanced > Add Relationships search for Entity Reference: Referencing entity (select the same field which was referenced under school content type) and click on apply

4. Under contextual filter > Search and select Content: Nid and in relationship option select the relationship and under WHEN THE FILTER VALUE IS NOT AVAILABLE
 select as  Provide default value > Content id from URL > Click on apply

5.  And under format or Fields, you can select anything depending on how you want to display the data

```
> 2 votes

---
Tags: views, entities
---


# Question
Title: Language specific settings for field formatters
I've created a custom field formatter widget for numeric fields. The formatter has A LOT of settings to customize the visual output of that number, to whatever designers/marketing wants (adding a lot of HTML markup, with\[out\] leading/trailing zeros, zeros as dash, one or two fractions, rounding, prefixes/infixes/suffixes,... ). Some of those settings are language-dependant though, so I'd like to enter different formatter settings in

/en/admin/structure/types/manage/MY\_CONTENT\_TYPE/display /de/admin/structure/types/manage/MY\_CONTENT\_TYPE/display /fr/admin/structure/types/manage/MY\_CONTENT\_TYPE/display

I've noticed that there is a `$langcode` parameter in
FormatterInterface::viewElements(FieldItemListInterface $items, $langcode)

but I don't know how to make
FormatterInterface.php FormatterInterface::settingsForm(array $form, FormStateInterface $form\_state)
language-aware.

Is it possible at all to have language-specific settings in a field formatter? If yes, how to I store and retrieve those settings in the correct language?

# Answer
> 5 votes
1. Define a schema in your module *config/schema/mymodule.schema.yml*.

Example from the date range module:

core/modules/datetime\_range/config/schema/datetime\_range.schema.yml

```
field.formatter.settings.daterange_default:
  type: field.formatter.settings.datetime_default
  label: 'Date range default display format settings'
  mapping:
    separator:
      type: label
      label: 'Separator'
      translation context: 'Date range separator'

```

For more information see Block configuration form values are not translated
2. You need an UI to translate, which is unfortunately not ready yet, see this issue:

Entity view/form mode formatter/widget settings have no translation UI

Until then you can edit the translated yaml file of an exported config in *config/sync/language/\[LanguageID\]* or install the patch from the issue.

---
Tags: 8
---


# Question
Title: How do I hook before the user is created in Behat tests?
I have a Behat test where I have a *Given user* step, and I want to alter some fields (token replacements). Which Behat hook should I use? I know that for *Given content*, the Behat hook would be @beforeNodeCreate.

Which hook is for users?

# Answer
Somewhat predictably, which I'm pretty sure is deliberate, it's `@beforeUserCreate`.

The Drupal Extension Hooks section of the docs has a bit of background in case you need it.
> 3 votes

---
Tags: testing
---


title: hook_node_validate called on delete?

text:
# Question
Title: hook_node_validate called on delete?
Why is my `hook_node_validate` implementation being called when I try to delete a node through the node editing form (by clicking the delete button at the bottom of form)? Validation fires and then my node doesn't get deleted which is not what I want.

I can delete without any problems when clicking on delete link at `admin/content` but not whenclicking delete button on node edit form since validation fires and fails. What could be the reason for validation firing here?

# Answer
> 1 votes
nmc is right, validate functions are called for delete button as well, see http://drupal.org/node/216064 for more details

# Answer
> 3 votes
You could check the Triggering element in the Form State for the button that triggers the Form Submission.

```
function MYMODULE_node_validate($node , $form_state , $form) {
  if ($form_state['triggering_element']['#value'] != 'Delete') {
    //Include the validations here
  }
}

```

# Answer
> 0 votes
It's not invoked when deleting a node, basing on the code for node\_delete\_multiple(); the only functions called from that function that involve hooks are the following ones:

```
    node_invoke($node, 'delete');
    module_invoke_all('node_delete', $node);
    module_invoke_all('entity_delete', $node, 'node');
    field_attach_delete('node', $node);

```

The function is called from node\_delete().

Looking at the code for node\_delete\_confirm\_submit(), the form submission hander executed when a node is being deleted from the node edit form through the "Delete" button, I notice the following code:

```
$node = node_load($form_state['values']['nid']);
node_delete($form_state['values']['nid']);

```

That would cause the implementations of hook\_node\_load() to be invoked, but as far as I can see, it would not cause hook\_node\_validate() (which is invoked from node\_validate()) to be invoked.

# Answer
> 0 votes
For fix that, you can do this:

```
function [mymodule]_form_alter(&$form, &$form_state, $form_id) {
  // For articles for example:
  if ($form_id == 'article_node_form') {
    $form['#validate'][] = 'myfunction_for_validate_article';
  }
}

function myfunction_for_validate_article($form, &$form_state) {
  // This only will be call on insert and update.
}

```

Source: http://befused.com/drupal/form-validation

# Answer
> 0 votes
In Drupal 7 you can suppress validation on all node edit Delete buttons with this code in a custom module:

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Suppress validation for Delete button.
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['delete']['#limit_validation_errors'] = [];
}

```

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


title: Override form.html.twig into module

text:
# Question
Title: Override form.html.twig into module
i need to override a form.html.twig in my custom module.

i used hook\_theme\_suggestions\_alter in my .theme file to add new suggestions.

```
function MY_THEME_theme_suggestions_alter(array &$suggestions, array $variables){

if (isset($variables['element']) && isset($variables['element']['#type']) && $variables['element']['#type'] == 'form') {
    $original_theme_hook = $variables['theme_hook_original'];
    $suggestions[] = $original_theme_hook . '__' . str_replace('-', '_', $variables['element']['#id']);
}

return $suggestions;
}

```

the debug show me this suggestions

```
THEME HOOK: 'form' -->
<!-- FILE NAME SUGGESTIONS: * form--pom-mapping-setting-form.html.twig x form.html.twig -->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/form.html.twig' -->

```

if i put form--pom-mapping-setting-form.html.twig in my\_theme/templates/ folder works.

if i put form--pom-mapping-setting-form.html.twig in my\_module/templates folder doesn't works

I don't understand why :/

why drupal doesn't read templates in module folder?

thanks

# Answer
> 0 votes
You need to alter the Theme registry and set the path of the hook suggestion "form" to your\_module/template path as bellow:

```
/**
 * Implements hook_theme_registry_alter().
 */
function My_Module_theme_registry_alter(&$theme_registry) {
  // You can add some conditions here in case you want
  // to override the form template only for some reasons.
  $theme_registry['form']['path'] = drupal_get_path('module', 'My_Module') . '/templates';
}

```

And the structure of your module should be:

```
-- My_Module
  +-- templates
     +-- form--pom-mapping-setting-form.html.twig

```

---
Tags: 8, theming
---


# Question
Title: How do I add a node field widget to a custom form?
I added a number of fields to a node content type in Drupal 8. I want to create a custom form and add the field widget form (the one used during node creation) to this form. How can I achieve this?

# Answer
Answering my own question, I ended up using the following:

```
<?php
//Create an empty representative entity
$node = \Drupal::service('entity_type.manager')->getStorage('node')->create(array(
                'type' => 'article'
            )
        );

//Get the EntityFormDisplay (i.e. the default Form Display) of this content type
$entity_form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')
                                        ->load('node.article.default');

$form['#parents'] = []; // Mandatory, otherwise the widget class throws an error

//Get the body field widget and add it to the form
if ($widget = $entity_form_display->getRenderer('body')) { //Returns the widget class
  $items = $node->get('body'); //Returns the FieldItemsList interface
  $items->filterEmptyItems();
  $form['body'] = $widget->form($items, $form, $form_state); //Builds the widget form and attach it to your form
  $form['body']['#access'] = $items->access('edit');
}

```

see EntityFormDisplay::buildForm
> 6 votes

# Answer
Also you can use this code

```
$entity = \Drupal::entityManager()->getStorage('node')->create([
        'type' => 'article'
      ]);
$form_state->set('node', $entity );
$form_display = EntityFormDisplay::collectRenderDisplay($entity, 'default');
$form_display->buildForm($entity, $form, $form_state);

```

I found this solution here
> 3 votes

---
Tags: 8, entities
---