# Question
Title: How to make Panel Page variant selection rules detect URL parameter?
On D7 I have set up a new panel page variant and want to use it with a certain selection rule:

```
 String: URL path   Current path is "*/cars/*?buy"

```

Eg I want this panel variant to be used if the URL is `new/cars/honda?buy`.

However the above doesn't work. Adding `?buy` to the url doesnt trigger it to be used.

Would anyone know a way to set selection rule so that I can use this page variant with a give parameter in the URL?

# Answer
I found the Selection Rule `Query string exists` does this.
> 0 votes

---
Tags: 7, panels
---


# Question
Title: How to theme all pages after a certain url
I'm using Drupal 8.7.8

I would like to create a new twig theme file for all pages that are after a certain URL. For example: example.com/example/this-page

"This-page" is what I want to create my twig file for. But there doesn't seem to be an option in the theme debugging for anything after example.com/example.

Another example...The twig file would be named page--example.html.twig ... Is there no way to say page--example/\*.html.twig ?

# Answer
> 0 votes
You can use THEME\_NAME\_theme\_suggestions\_page\_alter to create your own template suggestions!

In your theme:

File: `my_theme/my_theme.theme`

```
/**
 * Implements hook_theme_suggestions_HOOK_alter.
 */
function my_theme_suggestions_page_alter(&$suggestions, $variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $current_path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

  if (strpos($current_path, 'this-page') !== false) {
    $suggestions[] = 'page__this_page';
  }
}

```

File: `my_theme/templates/page--this-page.html.twig`

```
// Output html and stuff

```

Obviously replace "my\_theme" with the name of your custom theme.

Here is a nice tutorial that expands more on it.

---
Tags: theming
---


title: Function to get node view mode name

text:
# Question
Title: Function to get node view mode name
I've been using

```
$node->getType();

```

to get the content type.

For view mode, I am following this method:

Is there a function similar to `getType()` (that doesn't require adding a preprocess function) I can use to get the view mode of my node?

# Answer
> 2 votes
The node entity represents the database content of the node, which can be displayed in different view modes. If you want to alter such a display in a specific view mode use `mymodule_node_view_alter()`:

```
function hook_ENTITY_TYPE_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($build['#view_mode'] == 'full' && isset($build['an_additional_field'])) {

    // Change its weight.
    $build['an_additional_field']['#weight'] = -10;

    // Add a #post_render callback to act on the rendered HTML of the entity.
    $build['#post_render'][] = 'my_module_node_post_render';
  }
}

```

See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_ENTITY\_TYPE\_view\_alter/8.7.x

---
Tags: 8, nodes
---


# Question
Title: Can I create a form with a route like this /rooms/{node.alias}/booking?
I'm working on a booking project and I have to create a form for reservations.

I have created the accommodation content type and the `url_alias` for this is: `/rooms/[node:title]`

Example:

* `/node/1` = `/rooms/1-accommodation-example`
* `/node/2` = `/rooms/2-accommodation-example`

I need to know if I can do this:

```
booking.booking_form:
  path: 'booking/{url_alias}'
  defaults:
    _form: '\Drupal\booking\Form\BookingForm'
    _title: 'Accommodation booking'
  requirements:
    _access: 'TRUE'

```

Is this possible? `path: 'booking/{url_alias}'` or `path: '{url_alias}/booking'`

What happen next, if you try yo go to this route:

* `/booking/any-text-asdasdas` = the form page is loaded.
* `/booking/rooms` = the form page is loaded.
* `/booking/rooms/1-accommodation-example` = page not found.

I tried but I don't know how to find information about this way of routing.

I don't know if I have explained what I need well, any information will be very helpful.

Thanks,
STF

# Answer
I need to create a form for all nodes of a type. This form route has to be like this, the base `/booking` \+ the node alias. The node alias could be:

* /accommodation-test
* /rooms/accommodation-test
* /rooms/address-test/accommodation-test

Final form route:

* /booking/accommodation-test
* /booking/rooms/accommodation-test
* /booking/rooms/address-test/accommodation-test

To do this, I used three placeholders in routing definition:

```
booking.booking_form:
  path: 'booking/{path_1}/{path_2}/{path_3}'
  defaults:
    _form: '\Drupal\booking\Form\BookingForm'
    _title: 'Accommodation booking'
    path_2: NULL
    path_3: NULL
  requirements:
    _access: 'TRUE'

```

Now in BookingForm.php:

```
  public function buildForm(array $form, FormStateInterface $form_state, $path_1 = NULL, $path_2 = NULL, $path_3 = NULL) {
    // Generate alias from route
    $alias = $this->generateAlias($path_1, $path_2, $path_3);
    // Load from generated alias
    $node = $this->loadNodeFromAlias($alias);

    // Check if loaded node is an accommodation content type
    if (is_null($node) || $node->bundle() != 'accommodation') {
      throw new NotFoundHttpException();
    }

    ...
  }

```

Thx to @no-sssweat & @rainer-feike for help. If there is a better way to do this, comment here.

Thanks,
Alex Stf
> 0 votes

# Answer
> Is this possible? path: 'booking/{url\_alias}' or path: '{url\_alias}/booking'

`path: '{url_alias}/booking'` paths can never start with a slug/placeholder.

You'll have to use `path: 'booking/{url_alias}'`

In your form:

```
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $url_alias = NULL) {

    // Some DB query to check if $url_alias is the 2nd path of an alias.
    // In other words, check if "/rooms/$url_alias" exists.

    if ($db_query == false) { // if $url_alias is not the 2nd path of an alias.
       throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
    }

    // Your Form code goes here

    return $form;
  }

```
> 1 votes

# Answer
Use more placeholders in your route, like

```
path: 'booking/{url_alias}/{anyother}'

```

Then add a default for the last one, like

```
defaults:
  anyother: ""

```

Now your Path applies for two and three uri components.

Check this page for default parameters in form - routes: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes
> 1 votes

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


# Question
Title: How do I override the subscription block?
I am developing a Drupal 8 website and I want to override the subscription block used by the Simplenews module. I know how to achieve that at Drupal 7, but the module is different now. For Drupal 7, I followed http://api.worldempire.ch/api/simplenews/theme%21simplenews-block.tpl.php/7-2.

I want to do the same for Drupal 8. How can I achieve it?

# Answer
> 0 votes
There is no exact equivalent currently. To override the actual block template for that block you can use 'block--simplenewssubscription.html.twig'. You can use the input and form templates to override other elements. I would suggest enabling debugging in Twig so you can see the template overrides.

---
Tags: 8, emails
---


title: Drush sql-dump with stored procedures

text:
# Question
Title: Drush sql-dump with stored procedures
According to the current documentation I don't think this is possible, or is it? (`drush sql-dump --routines` doesn't work or anything like that)

Aaaannndd... let's say it's not possible, and I want to add this feature to drush sql-dump command, how can I do that? Where should I start?

# Answer
I got it working for MySQL with the `extra` option:

```
$> drush sql-dump --extra="--routines"

```

References:
> 1 votes

---
Tags: database, drush
---


# Question
Title: setup Drupal with Docker: clone repositories via deploy token
I am quite new working with docker. I tried to set up drupal via docker and docker-compose. So far i got a running instance and installed drupal via the installation script.

No i want to clone repositoires via the Dockerfile, which is a drupal module. So after cloning and rebuilding the module should appear in the admin/modzles page)

So i edited my `Dockerfile` so it looks like this (the last few lines).

```
FROM drupal:7-apache

RUN apt-get update && apt-get install -y \
        curl \
        git \
        mysql-client \
        vim \
        wget

RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \
        php composer-setup.php && \
        mv composer.phar /usr/local/bin/composer && \
        php -r "unlink('composer-setup.php');"

RUN wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.4.2/drush.phar && \
        chmod +x drush.phar && \
        mv drush.phar /usr/local/bin/drush

RUN rm -rf /var/www/html/*

COPY apache-drupal.conf /etc/apache2/sites-enabled/000-default.conf

WORKDIR /app/web/sites/all/modules
RUN git clone -b <branch> --single-branch \
      https://<deploytoken>:<pw>@<gitlab-address>/<path-to-git-rep>.git \

WORKDIR /app

```

This is my `docker-compose.yml`

```
version: '3'
services:
  db:
    image: mariadb:10.2
    environment:
      MYSQL_DATABASE: drupal
      MYSQL_ROOT_PASSWORD: <pswd>
    volumes:
      - db_data:/var/lib/mysql
    restart: always
  drupal:
    depends_on:
      - db
    build: .
    ports:
      - "80:80"
    volumes:
      - ./app:/app
    restart: always
volumes:
  db_data:

```

Then i used docker-compose build and docker-compose up. It looks like the repository gets cloned and the latest images is used (no errors) but the repository is not in the folder. What did i do wrong?

# Answer
> 1 votes
The way I handle this is creating a gitlab auth.json file and with your token and using a volume mount to put it into the container.

```
volumes:
  - /Users/${USER}/.composer/auth.json:/home/wodby/.composer/auth.json # composer auth

```

In some instances I've wanted my ssh keys in there as well for certain operations, but shouldn't be needed for a pull off gitlab. This is just as easy.

```
volumes:
- /Users/${USER}/.ssh/id_rsa:/home/wodby/.ssh/id_rsa # ssh

```

---
Tags: 7
---


# Question
Title: entity_autocomplete field thats added by ajax is not working
I have a field im adding to a node-edit form by ajax. the field is a simple taxonomy auto-complete field.

when I add it directly in my form\_alter it works, but when it's added by ajax, The autocomplete is not there - the field looks and behaves as a simple text field.

I have edited my question and added my code.

```
 use \Drupal\Component\Utility\NestedArray;

function MM_field_widget_MW_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context){
        $element['display_id']['#ajax'] = [
          'callback' => 'getAjaxArgumentsFields',
          'wrapper' => $id . 'arguments',
          'method' => 'replace',
          'event' => 'change',
        ];
        $display_id = $element['display_id']['#default_value'];
        $element['options']['arguments'] = get_argument_fields($display_id); //Works, with entity_autocomplete working

}

function getAjaxArgumentsFields(&$form,  \Drupal\Core\Form\FormStateInterface $form_state){
      $display_id = $form_state->getTriggeringElement()['#value'];
      $fields = get_argument_fields($display_id);
      NestedArray::setValue($form, $array_parents, $fields);
      return  NestedArray::getValue($form, $array_parents); //Returns the exact same fields, but no autocomplete functionality- they appeare and behave like a regular text field
}

function get_argument_fields($display_id){
      $args_field = [];
      $argument_definition = get_argument_definitions($display_id);
      $args_field = [
              '#type' => 'entity_autocomplete',
              '#title' => $argument_definition['title'],//Taxonomy term
              '#target_type' => $argument_definition['type'],//taxonomy_term
              '#default_value' => '',
              '#selection_settings' = [
                     'target_bundles' => $argument_definition['bundles'],//voc_name
               ],
      ];
     $args_field['#prefix'] = '<div id = "' . $id . 'arguments' . '">';
     $args_field['#suffix'] = '</div>';
     return $args_field;
}

```

