title: Why is cache_render very big?

text:
# Question
Title: Why is cache_render very big?
I am having a big problem with a newly created Drupal 8 site for a theater.

After going live we discovered that the cache\_render table grown extremely big, and extremely fast. After one weekend, it was already over 30 GB which makes a backup of the database impossible.

After some analysis and google search, I have stumbled upon cache\_render database table growing in size. They say it is wise to use a caching service such as Memcache but honestly, that does not really solve the problem at all.

I have set the Cache maximum age to 1 hour and the cache\_render page STILL sets the expiration date to infinity! Why?

What causes Drupal to fill up the database this much?

### System information

Drupal version: 8.1.0

Modules in use:

* List item
* color\_field 8.x-2.0-rc1
* contact\_block 8.x-1.1
* contact\_storage 8.x-1.0-beta4
* ds 8.x-2.3
* embed 8.x-1.0-rc2
* entity\_embed 8.x-1.0-alpha1
* entity\_reference\_revisions 8.x-1.0-rc6
* field\_group 8.x-1.0-rc4
* file\_entity 8.x-2.x-dev (2016-Apr-13)Aktuell Ok
* Google Analytics 8.x-2.0
* google\_map\_field 8.x-1.1
* imagemagick 8.x-1.0-alpha2
* layout\_plugin 8.x-1.0-alpha22
* mailchimp 8.x-1.1
* menu\_link\_attributes 8.x-1.0-beta1+5-dev (2016-Feb-23)
* metatag 8.x-1.0-beta8
* paragraphs 8.x-1.0-rc4
* smtp 8.x-1.0-alpha0
* token 8.x-1.0-alpha2
* weight 8.x-3.0
* yoast\_seo 8.x-1.0-alpha2+2-dev (2016-Mai-20)

# Answer
> 1 votes
It seems like this could be related to particular blocks or other renderable objects on your site that may have many permutations. In one case, I saw 100,000+ rows for one particular views exposed filter block.

Since users were able to select many different options, the block was stored hundreds of times per page/URL in the cache\_render table.

It's best to try to scan through the `cid` values of the table and see any patterns, e.g. with `SELECT COUNT(*) FROM cache_render WHERE cid LIKE "%interesting_cid_here%";`, to see if there are any major offenders.

Still trying to figure out the best way (besides periodically running `drush cr`) to fix this issue. ~~For now, I opened up an issue in the Drupal Core issue queue: cache\_render table becomes extremely large over time~~

See discussion around this issue in this Drupal Core issue: Make CACHE\_PERMANENT configurable in the database cache — currently allows unlimited growth: cache DB tables of gigabytes!.

# Answer
> 0 votes
> I have set the Cache maximum age to 1 hour and the cache\_render page STILL sets the expiration date to infinity! Why?

This is a core issue. You should be able to control the expiration date.

In Internal Page Cache it says:

> On the Performance page, you can configure how long browsers and proxies may cache pages; that setting is also respected by the Internal Page Cache module. There is no other configuration.

But this does not work.

You have to wait until the issue is resolved. Or you could try to set your own Expires date in a response event. If there is a date in the future, this will end up as expiration date in the cache table. See the code in this answer Anonymous user cache control.

# Answer
> 0 votes
To keep any of the cache bins (cache tables) from growing too big you can set the maximum number of rows they can have in `settings.php`

```
// max rows for cache_render table
$settings['database_cache_max_rows']['bins']['render'] = 50000;
// or any other bin
$settings['database_cache_max_rows']['bins']['dynamic_page_cache'] = 1000;

```

These settings take effect on cron run

To get appropriate values for each bin you can find out the current rows occupied using a `drush sql-query`

```
drush sql-query 'SELECT table_name AS "Table", TABLE_ROWS as "Num. of Rows", round(((data_length + index_length) / 1024 / 1024), 2) "Size in MB"  FROM information_schema.TABLES where table_schema = "DATABASENAME" and table_name LIKE "cache_%"  ORDER BY (data_length + index_length) DESC limit 10'

```

of course change `DATABASENAME` on above query

For more info about these settings see the change record or read the documentation in source of core/core.api.php or follow the whole issue and discussion

---
Tags: 8, caching
---


title: Project directory in Ubuntu

text:
# Question
Title: Project directory in Ubuntu
I am trying to get Drupal 8 installed on Ubuntu 18.04. I have installed LAMP and composer. I will install Drupal 8 with this (I think this is the latest recommended way) ...

```
composer create-project drupal/recommended-project my_site_name_dir

```

Where should `my_site_name_dir` be?

Some guides suggest it should be at apache2's web directory: `/var/www/html/my_site_name_dir`. And then change the directory owner to `www-data` (for apaches benefit?). But how then does Composer or myself write files to this directory if the owner is changed?

This guide Using Composer to Install Drupal says:

> Your 'my\_site\_name\_dir' will contain files that should be outside of your web root and not accessible by the web server. The web root will be 'my\_site\_name\_dir/web'

So am I right in thinking that `my_site_name_dir` should not be visible by apache, but `my_site_name_dir/web` should be? If so how to I tell apache to find it?

I was imaging that `my_site_name_dir` would be somewhere in my home directory (easier for dealing with file permissions?) and I would view it in a browser with something like: `http://localhost/my_site_name_dir`

