# Question
Title: How do I stop a stuck-and-running cron job (Elysia Cron on Pantheon)?
One of my cron jobs, which are all managed by Elysia Cron and running in its default channel, is stuck and running (R). My site is hosted by Pantheon, in case that matters.

The job in question is schedule to execute at 15 minute intervals.

What do you recommend I do to stop the stuck-and-running job?

# Answer
```
 update elysia_cron set running = 0 where name = '[THE NAME IF YOUR CRON JOB]';

```

Actual sql query based on Mika A answer above
> 10 votes

# Answer
I think if the job is stuck somewhere, you may not have direct access to the process to stop it. What you can do is just set the *running* value to 0 in the \*{elysia\_cron}\* table for the corresponding job.
> 4 votes

# Answer
Pay attention, the instruction given by @t14

```
update elysia_cron set running = 0 where name = '[THE NAME IF YOUR CRON JOB]';

```

should be given directly in MySQL (command line or phpMyAdmin whatsoever). With Drush it failed to update the table
> 0 votes

---
Tags: cron
---


# Question
Title: How to configure mysql database connection with a different socket
I have a Drupal 6 site that I ran for years before walking away about three years ago. I would like to resurrect the site in a more modern CMS and am first considering Drupal 8.

I run my site on a shared server where I have my own mysql socket. In Drupal 6, I connected to the database successfully in settings.php through the following syntax:

```
ini_set('mysqli.default_socket', '/path/to/my/mysql/socket');
ini_set('mysql.default_socket', '/path/to/my/mysql/socket');
$db_url = 'mysqli://dbuser:dbpass@localhost/dbname';

```

Looking at Drupal 8's settings.php it's a completely different syntax, and I am stumped on how to configure it correctly either there or on the Database configuration screen during install.php. Googling things like "drupal 8 mysql socket" brings up old articles that aren't relevant anymore.

PHP 7.0 is provided and I don't have write access to the ini, so I can't override the socket there.

I have confirmed that the database is running with this command:

```
mysqladmin --socket=/path/to/my/mysql/socket --user=dbuser -p status

```

Any help would be greatly appreciated on how to get the database setup in Drupal 8, thank you.

Edit: from Clive's suggestion I added the ini\_set() lines above to Drupal 8's settings.php to no avail. I'm assuming it's user error at this point so I'm still trying things.

# Answer
> 1 votes
According to this Drupal issue, setting the socket in the UI is just not possible right now: (at least in 8.6.10)

https://www.drupal.org/project/drupal/issues/793200

I also could not figure out how to set the socket in sites/default/settings.php.

I had to resort to hardcoding my socket in this file:

```
core/lib/Drupal/Core/Database/Driver/mysql/Connection.php

```

This block of code:

```
    // The DSN should use either a socket or a host/port.
    if (isset($connection_options['unix_socket'])) {
      $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
    }
    else {
      // Default to TCP connection on port 3306.
      $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
    }

```

I could not find any way to set "unix\_socket" value on $connection\_options, so I resorted to hardcoding it before this block like:

```
$connection_options['unix_socket'] = '/path/to/my/mysql/socket';

```

---
Tags: 8, database
---


# Question
Title: Set value to specific custom theme setting
I noticed that I can get a specific theme setting like so

```
theme_get_setting('myvar','mytheme');

```

but I don't see a way of actually setting a setting. Something along the lines of

theme\_set\_value('myvar','mytheme','value'); I looked at the functions available to me here https://api.drupal.org/api/drupal/core%21includes%21theme.inc/8.2.x but I didn't see anything specific to my needs.

I do see there's already a question asking the same thing here How to set theme setting but that is for Drupal 7 and I'm using 8.

Is there a quick way to set the value of a specific theme setting?

# Answer
> 2 votes
Drupal 8 use configuration to store configuration settings. You can follow document. And snippet code to set new value for custom theme(replace theme\_name with your theme name).

```
$config = \Drupal::service('config.factory')->getEditable('theme_name.settings');
$config->set('variable', 'value')->save();

```

---
Tags: 8
---


# Question
Title: Add a having condition that makes use of COUNT
I currently have a query that compiles to

```
SELECT n.nid AS nid, field_data_field_date.field_date_value AS incident_date, field_data_field_tweeted_date.field_tweeted_date_value AS tweeted_date, n.nid AS n_nid, (SELECT source.field_source_value AS field_source_value
FROM
field_data_field_sources sources
left JOIN field_data_field_source source ON source.entity_id = field_sources_value
WHERE  (sources.entity_id = n.nid)
ORDER BY sources.delta DESC
LIMIT 1 OFFSET 0) AS most_recent_source
FROM
node n
left JOIN field_data_field_incident_type incidenttype ON incidenttype.entity_id = n.nid
left JOIN field_data_field_date field_data_field_date ON field_data_field_date.entity_id = n.nid
left JOIN field_data_field_tweeted_date field_data_field_tweeted_date ON field_data_field_tweeted_date.entity_id = n.nid
WHERE  (n.type = 'incident') AND (n.status = 1) AND( (incidenttype.field_incident_type_tid IN  (9,25)) )
GROUP BY n.nid
ORDER BY field_data_field_date.field_date_value DESC

```

I want to add

```
HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2

```

And I can get it to work in the query when I manually create it in my SQL gui, but I can't seem to add it to the query in drupal properly.

I added

```
$query->addExpression('HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2');

```

But that didn't add it how I wanted to the query. The query compiled to

```
SELECT n.nid AS nid, HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2
AS expression FROM {node} n left JOIN {field_data_field_incident_type} incidenttype ON incidenttype.entity_id = n.nid
left JOIN {field_data_field_date} field_data_field_date ON field_data_field_date.entity_id = n.nid
WHERE (n.type = :db_condition_placeholder_0) AND (n.status = :db_condition_placeholder_1) AND (n.created < :db_condition_placeholder_2) AND( (incidenttype.field_incident_type_tid
IN (:db_condition_placeholder_3, :db_condition_placeholder_4)) )
GROUP BY n.nid ORDER BY field_data_field_date.field_date_value

```

I'd like to have it between GROUP BY and ORDER BY since that seems to be what worked in the query I manually wrote. Also it added 'AS expression' to the end of it. Is there a way I can specifically add 'HAVING COUNT(DISTINCT incidenttype.field\_incident\_type\_tid) = 2'? Or should I be going about it a different way?

# Answer
> 0 votes
Instead of putting everything in one expression. I was able to achieve what I needed by creating an alias for the COUNT like so

```
$query->addExpression('COUNT(DISTINCT incidenttype.field_incident_type_tid)','typeCount');

```

and then add a having Condition afterwards using the alias I created like so.

```
$query->addExpression('COUNT(DISTINCT incidenttype.field_incident_type_tid)','typeCount');

```

---
Tags: 7, database
---


# Question
Title: Show logged in user's comments with views
I want to have a page/block the last/ recent comments the logged in user has posted.

I made it in D7, but I can't seems to make it happen in D8. I googled, found article but mostly for D7 or less.

Until now I created a view of comment, made the relationship to "Comment:content" and a contextual filter on "Comment: Author" ( "When the filter value is NOT available", selected "Provide Default Value" and selected "User ID from Logged in User"). I also have a filter for the specific content type I need. But I keep on having my "NO RESULTS BEHAVIOR" showing, even though the dummy user I am checking with had comments.

EDIT:

```
uuid: aa49a3ff-3284-4361-9dac-c026d7f73016
langcode: en
status: true
dependencies:
  config:
    - comment.type.comment_node_locations
    - field.storage.comment.comment_body
    - field.storage.comment.field_review
    - user.role.administrator
    - user.role.authenticated
  module:
    - comment
    - node
    - starrating
    - text
    - user
    - views_infinite_scroll
id: recent_review_user_s_profile
label: 'Recent Review - User''s Profile'
module: views
description: ''
tag: ''
base_table: comment_field_data
base_field: cid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: role
        options:
          role:
            authenticated: authenticated
            administrator: administrator
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: none
        options:
          items_per_page: null
          offset: 0
      style:
        type: default
      row:
        type: fields
      relationships:
        uid:
          id: uid
          table: comment_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: author
          required: true
          entity_type: comment
          entity_field: uid
          plugin_id: standard
        node:
          id: node
          table: comment_field_data
          field: node
          relationship: none
          group_type: group
          admin_label: 'Comment: Content'
          required: false
          entity_type: comment
          plugin_id: standard
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          relationship: node
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
        subject:
          id: subject
          table: comment_field_data
          field: subject
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: comment_permalink
          settings:
            link_to_entity: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: comment
          entity_field: subject
          plugin_id: field
        field_review:
          id: field_review
          table: comment__field_review
          field: field_review
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: starrating
          settings:
            fill_blank: 0
            icon_type: star
            icon_color: '1'
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          plugin_id: field
        comment_body:
          id: comment_body
          table: comment__comment_body
          field: comment_body
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: text_default
          settings: {  }
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          plugin_id: field
        view_node:
          id: view_node
          table: node
          field: view_node
          relationship: node
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: true
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          text: 'Read more'
          output_url_as_text: false
          absolute: true
          entity_type: node
          plugin_id: entity_link
      filters:
        status:
          value: '1'
          table: comment_field_data
          field: status
          plugin_id: boolean
          entity_type: comment
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
        status_node:
          value: '1'
          table: node_field_data
          field: status
          plugin_id: boolean
          relationship: node
          entity_type: node
          entity_field: status
          id: status_node
          expose:
            operator: ''
          group: 1
        comment_type:
          id: comment_type
          table: comment_field_data
          field: comment_type
          relationship: none
          group_type: group
          admin_label: ''
          operator: in
          value:
            comment_node_locations: comment_node_locations
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            reduce: false
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          entity_type: comment
          entity_field: comment_type
          plugin_id: bundle
      sorts:
        created:
          id: created
          table: comment_field_data
          field: created
          order: DESC
          entity_type: comment
          entity_field: created
          plugin_id: date
          relationship: none
          group_type: group
          admin_label: ''
          exposed: false
          expose:
            label: ''
          granularity: second
      title: 'My Reviews'
      header: {  }
      footer: {  }
      empty:
        area:
          id: area
          table: views
          field: area
          relationship: none
          group_type: group
          admin_label: ''
          empty: true
          tokenize: false
          content:
            value: "MY OOPS MESSAGE"
            format: basic_html
          plugin_id: text
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - user.roles
      tags:
        - 'config:field.storage.comment.comment_body'
        - 'config:field.storage.comment.field_review'
  block_my_reviews:
    display_plugin: block
    id: block_my_reviews
    display_title: 'Block My Reviews'
    position: 2
    display_options:
      display_extenders: {  }
      style:
        type: default
      defaults:
        style: false
        row: false
        pager: false
        use_more: false
        use_more_always: false
        use_more_text: false
      row:
        type: fields
        options:
          default_field_elements: true
          inline: {  }
          separator: ''
          hide_empty: false
      pager:
        type: some
        options:
          items_per_page: 4
          offset: 0
      use_more: true
      use_more_always: true
      use_more_text: 'View more'
      display_description: ''
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - user.roles
      tags:
        - 'config:field.storage.comment.comment_body'
        - 'config:field.storage.comment.field_review'
  page_my_reviews:
    display_plugin: page
    id: page_my_reviews
    display_title: 'Page My Reviews'
    position: 1
    display_options:
      display_extenders: {  }
      path: user/%user/my-reviews
      display_description: ''
      pager:
        type: infinite_scroll
        options:
          items_per_page: 6
          offset: 0
          id: 0
          total_pages: null
          tags:
            previous: '‹ Previous'
            next: 'Next ›'
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          views_infinite_scroll:
            button_text: 'Load More'
            automatically_load_content: false
      defaults:
        pager: false
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - user.roles
      tags:
        - 'config:field.storage.comment.comment_body'
        - 'config:field.storage.comment.field_review'

```

# Answer
There are several issues to address here:

You have added the Author Relationship, yet it isn't necessary, neither of your fields or filters is using it. You have required it, which excludes comments from Anonymous users, but since you're already contextually filtering real users, this is unnecessary. You should remove the Author Relationship since it adds to the performance strain but doesn't add anything useful.

You have tried adding "Comment: Author" contextual filter with the "User ID from Logged in User" option, but these aren't compatible (textual name is not the same as the numerical ID).
You need to add "Comment: Author uid" Contextual instead and configure it:
`When the filter value is NOT available`
**Provide default value**
**User ID from logged in user**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**User ID**
**Single ID**
Configure other options to your needs.

This will show the current logged in user comments.

But I also see your path is `user/%user/my-reviews`. Does this mean you want to show the *related* user comments there, and not always the logged-in user's no matter which profile they're viewing?
If so, then you need to use the **User ID from route context** option instead of the "User ID from logged in user".
> 2 votes

---
Tags: views, 8
---


# Question
Title: After upgrading from drush 7 to 8 with multisites, using drush from site directory cannot find drupal 7 (Windows)
Previously with drush 7, I could `cd` to the site directory (e.g. `sites/example1.com`) and perform drush commands (e.g. `drush st`). Now with drush 8, unless I specify the root in the drush command, it cannot bootstrap past level 0:

```
$ drush st
 PHP configuration      :  C:\wamp64\bin\php\php7.1.9\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:/Users/Dan/AppData/Roaming/Composer/vendor/drush/drush/drush.php
 Drush version          :  8.1.18
 Drush temp directory   :  C:\Users\Dan\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :

$ drush st -r c:/wamp64/www/drupal7
           Drupal version                  :  7.64
 Site URI                        :  http://example.com
 Database driver                 :  mysql
 Database hostname               :  localhost
 ....

```

I do have a `sites/sites.php` file:

```
 <?php
 $sites = [
    'dev.example1.com' => 'example1.com',
    'dev.example2.com' => 'example2.com',
    'dev.example3.us' => 'example3.us',
 ];

```

Local site `sites\example1\drushrc.php` file:

```
<?php
$options['l'] = "http://dev.example1.com";
$options['r'] = 'c:/wamp64/www/drupal7';

```

Without the -r root option, drush doesn't load the `sites.php` or the `drushrc.php`.

Drush is installed globally using composer. It was not installed as part of drupal 8.

MORE INFO: Oddly, drush 8 is working with drupal 8 in a multisite directory.

# Answer
It appears that drush 8 does not support drupal projects that were not built with composer. Drush 7 does not have this requirement. I added this `composer.json` to the drupal 7 root directory:

```
{
  "require": {
    "drush/drush": "~8.0"
  },
  "extra": {
    "installer-paths": {
       ".": [ "type:drupal-core" ]
    }
  }
}

```

I found this in an issue for project `drupal-finder`, which seems to be used by the Drupal 9 `Drupal Launcher`. I'm guessing that drush 8 has similar code.
> 2 votes

---
Tags: drush, multi-sites
---


title: How to set a custom class to submenus

text:
# Question
Title: How to set a custom class to submenus
I am working on sidebar menu in a Custom Drupal 8 Theme. I am trying to set a class of sidebar\__menu--submenu-1,sidebar\__menu--submenu-2, sidebar\__menu--submenu-3 and so on depending on the level of the submenus.

So far, I was able to add the class sidebar\__menu to the first level & sidebar\__menu--submenu to all the submenus. However, I want to add the class sidebar\__menu--submenu-(number of the level) so I can style & control the sidebar better on css.

Any help will be really appreciate it!

Here it is my code menu.html.twig:

```
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level, menu_name) %}
  {% import _self as menus %}
  {%
    set menu_classes = [
      'sidebar__menu' ~ menu_name|clean_class,
    ]
  %}
  {%
    set submenu_classes = [
      'sidebar__menu' ~ menu_name|clean_class ~ '--submenu',
    ]
  %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('container mx-auto', menu_classes) }}>
    {% else %}
      <ul {{ attributes.removeClass(menu_classes).addClass(submenu_classes) }}>
    {% endif %}

    {% for item in items %}
     {%
      set classes = [
        'sidebar__item',
        item.is_expanded ? 'sidebar__item--expanded',
        item.is_collapsed ? 'sidebar__item--collapsed',
        item.in_active_trail ? 'sidebar__item--active-trail',
      ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

```

# Answer
Here's one way to modify your code to add a unique class for each menu level dynamically:

1. Add a new class appended with the value of `menu_level` plus one:

```
  {%
    set submenu_classes = [
      'sidebar__menu' ~ menu_name|clean_class ~ '--submenu',
      'sidebar__menu--submenu-' ~ (menu_level + 1),
    ]
  %}

```
2. Remove the previously added class, otherwise I believe it will add the class for each level incrementally.

```
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('container mx-auto', menu_classes) }}>
    {% else %}
      <ul{{ attributes.removeClass(menu_classes, 'sidebar__menu--submenu-' ~ (menu_level)).addClass(submenu_classes) }}>
    {% endif %}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How do I target Ajax Loader Throbber in CSS?
I recently installed Ajax Loader and it working great. However, I need some custom styling so, I can display the loading throbber in the center of the screen.

I can write my own CSS, But can't find the target class of Ajax Loader.

Looking forward for any help on this issue. Thanks in advance

# Answer
> 2 votes
To target the overlay you can use .ajax-progress and to target the throbber you can use .ajax-throbber.

Something like this would position the throbber on the center of the screen:

```
.ajax-progress {
  position: fixed;
  z-index: 99999999;
  background: rgba(255,255,255,0.6);
  text-align: center;
  width: 100%;
  height: 100%;
  top:0;
  left:0;
}

.ajax-throbber {
  left: 0;
  position:absolute;
  right:0;
  top: 50%;
  transform: translateY(-50%);
}

```

---
Tags: 7
---


title: Remove file pages

text:
# Question
Title: Remove file pages
Forgive me if this has already been addressed, I searched for it but couldn't find a similar issue. I'm using the file entity module and it automatically generates a page for each of the files. This causes SEO problems (Not sure how the crawler is finding them) because the pages arn't setup for it. I would really like to just eliminate the pages from show up. Does anyone know how to pull this off?

# Answer
> 0 votes
AFAICT the File entity module is all about adding the feature how to handle files by creating entities and their pages. If you delete the page, you also delete the file.

Is there any reason why you're using this module? Maybe you don't even need it?

If you disable and uninstall the module the files will remain, although you should test this first before applying to the main site (backup everything first, although backups are a must either way).

Have you tried `view files` Permission? Maybe you can restrict viewing the pages, while the files may be available through a reference on Content types.

Add this to your robots.txt to make the search engines not index these pages:

```
# Custom - added on Feb 28 2019
Disallow: /file/