What do you guys think could be the reason? Thank you!

# Answer
> 2 votes
Ok, So thanks to 4k4 I now understand what i was doing wrong, and for the favour of everyone that will meet this issue again:

The form\_alter is invoked as well when ajax callback is invoked. by the time the execution got to my ajax callback (getAjaxArgumentsFields) the form\_alter has already altered my form, so all i had to do was return the fields without changing them. Here is the code that worked for me:

```
use \Drupal\Component\Utility\NestedArray;

function MM_field_widget_MW_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context){
    $element['display_id']['#ajax'] = [
      'callback' => 'getAjaxArgumentsFields',
      'wrapper' => $id . 'arguments',
      'method' => 'replace',
      'event' => 'change',
    ];
    $display_id = $element['display_id']['#default_value'];
    $element['options']['arguments'] = get_argument_fields($display_id); //here I change my field, both on load of the page and also before ajax
}

function getAjaxArgumentsFields(&$form,  \Drupal\Core\Form\FormStateInterface $form_state){
    $array_parents =  clac the path to the wanted field
    return  NestedArray::getValue($form, $array_parents);
}

function get_argument_fields($display_id){
      $args_field = [];
      $argument_definition = get_argument_definitions($display_id);
      $args_field = [
          '#type' => 'entity_autocomplete',
          '#title' => $argument_definition['title'],//Taxonomy term
          '#target_type' => $argument_definition['type'],//taxonomy_term
          '#default_value' => '',
          '#selection_settings' = [
                 'target_bundles' =>
           $argument_definition['bundles'],//voc_name
           ],
           ];
      $args_field['#prefix'] = '<div id = "' . $id . 'arguments' . '">';
      $args_field['#suffix'] = '</div>';
      return $args_field;
}

```

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


# Question
Title: How can I add a cancel button to the content add form for a single content type?
I have several content types on a site and most of them are user-editable but not user-creatable. However, one content type, **Image**, allows users to upload a picture. Sometimes, however, users upload the wrong picture and they panic because they don't want that picture to be submitted to the site.

Of course they could always hit the browser's *back* button, but I'd like to add a **Cancel** button for additional assurance.

I found this thread that gives various solutions for adding cancel buttons on Drupal.org as well as this feature request for adding a cancel button to D8. However, there are several different general approaches and I don't know how to limit one to a given content type (in this case, my\_image).

# Answer
I would use the following code.

```
function mymodule_form_my_image_node_form_alter(&$form, &$form_state) {
  // If the node is being created, redirect the users to the page where
  // they can choose the content type for a new node; otherwise, redirect
  // them to the page showing the node.
  $destination = (!isset($node->nid) || isset($node->is_new)) ? 'node/add' : "node/{$node->nid}";

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );
}

```

### Notes

* markup is the default form element type; there is no need to use `#type = 'markup'`.
* In the node edit form, all the buttons are inside `$form['actions']`. The weights used from the buttons that form is using are 5 (Save), 10 (Preview), and 15 (Delete). I used 20 to show the link after those buttons, but you can change its weight to show it in a different position.

```
// Add the buttons.
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
  '#value' => t('Save'),
  '#weight' => 5,
  '#submit' => array('node_form_submit'),
);
$form['actions']['preview'] = array(
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED,
  '#type' => 'submit',
  '#value' => t('Preview'),
  '#weight' => 10,
  '#submit' => array('node_form_build_preview'),
);
if (!empty($node->nid) && node_access('delete', $node)) {
  $form['actions']['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#weight' => 15,
    '#submit' => array('node_form_delete_submit'),
  );
}

```
* There isn't the need to use `arg()` to understand if the form is for editing an existing node, or for creating a new one. I checked `!isset($node->nid) || isset($node->is_new)` is `TRUE`, to verify the node is being created. Drupal seems to simply check `empty($node->nid)`, even though node\_object\_prepare() uses `!isset($node->nid) || isset($node->is_new)`.
* If `$_GET['destination']` is set, the link added with `l()` will point to that path.
> 10 votes

# Answer
Each node form has its own unique id. It's consisted of node type's machine name followed by `_node_form`. So your `my_image` node type's form id is `my_image_node_form`

Here's a mock untested function (D6) to illustrate how to implement:

```
function HOOK_form_alter(&$form, &$form_state, $form_id) {
  $types = array(
    'my_image',
  );

  foreach($types as $type) {
    if($type.'_node_form' == $form_id) {
      if(arg(1) == 'add') {
        // If adding node link to node/add screen
        $link = l(t('Cancel'), 'node/add');
      }
      elseif(arg(2) == 'edit') {
        // If editing node, link to node view screen
        $link = l(t('Cancel'), 'node/'.arg(1));
      }
      $form['cancel'] = array(
        '#type' => 'markup',
        '#value' => $link,
        '#weight' => 0,
      );
    }
  }
}

```

If using Drupal 7 then change `#value` on the array to `#markup`.
> 7 votes

# Answer
All those solutions are for adding Cancel **link** not a **button**!

If you want to add the button instead of a link you should use this code for module `cancel_button.module`:

```
function cancel_button_form_alter(&$form, &$form_state, $form_id) {
    // node types for which Cancel button should be added
    $types = array(
      'biography',
      'faq',
      'draftlaw',
      'vocabulary',
      'draftlaw_page',
      'encyclopedia',
      'user', // if you want to add user's edit form too
    );

    foreach($types as $type) {
        if($type.'_node_form' == $form_id || $type.'_profile_form' == $form_id) {
            $form['actions']['cancel'] = array(
                '#type'   => 'submit',
                '#value'  => t('Cancel'),
                '#access' => TRUE,
                '#weight' => 55,
                '#submit' => array('cancel_button_form_cancel', 'node_form_submit_build_node'),
                '#limit_validation_errors' => array(),
                );
            }
        }
    }

    /**
     * cancel_button callback.
     */
    function cancel_button_form_cancel($form, &$form_state) {
        $link = '';
        $path = 'node';
        if('user_profile_form' == $form['#form_id']){
            $path = 'user';
        }
        if(arg(1) == 'add') {
            // If adding entity link to [user|node]/add screen
            $link = $path . '/add';
        }
        elseif(arg(2) == 'edit') {
            // If editing entity, link to node view screen
            $link = $path . '/' . arg(1);
        }
        $url = $_GET['destination'] ? $_GET['destination'] : $link;
        drupal_goto($url);
    }

```
> 7 votes

# Answer
```
function mymodule_form_my_image_node_form_alter(&$form, &$form_state) {
  // If the node is being created, redirect the users to the page where
  // they can choose the content type for a new node; otherwise, redirect
  // them to the page showing the node.
  $destination = (!isset($node->nid) || isset($node->is_new)) ? 'node/add' : "node/{$node->nid}";

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: Can I use Flysystem with backup_migrate?
I would like to use Backup & Migrate for my Drupal 8 site. Is there a way to use Flysystem for backups? Should I install S3FS?

I have Flysystem configured to handle all of my files and images to be saved and served from an S3 bucket. I do not see any capability to add an S3 bucket to Backup and Migrate.

I did install and enable S3FS but do not see the configuration for backup files only.

# Answer
To answer your title's question: No, because the files are stored in your S3 bucket. You don't need to backup these files because Drupal reads them from your S3 bucket's server. Since your files are not stored locally, you don't need to migrate them, ever.

If you're paranoid about losing your S3 files, have a read, Backup strategies for AWS S3 bucket.
> 0 votes

---
Tags: 8, backups
---


# Question
Title: Why are my users are being forced to reset passwords on almost every login?
After logging out of my site, after about 30 minutes, each user's password is reported to be invalid -- that is, they cannot login with their existing passwords and are forced to use the reset link.

This happens almost every time and happens absolutely every time after a certain period of time.

This is an extremely frustrating problem to diagnose -- I'm not even sure where to start. Any suggestions?

I'm on Drupal 7.50 using a bootstrap 3 subtheme -- heartbeat controls some features.

# Answer
> 1 votes
Out of the box, Drupal does not have a way to force reset password automatically for users, I am guessing there must of use of any contributed module or there might be custom module written.

One of the contributed module which could do this is Force Password Change, can yu check if you have this module enabled? If so disabling the module or changing the configuration could help, also can you list down all the enabled non-core modules you have, you can get the list by running the following drush command, that will help in identifying if there is any such module used.

```
drush pm-list --type=Module --no-core   --status=enabled

```

# Answer
> 0 votes
Drupal by default only allows login by Username. Many users expect to login by email. They can use their email to reset password. You can add the ability to login via username and email with Super Login module

---
Tags: users
---


# Question
Title: When installed in a subdirectory clean URLs don't work
I have my Drupal installation in the subdirectory with the following config file

```
server {
    listen 80;
    server_name example.com

    root /var/www/example;

    access_log /var/log/nginx/example_access.log;
    error_log /var/log/nginx/example_error.log;

    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }
    location ~ ^/sites/.*/private/ {
        return 403;
    }
    location ~ ^/sites/[^/]+/files/.*\.php$ {
        deny all;
    }
    location ~* ^/.well-known/ {
        allow all;
    }
    location ~ (^|/)\. {
        return 403;
    }
    location /manage/d7/ {
        index index.php
        try_files $uri /index.php$query_string;
    }
    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }
    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }
    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        include fastcgi_params;
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
       fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }
    location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
        try_files $uri @rewrite;
    }
    location ~ ^(/[a-z\-]+)?/system/files/ { # For Drupal >= 7
        try_files $uri /index.php?$query_string;
    }
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        try_files $uri @rewrite;
        expires max;
        log_not_found off;
    }
}