(I'm struggling a bit trying to grasp file ownership and how composer works.)

# Answer
It all depends on whether your Ubuntu 18.04 machine is intended for use as a local workstation or a web server exposed to the Internet.

If it's your local workstation, you should absolutely just make a sub-directory in your home directory.

I like to keep my projects in `~/repos/clientname/projectname/` directories. I call the directory `repos` because I recommend always keeping your project in a local git repository and pushing all your changes to a private repository on github/gitlab/bitbucket or wherever. That way you can always pick up work on a new computer if yours crashes.

Your local workstation is probably not (indeed, hopefully not!) the server where you will expose your Drupal site to the Internet. You want a local copy that you can break and fix a dozen times a day without taking the real site offline.

Then, you want a way to serve that to yourself on localhost. Check out my other answer here to see one way of serving the files locally. I recommend Lando for newbies because it manages a lot of the complexity for you, providing Docker containers for web server, database server and other services as needed. And you can easily free up system resources with `lando stop` and switch to another project with `lando start`. See my linked answer for more details.

Then you can worry about deploying the site to a production server ... ideally, multiple environments for Dev, Stage (Test), and Prod (Live) environments.

There are many ways to approach this depending on your hosting. Just take things one step at a time, start with local development and work your way up to DevOps concepts like automated testing and deployment.

If your Ubuntu 18.04 installation is intended to be a web server, then you'll want to install a complete LAMP stack and set up the directories as @pinueve suggests in his answer.

There is also a middle ground. You can test deploying your site from the local dev instance in your home directory to the local Apache server, but just be aware that you can run into port conflicts between your Ubuntu host's Apache server and the Docker guest's Apache server if you try to start both at once. This can be mitigated by changing your default Apache ports.

Edit the VirtualHost entries in `/etc/apache2/sites-available/000-default.conf` and change port 80 to something like port 8080:

```
<VirtualHost *:8080>

```

If you do this, you can browse the host machine's Apache on `http://localhost:8080` and you will still be able to start and stop your Docker containers with Lando.
> 3 votes

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


# Question
Title: Why do I get a page content instead of a redirect?
I have to send a request to an external API which returns a redirection link, using the following code.

```
try {
  $response = \Drupal::httpClient()->get($url, ['headers' => ['Accept' => 'text/html']]);
  $data = (string) $response->getBody();
  if (empty($data)) {
    return FALSE;
  }
  else{
    return $data;
  }
} catch (RequestException $e) {
  return FALSE;
}

```

What I get in `$data` is the following content.

```
<!doctype html>
<html lang="en" dir="ltr" class="h-100">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="asdsad">
  <!-- CSRF Token -->
  <meta name="csrf-token" content="aaaaa1231231">
  <title>TEST</title>
  <link rel="canonical" href="tamal.com">
  <!-- Bootstrap core CSS -->
  <link href="http:xyz.css" rel="stylesheet">

```

Why do I get a page content instead of a redirect?

# Answer
> 0 votes
this actually because of the second argument **\['headers' =\> \['Accept' =\> 'text/html'\]** it tells the server to serve a plain text instead of html so your browser will end up print the text instead of parsing it as HTML,so just remove the second argument **\['headers' =\> \['Accept' =\> 'text/html'\]**

so you code will become like this one :

Code :

```
$url = 'xyz';

try {
  $response = \Drupal::httpClient()->get($url);
  $data = (string) $response->getBody();
  if (empty($data)) {
    return FALSE;
  }else{
    return $data;
  }
} catch (RequestException $e) {
  return FALSE;
}

```

---
Tags: 8
---


# Question
Title: How to get the list of fields available in the user entity
I have created a custom field to allow users to set their privacy settings based on the fields attached into their account.

I would like to get the list of fields available in the user entity so that I can create a table select form where the users can select the permission per field based on account type.

How to do it in a custom field?

Here's my curreny code:

```
  namespace Drupal\privacy_settings\Plugin\Field\FieldType;

  /**
   * @FieldType(
   *   id = "privacy_settings",
   *   label = @Translation("Privacy Settings"),
   *   description = @Translation("Privacy Settings"),
   *   default_widget = "privacy_settings_widget",
   *   default_formatter = "privacy_settings_formatter_default"
   * )
   */
  class PrivacySettingsField extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['value'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('@operation access', ['@operation' => 'Privacy Settings']));
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'value' => [
          'type' => 'blob',
          'size' => 'big',
          'serialize' => TRUE,
          'not null' => TRUE,
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function setValue($values, $notify = TRUE) {
    if (isset($values['value']['table']['rows'])) {
      $values['value'] = serialize($values['value']['table']['rows']);
    }
    parent::setValue($values, $notify);
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->get('value')->getValue();
    return $value === NULL || $value === '';
  }

  /**
   * Return the list of operations available.
   *
   * @return array
   *   The list of operations.
   */
  public function getOperations() {
   return [
      t('Account Type 1'),
      t('Account Type 2'),
      t('Account Type 3')
    ];
  }

}

```

# Answer
> 4 votes
You can get user entity field definitions list by using the following code:

```
$user_field_definitions = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions('user', 'user');
// List of user field definitions.
dump($user_field_definitions);

```

# Answer
> 0 votes
```
 //1.Getting specific 'Entity type' manager storage
$User = \Drupal::entityTypeManager()->getStorage('user');

//2. load  a specific user entity by id
// we suppose that we want to get current connected user entity
$user_id = \Drupal::currentUser();
$UserEntity = $User->load($user_id);

// 3-use this for debugging prupose to display all the entity fields
// your field should display here
kint($UserEntity->toArray());

// 4.using information collected by kint to pritnt a field using
// $UserEntity->{field_name}->{property}
// {field_name} = first lvel in array
//{property} = exsit in the nested array 2nd level
echo $UserEntity->mail->value;
echo $UserEntity->name->value;
echo $UserEntity->roles->target_id;

```

---
Tags: 8
---


title: Check if block is visible

text:
# Question
Title: Check if block is visible
I'm on Drupal 8,

I'm using `\Drupal::entityQuery('block')` to get the list of blocks.

Now I want to determine if the block is visible for:

* Current Page (Content Type)
* Current User (Role)
* Current Path

I want this information according to visibility settings configured in block's configuration.

I can use `$block->getVisibility()` method when I load the block and there I can iterate through visibility settings and find out if the block is visible or not.

I wander if there is a better and easier way to do this??

# Answer
Checking view access to a block includes visibility checks. so you can just do this: `if ($block->access('view'))`.

Why do you want this information? block.module has a block.repository service with a `getVisibleBlocksPerRegion()` which gives you exactly that. a list of visible blocks, grouped by region.
> 2 votes

# Answer
`$block->access('view')` is helping me check if a particular block is accessible on the current page or not.

I need something that can help me check block access for some other page as well. For eg., I provide `page_url` and it returns if a block is accessible on that given page or not.

Any suggestions will really help.
> 0 votes

---
Tags: blocks, 8
---


# Question
Title: Optimize Drupal Composer Workflow via Gitlab
I have the following workflow for one of my product based on Drupal 8:

I use three custom private dependencies via composer ( two modules , one theme) , a lot of contrib modules and obviously drupal core. We git-ignore core drupal, contrib and custom modules/theme delivered via composer.

When I commit to one of my **custom modules/theme**, I have a lot of operations to do to update all projects :

* I commit and push my modification to the custom module/theme
* I have to composer update project, one by one, to the new release, via composer update
* I commit, one by one, a composer.lock
* I have to composer install project in live stage ( not really great ).

Others issues :

* My colleague must composer install when they are back to the project to get the update.

Environnement: We use Gitlab.com for all projects that use our product. We have access to Gitlab CI/CD but it's not used at this time.

How optimize this workflow ? Any tools ? Gitlab CI/CD examples ? We can reconsider the full workflow too.

# Answer
> 2 votes
Thats an interesting question.

* "I commit and push my modification to the custom module/theme". (Obviously you cannot skip that part)
* Then you will update your module version number.
* Then you will push your branch to gitlab repo.
* That should start a CI pipeline.

This pipeline will do everything you have to do manually for now :

* Getting your branch code
* Running composer install (as your module version number has changed, this would trigger an module download, depending on how you had set the updating strategy, this could requires some tweaking).
* Commiting composer.lock, vendors and modules to a build (it could be a branch commit, or a compressed package)
* Running tests if you have any (you should)
* Pushing the branch, the tag or the package to your integration platform

You need to consider your gitflow and your environment to start writing a gitlab CI pipeline. I'm using Gitlab so I cannot give you example.

You probably need to create or use a Docker image on which your code will run, and with the appropriate tooling (composer, obviously, maybe npm if you have SCSS, curl, gzip, whatever...).

Local environments will still need to run composer install manually. You could use docker and script the building process locally but that's a different subject.

---
Tags: composer
---


# Question
Title: How to bypass menu link access permission
I have added some links from the admin page to a menu, but these links are not displayed in anonymous.
Certainly anonymous doesn't have access permission to the links, but I want to display the menu.
is there a hook or something that bypass access permission? Thank you.

# Answer
> 3 votes
You could create your menu links as `/user/login?destination=/my-path` and that will mean authenticated users would get taken to `/user/login` but then instantly redirection to `/my-path` because they're already logged in

Anonymous users will see the menu links and be taken to the login page if they tried to click them

# Answer
> 1 votes
I have created a menu block referring to the following link.
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/group/menu/8.8.x#sec\_rendering And by placing that block in the block layout, I achieved my purpose.

---
Tags: 8
---


# Question
Title: How to add multiple conditions on a single field in views?
I have two fields in my content type. `State` and `test` . `State` have two values `active` and `inactive` and `test` is a `boolean` field.

I want to display the content of this content type using views which will display:

```
active content
inactive content if test is FALSE

```

How can I do this in views?

I tried with views filter groups and it generates this condition.

```
WHERE ((( (node.status = '1') AND (node.type IN  ('mycontnt')) AND (state = 'active') )OR( (state = '4') AND (test = '0') )))

```

But this is not displaying the correct content as I want.

# Answer
> 0 votes
So far as there is no support for nested groups in Drupal 7, we shoud do it slight differently.

Join general filters (Published and Node type) in first `AND` group. May be we also should to add there "State IS NOT NULL" condition to exclude content with empty State field.

In second group we should place State = 'active' OR test = 'false'. This group - `OR` group. In the Views admin interface in would be somthing like this:

---
Tags: 7, views
---


# Question
Title: Need to add SKU to order confirmation email - Commerce 2
I have been able to customize the order confirmation email twig file for a client to some degree, however when it comes to adding the SKU for each item ordered I cannot find a way to have it populate. I have tried to insert the commerce checkout order summary block that displays each product variation's sku, it did not populate in the email. I have also looked at the order item table which does include the SKU for the items ordered so I cannot pull from there.

Any advice on how to pull the SKU's into the order confirmation email twig file?

# Answer
> 1 votes
I found this article that helped:

https://www.drupal.org/forum/support/module-development-and-code-questions/2018-08-23/drupal-8-commerce-2-get-item-from

This is my commerce-order-receipt twig that displays the quantity, title, price and in a row below the sku.

Hope it helps.

```
 <table style="text-align: center; width: 100%; margin: 5px auto 0 auto; border: 1px solid #cccccc; border-radius: 5px; padding: 40px 30px 30px 30px;">
    <tbody>
    <tr>
      <td style="font-size: 30px; padding-bottom: 30px">{{ 'Order Confirmation'|t }}</td>
    </tr>
    <tr>
      <td style="font-weight: bold; padding-top:15px; padding-bottom: 15px; text-align: left; border-top: 1px solid #cccccc; border-bottom: 1px solid #cccccc; vertical-align: top;">
        {{ 'Order #@number details:'|t({'@number': order_entity.getOrderNumber}) }}
      </td>
    </tr>
    <tr>
      <td style="vertical-align: top;">
        {% block order_items %}
        <table style="padding-top: 15px; padding-bottom:15px; width: 100%">
          <tbody style="text-align: left;">
          {% for order_item in order_entity.getItems %}
           {% set product = order_item.getPurchasedEntity %}
          <tr>
            <td style="vertical-align: top;">
              {{ order_item.getQuantity|number_format }} x
            </td>
            <td style="vertical-align: top;">
              <span>{{ order_item.label }}</span>
              <span style="float: right;">{{ order_item.getTotalPrice|commerce_price_format }}</span>
            </td>
          </tr>
          <tr>
          <td style="vertical-align: top;">
              <span>SKU:</span>
          </td>
          <td style="vertical-align: top;">
              <span>{{ product.getSku }}</span>
          </td>
          </tr>
          {% endfor %}
          </tbody>
        </table>
        {% endblock %}
      </td>
    </tr>
    <tr>
      <td>
        {% if (billing_information or shipping_information) %}
        <table style="width: 100%; padding-top:15px; padding-bottom: 15px; text-align: left; border-top: 1px solid #cccccc; border-bottom: 1px solid #cccccc">
          <tbody>
          <tr>
            {% if shipping_information %}
              <td style="padding-top: 5px; font-weight: bold; vertical-align: top;">{{ 'Shipping Information'|t }}</td>
            {% endif %}
            {% if billing_information %}
              <td style="padding-top: 5px; font-weight: bold; vertical-align: top;">{{ 'Billing Information'|t }}</td>
            {% endif %}
          </tr>
          <tr>
            {% if shipping_information %}
              <td style="vertical-align: top;">
                {% block shipping_information %}
                  {{ shipping_information }}
                {% endblock %}
              </td>
            {% endif %}
            {% if billing_information %}
              <td style="vertical-align: top;">
                {% block billing_information %}
                  {{ billing_information }}
                {% endblock %}
              </td>
            {% endif %}
          </tr>
          {% if payment_method %}
            <tr>
              <td style="font-weight: bold; padding-top: 40px; vertical-align: top;">{{ 'Payment Method'|t }}</td>
            </tr>
            <tr>
              <td style="vertical-align: top;">
                {% block payment_method %}
                  <p>{{ payment_method }}</p>
                {% endblock %}
              </td>
            </tr>
          {% endif %}
          </tbody>
        </table>
        {% endif %}
      </td>
    </tr>
    <tr>
      <td style="padding-top: 20px; text-align: right;">
        {{ 'Subtotal: @subtotal'|t({'@subtotal': totals.subtotal|commerce_price_format}) }}
      </td>
    </tr>
    {% for adjustment in totals.adjustments %}
    <tr>
      <td style="text-align: right;">
        {{ adjustment.label }}: {{ adjustment.total|commerce_price_format }}
      </td>
    </tr>
    {% endfor %}
    <tr>
      <td style="padding-top: 10px; padding-bottom: 20px; font-size: 24px; text-align: right;">
        {{ 'Order Total: @total'|t({'@total': order_entity.getTotalPrice|commerce_price_format}) }}
      </td>
    </tr>
    <tr>
      <td style="padding-top: 30px; border-top: 1px solid #cccccc;">
        {% block additional_information %}
          {{ 'Thank you for your order!'|t }}
        {% endblock %}
      </td>
    </tr>
    </tbody>
  </table>

```

# Answer
> 1 votes
I solved it like this:

1) edit fields in /admin/commerce/config/product-variation-types/default/edit/display/summary

* you can add SKU or anything else

2) add {{ order\_item.getPurchasedEntity|commerce\_entity\_render('summary') }} in commerce-order-receipt.html.twig

```
 {% for order_item in order_entity.getItems %}
              <tr>
                <td>
                  {{ order_item.getQuantity|number_format }} x
                </td>
                <td>
                  {{ order_item.getPurchasedEntity|commerce_entity_render('summary') }}
                </td>
                <td>
                  <span>{{ order_item.label }}</span>
                  <span style="float: right;">{{ order_item.getTotalPrice|commerce_price_format }}</span>
                </td>
              </tr>
              {% endfor %}

```

in fact, I created a new display called "sku" and didn't use "summary"

*my post on drupal.org - https://www.drupal.org/project/commerce/issues/3130985*

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


# Question
Title: How can I restrict access to a static HTML page served from a subfolder of my site to authenticated users only?
I have a Drupal 8 site that has all roles and permissions necessary for authenticated users. One of the new requirements is to serve a static microsite (like a campaign site, totally different design compare to Drupal site) which is a single folder with all the static assets (HTML, CSS, JS , images). We have to serve this site under the same domain drupal is hosted and should be accessed ONLY by authenticated users.

I tried to host it under `sites/default/files/` directory, but it means it is public and anyone can access it.

# Answer
> 1 votes
One of the options to achieve this is using drupal's private file system. Drupal core out-of-box provides a way to access private files in a secured URL. Here are the steps:

1. upload the directory (e.g. `foo-bar`) to drupal's private file scheme. (you can find it under Administration-\>Configuration-\>Media-\>File system)
2. Create a hook\_file\_download($uri) in a custom module and check for necessary access conditions:

```
function mymodule_file_download($uri) {

  // Check user permission only if the requested
  // file is under foo-bar directory.
  if (strpos($uri, 'foo-bar') !== FALSE) {
    if (\Drupal::currentUser()->isAnonymous()) {
      return -1
    }

    // Return a header to inform access is granted.
    return ['Cache-Control' => 'private'];
  }
}

```
3. Now the directory is available for authenticated users at `www.example.com/system/files/foo-bar/index.html`.

Check Drupal\system\FileDownloadController::download() for more details

This would work for both Drupal 8 & 9. I haven't checked 7.

---
Tags: files
---


title: Image thumbnail styles are not created

text:
# Question
Title: Image thumbnail styles are not created
I'm moving a website in a production server and it appears that the image thumbnails aren't created from an Image Field in a content.

The images are uploaded correctly but no files are created in styles folder. I've already set to 0777 each folder in case of a permission problem, but it's not that.

The big problem is that I can't remove the images, probably because it raises a forbidden file as it doesn't exist. The only error log I can find is an access denied but nothing else.

Does anybody has the same problem ?

It works okay on local... maybe an Apache issue to look at ?

# Answer
> 11 votes
**Solution for Drupal 8 that worked for me**:

* create sites/default/files/styles folder manually
* set its permissions to 775
* create .htaccess file in this folder with following content:

```
<Files *>
  SetHandler none
</Files>

```

# Answer
> 5 votes
Having the same problem with a brand new Ubuntu 19.10 installation on development laptop.

As suggested in https://drupal.stackexchange.com/a/224999/97472, adding

```
<Files *>
  SetHandler none
</Files>

```

is fixing a problem, image style generation works fine. However, this is not an optimal solution. Finally, figured out that i forgot to add apache mod-rewrite module. Executing next lines in console fixed the problem fully, no need for .htaccess manual fix:

```
sudo a2enmod rewrite
systemctl restart apache2

```

# Answer
> 2 votes
Sometimes this is related to an odd space in one of your module or PHP files before the opening PHP tag... for example:

```
_
<?php

/**
 * Stuff here.
 */

```

That little line where the underscore is present can cause thumbnails to break on first render. See: Image styles not generated on first page load until page refreshed on Drupal.org.

To see if this might be your issue, grep your entire codebase for any files that have a newline, then a `<?php` tag. In my case, I found that the contrib Block Styles module had a submodule with a newline before the opening tag, and that caused a fair amount of grief!

# Answer
> 1 votes
From settings.php Drupal 8, please try add following:

```
$config['image.settings']['suppress_itok_output'] = TRUE;
$config['image.settings']['allow_insecure_derivatives'] = TRUE;

```

suppress\_itok\_output = True for remove itok token from image.

# Answer
> 1 votes
I used this snippet code which forces drupal to create image style for an image :

```
$styles = ImageStyle::loadMultiple();
$image_uri = $entity->getFileUri();
/** @var \Drupal\image\Entity\ImageStyle $style */
foreach ($styles as $style) {
  $destination = $style->buildUri($image_uri);
  $style->createDerivative($image_uri, $destination);
}

```

this code can be used in a function iterating on a group of nodes, select their image and create styles for them or could be used as file upload hook so any time an image is uploaded the styles would be created manually.

# Answer
> 0 votes
Drupal 8 solution for drupal image styles not generating:

set the permissions to 775 to sites/default/files/ folder. command \[ $ sudo chmod 775 /var/www/html/drupal-8.7.6/sites/default/files/\]

Comment the "SetHandler Drupal\_Security\_Do\_Not\_Remove\_See\_SA\_2013\_003" line in files folder .htaccess file.

Add the following lines in .htaccess file.

\# Override the handler again if we're run later in the evaluation list. #SetHandler Drupal\_Security\_Do\_Not\_Remove\_See\_SA\_2013\_003 SetHandler none

# Answer
> 0 votes
Having tried multiple owner change commands and permissions did not work. The solution was simply :

sudo a2enmod rewrite

systemctl restart apache2

---
Tags: media
---


# Question
Title: How can I trim a field's value for display?
In Drupal 7, on a content type's "Manage display" tab, it was possible to trim strings to a particular length, by setting the field's format to "Trimmed".

For example, you could trim a long text field to 200 characters for the Teaser mode.

This doesn't seem to be possible in Drupal 8 – I don't have the option to set a custom-field's format to "Trimmed". (The only option available is "Plain text".)

Has the "Trimmed" format indeed been removed for custom fields? If so, is there a way to get it back?

# Answer
> 0 votes
Your field type needs to be Text (formatted, long).

Then on the display settings page, you can change the display format to Trimmed, and edit the settings (by clicking the gear) to change the character limit.

---
Tags: 8
---


title: Adding attachment using Swiftmailer

text:
# Question
Title: Adding attachment using Swiftmailer
I am trying to add an attachment to an email from a form\_submit. I can see the attachment loading in the hook\_mail() before the email sends, but no attachment is coming through. I also tried to use the swiftmailer\_swiftmailer\_attach() hook and that doesn't work. The emails are coming over with Content-Type: multipart/alternative;

Here is the code:

```
// from submitForm()
$params['message'] = $body;
$mail_manager = \Drupal::getContainer()->get('plugin.manager.mail');

$mail_manager->mail('so_assets', 'banner_email', 'test@test.com', \Drupal::languageManager()->getDefaultLanguage()->getId(), [
  //'content_type' => "text/html; charset=UTF-8; format=flowed; delsp=yes",
  'from' => 'test@test.com',
  'message' => $body,
  'myattachment' => $store_logo[0],
]);

// in .module file
function so_assets_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message['langcode'],
  );
  //var_dump($params['myattachment']); die(); // I can see the managed file ID here and load it.
  switch ($key) {
    case 'banner_email':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('New Request');
      $message['body'][] = $params['message'];
      //$message['params']['files'][] = \Drupal\file\Entity\File::load($params['myattachment']);
      break;
  }
}
// I tried this, with and without the file attachment commented out in the hook_mail()
function so_assets_swiftmailer_attach($key) {
  return \Drupal\file\Entity\File::load(5130);
}

```

# Answer
> 3 votes
Swiftmailer currently expects a plain \stdClass object in files as this part hasn't been fully ported from D7. See https://www.drupal.org/node/2713651.

So you need to do something like

```
$file = (object) [
'filename' => $file->getFilename(),
'uri' => $file->getFileUri(),
'filemime' => $file->getMimeType(),
];
$message['params']['files'][] = $file;

```

# Answer
> 1 votes
It is also worth mentioning that if you have generated contents rather than a Drupal file, you have to use an array rather than a stdClass, and insert it into "attachments" rather than "files", for example

```
$file = [
    'filename' => $filename,
    'filemime' => $mimetype,
    'filecontent' => $contents,
] ;
$message['params']['attachments'][] = $file ;

```

I was getting crazy to get it to work, luckily I could look at Swiftmailer code, which is very clear.

---
Tags: 8
---


# Question
Title: Which is the highest version of Solr that is compatible with the "Apache Solr Search" module?
I have a setup of Drupal 7 with the Apache Solr Search module. I am planning to upgrade the solr server's current installed version(3.6) to a higher version.

The latest version of Solr available in their site is 8.5.1.

Which is the highest version of Solr that is compatible with the module?

# Answer
> 0 votes
Given there is an issue in the project issue queue (Solr 7 integration) about allowing to use the module with Solr 7, the module is at the moment only compatible with Solr 5 and eventually Solr 6.

Notice that the README.txt file has not been updated since 6 years ago and that the solr-conf directory contains configuration files for Solr 1.4, 3.x, 4.x, and 5.x. This means the module has been tested with Solr 5.x, at least the 5.x version that was available 4 years ago.

---
Tags: 7, search
---


# Question
Title: Composer: require dev branch then go back to stable once current dev is stable
Let's say you need a patch in a Drupal module (or core) only included in the dev version yet.

It's already commited and should normaly be included in the next stable release.

So I'd like composer to grab the dev version for now but switch back to stable as soon as the next release is out.

If I do this for ex.:

```
composer require drupal/bootstrap:3.x-dev

```

It'll continue to update to the dev version even after the patch I need is included to stable, wich I'd like to avoid...

Is there a way to achive this ?

For ex. a way to tell composer "I want a version of this module that **has** to include that commit be it dev or stable, but I'd prefere stable if available".

So I can patch my module and forget about it.

# Answer
You should better use a patch.

You will ask composer to download and install the required patch on top of the current stable release.

Once the patch will be inside the stable release, the patch won't be applied anymore (a patch is basically a diff file, so when there's no diff, there's not patch)

Install https://github.com/cweagans/composer-patches this is a dependencies that will allow to use a section in the composer.json to declare the patch. It will install it automatically.

`composer require cweagans/composer-patches`

Then add an extra section in your composer.json

```
"extra": {
    "enable-patching": true,
    "patches": {
        "drupal/module_to_be_patched": {
            "<patch1 information>": "<patch1 file path>",
            "<patch2 information>": "<patch2 file path>"
        }
     }
}

```

You will find the patch file path on the module tracker, on the repository of the module, for an issue

For exemple, successive patches for a drupal/webform issue : https://www.drupal.org/project/webform/issues/3137981

Then simply

```
composer install

```

You will see the patch is being installed right in your terminal.

Reference : https://groups.drupal.org/node/518975

Patching : https://www.drupal.org/patch/apply
> 4 votes

---
Tags: 8, composer
---


# Question
Title: How do I get the user ID from the $user_profile variable?
How can I get the user ID and load the user with `user_load()` using the `$user_profile` variable in the *user-profile.tpl.php* template file?

# Answer
> 1 votes
Using the following code in a module will make the user ID available to the *user-profile.tpl.php* template as `$user_id`.

```
function mymodule_preprocess_user_profile(&$variables) {
  $account = $variables['elements']['#account'];
  // Add the user ID into the user profile as a variable
  $variables['user_id'] = $account->uid;
  // Helpful $user_profile variable for templates.
  foreach (element_children($variables['elements']) as $key) {
    $variables['user_profile'][$key] = $variables['elements'][$key];
  }

  // Preprocess fields.
  field_attach_preprocess('user', $account, $variables['elements'], $variables);
}

```

This means that you can then copy the *user-profile.tpl.php* template from the *modules/user* directory to your theme directory and change it to the following.

```
<div class="profile"<?php print $attributes; ?>>
  <?php print $user_id; ?>
  <?php print render($user_profile); ?>
</div>

```

# Answer
> 0 votes
You cannot get the uid from $user\_profile as it does not contain any information we can use to get the current user.

To get the current user's object, use the following:

```
global $user;
echo $user->uid;

```

# Answer
> 0 votes
The *user-profile.tpl.php* template file doesn't get a variable containing the user ID, nor a user object. The `$user_profile` variable contains what needs to be rendered for the user profile. `template_preprocess_user_profile()` retrieves the user object used for the profile, but it doesn't pass it to the template file, nor does it pass the user ID.

If the user ID is necessary in the *user-profile.tpl.php* template file, implementing `hook_preprocess_HOOK()` helps.

```
function mymodule_preprocess_user_profile(&$variables) {
  if (isset($variables['elements']['#account']) && isset($variables['elements']['#account']->uid)) {
    $variables['uid'] = $variables['elements']['#account']->uid;
  }
}

```

The template file can then use `$uid` to get the user ID.

Notice that copying other code from `template_preprocess_user_profile()` is not necessary: `template_preprocess_user_profile()` is executed before any preprocess and process functions, whenever they are implemented in modules or in themes. An implementation of `hook_preprocess_user_profile()` doesn't override/replace `template_preprocess_user_profile()`.

---
Tags: 7, users
---


# Question
Title: Programmatically set the format for each value of a multi-value text field
I am trying to programmatically set the format of a multi value text field to 'full\_html'.

**I have tried:**

```
$Links = array (1, 2, 3, 4, 5);

$node->field_article_links[] = $Links;
$node->field_article_links->format = 'full_html';
$node->save();

```

and

```
$Links = array (1, 2, 3, 4, 5);

foreach ($Links as $Link) {
$node->set('field_article_links', $Link);
$node->field_article_links->format = 'full_html';
}
$node->save();

```

But the results are always the same, only the **format** of the first value of the field is set to 'full\_html' and the others remain unchanged.

What am i doing wrong ?

# Answer
> 3 votes
**Please, do not start with capital letter when naming variables, every time you do that a puppy dies.**

As 'field\_article\_links' can have more than one value (probably is a unlimited field), you should treat its value as an array and not as single entity, where each element has its value and format.

To do that, you have to build an array with the field data, then put this array into the field.

The following code is working as you expect:

```
$links = array (1, 2, 3, 4, 5);
$field_data = [];
foreach ($links as $link) {
    $element = [];
    $element['value'] = $link;
    if($link === 3) {
        $element['format'] = 'full_html';
    } else {
        $element['format'] = 'dasdas';
    }
    $field_data[] = $element;
}
$node->field_article_links = $field_data;
$node->save();

```

---
Tags: 8
---


# Question
Title: How to edit Advanced Search Form's Content Type checkbox-list using hook_form_alter
I have a Drupal 7 setup. I want to remove few Content types from the Content Type checklist that appears in Advanced Search form. I could see that advanced search form comes in 'advanced' field-set of 'search\_form'.

I tried to implement the solution given here, but I am not able to find the advanced array in $form.

I would also like to add styling changes and prefix elements to default text-fields that comes within Advanced Search form

Please find the below code that displays content of $form ($form\_id = search\_form), as I can't find advanced array within it.

```
    Array
(
    [#action] => /demodrupal7/search/node
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => search-form
                )

        )

    [module] => Array
        (
            [#type] => value
            [#value] => node
        )

    [basic] => Array
        (
            [#type] => container
            [#attributes] => Array
                (
                    [class] => Array
                        (
                            [0] => container-inline
                        )

                )

            [keys] => Array
                (
                    [#type] => textfield
                    [#title] => Enter your keywords
                    [#default_value] =>
                    [#size] => 40
                    [#maxlength] => 255
                )

            [processed_keys] => Array
                (
                    [#type] => value
                    [#value] =>
                )

            [submit] => Array
                (
                    [#type] => submit
                    [#value] => Search
                )

        )

    [#form_id] => search_form
    [#type] => form
    [#build_id] => form-wAV_M_UAj5lbJgb-6vcdpmtxls5NpioPam6uNtkzRnw
    [form_build_id] => Array
        (
            [#type] => hidden
            [#value] => form-wAV_M_UAj5lbJgb-6vcdpmtxls5NpioPam6uNtkzRnw
            [#id] => form-wAV_M_UAj5lbJgb-6vcdpmtxls5NpioPam6uNtkzRnw
            [#name] => form_build_id
            [#parents] => Array
                (
                    [0] => form_build_id
                )

        )

    [#token] => search_form
    [form_token] => Array
        (
            [#id] => edit-search-form-form-token
            [#type] => token
            [#default_value] => 374_q2sHn_uhIvUhwOdrriFMIM3UgfVoc7Jzsh_DHrE
            [#parents] => Array
                (
                    [0] => form_token
                )

        )

    [form_id] => Array
        (
            [#type] => hidden
            [#value] => search_form
            [#id] => edit-search-form
            [#parents] => Array
                (
                    [0] => form_id
                )

        )

    [#id] => search-form
    [#method] => post
    [#theme_wrappers] => Array
        (
            [0] => form
        )

    [#icon] =>
    [#icon_position] => before
    [#process] => Array
        (
            [0] => bootstrap_form_process
        )

    [#pre_render] => Array
        (
            [0] => bootstrap_pre_render
        )

    [#tree] =>
    [#parents] => Array
        (
        )

    [#validate] => Array
        (
            [0] => search_form_validate
        )

    [#submit] => Array
        (
            [0] => search_form_submit
        )

    [#theme] => Array
        (
            [0] => search_form
        )

)

```

Can anyone help me with this. Thanks in advance.

# Answer
> 1 votes
The advanced fields are added by the node.module in `node_form_search_form_alter()` (a `hook_form_FORM_ID_alter()` implementation). It sounds like your module's `hook_form_alter()` is getting called before the node.module one, so you're not seeing it's additions.

The ordering of when hooks are fired is controlled by the `weight` column in the system table. Have you altered that previously for your module? Usually, node.module has a weight of 0 so if your module comes before that in the rows in the system table when sorted by weight then that will be your problem.

---
Tags: 7, search
---


# Question
Title: How to prevent a PDO exception when using Rules to Set a data value after saving new content?
I need to write a rule that edits some elements of the node, as soon as it is created. Unfortunately Drupal doesn’t like that and crashes whenever you try to save the node within a rule that was triggered by "After saving new content".

**Event**: After saving new content

**Conditions**: ...

**Actions**: Set a data value, with Parameter: Data: \[node:field-workflow...\], Value: 1

The above results in:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation:

So far I managed to walk-around that with hook\_forms, changing the workflow in my portal (so I never have to edit the node just after it is created)

Things get really interesting when I try to use "Execute custom PHP code" action which will change the node value I want:

1. node\_save will result in drupal crushing
2. db\_update - seems to work most of the time...
3. db\_insert - sometimes works (works for superuser only)

Unfortunately all my hacks don't work for all my problems. How else I can address this situation?

# Answer
Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module works ...).

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rules Action (related to *Set a data value*) in a Rules Component, so that your Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Save new content" for sure completed, and your new content will have been created as expected.