```

Drupal 7 robots.txt

---
Tags: 7, files
---


title: Use of batch in REST endpoints

text:
# Question
Title: Use of batch in REST endpoints
I want to use batch in POST in rest endpoints in Drupal 8, but my batch is not getting progressed. I am creating rest endpoints for my module which will send email to bulk users. So for this purpose I need to use batch which will send email to all users without giving time out error. Please help.

my source code is:

```
class BatchController {

    public static function callBatch() {

        $batch = array(
        'title' => t('Sending ...'),
        'operations' => [],
        'init_message' => t('Sending is starting.'),
        'finished' => '\Drupal\module_mail\sendEmails::sendEmailsItemCallback',
        );

        $subject='hello';
        $body='body';

        $data = array(0 => array('id'=>1,'Fullname'=>"joy", 'Email'=>"example@gmail.com")
            );
        foreach($data as $row) {
        $batch['operations'][] = ['\Drupal\module_mail\sendEmails::sendEmailsUserItem',[$row,$subject,$body]];
        }
        batch_set($batch);
        return batch_process('home');
    }

}

namespace Drupal\module_mail;

class sendEmails {

    public static function sendEmailsUserItem($user, $subject, $body, &$context)
    {
        $message = 'Sending emails';
        $mailManager = \Drupal::service('plugin.manager.mail');
        $module = 'module_mail';
        $key = '';
        $to= $user['Email'];
        $params['email_body'] = $body;
        $params['email_subject'] = $subject;
        $langcode = \Drupal::currentUser()->getPreferredLangcode();
        $send = true;
        $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
    }

        //batch completed
    public static function sendEmailsItemCallback($success, $results, $operations)
    {
        if ($success) {
            $message = \Drupal::translation()->formatPlural(
                    count($results),
                    'sent.',
                    'Emails sent succesfully'
            );
        }
        else {
            $message = t('Finished with an error.');
        }
        drupal_set_message('Sent succesfully');

    }

}

```

Right now I am getting this output:

# Answer
> 1 votes
Batch API operations are driven by the end user and browser with meta refresh, which makes it not possible to use in web services. However we can think about implementing the same thing using Queue API.

This should give you enough to go on to re-implement your RestResource or Controller to use your own Queue service.

### Summary

I've used the following pattern in the past.

1. First request has a payload that can instantiate the operation.
    * It's important to make sure we're not flooding the serve so make sure you have flood protection.
    * Make sure that we have access to do the operation.
2. A response is returned with progress state and a queue item ID.
3. Subsequent requests have a payload with the queue item ID from the previous response.
    * These requests process 1..n queue items.
    * We need to claim queue items ourselves because we're processing queue items manually and not with a cron queue worker.
    * Make sure that things are valid and return the appropriate response code for validation, fatal or other errors.

### Request payloads

* Initial: `{"queue": null}`
* Subsequent: `{"queue": {"item_id": 1}}`

### Response payloads

Initial
```
{
   "success": true,
   "finished": false,
   "queue": {"item_id": 1},
   "progress": 0,
   "max": 23,
   "errors": [],
   "result": "something custom here",
}

```
Finished
```
{
   "success": true,
   "finished": true,
   "queue": null,
   "progress": 23,
   "max": 23,
   "errors": ["something wrong happened at some point"],
   "result": "something custom here",
}

```

### Queue API

The complexity here is that we cannot use cron queue workers. So we need to implement the database calls to get and claim queue items ourselves. Unfortunately the current Queue API classes are pretty limited in both Drupal 7 and Drupal 8. In the former, I used custom functions to fetch and update queue items directly from the database while in the latter we can create our own service, based on DatabaseQueue, and inject that into your RestResource plugin or Controller.

# Answer
> 0 votes
I had the same trouble running batches like this before as the classes were not loading properly. I suspect you might have the same problem. You can probably find in your database logs something like this

> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, class '\Drupal\module\_mail\sendEmails' not found

In such situations I usually include the functions as a file.

Create a file in your `MODULENAME/module_mail.emails_batch.inc` and in it your email processing logic as functions and not as class methods.

```
function module_mail_sendEmailsUserItem($user, $subject, $body, &$context)
{
// ...
}

//batch completed
function module_mail_sendEmailsItemCallback($success, $results, $operations)
{
// ...
}

```

and modify `finished` and `operarations` and callback function keys as follows

```
$batch = array(
  // ...
  'finished' => 'module_mail_sendEmailsItemCallback',
  'file' => drupal_get_path('module', 'batch_emails') . '/batch_emails.emails_batch.inc',
);

```

also need to change callback function

```
foreach($data as $row) {
  $batch['operations'][] = ['module_mail_sendEmailsUserItem',[$row,$subject,$body]];
}

```

**NOTE:** make sure `batch_process('home');` home is a valid path perhaps you can use `batch_process('<front>');` or `batch_process('node/1');`

---
Tags: 8, batch-operations
---


# Question
Title: What is the purpose of aggregation in view?
What is the purpose of aggregation in view?

And why is it important to enable him when you make charts?

# Answer
Without aggregation, Views fetches data from the database and lists that data in individual "rows".

When you turn on Aggregation some mathematical functions can be applied to the existing results under certain conditions. That is how you might get the SUM of all the values of a field, or the AVERAGE etc.

Charts usually don't display individual "rows" of data, they display statistical data that you get from calculating some values from the *entire* results list. That is why charts need Aggregation - to get to the numbers that are shown on the chart.
> 2 votes

---
Tags: views, 8, charts
---


# Question
Title: Cannot apply my custom styles to HTML tags in ckeditor
I'm using Drupal 8 and am trying to make ckeditor truly wysiwyg.

To that end I've successfully gotten ckeditor to use a custom stylesheet by adding a ckeditor\_sylesheets key to my theme's info.yml and my stylesheet's path as the value.

If within my custom stylesheet I create styles and assign them to a class, those styles are reflected within the form if I reference the class.

However, if within my stylesheet I define a style for an HTML element (e.g. h1, p, etc.) ckeditor ignores those styles.

This is the case regardless of how I set or unset "Limit allowed HTML tags and correct faulty HTML" and "Correct faulty and chopped off HTML" at /admin/config/content/formats.

As I mentioned, clearly ckeditor is accessing my stylesheet as styles assigned to classes work. Also, I can see the stylesheet in Chrome's inspector. If I inspect a HTML tag for which I've defined a style it shows me that user agent stylesheet is being used.

I don't think it matters but just in case; I'm using Seven for my administrative theme and my default theme is a sub-theme of bootstrap.

If someone could give me a clue I'd appreciate it.

# Answer
So I resolved this problem by clearing cache. Not Drupal's cache (I'd tried that about a zillion times) Chrome's cache. Duh.
> 0 votes

---
Tags: wysiwyg, input-formats
---


title: Add image to RSS Feed

text:
# Question
Title: Add image to RSS Feed
We are using the `Feed` Display for a view where we want to display all `Articles` in a `rss.xml` file. Below are the View settings. However, we cannot find a way to add an image attribute that meeting the RSS 2.0 specs.

**How can we add an image to the `RSS` feed display?**

View settings:

1. Format: Rss Feed
2. Show: Fields | Settings
3. Fields: `content: title`, `content: body`, `tracker: updated date`, `content: link to content`, `content: authored by`
4. Feed settings: path = `some/path/rss.xml`
5. Filter criteria: `published = yes` and `Content type = Articles`

When you click on settings in the `Show` section, we assigned the fields.

1. title field -\> content: title
2. link field -\> content: link to content
3. description field -\> content: body
4. creator field -\> content: authored by
5. publication date field -\> tracker: updated date

What we tried:

* Include `field_image` under `fields` and hide from display
* Rewrite the output of the body to include the following `<enclosure url="{{field_image}}" length="100" type="image/jpg" />`
* The `{{ field_image }}` is the available token after reordering field image under `Fields` section so that it is above `body` field.

Results of what we tried:

`<description>some body text **blank space where <enclosure> should display** </description>`

Expected output (cannot get this result because `<enclosure>` is stripped even when `Strip HTML is false`):

`<description>some body text</description>
<enclosure url="{{field_image}}" length="100" type="image/jpg" />`

# Answer
> 0 votes
I found there is a patch that works for exactly what we need. Support enclosure field in Views RssFields row plugin

---
Tags: views, 8, hooks, feeds
---


# Question
Title: Login user programatically (Create user session)
My question is based on this question: Programmatically User login not working i dont have this clear, to login an user (create an active session) only need use User::Load()? i'm triying make this on my custom module, due to i need an independent login and register form, but dont work. Someone can help me? i want create a user session and let the user navigate for all sections that your role have assigned, but without pass by "user/login" route. Thanks in advance. On resume i want emulate the login controller shipped with drupal 8.

# Answer
`User::load()` loads information about an account, it does not inject or alter the current session in any way. `user_login_finalize()` is one of the key functions when doing programatic user logins because it will create and set a session for the current user.

See more: https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user\_login\_finalize/8.7.x
> 5 votes

---
Tags: users
---


title: How do I re-order tabs in user page?

text:
# Question
Title: How do I re-order tabs in user page?
I'm developing a drupal 7 based website where the user profiles need some modification. Now I need to know how can I re-order tabs in user profile page such as, View, Edit, etc.

i'd like to keep the current tabs, but just reorder them. I'm looking for an easy way to do that.

# Answer
> 1 votes
You can use hook\_menu\_local\_tasks\_alter for example in the bellow example i will change the order between tab 2 and tab 3:

```
/**
 * Implements hook_menu_local_tasks_alter().
 */