```

Clear url does not work with the above configuration and i am unable to figure out what is causing the issue. Clean urls work with the same configuration if the Drupal install was in the root directory but when moved to the subdirectory, clean urls do not work, please help me figure out the issue.

# Answer
Found the solution. Need to specify the Location to the subdirectory. Changing the following confix fixed the issue

```
location /manage/d7/ {
    try_files $uri /manage/d7/index.php$query_string;
}

location @rewrite {
    rewrite ^/manage/d7/(.*)$ /manage/d7/index.php?q=$1;
}

```
> 0 votes

---
Tags: installation
---


# Question
Title: How to show forums even if you don't have access?
This is a follow up to this question.

I now know how to modify which forums are shown using the MYMODULE\_preprocess\_forum\_list hook. But I have another scenario I can't figure out.

When you create a forum taxonomy term, you can use Forum Access module to set which users can access which forums. I have:

* a board called "premium"
* a role called "premium

Only premium members can access this board and this works great. But I still want the premium board to show on the forum landing page. When the user clicks on it, it must tell them they don't have access.

A workaround would be to simply give users access to those forums. Then the forum will display. Then write some other hook or chunk of code that actually stops the user when he clicks through to those pages. But it really feels to me like this should just be setting somewhere.

Am I missing something, or is my suggested solution the best route to go?

**UPDATE**

My problem could be solved if I could add another option to the screen below that says: "View Posts in this Forum"

Then i can specifically allow them to see the posts, but not actually click through to them.

# Answer
Implementing custom permissions in Drupal 8:

https://www.aram.cz/article/custom-permissions-drupal-8

You should be able to use static permissions, which are configured in a YAML file in your custom module. From the article:

> To declare static permisisons, you need to create a file in the root directory of your custom module and name it `YOUR_MODULE.permissions.yml`.

```
'sample permission 1':
  title: 'First level permission'
  description: 'Gives first level permission to the users.'

'sample permission 2':
  title: 'Second level permission'
  description: 'Gives second level permission to the users.'

'sample permission 3':
  title: 'Third level permission'
  description: 'Gives third level permission to the users.'
  restrict access: true

```

Then you can check for that permission in PHP code like so:

```
if (\Drupal::currentUser()->hasPermission('sample permission 1')) {
  // The "sample permission 1" has been granted to the current user.
}
else {
  // The "sample permission 1" has NOT been granted to the current user.
}

```

I'm not sure exactly how you'll use this technique in your situation to allow users to see only a summary of forum post titles without the ability to click through and see the individual forum posts, but hopefully it will set you on the right track.
> 0 votes

---
Tags: 8
---


# Question
Title: Unit Testing code that retrieves content
I have a method which calls another one to retrieve a specific node ID. If it can be found, it then retrieves the node.

Is this the kind of functionality that can be tested in Drupal? Or even should it tested? If so what is the best approach for it?

```
private function retrieve() {
  // Call another method to get IDs of specific bundle based on its workflow status. We get just one ID back as there is only one node for this bundle.

  // If statement to validate we do have a node ID.
  // Call method to retrieve content for node based on the retrieved `nid`
  // Return node content if any has been found

  // If no content is found return FALSE.
}

```

# Answer
> 1 votes
By definition, when unit testing your function you should focus on the logic the unit delivers, which, in your case, is the following conditional logic:

```
IF (nid IS NOT FOUND) OR (a node for a found nid HAS NO CONTENT)
  => FALSE
ELSE
  => NODE.CONTENT

```

That being said, you could:

1. Mock the two internally-used methods:
    * methodA:
        + CaseA1: returns an empty result (no nid found)
        + CaseA2: returns X as a nid
        + CaseA3: returns Y as a nid
    * methodB:
        + CaseB1: Given X as a parameter returns an empty result (no content found)
        + CaseB2: Given Y as a parameter returns some dummy content
2. Assert that the `retrieve()` method returns for each of the following cases:
    * CaseA1: FALSE
    * CaseA2+CaseB1: FALSE
    * CaseA3+CaseB2: TRUE

This is not very "deep" testing, but your function does not carry much logic. It is still testable in this minimal way.

Good luck!

# Answer
> 0 votes
Yes, it can be tested, but if the purpose is just checking if a module you are developing is able to find a node created locally, that is quite what the `NodeLoadMultipleTest` class does.

```
  public function testNodeMultipleLoad() {
    $node1 = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
    $node2 = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
    $node3 = $this->drupalCreateNode(['type' => 'article', 'promote' => 0]);
    $node4 = $this->drupalCreateNode(['type' => 'page', 'promote' => 0]);

    // Confirm that promoted nodes appear in the default node listing.
    $this->drupalGet('node');
    $this->assertText($node1->label(), 'Node title appears on the default listing.');
    $this->assertText($node2->label(), 'Node title appears on the default listing.');
    $this->assertNoText($node3->label(), 'Node title does not appear in the default listing.');
    $this->assertNoText($node4->label(), 'Node title does not appear in the default listing.');

    // Load nodes with only a condition. Nodes 3 and 4 will be loaded.
    $nodes = $this->container->get('entity_type.manager')
      ->getStorage('node')
      ->loadByProperties(['promote' => 0]);
    $this->assertEqual($node3->label(), $nodes[$node3->id()]->label(), 'Node was loaded.');
    $this->assertEqual($node4->label(), $nodes[$node4->id()]->label(), 'Node was loaded.');
    $count = count($nodes);
    $this->assertTrue($count == 2, new FormattableMarkup('@count nodes loaded.', [
      '@count' => $count,
    ]));
    // Omissis.
  }

```

if the purpose is not testing a functionality very specific of the module, for example retrieving a node created on a remote site, I would not write a test for verifying the module is able to retrieve a node.
Notice that also the Workflows and the Content Moderation modules (included in Drupal core) have their own tests. Chances are there is already a test for the functionality you want to test, if you want to load nodes with specific workflow states.

---
Tags: 8, testing
---


title: Translating english node to spanish

text:
# Question
Title: Translating english node to spanish
How to create a Spanish version of node which is in English and that Spanish version of node should contain all fields from English content except one field. That one field should translate to Spanish Lang

# Answer
> 0 votes
Besides adding Spanish language in your site Regional settings (with Locale module from Drupal core) you need to install the Internationalization module.

Internationalization module comes with a lot of submodules. Read about them in the documentation: Submodules and see if some of them are useful to your multilingual setup.

The Synchronize translations submodule is the one you want where you can set that some fields are the same for all languages.

---
Tags: 7, i18n-l10n
---


# Question
Title: Exclude taxonomy term from view display except its own?
I work on a news publisher site and I need help excluding a taxonomy term from view but still to keep it with its own page.

E.g. Our content is organised by theme and region. For one set of articles I've added a certain tag to it. I would like to exclude articles with this tag from all region and theme view display pages, but still maintain a page with only this tag's view display. So that these certain articles will not display on the theme and region displays (though they are organised into such categories), but still display on the tag page.

So exclude tag: xyz from all pages except www.site.com/xyz

My problem is that when I filter criteria for the tag, it removes all articles from the tag's own landing page.

It would be simpler to just not give these certain articles regions and themes, but we need these to be organised as such on the back end and for future use.

Thank you in advance!!

# Answer
> 0 votes
You seem to be on D7 and using the default Taxonomy term Views.

Out-of-box Taxonomy term Views is set up to cover all taxonomy Vocabularies you create on your site.

You can override this to "split" that functionality into more than one View, that have different settings, and control which Views is responsible for displaying which Term pages.

BTW I find it best to disable the original Taxonomy terms view, Duplicate (Clone) it and work on the Duplicate so I always have the original to reference back to.

On D7 this is usually done with the help of the Taxonomy display module although this module only provides a convenient interface for adjusting each term, but it doesn't provide the "splitting" on the Views level.

You'll have to create the second View yourself, and edit the original Taxonomy term views to exclude that special term yourself.

In the original Views you can add another Contextual filter, set it to the fixed value of the ID of your xyz term, and under `More` set to `Exclude`. This way no articles tagged with this term will appear on other term pages.

Clone the Taxonomy terms Views, name it meaningfully, and override values for the Contextual filter to only show content for the xyz term (I'm guessing ti will again be the fixed default value, but without Exclude).

You mention regions and themes a lot, but that is not how you usually control filtering in Views. So if you have more than one View listing content where you want to exclude the special xyz tagged content, you'll have to edit each view to filter out that content. There is no easy way to filter according to theme regions that I'm aware of.

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


# Question
Title: Fetch live data (json) and make accessible to javascript or javascript library (React)
I've built a service that returns data from an external API (in JSON format).

I do not want to render that directly onto a page or store it in a node but rather make it accessible to javascript/jquery/React for further processing.

# Answer
> 1 votes
This is possible in Drupal without Drupal knowing anything about it. I have done things like this before in Twig templates:

```
{% if node.field_myfield is not empty %}
  <script>
    var request = new XMLHttpRequest();
    request.open("GET", "/api/v1/auth/" + {{ node.id }} + '?s=' + Date.now());
    request.responseType = "text";
    request.onload = function() {
      document.getElementById("authorize-banner").innerHTML = request.response;
    };
    request.send();
  </script>

  <div id="authorize-banner"></div>
{% endif %}

```

Where `request` is basic JS making a request to the Drupal backend (custom route) which handles the request and assembles the response, which is then written to the div below. Nothing is saved anywhere.

Here is a similar example, again in Twig, but this time there is no backend processing at all, React handles it:

```
<div class="js-search-mountnode" data-id="listing"></div>
<script>
var config = {
    id: 'listing',
    api: '{{ your_url_variable }}',
    type: "listing",
    showCalendar: true,
    showClear: true,
    showNewKey: false,
    showResultsSummary: true,
    dictionary: {
    resultsTitle: "Filter Search",
    facetsTitle: "Filter Search",
    facetsDescription: "Projects in this search date approx 3 years back.",
    searchBoxLabel: "Title, Number or Keyword",
    singleresult: "result",
    pluralresult: "results"
    }
};
window.listingConfigs = window.listingConfigs || [];
window.listingConfigs.config = config;
</script>