PS: I'm assuming this question is about D7.
> 0 votes

# Answer
In many ways, Rules is just a wrapper around core Drupal functionality. So while Rules tries to make this core functionality accessible to users who aren't hard-core Drupal programmers, there are of necessity quirks and assumptions inherited from Drupal that govern and explain how Rules behaves.

Specifically, in this case, the "After saving new content" event is just a way to access the core Drupal `hook_node_insert()` function. (Rules creates events for ALL the entity CRUD hooks). So if you want to understand how the "After saving new content" event works you need to understand how `hook_node_insert()` works. I don't know if this is explicitly described in the Rules documentation, but it's in the Drupal API documentation: https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_insert/7.x

> **function hook\_node\_insert** 7.x node.api.php hook\_node\_insert($node) Respond to creation of a new node. This hook is invoked from node\_save() after the database query that will insert the node into the node table is scheduled for execution, after the type-specific hook\_insert() is invoked, and after field\_attach\_insert() is called. Note that when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress. *The transaction is not finalized until the save operation is entirely completed and node\_save() goes out of scope.* You should not rely on data in the database at this time as it is not updated yet. You should also note that any write/update database queries executed from this hook are also not committed immediately. Check node\_save() and db\_transaction() for more info.

(emphasis added)

Likewise, "Before saving content" uses the core `hook_node_presave()` function, where the documentation says "This hook is invoked from node\_save() before the node is saved to the database." But since `node_save()` involves a lot of steps you need to be aware of what has been done and what hasn't been done yet at this point in the process.