function YouModule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if (isset($data['tabs'][0]['output'])) {
   $data['tabs'][0]['output'][0]['#weight'] = 0;
   $data['tabs'][0]['output'][1]['#weight'] = 2;
   $data['tabs'][0]['output'][2]['#weight'] = 1;
   $data['tabs'][0]['output'][3]['#weight'] = 3;
   $data['tabs'][0]['output'][4]['#weight'] = 4;
  }
}

```

---
Tags: 7
---


# Question
Title: How to place facet block in views page header? (not regions)
I've created a search with Search API module and Facets module. I've added two taxonomy term name fields to my search index and created two facets for those fields. Just for testing I've placed the facet blocks in my main content area, and fulltext search and faceted filtering are working as expected.

Now I want to place the facet blocks in the header of the view, and not in a page region. I've checked the block source file and ID of the facet blocks is `facet_block`. Facet blocks are derived blocks, so my best guess was that the block ID should be `facet_block:MACHINE_NAME_OF_FACET`.

I've added a `Global: Rendered entity - Block` to the header of the view. As block ID I've entered the schema from above, e.g. `facet_block:museum` for my "museum" facet.

However, the facet block doesn't show in the views header. (The same facets placed via block layout still work fine.)

Can anybody tell me how to render facet blocks **inside a view header**?

(I'm looking for a no-code-solution, without preprocessing or editing templates)

# Answer
Firstly, I would recommend that you consider placing the facet block right above the view instead of performing a surgery on views :D

That said, here's what I think *might work*:

# Solution 1: Views Header

* Views allows you to attach rendered blocks in the views header.
* In the views UI, click the *Add* button in the *Header* configuration.
* Then choose *Rendered Entity - Block* and choose the facets block you want to display

# Solution 2: Attachment Before

* Write a `hook_views_post_build()`
* In this hook, render the facet block as the `attachment_before` of the view.
* You might face some difficulties with views caching, etc, but you can fine-tune the views build to alter the caching rules.
* If you don't like the idea of *Attachment Before*, you can also consider adding a header item with a custom token like @facet:foo@ and then replace this custom token with a rendered facet block in `hook_views_pre_render()`

I hope this helps!
> 2 votes

# Answer
Since you want a no-code solution, have you tried the Views Block Area module? It allows injection of blocks anywhere in a view. Once enabled you should see a "Block area" option in your view then select the facet you want shown in the view header. Should be able to do everything via the UI alone.

> This module exposes all available blocks as a views area or field. This way you can add any block inside a field, footer or header in your view.
>
> *Blocks that are generated by views can not be selected, these blocks can not be inserted into views.*
> 2 votes

# Answer
This is an addition to @Jigar Mehta answer but I couldn't add it as comment because I needed more space.
There are some gotchas in Solution 1:
1. You need to create a facet and then place somewhere in the page.
2. You need to use the machine name of the block in *Render Entity - Block* form. No need to add `facets:MACHINE_NAME_OF_FACET`
3. The main issue is that the block needs to appear in the same page as the view so that it renders. It doesn't even render in the view preview section unless you save and visit that page.
4. I tried disabling the block while being placed in sidebar, or add a visibility rule that only makes it display on admin pages. Any rule that prevent its rendering prevents it from rendering in the view header.

Thus the only solution I see INMHO is to hide the actual block facet with CSS, but then this doesn't make sense since you can simply use the block on top of the view and not in the header unless there is a dire need for it.

## Solution 3

You can also try this module Core Views Facet
I think it might solve your problem by having facets attached to a view as exposed filters.
> 0 votes

---
Tags: 8, search
---


title: How to print H1 instead of H2 for Panel

text:
# Question
Title: How to print H1 instead of H2 for Panel
This is the template currently being used:

panels-pane.tpl.php

```
<?php if ($pane_prefix): ?>
  <?php print $pane_prefix; ?>
<?php endif; ?>
<div class="<?php print $classes; ?>" <?php print $id; ?> <?php print $attributes; ?>>
  <?php if ($admin_links): ?>
    <?php print $admin_links; ?>
  <?php endif; ?>

  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <<?php print $title_heading; ?><?php print $title_attributes; ?>>
      <?php print $title; ?>
    </<?php print $title_heading; ?>>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

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

  <div class="pane-content">
    <?php print render($content); ?>
  </div>

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

  <?php if ($more): ?>
    <div class="more-link">
      <?php print $more; ?>
    </div>
  <?php endif; ?>
</div>
<?php if ($pane_suffix): ?>
  <?php print $pane_suffix; ?>
<?php endif; ?>

```

The variable `$title_heading` is h2. It comes in `$content`

panels.module

```
  $vars['title_heading'] = !empty($content->title_heading) ? $content->title_heading : variable_get('override_title_heading', 'h2');

```

However, I see no way of supplying it, and cannot create it in my Fieldable Pane Panel:

If I try to add a field, it comes with the `field_` prefix, and I just need a plain `title_heading`.

How can I overcome this?

# Answer
> 0 votes
This feature is intended for Node title not Fieldable Panels Panes as per the screenshot below:

Your best option is to override the `panels-pane.tpl` according to theme suggestions for your target pane and manually add the `<h1>` tag in place of the `$title_heading` variable.
It might not be an elegant solution but it works!

---
Tags: 7, panels
---


# Question
Title: How to call User::load with dependency injection
I have code that worked, but I wanted to clean it up and use dependency injection. I'm working in a BlockBase that implements ContainerFactoryPluginInterface.

```
class DefaultBlock extends BlockBase implements ContainerFactoryPluginInterface {

```

I need to access some information from the user object. Right now I'm using Drupal\Core\Session\AccountProxyInterface. This works fine, but doesn't give me all the information I was expecting. I have a contrib module adding a field to the user. I can access that field if I use User::load($id) however, I get the warning that...

> User::load calls should be avoided in Drupal classes, use dependency injection instead

So I'm trying. And failing.

This code works...

```
$userIdx = \Drupal::currentUser()->id();
$userx = \Drupal\user\Entity\User::load($userIdx);
$countryx = $userx->country_iso_code_2;

```

But when I clean that up and do it the right way, I can't get that country\_iso\_code\_2 information.

Here is the code I'm "trying" to work with...

```
<?php

namespace Drupal\country_selector\Plugin\Block;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Country switcher"),
 * )
 */
class DefaultBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $account;

  /**
   * Class constructor.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->account = $account;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $userIdx = \Drupal::currentUser()->id();
    $userx = \Drupal\user\Entity\User::load($userIdx);
    $countryx = $userx->country_iso_code_2;

    $userId = $this->account->id();
    $country = $this->account->country_iso_code_2;
    .....

```

When I debug, I see that:

> $userx is Drupal\user\Entity\User
>
> $user is Drupal\core\Session\AccountProxy

So I get that I'm working with two different things. I just don't understand how I'm supposed to call something like User::load with dependency injection.

I hope that makes sense. Would love some advice!

# Answer
> 8 votes
You should use entity\_type\_manage to get the user storage. Something like this:

```
<?php

namespace Drupal\country_selector\Plugin\Block;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\UserStorageInterface;
/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Country switcher"),
 * )
 */
class DefaultBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $account;
  protected $userStorage;

  /**
   * Class constructor.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account, UserStorageInterface $user_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->account = $account;
    $this->userStorage = $user_storage;
  }

  /**
   * {@inheritdoc}
  */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user'),
      $container->get('entity_type.manager')->getStorage('user')
    );
  }

  /**
   * {@inheritdoc}
  */
  public function build() {
    $build = [];

    $userIdx = $this->$acount->id();
    $userx = $this->userStorage->load($userIdx);
    $countryx = $userx->country_iso_code_2;
    .....

```

Hope this helps.

---
Tags: 8, dependency-injection
---


# Question
Title: Adjusting Height of Panel Columns using CSS
I am using panel-2col-brick to make a 2 x 2 information block. The HTML structure of the page is as follows

```
<div class="panel-display panel-2col-bricks clearfix">
  <div class="panel-panel panel-col-top">
  <div class="center-wrapper">
      <div class="panel-panel panel-col-first"></div>
      <div class="panel-panel panel-col-last"></div>
  </div>
  </div>
  <div class="panel-panel panel-col-middle">
  <div class="center-wrapper">
      <div class="panel-panel panel-col-first"></div>
      <div class="panel-panel panel-col-last"></div>
  </div>
  </div>
</div>

```

Now i need to change height of the second occurrence of panel-col-first and panel col-second. I have tried

```
.panel-2col-bricks .center-wrapper .panel-col-first:first-of-type,
.panel-2col-bricks .center-wrapper .panel-col-last:first-of-type{
       height:80px;
       overflow:hidden;
}

```

However this changes the height of both top-first and bottom-first columns. Is there any way i can adjust height of both rows separately ?

# Answer
to achieve this you need make use of CSS pseudo selectors and apply them in the correct element, a good approach can be this:

```
.panel-2col-bricks > .panel-panel:nth-child(2) .center-wrapper .panel-col-first,
.panel-2col-bricks > .panel-panel:nth-child(2) .center-wrapper .panel-col-last

```

You can see this in action in the link below: https://codepen.io/anon/pen/xBZGGb
> 1 votes

# Answer
With the help of Jjsg08's idea of CSS pseudo selectors i was able to figure it out. The idea is to jump in multiples of 2. So `.center-wrapper:nth-child(2)` will apply to first row whereas `.center-wrapper:nth-child(4)` will apply to second. Strange as it may seem, as i have only **two** center-wrapper elements in the code, it works.
> 1 votes

---
Tags: theming, panels
---


title: Direct query with Search API Solr

text:
# Question
Title: Direct query with Search API Solr
I am new to Drupal. I'm trying to implement advanced search on my Drupal8 website. It's working perfectly with the logical operator 'OR' and 'AND' but not with 'NOT', '+', '-'.

Here is my request :

```
$index = \Drupal\search_api\Entity\Index::load('videos_full');
    $query = $index->query();
    $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
                  ->createInstance('direct');
    $query->setParseMode($parse_mode);
    $query->addCondition('search_api_language', \Drupal::languageManager()->getCurrentLanguage()->getId());
    $query->addCondition("status",5);

    $query->setFulltextFields(['field_title', 'title', 'resourcetype', 'tag', 'choreographer', 'director', 'producer', 'structure', 'contributor', 'secondaryauthor']);
    $query->keys($search);

    $query->sort('created','DESC');
    $results = $query->execute();

```

Thank you for your help !

# Answer
Please refer to following Drupal documentation example for advanced configuration of search query:

https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

$query-\>keys($search);

'+', '-' works by default in $search(searched keyword)
> 0 votes

---
Tags: search
---


# Question
Title: How to show/hide the prefix/suffix of fields in node templates?
I previously asked a question about hiding the prefix/suffix in `fields template` here, now I want to understand how can I programmatically hide the prefix or suffix of numeric fields in `nodes templates` only?

# Answer
On node level you can configure the content of prefix and suffix in the field settings and you can show/hide them for each view mode separately.

So you rarely need to override this programmatically and this is not easy, because the prefix and suffix is not added as extra render elements, but to the markup string of the formatted field value. So you need string manipulation to subtract the prefix and suffix again.

A simple solution could be to display the database value, and so bypassing the field template altogether, by using the node object:

```
{{ node.field_example.value }}

```

But then you lose all formatting options, not only prefix/suffix.
> 1 votes

# Answer
You could remove the prefix via

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

In case you need it for comments.

```
/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_comment_view_alter(array &$build, CommentInterface $comment, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if ($comment->getFieldName() === 'field_name') {
    unset($build['#prefix']);
  }
}

```
> 1 votes

---
Tags: theming, 8, nodes, entities
---


title: Block machine name

text:
# Question
Title: Block machine name
How do i get the block machine name `$block_id` programmatically in Drupal 8?

```
$block_id = 'machine_name_to_determine';

$block_config = \Drupal\block\Entity\Block::load($block_id);

```

# Answer
> 1 votes
Here is a helper function to get the block content by machine name:

```
/**
 * @param $machine_name
 *
 * @return \Drupal\block_content\Entity\BlockContent|\Drupal\Core\Entity\EntityInterface|null
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 */
function getBlockContentByMachineName($machine_name) {
  // Get the block id from machine name.
  $query_result = \Drupal::entityTypeManager()
    ->getStorage('block_content')
    ->getQuery()
    ->condition('machine_name', $machine_name)
    ->range(0, 1)
    ->execute();
  // Get the block id.
  $block_id = reset($query_result);
  if ($block_id) {
    $block = \Drupal\block_content\Entity\BlockContent::load($block_id);
    return $block;
  }
  else {
    return NULL;
  }
}

```

Use example:

```
$machine_name = 'machine_name_to_determine';

$block_content = getBlockContentByMachineName($machine_name);

```

`$block_content` is an instance of `BlockContent` you can do what you want with it for example get the build using:

```
 $build = \Drupal::entityTypeManager()
    ->getViewBuilder('block_content')
    ->view($block_content);
$block_render = render($build);

```

# Answer
> 0 votes
Why do you need the block's machine name? You can get the block ID from the admin interface. Then you can load the block using the ID.

Go to the block layout page https://example.com/admin/structure/block and from there, you can get the block ID. Simply click or hover on edit to get the ID from the edit URL of a block.

```
$block_details = \Drupal::entityTypeManager()->getStorage('block_content')->load($block_id);
$body_value = $block_details->body->view('full');

```

In this way, you get the various values attached to a block. I don't know what you want exactly, I hope this code may help you.

---
Tags: blocks, hooks
---


title: How to modify contact form

text:
# Question
Title: How to modify contact form
I'm trying to modify the contact form to add a privacy clause before the "Send" button, I have to add a text and two mandatory check boxes. But I just started with and I have not much idea.

Thanks.

# Answer
You can go to `/admin/structure/webform` and then click `Build` on the form you are using as a contact form.

Then you can click `Add element` and add your checkboxes or any other field you need.

The option to make the checkboxes mandatory will be under `Form validation`.
> 0 votes

---
Tags: forms, webforms
---


# Question
Title: Geofield (geocode from another field) - database entry not created
On a Drupal 7.63 site, I have a content type with a "Postal Address" field (address module, v7.x-1.3) (mandatory) and a "Geofield" field (geofield module, v7.x-2.4). The geofield field has no input interface: it uses the "Geocode from another field" widget and is configured to use the Postal Address field as a source. Its information is then used to render a small map using Google Map ("Geofield map").

My issue is that when creating new nodes, the geofield field remains empty and no map is rendered. And when updating the address on existing nodes, the map isn't updated (it still shows the old point).

I checked directly in the database (table `field_data_field_geofield`), and can confirm that the rows corresponding to the new nodes are *not* there. So it seems the data is never created in the table, but I don't know why.

I see no error message on the edit page of the nodes or in the recent log page (admin/reports/dblog).

The addresses used for those nodes are correctly formed and stored (I checked the `field_data_field_adresse` table); they are rather simple and can easily be found on Google Maps. (Example: Grand-Rue 5, 2900, Porrentruy, Switzerland)

I tried applying the patch provided in this issue, but it didn't solve my problem, even when creating new content (I have since rolled back this change). Maybe it's not the same problem.

**Update:** after more research, this issue seems to describe my problem. However:

* applying patch #29 doesn't solve the problem
* applying patch #41 doesn't solve the problem
* downgrading geocoder to v.1.3 doesn't solve the problem either.

Any suggestion on what is wrong would be greatly appreciated. What else should I check for?

(It's on a website that has used this system for several years and it's the first time I see this problem.)

(I created a request support ticket on the geofield page last week, but so far I haven't received any feedback.)

# Answer
> 0 votes
So in the end the problem actually had two causes, which made it more difficult to solve than it should have been:

1. a bug in the geocoder codebase (solution: apply this patch)
2. the Google Maps API key used in the geocoder configuration was actually invalid for this type of operation, and so I had to generate another key specifically for geocoding operations. (I noticed the problem via a geocoder error saved in the recent log entries pages.)

---
Tags: 7
---


title: How do I update from 8.4.5 to 8.5.0?

text:
# Question
Title: How do I update from 8.4.5 to 8.5.0?
I am trying to update Drupal core using Composer, but I am not able of doing it. I have followed a few blog posts, but nothing worked for me. This is the output of `composer update drupal/core --with-dependencies`.

>

# Answer
Hard to say without seeing files like `composer.json`

I had the same error "Nothing to install or update".

Here is what I’ve done and it worked :

In composer.json :

add

```
"require": {
        ---
        "drupal/core": "~8.5"
    },

```

remove if you have this :

```
"replace": {
    "drupal/core": "^8.x"
},

```

delete `vendor` folder

delete `composer.lock` file

Then `composer update --with-dependencies`
> 1 votes

# Answer
In my case I explicitly had to include `webflo/drupal-core-require-dev` in the update statement, as documented on the Drupal Composer template project

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

```
> 1 votes

# Answer
I am currently going from 8.4.8 - 8.6.10 After successfully running these commands below from the posts above:

1. change in composer.json:

"require": {

```
  "drupal/core": "~8.6.10"

```

},
2. deleted vendor folder
3. deleted composer.lock file
4. Ran in terminal:

composer update --with-dependencies

There were no errors in the terminal - however I now had the Drupal WSOD. Checking the log files showed that there were now 2 core folders : one one in the root and one in vendor/Drupal/.

In the error.log I have the following error:

Class 'Drupal\Core\Session\AccountInterface' not found in /home/xxx/xxx/xxx/core/includes/bootstrap.inc on line 65

I don't believe this is a valid upgrade path.

It is currently recommended to use composer to update Drupal projects using the following post. https://www.jeffgeerling.com/blog/2018/converting-non-composer-drupal-codebase-use-composer

================================

Update: I have got the upgrade working with the following steps:

Review all file permissions

deleted vendor folder

deleted composer.lock file

Update ownership - especially for sites/default/files

sudo chmod -R 777 sites/default/files

I then had to explicitly add various modules in use that wouldn't be installed update required in composer.json:

"require": {

```
  "composer/installers": "^1.0.24",

  "wikimedia/composer-merge-plugin": "^1.4",

  "squizlabs/php_codesniffer": "3.*",

  "drupal/flysystem": "^1.0",

  "twistor/flysystem-stream-wrapper": "^1.0",

  "drupal/flysystem_s3": "1.x-dev",

  "drupal/feeds": "^3.0",

  "drush/drush": "^9.5"

}

```

With drush installed run the following commands:

vendor/bin/drush cr

vendor/bin/drush updb

vendor/bin/drush entup

And I now have a working Drupal site from 8.4.8 to 8.6.10!
> 0 votes

---
Tags: 8, updating
---


# Question
Title: Create Custom Date Formatter for Date Posted Field
I followed a very helpful article by Antonio Benitez that gave some example code showing how to create a custom date formatter for date fields (How To Create a Custom Format for a Date Field). The code adds an additional format option in the manage display settings page. This works great for date fields I have created (such as an event date for an event content type) but it is not applying to the existing date fields such as the node posted date. How can I make this custom formatter apply to system date fields such as the posted date, so that it appears as an option on the manage display page as well?

I am reproducing the code Antonio posted in his article here:

```
/**
 * Implements hook_field_formatter_info().
 */
function custom_module_field_formatter_info() {
  return array(
    'custom_date_format' => array(
      'label' => t('Custom date format'),
      'field types' => array('date', 'datestamp', 'datetime'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function custom_module_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  foreach ($items as $delta => $item) {
    $element = array(
      'element' => $item,
      'field' => $instance,
      'display' => $display
    );
    $elements[$delta] = array(
      '#theme' => 'custom_module_formatter_' . $display['type'],
      '#element' => $element,
      '#field' => $field,
    );
  }

  return $elements;
}

/**
 * Implements hook_theme().
 */
function custom_module_theme() {
  $themes = array(
    'custom_module_formatter_custom_date_format' => array(
      'variables' => array(
        'element' => NULL,
        'field' => NULL,
      ),
    ),
  );
  return $themes;
}

/**
 * Implements theme function
 */
function theme_custom_module_formatter_custom_date_format($vars) {
  $element = $vars['element'];
  $field = $vars['field'];

  // Configure custom date
  $format_date = 'd M';
  $timezone_bd = date_get_timezone_db($field['settings']['tz_handling']);
  $publish_date = DateTime::createFromFormat('Y-m-d H:i:s', $element['element']['value'], new DateTimeZone($timezone_bd));
  $date = format_date($publish_date->getTimestamp(), 'custom', $format_date);
  $date = explode(' ', $date);

  // Declare array for render content with custom format and tags
  $render_array = array(
    'date' => array(
      'date-day' => array(
        '#prefix' =>'<span class="date-day">',
        '#markup' => $date[0],
        '#suffix' => '</span>'
      ),
      'date-month' => array(
        '#prefix' =>'<span class="date-month">',
        '#markup' => $date[1],
        '#suffix' => '</span>'
      ),
    ),
    '#theme_wrapper' => array('container'),
  );

  return render($render_array['date']);
}

```

# Answer
In Drupal 7, the created and updated "fields" on nodes (and other entities) are properties and not proper fields. The display values for these are created in the default `template_preprocess_node()` provided by core, which some theme and modules may override.

Note these lines:

```
$variables['date'] = format_date($node->created);
...
// Display post information only on certain node types.
if (variable_get('node_submitted_' . $node->type, TRUE)) {
  $variables['display_submitted'] = TRUE;
  $variables['submitted'] = t('Submitted by !username on !datetime', array(
    '!username' => $variables['name'],
    '!datetime' => $variables['date'],
  ));
  ...
}

```

So, if you want to change how this is displayed, you need to implement your own `template_preprocess_node()` (you can do this in a theme or module), and provide your own logic. You can either update the existing variables, which will allow the existing templates to be used, or you can add new variables and also provide your own node templates. Typically, I do the later.
> 1 votes

---
Tags: 7, theming, datetime
---


# Question
Title: Taxonomy filter exposed to user that dynamically only includes terms attached to currently published content
Background: a) Taxonomy: I have built as site that allows users to tag content of a particular content type with tags. The system started with a pre-existing taxonomy before any content was added, but has grown organically as users add content and terms of their own. What this means, of course, is that at any time, some of the terms in the taxonomy, may not be attached to any currently published content.

b) View with Exposed Tag Filter: As a means to allow users to find material of interest, I have exposed the Tag Field as a filter for a tabular view of the content. The Filter is a drop down list. When a user selects a tag from the list, the view is appropriately filtered to the matching items.