```

Without going into a lot of detail, the React component loads and fires a request to the `api` value in the config object (props) attached here, and React generates the entire display within the div as a React component. Again, nothing is stored or saved, both happen on load.

That said, you don't want it to render in a page (but won't it eventually, if its a React component?) - you could just request it directly in Javascript without putting it anywhere else, or from a non-Drupal site by doing the same.

---
Tags: javascript
---


# Question
Title: How to change the length of field from 255 to ilimit?
i have a field in web site but lenght limit this is field is 255 , but client wants to puts more caractere to that field i want to change field  from 255 to ilimit . any help please

# Answer
I don't think you can increase the length of a field within Drupal once there is data in the field.

Instead, go into your entity bundle and make a new field with a larger character limit.

Then, copy the data from the old field to the new field. There are several ways to accomplish this (programmatically with PHP; directly in the database with SQL queries; via database export and import; using Drupal Migrate API; or with the help of contrib modules such as Feeds / Feeds Tamper.)

If there are not too many nodes of your content type, you might find it simpler to just copy and paste from the old field to the new field manually.

No matter which approach you choose, be certain to verify that the data is good in the new field before deleting the old field.
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: How to include book traversal links on a custom twig template page
1. I use the Book module to create books with chapters.
2. When I use the default twig template `node.html.twig` to display a book chapter, a section titled "Book traversal links" is included, with links to the previous chapter, the next chapter, and to the book. The debugger says these links come from the `book-navigation.html.twig` template.
3. Instead of the default template, I'm using a custom twig template `node--chapter.html.twig` to display chapters.

QUESTION:

How can I get the same book traversal links onto my custom page?

NOTES:

1. I checked for a block containing the book traversal links that I could just insert in my twig template, but I don't see one.
2. I have checked the $variables array in the twig template to see if maybe a list of the chapter's siblings is already there, but don't see one.
3. I'm already using HOOK\_preprocess\_node(&$variables) to find the book parent book's id, so I can use it to find the chapter's siblings, if that's the way to go.

# Answer
Alas, there is no block for this; the book navigation links are hacked on to the node view in core.

From **core/modules/book/book.module**:

```
/**
 * Implements hook_ENTITY_TYPE_view() for node entities.
 */
function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $book_node = Node::load($node->book['bid']);
      if (!$book_node->access()) {
        return;
      }
      $build['book_navigation'] = [
        '#theme' => 'book_navigation',
        '#book_link' => $node->book,
        '#weight' => 100,
        // The book navigation is a listing of Node entities, so associate its
        // list cache tag for correct invalidation.
        '#cache' => [
          'tags' => $node->getEntityType()->getListCacheTags(),
        ],
      ];
    }
  }
}

```

The good news is that this should work with custom templates as long as you are using the *full* view mode.

I have a custom node template and I still get the navigation links on my books at the bottom of the content. (Unfortunately, whether I want them there or not-- as per the above code, they are forcibly added and there is no UI to control them.)
> 0 votes

# Answer
You can code the book navigation into your own block.

In this case, you will need to override `book_node_view()` so that the nav links are not displayed twice.

This may give you an idea (not complete code, cannot be used by itself; inspired by this post):

```
class BookNavigationBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    $node = \Drupal::routeMatch()->getParameter('node');
    if (isset($node)) {
      if ($node->bundle() == 'book') {
        $build['book_navigation'] = [
          '#theme' => 'book_navigation',
          '#book_link' => $node->book,
          '#weight' => 100,
          // The book navigation is a listing of Node entities, so associate its
          // list cache tag for correct invalidation.
          '#cache' => [
            'tags' => $node->getEntityType()->getListCacheTags(),
          ],
        ];
      }
    }
    return $build;
  }

```
> 0 votes

---
Tags: 8, theming
---


title: Import po-files using Drush

text:
# Question
Title: Import po-files using Drush
I have about 20 sites that have a common translation. I don't want to go into admin of each site each time the po-file is updated.

Is it possible to import a po-file using Drush?

# Answer
> 25 votes
I found a way to do this using Drush and Localization Update.

1. Install Localization Update `drush en l10n_update`
2. Configure a local path for po-files (admin/config/regional/language/update)
3. Configure automatic updates from remote servers or just local sources

Now you can put your own po-files in a local path (for example sites/all/translations). If you have translations for your own module then you name it according to this naming convention:

modulename-version.language.po

So a Swedish po-file for 'my\_module', version 7.x-1.1 would be named:

my\_module-7.x-1.1.sv.po

Now you have everything setup and you can start updating your sites translation with Drush:

```
drush l10n-update-refresh # Looks for new po-files
drush l10n-update # Updates translations

```

# Answer
> 3 votes
At the moment there's no way to do it with Drush but you can use the Localization Update module.

You could also try using Selenium IDE or a Selenium script if you have a lot of sites. This is the best solution I was able to come up with for getting translations as an exportable.

* I say there's no way to do it with Drush because I opened a feature request in the issue queue a few weeks ago and it was closed as "won't fix" with the reason that the maintainers think such a command should be tested in the i18n or other modules first before integrating it into the Drush trunk.

# Answer
> 1 votes
Also, the drush module Drush Language Commands has support for importing and exporting po files.

# Answer
> 1 votes
Your best bet is to use the Potx Exportables module.

It exposes Drush command `drush potx-import-all`

# Answer
> 1 votes
For those who lands here many years later, the same commands for Drush 9 are:

1. drush locale:check
2. drush locale:update

---
Tags: drush, i18n-l10n
---


# Question
Title: How can I print a referenced media extension
I am working in the node template. In my content type I have a referenced field to media called 'field\_event'. I created a new media type called 'document'. Inside document there is a file upload field called 'field\_document'. I need to print the file name, size and extension all separately in table cells. Example: Myfile | 80kb | pdf

This renders the file, link and name.

```
{{ content.field_event }}

```

Gives me: mypdf.pdf 80.00 KB, This is the name of my pdf

This prints out only the name

```
{{ node.field_event.entity.name.value }}

```

Gives me: This is the name of my pdf

How can I get the file extension? I have tried these.

```
{{ node.field_event.document.entity.field_document.entity.filesize.value }}

{{ node.field_event|field_target_entity.field_mime_type.value }}

{{ node.field_event|field_target_entity.field_mime_type.entity.filemime.value }}

```

I am using twig tweak

# Answer
```
{% set extension = node.field_event.entity.filemime.value|split('/') %}
{% set extensionDot = '.' ~ extension[1] %}

// File name
{{ node.field_event.entity.filename.value|replace({extensionDot : ''}) }}

// File size
{{ node.field_event.entity.filesize.value / 1000|round }}KB

// File extension
{{ extension[1] }}

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to apply Image Style with no effects and lazy load image?
We have two content types (Articles and Basic Page) that use the same Image (field\_image) field. We are using the lazysizes js library where you need to add `class="lazyload"` and `data-src="image-url.png"` on the `<img>` tag.

For the Article Content type only we want to be able to lazyload the images, but we want to do in a way that does not impact the Image field on the Basic Page content type.

We initially thought that the best way to do this was to assign an Image Style with no effects and then use the `mytheme_preprocess_image` hook to do the following below.

Is this the correct way to modify the `<img>` element the way we need to? The goal is to be able to lazyload the original image without modifying it (no scalling, resizing, cropping, etc.).

```
function mytheme_preprocess_image(&$vars) {
  $lazy_loading = [
    'lazy_load_image_style' // Machine name of Image Style.
  ];

  if(in_array($vars['style_name'], $lazy_loading) {
    // Copy src into data-src.
    $vars['attributes']['data-src'] = $vars['attributes']['src'];
    unset($vars['attributes']['src'];

   // Add css class.
   $variables['attributes']['class'] = 'lazyload';
}

```

# Answer
It may be easiest to use Blazy or Image Lazyloader.

If neither of those suit your needs, I would create a new field formatter class. In your custom module create a new formatter `src/Plugin/Field/FieldFormatter/LazyImageFormatter.php` that extends Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter.php. You'll need to use the same annotation that formatter has, but then you'll only need to implement the viewElements method. Begin the method by calling `$elements = parent::viewElements($items, $langcode);`. Traverse `$elements` afterward and update the render array similar to how you have done above. Make sure to `return $elements;` when you're done.

This will give you a formatter on the manage display screens that you can select on whichever image fields you want on any view mode of any entity. You can even get it to work with any image style selected via your new formatter.

If you've never extended a Drupal 8 plugin check out the plugin api. Once you know how to create and extend one plugin type it's very similar process to create or extend others and you'll quickly find that the world is yours.
> 1 votes

# Answer
I've built a lazy load module for drupal 8. Should work out-of-the-box: Fancyload - lazy load images pinterest-style

> Fancyload will automatically provide lazyloading of images on your website in a pinterest-style color scheme. It fetches the main color of your image and serves it until your image is loaded.
> 0 votes

---
Tags: 8, hooks, media
---


# Question
Title: How can I protect development sites with Basic Auth module enabled?
During development phase a dev site should be protected from being browsable by unauthorized visitors. Usually I use Basic Auth configured in the web server. This way the only information an unauthorized visitor gets is the domain name.

Drupal 8 uses Basic Auth or OAuth for REST (no Cookie method).

If you want to protect dev sites and use REST with Basic Auth you have a problem. Usually, you setup the webserver to use Basic Auth, as said above. But with Basic Auth module enabled Drupal triggers a 403 Access Denied because Drupal tries also to process the Basic Auth header.

Problems:

* The header goes also to Drupal, that tries to use it, giving you a 403 because webserver Basic Auth doesn't match with Drupal users.
* If you use two Basic Auth headers (one for the webserver or external layer, another for Drupal when consuming the REST services) you have you tweak your REST service consumers to send those two headers. Also, your webserver or external layer should remove the right header and pass header that Drupal should use.

**Obvious solutions**

* (Use always OAuth for REST services) It seems that OAuth uses Authorization header too so not a solution.
* Use other method to protect the dev site than Basic Auth.

Any other way to accomplish this?

**NOTE**: Clients have no static IP and can't use a VPN to connect (this is mainly because customers must be able to check the dev site).

# Answer
> 0 votes
Time has passed and now I've found a simpler approach: use Shield module

> PHP Authentication shield. It creates a simple shield for the site with Apache authentication. It hides the sites, if the user does not know a simple username/password. It handles Drupal as a "walled garden". This module helps you to protect your (dev) site with HTTP authentication.

Its configuration allows to whitelist certain paths. REST paths can be whitelisted because they already have their own authentication mechanism. It works with Apache or any other web server.

Note that the whitelist functionality is only available as a patch in Drupal 8.

# Answer
> 1 votes
The steps are as follows:

* Modify .htaccess to read `DirectoryIndex index.html index.php`
* Construct your index.html file to show whatever you need.
* Modify your robots.txt to disallow any search engine robots to index your site.

Clients can check http://www.example.com/index.php whenever they like, and you can revert your .htaccess and robots.txt when you are done.