The entire set of Node API Hooks is documented at https://api.drupal.org/api/drupal/modules%21node%21node.api.php/group/node\_api\_hooks/7.x

There's always an event that will work for what you need, it just might not be obvious which event that will be. Reading the above hook documentation should help you to figure out why the error occurred and which event would be a better fit for what you're trying to do.
> 0 votes

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


# Question
Title: How do we fetch the list of all content types refererencing a particular taxonomy vocabulary?
I am trying to delete a taxonomy vocabulary but before doing that, I want to know if there is any content type with a field referencing a taxonomy vocabulary.

My first thought was using a view, but that would only list content. Unless it can display the type and group by the type, it would not be the best solution.

# Answer
> 1 votes
If you want to check from UI then maybe you can try the Field list page (`/admin/reports/fields`) for checking which all the places have the required taxonomy field has been referenced/used.

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


# Question
Title: render call in hook_node_presave uses admin theme
I am using `hook_node_presave()` to render my node and then save the output to a field `field_node_cache`. However, when I do this, the renderer uses the admin theme, whereas I would like to use the site's main theme.

Is there a way to force it to use the site's main theme without disabling the admin theme?

```
function MYMODULE_node_presave(NodeInterface $entity) {
  switch ($entity->getType()) {
    case 'MY_CONTENT_TYPE':
      $render_controller = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
      $render_output = $render_controller->view($entity, 'MY_VIEW_MODE', 'ja');
      $html = \Drupal::service('renderer')->renderPlain($render_output);

      $entity->set('field_text_main_display', $html);
      $entity->field_node_cache->format = 'MY_FORMAT';
    break;
  }
}

```