Problem: As the taxonomy has grown, a good proportion are not, at any time, attached to any content. Thus, it is frustrating for the user to filter the table with a tag list that includes these terms, as they yield 0 results.

Requested Help: Therefore, I am looking for a way, that the terms shown in the tag filter are dynamically limited to only those that are attached to currently published content. It is not clear to me how to do it. I would greatly appreciate any advice on how this may be accomplished.

# Answer
You should have a look at Views Selective Exposed Filters, part of the Views Hacks module. It will limit the taxonomy terms to those in your view's result set.
> 0 votes

# Answer
The best answer would be: **Search API Views**.

List of nodes using **faceted taxonomy term filters**. By default faceted taxonomy filter will show only for **terms 'in use'**.

Still, if you really need to show a filter to **terms only in published nodes**, I believe this is gonna be achieved **by code** using some **hook** to **alter the facets**, or, automatically, if the current user does not have permission to **view unpublished nodes** the facet filter won't show the term.
> 0 votes

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


# Question
Title: Drupal System cron temporary file/folder error
I have very specific problem which I can't resolve. Thing is, I've created few files with function that creates temporary files and then system cron after running should delete them. Problem that I have is that I have manually deleted (temporary) file named "user-upload" and then created folder which has exact same name. Now when system cron runs it gives me two errors:

> Could not delete temporary file "public:///user-upload" during garbage collection public:///user-upload is a directory and cannot be removed using file\_unmanaged\_delete().

I think I should somehow clear something in database but not exactly sure where to look at. Running drush cc all isn't helping in this case.

Thank you

---

EDIT: Eh, it takes you to ask question so you can get better idea. For the reference, solving this issue is locating particular file under database table "file\_managed" column "filename" and then manually deleting it. Maybe it will help someone...

# Answer
> 1 votes
For the reference, solving this issue is locating particular file under database table "file\_managed" column "filename" and then manually deleting it.

# Answer
> 0 votes
As a small workaround for this issue added as a module in drupal.org here

Enable and configure it in admin-\>configuration-\>Development-\>logging and errors

https://www.drupal.org/project/skip\_temp\_file\_warnings

# Answer
> 0 votes
Since playing with DB is not a good practice for basic users,as @Vladan mentioned:

1. Open your database from phpmyadmin
2. under database table "file\_managed"
3. Check the box near every file with **status = 0**
4. Delete all files at once.
5. Run cron again

---
Tags: cron, files
---


# Question
Title: Twig error "Uknown image_style filter", but the filter isn't missing
I'm migrating a site to a new host. On the front end, I see...

```
Twig_Error_Syntax: Unknown "image_style" filter. in Twig_ExpressionParser->getFilterNodeClass() (line 57 of /var/www/prod/web/themes/mytheme/templates/paragraph--paragraph_image_block.html.twig).

```

However, I checked the filter referenced in the error, and the filter is not missing. I see the filter at admin/config/media/image-styles and its machine name is spelled correctly in the template. I have tried rebuilding the cache. Why is this filter unknown?

Here is line 57 in the template:

```
{% set img_url = file_url(content.field_paragraph_image['#items'].entity.uri.value | image_style('max_1300x1300')) %}

```

The 'max\_1300x1300' filter isn't missing.

# Answer
> 6 votes
The error message isn't complaining about a missing Drupal image style - it's complaining about a missing Twig filter *named* `image_style`.

That filter doesn't exist in Twig/Drupal core, but it does exist in the Twig Tweak module. Make sure that module is available and installed, and the error should disappear.

If you've never had Twig Tweak installed then it's probably custom. In that case search your codebase for `Twig_SimpleFilter('image_style'` and you should find the culprit.

---
Tags: theming, media
---


# Question
Title: Cannot create custom translated path alias for /user/login
I cannot create a path alias for spanish translation.

When I try to create, it says `Route is invalid or you don't have access`

Saw this but it doesn't have an answer: https://www.drupal.org/project/drupal/issues/236915

How can I translate the `/user/login path?`

# Answer
> 0 votes
You can try this module: https://www.drupal.org/project/rename\_admin\_paths Should do the job... Good luck!

---
Tags: 7, i18n-l10n, path-aliases
---


# Question
Title: How to prevent caching of field element data in custom field formatter?
I have a custom field formatter that performs dynamic calculations to determine the output. However, for anonymous user's the previous data is always stored until a cache clear is performed.

in the field formatter viewElements() function I have the $elements #cache max-age set to 0. I thought this would resolve the issue but it does not. Am I missing something?