# Answer
> 0 votes
> During development phase a dev site should be protected from being browsable by unauthorized visitors.

One, out of the box, solution is to put the site in maintenance mode (`/admin/config/development/maintenance`). So **only admins** can view/browse the site.

To login you have to manually go to `/user/login`

# Answer
> 0 votes
> This answer not solve several problems: info about site is leaked because you see the maintenance mode page that usually have a company log and other info. Also, you can only browse the site or consume the REST services as admin user, so you are unable to test/check the site with others users (for example, permissions are an issue as admin by pass all of them). You can mitigate this giving permissions to browse the site to ohter users, but you are at the end modifyng the real behavior of your site. The protection should be transparent for the site.

Fair enough, then you should use

### Maintenance Exempt

> Drupal allows you to set your site into maintenance mode in order to deploy code and database upgrades safely. However, access to the site during maintenance mode is by default controlled by a permission, which is generally only given to administrative users. It's not possible to test the site as a regular anonymous or authenticated user without giving all anonymous/authenticated users the "Use the site in maintenance mode" permission, so you generally have to test those things on the fly after moving the site back to "live" mode.
>
> **Until now, that is! This D7+ module (the necessary hook doesn't exist in D6 and below) allows specific people to perform the necessary testing on the site with all role combinations without opening the site up to all of your visitors.**

Now, if you don't want the logo to show up in your maintenance mode page then

Copy **maintenance-page.html.twig** located in `/modules/system/` and paste it in `/sites/all/themes/[your theme]/templates` folder.

Then edit the file and delete the `{{ logo }}` and anything else you want. Perhaps everything?

# Answer
> 0 votes
If you want to "***Use other method to protect the dev site than Basic Auth.***", you may want to have a look at my answer to the question about "How to make the permissions of a module more granular?". It uses (only) the Rules module, for which this is the summary of the included rule:

* **Rules Event**: Drupal is initializing.
* **Rules Conditions**: Check if it is an anonymous user and verify if they try to visit some URLs they do NOT have access to.
* **Rules Action**: Redirect those who meet the Rules Conditions to "some other URL instead" (with some informational message about it).

By adapting the URLs used in these Rules Conditions and Actions, you might be close to what you're looking for.

This rule works perfectly in Drupal 7, but I haven't tested it in a Drupal 8 setup yet. But maybe it's worth experimenting with the most recent dev version of Rules for Drupal 8 (to build a similar rule).

**Note**: if you're looking for something like "***URL param with a certain value***" (as in your own answer), you might also want to consider the Rules URL argument module. Refer to my answer to "How to make the Rules module perform a redirect to an URL that includes a query string?" for more details on that.

# Answer
> 0 votes
The only solution I see is use an external layer like Varnish or Nginx that comes before Drupal. This layer can check for a magic key (URL param with a certain value, a cookie or a custom header). If magic key is present, the external layer removes the magic key and delivers request to the back end, that's Drupal. If magic key is not present this external layer should return 403.

This external layer can check for IP, range or whatever methods to also easy the dev life.

A diagram:

This way:

* Site is absolutely private unless you have the magic key, no site info is leaked.
* No Authorization header conflict.
* Can be bypassed easily adding the cookie, URL param or header on the client. For non technical users the URL param should be used. In this case the external layer could also add a cookie with the magic key when this param is detected. So next requests pass through thanks of this added cookie.
* Transparent for Drupal: Drupal never knows.

Drawbacks:

* You have to setup the external layer.
* You have to supply a magic key on the requests. This can be cumbersome for non technical clients.

# Answer
> 0 votes
Drupal 8 basic\_auth module cannot be combined with other Basic Auth solutions. Check this core issue. The Shield module copes witht the question like this.

# Answer
> -1 votes
> Use other method to protect the dev site than Basic Auth.

Trying to keep thins as simple as possible, you may take advantage of the Drupal user permission setting. In your case, create roles you need (maybe developer, tester, themer, etc ) and give them access to content as per your needs. Once done, give no access to anonymous users. This can be done by a few lines of custom code or contrib modules (example https://www.drupal.org/project/content\_access )

Thanks for your feedback

---
Tags: 8, staging, users
---


title: Make CKEDITOR Caption Required

text:
# Question
Title: Make CKEDITOR Caption Required
Using Drupal 8 Ckeditor Core plugins -\> drupalimage/drupalimagecaption how do I make an image caption required? The checkbox shown should always be clicked.

# Answer
The CKEditor image dialog is a form, so you can change it via Drupal Form API with `hook_form_alter`:

```
/**
 * Implements hook_form_alter().
 */
function MyModule_form_alter(&$form, $form_state, $form_id) {
  // Check if the form is editor_image_dialog.
  if ($form_id == 'editor_image_dialog') {
    // Make caption required.
    $form['caption']['#required'] = TRUE;
    // Change default_value to true.
    $form['caption']['#default_value'] = TRUE;
  }
}

```
> 2 votes

---
Tags: 8, input-formats
---


# Question
Title: How to load a taxonomy term with case-sensitive?
I used this

```
    $this->termStorage->loadByProperties(['name' => 'test']);

```

I got two terms: `Test, test.` I want to get only one: `test`

This is working without case-sensitive:

```
    $this->termStorage->getQuery()->condition('name', 'test', '=')->execute();

```

```
    \Drupal::database()->select('taxonomy_term_field_data', 't')
      ->condition('t.name', 'test')
      ->fields('t', ['name'])
      ->execute()
      ->fetchAll();

```

```
    \Drupal::database()->query("SELECT name FROM taxonomy_term_field_data WHERE name='test'")->fetchAll();

```

# Answer
> 6 votes
To retrieve result with sensitive case, you can use **binary** in where clause:
Like this sql query.

`SELECT name FROM taxonomy_term_field_data WHERE binary name='test'`

For Drupal you can use `\Drupal::database()->select` with where conditions take a look here .

Try this:

```
 $result = \Drupal::database()->select('taxonomy_term_field_data', 't')
    ->where(
      'binary name = :term_name',
      ['term_name' => 'test']
    )
    ->fields('t', ['name'])
    ->execute()
    ->fetchAll();

```

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


title: Error: Class 'Drush\Sql\Sql' not found

text:
# Question
Title: Error: Class 'Drush\Sql\Sql' not found
This is my first attempt at installing Drupal using Composer. I have successfully installed Composer and the Drupal Project template, which comes configured with Drush. To install I use

```
composer create-project drupal-composer/drupal-project:~8.0 {dir} --stability dev --no-interaction

```

Next, when I try to install Drupal using Drush with

```
../vendor/bin/drush site-install --db-url=mysql://{username}:{password}@localhost/{database}

```

I receive this error

```
Error: Class 'Drush\Sql\Sql' not found in /Users/.../vendor/drush/drush/src/Sql/SqlBase.php on line 81

```

I have installed Drush and Composer locally. I have tried requiring drush again after the composer install. I have tried using Drush 9.2.3. SO, If I go through the manual install of Drupal, Drush init does run, but any other command other than version gives me

```
In Connection.php line 149:
SQLSTATE[HY000] [2002] No such file or directory

```

I'm using:

* Composer 1.6.5
* Drush 9.3
* Drupal 8.4.5

# Answer
> 5 votes
Does your password contain a #? Try this test:

```
<?php

function test_url($url) {
    $message = (parse_url($url) === false)?"parse_url unable to parse url:
{$url}\n":print_r(parse_url($url),true);
    echo  $message;
}

test_url("mysql://user:password@site/database_name");
test_url("mysql://user:C0mPl3XP4ss@site/database_name");
test_url("mysql://user:Ci)(*$!@@site/database_name");
test_url("mysql://user:pass#word@site/database_name");
?>

```

The last URL example fails to be parsed. This appears to be coming from

```
vendor/drush/drush/src/Sql/SqlBase.php:dbSpecFromDbUrl().

```

I hit the same issue and traced it to a '#' in my MySQL user password. Changed the password to remove the '#' and everything is working.

# Answer
> 0 votes
I had a similar issue on Windows 10. I didn't notice where the issue was coming from at first because I had Drush installed both globally and locally. After uninstalling drush globally, I noticed drush was not found anymore. After adding my local drush to my PATH I finally managed to launch the site install command.

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


# Question
Title: Using different .inc files with same function names in .module file
In our project, we have this module meant strictly for our custom API endpoints for our mobile applications to use. Currently, this is handled in a single .module file like so:

**my\_project\_mobile\_api.module**

```
<?php

function my_project_mobile_api_menu() {
  return array(
    'api/v1/user/register' => array(
      'page callback' => 'account_register',
      'access callback' => 'user_is_logged_in'
      'type' => MENU_CALLBACK
    ),
    ...
  );
}

function account_register() {
  ... logic to create an account
}

```

Up until now, this has worked great for us, but now we need to add a V2 of the API. My idea was to extract all of the page callback functions (like `account_register`) into their own `.inc` file. This would look like this:

**my\_project\_mobile\_api.module**

```
function my_project_mobile_api_menu() {
  return array(
    'api/v1/user/register' => array(
      'page callback' => 'account_register',
      'access callback' => 'user_is_logged_in'
      'type' => MENU_CALLBACK
    ),
    'api/v2/user/register' => array(
      'page callback' => 'account_register',
      'access callback' => 'user_is_logged_in'
      'type' => MENU_CALLBACK
    ),
    ...
  );
}

```

**my\_project\_mobile\_api.v1.inc**

```
function account_register() {
  ... logic to create an account
}

```

**my\_project\_mobile\_api.v2.inc**

```
function account_register() {
  ... logic to create an account (this logic differs from that of V1)
}

```

How can I make sure that my `.module` uses the right `account_register` function from the correct `.inc` file? Is there a way to specify the `file` in the `api/v1/user/register` array?

# Answer
You can use `file` key in your menu like:

I assume you have a **includes** directory contain both files `my_project_mobile_api.v1.inc` and `my_project_mobile_api.v2.inc` and both files contain `account_register` function.

Your `hook_menu` should be like the following.

```
function my_project_mobile_api_menu() {
  return [
    'api/v1/user/register' => [
      'page callback'   => 'account_register',
      'access callback' => 'user_is_logged_in',
      'type'            => MENU_CALLBACK,
      'file'            => 'includes/my_project_mobile_api.v1.inc',
    ],
    'api/v2/user/register' => [
      'page callback'   => 'account_register',
      'access callback' => 'user_is_logged_in',
      'type'            => MENU_CALLBACK,
      'file'            => 'includes/my_project_mobile_api.v2.inc',
    ],
  ];
}

```

You can also use `'file path'` if you files not in the same module take a look at this example.
> 2 votes

---
Tags: 7, files
---


# Question
Title: is there a way to generate dummy content for paragraphs?
I am working in Drupal 8. Is there any way, with devel, to generate dummy content for paragraphs to visually get a feel for how things would look? Is there a module or script to accomplish that might work?

# Answer
Paragraphs need a host entity to work normally iirc, so if the paragraph is attached to a node type through a reference field, I've had success creating them with Drupal console's node generator: `drupal create:nodes` which seems to populate all the fields it can.

Beware though: I've had to `drupal create:terms` first to generate a few taxonomy terms, or else the node generation takes ages! Your laptop may take off before the process finishes ;)
> 2 votes

---
Tags: 8, paragraphs
---


# Question
Title: How to embed drupal content in other sites (remove X-Frame-Options: SAMEORIGIN)?
I tried to make a iframe with a drupal page but I received the following message:

> Multiple "Refused to display (page adress) in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'."

Then, I tried to change the header of response in page controller using

`$response->headers->set('X-Frame-Options', 'GOFORIT');`

And I received the following message

> Multiple 'X-Frame-Options' headers with conflicting values ('GOFORIT, SAMEORIGIN') encountered when loading '(page adress)'. Falling back to 'DENY'.

Drupal core puts the following code in all responses.

`$response->headers->set('X-Frame-Options', 'SAMEORIGIN', FALSE);`

So, how can I override the X-Frame-Options header for only this response to embed this page in other sites?

I'm using Drupal 8.0.0.

# Answer
The `X-Frame-Options` header seems to have been added to Drupal 8 in order to prevent click-jacking: https://www.drupal.org/node/2514152

According to the notification above, in order to embed your Drupal site in other sites,

> a new Response Subscriber needs to be added that has a higher priority as the current FinishResponseSubscriber (see core.services.yml) to overwrite or remove the header - depending on the use case

It also provides a code example:

```
<?php
    $path = $request->getPathInfo();

    if (strpos($path, '/fb-app/') === 0) {
      $request->headers->remove('X-Frame-Options');
    }
?>

```
> 5 votes

# Answer
Drupal 8 adds the response header `X-Frame-Options: SAMEORIGIN` to all pages. This prevents that the content is included in iframes on third party sites.

You can check this for example in the google image search that your content does not appear in the preview frame.

This feature was introduced in drupal 8 beta 13.

The change record

Core is now protected against click-jacking by default (X-Frame-Options: SAMEORIGIN)

is not correct in that the priority has to be higher, in fact it has to be lower. The code example changes the request but it has to change the response.

To provide a solution to the question here is the complete code including the yaml file to put this in the service container:

`mymodule/src/EventSubscriber/RemoveXFrameOptionsSubscriber.php`:

```
<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RemoveXFrameOptionsSubscriber implements EventSubscriberInterface {

  public function removeXFrameOptions(ResponseEvent $event) {
    $response = $event->getResponse();
    $response->headers->remove('X-Frame-Options');
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['removeXFrameOptions', -10];
    return $events;
  }
}

```

`mymodule/mymodule.services.yml`:

```
services:
  remove_x_frame_options_subscriber:
    class: Drupal\mymodule\EventSubscriber\RemoveXFrameOptionsSubscriber
    tags:
      - { name: event_subscriber }

```
> 30 votes

# Answer
4k4 give great solution, but also may be

> $response-\>headers-\>set('X-Frame-Options', 'ALLOW-FROM https://ALLOWED.SITE/');

better then

> $response-\>headers-\>remove('X-Frame-Options');
> 8 votes

# Answer
It is very simple to override the headers from `.htaccess` with a single statement

```
Header set X-FRAME-OPTIONS "ALLOWALL"

```

**Alternativelly** you can make it only apply on certain condition using if statement apache expressions

```
<If "%{QUERY_STRING} =~ /embed/">
    Header set X-FRAME-OPTIONS "ALLOWALL"
</If>

```

and then you can call your URL adding `embed` in your query string

```
https://domain.com/yoururl?param1=true&embed

```

For this to work you will need **apache 2.4** or greater and **headers** module enabled. If not enabled you perhaps you can enable them with

```
sudo a2enmod headers
sudo service apache2 restart

```
> 4 votes

# Answer
There's now a downloadable module for Drupal 8: X-Frame-Options Configuration

> This module can be used to set the x-frame-options header on your website with the appropriate directive. This might be useful when you want to include one of the pages of your site inside an iframe in another site.
>
> The directives must be:
>
> 1. DENY
> 2. SAMEORIGIN
> 3. ALLOW-FROM uri (Currently \[2018-10-25\] not accepted by chrome nor Safari). You will be allowed to configure which uri.
> 4 votes

# Answer
For newer browsers the `ALLOW-FROM uri`-settings would not work anymore, see "allow-from uri (obsolete)"-section in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

You need to add

`$response->headers->set('Content-Security-Policy', 'frame-ancestors https://ALLOWED.SITE/');` in addition to what wakh.ru proposed:

`$response->headers->set('X-Frame-Options', 'ALLOW-FROM https://ALLOWED.SITE/');`
> 2 votes

---
Tags: 8
---


# Question
Title: Altering Views Exposed Form Elements and their Associated Labels
I have a series of Views Exposed Forms across a Drupal 8 website. My goal is to generate unique template suggestions so I can theme each individual input and their labels differently as needed.

Here is my current approach. Placed into theme.theme. I've hit a brick wall.

```
function HOOK_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $form['#attributes']['twig-suggestion'] = $form['#id'];
}

function HOOK_theme_suggestions_input_alter(&$suggestions, array $variables) {
    $element = $variables['element'];

    if (isset($element['#attributes']['twig-suggestion'])) {
      $suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['twig-suggestion'];
    }
}

function HOOK_theme_suggestions_form_element_label_alter(&$suggestions, &$variables, $hook) {
    $element = $variables['element'];

    if (isset($element['#attributes']['twig-suggestion'])) {
      $suggestions[] = 'label__' . $element['#attributes']['twig-suggestion'];
    }
}

```

All input and label \[#attributes\] are null via Kint.
Here are the URLs I have referenced for background:

1) http://kevinquillen.com/drupal/2017/01/28/adding-twig-template-suggestions-for-form-elements

2) https://www.chapterthree.com/blog/how-to-create-custom-theme-suggestions-drupal-8

3) https://yellowpencil.com/blog/getting-granular-with-drupal-eight-forms/