# Answer
> 0 votes
One way to work around this is to go to `/admin/appearance` and uncheck `Use the administration theme when editing or creating content`.

Alternately, you can create a separate user account that does not have permission **View the administration theme** and use that account to create content.

---
Tags: theming, hooks
---


# Question
Title: Understanding the Basic Context of Trusted Hosts
I got the *trusted host settings* error.

> The trusted\_host\_patterns setting is not configured in settings.php. This can lead to security vulnerabilities. It is highly recommended that you configure this. See Protecting against HTTP HOST Header attacks for more information.

I read the Trusted Host Settings documentation but **I'm not understanding some of the basic context.**

* Are the "trusted hosts" me and other administrators who want to be able to administer the site remotely?
* If so, would I add my PC's domain to the trusted host list?

# Answer
Trusted hosts refer to the domain that your Drupal site is hosting, not your remote PC's domain that is administering the site. For example, if your site running on Drupal was `www.thedrupaldude.com`, the trusted host regular expression would be `^www\.thedrupaldude\.com`.
> 4 votes

---
Tags: 8, security
---


# Question
Title: Manually laying out specific articles on page
I'm making a newspaper site and would like to manually lay out and embed a specific set of articles for the front page. Is there a way I can manually code the layout in columns and embed specific articles?

I don't want or expect the articles to be automatically populated when new content is published; I'd like this to be a manual process. Here's an example similar to what I'm hoping to accomplish pulled from today's New York Times layout:

# Answer
There is (as often) more than one way of solving this.

The dirty and easy way of doing it is with Blocks and Regions, like in Drupal 7. You'll need regions in your theme to be laid out the way you want (and be responsive). Then you manually add nodes/blocks to the regions you have laid out. Even the method of choosing nodes/blocks can be done in different ways.

---

The sophisticated way of building such a page is with the Layout builder and Paragraphs or a similar module that allows you to reference things.

One Content Type will serve as the container for the layout and all the other content you want shown there. Although it's possible to apply it to only the one node, the one you'll be using for the front page, you decide what makes sense structurally and procedurally in your project.

With Paragraphs you create different reference possibilites for the content you want displayed, and then arrange them with the Layout builder. The Paragraphs and Layout builder parts are usually done up front, you build them once and have it ready when new content is created.

When you publish new nodes and want to update the front page node to show it you will only have to change the references within the front page node to keep the layout and have different content in each "box area".

You can, of course, create more than one layout in your theme, so when needed also choose a different layout for the new content combination.

It's a super powerfull new approach in D8 that makes your Drupal site feel like a website builder software. It does require some effort up-front, so it all depends on your specific needs.
> 2 votes

---
Tags: theming
---


# Question
Title: How to avoid _0 _1 when editing a media entity and changing the file?
Say I add an image using the built-in Media module.

A couple months later, I have to change the image file for some reason. So I edit the media entity, delete the existing file, and upload the new file. The new file has the same name as the old file.

This creates a new file, **filename\_0.jpg**. How can I cleanly replace the file without adding a new suffix?

# Answer
> 1 votes
Use the Media Entity File Replace module. This is the exact use case it was created for.

---
Tags: media
---


# Question
Title: Use generated JWT from Keycloak to authenticate user using REST API
We are working on developing a mobile app and users should be able to log in to the app and in our backend Drupal site authenticated from Keycloak. Our main goal is that the user would be able to login from the app to update/create content using REST api.

We will be using a JWT token generated from Keycloak to authenticate user in the backend site.

We are using the following Drupal core and module versions:

* Drupal: 8.5.3
* OAuth2 JWT SSO: 8.x-1.0-rc1
* OpenID Connect: 8.x-1.0-beta5
* RESTful Web Services: 8.5.3
* Simple OAuth: 8.x-3.0
* OpenID Connect REST API: 8.x-1.0-rc1

I will first try with REST API to see if the implementation will work before integrating it to our mobile app.

Below are the steps of REST request executed in POSTMAN tool

### Pre-setup

From http://192.168.254.107:8080/admin/config/services/openid-connect We enable generic and fill in the following fields

```
GENERIC
Redirect URL: https://192.168.254.107/openid-connect/rest/generic
Client ID: opensocial
Client secret: XXXXX-XXXXX-XXXXX
Authorization endpoint
http://192.168.254.107:8083/auth/realms/master/protocol/openid-connect/auth
Token endpoint
http://192.168.254.107:8083/auth/realms/master/protocol/openid-connect/token
UserInfo endpoint
http://192.168.254.107:8083/auth/realms/master/protocol/openid-connect/userinfo

```

And I have client created in Keycloak,

```
http://192.168.254.107:8083/auth/admin/master/console/#/realms/master/clients/XXXXX-XXXXX-XXXXX
Client ID: opensocial
Client Protocol: openid-connect
Access Type: Confidential
* Valid Redirect URIs : http://192.168.254.107:8080/*
Base URL: http://192.168.254.107:8080
Web Origins: http://192.168.254.107:8080/*

```

### Steps

1. Generate JWT from Keycloak

```
REQUEST: POST
ENDPOINT: http://192.168.254.107:8083/auth/realms/master/protocol/openid-connect/token
HEADER: Content-Type: application/x-www-form-urlencoded
BODY: client_id=opensocial&client_secret=f3e8f92d-c9ff-4139-b715-33e3aaa7194d&username=[username_from_keycloak]&password=[password_from_keycloak]&grant_type=password

RESPONSE:

    {
        "access_token": "XXXXX.XXXXX.XXXXX",
        "expires_in": 3600,
        "refresh_expires_in": 1800,
        "refresh_token": "XXXXX.XXXXX.XXXXX",
        "token_type": "bearer",
        "not-before-policy": 0,
        "session_state": "7f739b98-421c-4aaf-a85c-6e38424d9492",
        "scope": "email profile"
    }

```
2. Validated in jwt.io website and/or by fetching userinfo from Keycloak

```
REQUEST: GET
ENDPOINT: http://192.168.254.107:8083/auth/realms/master/protocol/openid-connect/userinfo
HEADER: Authorization: Bearer [access_token]
RESPONSE:

{
    "sub": "331e758e-b7cd-44b0-93ca-97aa44310335",
    "email_verified": false,
    "preferred_username": "admin"
}

```

3. Create content using token

    REQUEST: POST ENDPOINT: http://192.168.254.107:8080/node (this is the backend site) HEADERS: Content-Type: application/json Authorization: Bearer \[access\_token\] RESPONSE:

    Status: 500 500 Service unavailable (with message) The website encountered an unexpected error. Please try again later.

In Drupal logs I find the following.

> Type php
>
> Date Thursday, May 9, 2019 - 06:52 User Anonymous (not verified) Location http://192.168.254.107:8080/node Referrer
> Message Error: Call to a member function validateAuthenticatedRequest() on null in Drupal\simple\_oauth\Server\ResourceServer-\>validateAuthenticatedRequest() (line 63 of /opt/app-root/src/html/modules/simple\_oauth/src/Server/ResourceServer.php) #0 /opt/app-root/src/html/modules/simple\_oauth/src/Authentication/Provider/SimpleOauthAuthenticationProvider.php(63): Drupal\simple\_oauth\Server\ResourceServer-\>validateAuthenticatedRequest(Object(Symfony\Component\HttpFoundation\Request)) #1 /opt/app-root/src/html/core/lib/Drupal/Core/Authentication/AuthenticationManager.php(52): Drupal\simple\_oauth\Authentication\Provider\SimpleOauthAuthenticationProvider-\>authenticate(Object(Symfony\Component\HttpFoundation\Request)) #2 /opt/app-root/src/html/core/lib/Drupal/Core/EventSubscriber/AuthenticationSubscriber.php(78): Drupal\Core\Authentication\AuthenticationManager-\>authenticate(Object(Symfony\Component\HttpFoundation\Request)) #3 \[internal function\]: Drupal\Core\EventSubscriber\AuthenticationSubscriber-\>onKernelRequestAuthenticate(Object(Symfony\Component\HttpKernel\Event\GetResponseEvent), 'kernel.request', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher)) #4 /opt/app-root/src/html/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(111): call\_user\_func(Array, Object(Symfony\Component\HttpKernel\Event\GetResponseEvent), 'kernel.request', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher)) #5 /opt/app-root/src/vendor/symfony/http-kernel/HttpKernel.php(127): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch('kernel.request', Object(Symfony\Component\HttpKernel\Event\GetResponseEvent)) #6 /opt/app-root/src/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #7 /opt/app-root/src/html/modules/simple\_oauth/src/HttpMiddleware/BasicAuthSwap.php(67): Symfony\Component\HttpKernel\HttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #8 /opt/app-root/src/html/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Drupal\simple\_oauth\HttpMiddleware\BasicAuthSwap-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #9 /opt/app-root/src/html/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #10 /opt/app-root/src/html/modules/jsonapi/src/StackMiddleware/FormatSetter.php(40): Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #11 /opt/app-root/src/html/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\jsonapi\StackMiddleware\FormatSetter-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #12 /opt/app-root/src/html/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #13 /opt/app-root/src/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #14 /opt/app-root/src/html/core/lib/Drupal/Core/DrupalKernel.php(664): Stack\StackedHttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #15 /opt/app-root/src/html/index.php(19): Drupal\Core\DrupalKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request)) #16 {main}. Severity Error Hostname 192.168.254.107

