title: What are cloned sites in Drupal 8?

text:
# Question
Title: What are cloned sites in Drupal 8?
When trying to export my site configurations from one Drupal 8 site to other I keep getting the following error

> The staged configuration cannot be imported, because it originates from a different site than this site. You can only synchronize configuration between cloned instances of this site.

So in this context what are cloned sites? How can I override this error to import the configurations?

# Answer
> 13 votes
Cloned site means that you copied the database instead of installing twice from scratch.

Drupal identifies two different sites as cloned sites by checking their `uuid`. If the uuids match, then it will assume that the sites are cloned instances.

Faulty configuration imports can lead to broken sites which we may not be able to restore. Hence to avoid this situation as discussed on https://www.drupal.org/node/2133325 a safety mechanism was introduced. And that mechanism was having a `uuid` for each Drupal site.

So if you know what you are doing and you are sure that you need to import the configurations, you can use the `drush cget system.site` command on source site and you can use `drush cedit system.site` on target website to change the uuid to that from the source.

# Answer
> 0 votes
This can happen in cloned sites also when I add to .gitignore and remove from git cache the exported /config/sync/system.site.yml.

---
Tags: 8, configuration
---


title: Module accidentally removed

text:
# Question
Title: Module accidentally removed
Somehow, I accidentally deleted the *shield* folder after installing the Shield module, and now I can't disable it. I can't work on my site.

Can anyone please tell me how to disable the module?

# Answer
> 0 votes
Just put the folder you deleted back where it was.

Then you'll be able to uninstall the module as normal.

---
Tags: 8
---


title: How to validate a config entity form?

text:
# Question
Title: How to validate a config entity form?
I have a config entity with a form which extends `Drupal\Core\Entity\EntityForm`, which has a public `form()` and a public `save()` methods. They both work fine and dandy. I want to validate some information before saving the form. As far as I can tell there's a `validateForm()` method already built in via the class it extends.

I can't seem to find much information on how to do that. I've tried the obvious, simply setting a `return false` in the `validateForm` method but it doesn't seem to be called at all.

I don't have much experience with Drupal in general so I'm obviously doing something wrong.

If anybody could point me in the right direction here, I'd be grateful.

I'd also like to keep the field values in case of an error. I can only assume that that happens by default, but then again I may be wrong.

# Answer
> 1 votes
You can override the `validateForm` method in your own form class. Just declare a method like so:

```
public function validateForm(array &$form, FormStateInterface $form_state) {
  // Your custom validation code.
}

```

Since the Drupal\Core\Form\FormBase (parent of Drupal\Core\Entity\EntityForm) class has no validation, just a blank method, there is no need to call the parent method from your own class.

---
Tags: forms
---


# Question
Title: How to programmatically set the color scheme for a theme?
Is there a way to **programmatically** change the color scheme, set by the color module, for a certain theme in Drupal 6 (in PHP or using drush)? For example, I can change Garland's color scheme from the UI:

but I want to do it programatically.

# Answer
No - this is not possible in 6.x due to how color is intended to work. Its meant to be a simple way to change a very basic theme, not for advanced users. In 6.x, when you change your color settings, it is doing the following:

* Replaces hexidecimal colour values in CSS files
* Creates sliced images with the new colours for use as CSS background images
* Copies unchanged images without alterations

This creates a dump of 'color files' that looks like this in your files directory (for the Garland theme)

```
bg-bar-white.png
bg-bar.png
bg-content-left.png
bg-content-right.png
...
style.css

```

It also creates a random number for the folder each time, so the folder is getting deleted and recreated each time you save the changes.

All of this is to make it easier for novice users to change their colors, with I assume the understanding that if users could configure their own CSS and theme in code, they wouldn't be using the color module to begin with. This approach is also confirmed here on D.O by Jeff Burnz

> Currently there is no way in Drupal core to export your custom color scheme to file, i.e. no way to capture the configuration

Conversely, there is no way to import an existing dump of colors files into your site.
> 1 votes

# Answer
As per @clive's suggestion, looking at what `color_sheme_form_submit()` is doing:

\_submit() will delete previous files listed in variable `color_garland_files`. But renaming the public files folder `color/garland-dda79d31` to `color/garland-RED` will give you a *permanent* copy of that folder full of garland color files.

(Let color module generate that folder for you -- make a permanent copy)