# Answer
> 0 votes
1. Should add `#attributes` to your element form so the form alter should be like:

```

function HOOK_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $form['name_of_element']['#attributes']['twig-suggestion'] = $form['#id'];
}

```
2. `HOOK_theme_suggestions_input_alter` will works only with input elements `textfield`.

# Answer
> -1 votes
```
/*
*  hook_form_views_exposed_form_alter
*/
function THEMENAME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-global-search-default'){
    $form['#attributes']['class'][] = 'row popup-form';  //add form class
    $form['combine']['#attributes']['class'][] = 'search_input';  //add class to input
    $form['combine']['#attributes']['placeholder'][] = t('Search...');
    $form['combine']['#theme_wrappers'] =  [];  //remove the extra stuff
    $form['actions']['submit']['#attributes']['class'][] = 'search_icon button';  //add class to button
  }
}

```

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


title: Using variables in an expression

text:
# Question
Title: Using variables in an expression
I am checking for a specific block in a specific theme region.

```
{% if page.header_first.blockmachinename %}
   // Show stuff
{% endif %}

```

This works when I have the right machine name. But I want to be able to use a variable in place of `blockmachinename`.

Something like this, which of course doesn't work.

```
{% if page.header_first.{{ the_variable }} %}

```

This also didn't work, as expected

```
{% set block_name = 'page.header_first.' ~ the_variable %}
{% if block_name %}

```

Any clues?

# Answer
> 3 votes
Since the dot syntax can mean a lot of different things, try to make it more clear by using the array syntax:

```
{% set the_variable = 'mytheme_myblock' %}

{% if page.header_first[the_variable] %}

```

# Answer
> 1 votes
you were very close ! try twigs "in" . for explanation see https://stackoverflow.com/questions/8319011/if-a-true-or-b-true-statement

```
// remove the first line obviously.
{% set  blockmachinename  = 'hello' %}
{{ blockmachinename }}

{% set full_block_name = 'page.header_first.' ~ blockmachinename %}

{{ full_block_name }}

{% if full_block_name in ['page.header_first.hello'] %}

    <h1>Cool things go here.</h1>
{% endif %}

```

---
Tags: 8, theming
---


# Question
Title: Facet block is not getting display on search page created by view
I am using the Search API module with an Apache SOLR server. On my search page, the search results are rendering properly, but the content type facet block is not getting render in any defined region.

I followed the same steps as mentioned in Enable facets.

Is there any version compatibility issue?

I am using the following versions of the dependent modules.

* drupal/search\_api 1.14
* drupal/facets 1.4
* drupal/search\_api\_solr 3.7
* drupal/search\_api\_autocomplete 1.2

# Answer
It's working now. There was an issue with context which was overriding block layout property and that's the reason facet block was not rendering on the page.

Summary: If you are using context on the page then block layout property will not work for rendering the block. So need to configure block in the context.
> 0 votes

---
Tags: 8, search
---


# Question
Title: How to stop download in hook_file_download
I'm building a page with different download buttons linked to private zip files. Users have to log in to download. I am using module Permissions by Term to manage who can see which button.
I added a field to user entity to log each download. In hook\_file\_download() I check, if and how often this file is already downloaded by this user. Up to here everything works fine.
I want to stop or block the download and show a message to the user, if download counter reaches 5 or 10. Is hook\_file\_download the right hook to achieve this?

# Answer
> 1 votes
I have this to check that the users has remaining downloads or redirect them to an upgrade page.