Why does using a valid JWT token generated from Keycloak resulted into user not being authenticated in Drupal using REST API request? Is the method I used not possible? If not, then is there any other processes I can follow to achieve the goal?

# Answer
JWT token generated from keycloak is rejected because Drupal api accepts token generated by its own internal authorization server.

Drupal's api is protected by OAuth2 protocol. Drupal use its own OAuth2 authorization server to protect its api. So, to gain access to drupal api, you need to provide an access token issued by drupal authorization server.

you can check the "iss" field in the access\_token: value must be related to drupal's authorization server.

About the keycloak configuration you gave: it is related to the drupal account creation / login via OpenIdConnect. It allow to automatically create an account / log into with user data and credentials provided by keycloak. But it is not related to drupal api access. These are 2 distinct things:

* OpenIdConnect: to create an account and log into system using an external identity provider, like keycloak here
* OAuth2: to restrict / secure api access.

I'm also looking for a way to configure drupal to use an external OAuth2 authorization server like Keycloak
> 1 votes

---
Tags: 8
---


# Question
Title: how do I get the parent node of an entity reference node
I have two content types - A and B. For content type A, there are 5 content items - Aa, Ab, Ac, Ad, Ae. For content type B, I have two items Ba, Bb. Content type B has a field that is an entity reference of content type A. In a single page I have the following setup:

Ba -\> Aa, Ab, Ac, Ad, Ae
Bb -\> Aa, Ab, Ac, Ad, Ae

I have a twig template for B and a separate one for A. When rendering Aa - Ae, I need to know if the container node is Ba or Bb because it is rendered differently. Ba and Bb know about the referenced entities (Aa - Ae), but the referenced entities don't know who their parent is.

I've tried using the preprocessor but I can't seem to find a way to get the parent (containter) node.

Any suggestions?

TIA.

# Answer
> 3 votes
You should be able to do this:

```
$loaded_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'field_node_reference' => $node->id(),
]);
$parent_node = reset($loaded_nodes);

```

Replace the field name with your actual field name.

---
Tags: nodes
---


# Question
Title: Why does my do-nothing subtheme break the parent theme?
I'm trying to get started with sub theming in Drupal 8. I followed the example from the Drupal documentation and created what I thought was supposed to be an unmodified inherited copy of the Bartik theme, but the main navigation menu is changed per the below screenshots. My code is as follows, identical to the tutorial other than Bartik as the base theme.

What am I missing here? Why am I not starting with an identical layout to the Bartik theme?

**info.yml:**

```
name: wilmettewatch
type: theme
description: Wilmette Watch's theme based off Bartik for now
core: 8.x
# Defines the base theme
base theme: bartik
# Defines libraries group in which we can add css/js.
libraries:
  - wilmettewatch/global-styling
# Regions
regions:
  header: Header
  featured: Featured
  content: Content
  sidebar_first: First sidebar
  sidebar_second: Second sidebar
  footer: Footer

```

**libraries.yml:**

```
global-styling:
  css:
    component:
      css/style.css: {}

```

**Bartik Theme:**

**My Sub Theme:**

# Answer
> 2 votes
The sub theme is fine. Sometimes when you activate a sub theme, you may need to recreate some or all of the block layout. In this case, the primary menu got placed in the header, where it gets a different layout.

Just make note of the block layout in the Bartik theme and duplicate it in the sub theme.

---
Tags: 8, theming
---


title: Is extending Bartik a recommended move?

text:
# Question
Title: Is extending Bartik a recommended move?
I'm starting a new Drupal 8 project. As first steps I need to choose a theme. So far, I have only experience with Bario, chosen initially for using Bootstrap 4. I'm now looking for a theme that's not using Bootstrap.

I'm considering extending Bartik. Is this correct, or should I extend a different theme?

# Answer
> 0 votes
Please have a look at the Drupal core themes no longer extend Classy change record.

> Bartik, Claro, Seven, and Umami are part of the product rather than the API and therefore it is not officially supported to extend them. These themes can change as part of a minor release and cause regressions to any themes extending them.

Means: No it's not recommended to extend Bartik. Extend Classy or Stable instead.

---
Tags: 8
---


# Question
Title: How do form #states interact with dialog action buttons, if at all?
A dialog can be fired by a link formatted as such:

```
<a class="use-ajax"
    data-dialog-options="{"width":400}"
    data-dialog-type="modal"
    href="/some/path">
    Some path displayed in modal dialog.
</a>

```

If the contents of /some/path are a form, then drupal takes its action buttons and drops them into a "footer" `<div class="ui-dialog-buttonset"></div>` in the dialog. This seems to take into account the initial state of the buttons -- so if submit has the `disabled` attribute by default then the corresponding UI button gets the `.is-disabled` class applied. The "real" form action buttons are rendered but set to `display: none`.

However, I've got #states set up on my submit button with

```
$form['actions']['submit']['#states'] = [
  'disabled' => [
    ':input[name="field_fivestar_rating[0][rating]"]' => [
      [
        ['value' => '-'],
        ['OR'],
        ['value' => '0'],
      ],
    ],
  ],
];

```

The "real" form submit button is updated correctly according to its #states attribute, but the same cannot be said for the corresponding dialog button. It seems to be static based on the initial state of the submit button.

Is this expected behavior? If so, is this something that deserves an issue in the queue? Seems like an oversight and usability concern.

# Answer
> 2 votes
This doesn't answer the question itself, but since I struggled for a while to get this all syncd up I figured I should drop the work into something that people might hit from google. To get the attributes all syncd up you can use the following js file:

```
(function ($, Drupal, drupalSettings) {
  var handler = Drupal.behaviors.commentsRatingFlexible = {
    attach: function (context, settings) {
      // If our form is loaded in a modal, then the context is
      // the form itself. Therefore we cannot look for the form
      // inside of context. As such, we need to check for forms
      // that exist in both situations an handle accordingly.
      var formInstances = [];

      // This would be the class for your particular form
      $('.comment-rating-flexible-form', context).each(function () {
        formInstances.push($(this));
      })

      if ($(context).hasClass('comment-rating-flexible-form')) {
        formInstances.push($(context));
      }

      // Lookup any rating-flexible-forms and disable the submit
      // button by default, since it shouldn't allow an empty val
      // for the fivestar field (if it's present)
      for (var k in formInstances) {
        var $form = formInstances[k];
        var $submit = $('.form-submit', $form);
        var $fivestarSelect = $('[name="field_fivestar_rating[0][rating]"]', $form);

        if (!$fivestarSelect.length) {
          return
        }

        handler.dialogSubmitButtonHandler($form); //must be called first
        handler.observeAttributes($submit);

        if ($fivestarSelect.val() == '-' || $fivestarSelect.val() == '0') {
          // #states don't apply on form load, only on change,
          // so we need to disable the form button here and
          // sync that onto the dialog's button
          $submit.attr('disabled', "");
        }
      }
    },
    /**
     * Syncs attributes from real form-submit onto dialog submit btn.
     *
     * @param $form
     *   The form contained in the dialog
     */
    dialogSubmitButtonHandler: function ($form) {
      var $drupalModal = $form.parent();

      // If the form is loaded outside the context of a modal, don't execute
      if ($drupalModal.attr('id') !== 'drupal-modal') {
        return;
      }

      // The actual modal and the rest of its contents won't exists
      // on the initial load. As such, we need to add a watcher to
      // the DOM to find out when our dialog action buttons exist
      // so that we can act on them then.
      var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
          if (!mutation.addedNodes.length) {
            return
          }

          mutation.addedNodes.forEach(function (node) {
            var $node = $(node);
            if (!$node.hasClass('ui-dialog-buttonpane')) {
              return;
            }

            var $formSubmitButton = $('.form-submit', $form);
            var $dialogSubmitButton = $('.form-submit', $node);

            // Watch for our custom $.event from observeAttributes
            $formSubmitButton.on('attributeUpdated', function (e, attrData) {
              $dialogSubmitButton.attr(
                attrData.attributeName,
                attrData.attributeNewValue
              );
            })

            observer.disconnect();
          })
        })
      })

      observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: false,
        characterData: false
      })
    },
    /**
     * Fires an event when an element's attributes change.
     *
     * @param $el
     *   The jQuery element being observed
     */
    observeAttributes: function ($el) {
      var observer = new MutationObserver(function (mutationList, observer) {
        var eventData = [];

        mutationList.forEach(function (mutation) {
          if (mutation.attributeName === 'style') {
            return;
          }

          var attributeName = (mutation.attributeName === 'class') ? 'classList' : mutation.attributeName;

          $el.trigger('attributeUpdated', {
            'attributeName': mutation.attributeName,
            'attributeNewValue': mutation.target[attributeName],
            'attributeOldValue': mutation.oldValue
          })
        })
      });

      observer.observe($el[0], {
        attributes: true,
        attributeOldValue: true,
      });
    },
  }
})(jQuery, Drupal, drupalSettings);

```

---
Tags: forms, modal-dialogs
---


# Question
Title: CKEditor strips all inline CSS and some tokens
I'm trying to add a color and font size to some text using the CKEditor. As soon as I save it these are stripped out.
I've also noticed some tokens are stripped down when certain settings are enabled.

I went to add a bit of text in a different font and color but when I saved it and viewed the text the spans were stripped of their "style" tag.
I went to `config/content/formats/manage` and enabled `Limit allowed HTML` and added span to the list like so :

```
<a hreflang href> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol type start> <li>
<dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <img src alt data-entity-type data-entity-uuid>
<u> <s> <p> <h1> <pre> <table> <caption> <tbody> <thead> <tfoot> <th> <td> <tr> <span style>

```

After saving this all the attributes inside of span are still stripped. I also noticed that many of the tokens I was using (such as `site:url`) are broken and only half of it remains.