Inside a "good hook" (I use \_page\_alter()) ... you can dynamically, temporarily over-write the `$conf` array (full of `variable_get()` variables for this current page call:

```
function modulename_ctools_render_alter() {
 // look at all the variables
 global $conf;
 kpr($conf);
 // look at the one we need
 $RED = variable_get('color_garland_stylesheets');
 // this, we will re-use:
 echo var_export($RED);
}

```

... will show you a PHP-formed array of said variable. Over-write it.

```
// this is how they look
#$STYLES = variable_get('color_garland_stylesheets');
#echo var_export($STYLES);
// over-write
$conf['color_garland_stylesheets'] = array(
    0 => 'public://color/garland-RED/style.css',
    1 => 'public://color/garland-RED/style-rtl.css',
  );

```

That was sufficient for me. All files in that folder can keep their filenames. All .css stays and works.
> 0 votes

---
Tags: theming, 6
---


# Question
Title: How to get block instance id in block plugin?
I have block plugin that renders lazy builder placeholder. In my lazy builder I need to get to the block's settings so I wanted to set the block id as lazy builder argument but it turned out the block instance info is not available to the block plugin itself.

Is there some proper Drupal way how to get to this information beside serializing the configuration as lazy builder argument or storing the configuration elsewhere?

# Answer
No there isn't.

Block plugins can also be used in e.g. page manager and then there's no block entity, it stores configurations for multiple block plugins in a single config entity.

So you shouldn't be relying on the existence of that and instead pass in the relevant configuration to your lazy builder.
> 1 votes

# Answer
See https://drupal.stackexchange.com/a/239317/11500, I store the id as a block entity configuration value. That means you can't use those blocks in page manager (which is acceptable for me).
> 0 votes

---
Tags: blocks, 8, theming, plugins
---


# Question
Title: How to configure ckeditor for different toolbars?
In D7 I would like to use ckeditor with a specific profile for a user role. The user is only allowed to use bulleted listed. How to do this?

I did the following:

* Configured in drupal a ckeditor profile call "builder"
* For a role say"Client" I added a text format say "Bullitsformat"
* for a field in a content type "testfield" I configures user can choose own filter.

If I test the edit form no toolbar is displayed when user selects Bullitsformat.

What to do?

# Answer
Found the solution to first add the bullitsformat and then edit the profile, so this profile is shown in the profile of the ckeditor.
> 0 votes

---
Tags: wysiwyg
---


title: How to add <div> around two blocks?

text:
# Question
Title: How to add <div> around two blocks?
In D7 I have a search view but would like to change some layout of it.

My current HTML situation is:

```
<div id="block-block-12"  ..... </div>
<div id="block-block-13"  ..... </div>
<div id="block-block-14"  ..... </div>

```

In the current layout:

```
 --------------------------
|            |            |
|     B12    |     B13    |
|            |     B14    |         |
---------------------------

```

I would like to change this into

```
<div class ='xxtr'>
 <div id="block-block-12"  ..... </div>
 <div id="block-block-13"  ..... </div>
 <div id="block-block-14"  ..... </div>
</div>

```

The reason for this is that I would like to have a 100% background color styling with the help of class xxtr.

I set the width of all block at 33.3% but then the display is:

```
 ------------------------------------
|            |            |         |
|     B12    |     B13    |   B14   |
|            |            |         |
-------------------------------------

```

While the result should be with all the same background color:

```
 ------------------------------------
|            |            |         |
|     B12    |     B13    |   empty |
|            |     B14    |         |
-------------------------------------

```

I add a custom tpl for this query but do not understand how to get that extra div around these blocks.

The tpl file.

```
<?php

?>
<div class="<?php print $classes; ?> view--page">
    <div class="view-content-wrapper">

        <?php print render($title_prefix); ?>
        <?php if ($title): ?>
            <?php print $title; ?>
        <?php endif; ?>
        <?php print render($title_suffix); ?>
        <?php if ($header): ?>
            <div class="view-header">
                <?php print $header; ?>
            </div>
        <?php endif; ?>

        <?php if ($exposed): ?>
            <div class="view-filters">
                <?php print $exposed; ?>
            </div>
        <?php endif; ?>

        <?php if ($attachment_before): ?>
            <div class="attachment attachment-before">
                <?php print $attachment_before; ?>
            </div>
        <?php endif; ?>

        <?php if ($pager): ?>
            <?php print $pager; ?>
        <?php endif; ?>

        <?php if ($rows): ?>
            <div class="view-content">
                <?php print $rows; ?>
            </div>
        <?php elseif ($empty): ?>
            <div class="view-empty">
                <?php print $empty; ?>
            </div>
        <?php endif; ?>

        <?php if ($pager): ?>
            <?php print $pager; ?>
        <?php endif; ?>

        <?php if ($attachment_after): ?>
            <div class="attachment attachment-after">
                <?php print $attachment_after; ?>
            </div>
        <?php endif; ?>

        <?php if ($more): ?>
            <?php print $more; ?>
        <?php endif; ?>

        <?php if ($footer): ?>
            <div class="view-footer">
                <?php print $footer; ?>
            </div>
        <?php endif; ?>

        <?php if ($feed_icon): ?>
            <div class="feed-icon">
                <?php print $feed_icon; ?>
            </div>
        <?php endif; ?>
    </div>

</div><?php /* class view */ ?>

```

Any suggestion ?

# Answer
I solved this by adding the view of the second box in the footer of the first box and add the php code of the third box in the footer of the second view. This way only one box is shown and with the help of the blok\_wrapper css can be used to layout this template.
> 0 votes

---
Tags: 7
---


title: Rules schedule force actions

text:
# Question
Title: Rules schedule force actions
In Drupal I've scheduled, on the future, some e-mail, using rules schedule module. Now I want to force the delivery, before the scheduled time, to check the text of e-mail. Is this is possible?

# Answer
> 1 votes
Yes, you can do it by clicking the execute link in your components tab.

OR, you can click the schedule link and schedule something to run 1 min from now. Just remember that your scheduled action will only run after cron runs. So if you have set cron to run once a day or every 1 hour, it won't happen until then. So will have to manually run cron, by clicking the run cron button to see if it gets delivered after 1 min from now.

# Answer
> 0 votes
There is no out-of-the-box solution to force the execution of an already scheduled rule before the "scheduled date". All you can do for such scheduled rules is to "delete" such rules from the list of schedule rules (via `admin/config/workflow/rules/schedule`), so that they don't actually get executed.

There are indeed the "operations" like *execute* and *schedule*, as already mentioned in the previous answer, but using those options you actually trigger a new instance of such rule to be executed (they do not actually release an already scheduled rule).

They only way around this, and to do something similar to what you're asking for, is to temporary adapt (or clone) the rule you already have in place, and schedule the rule to be executed after (eg) a few minutes already. But in this case also, you're not triggering the execution of an already scheduled rule: you're only scheduling another rule after (eg) just a few seconds or minutes after such schedule rule gets scheduled.

---
Tags: 7, rules
---


title: Custom views filter

text:
# Question
Title: Custom views filter
In Drupal 8, I have a view that gathers all the nodes built in my `Gallery Hours` content type. The content type has a field called `View Order` that I use for another view that displays the list of gallery hours in that order. What I am trying to do is to build another view that checks for the gallery hours for today. For instance, today is Tuesday, so I would like the view to display the gallery hours for Tuesday.

My thought was to create a custom filter option that compares the numeric value of a field, such as my View Order field which is set to 1=Sunday, 2=Monday, etc., with `DATE_FORMAT(NOW(),"%N")`. This is my first foray into custom Drupal module development and am spinning my wheels. Any and all suggestions welcome.

The one thing I think I have correct are my yaml files.

todaysdate.info.yml

```
name: Todays Date Filter module
description: 'Creates a filter to search by todays day of the week.'
type: module
core: 8.x
package: SMA Modules

```

todaysdate.routing.yml

```
todaysdate:
  defaults:
    _controller: Drupal\todaysdate\Plugin\Filter\todays_date_handler_filter_numeric::operators
  requirements:
    _permission: 'access content'

```

Where I am really confused is where to go from there. I am trying to piece together a class that extends the `NumericFilter` and add a new operator that then add to the WHERE expression with the dateformat I'm looking for.

Anyhoo, this is my attempt at creating the filter. I am not getting any errors, but I am also not getting the new operator on my numeric fields in my view.

todays\_date\_handler\_filter\_numeric.php

```
<?php

/**
 * @file
 * Provides views filter option for the Todays Date module.
 */

namespace Drupal\todaysdate\Plugin\Filter;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\NumericFilter;
use Drupal\views\Plugin\views\filter\InOperator;

class todays_date_handler_filter_numeric extends NumericFilter {
  function operators(){
    $operators = parent::operators();
    $operators += array(
      'todays date' => array(
        'title' => $this->t('Is this day of the week'),
        'short' => $this->t('todays date'),
        'method' => 'op_day_of_week',
        'values' => 0,
      )
    );
    return $operators;

    function op_day_of_week($field) {
      $this->query->addWhereExpression($this->options['group'], 'DATE_FORMAT(NOW(),"%N")');
    }
  }
}

```

Thank you all in advance for any assistance you can provide. I can't tell you how many times StackOverflow has helped me in the past.

# Answer
You should register your custom filter in both `mymodule.views.inc` and in the class annotations.

**\Drupal\mymodule\Plugin\views\filter\MyCustomNumericFilter**

```
<?php

namespace Drupal\mymodule\Plugin\views\filter;

use Drupal\views\Plugin\views\filter\NumericFilter;

/**
 * My custom numeric filter.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("my_custom_numeric_filter")
 */
class MyCustomNumericFilter extends NumericFilter {

  public function query() {
    $this->query->addWhereExpression($this->options['group'], 'DATE_FORMAT(NOW(),"%N")');
  }

  protected function operators() {
    $operators = parent::operators();
    $operators += array(
      'todays date' => array(
        'title' => $this->t('Is this day of the week'),
        'short' => $this->t('todays date'),
        'method' => 'op_day_of_week',
        'values' => 0,
      )
    );
    return $operators;
  }

}

```

**mymodule.views.inc (placed in custom module root)**

```
function mymodule_views_data() {
  $data = [];
  $data['views']['my_custom_numeric_filter'] = [
    'title' => t('My custom numeric filter'),
    'filter' => [
      'title' => t('My custom numeric filter'),
      'group' => 'Custom',
      'help' => t('Provides custom numeric filter.'),
      'id' => 'my_custom_numeric_filter'
    ],
  ];
  return $data;
}

```

I moved your custom query expression (without checking) to the `query()` method since Views calls this method on filtering.

Let me know if this works for you.
> 4 votes

---
Tags: 8, views
---


title: How to show a custom form in a block?

text:
# Question
Title: How to show a custom form in a block?
I have a custom form which currently shows on a page. The form is submitted via ajax and the view embedded is also updated via ajax. I do not want to show the form on a page. Instead I want to show it in a block. I should be able to put the block anywhere on the website.

This is my form

```
/**
 * Provide a form.
 */
function MYMODULE_form($form, &$form_state) {

  $form['wrapper'] = [
    '#type'       => 'container',
    '#attributes' => [
      'id' => 'mywrapper',
    ],
  ];

  $form['wrapper']['node_form'] = [
    '#type'  => 'fieldset',
    '#title' => t('Add article'),
  ];

  $form['wrapper']['node_form']['node_title'] = [
    '#type'     => 'textfield',
    '#title'    => t('Article title'),
    '#required' => TRUE,
  ];

  $form['wrapper']['submit'] = [
    '#type'   => 'submit',
    '#value'  => t('Save'),
    '#submit' => ['MYMODULE_form_submit'],
    '#ajax'   => [
      'callback' => 'MYMODULE_MYCALLBACK',
      'wrapper'  => 'mywrapper',
    ],
  ];

  $form['wrapper']['view_display'] = [
    // view machine name && display/block name
    '#markup' => views_embed_view('nodes', 'block'),
  ];

  return $form;
}

/**
 * Do some validation.
 */
function MYMODULE_form_validate($form, &$form_state) {
  // Better do some validation.
  // Here or via #element_validate.
  // @see https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#element_validate
}

/**
 * Form submit. Node creation.
 */
function MYMODULE_form_submit($form, &$form_state) {

  global $user;
  $node = new stdClass();

  $node->type     = 'article';
  $node->title    = $form_state['values']['node_title'];
  $node->language = LANGUAGE_NONE;
  $node->uid      = $user->uid;

  node_object_prepare($node);
  node_save($node);

  // Empty out title field on rebuild.
  $form_state['input']['node_title'] = '';

  // Rebuild form.
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback to return the whole wrapper.
 */
function MYMODULE_MYCALLBACK($form, &$form_state) {

  return $form['wrapper'];
}

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items['example/form'] = [
    'title'            => 'Example Form',
    'description'      => 'A form to mess around with.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['MYMODULE_form'],
    'access arguments' => ['create article content'],
  ];

  return $items;
}

```

# Answer
> 1 votes
Create a block with hook\_block\_info and embed your custom form within a block using hook\_block\_view. Assuming module's name to be example, this module creates a "My block" with the form.

FYI, in the below code `drupal_render(drupal_get_form('MYMODULE_form'));` is the one rendering your form in the block where **MYMODULE\_form is the form ID**.

```
 <?php
    /**
     * Implements hook_block_info().
     */
    function example_block_info() {
      $blocks = array();

      $blocks['MYBLOCK'] = array(
        'info' => t('My block'),
        'cache' => DRUPAL_NO_CACHE,
      );
      return $blocks;
    }

    /**
     * Implements hook_block_view().
     */
    function example_block_view($delta = '') {
      $block = array();

      switch ($delta) {
        case 'MYBLOCK':
          $block['subject'] = t('My block title');
          $block['content'] = drupal_render(drupal_get_form('MYMODULE_form'));
      }
      return $block;
    }

```

---
Tags: 7, views, forms, blocks, ajax
---


# Question
Title: Redirect to a view with contextual filters
I would like to redirect the user to a view with some contextual filters on the submit of a custom form.

For now I use this :

```
$form_state->setRedirect('view.search.page_1', ['myvalue' => $value]);

```

But it add "myvalue" like this : `/search?myvalue=$value`

and what I want is : `/search/$value`

Thanks

# Answer
> 7 votes
You have to use the route parameter names defined in the route.

You can check the route definition of this view display with help of the Devel module by visiting:

```
www.example.com/devel/routes

```

When you define contextual filters the route parameter names are usually `{arg_0}`, `{arg_1}` ...

So this could work:

```
$form_state->setRedirect('view.search.page_1', ['arg_0' => $value]);

```

# Answer
> 0 votes
I guess it is not directly possible, you could however solve it with a small workaround:

```
$uri = \Drupal\Core\Url::fromUri('base:/your-views-path/' . $value, ['absolute' => TRUE]);
$form_state->setRedirectUrl($uri);

```

Edit: @4k4 has the better solution.

---
Tags: views, 8, redirection
---


title: Edit node as text link in Twig

text:
# Question
Title: Edit node as text link in Twig
How to write the same code in Twig?

```
<?php print l(t('Edit this node'), 'node/' . $entity->nid . '/edit'); ?>

```

# Answer
See this example from Functions - In Twig Templates:

```
{# Link to node page. #}
<a href="{{ path('entity.node.canonical', {'node': node.id}) }}">{{ 'View node page'|t }}</a>

```

in which you need to use the route to edit the node: `entity.node.edit_form`
> 4 votes

---
Tags: theming, 8
---


# Question
Title: How to place size of file in the node in the title?
I want create page for issues of newspaper. Title of the issue page must contain the issue number, date of publishing and size of newspaper file in MB.

I implemented number and date in title with Automatic Entity Labels and Token modules. But how I can place in title size of the uploaded file?

I tried to use custom module:

```
/**
* Implements hook_token_info().
*/
function mytokens_token_info() {
$node_tokens['field_file']['size'] = array(
  'name' => t('File size'),
  'description' => t('File size'),
);
$node_tokens['field_file']['size']['mbytes'] = array(
  'name' => t('In MB'),
  'description' => t('File size in MB'),
);
return array(
  'tokens' => array(
  'node' => $node_tokens,
  ),
);
}

/**
 * Implements hook_tokens().
 */
function mytokens_tokens($type, $tokens, array $data = array(), array $options = array()) {
$replacements = array();

if ($type == 'node' && !empty($data['node'])) {
$node = $data['node'];

foreach ($tokens as $name => $original) {
  if ($name == 'mbytes') {
    $replacements[$original] = $node->field_file['und'][0]['filesize']/(1024*1024);
  }
}
}

  return $replacements;
}

```

But my tokens don't shows in the token tree and nothing replacements occur.

# Answer
Install Token and you can use `[file:size]` in your title to fetch file size. Here is the list of all file tokens you can choose from.
> 0 votes

---
Tags: 7, tokens, nodes
---


# Question
Title: hook_form_FORM_ID_alter being called twice (even before submit)
I want to make some changes to the "Content" page. The ID of the form is `views_form_content_page_1`, so I made a quick test (after drush cr of course):

```
function my_module_form_views_form_content_page_1_alter(&$form, FormStateInterface $form_state) {
  kint($form);
}

```

When I go to the page, the $form is being printed twice by the devel. I checked, all of the array items are the same. If I do `kint('cat');`, then it will print cat two times.

Why is this happening? Of course I could make it work, that my action will run only once (eventho drupal tries to run it twice) but I would like to rather solve this one, and understand if it's a bug, and why it is happening.

# Answer
It has to do with the fact that Drupal redirects after the form submit. So after a form submit you will make 2 requests: the form submit and the redirect. Hence the 2 messages in your `hook_form_alter()`.

You can disable this redirect by calling `$form_state->disableRedirect()` in your form submit handler. By disabling the redirect the form values will be preserved in the form. The redirect is in place to 'clean' the form inputs after submission.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: User's to edit roles and permissions for any user less privileged
Our website needs to allow staff (staff role) and editors (editor role) to be able to edit the accounts and roles of authenticated users and all other users with roles less privileged than their own role, without being able to edit the accounts and privileges of users of a higher privilege level.

Here is an example of hierarchy of our user roles:

* admin (super-user, developer only)
* editor (organization's admin and non-development high-level user, many privs)
* staff (organization's staff users, some special privs)
* member (user with special access privs)
* authenticated user (regular user)

Currently, if I allow users to edit user accounts and assign roles, they are able to not only assign themselves to top-level administrator account, but also de-assign the administrators and change their passwords, etc.

This post asks a similar/related question which is slightly different but also does not have an answer. I assumed the Drupal Core had a built-in functionality that allows for this by considering the order of roles, so I am wondering if I did something wrong.

# Answer
Drupal core doesn't have any out of the box functionality to manage roles and permissions in a hierarchical manner.

However, there are a couple modules that provide extra permissions which might be helpful in what your trying to achieve.

1. Role Delegation gives you a new set of permissions which are very fine-grained. From the module page-

> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
2. Administer Users by Role. From the module page-

> This module allows site builders to set up fine-grained permissions for allowing "sub-admin" users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

From the readme of the module-

> NEW PERMISSIONS
>
> Access the users overview page See the list of users at admin/people. Only users that can be edited are shown.
>
> Create new users Create users, at admin/people/create.
>
> Edit users with no custom roles Allows editing of any authenticated user that has no custom roles set.
>
> Edit users with role XXX Allows editing of any authenticated user with the specified role. To edit a user with multiple roles, the sub-admin must have permission to edit ALL of those roles. ("Edit users with no custom roles" is NOT needed.)
>
> The permission for cancel work exactly the same as those for edit.

(1) should give what you need but still including (2) which might have a new permission that you wouldn't want to miss out on.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Can't uninstall module because of checkbox field
I've a custom module that alters the MenuLinkContent entity by adding a field. My field is defined as follow.

```
/**
 * Implements hook_entity_base_field_info().
 */
function svg_icon_menu_link_entity_base_field_info(EntityTypeInterface $entity_type) {

  $fields = array();

  if ( $entity_type->get('id') !== 'menu_link_content' ) {
    return $fields;
  }

  $fields['hide_label'] = BaseFieldDefinition::create('boolean')
    ->setLabel(t('Hide label'))
    ->setDescription(t('Display only the icon.'))
    ->setDisplayOptions('form', array(
      'type' => 'checkbox',
      'weight' => 0
    ));

  return $fields;
}

```

By default the checkbox is saved in the DB with a value of `0` if unchecked, and with a value of `1` if checked. To Drupal there's always a value for that field, that's why it prevent me to uninstall the module with the message `There is data for the field hide_label on entity type Custom menu link`.

How should I manage this situation? Should I save a value of `NULL` if unchecked in some way, or should I have to do something when uninstalling my custom module?

# Answer
> 1 votes
You could create a custom form and set all the field values to NULL in the submit handler.

For example:

```
<?php

namespace Drupal\mymodule\Form;

use Drupal;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

class TestForm extends FormBase {

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

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [
      'test' => [
        '#type' => 'submit',
        '#value' => 'Clear field values',
      ],
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $query = Drupal::entityQuery('node');
    $query->condition('type', 'menu_link_content');
    $result = $query->execute();

    $nodes = Drupal::entityTypeManager()->getStorage('node')->loadMultiple($result);

    foreach ($nodes as $node) {
      if ($node instanceof Node) {
        $node->set('your_field', NULL);
        $node->save();
      }
    }
  }

}

```

---
Tags: 8, entities, installation
---


# Question
Title: hook_form_alter or overriding the routing and UserLoginForm class
I am trying to add another mechanism for login into Drupal (adding an SSO function which would validate based on some criteria that a third party system will provide to Drupal).

I am trying to decide whether using hook\_form\_alter() (like I would in Drupal 7) is the more "Drupal 8" way or if altering the routing (shown below) so that it goes towards my custom login class that extends UserLoginForm would be a better option. I am guessing that the second approach is considered the "proper" way to do things.

Routing:

```
user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

```

Class I would be extending in my own custom class:

```
class UserLoginForm extends FormBase {

}

```

So my real question is this - if I need to override the login mechanism (including both the SSO functionality as well as standard Drupal authentication if the SSO login fails), what is the "proper" method to do this?

# Answer
> 0 votes
I would definitely go for the second option. In my opinion the `form_alter` hooks are reserved for 'minor' changes to a form. I always use custom forms as much as possible (extending the original form).

---
Tags: forms, 8, users, routes
---


title: Can't access my administration panel

text:
# Question
Title: Can't access my administration panel
I was playing around with my website, which was built by a developer long time ago, and I remove the permission for the "administrator" role, and now as a "superadmin" I can't access the Drupal panel of my own site.

Can someone help me figure out how can I access the control panel?

Thank you!

# Answer
> 0 votes
Use Drush commands instead like

Drush urol command

Or update existing role with the proper permission to access your backend admin

Drush add permistion command

---
Tags: users
---


# Question
Title: Let Users Make a Feedback before Download File
I want to let users fill a form feedback about the node before downloading the file that attached to that node! like in Dialog or Popup, which modules should I use here?

# Answer
> 1 votes
Depending on your Drupal coding skills I would use a custom form with a modal using the OpenModalDialogCommand. In the modal you can attach a form with a textarea and a submit button. On clicking the submit button the feedback from the textarea gets stored, the modal gets closed (CloseModalDialogCommand) and a BinaryFileResponse gets returned.

I don't know of any contributed modules that provide this functionality.

P.S. I am assuming that you are using Drupal 8 here.

---
Tags: views, nodes, webforms
---


# Question
Title: Drupal 8 Permission to see Structure > Menu
Drupal 8. I want a user with a certain role to be able to see and administer menu items /admin/structure/menu/manage/main

On the permissions page /admin/people/permissions I have 'Administer menus and menu items' checked. This worked in Drupal 7.

I can get to the /admin/structure/menu/manage/main page if I manually type in in the browser.

But the 'Structure' button/link does not appear in the toolbar for that role. It shows up for me when am logged in as User/1

How do I get the 'Structure' in the Toolbar? Am I choosing the wrong permission? Am I missing one?

# Answer
You would have to grant the following permissions to the role:

#### Required

* *Use the toolbar*
* *Administer menus and menu items*
* *Use the administration pages and help*

#### Optional

* *View the administration theme*
> 19 votes

---
Tags: users, navigation
---


# Question
Title: How to conditionally hide a space in a rules action if the first token is empty?
I am using the tokens module to print personalized email notifications. Sometimes a webform component is not filled out and the email notification leaves an empty space before the token. I am using the Rules module to send a mail.

E.g.

```
[data:title-value-raw] [data:name-value-raw]

```

**Default output**

```
Mr. Example

```

**Expected result**

```
Example

```

**Actual result**

```
 Example

```

How can I hide the space if the first token is empty?

Drupal rule to send message.

```
{ "rules_mail_confirmation" : {
"LABEL" : "Mail Confirmation",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "webform_rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "contact" : "contact" } } } },
  { "node_is_webform" : { "node" : [ "node" ] } }
],
"DO" : [
  { "mail" : {
      "to" : "[data:email-value]",
      "subject" : "Confirmation",
      "message" : "[data:title-value-raw] [data:name-value-raw],\r\n\r\n",
      "from" : "[site:mail]"
    }
  }
]

```

} }

# Answer
Many thanks to your replies. Your answer has been really useful to me. I didn't expect that hiding a space with a simple rules action requires so much effort. I've ended up using 2 rules (yeah, not perfect) with a custom php code that checks for value *none*. Now, instead of a text field I am using `select options` as a webform component. If you find a more elegant solution, feel free to share it.

Here's what works for me.

1. Within the Webform select options I've added a key-value pair `none|`
2. Create a new rules condition using **Execute custom PHP code** and add the following code as value:

---

```
if ($data['components']['title']['value'][0]=='none') {
return TRUE;
} else {
return FALSE;
}

```

**Rule 1: Without title**

```
{ "rules_mail_confirmation_without_title" : {
    "LABEL" : "Mail Confirmation without Title",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules", "php" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "contact" : "contact" } } } },
      { "node_is_webform" : { "node" : [ "node" ] } },
      { "php_eval" : { "  if/else code from above " } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[data:email-value]",
          "subject" : "Confirmation",
          "message" : "Hello [data:name-value-raw],\r\n\r\n",
          "from" : "[site:mail]"
        }
      }
    ]
  }
}

```

**Rule 2: With title**

```
{ "rules_mail_confirmation_with_title" : {
    "LABEL" : "Mail Confirmation with Title",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules", "php" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "contact" : "contact" } } } },
      { "node_is_webform" : { "node" : [ "node" ] } },
      { "NOT php_eval" : { " if/else code from above " } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[data:email-value]",
          "subject" : "Confirmation",
          "message" : "Hello [data:title-value-html] [data:name-value-raw],\r\n\r\n",
          "from" : "[site:mail]"
        }
      }
    ]
  }
}

```
> 0 votes

# Answer
If I was to implement this, I'd create a special (tiny) Rules Component as a kind of helper function, and use that in your existing rule also. The *clue* of that Rules Component is the (not often used) "Provided" facility for one of its parameters. More details below ...

### Part 1: Create a Rules Component

Create a new Rules Component that looks like so (in Rules Export format):

```
{ "rules_create_email_body_prefix" : {
    "LABEL" : "Create eMail body prefix",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "title_value" : { "label" : "Title value", "type" : "text" },
      "prefix_value" : { "label" : "Prefix value", "type" : "text", "parameter" : false }
    },
    "IF" : [ { "NOT data_is_empty" : { "data" : [ "title-value" ] } } ],
    "DO" : [
      { "data_set" : { "data" : [ "prefix-value" ], "value" : "[title-value:value] " } }
    ],
    "PROVIDES VARIABLES" : [ "prefix_value" ]
  }
}

```

Some details about the above Rules Component:

* It uses 2 parameters:
    + it ***accepts*** `title_value` as an input parameter (Usage = Parameter).
    + it ***provides*** `prefix_value` as output of it (Usage = Provided).
* The logic of this Rules Component is like so:
    + Rules Condition: verify that the value of `title_value` is NOT empty.
    + Rules Action: set the value of `prefix_value` equal to the value provided via `title_value`, and follow it by a space (note!).

### Part 2: Integrate the Rules Component in your existing rule

Here is an updated version of your rule (also in rules export format).

```
{ "rules_mail_confirmation_with_optional_prefix" : {
    "LABEL" : "Mail Confirmation with optional prefix",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "contact" : "contact" } } } },
      { "node_is_webform" : { "node" : [ "node" ] } }
    ],
    "DO" : [
      { "component_rules_create_email_body_prefix" : {
          "USING" : { "title_value" : "[data:title-value-raw]" },
          "PROVIDE" : { "prefix_value" : { "prefix_value" : "Prefix value" } }
        }
      },
      { "mail" : {
          "to" : "[data:email-value]",
          "subject" : "Confirmation",
          "message" : "[prefix-value][data:name-value-raw],\r\n\r\n",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

These are the changes I applied (as compared to your rule):

* Rename the rule (to not override your own rule).
* Add a Rules Action (as the first one) to invoke the newly created Rules Component (whereas the value `[data:title-value-raw]` is passed to the `title_value` parameter).
* Adapt the message body of the eMail, to now use the `prefix_value` as provided by the Rules Component. To be complete: if the Rules Condition in the Rules Component is NOT satisfied, the value of `prefix_value` is empty, otherwise the Rules Component will assign a value is equal to `title_value` followed by a space.

**Notes**:

The exported rule as included in the 1st revision of your question, contains some errors/challenges, i.e:

1. It contains a syntax error, the comma at the end of your 2nd Rules Condition should not be there (only after I removed that comma I was able to import your rule ...).
2. Something doesn't seem right in the `[data:[data:title-value-raw]]` token you included, pretty sure it should be `[data:title-value-raw]`, as confirmed somehow also in the edit you applied in revision 6 of your question.
3. IMO there is no need for "PHP" (as shown within "REQUIRES" in your exported rule ...), as confirmed somehow also in the edit you applied in revision 6 of your question.
> 1 votes

# Answer
The action you are looking for is called trimming; stripping whitespace from the beginning (and end) of a string.

However to do that, we first need to merge your two fields into one. Before the mail add the action of `Add a variable`, give it the value `[data:title-value-raw] [data:name-value-raw]` (No data selector, just direct input mode). Also give it a sensible name for later.

Now we have one token that contains `Mr. Example` or `[whitespace]Example`. By removing the whitespace from this one token we can get the desired result. (Removing the white space from individual tokens would not have made any difference.) Rules by default does not offer a Trim action , but Rules Data Transforms does. Add the trim action for your previously created field and use the trimmed output in your mail.
> 0 votes

# Answer
use rules conditional module, first action: add a conditional, add an IF, "data value is empty", field:\[data:\[data:title-value-raw\], here you have only content with token empty, avoid in message token value, add an action:

```
"DO" : [
{ "mail" : {
  "to" : "[data:email-value]",
  "subject" : "Confirmation",
  "message" : "[data:name-value-raw],\r\n\r\n",
  "from" : "[site:mail]"
}
}
]

```

add an ELSE "under conditional", here you are with content that token value is not empty, so, include token value in message, add an action under ELSE:

```
"DO" : [
{ "mail" : {
  "to" : "[data:email-value]",
  "subject" : "Confirmation",
  "message" : "[data:[data:title-value-raw] [data:name-value-raw],\r\n\r\n",
  "from" : "[site:mail]"
}
}
]

```

Done, i hope it helps.

EDIT: if do not want to install another module, then make two rules, on first rule, add a condition: "data value is empty", field:\[data:\[data:title-value-raw\], set message avoiding in message empty token value. Second rule: "data value is empty", NEGATE, field:\[data:\[data:title-value-raw\], the complete your message including token, this time token wont be empty.
> 0 votes

---
Tags: 7, rules, tokens
---


# Question
Title: How to define custom content entity one to many relationship?
I have two custom entities; `A`, `B`.

In terms of database relationships, I want `A` to have many `B`.

I find I am able to define a `reference_entity` field in the entity's `baseFieldDefinition()`. However, because this just defines a single column in the database my relationships are back to front:

I can give `B` a reference to `A` and then use `$B->getEntity()->referencedEntities()` to get a `B`'s associated `A`, but I can't do it the other way round because there's just a single id for each row.

Is there a correct way to query or set up these kinds of relationships 'out-the-box' or is a better solution to add my own method to the `A` entity `getReferencedBs()` and query the `B` table for references to `A`.

Many thanks

# Answer
> 1 votes
Sounds like you need to add setCardinality(-1) to your B reference field definition in your A entity. This will change the B reference field to support an unlimited number of references instead of 1, the default cardinality.

---
Tags: 8, entities, database
---


# Question
Title: How do I make the output of a View a particular Field?
Right now my View is outputting a list of Nodes by their title. I've added a 'subtitle' field to these node's Content Type and I would like to use this as my outputted result instead.

I've gone to the 'Fields' section of my View but cannot find my newly added Content Field among the options there (have cleared cache and rebuilt registry).

Would anyone know how to achieve this?

(ps: why is it called 'Views'? Wouldn't 'Queries' be more accurate?)

# Answer
Turns out my Field was there in that list, but its name was different. It had adopted that name of a Paragraph it was used on. Apparently, if the Field is used in a Paragraph, the name you give it in that instance will be trump any other names you give it.

I don't know why this is or why this feature is useful.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Installing new module in Drupal 8.3.2 link is not exist in xampp
I installed drupal 8.3.2 in xampp (localhost). But i can't add new modules like themes,image slider etc.. What I want to do?

# Answer
Check the **Update Manage**r module weather it is enabled or not. If it is disabled then enable it.

OR

Installing Modules

How to Install Modules in Drupal 8
> 0 votes

# Answer
Just download zip unzip it and paste folder to xampp\htdocs\modules. It should be working then.
> 1 votes

---
Tags: theming, 8
---


title: Xdebug w/ PhpStorm

text:
# Question
Title: Xdebug w/ PhpStorm
I'm using `drupal server` to use the built-in PHP server when building my Drupal 8 site.

I have xdebug set up and I'm using phpstorm. Both work.

The only small issue is that every time I start a debug session, it stops at the .console/router.php file. If I continue on, I get to my actual breakpoint. But I can't figure out how I can bypass this initial break that happens every time.

How can I do that?

# Answer
Go to PHPStorm - Settings

-\> Languages & Frameworks

-\> PHP

-\> Debug

... Section "External connections" -\> "Break at first line in PHP scripts" ... disable this option

Additional suggestion:

... Section "Xdebug" -\> disable the last two checkboxes

... Section "Advanced settings" -\> disable "Notify if debug session was finished without beeing paused"
> 3 votes

---
Tags: debugging
---


# Question
Title: How do I add a cart form to the product view?
With Drupal Commerce 8.x-2.0-beta5, I created some products and a view that lists all products with their variations.

I wanted to add the cart form to any variation, but I was not able to do so.

How can I achieve it?

# Answer
> 4 votes
To display an "add to cart" button on a **product's display** you need to:

1. Go to /admin/commerce/config/product-types/TYPE/edit/display
2. Make sure that Variations field is displayed
3. Select "Add to cart form"

**Views display:**

You simply need to add the "Product: Variations" field and set its display as "Add to cart form"

You of course you need to have the "Commerce Cart" module enabled :)

Not intuitive really. I might end up using Commerce Variation Add to Cart module.

# Answer
> 1 votes
You can use this module Commerce Variation Add to Cart

> How to use it?
>
> After you install the module go to product types 'admin/commerce/config/product-types' and click on the Edit button of your product type. Now go to Manage display tab and choose 'Variation add to cart form' as a formatter for Variations field. If you click on the gear icon, you can see additional settings.

After that choose ***Product variation referenced from variations*** as a relationship in your view and add the field ***Product: Variations*** with the formatter ***Variation add to cart form***.

Also, see this thread https://www.drupal.org/node/2834812

---
Tags: views, 8, commerce
---


# Question
Title: Changing the image path after images were uploaded
I have created a image field under a custom Content Type and let the file directory setting to default, meaning the files are not uploaded to any sub directory.

As I can see now this is not a suitable situation for me and I would like to save the files in a sub directory. If I change the File Directory setting under the Field Settings will this break the paths of the files uploaded prior?

Thanks

# Answer
> 1 votes
If I change the File Directory setting under the Field Settings will this break the paths of the files uploaded prior?

Yes

As i think you need to go a two step process.

1. Move the images to the new folder.
2. Update the existing image path in database.

Before moving with any process keep all the backups.

Refer these links which may help you to move

seeking advice on changing file system path after files have been upload

Moving the files directory

---
Tags: 7
---


# Question
Title: how to add to cart button in drupal 8 commerce?
I am using zircon theme for my commerce site need to add cart and checkout pages to my site,how to create an add to cart button in drupal8 for product display which goes to cart page.

# Answer
> 1 votes
Wait until alpha3 is released, recreate your site, and use the core Add to Cart functionality on your product pages. Note: as we've been saying for some time, there is no alpha to alpha upgrade path, so you'll have to rebuild the site from scratch each time until we hit beta in late March.

# Answer
> 0 votes
Commerce 2 for Drupal 8 is now in Beta and we do have a cart to play with now, YAY. But adding a button for add to cart is not that clear.

I answered similar question here: https://drupal.stackexchange.com/a/239399/6488

---
Tags: commerce, 8
---


# Question
Title: Are there any module options or techniques to authenticate through OpenAM on Drupal 8?
I see that there is an OpenAM module for Drupal 7, but I do not see one for 8. Is there an option for this?

# Answer
> 0 votes
Yes. Port OpenAM to Drupal 8 yourself.

Alternatively, create a new issue and wait until maybe someone else ported it.

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


# Question
Title: How to alter form password and add current password in user_profile_form
How to alter form password and add current password like in this image?

# Answer
> 0 votes
Take a look on Password Separate Form module.

The Password Separate Form module provides the separate password change form.

By default it comes with user account page that little bit confusing for end users. This module would help to make this form as a separate form to help end users, there is no need to change these fields every time if you are editing some other fields on user account page.

---
Tags: 7, forms
---


# Question
Title: How to get the template file using hook block view?
```
function tgs_user_block_info() {
  $blocks = array();

  $blocks['user-list'] = array(
    'info' => t('List of Users'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function tgs_user_block_view($delta = '') {
  $block = array();

$variables['logo'] = theme_get_setting('logo');
$variables['module_path'] = drupal_get_path('module', 'tgs_user');
$variables['current_path'] = '/' . current_path() . '/';

switch($delta) {

  case 'user-list':
    $block['content'] = theme('user_list', $variables);
    break;
  }

  return $block;
}

/**
 * Implements hook_theme().
 */
function tgs_user_theme() {
  $theme = array();

  $theme['user_list'] = array(
    'template' => 'templates/users',
  );

  return $theme;
}

```

This is my code in module. It doesn't call in template that I have been created on my hook\_theme.

# Answer
Try doing it this way, you need to separate your template name from the filepath.

```
/**
* Implements hook_theme().
*/
function tgs_user_theme() {
  $theme = array();

  $theme['user_list'] = array(
    'path' =>  drupal_get_path('module', 'my_module') . '/templates',
    'template' => 'my_template'
  );

  return $theme;
}

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to display a block in the webform confirmation page?
I'm looking for a way to display a block (a view) in the page that is displayed when a webform is submitted. This is the url of the confirmation/done page :

```
domain.com/node/*/done

```

I can't figure out a way to target this url structure by using the ***Show block on specific pages*** or ***context path*** settings.

Any ideas ?

# Answer
It is funny how you have a part of answer in your question. Since you have a block, in **"Show block on specific pages"**, check **"Only on the listed pages"** and type-in `node/*/done` (more on wildcards)

Get back if I missed something here.
> 0 votes

---
Tags: 7, webforms
---


title: Twig extension issues

text:
# Question
Title: Twig extension issues
I'm trying to write a simple twig extension to render a menu inside twig template files.

I created a custom module for this purpose. It's folder structure looks like this:

```
-modules
--MenuRender
---src
----MenuRenderExtension.php
--menurender.info.yml
--menurender.services.yml

```

The `*.info` file is a standard file, the `*.services` files looks like this:

```
services:
  menurender.twig_extension:
    class: Drupal\MenuRender\MenuRenderExtension
    tags:
      - { name: twig.extension }

```

And the `MenuRenderExtension` class is as follows:

```
namespace Drupal\MenuRender;

class MenuRenderExtension extends \Twig_Extension {

  public function getName() {
    return 'MODULE.twig_extension';
  }

  /**
   * @return array
   */
  public function getFunctions() {
    return [
      new \Twig_SimpleFunction('renderMenu', [$this, 'renderMenu'])
    ];
  }

  /**
   * Provides function to programmatically rendering a menu
   *
   * @param String $menu_name
   *   The machine configuration id of the menu to render
   */
  public function renderMenu($menu_name) {
    // 50+ lines so i cut this part as it's mostly clean PHP
  }

}

```

I am constantly getting this error msg in apache's error log

***Service 'menurender.twig\_extension' for consumer 'twig' does not implement Twig\_ExtensionInterface***

Any one have a clue ? p.s. new to drupal8

# Answer
Your module name should not be camel case, but should instead be mymodule (not MenuRender). Your namespace needs to reflect that, too. It should likely live under a folder in src called `TwigExtension`, and your module name in the namespace should match the directory (i.e. `Drupal\mymodule`, not `Drupal\MyModule`).

Here is a module that uses TwigExtension for comparison.

What's likely happening is the application is unable to locate certain things due to the file naming and namespacing.
> 3 votes

---
Tags: theming, 8
---


# Question
Title: Get fields from a collection field in .theme
I would like to know how I have to collect the field collection to get the fields it contains

```
$fieldItemList = $node->field_collection_gallery;
$fieldCollection = $fieldItemList[0];
$fieldCollectionItem = FieldCollectionItem::load($fieldCollection->value);

```

# Answer
> 0 votes
Use the following code:

```
$fieldCollectionItems = $node->get('field_collection_gallery');

    foreach ($fieldCollectionItems as $key => $item) {
      $fcItem = FieldCollectionItem::load($item->value);

      if ($fcItem instanceof FieldCollectionItem) {
        $fcValue = $fcItem->get('field_name')->getValue();
      }
    }

```

The `$fcValue` variable should contain the value from the field in the field collection item.

You have to replace the `field_name` with your own field name in the last line in the `foreach()` loop.

---
Tags: 8, entities
---


title: Programmatically set view header

text:
# Question
Title: Programmatically set view header
I know there is a post on how to set a view header/footer value here, but how do I set a view header/footer without having to create it through views UI first?

The reason why I want to implement a view header programmatically is because (**a**) I want to write php code in it, by leveraging the Drupal's API, something that is not so convenient in a textarea field, like the one that the views UI provides -and any other textarea field- plus the fact that some functions may never get invoked and (**b**) because I want to conditionally set/unset the view header/footer.

# Answer
After some research I managed to answer my own question by implementing the hook\_views\_pre\_view in my custom module. The method set\_item is used to set the configuration of an item (field/sort/filter/etc) on a given display. The `$print` variable bares the content to be rendered in the view header, it is just an example and it can be replaced by anything. Apparently now I can take advantage of the Drupal API or even set/unset any view item conditionally.

```
/**
 * Implementation of hook_views_pre_view.
 */
function my_module_views_pre_view(&$view, &$display_id, &$args) {

  $path = $_GET['q'];
  // Construct the print link.
  $print = l(t('Display a printer-friendly version of this page'), '/print/' . $path . '/print-friendly',  array(
    'attributes' => array(
      'class' => array('print-friendly'),
      'target' => '_blank',
      'title'=> t('Display a printer-friendly version of this page.'),
      ),
    )
  );

  if ($view->name == 'my_view_name' && $display_id == 'my_view_display') {
    // View's header declaration.
    $item = array(
      'id' => 'area',
      'table' => 'views',
      'field' => 'area',
      'relationship' => 'none',
      'group_type' => 'group',
      'ui_name' => '',
      'label' => '',
      'empty' => 0,
      'content' => $print,
      'format' => 'filtered_html',
      'tokenize' => 0,
    );
    // Render the header.
    $view->set_item($display_id, 'header', 'area', $item);
  }
}

```
> 8 votes

# Answer
Just as a second option, you could always use a preprocess function to override the theme hook.

For starters, turn on theme\_debug in your `settings.php` file, clear your site cache and navigate to the page that contains the view display that you'd like to alter.

Open your browser's developer tools (e.g. Chrome: Ctrl+Shift+I, or right click and choose "Inspect") and find the display's markup within the source code. You should see something similar directly above the element.

Next, inside `template.php` of your theme, write a preprocess function that calls the same theme hook:

```
function THEMENAME_preprocess_views_view(&$vars) {
    //logic
}

```

The `$vars` variable is an array that contains the view object. Use a debug tool like devel to introspect the render array. Then set the header and footer attribute by assigning it a value.

```
/**
 * Implements template_preprocess_views_view().
 */
function THEMENAME_preprocess_views_view(&$vars) {
    //logic
    $vars['header'] = "Something Special";
}

```

Source: template\_preprocess\_views\_view
> 4 votes

---
Tags: 7, views
---


# Question
Title: How do I migrate while content is still created on production site?
I've written a bunch of migration script to migrate a site from Drupal 6 to Drupal 8.

On the development server I just ran a sample of each content type migration to test everything was OK while new content was still being created on production server on a daily basis by redactors.

During the validation time by the project team (which could take several weeks), I'll run migration everyday on a fresh database dump from production server. During that time also, the project team will need to create specific new content (content that is not being migrated) for different purposes, like testing brand new content type or creating specific base pages needed by the new site templates.

Since the migration process keeps the original ID, I need to find a way for new content to be created without taking the node ID from a node created on the production server. I’ve not been able to find any information about that case (which is quite a common case, I think) in the Drupal migration literature.

My first idea would be to change auto\_increment value in relevant tables adding (let’s say) 100.000 to the current value, that way there wouldn’t be any collision between newly created content and the ones created the day before on production server. A brief look to the Drupal 8 database schema gave me the following tables and fields to alter:

* file\_managed =\> fid
* node =\> nid
* node\_revision =\> vid
* url\_alias =\> pid

I am not sure the file managed fid field is kept during migration process; the same is true for the URL alias pid field since the link is made on the source field.

Do you think it would be enough to alter only the node and node\_revision tables?

I also noticed a sequences table with a single value field with only one row. As far as I've read about this table, I've not really been able to figure out what it is used for. Maybe some of you can explain me and tell me if it's important regarding my issue.

Do you this is a correct approach? Are there other tables that could need to be altered?

# Answer
Migrate, as shipped with Drupal 8, has two components:

1. The `migrate` module. This provides a very flexible API.
2. The `migrate_drupal` module. This provides Drupal 6 / 7 to 8 migrations (the migrations themselves has been scattered into the modules). This is the part which keeps IDs and the motivation for this was very simple: there's just no way to tell where those IDs might lurk. Say, one of the old nodes has a http://example.com/node/12345 link in the body text and we changed the node id to 67890 during migration? Then that link breaks. It also made for more rapid development which is not a bad side effect either. It is arguable whether for example file IDs deserved such treatment or not.

As @berdir comments, if you remove the `nid: nid` process definition from a node migration then it will happily generate new node IDs for you, no sweat but you need to look everywhere for the same to make sure that any references are changed to a `migration_lookup` process definition. Some of it is already done for you, some of it is not.

For example, `comment/migration_templates/d6_comment.yml` has:

```
# If you are using this file to build a custom migration consider removing
# the cid field to allow incremental migrations.
cid: cid
pid:
  plugin: migration_lookup
  migration: d6_comment
  source: pid

```

For core, `pid: pid` would work just as well but instead, this migration is already prepared for this migration creating new IDs. But then it continues with

```
entity_id: nid

```

Now the corresponding `node/migration_templates/d6_node.yml` has

```
# If you are using this file to build a custom migration consider removing
# the nid and vid fields to allow incremental migrations.
nid: tnid
vid: vid

```

If you actually do that then you need to circle back to `comment/migration_templates/d6_comment.yml` and write

```
entity_id:
  plugin: migration_lookup
  migration:
    - d6_node:article
    - d6_node:page
  source: nid

```

Because the actual migration is not `d6_node` but rather `d6_node:nodetype`.
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: Rendering a 'google_map_field' when referenced via entity reference field
I have a content type with an entity reference field to another content type. We'll call the first content type **A**, and the other **B**.

In my node level template for A, I need to output a google\_map\_field (https://www.drupal.org/project/google\_map\_field) from referenced entity (B).

I'm outputting other fields from B by using:

`node.field_entity_reference.entity.field_example.value`

However, this does not work for the google\_map\_field. Lots of errors spit out, regarding parts of the google\_map\_field, such as lat, lng etc. I'm guessing this is because the module usually does some processing of this field, which isn't being done due to the nature of how I'm outputting it?

I need to work out how to tell Drupal to render it as a `GoogleMapFieldType` (I beleive).

Any guidance on this would be highly appreciated!

Thanks in advance.

# Answer
> 1 votes
The most out of the box way to display a referenced entity is this:

1) Create a custom view mode "google\_map".

2) Set field\_entity\_reference to render the entity with that view mode.

3) Output the field from the content variable, like this:

```
 {{ content.field_entity_reference }}

```

In your case, as you're pulling raw values out in your question, it looks like you want the control that comes from having all of your variables (including those from a referenced entity) in one template.

You can do this in a preprocess hook. For example in hook\_preprocess\_node() in your custom theme or module, you can assign the google map from the referenced entity to a variable:

```
 if ($node->field_entity_reference->isEmpty() === FALSE) {

    $referenced_entity = $node->field_entity_reference->referencedEntities()[0];

    $vars['google_map'] = $referenced_entity->field_example->view();

  }

```

If you want to pass a view module in to the view() method, you can do it like this:

```
$vars['google_map'] = $referenced_entity->field_example->view('default');

```

or

```
$vars['google_map'] = $referenced_entity->field_example->view('google_map');

```

Then in your twig, you would just access it like this:

```
{{ content.google_map }}

```

If you want to pull other raw values out of your referenced entity, you can access them easily like this:

$vars\['referenced\_entity\_field\_value'\] = $referenced\_entity-\>field\_example\_description-\>value;

But if you do this, you lose the formatting from a field formatter. For plain text fields, that's may be fine for your use case. But it's something to watch out for.

# Answer
> 1 votes
I would recommend using a view mode to render out the referenced entity.

For instance, **A**'s display settings is set to display **B** using the 'teaser' view mode. Then, you can configure **B**'s teaser display to show what you want.

I know this doesn't answer your direct referenced entity value question, but this is how I would tackle this problem.

I hope that helps!

---
Tags: theming, 8, google-maps
---


# Question
Title: Block configuration form values are not translated
I have the following code in my custom block:

```
    public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['headline'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Block headline'),
      '#default_value' => isset($config['headline']) ? $config['headline'] : NULL,
      '#required' => TRUE,
    );

      return $form;
    }

```

and:

```
    public function blockSubmit($form, FormStateInterface $form_state) {
      $this->setConfigurationValue('headline', $form_state->getValue('headline'));
    }

```

The configuration is saved correctly, but only for English language.
The block translation doesn't show my variable (headline) in the translatable configuration.
What am I doing wrong?

Thanks

# Answer
You have to provide a schema in `/config/schema/mymodule.schema.yml` of the type `block_settings`.

Example:

```
block.settings.example_configurable_text:
  type: block_settings
  label: 'Example configurable text block configuration'
  mapping:
    block_example_string:
      type: text
      label: 'Block contents'

```

From the example module https://git.drupalcode.org/project/examples/-/blob/HEAD/modules/block\_example/config/schema/block\_example.schema.yml

Configurations mapped as `type: label` (single line of text) or `type: text` (multiple lines of text) are translatable.
> 11 votes

---
Tags: 8
---


# Question
Title: Add markup inside a link (in the renderable array) in preprocess field
My question is for D8...

I have a field which is rendered as a link. Let say for simplicity that it will be rendered like this: `<a href="url">My Title</a>`

I would like to add a bootstrap icon inside the link to get a result like this: `<a href="url"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>My Title</a>`

I know that I can take the url and the title from within the preprocess function to reconstruct a new link (#markup)... But is it possible to simply add the icon code somewhere in the array to get the same result?

I am adding some more information to clarify:

1-The field which is rendered as a link is a term reference field rendered as a linked label

2-Here is my try in the preprocess\_field function to achieve this

```
function mymodule_preprocess_field(&$vars) {
  $fn = $vars['element']['#field_name'];
  switch ($fn) {
    case 'my_field':
      foreach ($vars['items'] as $key => $item) {
        $icon = '<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>';
        $vars['items'][0]['content']['#title']=$icon.$item['content']['#title'];
      }
      break;
  }
}

```

# Answer
> 7 votes
Use the FormattableMarkup class for this:

```
$markup = new FormattableMarkup('<a href="@url"><span class="glyphicon glyphicon-info-sign" aria-hidden="true /></a>', [
          '@url' => $url->toString(), // If $url is an Drupal\Core\Url object.
        ]);

$renderArray['your_element'] = $markup;

```

**After edit:**

Use the Markup class for this since your seem to be in control over your markup. If not use FormattableMarkup with placeholders for safety:

```
  function mymodule_preprocess_field(&$vars) {
    $fn = $vars['element']['#field_name'];
    switch ($fn) {
      case 'my_field':
        foreach ($vars['items'] as $key => $item) {
          $icon = '<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>';
          $uri = $item['content']['#title'];

          $formattedIcon = \Drupal\Core\Render\Markup::create($icon . $uri);

          $vars['items'][0]['content']['#title'] = $formattedIcon;
        }
        break;
    }
  }

```

From the FormattableMarkup docs:

> When cast to a string, this object replaces variable placeholders in the string with the arguments passed in during construction and escapes the values so they can be safely displayed as HTML. See the documentation of \Drupal\Component\Render\FormattableMarkup::placeholderFormat() for details on the supported placeholders and how to use them securely. Incorrect use of this class can result in security vulnerabilities.

# Answer
> 2 votes
For the link field you can insert a markup-array in the title var, like this:

```
$icon = '<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>';
$variables['link_field_name']['title'] = [
  '#markup' => $icon . $variables['link_field_name']['title'],
];

```

**Edit:** For the term reference title use:

```
$vars['items'][0]['content']['#title'] = [
  '#markup' => $icon . $vars['items'][0]['content']['#title'],
];

```

Or like suggested from @Gun5m0k3 the new drupal 8 classy way:

```
$vars['items'][0]['content']['#title'] = \Drupal\Core\Render\Markup::create($icon . $vars['items'][0]['content']['#title']);

```

# Answer
> 2 votes
One way to handle this is to create an inline\_template render item:

```
  function mymodule_preprocess_field(&$vars) {
    $fn = $vars['element']['#field_name'];
    switch ($fn) {
      case 'my_field':
        foreach ($vars['items'] as $key => $item) {
          $vars['items'][0]['content']['#title'] = [
            '#type' => 'inline_template',
            '#template' => '{{ icon }} {{ title }}',
            '#context' => [
              'icon' => '<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>',
              'title' => $item['content']['#title'],
              ],
          ];
        }
        break;
    }
  }

```

---
Tags: theming, 8, navigation
---


title: eCommerce : fields vs attributes?

text:
# Question
Title: eCommerce : fields vs attributes?
From the docs :

> Products variations can have attributes and other kinds of fields. Going back to our t-shirt analogy from above, if our t-shirts come in sizes and colors, perhaps the product variation should have an image field so you can upload a picture of a small red shirt. These kinds of non-attribute fields are loaded dynamically when variations are chosen.

What is the difference of purpose and meaning of "non-attribute fields" AND attributes ? How are they different and similar ?

# Answer
> 3 votes
The way I think about it is in terms of sku numbers (or manufacturing part number/catalog number.) If a single product is available in multiple sizes (1 mg, 50 mg, 1 gm), each one will have its own unique sku. Those sizes are the variation attributes. But then I may also want to add on a non-attribute field like an image or a packaging/shipping surcharge (for a larger size). That data is specific to the product variation but isn't related to the sku.

Using the t-shirt analogy, if both size and color are attributes, then you might have the following unique variations:

* TS\_SM\_01: small, blue t-shirt
* TS\_MD\_01: medium, blue t-shirt
* TS\_LG\_01: large, blue t-shirt
* TS\_SM\_02: small, red t-shirt
* TS\_LG\_02: large, red t-shirt
* TS\_SM\_03: small, green t-shirt
* TS\_MD\_03: medium, green t-shirt
* TS\_LG\_03: large, green t-shirt

If I add on a field for an image or a field for some sort of customization, those new "non-attribute" fields do not cause me to create a whole new set of product variation sku numbers.

# Answer
> 3 votes
Hey there :) I wrote the above documentation a year or two ago. I think your question has two parts:

## 1. What is an attribute?

In the simplest terms possible, an attribute is something that differentiates your products at the SKU level.

An attribute for Drupal 8 is actually an entity, like a product or a piece of content. It's a specialized entity that has a specialized form for creation and management because the majority of product variations on Drupal Commerce 1.x needed something like what we built for 2.x.

One of the use cases we wanted to meet was the ability to add fields to attributes. So color or size are often used to describe an attribute. A color might need a field for a photorealistic representation of the color and a hexadecimal field that describes the color within the RGB spectrum.

## 2. In terms of entity architecture, why would I choose to make a differentiator an attribute? And the opposite situation?

When creating product variations, you can choose to create any number of fields. Sometimes those fields are best off being attribute references. Using attribute references lets the add-to-cart form understand the nature of your products and can help give you a configurable product form. This lets you pick the color and size combinations instead of picking from a long list of products with both colors and sizes pointed out.

In the end, no one is forcing you to use the attributes to document the differentiators. If you want to create an integer field per SKU that defines the length of the fabric you're selling, that doesn't have to be an attribute, but it could be a part of the pricing. (final price could be length x price)

---
Tags: commerce
---


title: How to list events filtered by date

text:
# Question
Title: How to list events filtered by date
In Drupal 8, I have an 'event' content type with a date range that specifies when the event starts and when it ends. In my view, I need to set up a filter with the following behavior: i choose a specific day from a calendar (btw how to create a calendar and make it work like a view filter in D8?!?), and the view only lists events that start \<= the specific day AND end \>= the specific day.

Thanks in advance.

# Answer
> 1 votes
As jQuery UI is part of Drupal 8 core for the calendar functionality you can simply do this:

## modulename.libraries.yml

```
modulename.id:
 version: VERSION
 js:
  js/custom.js: {}
 dependencies:
  - core/jquery
  - core/jquery.ui.datepicker

```

## custom.js

```
function ($, Drupal) {
  "use strict";
  Drupal.behaviors.mymodule = {
    attach: function(context) {
      $('#views-exposed-form-id
       input:text').datepicker();
     }
   };
})(jQuery, Drupal);

```

To query for data between event starts & end date you can use hook\_view\_query\_alter();

# modulename.module

```
use \Drupal\views\Plugin\views\query\QueryPluginBase;
use \Drupal\views\ViewExecutable;

function modulename_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ( $view->id() !== "view_id" ) { return; }
 foreach ($query->where as &$condition_group) {
  foreach ($condition_group['conditions'] as $index => &$condition) {
   if (!empty($view->exposed_raw_input['start']['min']) && !empty($view->exposed_raw_input['start']['max'])) {
$query->addWhereExpression(0,'FROM_UNIXTIME(tablename.created, :format ) BETWEEN :min AND :max ',
array(':min' => $view->exposed_raw_input['start']['min'],':max' => $view->exposed_raw_input['start']['max'],':format' => '%m/%e/%Y'));
   }
  }
 }
}

```

Idea is to use BETWEEN :min AND :max in your query. Maybe there are other ways to solve this problem, but this is how I would approach this issue.

---
Tags: 8, datetime
---


# Question
Title: How do uploaded photos and files impact search performance?
I am creating a Drupal site where performance is a key goal and have a few questions:

* Does Drupal store the photos in the same table as the rest of the node's fields?
* Will enabling photo uploads on nodes adversely impact search performance any more than other conventional field types? (text etc) If the answer to the above question is yes but it does not negatively impact search performance, why not?

Thanks for your help!

# Answer
> Does Drupal store the photos in the same table as the rest of the node's fields?

Well, no. In fact Drupal stores all fields in their own table. I suppose you could have figured this out by yourself by just looking into the database.

> Will enabling photo uploads on nodes adversely impact search performance any more than other conventional field types?

I cannot see how it would; an image does not contain text. It would be pretty useless of Drupal to search through the image's binary data. If are unsure and do not trust it, you can always use the search api module, which allows you to select which fields you want to index and search.
> 0 votes

---
Tags: performance
---


# Question
Title: How do I add an 'order complete' from the Commerce module to the Rules events in Drupal 8?
I need to add a new event to rules triggered by the successful completion of an order. The action is to grant a user a role which will expire in a fixed duration.

I've tried following the Rules documentation and adding a module with a \*.rules.events.yml file. But modifying it to use the `order_complete` event which I got from this tutorial.

Unfortunately, even though it DID add an option to the events drop down, it doesn't trigger an action.

I've tried a `grep` through the commerce code for `order_complete` but it doesn't yield anything.

The action I've set to the rule is just to print a message.

# Answer
> 1 votes
After trying out combinations and with the helpful comments, the solution was to follow the Rules documentation but change the event to `commerce_order.place.post_transition` which I got from the tutorial.

The final code was to create a `MODULENAME.rules.events.yml` file and add the following code:

```
commerce_order.place.post_transition:
  label: 'Order has been completed'
  category: 'Order'

```

This created the option in the dropdown and allowed me to create the rule that triggered the action.

# Answer
> 0 votes
Interesting, this is the first time I've heard of someone trying to use Rules with Commerce 2 ... definitely not a lot of documentation on that. Likely you need to rebuild your cache and confirm the event is firing by using a very simple (not prone to breaking) action and/or enabling the debugging mode of rules (to see if the rule processed as requested).

Likely, your event is firing just fine but your action, which you provided no information on, is the culprit.

---
Tags: 8, commerce, rules
---


# Question
Title: AJAX forms will break when used in subform
When using the following AJAX element in a `BlockBase` extended class everything seems to work just jolly good in the Block-layout page.

```
$form['foobar_row']['add_more'] = [
  '#type' => 'submit',
  '#value' => $this->t('Add more'),
  '#submit' => [[$this, 'addOne']],
  '#ajax' => [
    'callback' => [$this, 'addmoreCallback'],
    'wrapper' => 'foobar-wrapper',
    'method' => 'replaceWith',
    'event' => 'click'
  ],
  '#id' => 'foobar__add_more'
];

```

Though, the block form will fail when used as a subform, in my case it's being used in a paragraph, which contains a block\_field. And I can completely see why it's failing, since the `$form` in the callback method contains the entire node form. I even experimented with the following alteration to my callback method, which works, but is absolutely no solution since the entire path to the element should always be the same.

```
  public function addmoreCallback(array &$form, FormStateInterface $form_state) {
    $referral_field = $form_state->get('num_foobar_rows');

    // Note every parenting element being addressed in following, but I would ideally only have to define ['settings']['foobar_row'];
    return $form['field_paragraphs']['widget'][0]['subform']['field_paragraph_block_blocks']['widget'][0]['settings']['foobar_row'];
  }

```

How would I make my `addmoreCallback` more dynamic and make sure it returns the right element?

# Answer
Use `$form_state->getTriggeringElement()`!

Example for the callback:

```
public function addmoreCallback(array &$form, FormStateInterface $form_state) {
    $items_field = $form_state->get('num_foobar_rows');

    // Gets the button that triggers the ajax call
    $triggering_element = $form_state->getTriggeringElement();

    // Retrieve the parents, so we can climb back up the tree and do not have to hard code the unknown position of our subform
    $parents = array_slice($triggering_element['#array_parents'], 0, -1);

    // Use NestedArray to get the element in `$form` at the path that `$parents` describes.
    return NestedArray::getValue($form, $parents);
}

```

Note that I'm using `#array_parents`, this will contain all the parents including simple array parents or elements without `#tree`. This will prevent problems you are most likely to encounter when your form gets embedded in a field and ofcourse other forms.

Also note that the `array_slice` part, this will just slice off some parents to make sure we have the path to our first (`-1`) parent. If the element that you want to return is one or more parents up the tree, you'll need to adjust the `-1` accordingly. Also, if your to be returned element is not actually the parent of the triggering element you'll want to alter the `$parents` array accordingly.
> 2 votes

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


# Question
Title: Why would piece of content of each content type be migrated but their text formats wrong?
I'm trying to migrate content D6 -\> D7. I've written the importers (actually just edited existing ones) and run the process. However, as far as I can see, body of content are imported but with the wrong format i.e. one of them correctly shows as Full HTML while another shows just Select.

Below is my importer:

```
class StoryMigration extends NodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);
    $this->addFieldMapping('title', 'title');
    $this->addFieldMapping('body', 'body');
    $this->addFieldMapping('taxonomy_tags_1', 'field_tags')
      ->defaultValue('tid');
    $this->addFieldMapping('field_headerimage', 'field_headerimage')
      ->sourceMigration('Files');
    $this->addFieldMapping('field_headerimage:file_class')
      ->defaultValue('MigrateFileFid');
  }
}

```

UPDATE: I also did a format mapping, like below:

```
$common_arguments = array(
    'source_connection' => 'default',
    'source_version' => 6,
    'format_mappings' => array(
      '1' => 'filtered_html',
      '2' => 'full_html',
      '3' => 'php_code'
    ),
   ...
   ...
   ...
  );

```

# Answer
You need to map the body format.

This is from 6 years ago, but reposting in case mikeryan does not see this question.

> if the format is part of the source data (i.e., it varies from node to node), you can make use of the source\_field feature:

```
$this->addFieldMapping('body', 'body')
     ->arguments(array('format' => array('source_field' => 'body_format'));

```

Where `body_format` is the value from the source db I believe.

It has been a loooong time since I have done a 6 to 7 migration.

This post might also be of use if you are using migrate\_d2d.
> 0 votes

---
Tags: 6, migrations
---


# Question
Title: What should I set my Content-Security-Policy to?
I'm using Drupal 8, and I currently use

```
Header always set Content-Security-Policy "default-src 'self'; nosniff"

```

However, this causes bugs, such as Google Analytics not working and the textbox mysteriously disappearing from the Edit page. What should I do?

# Answer
> 3 votes
The policy needs to contain every domain where assets are loaded from, which will vary depending on which services your site uses such as a CDN or third party JavaScript widgets.

For Google Analytics, it must be able to connect to `www.google-analytics.com`, and `stats.g.doubleclick.net` if Display Features tracking is enabled.
The *Google Analytics* module also requires the `unsafe-inline` policy value, since it injects the analytics snippet directly on the page.
*Googalytics* is an alternative built specifically for Drupal 8 that works without `unsafe-inline`.

Core also currently requires 'unsafe-inline' for scripts in element attributes due to its use of CKEditor 4 (see https://www.drupal.org/project/drupal/issues/2789139)

---

In order to test a Content Security Policy without impacting the functionality of your site, first use the `Content-Security-Policy-Report-Only` header instead. This will make the browser report violations of the policy in the browser console and to the `report-uri` address, without blocking the content on the page. Once you have a policy that works without violations, change the header to `Content-Security-Policy`.

You can also provide both headers at the same time, allowing you to test changes without the risk of breaking functionality.

Report-uri.io provides a free logging service that you can use to collect violations of both your enforced and report-only rules, and audit for any changes you may need to make.
They also have a wizard utility to help setup your policy for the first time.

---

Setting up a policy in Drupal 8 is also easier with the Content Security Policy module. It integrates with Drupal 8's libraries system to automatically add script and style sources, provides an admin UI that validates your settings, provides a local handler for report violations, and will apply some optimizations to shorten the policy if possible.

---
Tags: 8, http-request
---


title: Print variable views template

text:
# Question
Title: Print variable views template
I have created a view with table format but i am not able to print field variables in twig template of **view** suppose machine name of eck field is **field\_large**,**field\_quote\_source** and so on.

```
 <ul class="bxslider">
  {% for row in rows %}
<li{{ row.attributes }}>
  {% for key, column in row.columns %}
        {% for content in column.content %}
          {{- content.separator }}{{ content.field_output -}}
          {{ content.field_large }}
        {% endfor %}
  {% endfor %}
</li>
 {% endfor %}
 </ul>

```

# Answer
> 0 votes
This is the path for accessing single fields in a view table template, for example in the first row:

```
rows.0.columns.fieldname.content.0.field_output

```

In your code example, to get all field names available, use this in the first loop:

```
{{ dump(row.columns|keys) }}

```

The naming of the fields depends on how you have configured the view and is not necessarily the machine name of the field in the entity.

---
Tags: 8
---


# Question
Title: Is there any way to hide author information from custom article rather than content type?
I know that I can hide author information in below path in Drupal 8:

```
Home>Admin>Structure>Types>Article>Display settings

```

but I want to know is there any setting or selective options to hide author information per custom article or post, rather than all post of custom content type?

# Answer
No, but it would be easy to implement:

1. Add a Boolean field called show\_author\_info or something
2. Create a node template for that content type in your theme (or for nodes in general if you don't need to specify a type)
3. Add a conditional to the template to only output the author information if the node has a positive value for that field
> 4 votes

---
Tags: 8, nodes
---


title: Error generating images

text:
# Question
Title: Error generating images
I was experiencing weird GD library issues with Drupal 8, when the site tries to generate thumbnails from image style. I am using Docker PHP.

The error is simply saying *Error generating image*. I checked the logs, but I didn't find anything helpful.

# Answer
This is the fix for the issue.

The code taken from duplicated issue in https://stackoverflow.com/questions/36359917/docker-gd-module-for-php-7

Please take this with heaps of grain and salt, and modify the script accordingly.

```
# Install GD
RUN apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng12-dev
RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
RUN docker-php-ext-install gd

```

What is actually happens is your GD library is installed **BUT without JPEG library configured**. Your Drupal will be chill saying GD installed but there is hidden requirement that JPEG need to be exist too.

The line 179 in GDToolkit.php:

```
$function = 'imagecreatefrom' . image_type_to_extension($this->getType(), FALSE);

```

Causes the function imagecreateformjpeg fails to be executed.

Hope it helps someone that confused, cant generate thumbnail with limited knowledge of the errors.

:)
> 3 votes

---
Tags: 8, media
---


# Question
Title: How to control image height within a "Rendered Entity" that displays images & text fields within a View?
I currently have a view that displays (1) Image field and (2) Text fields. This view is

* HTML List view of
* Rendered Entities

The Rendered Entities is the default "Product List" view mode from Commerce Kickstarter.

When I try to set a "min-height" for this field, the css is applied to all items within the field, which isn't what I'm after. I want to set a min-height for the image, so that the grid is consistent across the row.

```
.view-collection-products .view-content .item-list .products-per-collection li .commerce-product-field, .view-collection-taxonomy-term .view-content .item-list .products-per-collection li .commerce-product-field {
color: #000000;
font-size: 14px;
margin-bottom: 5px;
text-decoration: none;
/* min-height: 300px; */

```

}

Without it, the text fields jog up and down, adjusting to the image height.

How do I re-write the css so that it targets just the image field in this view?

# Answer
To restrict your css rule only on the image just add "img" to your actual css :

```
.view-collection-products .view-content .item-list .products-per-collection li .commerce-product-field, .view-collection-taxonomy-term .view-content .item-list .products-per-collection li .commerce-product-field img {
    min-height: 300px;
    }

```

But if you want to be sure to have consistent rows, you should directly fix a height.

```
.view-collection-products .view-content .item-list .products-per-collection li .commerce-product-field, .view-collection-taxonomy-term .view-content .item-list .products-per-collection li .commerce-product-field img {
height: 300px;
}

```

Or at least use max-height whereas min-height.
> 1 votes

---
Tags: views, theming, media
---


# Question
Title: Truncate field storage tables added by module before uninstall
I've added a field via `hook_entity_base_field_info()`. It has data stored in it. I then go to uninstall my module and I get the following error:

```
-> drush8 pm-uninstall massing -y
The following extensions will be uninstalled: massing
Do you really want to continue? (y/n): y
exception 'Drupal\Core\Extension\ModuleUninstallValidatorException' with message 'The following reasons prevents the modules from being uninstalled:    [error]
There is data for the field massing_memberships on entity type User' in
/Users/les.peabody/Sites/drupal8/core/lib/Drupal/Core/Extension/ModuleInstaller.php:347
Stack trace:
#0 /Users/les.peabody/Sites/drupal8/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(95):
Drupal\Core\Extension\ModuleInstaller->uninstall(Array, true)
#1 /Users/les.peabody/opt/drush8/commands/core/drupal/environment.inc(227): Drupal\Core\ProxyClass\Extension\ModuleInstaller->uninstall(Array)
#2 /Users/les.peabody/opt/drush8/commands/core/drupal/pm_8.inc(80): drush_module_uninstall(Array)
#3 /Users/les.peabody/opt/drush8/commands/pm/pm.drush.inc(1190): _drush_pm_uninstall(Array)
#4 [internal function]: drush_pm_uninstall('massing')
#5 /Users/les.peabody/opt/drush8/includes/command.inc(364): call_user_func_array('drush_pm_uninst...', Array)
#6 /Users/les.peabody/opt/drush8/includes/command.inc(215): _drush_invoke_hooks(Array, Array)
#7 [internal function]: drush_command('massing')
#8 /Users/les.peabody/opt/drush8/includes/command.inc(183): call_user_func_array('drush_command', Array)
#9 /Users/les.peabody/opt/drush8/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
#10 /Users/les.peabody/opt/drush8/drush.php(70): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#11 /Users/les.peabody/opt/drush8/drush.php(11): drush_main()
#12 {main}

```

So what I'm trying to figure out how to do is how to drop the data in this table after I've called for an uninstall on the module, but before the check happens for whether or not there is data in the table. I've tried implementing `hook_uninstall()` and `hook_module_preuninstall()` but neither of these hooks are invoked before the check for data presence. Thoughts?

**EDIT:** Looking at ModuleInstaller.php at line 343 (D8 RC1), it runs uninstall validators prior to triggering `hook_module_preuninstall` and `hook_uninstall`. This is where it is failing. So, maybe there is a way to add an uninstall validator for my module and run it first? There doesn't look to be any other way to do it besides adding some kind of mechanism to the module which makes it "purge" itself of any data it's added to the system, which then lets you uninstall it. Seems terribly convoluted and not side builder friendly in the slightest, very frustrating.

# Answer
I was able to solve this problem by implementing `hook_uninstall()` in my module's install file and explicitly deleting my custom entities.

For example:

```
function mymodule_uninstall() {
  //remove_fields_user();

  $results = \Drupal\mymodule\Entity\MeetEntity::loadMultiple();
  foreach ($results as $entity) {
    $entity->delete();
  }
  $results = \Drupal\mymodule\Entity\Team::loadMultiple();
  foreach ($results as $entity) {
    $entity->delete();
  }
}

```

See Drupal 8 hook\_uninstall() docs for more details
> 2 votes

# Answer
I encountered this same issue, and unfortunately found no satisfactory answer here so I am posting my solution. It is a solution which I find unappealing but it is the most graceful solution that I could come up with after hours of searching and finding no answer.

First the reason that the solution from Eric C does not work for me is because, as with the original request, my entity is User, and I have added fields to it. I cannot simply delete the User entity, so I must empty the fields before uninstalling.

This can be handled a few ways, one is to create a custom page to visit and delete all of the data, then uninstall the module. I considered this but because I am not the one that will be handling those operations I created a solution which I think is more elegant, though still unfortunate.

Three basic steps:

1. When the user is loaded, fill the fields.
2. When the user logs out empty the fields.
3. Make sure that the fields are still initialized.

Step one:

```

function myModule_user_load(array $entities) {
    $fields=['field_1','field_2',...];

    foreach ($entities as $index => $user) {

        foreach ($field as $field) {
                $entities[$index]->set($field, 'value');

        }
    }
}

```

This basically sets the data on user load because we are going to be destroying the data when they logout.

Step 2:

```

function myModule_user_logout($account) {

    $user = User::load($account->id());
    $fields=['field_1','field_2',...];

        foreach ($field as $field) {
            $user->set($field, NULL);
        }
    $user->save();

    initilizeFieldsFunction();
}

```

Now assuming that every user has logged out before you uninstall this module, the data should be empty, freeing the fields. However drupal seems to still require that the fields be initialized and I have had the uninstaller fail due to the fields not being found. So at the bottom of the logout hook we have to make sure that the fields are initialized. This is basically the same as what you, probably did at the installation of your module, if you created these fields through the BaseFieldDefinition::create() method.

Step 3:

```

function initilizeFieldsFunction() {
       $fields=['field_1','field_2', ...];

        //  Check that the fields are empty
        // by querying all uids where the fields
        // still exist.
        $query = \Drupal::entityQuery('user');
        $group = $query->orConditionGroup()
                ->exists('field_1')
                ->exists('field_2')
                ->exists('...');
        $uids = $query->condition($group)
                ->execute();

        if (count($uids) === 0) {
            foreach ($fields as $field) {
                $definition = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('user')[$field];
                \Drupal::service('field_storage_definition.listener')->onFieldStorageDefinitionCreate($definition);
            }
        }
    }

```

Now assuming that every user with data has logged out, you ought to be able to uninstall the module.

I hope this helps someone, though more I'd like a better solution to this issue. I never found the validator method that the original requester was pondering to work, and I don't actually know when the validator runs, so the issue that I have is that I can't destroy this data for every user if the validator runs before uninstall is triggered because they may be using that data up until uninstall. So basically as far as I can tell this needs to be able to happen in hook\_uninstall and drupal 8 just doesn't permit that.

If any one has a more appropriate solution please do contribute because this seems to be a fairly unaddressed issue in D8.
> 1 votes

---
Tags: 8, installation
---