```
/**
 * Implements hook_file_download().
 */
function mymodule_file_download($uri) {
  // Check if user is logged in
  if (\Drupal::currentUser()->isAuthenticated()) {
    // Load entity of current user
    $current_user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    // Check if current user is: access || student || (professional && trial_actived)
    $download_control = $current_user->hasRole('professional') && $current_user->field_user_free_trial->value == 'trial_actived' ? TRUE : FALSE;
    $download_control = $download_control || $current_user->hasRole('access') || $current_user->hasRole('student') ? TRUE : FALSE;

if ($download_control) {

  // Declare files that decrease the counter
  $controlled_uris = [
    'private://mechanisms/files',
  ];

  // Check if requested uri matches with controlled uris
  foreach ($controlled_uris as $c_uri) {
    if (strpos($uri, $c_uri) !== FALSE) {

      // Check if user still has remaining downloads
      if ($current_user->field_user_download_counter->value > 0) {

        // Decrease user downloads counter
        $current_user->field_user_download_counter->value--;
        $current_user->save();
      }
      else {
        // Prepare redirect url to the prices page
        $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 39])->toString();

        // Set message
        $message = t('Your account has reached the maximum limit of downloads.');
        \Drupal::messenger()->addWarning($message);

        // Send response to url
        $response = new \Symfony\Component\HttpFoundation\RedirectResponse($url);
        $response->send();
      }
    }
  }
}
  }
}

```

---
Tags: 8, hooks
---


# Question
Title: Hide certain field on form alter using AJAX
I have a webform created using interface, and need to hide some fields through button. Using form\_alter I have added that button added AJAX call with it. Now I want to remove/hide certain element using that button and AJAX.

Below is the sample code

```
function xyz_user_signup_form_webform_submission_form1_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

  $form['#attached']['library'][] = 'xyz/xyz.global';

  $form['start'] = [
      '#type' => 'button',

      '#ajax' => [
        'callback' => 'xyz_user_signup',
       ],
      '#value' => t('START >>'),
  ];

}

function xyz_user_signup(array &$form, FormStateInterface $form_state) {

    $elements = &WebformFormHelper::flattenElements($form['elements']);

    $elements['field1']['#access'] = FALSE;

    return $elements;
}

```

On clicking start button I want to hide field1.

# Answer
> 2 votes
Your AJAX needs to have a target ID where it will put your AJAX output. You declare that ID in the `wrapper` key.

**In your form\_alter**

```
  '#ajax' => [
    'callback' => 'xyz_user_signup',
    'wrapper' => 'load-me-here-id', // This element is updated with this AJAX callback.
   ],

```

Then you need to wrap the field with this ID so AJAX replaces it.

```
 $form['elements']['field1']['#attributes'] = ['id' => 'load-me-here-id'];

```

**In your ajax callback**

```
return $elements['field1']; // so it doesn't return the entire form.

```

---
Tags: 8, ajax, webforms
---


# Question
Title: How can I create a patch for a contrib module or core which is not in version control?
Because we use a devOps system that installs packages on the server via Composer, my core drupal installation and contrib modules are not in version control (Git).

I used to patch modules as follows:

* Commit everything, so my branch is up-to-date.
* Make my changes to the module (= write the fixes in the module).
* Inside my code editor go to Code -\> Create patch and follow the steps there (because of Git, my editor knows what has changed).
* My patch gets saved where I prefer to do it.

Since we started working with keeping modules and core out of Git I do not have a clue on how to create my patches anymore.

Curious about the solutions you might have!

# Answer
> 22 votes
So, you would have to download the module seperately, like:

```
git clone --branch 8.1.x http://git.drupal.org/project/colorbox.git

```

Then, you make the change and run the following:

```
git diff 8.1.x > colorbox-css-issue.patch

```

This creates a patch for this module. Now you can place the patch in a patches folder and add it to your composer.json file. Source: This blogpost

**Update**: created a small tutorial in this video

---
Tags: 8
---


# Question
Title: How to add a local image file to an image field programatically
I have serveral image files in the folder /sites/subsite.example.com/files/blog.dir/1/gallery1, and I need to add these files to a node programatically. I think this is the right code:

```
 use Drupal\node\Entity\Node;
 use Drupal\file\Entity\File;

  $node = Node::load(1);
  $uri = 'public://image.jpg'; <--- this is my problem

  // check first if the file exists for the uri
  $files = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => $uri]);
  $file = reset($files);

  // if not create a file
  if (!$file) {
    $file = File::create([
      'uri' => $uri,
    ]);
    $file->save();
  }

  $node->field_image[] = [
    'target_id' => $file->id(),
    'alt' => 'Alt text',
    'title' => 'Title',
  ];

  $node->save();

```

What I don't know is how must be the $uri I need to put when my files are in a subdomain directory in a mulitsite drupal installation.

# Answer
> 1 votes
`public://` is the `Public file system path` that you can set in `/admin/config/media/file-system`.

In your case it would probably be `sites/subsite.example.com/files`.

To get the image you must then use, `public://blog.dir/1/gallery1/image.jpg`, where `public://` is the same as `sites/subsite.example.com/files`.

---
Tags: 8, files
---


title: Check access to existing plugin block

text:
# Question
Title: Check access to existing plugin block
I have a programmatical plugin block defined in theme region. I need to check access to this block in my module hook. The following code creates a new instance, but I need to load an existing plugin block from the theme with its custom visibility settings and find out if it is going to be displayed or not.

```
$block_manager = \Drupal::service('plugin.manager.block');
$config = [];
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
$access_result = $plugin_block->access(\Drupal::currentUser());

```

Please advise.

# Answer
Loading a block should be in theme context, because block visibility configured by theme, here is an example to how load `system_breadcrumb_block` block in your active theme.

```
   use Drupal\block\Entity\Block;
    // Get block ids.
        // This will return block ids by theme like the following
        /*  [
              "bartik_breadcrumbs" => "bartik_breadcrumbs"
              "seven_breadcrumbs" => "seven_breadcrumbs"
            ]
        */
        $ids = \Drupal::entityQuery('block')
          ->condition('plugin', 'system_breadcrumb_block')
          ->execute();
        // Get the active theme name.
        $active_theme_name = \Drupal::service('theme.manager')
          ->getActiveTheme()
          ->getName();
        $my_block_id = '';
        foreach ($ids as $id) {
          // Check the if the id start with theme name.
          if (strpos($id, $active_theme_name) === 0) {
            $my_block_id = $id;
          }
        }
        // Load Block.
        $block = Block::load($my_block_id);
        // Get the block visibility array
        // Something like
        //    [
        //      "user_role" => [
        //        "id"    => "user_role",
        //        "roles" => [
        //          "administrator" => "administrator",
        //        ],
        //      ],
        //    ]
        $visibility = $block->getVisibility();
        $currentUser = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        /**
         * TODO: Do your visibility check
         */
        // Example to check if the user has the access by role
        $has_access = FALSE;
        if ($visibility['user_role']['roles']){
          foreach ($visibility['user_role']['roles'] as $role => $name){
            if ($currentUser->hasRole($role)){
              $has_access = TRUE;
            }
          }
        }
        dpm($has_access);

```
> 0 votes

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


title: sql-dump piping output to the screen

text:
# Question
Title: sql-dump piping output to the screen
I am trying to dump a remote Drupal site to a local SQL dump file. In Drush 8 this worked a treat:

```
drush @site.alias sql-dump > ~/Dumps/dumpy.2019-02-19.sql

```

Now, if I run this command in Drush 9 (9.4.0) I see the raw SQL just printed on the screen.

If I add `2>&1` to the command, this does not help.

If I add a `--result-file=` this creates a file on the remote server (not what I want).

Does anyone have any ideas here?

# Answer
> 9 votes
The output on the screen is caused by a bug in Drush.

From https://github.com/drush-ops/drush/issues/4004#issuecomment-479155241:

> The problem is that Drush is setting tty mode even though output is redirected. This is wrong.

**Workaround 1** via the command line:

```
drush -Dssh.tty=0 @site.alias sql-dump > ~/Dumps/dumpy.2019-02-19.sql

```

**Workaround 2** via the YAML file that defines the remote, as suggested at https://github.com/drush-ops/drush/issues/4004#issuecomment-500157166:

> For anyone coming across this issue. I had a similar problem with Drush 9.7.0 where sql:dump output was sent to standard output instead of a file. Based on the above workaround, I fixed it with the 'ssh' option in the drush alias of the remote site:

```
site.alias:
  ssh:
    tty: 0

```

---
Tags: drush
---


# Question
Title: Where are the webform files in the D8 directory?
I'm trying to manually update the D8 webform module but cannot find any directory, folder, or file named webform. Where are the webform module files located?

# Answer
> 0 votes
We can install the modules in (root/modules/contrib) as webform is contributed module.

But by default, all contrib modules are in (root/core/modules/webform.)

---
Tags: webforms
---


# Question
Title: Losing SSH access to Acquia Cloud: "permission denied (publickey)"
Sometimes, when working on an Acquia Cloud project, I seemingly spontaneously lose git access on the AC server. This might be related to switching between multiple workstations while working on the project. When I try to run a git command, I get

`Permission denied (publickey).
fatal: Could not read from remote repository.`

I have not changed my keys related to this project.

# Answer
I haven't determined the root cause of this issue, but I found a functional solution:

When I get this issue, rather than in my IDE I ssh to AC via the Acquia Dev Desktop interface (clicking the small terminal icon next to the SSH address). This runs a specific SSH connection with several options:

`ssh -p 22 -i "/Users/username/.ssh/acquia_key_name" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null sitename.dev@server.devcloud.hosting.acquia.com`

After this command is run (in my case in Mac Terminal), I can access the git repo again via my IDE.
> 3 votes

# Answer
I was having a similar issue with connecting to Acquia Cloud within my vagrant box. After reading the above solution I managed to get the connection to work by running the following from my home directory:

```
ssh -p 22 -i ".ssh/acquia_key_name" sitename.dev@server.devcloud.hosting.acquia.com

```

Then I ssh-ed back into my vagrant box and managed to connect
> 0 votes

---
Tags: acquia-dev-desktop
---


# Question
Title: dump $variables in theme_preprocess functions
In theme\_preprocess functions (e.g. theme\_preprocess\_block, theme\_preprocess\_menu, etc) there is the $variables argument.

In Drupal 7 I could look at this variable using devel module and typing dpm($variables).

How I can do that in Drupal 8?

I tried kint, dump and var\_dump, but for all of them I get a fatal error memory exhausted.

# Answer
The best way would probably be a breakpoint with xdebug turned on. Which requires configuration efforts though.

What I was normally doing in similar cases was a step-by-step approach. I was printing out `$variables` keys first and then narrowing my var\_dump with a specific key. E.g. `var_dump($variables['key'])`. Slowly but surely.

In the end I think that in terms of efforts it is way better to set up debugger and use breakpoints to inspect variables.
> 1 votes

