# Question
Title: Deleting migrate module tables post migration
We did a *massive* migration a while back, several hundred thousand rows. Needless to say we now have a bunch of migrate tables that we could do without.

I've disabled the migrate modules but before I dropped the tables (or should I truncate?) I wanted to make doubly sure that this will have no affect on anything.

Thanks in advance.

# Answer
> 0 votes
So, I deleted the tables (actually truncated them) on my dev server and there have been no side effects that I have noticed, so will try deleting the tables in their entirely. The migrate tables made up around 600mb in a dump.

# Answer
> 0 votes
It seems it's usefull to keep the migrate tables while you are working on migration, in case you need to see the mapping and revert/redoing stuff.

But actually I was having some troubling while using the migrate module for other pursings. This SQL error: `SQLSTATE[HY000] [2002] No such file or directory` did keeping show up when I did try to use drush migrate:... till delete those tables.

With this query you can delete all table with prefix `migrate`

```
SET GROUP_CONCAT_MAX_LEN=10000;
SET @tbls = (SELECT GROUP_CONCAT(TABLE_NAME)
               FROM information_schema.TABLES
              WHERE TABLE_SCHEMA = 'db'
                AND TABLE_NAME LIKE 'migrate\%');
SET @delStmt = CONCAT('DROP TABLE ',  @tbls);
-- SELECT @delStmt;
PREPARE stmt FROM @delStmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

```

---
Tags: database, migrations
---


# Question
Title: What effect does BigPipe have if my traffic is mostly anonymous and I'm serving unpersonalized content behind varnish?
I've looked into this before and *I swear*, though I can't seem to find any documentation to confirm it now, that I read BigPipe only helps performance for authenticated users. (Note: I'm sure I'm just misremembering.)

I think this was due to the fact that anonymous users don't have regular sessions. I'm having trouble tracking this down too, but I did find the following quote:

> If you run that chunk of code from the preceding section as an anonymous user, you'll note that the entry gets created in the database with a session ID, as expected. However, upon the next request, if you try to retrieve the value by key, you won't find it. That is because anonymous users do not necessarily have a session started. This means a new session ID is created for each request.

Anyway, my understanding is that the Sessionless BigPipe module fixes any issue with anonymous traffic and ensures that BigPipe **will** have an impact for those users.

On the Sessionless BigPipe module's project page I see:

> This module uses BigPipe to accelerate the first unpersonalized response! And after that first response is sent, the response is stored in Page Cache. Which means that any subsequent requests for that unpersonalized page will be answered very quickly by Page Cache!

Does this mean that when a page is flushed from cache (Page Cache and Varnish) I'll see something like the following chain for subsequent anonymous requests for that same page?

1. First request: Varnish miss, Drupal Page Cache miss, BigPipe builds the page (This is the one case where BigPipe would have an impact)
2. Second request: Varnish miss, Drupal Page Cache hit, Drupal Page Cache serves the page
3. Third and all subsequent requests: Varnish hit, Varnish serves the page

**Edit:** I now see that this is explicitly outlined further down on the project page:

> So, when using Varnish: the first request will be streamed by BigPipe, and not cached in Varnish. The second request will be a Page Cache hit, not a Varnish hit. The third request and all later requests will be Varnish hits.

Additionally, why does the second request bypass Varnish?

# Answer
> 5 votes
*How does BigPipe have an effect if my traffic is mostly anonymous and behind varnish?*

This really depends on the content of the page. Taking away any content depending on the logged-in user there might be no dynamic part left which could have any effect.

*Additionally, why does the second request bypass Varnish?*

As mentioned in the module description it is not possible the send the cache tag headers after the dynamically generated content has been streamed to Varnish. The Internal Page Cache can be controlled without sending headers because it is cached in the local database.

---
Tags: 8, caching
---


title: Webform block not shown on front-end

text:
# Question
Title: Webform block not shown on front-end
I'm new to using the Webform module, and started with the Contact form provided on install. I have added a Webform block to the Content region, but it doesn't show up on the front-end at all (even when I remove all restrictions such as only showing on certain pages).

I thought it might be a permissions issue, so I checked that all roles have access to see the form. When I tick "Allow users to post submissions from a dedicated URL" and choose a path, both anonymous and logged-in users can view the form at that URL. It's only when it's a block that it doesn't show up. I have also tried clearing the cache, and placing the block in other regions.

I am using Drupal 9 with Webform 6.0.0.

Edit: After some suggestions below I have also tried:

* Another theme: The issue does not happen in the parent theme of my sub-theme, narrowing it down to a possible theme-level issue.
* Deleting my theme's overrides of `region.html.twig` and `block.html.twig`. The issue persists in my theme.
* Placing a HTML comment in `block.html.twig` before any Twig code, to check when that file is being used (i.e. it might be loaded, but have a problem with the output code). It is not rendered at all for this specific block.

What are some other possible things that can cause the block to not show up?

# Answer
Rather than checking the block's config in the existing instance, delete it and re-insert it, checking the settings again in the insertion screen. It now shows up for me after doing it this way.
> 0 votes

---
Tags: webforms, 9
---


# Question
Title: View based on months or days - display certain items during specified times of the year
I am trying to create a calendar-type view that will display links to specific nodes during certain months of the year. For example, this would show 'Taxes' in Feb and April, 'Travel' from May to September, etc.

So far I have added a boolean field to my node to appear in the view, but I am stuck on how to implement the date selector. Theoretically I would like to have people select the months that this node should appear in the view, and the view will contextually display the nodes depending on the current month.

The problems I'm running into are:

* The date field seems to require a year, but I want this to be year agnostic
* The date field doesn't allow selection of multiple months

I am thinking that I will have to use a date field so that I can use contextual filters to display based on month of the year. I don't have access to the codebase so I need to do all of this within the UI using modules, if possible.

Any tips on how I can achieve this?

# Answer
Here's an idea for something you could do in the Drupal admin UI (using only modules that are part of Drupal 8 core) since it seems you don't have access to the codebase.

As you noted, the date field requires a year. So you can't use it if you want your months to be year-agnostic.

I assume that your requirement is "each node should be assigned to one or more months" and we don't have to worry about days (for example, a node could be "January and February", but it could not be "Jan 12 - Feb 10").

In that case, you can add a field of type **List (Text)** to the node content type that you want to sort in Views. For the value of the field, enter the 12 months and allow multiple values so that multiple months can be selected.

Then, you can configure the view to filter based on your month field. To set the current month, I'm pretty sure you can use Twig date in a Views filter to input the current month (not tested, from memory).
> 0 votes

---
Tags: views, datetime
---


title: Set placeholder for views exposed input

text:
# Question
Title: Set placeholder for views exposed input
I create a search section with view and I want hide label of search inputs and set placeholder for them.

Is there any section to set this?

Drupal 8

# Answer
> 1 votes
```
function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if($form_id == 'views_exposed_form'){
      $form['field-name']['#attributes']['placeholder'] = t('Placeholder Keyword');
   }
}

```

# Answer
> 1 votes
```
function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if($form['#id'] == 'views_exposed_form'){
     $form['field-name']['#attributes']['placeholder'] = t('Placeholder Keyword');
   }
}

```

That's what it should be for Drupal 8.3.2

# Answer
> 1 votes
There is no need for preprocessing since Drupal 8.5

There is a field available named *placeholder*

---
Tags: views, 8
---


# Question
Title: How do I hook the stock status message to the product page?
I have a Commerce Demo site that uses the off canvas flyout cart and I am using the Commerce Simple Stock module to stop items being sold if they are out of stock.

The module changes the stock number and prevents the item being loaded to the cart if already purchased. It sends user/status messages and removes the add to cart button using `commerce_simple_stock_form_commerce_order_item_add_to_cart_form_alter()`.

This hook doesn't work for the Commerce Demo form.

The theme hook for the *Add to cart* button in Commerce Demo is `commerce_cart_flyout_add_to_cart_button()`.

The stock status messages show on the admin pages but not on the product page itself.

How do I hook the stock status message from the module to the product page?

# Answer
System Messages are printed to the page via a block (Block: Messages, Category: System).

If the messages block isn't aren't appearing on a particular page:

1. Check to make sure the block is added to a region in the active theme for the page in question.
2. Check to make sure any visibility settings for the block are configured correctly for the target audience
3. Make sure that your theme actually renders the region that you added the block to.

If you're still not seeing the messages block:

1. Create a static custom block (something that should always appear) and place it in the region.
2. Test with the block added to a region you know is rendering, i.e. the main content region.
3. Inspect the source html of the page to make sure the html is actually missing and isn't just being hidden by css.
4. Enable twig\_debug and verify that the page is built with the templates you think it is. Check each template (Page, Region, Block, potentially others, but it would likely be one of these that's the issue) and make sure the template is properly rendering what it needs to.
> 0 votes

---
Tags: commerce
---


title: PSR12, Drupal or DrupalPractice?

text:
# Question
Title: PSR12, Drupal or DrupalPractice?
I want to respect coding standard in my new Drupal projects (for Drupal 8 and Drupal 9). Using phpcs and phpcbf, I am wondering if I should use PSR12, Drupal, or DrupalPractice coding standards. Do you have any advice?

# Answer
> 1 votes
Drupal / DrupalPractice are the Drupal coding standards, which is probably why your question got downvoted.

The Drupal coding standards are pretty well documented.

Drupalize.me also has a tutorial about how to set up your local dev environment.

There are also a variety of tools that automatically apply the coding standards such as the Drupal Code Quality Checker.

---
Tags: coding-standards
---


# Question
Title: How can I programmatically change the parse mode?
We have a view that works with Search API and Solr search. The multiple search terms work with single quotes and with no quotes. I want to make the search terms work with double quotes as well. The issue is also listed here without a fix:

https://www.drupal.org/project/search\_api/issues/2141575

I found that I can change the parse mode in the View \> Query \> Settings to direct method and the term with double quotes work just fine. I want to make this change using hooks. I have tried `hook_search_api_views_query_alter` and it does not work. Does anyone know how to change the parse mode in the query settings using hooks?

# Answer
> 2 votes
On Drupal 7, I've achieved this by using `hook_views_pre_build()` since this hook is executed before `hook_views_pre_execute()` and `hook_search_api_views_query_alter()`. Using code similar to the following will do the job.

```
$options = $view->display_handler->get_option('query');
$options['options']['parse_mode'] = 'TYPE_OF_PARSE_MODE';
$view->display_handler->set_option('query', $options);

```

Note that `TYPE_OF_PARSE_MODE` can be:

* Direct query - direct
* Single term - single
* Multiple terms - terms

---
Tags: 7, views, search
---


# Question
Title: How do I sort a date field in views without the time?
Drupal 7

I have a view that sorts on three fields so the ORDER BY statement looks like: ORDER BY

node\_status ASC, field\_data\_field\_date\_field\_date\_value DESC, field\_data\_field\_sort\_order\_field\_sort\_order\_value ASC

I need the sort of the date field to not be granular to the time. I just want it sorted by the date so that the sort order field will take it from there. When I run the query against the database itself, I see that the date field returned is showing the full value like: 2016-06-19 08:48:12, but some of the values are different by a second, causing the "incorrect" (not the desired) sort order.

How can I get it to sort on the date field (date field module) without the "full date" field?

EDIT: (adding screen shot of view)

# Answer
D7 only provides granularity for the core fields not added fields.

D8 provides granularity for the core and added fields.

I have added D7 functionality as a patch to the module views\_date\_format\_sql. See this patch.

Views\_date\_format\_sql can also do custom formats as well.

Note:

* The D8 patch is only for core date fields so far (e.g. node updated).
> 1 votes

# Answer
you can change the granularity of the sort under the settings for the sort criteria:
> 1 votes

---
Tags: views, datetime
---


title: How do I log in a user?

text:
# Question
Title: How do I log in a user?
I want to log in Drupal 8 users from an external PHP file. I am trying the following code.

```
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\user\UserInterface;
//$autoloader = include('/vendor/autoload.php');
$autoloader = require_once __DIR__ . '/vendor/autoload.php';
$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

// ID of the user.
// REPLACE WITH WHATEVER ID YOU WANT TO LOGIN AS;
$uid = 100;
$user = Drupal\user\Entity\User::load($uid);

// This is required to call user_login_finalize here.
$kernel->prepareLegacyRequest($request);
user_login_finalize($user);

$response->send();

$kernel->terminate($request, $response);

```

When I run it, I get the following error.

> TypeError: Argument 1 passed to user\_login\_finalize() must implement interface Drupal\user\UserInterface, null given, called in /var/www/html/stocksee/public\_html/component/login.php on line 22 in user\_login\_finalize() (line 554 of core/modules/user/user.module).

Please help me.

# Answer
> 2 votes
I'd say in this specific case the error message looks like saying that $user is NULL. You need to validate that User::load returns a valid UserInterface because if the $uid passed to the method is not found, it will return NULL, which is the value you are getting. Try with a valid uid like 1, see what happens and move ahead from there.

---
Tags: users, external-scripts
---


# Question
Title: How can webform performance be improved on low internet connection?
I built a site with Drupal 9 and webform. The form consists of three pages and contains a few computed fields. On the first page are mandatory fields. The form is used by logged-in users only.

When on a machine with a normal/fast internet connection, everything is fine. When on a machine (smartphone) with a slow internet connection (or on *Low-end mobile* in Chromium's developer tools), I can enter all information on the first page, press next, it loads the second page and jumps back to the first one, claiming that the mandatory fields were empty.

Is there something that should be cached and that I missed so far? Do I have to manipulate some timeouts (where are they, I didn't find them)?

# Answer
To enable all caching:

* Navigate to "Extend" and enable the following modules:
    + Internal page cache
    + Internal dynamic page cache
* Navigate to "Configuration \> Development \> Performance" and enable cache for a period of time (E.g. 6 hours) and check both the options for "Aggregrate CSS/JS"

Hopefully that may help with your issue.
> 0 votes

# Answer
I tried the Advanced Aggregation module. This gave me the hint that the scripts should be compressed. Since the application is served by an nginx server, I had to update the server configuration by adding the `gzip` line to the following snippe:

```
location ~ ^/sites/.*/files/(css|js) {
   # add_header Cache-Control 'public, max-age=31536000, immutable';
    gzip_static on;
}

```

At least with my local testing scenario (*Low-end mobile* in Chromium's developer tools) it does the trick. We'll see, whether it does so in real world low internet connections.
> 0 votes

---
Tags: webforms, performance
---


# Question
Title: How to filter my view of Groups to show results matching Term A or Term B
I am adding taxonomy terms to groups (using the group module) and want to use the terms to filter groups within a view. However, my exposed filters don't seem to work. There is no error, but the behavior of filters is not what I expect.

When I request the display of A-term groups and B-term groups (from two different vocabularies), the view displays nothing. It is not logic.

Question: is group module compatible with taxonomy core module? I mean: is it possible to add taxonomy terms directly to groups (and not group contents)?

Here is my view:

```
uuid: 152ca6c2-f625-43db-8f2a-efa020ff5dd3
langcode: fr
status: true
dependencies:
  config:
    - field.storage.group.field_locate_place
    - field.storage.group.field_place_type
    - taxonomy.vocabulary.existing_places
    - taxonomy.vocabulary.projects
  module:
    - address
    - better_exposed_filters
    - group
    - leaflet
    - leaflet_views
    - link
    - taxonomy
id: map
label: Map
module: views
description: ''
tag: ''
base_table: groups_field_data
base_field: id
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: none
        options: {  }
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: bef
        options:
          submit_button: Filter
          reset_button: true
          reset_button_label: Remove
          exposed_sorts_label: 'Sort by'
          expose_sort_order: false
          sort_asc_label: Asc
          sort_desc_label: Desc
          text_input_required: 'Sélectionnez n''importe quel filtre et cliquez sur Appliquer pour voir les résultats'
          text_input_required_format: restricted_html
          bef:
            general:
              autosubmit: false
              autosubmit_exclude_textfield: false
              autosubmit_textfield_delay: 500
              autosubmit_hide: false
              input_required: false
              allow_secondary: false
              secondary_label: 'Options avancées'
              secondary_open: false
            filter:
              field_place_type_target_id:
                plugin_id: default
                advanced:
                  rewrite:
                    filter_rewrite_values: ''
                  collapsible: false
                  is_secondary: false
              field_place_type_target_id_1:
                plugin_id: default
                advanced:
                  rewrite:
                    filter_rewrite_values: ''
                  collapsible: false
                  is_secondary: false
      pager:
        type: some
        options:
          items_per_page: 1000
          offset: 0
      style:
        type: leaflet_map
        options:
          grouping: {  }
          data_source: field_locate_place
          entity_source: __base_table
          name_field: label
          description_field: ''
          view_mode: token
          leaflet_map: 'OSM Mapnik'
          height: '700'
          height_unit: px
          hide_empty_map: false
          disable_wheel: true
          fullscreen_control: true
          gesture_handling: false
          reset_map:
            control: false
            position: topright
          map_position:
            force: true
            center:
              lat: 46
              lon: 2
            zoom: 6
            minZoom: 1
            maxZoom: 16
            zoomFiner: 0
          weight: ''
          icon:
            iconType: marker
            iconUrl: ''
            shadowUrl: ''
            className: ''
            html: '<div></div>'
            html_class: leaflet-map-divicon
            circle_marker_options: '{"radius":100,"color":"red","fillColor":"#f03","fillOpacity":0.5}'
            iconSize:
              x: ''
              'y': ''
            iconAnchor:
              x: ''
              'y': ''
            shadowSize:
              x: ''
              'y': ''
            shadowAnchor:
              x: ''
              'y': ''
            popupAnchor:
              x: ''
              'y': ''
          leaflet_markercluster:
            control: true
            options: '{"spiderfyOnMaxZoom":true,"showCoverageOnHover":true,"removeOutsideVisibleBounds":false}'
          path: '{"color":"#3388ff","opacity":"1.0","stroke":true,"weight":3,"fill":"depends","fillColor":"*","fillOpacity":"0.2","radius":"6"}'
          geocoder:
            control: false
            settings:
              position: topright
              input_size: 25
              providers:
                kml_file:
                  weight: '0'
                  checked: 0
                openstreetmap:
                  weight: '0'
                  checked: 0
              min_terms: 4
              delay: 800
              zoom: 16
              popup: false
              options: ''
      row:
        type: 'entity:group'
        options:
          relationship: none
          view_mode: default
      fields:
        field_locate_place:
          id: field_locate_place
          table: group__field_locate_place
          field: field_locate_place
          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: leaflet_formatter_default
          settings:
            multiple_map: false
            popup: true
            popup_content: "[group:title]\r\n[group:field_place_type]\r\n[group:url]\r\n\r\n\r\n"
            leaflet_map: 'OSM Mapnik'
            height: 700
            height_unit: px
            hide_empty_map: false
            disable_wheel: true
            fullscreen_control: true
            gesture_handling: false
            reset_map:
              control: false
              position: topright
            map_position:
              force: true
              center:
                lat: 46.5
                lon: 2.5
              zoom: 6
              minZoom: 1
              maxZoom: 16
              zoomFiner: 0
            weight: ''
            icon:
              iconType: marker
              iconUrl: ''
              shadowUrl: ''
              className: ''
              html: '<div></div>'
              html_class: leaflet-map-divicon
              circle_marker_options: '{"radius":100,"color":"red","fillColor":"#f03","fillOpacity":0.5}'
              iconSize:
                x: ''
                'y': ''
              iconAnchor:
                x: ''
                'y': ''
              shadowSize:
                x: ''
                'y': ''
              shadowAnchor:
                x: ''
                'y': ''
              popupAnchor:
                x: ''
                'y': ''
            leaflet_markercluster:
              control: true
              options: '{"spiderfyOnMaxZoom":true,"showCoverageOnHover":true,"removeOutsideVisibleBounds":false}'
            path: '{"color":"#3388ff","opacity":"1.0","stroke":true,"weight":3,"fill":"depends","fillColor":"*","fillOpacity":"0.2","radius":"6"}'
            geocoder:
              control: false
              settings:
                position: topright
                input_size: 25
                providers:
                  kml_file:
                    weight: 0
                    checked: false
                  openstreetmap:
                    weight: 0
                    checked: false
                min_terms: 4
                delay: 800
                zoom: 16
                popup: false
                options: ''
          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_group:
          id: view_group
          table: groups
          field: view_group
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: true
          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
          text: voir
          output_url_as_text: false
          absolute: false
          entity_type: group
          plugin_id: entity_link
        label:
          id: label
          table: groups_field_data
          field: label
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: true
            text: "<div>\r\n    {{ label }}\r\n    {{ field_locate_place }}\r\n    {{ field_place_type }}\r\n    {{ view_group }}\r\n</div>\r\n\r\n    \r\n    "
            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: null
          entity_field: label
          plugin_id: field
      filters:
        field_place_type_target_id:
          id: field_place_type_target_id
          table: group__field_place_type
          field: field_place_type_target_id
          relationship: none
          group_type: group
          admin_label: ''
          operator: or
          value: {  }
          group: 1
          exposed: true
          expose:
            operator_id: field_place_type_target_id_op
            label: 'Place type'
            description: null
            use_operator: false
            operator: field_place_type_target_id_op
            operator_limit_selection: false
            operator_list: {  }
            identifier: field_place_type_target_id
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            reduce: false
          is_grouped: true
          group_info:
            label: 'Existing places'
            description: ''
            identifier: field_place_type_target_id
            optional: true
            widget: radios
            multiple: true
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items:
              1:
                title: 'place A'
                operator: or
                value:
                  82: '82'
              2:
                title: 'place B'
                operator: or
                value:
                  83: '83'
              3:
                title: 'place C'
                operator: or
                value:
                  84: '84'
          reduce_duplicates: false
          type: select
          limit: true
          vid: existing places
          hierarchy: false
          error_message: true
          plugin_id: taxonomy_index_tid
        field_place_type_target_id_1:
          id: field_place_type_target_id_1
          table: group__field_place_type
          field: field_place_type_target_id
          relationship: none
          group_type: group
          admin_label: ''
          operator: or
          value: {  }
          group: 1
          exposed: true
          expose:
            operator_id: field_place_type_target_id_1_op
            label: 'Place type'
            description: null
            use_operator: false
            operator: field_place_type_target_id_1_op
            operator_limit_selection: false
            operator_list: {  }
            identifier: field_place_type_target_id_1
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            reduce: false
          is_grouped: true
          group_info:
            label: Projects
            description: ''
            identifier: field_place_type_target_id_1
            optional: true
            widget: radios
            multiple: true
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items:
              1:
                title: 'project 1'
                operator: or
                value:
                  85: '85'
              2:
                title: 'project 2'
                operator: or
                value:
                  86: '86'
              3:
                title: 'project 3'
                operator: or
                value:
                  87: '87'
          reduce_duplicates: false
          type: select
          limit: true
          vid: projects
          hierarchy: false
          error_message: true
          plugin_id: taxonomy_index_tid
      sorts: {  }
      title: 'Map'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
      filter_groups:
        operator: OR
        groups: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - user
      tags:
        - 'config:field.storage.group.field_locate_place'
  page_1:
    display_plugin: page
    id: page_1
    display_title: 'Map'
    position: 1
    display_options:
      display_extenders: {  }
      path: node
      display_description: ''
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - user
      tags:
        - 'config:field.storage.group.field_locate_place'

```

# Answer
> 1 votes
By default, all Filters get added to the same Filter Group (a filter group is just a group of filters that share a logical operator, e.g. AND or OR). The default behavior is to put all filters into the same group with the logical operator AND. This means that if you have Filter A, Filter B, and Filter C, the view will only produce results that have the value from each filter, Filter A, Filter B and Filter C.

You can review your filter operators and grouping by clicking the Dropdown Button for Filter Criteria and choosing the And/Or Rearrange option.

However, it sounds like you want Filter B and Filter C to use an OR Filter group, i.e. you want the view to show results where the content has the value from Filter B or has the value from Filter C.

To do this, you need to make sure that Filter B and Filter C are in their own Filter group and that group's logical operator is set to OR. If you only have the two filters, you can use the original grouping, but change the operator. However, if you have other filters, e.g. my example with 3 filters, you'll need to create a new group.

After you create a second filter group, you'll see that you can control the operator for each filter group and you can also control the operator between the filter groups.

In an example with Filters A, B, and C, if I want to display all results where content has the value from Filter A **AND** the content has the value from Filter B **OR** Filter C, I would create two filter groups:

1. Group 1: with only Filter A
2. Group 2: with Filter B and Filter C

I would then set the logical operators:

* Group 1's logical operator would be set to **AND** (the default, there's only one filter here so it shouldn't matter).
* Group 2's logical operator would be set to **OR** (as we want to get results where the content matches either of the Filter B or Filter C, it does not need to match both).
* The operator between Group 1 and Group 2 would be set to **AND**

# Answer
> 0 votes
I do not think that there is a way to do that unless I do not understand the question correctly.

Group (Types) are meant to be used as content types and thus you can not attach taxonomy terms directly to them. Groups are meant to be used as nodes. If you want all the groups in a specific group type to belong to certain taxonomy term then you can maybe work something out with the default value of the reference field.

Now concerning your question specifically, i would first check if there is any mistake in the view's configuration. If I get this right, you wish to display groups that belong to terms A.term and B.term so your are probably using the combined filter. Could you share your view configuration, in order to further examine your issue?

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


# Question
Title: How can you prevent a Webform from going to a confirmation modal if remote post handler fails in a service response?
I have a webform with a single handler - an extended remote post handler that sends the submission to an external service. The entire form loads in a modal dialog and has two wizard steps.

This service can return a 200 (with confirmation id and date) or 400 (and any number of errors).

How can I either:

* Prevent the submission on error from the service, and reload the form to try again (with values retained)
* Change the confirmation message to reflect that something went wrong, and either reload the form fresh with that appended or just have a link in the modal that goes "back to form"

I have looked at a few other questions like:

I can't get them to work. `preprocessConfirmation()` is never triggered in my handler, I don't see other examples or where that would be called. How are we supposed to implement that effectively? If there was an error saving the data to the remote service, I either want the user to try again, or just delete the webform submission in Drupal and start over.

# Answer
> 1 votes
I believe it is too late to halt the Webform with validation errors once it is past the validation phase ie. in `postSave()`. If you are expecting validation errors on user input however, then you could move the service call to **`WebformHandlerBase::validateForm()`** and then save the service response in the `$form_state` object if you need it.

```
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    parent::validateForm($form, $form_state, $webform_submission);

    try {
      $response = $this->doServiceRequest()
    }
    catch (\Exception $e) {
      $form_state->setErrorByName('foo', $e->getMessage());
      return;
    }

    // Save service response output.
    $webform_submission->setData($response->getData() + $webform_submission->getData());
  }

```

**Note:** This probably goes against the design of the `RemotePostWebformHandler`, but I think it could work..., or you could directly extend `WebformHandlerBase` instead.

---
Tags: 8, webforms
---


# Question
Title: How to use the filter flag in drush config:status
I am using Drush 10.3.6.

Drush config:status gives me:

```
# drush config:status
 --------------------------------- ------------
  Name                              State
 --------------------------------- ------------
  webform.settings                  Different
  webform.webform.contact           Only in DB
  webform.webform.example_webform   Only in DB
 --------------------------------- ------------

```

I am interested in filtering this to display only certain items, however the filter parameter does not work as expected:

```
# drush help config:status|grep Filter
  --filter[=FILTER] Filter output based on provided expression

# drush --filter='^webform\.webform\..*$' config:status
In OperatorFactory.php line 50:
  Could not parse expression ^webform\.webform\..*$

# drush --filter='webform.webform.*' config:status
In OperatorFactory.php line 50:
  Could not parse expression webform.webform.*

```

What is format of the expression that needs to be passed to the filter parameter?

# Answer
If you look at the *Consolidation\Filter\OperatorFactory* class mentioned with the error, you'll see documentation at the top of the Class that outlines the acceptable syntax.

```
**
 * Convert a simple operator expression into an Operator.
 *
 * The supported operators include:
 *
 *      key=value           Equals
 *      key*=value          Contains value
 *      key~=#regex#        Regular expression match
 *
 * It is also possible to negate the result of an operator by
 * adding a logical-not operator either before the entire expression,
 * e.g. !key=value, or before the operator, e.g. key!=value.
 *
 */

```

Using the above documentation as a guide, the following all work for me - examples two and three should work for your example case.

```
// 1. Use the *Equals* option to show only the config entity with name "webform.webform.contact"
drush --filter="name=webform.webform.contact" config:status

// 2. Use the *Contains value* option to show any config entity with name containing "webform.webform"
drush --filter="name*=webform.webform" config:status

// 3. Use the *Regular expression match* option to show any config entity with name starting with "webform.webform."
drush --filter="name~=#^webform\.webform\.*#" config:status

```
> 4 votes

---
Tags: drush
---


title: Where are the field formatter settings?

text:
# Question
Title: Where are the field formatter settings?
When I'm managing a display for an entity and select a field formatter, some formatters have options available (see screenshot 1).

However, when I use that same field formatter in Views, there's no way to set my options. How can I set my options?

This works.

This doesn't have a way to select options.

# Answer
4k4's comment was helpful in that it indicated the correct behavior. This isn't what was happening; the POST requests were returning correctly, but I assume they're not returning a correct part of the dialog to replace.

However, with this knowledge in mind, I was able to use Configuration Management to export the View and the Entity view display, pull the appropriate setting names from the Entity view display, and manually apply them to the View YAML and reimport. It's imperfect, but knowing that this should be possible was a great help in finding a workaround.
> 0 votes

---
Tags: 8, views, media
---


# Question
Title: How to filter content by a specific taxonomy term when vocabulary allows multiple values?
I have defined a vocabulary that allows multiple terms to be checked for a Content Type and I would like to create a View that could gather all the data from that Content Type but grouping the results by a specific term.

When I'm not applying any contextual filter, the result list should contain a group of data for every term in my vocabulary. Naturally, some of the items will appear in multiple groups because of the multiple terms scenario.

I would like to create a contextual filter for a specific term and get as a result only one of those groups. The problem is that I'm getting not only the group I expect but other groups in which some of the results have more than one term selected for the same vocabulary.

For example:

* Content type is "Dogs".
* Vocabulary is "Places".
* Taxonomy terms for "Places" are: "Kitchen", "Living room", "Garage", "Outside".

"Dogs" has a field called "Places to play with my owner" which is related to "Places" and the user can select one or more options.

I created a view that has:

* A relationship with "Places" vocabulary.
* A contextual filter that retrieves all the "Dogs" that play on each of those places when there is no specific term to filter.
* A field group using the "Places" term names.

And retrieves the following results on a URL like: `/dogs/places-to-play/`:

* Kitchen: Dog A, Dog B.
* Living Room: Dog A.
* Garage: Dog C.
* etc.

The contextual filter should receive a "Places" term name via URL like: `/dogs/places-to-play/kitchen` and the expected result would be:

* Kitchen: Dog A, Dog B.

But in my case, the results are:

* Kitchen: Dog A, Dog B.
* Living Room: Dog A.

Because "Dog A" has options "Kitchen" and "Living Room" selected in its "Places to play" field.

The question is: Is there a way to avoid getting the extra groups?

Thanks in advance.

# Answer
> 0 votes
To solve the problem:

1. Removed the relationship with "Places" vocabulary and used the field "Places to play" to create the field groups, checking the "Use rendered output for a group of rows" option.
2. Unchecked the "Display all values in the same row" option for "Places to play" field.
3. Created a contextual filter for "Places to play" field to receive the value via URL.

As a result I now get what I was expecting.

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


# Question
Title: Theme suggestion template is not being picked up
I add template suggestion in my discount module:

```
function discount_theme_suggestions_field_multiple_value_form_alter(array &$suggestions, array $variables) {
    if ($variables['element']['#field_name'] == 'user_discount'){
      $suggestions[] = 'field_user_discount';
      kint($suggestions);
    }
}

```

And I can see template suggestion on my admin form:

However I added template field-user-discount.html.twig (I don't place it here as it simply the copy of classy one with change of order) in discount module templates folder and it is not being picked up, it still picks up the classy one. I cleared all the caches, both from drush and site itself. I also tried to add this template to theme templates, it is not being picked up there as well. Other templates from both theme and discount modules are being picked up.

How can Drupal pick it up? It is the field on admin pages.

# Answer
> 5 votes
After you add your theme suggestion:

```
function discount_theme_suggestions_field_multiple_value_form_alter(array &$suggestions, array $variables) {
    if ($variables['element']['#field_name'] == 'user_discount'){
      $suggestions[] = 'field_user_discount';
    }
}

```

You need to tell Drupal in this hook you should pick my template by implementing ***hook\_theme*** like the following.

```
/**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field_user_discount' => [
      'base hook' => 'field_multiple_value_form'
    ],
  ];
}

```

Now just put your template in you templates module folder clear cache and it will be picked.

**Note:** if you want to use a different name from the suggested one (***field-user-discount***) of your template like ***field-user-discount-something.html.twig*** just tell the hook\_theme the name of template like:

```
 /**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field_user_discount' => [
      'base hook' => 'field_multiple_value_form',
      'template' => 'field-user-discount-something'
    ],
  ];
}

```

# Answer
> -1 votes
> I added template field-user-discount.html.twig ... in discount module templates folder

That's the wrong place to put it. You need to put this in your theme, not in the module's templates folder.

---
Tags: 8, theming
---


# Question
Title: How to unflag/reset a flag again, when matching some conditions in onFlag event?
in my custom module I have an event subscriber service for flag module. I used the tutorial here as a base for learning: Link to Tutorial

Here is my code:

```
namespace Drupal\MYMODULE\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\flag\Event\FlagEvents;
use Drupal\flag\Event\FlaggingEvent;
use Drupal\flag\Event\UnflaggingEvent;
use Drupal\user\UserInterface;
use Drupal\user\Entity\User;

class MYMODULEFlagSubscriber implements EventSubscriberInterface {

  /**
   * Do the logic when the upgrade flag is triggered to flag.
   */
  public function onFlag(FlaggingEvent $event) {
    $flagging = $event->getFlagging();
    $flag = $flagging->getFlag();
    $flag_machine_name = $flag->id();
    if ($flag_machine_name === 'my_awesome_flag') {
      $entity_nid = $flagging->getFlaggable()->id();
      $user = User::load($entity_nid);
      $user_is_active = $user->isActive();
      $field_1 = $user->get('field_1')->value;
      $field_2 = $user->get('field_2')->value;
      $break_with_error = FALSE;
      $upgrade_message = '';
      $roles_to_ignore = [
        'administrator_junior',
        'team_sales',
        'administrator',
      ];
      if (!$user->hasRole('authenticated_level_2')) {
        if (($user_is_active == TRUE) && ($field_1 == 1) && ($field_2 == 1)) {
          foreach ($roles_to_ignore as $role_to_ignore) {
            if ($user->hasRole($role_to_ignore)) {
              $break_with_error = TRUE;
              $upgrade_message = 'The User has a company role already and can not being upgraded as a Level 2 user.';
              break;
            }
          }
        }
        else {
          $break_with_error = TRUE;
          $upgrade_message = 'The User can not being upgraded as a Level 2 User. Reasons: 2. The account is not activated yet, 3. The user has not yet checked field 2';
        }
      }
      else {
        $break_with_error = TRUE;
        $upgrade_message = 'The User was upgraded as a Level 2 User already.';
      }

      switch ($break_with_error) {
        case TRUE:
          \Drupal::messenger()->addError($upgrade_message);
          $flagging->unflag($flag_machine_name, $entity_nid);
          return;

        case FALSE:
          $user->addRole('authenticated_level_2');
          $user->save();
          \Drupal::messenger()->addStatus('The User was upgraded as a Level 2 User sucessfully.');
          return;
      }

    }
  }

```

**My Problem is**

How can I unflag the flag again, when my logic checks settings and my variable $break\_with\_error becomes true?

```
$flagging->unflag($flag_machine_name, $entity_nid);

```

throws me an PHP error.

Update:

My intention was the following:

I use the flag here as a substitute for a link/button to trigger the "business logic" checks and to give the user a additional role with more privileges if the checks are passed.

In my opinion it's a easy way to quickly have a link/button in multiple variants (e.g. in a view or as a field in user account). Another advantage is, that other people (in my case sales team or other admins) see the business logic checks have performed already when the user entity is flagged. But in case the logic checks are failing, the user entity should unflagged again.

For other opportunities to have a "business logic trigger" I'm open and thankful of course.

# Answer
I'm guessing the problem is that in the onFlag event, the flag is still being created, so it can't be unflagged because it hasn't been fully saved yet.

But I think the bigger problem is that your code has a logic error-- validation should happen before the action, not after the action.

It looks like you are trying to do this:

1. When a user is flagged,
2. check if the flag meets certain "unflag" conditions,
3. if the conditions are met, unflag the user.

However, validation in Drupal usually is applied **before** something happens, not after. Validation is not supposed to be a kill switch to stop a problem; you should stop the problem before it happens.

One reason to stop the problem before it happens is that you later may add code that does something when a node is flagged (for example, in `hook_entity_insert()`); in such a case, you would also have to undo the code in your flag event subscriber.

So, what you probably want to do is apply the validation login in `hook_form_alter()` so you can stop the flagging before it happens.
> 3 votes

---
Tags: 8, flags
---


# Question
Title: View Taxonomy Term List with Exposed Has taxonomy terms (with depth) filter
I have view list of terms of a vocabulary. The terms of it have an entity reference field of another vocabulary (with hierarchically organized terms).

I would like to filter the terms by that entity reference like I am used to do with nodes with a "Has taxonomy terms (with depth)" filter.

Does a depth filter really only work with nodes?

Kind regards and thank you for your support.

# Answer
> 1 votes
There is a issue as you ask the question.

The current answer is that Drupal 8 does not yet support this feature besides node content type.

I'm also following this issue.

more details at:

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

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

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


# Question
Title: Using Drush how can you see the last user that logged in?
Using drush, how can you see the last user that logged in? What about the last 5, 10, 20?

# Answer
```
drush sqlq "SELECT name FROM users ORDER BY login DESC LIMIT 10"

```

Tweak LIMIT to change the number returned.
> 2 votes

# Answer
You could use `drush sql-query` to do this:

```
drush sql-query "SELECT * FROM users ORDER BY login DESC LIMIT 10"

```

The above will display the 10 latest logins (or less).

If you only want some name you can change the `*` to `name` and you can also change the `LIMIT 10` to the number of results you would like to display.

For example this would return the `name` and `uid` for the last 5 users:

```
drush sql-query "SELECT uid, name FROM users ORDER BY login DESC LIMIT 5"

```

Here is the structure for the `users` table:

```
+------------------+------------------+------+-----+---------+-------+
| Field            | Type             | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+-------+
| uid              | int(10) unsigned | NO   | PRI | 0       |       |
| name             | varchar(60)      | NO   | UNI |         |       |
| pass             | varchar(128)     | NO   |     |         |       |
| mail             | varchar(254)     | YES  | MUL |         |       |
| theme            | varchar(255)     | NO   |     |         |       |
| signature        | varchar(255)     | NO   |     |         |       |
| signature_format | varchar(255)     | YES  |     | NULL    |       |
| created          | int(11)          | NO   | MUL | 0       |       |
| access           | int(11)          | NO   | MUL | 0       |       |
| login            | int(11)          | NO   |     | 0       |       |
| status           | tinyint(4)       | NO   |     | 0       |       |
| timezone         | varchar(32)      | YES  |     | NULL    |       |
| language         | varchar(12)      | NO   |     |         |       |
| picture          | int(11)          | NO   | MUL | 0       |       |
| init             | varchar(254)     | YES  |     |         |       |
| data             | longblob         | YES  |     | NULL    |       |
+------------------+------------------+------+-----+---------+-------+

```

Here is an explaination of some of the columns:

* uid - Unique user id
* name - Unique user name
* mail - Users e-mail address
* created - Timestamp for when user was created
* access - Timestamp for previous time user accessed the site
* login - Timestamp for user?s last login
* status - Whether the user is active(1) or blocked(0)
> 2 votes

# Answer
The same functionality for Drupal 8.x+. The users' table is "users\_field\_data".

```
drush sqlq "SELECT uid,name,mail FROM users_field_data ORDER BY login DESC LIMIT 10"

```
> 2 votes

---
Tags: drush, users
---


# Question
Title: Unprocessable Entity: The following relationship fields were provided as attributes
I'm trying to set the value of a taxonomy term entity reference field with a POST operation in JSON:API.

```
const data = {
  data: {
    type: 'node--page',
    attributes: {
      field_text: {
        value: `${values.textFieldValue}`,
        format: 'basic_html',
      },
      field_ref_term: {
        type: 'taxonomy-term--my-vocabulary',
        id: '9ca0cdc7-384c-4aa4-8ce9-d6c97fc2f44b',
      },
    },
  },
};

```

However, that gives me this error:

> Unprocessable Entity: The following relationship fields were provided as attributes: \[ field\_ref\_term \]

What am I supposed to do to fix this?

# Answer
> 2 votes
As the error indicates, the entity reference has to be set in **relationships**, not **attributes**.

The documentation gives this example:

```
{
  "data": {
    "type": "node--article",
    "attributes": {
      "title": "Article by admin",
      "body": {
        "value": "Custom value",
        "format": "plain_text"
      }
    },
    "relationships": {
      "uid": {
        "data": {
          "type": "user--user",
          "id": "{{UUID of user 1}}"
        }
      }
    }
  }
}

```

In this example, the author of the node is set using the relationship of `uid`. However, it wasn't immediately clear to me how to set the entity reference field.

It turns out to be quite easy:

```
const data = {
  data: {
    type: 'node--page',
    attributes: {
      field_text: {
        value: `${values.textFieldValue}`,
        format: 'basic_html',
      },
    },
    relationships: {
      field_ref_term: {
        data: {
          type: 'taxonomy-term--my-vocabulary',
          id: '9fa0cdc7-384c-4aa4-8ce9-d6c97fc2f44b',
        },
      },
    },
  },
};

```

The key for the relationship is the machine name of the entity reference field.

---
Tags: 8, entities
---


# Question
Title: How do I display the content type's description in a view's header?
I have a view that lists nodes of a single content type, where the content type is given as contextual filter.

I'd like to add the name of the content type and a description to the header, for example as the following.

> ## Content Type: Cooking
>
> The Cooking content type is for cooking-related content

I can show the content type name by by adding a hidden field to the view and then using `<h1>{{ type }}</h1>` in the header, but I don't see such an option for the description.

Is there a way to achieve this?

# Answer
> 1 votes
Here's what you can do:

First, add then config the contextual filter like this:

Then you update the header like this:

## You can update the header status at this step also.

And then here is the result:

**One more thing need you to handle:**

The exception when the filter value is not in the url. Can it be your part?

---
Tags: 8, views
---


# Question
Title: Creating an API via module routing files that includes csrf verification headers
I am working on migrating a custom API from D7 to D8 and am doing so by using module routing. I have a routing.yml file that looks like so:

```
ytp_user.api.login:
  path: "/api/v1/user/login"
  defaults:
    _title: "User API Login"
    _controller: '\Drupal\ytp_user\Controller\UserAPIController::login'
  methods: [POST]
  requirements:
    _csrf_request_header_token: "TRUE"
ytp_user.api.get_current_user:
  path: "/api/v2/user/me"
  defaults:
    _title: "User API Get Current User"
    _controller: '\Drupal\ytp_user\Controller\UserAPIController::getCurrentUser'
  methods: [GET]
  requirements:
    _custom_access: '\Drupal\ytp_user\Controller\UserAPIController::authorize'

```

In the first route, I am trying to validate a csrf token provided in the headers, via the requirement `_csrf_request_header_token: "TRUE"`, however, this does absolutely nothing. It doesn't validate or even check that the header exists as the documentation suggests it should.

I've tried replacing this with `_csrf_token: 'TRUE'` which at least checks that the token exists in the query, but I can't get a valid token!!! If I grab a token from `/session/token` and then pass it along in the query as `?token=<token-from-session/token>` then I just get an error saying the CSRF token is invalid.

Am I missing another step or is the documentation just straight up incorrect? I have been searching for hours and everything suggests that what I have should work, so why is the CSRF token not being validated properly?

# Answer
> 1 votes
The requirement `_csrf_request_header_token: "TRUE"` works only if user is connected because CsrfRequestHeaderAccessCheck use session informations.
If you look at CsrfRequestHeaderAccessCheck in the `access` method there is:

```
 if ($account
      ->isAuthenticated() && $this->sessionConfiguration
      ->hasSession($request)) {

```

To check if the user is connected and it there is a session identifier in the request if it's not it will go directly to:

```
// Let other access checkers decide if the request is legit.
    return AccessResult::allowed()->setCacheMaxAge(0);

```

so it will not check if `X-CSRF-Token` is in the headers or not even if you set the route requirement `_csrf_request_header_token: "TRUE"`.
**Code** **MODULE.routing.yml** MODULE.login:

```
  path: "/api/v1/user/login"
  defaults:
    _title: "User API Login"
    _controller: '\Drupal\MODULE\Controller\UserAPIController::login'
  methods: 'POST'
  requirements:
    _csrf_request_header_token: 'TRUE'

```

**UserAPIController.php**

```
class UserAPIController extends ControllerBase {

  public function login(Request $request) {
    $response['data'] = 'Some test data to return';
    $response['method'] = 'POST';

    return new JsonResponse( $response );
  }

}

```

**Test**

1. With Connected user
2. with anonymous user

---
Tags: 8, routes
---


# Question
Title: Can entity references have "types" like links in Jira?
Suppose I have a node that represents a task, or a to-do item:

> Node 1: Instructions for building a drivable car

I want to link this node to another node, such as a sub-task of the original node:

> Node 2: Instructions for assembling an engine (Sub-task of Node 1)

Now suppose I have another node that is *caused by* one of my original nodes, but is not a sub-task of it.

> Node 3: How to obtain a driver license (required by Node 1)

The entity reference from Nodes `2` to `1` is of type `sub-task` while the link from `3` to `1` is of type `required by` (or maybe `related to`, whatever).

When viewing Node `1`, it might be helpful to display a view of referenced nodes, but rather than just showing the nodes, it would be useful to show the relationship type as well:

```
Items related to "Instructions for building a drivable car":

| Link Type      | Node                                  |
|--------------------------------------------------------|
| Parent Task of | Instructions for assembling an engine |
| Requires       | Getting a driver license              |

```

Applications such as *Jira* handle this via link types. Is functionality like this available within the Drupal ecosystem? Alternatively, what would be a logical way of implementing such functionality?

# Answer
> 1 votes
In Drupal 7, this is possible with the Relation module.

Relations are entities.

So instead of creating entity references to link nodes, when using the Relation module, you create Relation entities, and these Relation entities can contain entity references to two or more entity references to connect them via a "type". In the case of the Relation module, this is an entity type.

Also, because relations are entities, you can add fields to them. And the module provides Views integration and other useful features.

Unfortunately, the port of Relation to Drupal 8 has been abandoned and the maintainers now recommend using the features of core itself-- this is possible, but it's a lot more work than what Relation provided out of the box.

**Creating a similar config to Relation module in D8**

1. Make each "type" its own entity type.
2. Add entity reference fields to each type and set them appropriately.
3. Customize your Views accordingly.

# Answer
> 1 votes
For many real world scenarios, I'd build your example with multiple fields on the node, one for subtasks, and a second for prerequisites, etc.

Obviously, you can run into trouble with that if you want a truly flexible field with many types of references across many different content types or types of content.

For more robust, "Jira style linking", I would look to create a relationship entity to sit between my content.

Based on your notes, this relationship entity would have three fields: one for Entity A, a second for relationship type, and a third for Entity B.

My relationship type field would reference a *Relationship Type* taxonomy vocabulary. I'd use the taxonomy term name's field to describe the relationship type from the perspective of Entity A, and add an additional field to describe the relationship type from Entity B's perspective. E.g. Term Name: "Blocks", Alternate Name: "Is Blocked By".

I would also avoid referencing the relationship entity directly from either Entity A or Entity B. I.e. I would not create an entity reference field on Entity A or Entity B to reference the relationship. (The Relationship Entity already knows about both Entity A and Entity B.) Instead I'd look to implement something like what the Redirect module does - it allows you to view all of the redirects on the node screen, but creating a new one opens the redirect form in a new window and does not directly attach the redirect to the node.

---
Tags: 8, nodes
---


# Question
Title: How do I get the UUID for a current logged in user?
In the Drupal 8 user's table, there is a UUID field. I'm trying to figure out if there is some method to easily access the UUID for a current user like you would when you get a UID for a user.

Thoughts?

# Answer
> 5 votes
You can load the UUID from entities with the method uuid(). If you have an account from the current user service then you have to load the user entity first:

```
$account = User::load($account->id());
$uuid = $account->uuid();

```

# Answer
> 3 votes
I ended up with something similar just now:

```
  /** @var \Drupal\user\Entity\User $user */
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $uuid = $user->uuid();

```

# Answer
> 0 votes
If you're using JSON:API, you can get the UUID of the currently logged in user from `/jsonapi`, which returns a "me" link in the "meta" info:

```
{
  "jsonapi": {
    "version": "1.0",
    "meta": {
      "links": {
        "self": {
        "href": "http://jsonapi.org/format/1.0/"
      }
    }
  }
},
"data": [],
"meta": {
  "links": {
    "me": {
      "meta": {
        "id": "7ab54c06-e431-41a7-8f1f-a7c2165114a2"
        },
        "href": "http://example.lndo.site/jsonapi/user/user/7ab54c06-e431-41a7-8f1f-a7c2165114a2"
      }
    }
  },

```

If you need to get the UUID of a specific user from JSON:API and you have the Drupal UID, you can do this:

```
https://example.com/jsonapi/user/user?filter[uid][value]=123

```

Source

---
Tags: 8
---


# Question
Title: Ajax not getting triggered on change event of selectbox field
I've tried all options to trigger an ajax event on change of a selectbox option inside form alter hook, but nothing works. Below is the sample code

```
$form['field_select_box']['#ajax'] =
   [
     'callback' => 'toggleOptions',
     'event' => 'change',
     'wrapper' => 'edit-field-target'
   ];

```

If I just try to attach the ajax event to a simple text field (like title), it WORKS.

```
$form['title']['widget'][0]['value']['#ajax'] =
  [
    'callback' => 'updateSubdomain',
    'disable-refocus' => FALSE,
    'event' => 'change',
    'wrapper' => 'edit-field-subdomain-0-value',
  ];

```

Help is appreciated

# Answer
For select list, the ajax should be

```
$form['field_select_box']['widget']['#ajax'] = [
  ...
];

```

and please try to code as Drupal standard.
> 0 votes

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


# Question
Title: Entity Print Content Modification For Views
I have a views that I am printing to PDF using Entity Print. The views is a combination of several entities and as such cannot directly utilize the instruction in the "Modify entity content" section of the documentation:

> To modify the content of your entity, you create a twig template using the 'pdf' view mode name (e.g. node--article--pdf.html.twig). In this template you can modify the markup as you normally do with other view modes using {{ content.field\_example }} or {{ node.field\_example }}.

See screenshot of the view:

I tried this twig template suggestion `entity-print--views--machine_name--pdf.html` and template variables like `{{ content.field_bright_news }}` (where the name of one of the fields of a referred entity of the view is `field_bright_news`) but that doesn't seem to work except I may be missing something.

Is the stated instruction in the documentation applicable to views as well or it's solely meant for actual entities. If yes, what is the correct template and variable pattern for this scenario ?

# Answer
I don't think that your template suggestion is correct in this case, so {{content.field\_bright\_news}} may not work.

A few things I can clarify for you are as follows:

{{content.field\_bright\_news}} - this variable is only available in the template of the content type containing that field, it cannot be used in the view template.

For your quote, it is missing the following:

> By default this module only installs the PDF view mode for Nodes. If you have any custom entities on your Drupal site and want to hide the "View PDF" link on those, you must first create a PDF view mode for the entity type. To do this navigate to "admin / structure / display-modes / view" and click on "Add view mode". In the list click the entity type for which you would like to create the PDF view mode. You'll now be asked to name the view mode, you can name it whatever you like but make sure the machine name is just "pdf", which will be automatically prefixed with the entity name. You can now follow the steps in the previous paragraphs for your custom entity.

That is, you must create a display mode for that content type to have a template suggesting as the form

**node--content\_type--display\_mode.html.twig**

And that means, **{{content.field\_bright\_news}}** can be used in the template suggested above.
> 0 votes

---
Tags: 8
---


# Question
Title: How do I modify the email maximum length to 320 characters?
I want to overwrite the maximum charcater limit to 320. It is defined in /core/lib/Drupal/Core/Render/Element/Email.php

Can anybody tell me how to overwrite it?

# Answer
> 3 votes
You can using hook\_element\_info\_alter.

mymodule.module

```
/*
 * Implements hook_element_info_alter().
 */
function mymodule_element_info_alter(array &$info) {
  if (!empty($info['email'])) {
    $info['email']['#maxlength'] = 320;
  }
}

```

Flush all caches so hook gets pickedup.

As Neograph734 pointed out, the mail column's VARCHAR length will also have to be increased in the DB. See Resizing Fields in Drupal 8 Without Losing Data to learn how you can accomplish that.

# Answer
> 0 votes
This can be only changed in patching core , there is a patch contributed here https://www.drupal.org/project/drupal/issues/3177834

---
Tags: 8, emails
---


title: Show the site name in a custom block

text:
# Question
Title: Show the site name in a custom block
I am working on Drupal 8 custom block. I want to print the site name in this custom block.

### MyBlock.php

```
public function build() {
  return [
    '#markup' => t('This is a simple block!'),
  ];
}

```

How can I get the site name?

# Answer
> 5 votes
Get the site name from config and add the config as cacheable dependency so that the block gets updated when you change the site name.

```
public function build() {
  $config = \Drupal::config('system.site');

  $build = [
    '#markup' => $config->get('name'),
  ];

  $renderer = \Drupal::service('renderer');
  $renderer->addCacheableDependency($build, $config);

  return $build;
}

```

---
Tags: blocks
---


# Question
Title: Ajax Callback to Update Select List not Working
I have defined couple of fields inside my custom entity basefielddefinitions() like so...
`$fields['product_line'] = BaseFieldDefinition::create('entity_reference')...`

`$fields['product'] = BaseFieldDefinition::create('entity_reference')...`.

Then in entity form class (ProductLineForm.php), I try to attach an ajax callback to my `product_line select` list such that it populates the `product select list`, like this

```
    $form['product_line']['#group'] = 'details';
    $form['product_line']['#ajax'] = [
      'callback' => '::populateProducts',
      'event' => 'change',
      'wrapper' => 'edit-products'
    ];

```

Then my product select list looks like this...

```
    $form['product']['#group'] = 'details';
    $form['product']['#attributes'] = [
      'id' => 'edit-products',
    ];

```

and then my populateProducts() function...

```
  public function populateProducts(array $form, FormStateInterface $form_state) {
    $form['product']['#options'] = ['1' => 'One', '2' => 'Two'];
    $form_state->setRebuild(TRUE);
    $response = new AjaxResponse();
    $option = "<option value='45'>Just testing</option>";
    $response->addCommand(
      new \Drupal\Core\Ajax\ReplaceCommand(
        '#edit-products',
        ($form['product'])
      )
    );

    return $response;
  }

```

The problem is that nothing whatsoever happens, no signs of any ajax call, and the product select list stays empty as it always been.

(1)Is the the entityform class the right place for me to attach an #ajax call to a field defined in a custom entity? Or do I need a hook? Meanwhile I've done a lot of other modifications on the custom fields here in this entity form edit class (like grouping into fieldsets, vertical tabs and even modifying weight (eg `$form['product_line']['#weight'] = 3` \- and they all work, why not `$form['product_line']['#ajax']`....?

(2) Is there a way of attaching the ajax callback directly inside my custom entity's `basefielddefinitions` where I define the fields, I would prefer that...

Really stuck on this one, folks, please could someone help me? Appreciate all your input, Thank you all.

# Answer
> 0 votes
just got this sorted out! Decided to drill down to the array structure of the form, and found out that the `#ajax` element had to be attached to the `widget` array of the field, like this... `$form['product_line']['widget']['#ajax'] = [...]` Now it works. Another reason I keep crying "better documentation for Drupal"!!! How in the world was anybody supposed to know that for existing form fields, this was the format for adding Ajax?!!! Oh well, thanks community for pointing in the right direction. Anybody knows the right place to insert this in the existing documentation? Cheers all.

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


title: How to migrate password with hash

text:
# Question
Title: How to migrate password with hash
I'm doing a user migration from Drupal 7 to Drupal 8 (the data is in json format)
Most of the fields have been imported to the new website. Now, I'm in the process to migrate the password; this field is, of course, encrypted/hashed (as far as I understood, Drupal uses SHA512 by default with a salt).

So far, I have found this answer and adapted my code like below:

```
$users_json = file_get_contents("../import/users.json");
$users_array = json_decode($users_json, true);

foreach($users_array as $user){

    $values = array(
        'name' => $user["name"],
        'pass' => [
            'value' => $user["pass"],
            'pre_hashed' => TRUE,
        ],
        'status' => $user["status"],
        'mail' => $user["mail"],
    );

    $userStorage = \Drupal::entityTypeManager()->getStorage('user');
    $userEntity = $userStorage->create($values);

    $role = $user["roles"][0];
    $userEntity->addRole($role);

}

```

Now, my question is: Is it a good approach? How do I import this kind of field? Do I have to decrypt/de-hash the password?

# Answer
> 0 votes
You can follow document.

> The $P$ is the so called hash type identifier which indicates that the hash is a portable Phpass hash. The string after that consists of salt and a hash. The portable Phpass hashes can be migrated to Drupal 8 as-is. When the user logs in to your Drupal 8 site for the first time, Drupal will re-hash the password. The salted hash used in this example is for a password 'test'.

> If the source system was a PHP based application that used crypt() or password\_hash(), these hashes should work as-is and they can be migrated 1:1 like in the Phpass example above. When the user logs in to your Drupal 8 site for the first time, Drupal will re-hash the password.

Here is my example convert old pass using **md5**

```
<?php

namespace Drupal\my_module;

use Drupal\Core\Password\PhpassHashedPassword;
use Drupal\Core\Password\PasswordInterface;

/**
 * Provides custom password hash comparison for migrated passwords.
 */
class MyModulePasswordService extends PhpassHashedPassword implements PasswordInterface {

  public function check ($password, $hash) {
    // Check old pass is md5
    if (preg_match('/^[a-f0-9]{32}$/', $hash)) {
      $pwd_sercet = "pwd_sercet";
      $pass_hash = md5($pwd_sercet . $password);
      return ($pass_hash == $hash);
    }
    return parent::check($password, $hash);
  }
}

```

---
Tags: users, migrations
---


# Question
Title: How do I display username in a custom block?
Am new to Drupal so this is a very fundemental question.

How do I display the current username ? In a custom Block? I beleive is the `$user->name` session variable.

**Do I create a Custom Block Type?** If so how do I reference the username?

**Do I edit files on the file system?** If so which files?

**Do I create new files?** If so where?

In other web frameworks the templating engine allows server script tags... ex.. like

`<%= username %>`

Ive tried putting

`$user->name` and `{{app.user}}`

into the custom block editor but nope, I've learned it's a WYSISYG with no way to render

All I want to do is display a user name in a block I can add a label too.

Any help appriciated.

# Answer
You can do this in sevaral ways, one of this could be use a `preprocess function`. In your custom module in the `.module` file or your custom theme in the `.theme` file (recommended) write this:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function [my_module_or_theme]_preprocess_block(&$variables) {
  $variables['username'] = \Drupal::currentUser()->getUsername();
}

```

and then in your template suggestions of `block.twig.html` print the variable `{{ username }}`
> 3 votes

# Answer
To answer my question I created a custom module with a block.

That needed a folder for the module, a .info.yml file and a file for the block.

1) A folder for the module `modules/custom/my_show_user`

2) The file `modules/custom/my_show_user/my_show_user.info.yml`

```
name: Show User Module
description: Displays the logged in user name in a block.
package: Custom

type: module
core: 8.x

dependencies:
  - drupal:block

php: 5.6

```

3) The file `modules/custom/my_show_user/src/Plugin/Block/UserNameBlock.php`

```
<?php

namespace Drupal\my_show_user\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'User Name' Block.
 *
 * @Block(
 *   id = "my_show_user",
 *   admin_label = @Translation("Show User"),
 *   category = @Translation("Show User"),
 * )
 */

class UserNameBlock extends BlockBase {

    /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t(\Drupal::currentUser()->getUsername()),
    );
  }

}

```

That's it done. .

fyi, any time a change is made clear the cache to see it
`Manage>Configuration>Performance>Clear All Caches`

In Structure \> Place Block a block called `UserNameBlock` can now be selected and it displays the current logged in user.

Adding the dependency `- drupal:block` and keeping the commented annotations @Block and @inheritdoc was key.

the line

`'#markup' => $this->t('any html string can go here ' .
 \Drupal::currentUser()->getUsername() .
 ' concatenated with data in the template, in this case username' ),`

is the entry point for your 'custom template'.
> 2 votes

# Answer
public function build() { return \[ '#markup' =\> $this-\>t(\Drupal::currentUser()-\>getUsername()), \]; }
> 0 votes

---
Tags: blocks, sessions
---


# Question
Title: Loading nodes that are only available to the current user
How do I programmatically load nodes that are available to the current user?

I used `node_load_multiple()`, but it seems to directly load nodes from the database, bypassing permissions.

# Answer
> 1 votes
You need to use the `EntityFieldQuery` class. The following is example code to load all the published nodes whose content type is *Article*.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED);

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

```

EntityFieldQuery returns only the nodes to which the currently logged-in user has access. In the case you would get all the nodes for which you know the author user ID, you should use the following code.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('uid', $uid);

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

```

That code returns all the nodes created in the site. To get only 10 nodes, it sufficient to add a call to `$query->range(0, 10)` before calling `$query->execute()`.

---
Tags: 7, nodes
---


title: Cannot upload file of type image

text:
# Question
Title: Cannot upload file of type image
I am experiencing a really strange behavior I have never seen before with Drupal. I am able to upload files of every type but not images. The files system is public. The problem appears on the local test server and on the live server.

**Error message:** The image upload widget shows the standard error box logging: \**The file xyz.jpg could not be uploaded.

* This value should not be null\**

This issue appears on the whole site on every image of the file field widget within the backend. Even the file upload for Drupal's "File Archive" does just work with every other file type than 'jpg', 'jpeg', 'gif', 'png' file types.

The issue appeared after updating to the "web/" file structure while also updating the core to 8.8. I tried to update to 8.9.12 including every module installed but the error when trying to upload a file stays.

I rechecked all the settings regarding "tmp folder" and also tested the folder access rights (chown, chmod). It is set to 777.

I updated the database (drush updb) and also rebuild the cache (drush cr).

No PHP error log is created (not in Drupals Watchdog or the apache log).

I am sure that it is not a configuration issue as I am able to upload files that are not image files without problems. Another interesting bit is that when uploading a file it is actually created in the final sites/default/files location. The file also has the correct owner and access rights.

I could not find a related issue when researching nor I am able to come up with another idea. I even tried to change the file system to private, created new entities with image or file fields and tried different image upload widgets - nothing seems to work.

Any help is greatly appreciated.

# Answer
> 0 votes
After spending good 20hours with investigating the issue I was able to fix it by repairing an entity error in the database via un and installing the file\_entity module.

---
Tags: 8, files
---


# Question
Title: How to insert custom redirect script in index.php without losing it on update
At the moment I'm migrating an old site to Drupal. To redirect all old url's to new ones, I made a script that has to be inserted before anything goes off, so in index.php at the top.

```
   <?php

    include 'custom.php';

    use Drupal\Core\DrupalKernel;
    use Symfony\Component\HttpFoundation\Request;
    etc.etc.

```

All is fine until an update wipes this out. Could (should?) it be done some other way to preserve this?

# Answer
If you want to run code before the Drupal kernel is started use a middleware.

Use the drush code generator `drush gen middleware` and put your code in handle() of the generated middleware class:

*MymoduleMiddleware.php*

```
<?php

namespace Drupal\mymodule;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * MymoduleMiddleware middleware.
 */
class MymoduleMiddleware implements HttpKernelInterface {

  use StringTranslationTrait;

  /**
   * The kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * Constructs the MymoduleMiddleware object.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
   *   The decorated kernel.
   */
  public function __construct(HttpKernelInterface $http_kernel) {
    $this->httpKernel = $http_kernel;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {

    if ($request->getClientIp() == '127.0.0.10') {
      return new Response($this->t('Bye!'), 403);
    }

    return $this->httpKernel->handle($request, $type, $catch);
  }

}

```
> 4 votes

---
Tags: 8, redirection
---


title: Join user to custom table

text:
# Question
Title: Join user to custom table
I have a custom table (myusersession) which contains the *uid* field that is a reference to user entities.

How can I add user entity fields (exactly 'name') to my view?

I tried many variations of join, in `hook_views_data()`, but none of them works.

```
  $data['myusersession']['table']['join'] = array(
    'users_field_data' => array(
      'field' => 'uid',
      'left_field' => 'uid',
    ),
  );

  $data['myusersession']['uid'] = array(
    'title' => t('UID'),
    'help' => t(''),
    'field' => array(
      'id' => 'numeric',
    ),
    'filter' => array(
      'id' => 'numeric',
    ),
    'argument' => array(
      'id' => 'numeric',
    ),
    'relationship' => array(
      'title' => t('User'),
      'help' => t(''),
      'base' => 'users',
      'base field' => 'uid',
      'id' => 'standard',
    ),
  );

```

I also tested variations of the table name, such as users\_field\_data, users, and user.

As I understand the following code should be work, but it doesn't in my case.

```
    'relationship' => array(
      'title' => $this->t('User'),
      'label' => $this->t('User'),
      'base' => 'users',
      'base field' => 'uid',
      'relationship field' => 'uid',
    ),

```

With `['table']['join']`, the table appears as column on the view with *User* as base, but but if the view base is *myusersession*, *User* doesn't appear.

# Answer
> 1 votes
```
    //Relationship b/w users_field_data and myusersession
  $data['myusersession']['uid']['relationship'] = [
    'title' => t('User'),
    'help' => t('Relate User.'),
    'id' => 'standard',
    'base' => 'users_field_data',
    'base field' => 'uid',
    'field' => 'uid',
    'label' => t('User'),
  ];
  return $data;

```

This code will work.

# Answer
> 0 votes
Found that there is additional step: you have to add/enable that relationship at View GUI-\>Advanced-\>Relationship

---
Tags: views, 8
---


# Question
Title: How to add extra classes to <div view-content> in Views?
Is there a way to add an extra class to the View content wrapper, which outputs as `<div class="view-content">`?

To make it clear: I use Semantic views to generate a nice UL for a slider, but I am not able to add a wrapper with the proper class name to trigger the Jquery.

# Answer
**For Drupal 7**

The div with view-content class comes from views-view.tpl.php template file.

You can always override your view theme and adjust the class names, HTML etc..

Under Advanced section of view click on information at the bottom of the section next theme, you will see a list of template files including the top level template which is views-view.tpl.php.

You can find a lot of tutorials how to override views templates file but in general, it's all about copying the right file to your theme and rename it with the right template file.

You can take look at this tutorial how to do that

**For Drupal 8**

Views UI no longer provide suggestions, In order to get the same information you need to enable Twig debugging.

You can enable Twig Debugging in sites/default/services.yml.

Set the debug variable to true. And clear cache.

```
parameters:
  twig.config:
    debug: true

```

(*If services.yml does not yet exist; copy default.services.yml and copy it to services.yml.*)

Using your browser debugger, you will see the templates suggestion as HTML comments, just be sure your browser debugger is set to show HTML comments.
> 4 votes

# Answer
If your theme uses Classy as base theme (like Bartik does). (You can check this in your theme's .info.yml.)

Then copy /core/themes/classy/templates/views/views-view.html.twig

and paste it in your theme's /templates folder.

Now simply add new class here

```
  {% if rows %}
    <div class="view-content some-new-class">
      {{ rows }}
    </div>
  {% elseif empty %}

```

---

If this question is for D7, then replace .html.twig with .tpl.php
> 4 votes

# Answer
Not sure if it's the best way to do this, but you can use the following code, with Drupal 7.

```
function MODULENAME_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'VIEWNAME') {
    $vars['rows'] = "<div class='wrapper-class'>" . $vars['rows'] . "</div>";
  }
}

```

This will wrap contents just below the "view-content" class
> 0 votes

---
Tags: views, theming
---


# Question
Title: How can I override the markup of a view I printed in a template file?
I installed the Twig Tweak module on my site to render Views on the home page.

I want to make the display mode `frontpage_tasks` for the current user, his account, his stores and his groups.

```
{{ drupal_entity('user', user.id, 'frontpage_tasks') }}
{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}
{{ drupal_view('accueil_page_liste_des_taches_groupe', 'block_1') }}

```

Here is one of my Views :

The problem is that the Views module adds a lot of unnecessary markup that makes it impossible to display it correctly.

I just want to make the display mode, without any additional tags.

How to do this ? Is there a Twig code to render only Views without the additional View tags ?

**UPDATE**

I created an `views-view--accueil_page_liste_des_taches_boutique.html.twig` template. It only contains the following code :

```
{{ rows }}

```

I display the Views blocks with the code below, on my homepage :

```
                <div class="main-timeline">
                  <div class="row">
                    {{ drupal_entity('user', user.id, 'frontpage_tasks') }}
                    {{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }}
                    {{ drupal_view('accueil_page_liste_des_taches_groupe', 'block_1') }}
                  </div>
                </div>

```

I still have this damn markup :

```
                <div class="views-element-container">
                  <div>
                    ...
                  </div>
                </div>

```

Is there a code in TWIG to remove this basisage ?

https://ibb.co/b1tKXhQ

# Answer
1. You can enable Twig debugging for your site in sites/default/services.yml

```
    parameters:
      twig.config:
        debug: true

```
2. Clear cache
3. Inspect element in the browser and you will see the path to the template
4. Copy the template to your custom theme's templates/ directory and adjust the markup
> 1 votes

# Answer
For override view template, you should override (views-view.html.twig) this is template for all views.

If you want override only one specific view then copy code from views-view.html.twig to:

```
[base template name]--[view machine name].html.twig

```

example: (views-view--partners--block-1.html.twig)

and override this view as you want
> 0 votes

# Answer
You should add suggestions for views using this patch https://www.drupal.org/files/issues/views-template-suggestions-2839945-2.patch recommended here https://www.drupal.org/project/drupal/issues/2839945 in order to see twig suggestion in debug html, additional you should enable the twig debug as mention above
> 0 votes

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


title: Unlimited values for 2 combined fields

text:
# Question
Title: Unlimited values for 2 combined fields
I want to add 3 fields to my articles:

* `repeatable` (boolean)
    + unlimited values for `repeat_date` and `repeat_comment`

I created the fields and with fields dependency I made the it possible that `repeat_date` and `repeat_comment` only appear if `repeatable` is checked. I can also create an unlimited number of values for `repeat_date` and `repeat_comment`.

But these 2 fields are independet of another. I could create 2 values of `repeat_date` entries and 4 values of `repeat_comment`. Also those fields appear separate when editing articles.

How can I combine those 2 fields and have unlimited values for this combined fields?

# Answer
> 0 votes
In the end I used the field collection module since I had it already installed. I created such collection containing 2 fields: `repeat_date` and `repeat_comment`. Then I made the collection itself unlimited repeatable.

# Answer
> 3 votes
You can wrap the fields in a Paragraph with the paragraphs module. I.e. create a new paragraph type, *repeatable\_date*, with two fields: date and comment. Then add a new paragraphs reference field to your article and set cardinality to unlimited. This will allow you to add unlimited repeatable date items, each with date and comment.

Or you can create a new custom field type that has a date field and a comment field. This is more difficult to do, but may be preferable if the paragraphs route doesn't suit you. See How to create a new field type for details.

---
Tags: 7
---


title: Hide breadcrumb from CMIS views

text:
# Question
Title: Hide breadcrumb from CMIS views
We're running Drupal 7.65 and Alfresco 5.2.4. We've the ability to display CMIS content (hosted in Alfresco) by fetching a URI like: `https://domain.com/cmis/browser?id=<node_ID>`. Doing so allow users who doesn't have access to Alfresco to download a file (if `node_ID` refers to a file) or browse the content of a directory (if `node_ID` refers to a directory).

**Issue:** sharing a directory via this method allow users to navigate the whole content of Alfresco by navigating the breadcrumb.

**We'd like to remove this breadcrumb**, could you recommend ways to do it ?

Here's what we've been thiking at:

* Ideally, find a Drupal/Alfresco setting that allow us to restrict display
* Comment out the line(s) responsible of displaying this breadcrumb inside Drupal' source code
* less ideally, filter the DOM through JS (`document.getElementById('cmis-breadcrumb').innerHTML = ''`)

---

Apologies for my English and the lack of knowledge about CMIS and Drupal

---

**edit 19/01/2021**: I believe I've found the module & the function responsible for the breadcrumb: https://git.drupalcode.org/project/cmis/-/blob/7.x-1.x/cmis\_browser/cmis\_browser.theme.inc#L125

# Answer
> 1 votes
CMIS Browser, a submodule of CMIS API, handles CMIS links. We are using CMIS API v7.x.x.

Here's the function responsible for the breadcrumb:

```
# cmis/cmis_browser/cmis_browser.theme.inc #125

function theme_cmis_browser_browse_breadcrumb($variables) {

  $next_img = theme('image', array('path' => drupal_get_path('module', 'cmis_browser') .'/images/next.gif'));
  $contents = '';
  $currentpath = '';

  $contents .= '<div id="cmis-breadcrumb">';
  if (!empty($_GET['type']) && $_GET['type'] == 'popup') {
    $contents .= l('Root', 'cmis/browser'. $currentpath, array('query' => array('type' => 'popup', 'caller' => $_GET['caller'])));
  }
  else {
    $contents .= l('Root', 'cmis/browser'. $currentpath);
  }

  $currentpath = '';
  foreach ($variables['bcarray'] as $space) {
    $contents .= $next_img .' ';
    $currentpath .= '/'. $space;
    if (!empty($_GET['type']) && $_GET['type'] == 'popup') {
      $pagelink = l($space, 'cmis/browser'. $currentpath, array('query' => array('type' => 'popup', 'caller' => $_GET['caller'])));
    }
    else {
      $pagelink = l($space, 'cmis/browser'. $currentpath);
    }
    $contents .= $pagelink;
  }

  $contents .= '</div>';

  return $contents;
}

```

Our workaround is simply to return an empty `<div>` earlier:

```

function theme_cmis_browser_browse_breadcrumb($variables) {
  return '<div id="removed-breadcrumb"></div>';

  .....
}

```

Be careful since it's not a persistent solution.

---
Tags: breadcrumbs
---