```
 public function viewElements(FieldItemListInterface $items, $langcode) {

    $elements = [];

    foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
      // Check if gate cookie is set

      if (isset($_COOKIE['Drupal_visitor_resource_gate'])){

        //$tags = $file->getCacheTags();
        //Cache::invalidateTags($tags);
        $item = $file->_referringItem;

        $elements[$delta] = [
          '#theme' => 'file_link',
          '#file' => $file,
          '#description' => $this->getSetting('use_description_as_link_text') ? $item->description : NULL,
          '#cache' => [
            'max-age' => 0,
          ],
        ];

        // Pass field item attributes to the theme function.
        if (isset($item->_attributes)) {
          $elements[$delta] += ['#attributes' => []];
          $elements[$delta]['#attributes'] += $item->_attributes;
          // Unset field item attributes since they have been included in the
          // formatter output and should not be rendered in the field template.
          unset($item->_attributes);
        }
        $elements['#cache']['max-age'] = 0;
        return $elements;
      }else{
...
}

```

# Answer
> 2 votes
Can you try adding:
`\Drupal::service('page_cache_kill_switch')->trigger();`
At the beginning of the `viewElements` function before the `foreach` loop?
Another thing to try is to set the following also:

```
$elements['#cache']['max-age'] = 0;
$elements['#cache']['contexts'] = [];
$elements['#cache']['tags'] = [];`

```

# Answer
> 2 votes
For anonymous traffic in general there are probably better solutions client-side. If you want to build this server-side in Drupal then better use a session, this will pass the built in page cache for anonymous traffic.

If you want to handle your own cookies you have to uninstall the Internal Page Cache and cache the pages only in the Internal Dynamic Page Cache. Then for better caching performance set a cache context for the cookie instead of max-age:

```
  $elements['#cache']['contexts'][] = 'cookies:Drupal_visitor_resource_gate';

```

# Answer
> 0 votes
The caching is done per entity not per field.

Depending on your use case you might want to consider excluding specific content types from caching or specific nodes

```
function MODULENAME_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  // for specific Content types
  if ($node->getType() == 'CONTENTTYPE' && $view_mode == 'full') {
    $build['#cache']['max-age'] = 0;
  }

  // for specific nodes
  if ($node->id() == xxx ) {
    $build['#cache']['max-age'] = 0;
  }
}

```

or can even try the cache exclude module

---
Tags: 8
---


# Question
Title: how to implement Ajax callback on form_alter for entity field?
EDITED: I am able to display image for a field dropdown which have entity reference values to another content type. That is when a node content is edited or created.

`Note:` I'm not creating form elements I'm using them.

For a content type I have a field\_select dropdown list (entity reference to another content type). I am trying to alter my form, to display the images of the selected entity from dropdown.

I'm new to the ajax callback functions, and need a little help here. I have a searched a lot and succeeded a bit.

output of my dsm($form):

```
$form => array (
['field_select'] => array (
  ['und'] => array (
    ['#options'] => array (
      [_none] => -None-
        [1] => content1 //1 is key
        [2] => content2 //2 is key
        [3] => content3 //3 is key
      )
    )
  )
)

```

**Present ISSUE:** When the below drop down is selected to a value of above, Image is being displayed in the dummy field below, but only once. For example if I select **1** (content1) the it renders image from **node 1** according to the ajax callback function \[success\]. But now if I select **2** its not loading image from **node2**, instead it shows only node1 image which was rendered first.

```
function custom_form_alter(&$form, &$form_state, $form_id){

 if ($form_id == "article_node_form"){
   $form['field_select']['und']['#ajax'] = array(
     'callback' => 'field_select_ajax_callback',
     'wrapper' => 'another-field-select-image',
   );
   $form['field_select']['und']['#prefix'] = '<div id="another-field-select-image">';
   $form['field_select']['und']['#suffix'] = '</div>';

}

function field_select_ajax_callback($form, $form_state) {
  $id = $form_state['values']['field_select']['und'][0]['target_id']; //node id
  $node_id = node_load($id);

  if(is_object($node_id)) {
    $image_uri = $node_id->field_image['und'][0]['uri'];
    $image_url = file_create_url($image_uri);
    $image = '<img src="' .$image_url. '" />';
  }
  return $image;
}

```

I want to display respective selected dropdown image near to field-select

# Answer
Posting my own answer, I will be happy if it helps someone.

```
function custom_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == "article_node_form"){
    $form['field_select']['und']['#ajax'] = array(
      'callback' => 'field_select_ajax_callback',
      'wrapper' => 'field-image',
    );

//Note: this $form_state is set only after ajax function call (field_select_ajax_callback)
    if(isset($form_state['values']['field_select']['und'][0]['target_id'])) {
      $node_id = $form_state['values']['field_select']['und'][0]['target_id'];
      $image_path = get_image($node_id);
      $form['field_image']['und'] = array(
        '#markup' => '<div class="sponsor-image"> ' .$image_path. ' </div>',
      );
    }
    $form['field_image']['und']['#prefix'] = '<div id="field-image">';
    $form['field_image']['und']['#suffix'] = '</div>';
    return $form;
  }
}

function field_select_ajax_callback($form, $form_state) {
  return $form['field_image']; // very important step, Where I did it differently from previous.
}

function get_image($id) {
  $node_id = node_load($id);

  if(is_object($node_id)) {
    $image_uri = $node_id->field_image['und'][0]['uri'];
    $image_url = file_create_url($image_uri);
    $image = '<img src="' .$image_url. '" />';
  }
  return $image;
}

```

Yay fixed it.
> 1 votes

# Answer
As a guide for de ajax you can check this module in the dev version at this moment and then adapt it to show image. I think it can help you a lot.

https://www.drupal.org/project/entity\_field\_condition/releases/8.x-1.x-dev
> 0 votes

---
Tags: 7, forms, ajax
---


title: HTTPS Links behind AWS Load Balancer

text:
# Question
Title: HTTPS Links behind AWS Load Balancer
I really tried many Solutions to get my site work on Amazon AWS. There is only one last thing i can not solve. Some of my links are still "http://"-links and i dont know how to get them right.

My Setup:

* Drupal 8.6.10 running on an EC2-Instance managed via Beanstalk
* the Load-Balancer is managing the access and has two open ports (http/80 and https/443) directing to the ec2-instance via http (port 80)
* the ssl-certificate is configured
* my domain has the correct dns-config directing to xxx.eu-central-1.elasticbeanstalk.com
* settings.php includes the following lines

```
     $settings['reverse_proxy'] = TRUE;
     $settings['reverse_proxy_addresses'] = array($_SERVER['PROXY_ADDRESS']);
     $settings['reverse_proxy_proto_header'] = 'https';
     conf['https'] = TRUE;
     $_SERVER['HTTPS']='on';

```
* $\_SERVER\['PROXY\_ADDRESS'\] is assgned to 'xxx.eu-central-1.elasticbeanstalk.com' by beanstalk
* .htaccess includes the following lines:

```
     RewriteCond %{HTTPS} off
     RewriteCond %{HTTP:X-Forwarded-Proto} !https
     RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

The affected places are:

* in a twig: url('')
* in a php-file: fileentities-\>url();

All other links are nicely rendered as 'https'-links. I would be really thankfull for any advice you could give me.

Best Regards,

FirstSanny

# Answer
> 0 votes
Try the folling setup:

In settings.php:

```
if (PHP_SAPI !== 'cli' && !empty($_SERVER['REVERSE_PROXY_ADDRESSES'])) {

  $settings['reverse_proxy'] = TRUE;
  $settings['reverse_proxy_addresses'] = array($_SERVER['REVERSE_PROXY_ADDRESSES']);

  $settings['reverse_proxy_header'] = 'X-Forwarded-For';
  $settings['reverse_proxy_proto_header'] = 'X_Forwarded-Proto';
  $settings['reverse_proxy_port_header'] = 'X-Forwarded-Port';

  // HTTPS behind reverse-proxy
  if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
    $_SERVER['HTTPS'] = 'on';
    // This is hardcoded because there is no header specifying the original port.
    $_SERVER['SERVER_PORT'] = 443;
  }
}

```

In your .htaccess:

```
RewriteCond %{HTTP:X-Forwarded-Proto} !https
#RewriteCond %{HTTP_HOST} !^(.*\.)*localhost(.*)$ [NC]
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

```

(change $\_SERVER\['REVERSE\_PROXY\_ADDRESSES'\] to $\_SERVER\['PROXY\_ADDRESS'\] for your setup)

This worked fine for me.

---
Tags: 8, ssl
---


# Question
Title: File added programaticaly are not deleted when node is deleted
I'm creating a node programmatically with one image field. Nodes are Created without any problem.

But if I delete the node the file is marked as "used in 0 place" but never deleted (I run the cron).

If I edit the node and delete the file of the image field, the file is still marked as "used in 1 place".

I want the file be deleted instantaneously like if I create the node using the node form.