I went back and disabled the `Limit allowed HTML` option and then when I saved the text the styles and token would save properly.
When viewing the text in an email, the tokens had worked just fine but the span had it's css striped.

I've tried looking for an answer but most are saying I need to enable and add the span to the limit html option but this definitely does not work for me.

There is also `Correct faulty HTML` enabled, would that be a problem for this?
How can I enable in line styling with the CKEditor?

# Answer
> 2 votes
See

for some further reference :)

---

You could try using custom CKEditor styles. For using custom styles you'll need a custom module.

* MYMODULE/
    + /MYMODULE.module
    + /MYMODULE.libraries.yml
    + /css/style.css

**MYMODULE/MYMODULE.module:**

```
function MYMODULE_editor_js_settings_alter(array &$settings) {

  foreach ($settings['editor']['formats'] as $name => $value) {

    // You can check for specific editors.
    // if ($settings['editor']['formats'] == 'basic_html') {
    //
    // }

    // Otherwise, add our custom styles to all editors.
    $settings['editor']['formats'][$name]['editorSettings']['stylesSet'] = [

      [
        'name' => 'Custom Color Text',
        'element' => 'p',
        'attributes' => [
          'class' => "custom-color-text"
        ]
      ],
      [
        'name' => 'Custom Color Link',
        'element' => 'a',
        'attributes' => [
          'class' => "custom-color-link"
        ]
      ],
    ];
  }
}

function MYMODULE_preprocess_node(&$variables) {

  // Attach our styles library.
  $variables['#attached']['library'][] = 'MYMODULE/styles';
}

// Nice to haves:
function MYMODULE_ckeditor_css_alter(&$css, $editor) {

  // Add our ckeditor style sheet to ckeditor.

  // This adds our theme styles to the editor field.
  $css[] = drupal_get_path('theme', 'MYTHEME') . '/css/style.css';

  // This adds our styles from the module directory.
  $css[] = drupal_get_path('module', 'MYMODULE') . '/css/style.css';
}

```

**MYMODULE/css/style.css:**

```
.custom-color-text {
  color: #f00;
}

.custom-color-link {
  color: #00f;
}

```

**MYMODULE/MYMODULE.libraries.yml:**

```
styles:
  version: 1.x
  css:
    theme:
      css/style.css: {}

```

These will now be available in the "style" dropdown in the CKEditor field.

---
Tags: 8, wysiwyg, tokens
---


# Question
Title: Why do I get a Symfony NativeSessionStorage error after adding a .theme file?
After creating (e.g empty) .theme file in my template folder, I get the following error message:

> The website encountered an unexpected error. Please try again later.RuntimeException: Failed to start the session because headers have already been sent by "/homepages/d825952918/htdocs/themes/universaldenker/universaldenker.theme" at line 1. in Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage-\>start() (line 145 of vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php).

If I delete the .theme file, everything works again. I think it has something to do with opcache, because the path "/homepages/d825952918/htdocs/themes/universaldenker/universaldenker.theme" comes from the .opcache folder.

How can I tell Drupal not to use it and clear all the cached files?

# Answer
I suspect that your .theme file was not actually empty. Please try the experiment again and check the file size. If it is 3, then your file starts with a Unicode byte order mark (BOM).

The BOM is typically invisible in editors, but it gets sent to the browser before Drupal internally calls the `header()` function. This causes the error message you have seen.

From a glance on your paths, I would not conclude that the OPcache plays a role here.
> 1 votes

---
Tags: theming
---


# Question
Title: Warning: Invalid argument supplied for foreach() in template_preprocess_update_report()
In a Drupal 8 install, I visit `/admin/reports/updates`, and I receive the following error:

> Warning: Invalid argument supplied for foreach() in template\_preprocess\_update\_report() (line 44 of core/modules/update/update.report.inc).

From this page, I have tried to the run the SQL query:

```
delete * from 'prefix_key_value' where collection = 'update_fetch_task';

```

but I receive error:

> MySQL said: Documentation
>
> 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '\* from 'prefix\_key\_value' where collection = 'update\_fetch\_task'' at line 1

Help appreciated.

# Answer
> 0 votes
From this page I tried an SQL query to remove `* from 'prefix_key_value' where collection = 'update_fetch_task';` but that failed, so I deleted the `update_fetch_task` entry manually from the `prefix_key_value` table.

That resolved the error.

# Answer
> 1 votes
`delete * from ...` is invalid SQL, you don't need the asterisk.

# Answer
> 0 votes
From the same page referenced in the question, you need to have an update.settings.yml file, which can be set at ./admin/reports/updates/settings

Once you have this file, the update report screen at ./admin/reports/updates should work.

---
Tags: 8
---


# Question
Title: How can I create a "Best Answer" option for a forum?
I need an approach to create a best answer option for question author to accept a comment as best answer in Drupal 8 Forum.

Do you have any advice?

# Answer
> 1 votes
Since the Forum comments are actual Drupal comments on a node (forum thread/post is a node) you can easily do anything that can be done to Drupal comments.

This includes tagging the comments with Taxonomy terms or using Flags.

Flag might be the most suitable module when it comes to the feature of marking up comments.

You might need to do some custom theming or code if you need to reorder the comments based on that flag so the accepted answer comes up on top. You could also use Views to display the comments and order them based on the flag status first.

---
Tags: 8
---


# Question
Title: What's the difference between web service (API) implementation with REST and routing?
what are the real differences between these two methods of creating a webservice :