# Answer
Best approach for this is to use print step by step. Use echo ''; var\_dump($variables); This will fetch the result in readable format.
> 0 votes

---
Tags: 8, debugging, theming
---


# Question
Title: Generate PDF with wkhtmltopdf after batch finished
I would like to generate a pdf with wkhtmltopdf at the end of my batch.

I integrate the generation in the callback function but it does not offer me the download of the file

This is my finished function:

```
function csm_generate_pdf_finished($success, $results, $operations) {
  $message = 'some errors';

  if ($success) {
    if (($library = libraries_load('phpwkhtmltopdf')) && !empty($library['loaded'])) {
      $pdf = new WkHtmlToPdf();
      $html = $results['data'];
      $start = $results['start'];
      $end = $results['end'];
      $pdf->addPage( $html );

      $filename = 'document_'.$start.'_'.$end.'.pdf';

      $pdf->send($filename);

      $message = 'Generation PDF ok';
    }
  }
  drupal_set_message($message);
}

```

# Answer
The Finish function runs in the background and you can't return file there, the solution for your case is redirected to another page and create and return pdf file there.

something like `drupal_goto('your_custom_url_to_generate');`
> 1 votes

---
Tags: 7, batch-operations
---


# Question
Title: Override a theme template variable with a module
I created two variables for use in my theme's page templates. I used variables because I wanted that value to be flexible.

```
function mytheme_preprocess_page(&$variables) {
  $variables['var1'] = 'value1';
  $variables['var2'] = 'value2';
}

```

Without creating a new `page.html.twig` template, I want to choose new variables in `mymodule`. Like, maybe...

```
function mymodule_preprocess_page(&$variables) {
  $variables['var1'] = 'newvalue1';
  $variables['var2'] = 'newvalue2';
}

```

This isn't working. I have a feeling it's because themes get priority? Any ideas?

Edit: I should clarify. How do I do this?

# Answer
> 3 votes
Taking the lead from @Alfred Armstrong above and my colleague, this ended up working!

In `mytheme.theme`

```
function mytheme_preprocess_page(&$variables) {
  if(!isset($variables['var1'])) {
    $variables['var1'] = 'defaultvalue1';
  }
}

```

In `mymodule.module`

```
function mymodule_preprocess_page(&$variables) {
  $variables['var1'] = 'myvalue1';
}

```

---
Tags: 8
---


title: notify user account creation?

text:
# Question
Title: notify user account creation?
I can't seem to find documentation for notifying a user via email after their account has been created by a script.

```
$user = \Drupal\user\Entity\User::create();

$user->setPassword('xxx');
$user->enforceIsNew();
$user->setEmail('xxx+'.time().'@gmail.com');
$user->setUsername('xxx'.time());

$user->set('init', 'email');
$user->set('langcode', $language);
$user->set('preferred_langcode', $language);
$user->set('preferred_admin_langcode', $language);
$user->activate();

//$user->notify()? something?

$result = $user->save();

```

# Answer
> 2 votes
You can find the configuration on admin in the `/admin/config/people/accounts` but if you want to notify the user programmatically without taking care of what is the config you can use `_user_mail_notify` function.

\_user\_mail\_notify documentation

---
Tags: 8, users
---


# Question
Title: If content type with specific field that is not empty has specific taxonomy term attach library
I would like to attach a specific library using a taxonomy term to a content type with a specific field that is not empty. The following is not working:

```
function lehigh_preprocess_page(&$variables) {
// Via taxonomy term: If the landing page is a node and has taxonomy
via a field named field_taxonomy
$current_route = \Drupal::routeMatch();
$node = $current_route->getParameter('node');
$target_taxonomy_id = 123;
   if ($node->getType() === 'standard_content_page') && $node->hasField('field_section') && !$node->get('field_section')->isEmpty()) {
     if ($node->get('field_section')->referencedEntities()[0]->id() == $target_taxonomy_id) {
     $variables['#attached']['library'][] = 'lehigh/financialaid';
}
}
}

```

# Answer
> 0 votes
Try the following , and don't forget to clear the cache

```
function lehigh_preprocess_page(&$variables) {
    $current_route = \Drupal::routeMatch();
    $node = $current_route->getParameter('node');
    $target_taxonomy_id = 123;
    if (isset($node) && $node->getType() == 'standard_content_page'
        && $node->hasField('field_section')
        && !$node->get('field_section')->isEmpty()) {
        if ($node->get('field_section')->referencedEntities()[0]->id() == $target_taxonomy_id) {
            $variables['#attached']['library'][] = 'lehigh/financialaid';
        }
    }
}

```

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


# Question
Title: Custom Entity is only showing via admin theme
I implemented a custom content entity with Drupal console. By default the routing is done in JobListingEntityHtmlRouteProvider.php file. I am getting a standard path such as /admin/structure/my\_custom\_entity/id.

I tried to use URL alias pattern to change it such as /my\_custom\_entity/id. That worked but still give me the admin theme upon viewing the entity. I did defined a themable custom twig template but it's not picking it up.

I also changed \_admin\_route to FALSE in JobListingEntityHtmlRouteProvider.php routing file. No go.

Any help appreciated.

# Answer
> 3 votes
As 4k4 said in the comments, the route is being generated using the link template in the entity annotations. Changing these link templates should be how you set the path to any custom entity page. For future content entities, drupal console will use the base path specified in this step: `Enter the base-path for the content entity routes [/admin/structure]`

---
Tags: theming, entities
---


title: How can I display tags on one line

text:
# Question
Title: How can I display tags on one line
How to change the below output of a drupal article Tags display with bootstrap theme

To something like this which is displayed in stackoverflow below any questions

Is there a ready made module available, I know this can be achieved using JS tagEditor plugin for jQuery

I tried to use `Expert` Field format mode in `Display Suite` by setting `span` for the item tag, it is not working

# Answer
I solved this using below CSS

```
.field--name-field-tags .field--item {
   display: inline;
}

.field--name-field-tags .field--item a,
.field--name-field-tags .field--item a:visited,
.field--name-field-tags .field--item a:active,
.field--name-field-tags .field--item a:hover {
   color: #fff;
   background-color: #ff5588;
   padding: 1px 5px 1px 5px;
   border-radius: 3px;
}

```

which gave this output

I used Asset Injector which is easy online edit
> 0 votes

---
Tags: 8, theming, taxonomy-terms
---


# Question
Title: Content Moderation: Editorial workflow not installed and broken/missing handler on the moderated content view
I'm having troubles enabling Content Moderation Module (content\_moderation) on a Drupal 8.7.8 site.

During installation everything seems fine, `drush en content_moderation` finishes without errors, workflows module is already enabled before.

After install the editorial workflow is missing, but it's possible to create a new content moderation workflow.

All role permissions are available and the Moderation State widget shows up on nodes of the selected types. But using the widget has no effect, nodes don't get published or unpublished.

The database tables for Content Moderation are created properly (ie. content\_moderation\_state and three more with similar names).

Also the **view moderated\_content** shows "**Broken/missing handler**" where the filter criteria "**Content revision: Moderation state (exposed)**" and "**Content revision: Moderation state (\<\> Published)**" are supposed to be.

Clicking the Broken/missing handler fields shows some details for the two broken handlers:

```
The handler for this item is broken or missing. The following details are available:
id: moderation_state_1
table: node_field_revision
field: moderation_state
relationship: none
group_type: group
admin_label:
operator: not in
group: 1
exposed:
is_grouped:
entity_type: node
plugin_id: moderation_state_filter
Enabling the appropriate module may solve this issue. Otherwise, check to see if there is a module update available.

```

Second field shows this info:

```
id: moderation_state
table: node_field_revision
field: moderation_state
relationship: none
group_type: group
admin_label:
operator: in
group: 1
exposed: 1
is_grouped:
entity_type: node
plugin_id: moderation_state_filter

```

I also can't add any moderation state related fields to the view like "Moderation state". The fields do not show up in the "Add fields" dialog.

I'm having no problems setting up Content Moderation on a vanilla Drupal 8.7.8 it just fails on this existing site (same version).

I already tried reverting the site and reinstalling workflows and content\_moderation on different ways, with drush and manually. I uninstalled all custom modules and patches and reinstalled content\_moderation.

Are there any modules (except workbench) or settings known to cause problems with Content Moderation?

Any ideas what could be causing the problem or where to start looking?

Thanks a lot!

# Answer
> 2 votes
The guys over at Drupal's Slack channel pointed me in the right direction. I added detailed troubleshooting infos to the Content Moderation Guide.

If you enable Content Moderation (drush en content\_moderation) on a site, that was not installed using Drupal's Standard Profile as a base, you will run into some problems which require a few manual steps before you can use Content Moderation, as detailed in the guide.

**Fix missing Editorial workflow**

If the Editorial workflow was not created when enabling Content Moderation, you can either manually create a new workflow and assign a content type, that's used with your new workflow or import the Editorial workflow manually.

The template for the Editorial Workflow is:

```
langcode: en
status: true
dependencies:
  module:
    - content_moderation
id: editorial
label: Editorial
type: content_moderation
type_settings:
  states:
    archived:
      label: Archived
      weight: 5
      published: false
      default_revision: true
    draft:
      label: Draft
      published: false
      default_revision: false
      weight: -5
    published:
      label: Published
      published: true
      default_revision: true
      weight: 0
  transitions:
    archive:
      label: Archive
      from:
        - published
      to: archived
      weight: 2
    archived_draft:
      label: 'Restore to Draft'
      from:
        - archived
      to: draft
      weight: 3
    archived_published:
      label: Restore
      from:
        - archived
      to: published
      weight: 4
    create_new_draft:
      label: 'Create New Draft'
      to: draft
      weight: 0
      from:
        - draft
        - published
    publish:
      label: Publish
      to: published
      weight: 1
      from:
        - draft
        - published
  entity_types:
    node: null
  default_moderation_state: draft

```

Copy the template to some yml file and import it using drush config:import --partial.

**Fix Broken/missing handler on the Moderated Content view**

This error occurs, if there exists no moderation workflow that is assigned to a content type. Wether you just imported the Editorial workflow as described above or created a custom moderation workflow, you'll have to make sure it has at least one content-type assigned to it. Just edit your moderation workflow, scroll to the bottom of the page and select at least one content type that is used with this workflow. After you save your changes, the "Broken/missing handler" on the Moderated Content will be gone and the view at /admin/content/moderated will work as expected.

---
Tags: installation, workflows
---