```
/**
 * Create a new book from google data
 *
 * @param array $booksData
 * @return \Drupal\Core\Entity\EntityInterface\static
 * @throws Exception
 */
function book_market_create_book_node(Google_Service_Books_Volumes $booksData) {

  // Google_Service_Books_Volumes object automatically iterate, this will get data from the first book
  $bookData = $booksData[0];

  if (empty($bookData['modelData']['volumeInfo']['title'])) {
    throw new Exception('book data are incomplete');
  }

  $bookNode = Node::create([
    'type' => 'book',
    'moderation_state' => 'published',
    'title' => $bookData['modelData']['volumeInfo']['title'],
    'body' => $bookData['modelData']['volumeInfo']['description']
  ]);

  $imageLink = $bookData['modelData']['volumeInfo']['imageLinks']['smallThumbnail'];

  if (isset($imageLink)) {
    $data = file_get_contents($imageLink);

    $transliterator = new Drupal\Core\Transliteration\PHPTransliteration(NULL, \Drupal::moduleHandler());
    $fileName = $bookData['modelData']['volumeInfo']['title'];
    $fileName = str_replace(' ', '_', $fileName);
    $fileName = $transliterator->transliterate($fileName, 'fr', '_') . '.jpeg';

    $field_cover_settings = $bookNode->field_cover->getDataDefinition()
      ->getSettings();
    $destination = $field_cover_settings['uri_scheme'] . '://' . $field_cover_settings['file_directory'] . '/' . $fileName;
    $destination = \Drupal::token()->replace($destination);

    $file = file_save_data($data, $destination, FILE_EXISTS_RENAME);

    $bookNode->set('field_cover', [
      'target_id' => $file->id(),
    ]);
  }

  $bookNode->enforceIsNew();
  $bookNode->save();

  return $bookNode;
}

```

# Answer
> 1 votes
Permanent images are not deleted in Drupal 8, read this https://www.drupal.org/node/2891902

To remove the images, you can set `$config['file.settings']['make_unused_managed_files_temporary'] = TRUE;` in your settings.php. That should be it, it worked for me!

This will remove the permanent files when they are not in use anymore, depending on the time set in /admin/config/media/file-system

For example when you remove a node that contains an image, the image will not be removed at once. The image will be removed when cron executes and `make_unused_managed_files_temporary = TRUE`.

# Answer
> 2 votes
I think that file will be delete when you run cron. File can't delete because temporary file have time life. You can see code in file\_cron.

```
function file_cron() {
  $age = \Drupal::config('system.file')->get('temporary_maximum_age');
  $file_storage = \Drupal::entityManager()->getStorage('file');

  // Only delete temporary files if older than $age. Note that automatic cleanup
  // is disabled if $age set to 0.
  if ($age) {
    $fids = Drupal::entityQuery('file')
      ->condition('status', FILE_STATUS_PERMANENT, '<>')
      ->condition('changed', REQUEST_TIME - $age, '<')
      ->range(0, 100)
      ->execute();
    $files = $file_storage->loadMultiple($fids);
    foreach ($files as $file) {
      $references = \Drupal::service('file.usage')->listUsage($file);
      if (empty($references)) {
        if (file_exists($file->getFileUri())) {
          $file->delete();
        }
        else {
          \Drupal::logger('file system')->error('Could not delete temporary file "%path" during garbage collection', array('%path' => $file->getFileUri()));
        }
      }
      else {
        \Drupal::logger('file system')->info('Did not delete temporary file "%path" during garbage collection because it is in use by the following modules: %modules.', array('%path' => $file->getFileUri(), '%modules' => implode(', ', array_keys($references))));
      }
    }
  }
}

```

You can see line `if($age)` and line `->condition('changed', REQUEST_TIME - $age, '<')`. It's logic when run cron delete file.

And you can go **admin/config/media/file-system** to see time life of temporary file. Default are **6 hours**.

---
Tags: nodes, 8, files, media
---


# Question
Title: How do I dynamically set up different cookies for multiple domains?
My site uses the Domain Access module to maintain multiple domains and sub-domains, such as:

* www.domain1.com, apple.domain1.com, orange.domain1.com
* www.domain2.com, dog.domain2.com, cat.domain2.com

Users from the same domain (for example, domain1.com) should be able to go back and forth between the different sub-domains (www, apple, orange) without having to log in each time.

If I set the cookie domain inside services.yml, users from domain1 will be able to go back and forth between domain and sub-domain; however, users from domain2 won't be able to use the site.

```
parameters:
  session.storage.options:
    cookie_domain: '.domain1.com'

```

If I don't set `cookie_domain`, users from either domain will have to log in each time when they go between sub-domains and domain.

In Drupal 7, it was possible to change the cookie configuration dynamically as explained on cookie domain disables other top domains.

In Drupal 8, the cookie\_domain is set in a YAML file that can't be changed dynamically. A workaround on Drupal 8 is to load dynamically a different YAML file as explained here: https://bit.ly/2Nwgzlr. However; this is not an option for sites with a large number of domains and sub-domains.

Writing a new YAML file per site and modifying the settings.php every time a new domain is added to the pool, is not the most productive way. There is always a way of overriding things inside the Drupal code. I hope this is not the exception.

Can anyone tell me what hook or class I can use to implement the logic I need?

# Answer
> 0 votes
You should be able to do this by altering the services container: https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services.

You can put your logic in there to dynamically set/override values that would usually be set static in a .yml file.

---
Tags: domain-access
---


# Question
Title: How to use entity_reference programatically
i'm building a module with an Company entity, this entity should be linked to other 2 entities and i think that the type "entity\_reference" should be useful for this pourpose, but i dont see how configure this, and only found tutorials to make this by UI, some know how should use or known some link where is weel explained?

There is my actual code, "producto" and "tipo" should be "entity\_reference"

```
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
        $fields['id'] = BaseFieldDefinition::create('integer')
            ->setLabel(t('ID'))
            ->setDescription(t('Identificador de la empresa.'))
            ->setReadOnly(TRUE);

        $fields['uuid'] = BaseFieldDefinition::create('uuid')
            ->setLabel(t('UUID'))
            ->setDescription(t('Identificador único de la empresa.'))
            ->setReadOnly(TRUE);

        $fields['razon_social'] = BaseFieldDefinition::create('string')
            ->setLabel(t("Nombre de la empresa"))
            ->setDescription(t('Nombre de la empresa.'))
            ->setSettings(array(
                'max_length' => 255,
                'text_processing' => 0,
            ))
            ->setRequired(TRUE);

        $fields['logo'] = BaseFieldDefinition::create('uri')
            ->setLabel(t('Logo'))
            ->setDescription(t('Logo de la empresa.'))
            ->addPropertyConstraints('value', ['Image' => []])
            ->setRequired(TRUE);

        $fields['resumen'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Descripción de la empresa'))
            ->setDescription(t('Un resumen general de la empresa hacia el mercado.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['url'] = BaseFieldDefinition::create('string')
            ->setLabel(t("URL"))
            ->setDescription(t('Sitio web de la empresa.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 255,
                'text_processing' => 0,
            ))
            ->addPropertyConstraints('value', ['Url' => []]);

        $fields['quienes_somos'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Quienes Somos'))
            ->setDescription(t('Texto del Quienes Somos.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['mision'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Misión'))
            ->setDescription(t('Misión de la empresa.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['vision'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Visión'))
            ->setDescription(t('Visión de la empresa.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['tipo'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Descripción de la empresa'))
            ->setDescription(t('Un resumen general de la empresa hacia el mercado.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 5000,
                'text_processing' => 1,
            ));

        $fields['producto'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Descripción de la empresa'))
            ->setDescription(t('Un resumen general de la empresa hacia el mercado.'))
            ->setSettings(array(
                'default_value' => '',
                'max_length' => 255,
                'text_processing' => 1,
            ));

        return $fields;
    }
}

```

# Answer
To add entity\_reference try something like, the following example to reference to user: Adapted it to your use case.

```
$fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of Entity entity.'))
      ->setRevisionable(TRUE)
     // Set your target type here change user by your target.
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);

```
> 2 votes

---
Tags: entities
---


# Question
Title: View: Link to content is always rendering in the default language
I have a View that is list of a content type using fields. (I am also using a Relationship and a Contextual Filter, btw.)

One of those fields is "link to content".

The content type is translatable. The View is filtered by `Translation language (= Interface text language selected for page)`. In my secondary language (German) only nodes with a translation are shown. So far, so good.

The rendering language is set to: `Interface text language selected for page`.

However, the rendered rows always link to the default language (`/en`), even when the rest of the page is rendered in the secondary language (`de`).

What can I do to get the rows to render the links in the correct language?

# Answer
> 4 votes
It's a bug and it's being worked on, the solution is provided and it's currently labeled as `Needs review`. Perhaps you can apply the patch and test yourself:

Entity Links fields does not have translation support

In Drupal 8.4 and earlier versions it was possible to use the workaround of `Path` field and using Custom text field to construct the link:

`<a href="{{ path }}">{% trans %} View more {% endtrans %}</a>`

The Path field output correctly translated links with correct path prefix, see here: Translate Content: Link to Content field on Views in Drupal 8. But in Drupal 8.5 the Path field is no longer supported, so you have to patch or wait for the update to gets released.

# Answer
> 2 votes
Add 2 fields to your view:

1. a "Content: Node ID (Node ID)" field
2. a "Content: Translation language (Translation language)" field.

Exclude the "Content: Node ID" field from display.

---

Override the output of this field with custom text:

```
{% trans %} View more {% endtrans %}

```

Rewrite the "Content: Translation Language" field as a custom link:

```
{{ langcode_value }}/node/{{ nid }}

```

---

Then go to admin/config/regional/translate.

You may translate View more in any desired language: FILTER TRANSLATABLE STRINGS (View more) and translate it according to language

# Answer
> 0 votes
The Answer by Jturpin helped me fix this issue. In addition to that you could shorten

```
{% trans %} View more {% endtrans %}

```

to

```
{{'View more'|t}}

```

---
Tags: views, 8, i18n-l10n
---