1. Routing + Controller (https://www.chapterthree.com/blog/custom-restful-api-drupal-8)
2. REST plugin (https://www.drupal.org/docs/8/api/restful-web-services-api/custom-rest-resources)

advantages/disadvantages of both?

I think we can create a restfull API with one as with the other, isn't it?

Thanks

# Answer
> 2 votes
actually to create a wbesrvice endpoitns in Drupal 8 we need to activate one of or both of this 2 modules :

1. **JSON:API module (best one)**:

after the activation of this module you can access to all Drupal entities (user , node , taxonomy ) throw a dynamic endpoints that have this structure **http://{host}/json\_api/{entity\_type}/{bundle}?Parameters**, with the ability to fitter the result + built in pagination + sorting ex of endpoints :

* **/jsonapi/node/article** : get a json contains all node article.
* **/jsonapi/node/article,sort=-created** : get a json contains all node article and order them with e created field in DESC order.article.
* **/jsonapi/taxojomy\_term/article** : get a json contains all taxnomy term category.

> understand the Drupal entity type first will be better : https://www.youtube.com/watch?v=FrSjwe8bh7I
>
> then use the JSON:api using this videos : https://www.youtube.com/watch?v=--ZL3EAhnwc&list=PLZOQ\_ZMpYrZsyO-3IstImK1okrpfAjuMZ

2. **RESTful Web Services**

* Exposing Views using the RESTful Web Services module( Do you need an easy configuration from backoffice to set up and endpoint ?) https://www.youtube.com/watch?v=TMvNwRVJSEQ.
    * Creating a Custom REST Resources to expose data that can’t be exposed by the previous solution - when to use this solution when none of the previous solution can expose this data (Does **JSON:API** and **View exposing** can't expose this type of data ?)

note : the methos in this url https://www.chapterthree.com/blog/custom-restful-api-drupal-8 never use it because we get out of the context of drupal, and you waon't be able to use a hiddne power of Rest module ex :l by default any custom rest endpoint will display i if rest ui (https://www.drupal.org/project/restui) module installed .

# Answer
> 2 votes
Basically you can implement API REST using both methods, (Routing+Controller) or (Plugins).

**(Routing+Controller)**

* Its an initial approach and it is not recommended to use it at these times for API REST.

**(Plugins), Its recommended to use it, why?**

* Define a standard (for all developers) for creating Web services/endpoint in Drupal 8+.
* Its in `core` to this purpose! Its like as a superior version of the classic (Routing+Controller) implementation with much others REST improvements.
* It has integration with other modules and features like `basic_auth`, `jsonapi`, `restui`, etc (not the other method, Routing+Controller).

Among other things, basically I think is for that.

> In other words, to not reinvent the wheel, use **Plugins**.

---
Tags: 8
---


# Question
Title: Trying to get property of non-object throws exception that cannot be handled
In a custom Drupal 8 module I decided to wrap a line of code in a try...catch block, in case $node was null.

I understand that in php errors and exceptions are different, and according to Error message - Trying to get property of non-object this is an error, so will not be handled by try...catch, and the code should continue to run after the error.

However when this code runs under Drupal 8 the error hander raises an exception. So I added the try...catch block. But the exception is still unhandled crashed the program.

This is a cut-down version of my code:

```
$node = null;
try {
  // The next line results in an unhandled exception
  $f = $node->field_example;
} catch (Exception $e) {
  // Never gets here
  watchdog_exception('example', $e);
}
// Never gets here

```

Am I missing something? Surely this can't be the intended behaviour?

# Answer
> 2 votes
I actually over-simplified by question. The crash doesn't happen in the simple case I posted, just an error and execution continues. It arises when I use field API syntax to refer to a null referenced entity, and only then when the target\_id is not null.

```
$node->field_foo->target_id = 999; // term 999 does not exist
try {
  // The next line results in an unhandled exception
  $v = $node->field_foo->entity->field_bar->value;
} catch (\Exception $e) {
  // Never gets here
  watchdog_exception('example', $e);
}
// And never gets to continue here

```

The issue was why and Drupal does this. The solution (thanks @Clive) is to replace `catch (\Exception $e)` with `catch (\Throwable $e)`

# Answer
> 0 votes
You are trying to catch `Exception`, when you should be catching `\Exception`.

```
} catch (\Exception $e) {

```

EDIT: Assuming that an exception is actually thrown as stated in the original post.

---
Tags: 8
---


# Question
Title: Add the Form name to the theme suggestions input field
How do I get the form name to the theme a suggestion input in Drupal 8?

```
function [THEME_NAME]_theme_suggestions_input_alter(array &$suggestions, array $variables) {
  if (isset($variables['element']['#parents'])) {
    $suggestions[] = 'input__'.$variables['element']['#parents'][0] ;
  }
}

```

# Answer
In your `yourTheme.theme`, you could do:

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

  foreach (\Drupal\Core\Render\Element::children($form) as $key) {
    $form[$key]['#attributes']['data-twig-suggestion'] = $form['#id'];
  }

  $form['actions']['submit']['#attributes']['data-twig-suggestion'] = $form['#id'];
}

```

The function `\Drupal\Core\Render\Element::children($form)` returns an array of all the children elements (for a form) for which the keys don't start with `#`.

So, this array will have the field names as its elements. Then, you iterate over the array and add the attribute `data-twig-suggestion` and its corresponding value. Note that the array will have some extra elements that aren't form fields, and those would also get the new attribute and its value. I don't think there is any collateral damage on that.

For the submit button (`$form['actions']['submit']`) we are adding the attribute "manually", as the field element (`submit`) is "nested" inside the `actions` array, so our previous loop won't have added the attribute to the correct element in the array.

Then, you also add this function:

```
function yourTheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if (isset($element['#attributes']['data-twig-suggestion'])) {
    $suggestion_suffix = str_replace(['-'], '_', $element['#attributes']['data-twig-suggestion']);
    $suggestions[] = 'input__' . $element['#type'] . '__' . $suggestion_suffix;
  }
}

```

Here, each form input field is processed and a template suggestion is added based on the previously created attribute.

PS: this solution is based on this article: Getting granular with Drupal 8 forms.
> 11 votes

# Answer
The Formdazzle! module does exactly that.

> Theming drupal forms can be difficult and time-consuming. This module provides a set of utilities that make form theming easier.
>
> Currently, this module provides theme suggestions for forms that are much more useful than those provided by Drupal core.
>
> * Theme suggestions for all form elements (including buttons)
> * Theme suggestions for all form element labels
> * All theme suggestions include the form ID and the form element name; e.g. `[element-type]--[form-id]--[form-element-name].html.twig`
> 0 votes

---
Tags: theming, 8
---


# Question
Title: twig template suggestion for comment reply form
there is no template suggestion for a comment reply form in Drupal 8, how can i create one? i am not talking about the reply form displayed in the node for which Drupal suggest a template :

```
field--node--comment--article.html.twig

```

I'am talking about the form in the redirection page after we click "reply" in a comment. there is no template suggestion, only this template is suggested

```
form.html.twig

```

Can you please tell me how can i create a specific template in my .theme file of my theme.

# Answer
> 1 votes
It's a bit unclear what exactly you want to achieve. But you can easily add another template suggestion based on the form ID by implementing `hook_theme_suggestions_HOOK_alter` for forms. The form ID can be found in the `$variables` then. But no matter if you are on the node route or the reply route this will simply give you `comment_comment_form`.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  $form_id = $variables['element']['#form_id'];
  // Add template suggestion based on form ID.
  $suggestions[] = 'form__' . $form_id;
}

```

If you want to do something different on the reply route you could check the current path for the `/reply` and `/comment` arguments OR check if the route parameters contain a PID, which would be the parent comment ID.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  // Add template suggestion based on form ID.
  $suggestions[] = 'form__' . $variables['element']['#form_id'];
  // Add template suggestion based on form ID and parent comment ID.
  if ($pid = \Drupal::routeMatch()->getParameter('pid')) {
    $suggestions[] = 'form__' . $variables['element']['#form_id'] . '__reply';
    $suggestions[] = 'form__' . $variables['element']['#form_id'] . '__reply__' . $pid;
  }
}

```

Which will give you the following theme suggestions.

```
<!-- FILE NAME SUGGESTIONS:
   * form--comment-comment-form--reply--1.html.twig
   * form--comment-comment-form--reply.html.twig
   * form--comment-comment-form.html.twig
   x form.html.twig
-->

```

---
Tags: theming, comments
---


# Question
Title: Why is the main page showing only the user login form?
I just installed the Paragraphs module along with all of the other accompanying modules including the demo module. The demo module created the demo page successfully but it also decided to change my site's default front page to the demo page.

When I changed the front page field back to the default null text, anonymous users now see nothing but this login form instead of my former front page. Registered users are sent to their user page, e.g. http://example.com/user/1.

Before installing the demo, my front page showed any articles that were promoted to the front page and had no login screen. Could this be a permissions issue? What might have happened and how can I restore the main page?

# Answer
The default front page at /admin/config/system/site-information for a standard installation isn't an empty string, it's `/node`, despite the text underneath the field that reads:

> Optionally, specify a relative URL to display as the front page. Leave blank to display the default front page.
> 0 votes

---
Tags: 8
---


# Question
Title: The item of an unregistered user's cart is shown a different unregistered user
Using Drupal Commerce 2 in Drupal 8.8, if an unregistered user puts something in the cart (and doesn't check it out) another unregistered user sees these items in *Cart* block (provided by view (order)). They aren't shown to the users on the /cart page.

# Answer
> 1 votes
The reason for the behavior described above is that in Views I changed the advanced option context filter - order id - for "if there is no value for the context filter" from: "static" (the option after installation, which had the effect that no cart was shown at all) to "show all results" (with the effect described above).

I found this link https://www.drupal4u.org/howtos/how-hide-empty-shopping-cart-drupal-commerce saying the correct value would be "Current user's cart order ID", but this was not available. I'm not sure if this is a bug, if things changed for Commerce 2 or if I configured something wrong.

# Answer
> 0 votes
Without know your specific site, it's hard to say what the culprit is, but this sounds like a pretty typical caching issue. Ultimately, you need to prevent Drupal from caching pages or page elements rendered for anonymous users with shopping carts.

---
Tags: commerce
---


# Question
Title: Navigate to next page / previous page based on entity reference field instead of Book module
I am trying to create next/previous page links like the Book module.

I have two content types, **Chapter** and **Page**.

The **Chapter** content type contains an entity reference field (unlimited) for pages.

So, each chapter contains an arbitrary number of pages in the entity reference field **Pages in Chapter**, and these are re-ordered to determine the order of the pages.

Now, on each **Page**, I want to make links to the previous and next pages based on the values of the parent **Chapter**'s entity reference field **Pages in Chapter**.

Specifically, using a view or block or similar on the **Page**, I need to get the **Chapter** that references the current **Page**, iterate through the values of the entity reference field **Pages in Chapter**, find the **Page** that is immediately before and the **Page** that is immediately after the current **Page**, and then output this as a simple unordered list.

I can code a little but I'm not very good so I'm having trouble finding an approach to implement this.

**What I tried**

I tried to build this in Views. The problem I encountered was that it is very difficult to iterate through the subdivision entity reference field and filter out the previous and next links.

This is a similar question for Drupal 7 but since Drupal 8 includes so much more in core (Views and Entity References, for example), I think it's fair to ask the question again.

**Why not just use the Book module?**

I only need the next/previous page functionality, and ideally it would be based on my entity reference field **Pages in Chapter**. The book module navigation in Drupal 8 doesn't follow the same patterns as the rest of core (it's not a block, and it's not a menu). I spent a couple hours this afternoon going through the Book issue queue and cleaning up old issues, and it seemed there is very little effort to "modernize" the module, so I thought it would be better to try to implement this feature on my own.

# Answer
> I can code a little but I'm not very good so I'm having trouble finding an approach to implement this.

I started 7 years ago from zero, I only knew HTML and CSS. I learned and mastered Rules & Views. But like 4 or 5 years ago, I ran into scenarios like this one where the existing modules didn't quite do what I needed or felt I had to do overkill/bulky-overhead workarounds with existing modules. So I learned PHP from online resources and I learned how to create custom modules for Drupal.

I highly suggest you improve your backend/coding game. Specially since Rules in D8 is barebones compared to D7.

> I tried to build this in Views. The problem I encountered was that it is very difficult to iterate through the subdivision entity reference field and filter out the previous and next links.

While it's possible to **programmatically** solve it with Views, it feels overkill/unnecessary to do this in Views just for prev and next links. A better approach is to create `prev_url` and `next_url` variables for Twig. Using a preprocess function we can create and pass those variables to the appropriate template file, node.html.twig in this case.

I've put lots of comments, so you can follow and hopefully learn a thing or two.

In **mytheme.theme** (since this particular hook can also be used in theme, rather than creating a custom module).

```
/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node']; // obtain current page node object
  if ($node->getType() == 'page') { // check it's a "page" content type
    $page_nid = $node->id(); // get the current page node id
    // get Chapter nids using Entity Field Query
    $query = \Drupal::entityQuery('node')
      ->condition('type', 'chapter')
      ->condition('field_reference', $page_nid); // check if current page NID is set on any Chapter's reference field
    $chapter_nids = $query->execute(); // returns array of Chapter nids
    if (!empty($chapter_nids)) { // check we have a result
      $chapter_nid = reset($chapter_nids); // Extracts the first array value, since we assume current page can only belong to one Chapter.
      $chapter_node = Drupal\node\Entity\Node::load($chapter_nid); // load chapter node
      $referenced_page_nodes = $chapter_node->field_reference; // get referenced nodes
      foreach ($referenced_page_nodes as $key => $referenced_item) { // loop though referenced nodes
        if ($referenced_item->entity) {
          if ($node->id() == $referenced_item->entity->id()) { // check if current page nid equals referenced nid
            $prev_key = $key - 1; // we'll use these keys to access prev/next array values
            $next_key = $key + 1;
            if (!empty($referenced_page_nodes[$prev_key])) { // check if previous key exists
              $prev_url = $referenced_page_nodes[$prev_key]->entity->toUrl()->toString(); // get prev URL
              $variables['prev_url'] = $prev_url; // creates prev_url variable in node.html.twig
            }
            if (!empty($referenced_page_nodes[$next_key])) { // check if next key exists
              $next_url = $referenced_page_nodes[$next_key]->entity->toUrl()->toString(); // get next URL
              $variables['next_url'] = $next_url; // creates next_url variable in node.html.twig
            }
            break; // since we found it, exit from loop as no point in continuing to loop through.
          }
        }
      }
    }
  }
}

```

<sub>**Note:** Rename `field_reference` (2 places) to the machine name of your actual reference field in Chapter content type.</sub>

In mytheme/templates/**node.html.twig**, you can place them after the `{{ content }}` part

```
{% if prev_url is not empty %}
  <span><a href="{{ prev_url }}">{{ 'Previous page'|t }}</a></span>
{% endif %}
{% if next_url is not empty %}
  <span><a href="{{ next_url }}">{{ 'Next page'|t }}</a></span>
{% endif %}

```
> 4 votes

---
Tags: navigation
---