# Question
Title: views.view.unformated.html.twig taxonomy conditional if/else
I am trying to get to the field\_news\_type term\_id/label. I can print the field and I get the term label. Need guideance to be able to select which one I want to use.

```
{{ fields.field_news_type.content }} //prints the term 'Grid 2' which is correct.

```

I am trying to get either the label or term\_id, so I can do a conditional. The below does not work. I have tried many variations. I have not found an answer that has produced a working result. Can someone guide me to finding the correct way to print this out in a views template page?

```
{% if fields.field_news_type.target_id == '2871' %}

```

I can use this for a node template page and it works...but not in the views twig file.

```
{% if content.field_research_focus_areas['#items'].getValue() %}

```

# Answer
> 0 votes
The code doesn't match the template, it's more likely from a views-view-fields.html.twig template. Then you could configure a separate field in Views UI to produce the output you want. Views fields are not a 1:1 match of entity fields, you can rewrite the entity content to whatever you want. Most times it's a better idea to put Twig in Views UI and not in Views templates.

If you really want to access raw field values, don't use the output of Views field plugins. Access field values directly through the node object:

```
{{ row._entity.field_ref.target_id }}

```

More info Access row value in template\_preprocess\_views\_view\_fields(&$variables)

---
Tags: views, theming
---


# Question
Title: How can I copy a body field from one node to another node?
I'm trying to write a small module that copies the body content from one node to another node. The module does almost what it should and everything arrives so far. However, I have to open the node to be copied once, then save it and then open it again. Then it has taken over everything correctly. But I would like to have the field already copied when I open the node. Since this is my beginnings in module development, I would of course appreciate any tips. I am also sure that this can be done more elegantly.

```
/**
 * Implements hook_form_alter().
 */
function copy_fields_from_model_contract_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $nid = 6766;
  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $node = $node_storage->load($nid);
  if ($nid == '6766') {
    $getcontract = $node->field_vertragsinhalt->value;
  }

  $nid = 6716;
  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $node = $node_storage->load($nid);
  if ($nid == '6716') {
    if ($form_id == 'node_buch_anlegen_edit_form') {
      $node->field_vertragsinhalt->value = $getcontract;
      $node->body->format = 'full_html';
      $node->save();
      dpm("Testsetest");
    }
  }
}

```

# Answer
Use hook\_ENTITY\_TYPE\_prepare\_form if you want to change a field value before the form is built for an existing node:

```
<?php

use Drupal\node\NodeInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for node entities.
 */
function mymodule_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
  if ($operation == 'edit') {
    if ($node->id() == '6716') {
      $node->field_vertragsinhalt->value = $getcontract;
      $node->body->format = 'full_html';
      // don't save the node yet, it will be saved after submitting
    }
  }
}

```

For the more common case of setting field values when creating new nodes see Pre-populate an entity reference field (media image) when creating a node
> 1 votes

# Answer
Vielen dank dafür, dass war genau das was ich brauchte. Und ich habe das auch soweit hin bekommen in der node edit version:

```
<?php

use Drupal\node\NodeInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for node entities.
 */
function copy_fields_from_model_contract_node_edit_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state)
{

//TODO Build NID as array and go through with loop

  $nid = 6766;
  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $node = $node_storage->load($nid);

  if ($nid == '6766') {
    $getcontract = $node->field_vertragsinhalt->value;
  }

  //TODO Works without ($operation == 'default')

  if ($operation == 'edit')  {
    dpm ("Modul an edit");
    //TODO Shall always pull the current node and nid. But does not work yet with node creation. Error: Call to a member function id() on null in

    $node = \Drupal::routeMatch()->getParameter('node');
    $nid = $node->id();
    $node_storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $node_storage->load($nid);

    if ($node->getType() == 'buch_anlegen') {
      dpm($nid);
      $node->field_vertragsinhalt->value = $getcontract;
      $node->body->format = 'full_html';
      // don't save the node yet, it will be saved after submitting
    }
  }
}

```

That also does what it is supposed to. Now I would like to write the content when the node is created. There the hook also geift so far.

I have edited for this:

```
 if ($operation == 'edit')

```

to

```
 if (($operation == 'edit')|| ($operation == 'default'))

```

But then it throws me an error in line 30:

```
$nid = $node->id();

```

Could it be that when a node is created at this point the ID is not yet assigned? Or do I have a knot in my head now somehow. I'm trying to use hook\_entity\_type\_create for this geread. The example for this:

```
/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(\Drupal\node\NodeInterface $node) {

  if ($node->getType() == 'my_content_type') {
    $media = \Drupal::entityTypeManager()->getStorage('media')->load(38);
    $node->field_image[] = $media;
  }

}

```

Or am I all wrong there? And how do I get this to fit my case? This is what I have so far:

```
<?php

use Drupal\node\NodeInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for node entities.
 */
function copy_fields_from_model_contract_node_create_node_create(NodeInterface $node)
{
//TODO Build NID as array and go through with loop

  $nid = 6766;
  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $node = $node_storage->load($nid);

  if ($nid == '6766') {
    $getcontract = $node->field_vertragsinhalt->value;
  }

  //TODO Works without ($operation == 'default')

  if ($node->getType() == 'mustervertrage') {
    /*dpm ($node->field_vertragsinhalt->value);*/
    //TODO Shall always pull the current node and nid. But does not work yet with node creation. Error: Call to a member function id() on null in

//        $node = \Drupal::routeMatch()->getParameter('node');
//        $nid = $node->id();
    $node_storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $node_storage->load($nid);

    if ($node->getType() == 'mustervertrage') {
      dpm($nid);
      $node->field_vertragsinhalt->value = $getcontract;
      $node->body->format = 'full_html';
      // don't save the node yet, it will be saved after submitting
    }
  }
}

```
> 0 votes

---
Tags: nodes, hooks
---


# Question
Title: How do I install with PostgreSQL using Docksal?
I use Docksal for developing on Drupal. Recently, I decided to install Drupal 9 with PostgreSQL as a database using Docksal.

Firstly, I cloned https://github.com/docksal/boilerplate-drupal9. Then, I modified some files accordingly to https://github.com/docksal/docksal/issues/193#issuecomment-376343111. Lastly, I ran `fin init` and this error message.

> \[warning\] Failed to drop or create the database. Do it yourself before installing.
> ERROR 2002 (HY000): Can't connect to MySQL server on 'db' (115)
>
> \[notice\] Starting Drupal installation. This takes a while.

Frankly speaking, I can't understand what does MySQL has to do with it? The database driver should be PostgreSQL and the default database should be also PostgreSQL.

Has anybody encountered this problem? Is it possible to install Drupal 9 on PostgreSQL via the Docksal service?

# Answer
> 1 votes
It should be noted that you need postgres 10+ when using Drupal 9.

The steps that you are following in are for Drupal 8 and they will install postgres 9.

Recently a services has been added to Docksal that installs a postgres database that matches your Drupal version (8 or 9). See the Docksal documentation on adding a postgres service.

Add this service and outcomment the default db image in docksal.env:

```
#DB_IMAGE='docksal/mysql:5.7-1.4'

```

When this services is added check that it works correctly by checking the docksal status:

```
~/S/mysite ❯❯❯ fin status
   Name                  Command                 State                         Ports
-------------------------------------------------------------------------------------------------------
d9geo_cli_1   /opt/startup.sh supervisord     Up (healthy)   22/tcp, 3000/tcp, 9000/tcp
d9geo_db_1    docker-entrypoint.sh postgres   Up             0.0.0.0:49174->5432/tcp,:::49174->5432/tcp
d9geo_web_1   httpd-foreground                Up (healthy)   443/tcp, 80/tcp

```

Your Drupal settings should look as follows (note that the driver should be pgsql)

```
$databases['default']['default'] = [
    'database' => 'default',
    'username' => 'user',
    'password' => 'user',
    'host' => 'db',
    'driver' => 'pgsql',
];

```

User, password etc. can be changed using environment variables.

Now you should be able to install the website.

---
Tags: database, 9
---


# Question
Title: It's possible to pass a variable on attach_library in a template on Drupal 8?
I need to pass a variable to a library called on a Twig template, is this possible?

```
{{ attach_library('theme/some-library') }}

```

# Answer
.module

```
/**
 * Implements hook_ENTITY_TYPE_load()
 */

function my_module_node_load($nodes) {
    foreach ($nodes as $node) {
      if ($node->getType() == 'article') { // is of article content type
        $data_passer = &drupal_static('my_module_node_field_name');
        // use &drupal_static to pass value between hooks.
        $data_passer = $node->field_name->value;
      }
    }
}

/**
 * Implements hook_page_attachments()
 */
function my_module_page_attachments(array &$attachments) {
    if (!empty(&drupal_static('my_module_node_field_name'))) {
      $data_passer = &drupal_static('my_module_node_field_name');
      $node_field_name = $data_passer;
      $attachments['#attached']['drupalSettings']['my_variable'] = $node_field_name;
    }
  }
}

```

.js

```
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.my_behaviour = {
    attach: function (context, settings) {

      alert(drupalSettings.my_variable); //alerts passed in node field_name

    }
  };
})(jQuery, Drupal, drupalSettings);

```
> 3 votes

# Answer
I have passed my variable in twig like this:

```
{{ attach_library('theme/library' ~ variable ) }}

```
> -1 votes

---
Tags: 8
---


# Question
Title: How to change Search API index field machine name?
I am using Search API and Search API Solr modules on drupal 7. I have also drupal 8 and drupal 9 sites, and all those sites are indexed on the same solr index. So I need the same machine name for indexed fields on Solr index. For this purpose, I need to change marked machine names. Solr index field names are generated from those machine names.  For drupal 7 I can't find a field mapping solution like Search API field map module for drupal 8, 9. Is there any solution to override those fields' machine names in index creation? Thanks.

# Answer
> 1 votes
My answer I found in search\_api\_solr module search\_api\_solr.api.php file. I used **hook\_search\_api\_solr\_field\_mapping\_alter**

```
/**
 * Change the way the index's field names are mapped to Solr field names.
 *
 * @param SearchApiIndex $index
 *   The index whose field mappings are altered.
 * @param array $fields
 *   An associative array containing the index field names mapped to their Solr
 *   counterparts. The special fields 'search_api_id' and 'search_api_relevance'
 *   are also included.
 */
 function hook_search_api_solr_field_mapping_alter(SearchApiIndex $index,
                                                               array &$fields) {
   if ($index->entity_type == 'node' && isset($fields['body:value'])) {
    $fields['body:value'] = 'tm_text';
   }
 }

```

Here you can add required Solr index field name('tm\_text') for according field('body:value').

---
Tags: 7, search
---


# Question
Title: Issue trying to implement the Swagger UI module in Drupal: ReferenceError: SwaggerUIBundle is not defined
I am trying to integrate the Swagger UI module into Drupal 8 after adding custom REST routes/resources. I have installed the `OpenAPI`, `OpenAPI_UI`, and `OpenAPI_Rest` modules and I'm able to get a valid swagger json resource back when navigating to `<mysite>/openapi/rest` after installing all the modules.

The issue I am having now is trying to get the Swagger UI module to render in the OpenAPI module. After navigating to `Administration` -\> `Configuration` -\> `Web Services` -\> `OpenAPI Resources` I am able to select the `Explore with Swagger` button, which should utilize the Swagger UI Module which has been installed following the steps listed here: https://www.drupal.org/project/openapi\_ui\_swagger

Navigating to the page leads to an empty table, and digging into the console, I get this error:

```
js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:1544 Uncaught ReferenceError: SwaggerUIBundle is not defined
    at Object.attach (js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:1544)
    at js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:59
    at Array.forEach (<anonymous>)
    at Object.Drupal.attachBehaviors (js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:56)
    at js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:284
    at HTMLDocument.listener (js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:276)

```

This is being thrown inside the `swagger.js` file inside the Swagger UI module:

```
 var config = {
        dom_id: dom_id,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl,
          SwaggerUIHideTopbarPlugin
        ],
        layout: "StandaloneLayout"
      }

```

It seems like the SwaggerUIBundle and other Swagger JS objects aren't being exported properly and JS is throwing the `UncaughtReferenceError` when accessing these members. Has anyone come across this error before? I am pretty new to Drupal and I'm trying to figure out what the issue is, because it seems like I've followed the steps properly to get everything working.

This also seems to be close to what I am experiencing, but unfortunately there was no posted resolution: https://www.drupal.org/project/openapi\_ui\_swagger/issues/3073250

# Answer
I seem to have found a resolution to this issue.

In the installation notes for the SwaggerUI module, the instructions state to add this block of code to the `composer.json`

```
"extra": {
  "installer-paths": {
    ...
    "web/libraries/{$name}": ["swagger-api/swagger-ui", "type:drupal-library"],
    ...
  }
}

```

When running `composer install`, composer will place the external swagger-api in the `/web/libraries/<whatever>` directory.

In the `openapi_ui_swagger.libraries.yml` file located within the SwaggerUI module, it is pulling in the external swagger-api here:

```
swagger_ui:
  js:
    /libraries/swagger-ui/dist/swagger-ui-bundle.js: {}
    /libraries/swagger-ui/dist/swagger-ui-standalone-preset.js: {}
  css:
    theme:
      /libraries/swagger-ui/dist/swagger-ui.css: { minified: true }

swagger_ui_integration:
  js:
    js/swagger.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - openapi_ui_swagger/swagger_ui

```

The library paths need to be updated to match the directories created in the installation notes:

```
js:
    /web/libraries/swagger-ui/dist/swagger-ui-bundle.js: {}
    /web/libraries/swagger-ui/dist/swagger-ui-standalone-preset.js: {}
  css:
    theme:
      /web/libraries/swagger-ui/dist/swagger-ui.css: { minified: true }

```
> 2 votes

---
Tags: views
---


# Question
Title: How do I get the title of a referenced node from a field?
I am trying to build a View that lists People's Profiles which are referenced to a Team via a Paragraph (within that Profile) to print out the Name of the Person and other data from the Profile.

The *Team* content type is for representing a team, with title, picture, and description. *Profile* content type has a title, name, some other fields, and a paragraph with further role-based data for a team.

### Profile

* Name
* Body
* Role\_in\_Team (Paragraph):
    + Datetime\_Start
    + Datetime\_End
    + Role\_Name
    + Team\_Reference (Entity reference to a Team)
    + ...

On a Team node, a view shall show the matching profiles beneath.

I build a view Block with:

* A contextual Filter with "ID from URL" to relate everything just to the shown team node
* A relationship with "Team\_Reference" to show only paragraphs that are referenced to (this) team (Paragraph uses *Team\_Reference*.)
* A relationship with "Content using Team\_Reference" (with relationship "Team\_Reference" within)

The view block shows the correct number of profile entries (that are referenced), but I can't get it to show the profile's names.

How do I get access the parent node's fields of the of the specific paragraph?

>

This is the exported block.

```
uuid: 60312c0b-a7b5-4e59-9935-005b4eeec9c3
langcode: de
status: true
dependencies:
  config:
    - field.storage.node.field_geburtstag
    - field.storage.paragraph.field_bezeichnung
  module:
    - datetime
    - node
    - paragraphs
    - user
    - views_bootstrap
id: team_profile
label: Team->Profile
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Anwenden
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: some
        options:
          items_per_page: 5
          offset: 0
      style:
        type: views_bootstrap_table
        options:
          grouping: {  }
          row_class: ''
          default_row_class: true
          override: 1
          sticky: 0
          caption: ''
          summary: ''
          description: ''
          columns:
            title: title
            field_geburtstag: field_geburtstag
          info:
            title:
              sortable: 0
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: 0
              responsive: ''
            field_geburtstag:
              sortable: 0
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: 0
              responsive: ''
          default: '-1'
          empty_table: 0
          responsive: 0
          bootstrap_styles:
            striped: 0
            bordered: 0
            hover: 0
            condensed: 0
      row:
        type: fields
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          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: 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
          plugin_id: field
        field_geburtstag:
          id: field_geburtstag
          table: node__field_geburtstag
          field: field_geburtstag
          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: datetime_default
          settings:
            timezone_override: ''
            format_type: medium
          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
        field_bezeichnung:
          id: field_bezeichnung
          table: paragraph__field_bezeichnung
          field: field_bezeichnung
          relationship: reverse__paragraph__field_referenz_auf_team
          group_type: group
          admin_label: ''
          label: Bezeichnung
          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: true
          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: {  }
          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
      filters:
        status:
          value: '1'
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
            operator_limit_selection: false
            operator_list: {  }
          group: 1
      sorts:
        created:
          id: created
          table: node_field_data
          field: created
          order: DESC
          entity_type: node
          entity_field: created
          plugin_id: date
          relationship: none
          group_type: group
          admin_label: ''
          exposed: false
          expose:
            label: ''
          granularity: second
      title: Team->Profile
      header: {  }
      footer: {  }
      empty: {  }
      relationships:
        reverse__paragraph__field_referenz_auf_team:
          id: reverse__paragraph__field_referenz_auf_team
          table: node_field_data
          field: reverse__paragraph__field_referenz_auf_team
          relationship: none
          group_type: group
          admin_label: field_referenz_auf_team
          required: false
          entity_type: node
          plugin_id: entity_reverse
        field_referenz_auf_team:
          id: field_referenz_auf_team
          table: paragraph__field_referenz_auf_team
          field: field_referenz_auf_team
          relationship: reverse__paragraph__field_referenz_auf_team
          group_type: group
          admin_label: 'field_referenz_auf_team: Inhalt'
          required: false
          plugin_id: standard
      arguments:
        nid:
          id: nid
          table: node_field_data
          field: nid
          relationship: none
          group_type: group
          admin_label: ''
          default_action: default
          exception:
            value: all
            title_enable: false
            title: All
          title_enable: false
          title: ''
          default_argument_type: node
          default_argument_options: {  }
          default_argument_skip_url: false
          summary_options:
            base_path: ''
            count: true
            items_per_page: 25
            override: false
          summary:
            sort_order: asc
            number_of_records: 0
            format: default_summary
          specify_validation: false
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          not: false
          entity_type: node
          entity_field: nid
          plugin_id: node_nid
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.node.field_geburtstag'
        - 'config:field.storage.paragraph.field_bezeichnung'
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.node.field_geburtstag'
        - 'config:field.storage.paragraph.field_bezeichnung'

```

# Answer
Paragraphs are just double-layered Entity Reference fields. You want to show backwards information, to show children and grandchildren (Profiles) on Parent/Grandparent (Teams) nodes.

To show "backwards" info you need the "backwards" Relationship. "Backwards" Relationships are named slightly differently from "forward" ones, you need to recognize which of the two for a field you need to use by logic of "something referenced" or "something that is referencing".

Since you have two levels of connections you need to chain 2 "backwards" Relationships in order to get to grandchildren starting from grandparents.

First you need the backwards Relationship for the field between Team and Paragraph, you may have that already. Then you need to add another backwards Relationship, this time for the field between Profile and Paragraph, and make it use the first Relationship I mentioned to chain them.

Now Views has access to all the database tables you want. To show Profile fields add a field you want and make it use the second chained Relationship.

Your Contextual filter seems in good order, but I'm not sure about the second Relationship you mentioned, if you didn't add it for some other purpose you probably need to remove it.
> 2 votes

# Answer
Following the prkos' answer, I obtained the following view block.

```
uuid: 60312c0b-a7b5-4e59-9935-005b4eeec9c3
langcode: de
status: true
dependencies:
  config:
    - field.storage.paragraph.field_bezeichnung
  module:
    - node
    - paragraphs
    - user
    - views_bootstrap
id: team_profile
label: Team->Profile
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Anwenden
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: none
        options:
          offset: 0
      style:
        type: views_bootstrap_table
        options:
          grouping: {  }
          row_class: ''
          default_row_class: true
          override: 1
          sticky: 0
          caption: ''
          summary: ''
          description: ''
          columns:
            title: title
            field_geburtstag: field_geburtstag
          info:
            title:
              sortable: 0
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: 0
              responsive: ''
            field_geburtstag:
              sortable: 0
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: 0
              responsive: ''
          default: '-1'
          empty_table: 0
          responsive: 0
          bootstrap_styles:
            striped: 0
            bordered: 0
            hover: 0
            condensed: 0
      row:
        type: fields
      fields:
        title_1:
          id: title_1
          table: node_field_data
          field: title
          relationship: none
          group_type: group
          admin_label: ''
          label: Titel
          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: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
        field_bezeichnung:
          id: field_bezeichnung
          table: paragraph__field_bezeichnung
          field: field_bezeichnung
          relationship: field_vereinsaufgaben
          group_type: group
          admin_label: ''
          label: Bezeichnung
          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: true
          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: {  }
          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
      filters:
        status:
          value: '1'
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
            operator_limit_selection: false
            operator_list: {  }
          group: 1
      sorts: {  }
      title: Team->Profile
      header: {  }
      footer: {  }
      empty: {  }
      relationships:
        field_vereinsaufgaben:
          id: field_vereinsaufgaben
          table: node__field_vereinsaufgaben
          field: field_vereinsaufgaben
          relationship: none
          group_type: group
          admin_label: 'field_vereinsaufgaben: Seitenabschnitt'
          required: true
          plugin_id: standard
        field_referenz_auf_team:
          id: field_referenz_auf_team
          table: paragraph__field_referenz_auf_team
          field: field_referenz_auf_team
          relationship: field_vereinsaufgaben
          group_type: group
          admin_label: 'field_referenz_auf_team: Inhalt'
          required: true
          plugin_id: standard
      arguments:
        nid:
          id: nid
          table: node_field_data
          field: nid
          relationship: field_referenz_auf_team
          group_type: group
          admin_label: ''
          default_action: default
          exception:
            value: all
            title_enable: false
            title: All
          title_enable: false
          title: ''
          default_argument_type: node
          default_argument_options: {  }
          default_argument_skip_url: false
          summary_options:
            base_path: ''
            count: true
            items_per_page: 25
            override: false
          summary:
            sort_order: asc
            number_of_records: 0
            format: default_summary
          specify_validation: false
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          not: false
          entity_type: node
          entity_field: nid
          plugin_id: node_nid
      display_extenders: {  }
      use_ajax: false
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.paragraph.field_bezeichnung'
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
      block_category: profil
      block_description: Team->Profile
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.paragraph.field_bezeichnung'

```
> -1 votes

---
Tags: views, paragraphs, 9
---


# Question
Title: image not linking to user during migration
I run a migration to first import images as below , it works and imports the pictures as files but when i do the user import with the snipped at the end of this post it doesnt attach the image to the user

```
id: vcd7_user_pictures
label: 'user pictures migration'
migration_group: custom
source:
  constants:
    DRUPAL_FILE_DIRECTORY: 'public://profiles/'
  plugin: vcd7_user_pictures

  ids:
    photo_id:
      type: string
process:
  psf_destination_filename:
    plugin: callback
    callable: basename
    source: photo_url
  psf_destination_full_path:
    - plugin: concat
      source:
        - constants/DRUPAL_FILE_DIRECTORY
        - '@psf_destination_filename'
    - plugin: urlencode
  psf_source_image_path:
    plugin: urlencode
    source: photo_url
  uri:
    plugin: file_copy
    source:
      - '@psf_source_image_path'
      - '@psf_destination_full_path'
    file_exists: 'rename'
    move: FALSE
    uid: uid

destination:
  plugin: 'entity:file'
migration_dependencies: {}  `

```

this is the code in my user migration

```
user_picture: # Image field name in Drupal 8 site
-
  plugin: default_value
  source: user_picture # Image field name in Drupal 7 site
  default_value: null
-
  plugin: migration_lookup
  migration: vcd7_user_pictures

```

# Answer
> -1 votes
My plugin was using user information instead of file information . instead i changed to the generic plugin for files source: plugin: d7\_file

and it worked .

---
Tags: migrations
---


# Question
Title: What's the difference between indexed and non-indexed field in Views and Search API?
I'm using Search API with a database backend and Views to build the search results page. More specifically, I'm using fields in Views. When selecting fields, I see two options for example:

* Title
* Title (indexed field)

When using this field, I get the same result. So I'm wondering why might I use the indexed version over the regular?

# Answer
> 1 votes
Simple:

* **Title** provided for Views from Content entity.
* **Title (indexed field)** provided for Views from SOLR.

For example: You have 1000 contents, and you want to show 10 of these, titles of that starts "Z" letter.

If you use `Title` as filter - Drupal will use it by Views handlers, so:

1. It will request data from SOLR server, in our case - all 1000 items.
2. The Views filter on found items, reducing it to the required 10 "Z" contents.

As you see - *it's not good for performance*. Better is using `Title (indexed field)`as Views filter, that will request only required **10 records** from SOLR server.

p.s. Against it, `title` will prefer for Views output than indexed field (*for some cases*).

---
Tags: views, entities, search
---


# Question
Title: Can't update via composer because of lock file
I am trying to install Lightning 8.1.0. I am currently at 8.1.00-rc5. When I run `composer require drupal/lightning:8.1.0` I get the following response:

```
± |master ✓| → composer require drupal/lightning:8.1.0
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
    1/1:  http://packagist.org/p/provider-latest$aa4f1da6acef0b15640bc1cace21327f5342dbb88c61b4605f0b1b0ff21d7399.json
    Finished: success: 1, skipped: 0, failure: 0, total: 1
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: drupal/entity_browser[8.1.x-dev, 8.1.0-alpha3].
    - Can only install one of: drupal/entity_browser[8.1.0-alpha3, 8.1.x-dev].
    - drupal/lightning 8.1.00 requires drupal/entity_browser 8.1.0-alpha3 -> satisfiable by drupal/entity_browser[8.1.0-alpha3].
    - Installation request for drupal/lightning 8.1.0 -> satisfiable by drupal/lightning[8.1.00].
    - Installation request for drupal/entity_browser (locked at 8.1.x-dev) -> satisfiable by drupal/entity_browser[8.1.x-dev].

Installation failed, reverting ./composer.json to its original content.

```

The only way I get around this is that I have to remove the composer.lock file before I run `composer require drupal/lightning:8.1.0`. Does this sound like the right way to do it?

# Answer
> 3 votes
The way I updated is I manually updated composer and set Lightning to 8.1.0 and then ran `composer update drupal/lightning`.

# Answer
> 3 votes
If you're dealing with a top level dependency, you can remove the old version and then install the new version:

```
composer remove drupal/lightning
composer require drupal/lightning:8.1.0

```

# Answer
> 0 votes
I had a similar case due to security reasons on a GitHub repository.

I solved updating the dependency to a specific version like this:

```
composer require phpseclib/phpseclib:2.0.31

```

If you are working with virtual environments like docker containers (ddev, lando, etc..) before running it you should connect to the container with a:

```
ddev ssh

```

---
Tags: 8, composer
---


# Question
Title: Unable to edit custom block without administrator permissions
I created a content type "landingpage" and a user role "editor". I enabled layout builder for this content type and enabled the option to overwrite the the layout for individual pages.

As Admin I can easily add custom blocks to the layout and afterwards I\*m able to edit those blocks oder delete them.

As Editor, however, though I a am able to add custom blocks, I neither can edit my own blocks nor am I able to remove them.

I granted the editor role following permissions:

* Admin blocks
* Custom block: Manage display
* Content - Landing page: Configure layout overrides for content that the user can edit.
* Create and edit custom blocks
* Manage Layout Builder Modal

Im using Drupal 8.9.14

Has anyone an idea to solve my problem?

# Answer
> 1 votes
To edit the blocks in layout builder, the user needs to have permission to use contextual links.

---
Tags: blocks, layout-builder
---


# Question
Title: How to store Views templates with a module instead of a theme
I have created several views templates that are currently stored in my active themes directory. In would prefer these templates be stored within my module directory.

My question is, how can I bring these theme files (views-view-field.tpl.php for example.) into my modules directory and have them be seen by Views?

Looking at the Views modules, I can see that default templates are stored in views/theme, but I don't see how it has been implemented.

# Answer
This took me a while to figure out as well. The following code should be placed in your .module file (the code assumes your module is called "NAME")

```
/**
* Implements hook_views_api().
*
* Enabling using templates inside module
*/
function NAME_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'NAME'),
    'template path' => drupal_get_path('module', 'NAME'),
  );
}

```

This will tell Views to look in the root directory of your module. I personally am a fan of adding a subdirectory to the module to hold template files. To do this append the directory name to the end of the template path, eg:

```
'template path' => drupal_get_path('module', 'NAME') . '/templates',

```
> 29 votes

# Answer
Another approach is to define the template using 'hook\_theme', as this article describes: http://grayside.org/2010/09/how-override-views-field-template-module
> 3 votes

# Answer
If the above examples will not work in **Drupal 8** try this:

```
/**
 * Implements hook_theme().
 */
function MODULENAME_theme($existing, $type, $theme, $path) {
  return [
    'views_view_grid__dashboard__page_1' => [
      'template' => 'views-view-grid--dashboard--page-1',
      'base hook' => 'views',
    ],
  ];
}

```

**OR**

```
/**
 * Implements hook_theme_registry_alter().
 */
function MODULENAME_theme_registry_alter(&$theme_registry) {
  // Override view template in module, not in the theme
  $theme = \Drupal::theme()->getActiveTheme()->getName();
  if ($theme == 'adminimal_theme') {
    $theme_registry['views_view_grid']['path'] = drupal_get_path('module', 'MODULENAME') . '/templates';
  }
}

```

But note that MODULENAME\_theme\_registry\_alter works only once after cache clear and can not be usable in some places

**views\_view\_grid** is the template name in your templates folder
> 2 votes

---
Tags: views, theming
---


# Question
Title: How to add an article to a page automatically
What I want to do is to add the title and the body of an article I create on my homepage just as you would do it for a news. I've been trying to make this work but I can't find a way to do it without having to remember the path and then manually creating a block.

# Answer
> 0 votes
A couple of ways to do this based on your requirements.

1. Display multiple articles on your homepage

As @leymanxx mentioned create a view with a page display then set the path of the page you created as your default front page.

2. Display a single article on the homepage

Create an article and set that's article path as your default front page.

You can read more here

---
Tags: views, nodes
---


# Question
Title: Drush out of memory when php memory limit is 1024M on my dedicate server. (CentOS)
This happened when I restarted Apache because my site was down. Normally restarting Apache or other service doesn't break Drush, but today it happened.

I'm sure on my server my php.ini has memory limit set to 1024M, this is my own dedicate server, and the Drupal installation runs well, I check the status report on Drupal (admin/reports/status), the PHP memory limit is set to 1024M.

This happened on my Drupal sites on my server.

When I...

```
[root: sites]# drush st

```

I got

```
Drush command terminated abnormally due to an unrecoverable error.       [error]
Error: Out of memory (allocated 10485760) (tried to allocate 122880
bytes) in /home/mywebsite/public_html/modules/system/system.module, line 1336

```

I also tried...

```
[root: sites]#  php -i | grep memory_limit

```

And I got

```
memory_limit 1024M

```

Is there anyone has some ideas?

My Server:

* CENTOS 5.9 x86\_64
* WHM 11.36.0 (build 14)
* PHP 5.2.17
* Drush 5.8

I've tried `drush status --debug` and it gave me :

> Bootstrap to phase 0. \[0 sec, 3.02 MB\]
> \[bootstrap\] Drush bootstrap phase : \_drush\_bootstrap\_drush() \[0.01 sec, 3.23 MB\] \[bootstrap\] Cache HIT cid: 5.8-commandfiles-0-15880291c3f5c759ee66bf106fd77cbd \[0.01 sec, 3.24 MB\] \[debug\] Bootstrap to phase 0. \[0.04 sec, 7.43 MB\]
> \[bootstrap\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_root() \[0.05 sec, 7.49 MB\] \[bootstrap\] Drush command terminated abnormally due to an unrecoverable error.
> \[error\] Error: Out of memory (allocated 10485760) (tried to allocate 122880 bytes) in /home/mywebsite/public\_html/modules/system/system.module, line 1336 \[0.06 sec, 9.28 MB\]

# Answer
> 2 votes
Your particular setup might be one that (deliberately) has 2 php.ini files:

1. for Apache, e.g. on your server at: `/etc/php5/apache2/php.ini` (or similar path depending on your distro)
2. for command line (i.e. for drush) e.g. on your server at: `/etc/php5/cli/php.ini` (or similar path depending on your distro)

(I believe that this is perfectly normal kind of setup to have 2 files, I have this myself.)

You need to ensure that `memory_limit` is `1024M` is set for `/etc/php5/cli/php.ini`(or similar path depending on your distro) php executed in the command line/terminal/console i.e. drush. You could also try `memory_limit` is `-1` which allows the server to allocate as much memory as is available.

# Answer
> 0 votes
Had a quite similar case here:

CLI PHP had memory\_limit = -1

```
$ php -r 'print ini_get("memory_limit") . "\n";'
-1

```

But drush only knows of 128MB

```
$ drush php-eval 'print ini_get("memory_limit") . "\n";'
128M

```

BUT that was my global drush

```
which drush
/users/bernhard/.composer/vendor/bin/drush

```

Again with the local drush in the current project:

```
$ ./vendor/bin/drush php-eval 'print ini_get("memory_limit") . "\n";'
-1

```

Turned out that the global drush (installed with composer) was in my home folder and in my home folder I had a .phpversion file specifying another php-version for phpenv than in my project dir. So drush used this version with another memory\_limt setup:

```
$ php -v
PHP 7.4.16 (cli) (built: Mar  4 2021 20:49:25) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.16, Copyright (c), by Zend Technologies
    with Xdebug v2.8.0, Copyright (c) 2002-2019, by Derick Rethans

$ drush php-eval 'print phpversion() . "\n";'
7.3.27

```

Hope this gives you the tools at hand to find out where things go wrong :-)

---
Tags: drush
---


# Question
Title: How to add an autocomplete field with pure javascript
I'm implementing the javascript library Annotorious which allow to add annotations on an image. My goal is to be able to link content with part of the image select with Annotorious. When we select a zone, Annotorious open a form we can personalize to add information we want link with the zone. In my case, I added a fieldtext but I want it uses the autocomplete but I don't know how to activate this behavior.

Regarding the code in core/lib/Drupal/Core/Render/Element/FormElement.php, the form element add the class 'form-autocomplete' and the attributes 'data-autocomplete-path' equals to the url of an autocomplete function on his input and inject the library core/drupal.autocomplete. Regarding this, I tried to reproduce the same behavior. But I guess something is missing because my field doesn't query my endpoint when I typed in it but I don't know why. I was also thinking this maybe doesn't work because it's add by javascript after the loading of the page but in this case, I don't know how to solve this problem.

Here my code:

My widget field:

```
class ImagePinWidget extends ImageWidget {

  public static function process($element, FormStateInterface $form_state, $form) {
    $element = parent::process($element, $form_state, $form);

    $element['preview']['#attributes'] = array('id' => array('my-image'));

    $element['#attached']['library'][] = 'my_module/image-pin';
    $element['#theme'] = 'image_pin_widget';

    return $element;
  }

}

```

My my\_module.libraries.yml

```
recogito-annotorious:
  version: 1.x
  css:
    component:
      /libraries/annotorious/annotorious.min.css: { minified: true }
  js:
    /libraries/annotorious/annotorious.min.js: { minified: true }

annotorious-toolbar:
  version: 1.x
  js:
    https://cdn.jsdelivr.net/npm/@recogito/annotorious-toolbar@latest/dist/annotorious-toolbar.min.js: { type: external, minified: true }

image-pin:
  version: 1.0.0
  css:
    component:
      css/image-pin.css: {}
  js:
    js/image_pin.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings
    - my_module/recogito-annotorious
    - core/drupal.autocomplete
    - my_module/annotorious-toolbar

```

image\_pin.js:

```
(function ($, Drupal, drupalSettings, Annotorious) {

  'use strict';

  Drupal.behaviors.redacto_form_image_pin = {
    attach: function (context) {
      var config = {
        image:'my-image',
        widgets: [
          Drupal.behaviors.my_module_image_pin.nodeSelectorWidget,
        ],
      };

      var anno = Annotorious.init(config);

      Annotorious.Toolbar(anno, document.getElementById('toolbar'));
    },

    /**
     * Dynamic behavior when the status changes.
     *
     * @param $status
     */
    nodeSelectorWidget: function (args) {

      // Adding the autocomplete field
      var createField = function() {
        var input = document.createElement('input');

        input.classList.add('form-autocomplete');
        input.setAttribute('data-autocomplete-path', '/fr/autocomplete/custom');

        return input;
      }

      var container = document.createElement('div');
      container.className = 'nodeselector-widget';

      container.appendChild(createField());

      return container;

    }

  };

})(jQuery, Drupal, drupalSettings, Annotorious);

```

I precise the path /fr/autocomplete/insects return correctly a json list of content and autocomplete create in a usual form works correctly with it. Example of autocomplete I do in an usual drupal form with this custom autocomplete:

```
$element['test_autocomplete'] = [
     '#type' => 'textfield',
     '#title' => t('Autocomplete Articles'),
     '#autocomplete_route_name' => 'my_module.custom_autocomplete',
   ];

```

# Answer
Thanks to Clive for his help ! To active the autocomplete, I should re-attach the autocomplete behavior after added my new element.

```
nodeSelectorWidget: function (args) {

      // Adding the autocomplete field
      var createField = function() {
        var input = document.createElement('input');

        input.classList.add('form-autocomplete');
        input.setAttribute('data-autocomplete-path', '/fr/autocomplete/custom');

        return input;
      }

      var container = document.createElement('div');
      container.className = 'nodeselector-widget';

      container.appendChild(createField());

      // Re-attach autocomplete behavior to active the autocomplete on the added input
      Drupal.behaviors.autocomplete.attach(container);

      return container;

    }

```
> 4 votes

---
Tags: 8, javascript, ajax
---


title: How can I find the form ID of a form?

text:
# Question
Title: How can I find the form ID of a form?
How do I get the form id of my form? I've just begun to make my modules and I'm at a standstill. I got this code from someone else and am trying to customize it:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form id for the node form') {
    $form['#submit'][] = 'my_custom_submit_handler';
  }
}

```

# Answer
> 18 votes
Try printing the form variables with PHP function print\_r.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  print_r($form);
}

```

When you visit the page the form is on, the variables (and name) will be displayed.

An easier way of accessing (or rather viewing) the information would be using dpm() function provided by the Devel module. You can use it in the same way you would use print\_r.

# Answer
> 42 votes
## Finding FORM ID without installing module

**Finding the Form ID is very easy** **no need to install modules** and all

**STEP 1:** Open you from go to its edit page(OR inspect your form).

**STEP 2:** if its a **node form** find "**node-form**" in the inspect element

check you are in the **form** element.

**STEP 3:** see attached image the **highlighted green** text is the ID of the form

**STEP 4: IMPORTANT** Finally if you want to use it in `hook_form_alter()` replace the **hypen** with **underscore**

For example: `yourform_id_with_content_type_name_form`

Like wise you can find id of any form in drupal all you have to do is inspect-\>find form element and search for the ID attribute and use it

Hope it helps :)

# Answer
> 10 votes
If your webform is located at "www.mydomain.com/node/351" then your form ID will be "webform\_client\_form\_351". So, whatever your nid is - that's your form ID.

# Answer
> 6 votes
If you know where the code is that defines the form you want to alter, look there. The form id is just the name of the function defining that form.

For example, Views defines the function views\_ui\_edit\_view\_form on line 875 of views/includes/admin.inc. The Hierarchical Select views filter looks for that form id on line 50 of hierarchical\_select/modules/hs\_taxonomy\_views.module in a hood\_form\_alter function.

# Answer
> 5 votes
Use `drupal_set_message()` function to display the form id.

```
function hook_form_alter(&$form, $form_state, $form_id) {
drupal_set_message($form_id);
// other codes
}

```

# Answer
> 4 votes
Use the Get Form ID module to easily find out form id of any form in Drupal.

Here is a quote about it from its project page:

> By hovering over any form you will see a contextual link available. By expanding the link you will see the form ID. Click on the link and you will see a modal window with copyable form id and hook\_form\_FORM\_ID\_alter() hook suggestion.
>
> This module is deprecated. It was improved, extended and rebranded as Devel form debug; use it instead.

Disclosure: I'm maintainer of these modules.

# Answer
> 3 votes
As the code you reported is looking for the form ID of the node form, there are two cases.

### Drupal 6

If the code is trying to alter the form used to set the settings for a content type, then it should use the following IF-statement.

```
if ($form_id == 'node_type_form' && isset($form['identity']['type'])) { /* … */ }

```

If the code is trying to alter the node edit form, then the code should use the following IF-statement.

```
if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) { /* … */ }

```

### Drupal 7 and higher

In the first case, the IF-statement should be the following one:

```
if ($form_id == 'node_type_form') { /* … */ }

```

Using a different approach, supposing that mymodule is the short name of your module, you could use `mymodule_form_node_type_form_alter(&$form, &$form_state, $form_id)`. Since Drupal 7, all the hooks used to alter the form implemented by another module gets `$form_id` as last parameter. See hook\_form\_alter(), hook\_form\_FORM\_ID\_alter(), hook\_form\_BASE\_FORM\_ID\_alter().

In the second case, the IF-statement is the same used for Drupal 6.

```
if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) { /* … */ }

```

# Answer
> 2 votes
First install Devel module.Then create a module like the code below

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}

```

Then you can see ALL details of a form, like form ID, field names of a form etc.

# Answer
> 0 votes
In Drupal 8 you can get a form id like this. You have to write this code in your `.module` file

```
function modulename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  echo "my form id is : ".$form_id;
}

```

---
Tags: forms
---


title: Control number of autocomplete results

text:
# Question
Title: Control number of autocomplete results
Is there any way to control number of results in an autocomplete field?

Usually node reference autocomplete fields provide 10 results. I want to increase that number.

Is there any global configuration available? How can I alter that number?

# Answer
You will have to make a custom module to alter the result of autocomplete coming from node reference module. This example(taken from here) is for 20 result, you can increase/decrease according to your need.

```
function MYMODULE_menu_alter(&$menu) {
  if (isset($menu['nodereference/autocomplete'])) {
    $menu['nodereference/autocomplete']['page callback'] = 'MYMODULE_nodereference_autocomplete';
  }
}
function MYMODULE_nodereference_autocomplete($field_name, $string = '') {
  $fields = content_fields();
  $field = $fields[$field_name];
  $match = isset($field['widget']['autocomplete_match']) ? $field['widget']['autocomplete_match'] : 'contains';
  $matches = array();
  $references = _nodereference_potential_references($field, $string, $match, array(), 20);
  foreach ($references as $id => $row) {
    // Add a class wrapper for a few required CSS overrides.
    $matches[$row['title'] ." [nid:$id]"] = '<div class="reference-autocomplete">'. $row['rendered'] . '</div>';
  }
  drupal_json($matches);
}

```
> 4 votes

# Answer
In Drupal 8 you can configure the autocomplete limit `match_limit` directly in the field settings. This works fine for `select2_entity_reference` fields.

If you cannot modify the field settings because there are already data, export the field configuration with `drush cex`, modify the `match_limit` and import the modified config with `drush cim`.

(For url link fields, a different approach is needed: How to display more than 10 items in link widget autocomplete?)
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: "Drupal root not found. Pass --root or a @siteAlias in order to see Drupal-specific commands"
I have multiple sites inside the same htdocs directory. In one, I removed all the folders except vendor under Web. Now drush will not work (it worked before I moved the folders). But now, it cannot find the database, which is correctly defined in web/sites/default/settings.php

```
/srv/www/htdocs/jar/drupal # ./drush status
 PHP binary    : /usr/bin/php
 PHP config    : /srv/www/php.ini
 PHP OS        : Linux
 Drush script  : /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush
 Drush version : 10.3.6
 Drush temp    : /tmp
 Drush configs : /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush.yml
 Drupal root   : /srv/www/htdocs/jar/drupal

```

I am running Drupal 9.0.8 and drush 10.3.6 (in /srv/www/htdocs/jar/drupal). I have removed drush using composer (2.0.3) and reinstalled it (recreating vendor in the process).

```
/srv/www/htdocs/jar/drupal # ./drush -vvv cr
 [preflight] Config paths: /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush.yml
 [preflight] Alias paths: /srv/www/htdocs/jar/drupal/drush/sites,/srv/www/htdocs/jar/drush/sites
 [preflight] Commandfile search paths: /srv/www/htdocs/jar/drupal/vendor/drush/drush/src
 [debug] Starting bootstrap to site [0.04 sec, 8.17 MB]

In BootstrapHook.php line 32:
  [Exception]
  Bootstrap failed. Run your command with -vvv for more information.
Exception trace:
  at /srv/www/htdocs/jar/drupal/vendor/drush/drush/src/Boot/BootstrapHook.php:32
 Drush\Boot\BootstrapHook->initialize() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/Hooks/Dispatchers/InitializeHookDispatcher.php:44
 Consolidation\AnnotatedCommand\Hooks\Dispatchers\InitializeHookDispatcher->doInitializeHook() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/Hooks/Dispatchers/InitializeHookDispatcher.php:36
 Consolidation\AnnotatedCommand\Hooks\Dispatchers\InitializeHookDispatcher->callInitializeHook() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/Hooks/Dispatchers/InitializeHookDispatcher.php:29
 Consolidation\AnnotatedCommand\Hooks\Dispatchers\InitializeHookDispatcher->initialize() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/CommandProcessor.php:145
 Consolidation\AnnotatedCommand\CommandProcessor->initializeHook() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/AnnotatedCommand.php:296
 Consolidation\AnnotatedCommand\AnnotatedCommand->initialize() at /srv/www/htdocs/jar/drupal/vendor/symfony/console/Command/Command.php:221
 Symfony\Component\Console\Command\Command->run() at /srv/www/htdocs/jar/drupal/vendor/symfony/console/Application.php:1018
 Symfony\Component\Console\Application->doRunCommand() at /srv/www/htdocs/jar/drupal/vendor/symfony/console/Application.php:271
 Symfony\Component\Console\Application->doRun() at /srv/www/htdocs/jar/drupal/vendor/symfony/console/Application.php:147
 Symfony\Component\Console\Application->run() at /srv/www/htdocs/jar/drupal/vendor/drush/drush/src/Runtime/Runtime.php:118
 Drush\Runtime\Runtime->doRun() at /srv/www/htdocs/jar/drupal/vendor/drush/drush/src/Runtime/Runtime.php:49
 Drush\Runtime\Runtime->run() at /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush.php:72
 require() at /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush:4

```

I looked at all the above suggestions, but am stuck. Drush works perfectly on my other 5 sites...

# Answer
> 0 votes
A missing composer.json file was the solution for me.

---
Tags: drush
---


# Question
Title: Allow to filter (in a view) on a datetime field of a custom entity
I have created a custom entity as follow:

Here is an extract of my entity definition in `modules/custom/bank_operation/src/Entity/BankOperation.php`

**Notes**:

1- As you can see, I have changed the value of the `views_data` key

2- The `operation_date` base field have the `datetime` type

```
 * @ContentEntityType(
 *   id = "bank_operation",

 ...

 *     "views_data" = "Drupal\bank_operation\BankOperationViewsData",

 ...

class BankOperation extends ContentEntityBase implements BankOperationInterface {

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    ...

    $fields['operation_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t("Operation date"))
      ->setRequired(TRUE)
      ->setSettings([
        'datetime_type' => DateTimeItem::DATETIME_TYPE_DATE,
      ])

    ...
}

```

Here is an extract of my overrode EntityViewsData in `modules/custom/bank_operation/src/BankOperationViewsData.php`

This class is used according to the value of the `views_data` key. This is my attempt to allow a view to filter on the `operation_date` field

```
class BankOperationViewsData extends EntityViewsData {

  public function getViewsData() {
    $data = parent::getViewsData();
    $data['bank_operation']['operation_date']['filter'] = [
      'id' => 'datetime',
      'field' => 'operation_date',
      'table' => 'bank_operation',
      'field_name' => 'operation_date',
      'entity_type' => 'bank_operation',
    ];
    return $data;
  }

}

```

After that, I have created a view to display my `BankOperation` entities with an exposed filter on the `operation_date` field.

Here is the error produced when using this filter (I don't understand why `ViewsYearFilterDatetime` is called)

```
Exception: DateTime object not set. in Drupal\Component\Datetime\DateTimePlus->__call() (line 360 of core/lib/Drupal/Component/Datetime/DateTimePlus.php).

Drupal\datetime\Plugin\views\filter\Date->opSimple() (Line: 63)
Drupal\views_year_filter\Plugin\views\filter\ViewsYearFilterDatetime->opSimple() (Line: 330)
Drupal\views\Plugin\views\filter\NumericFilter->query() (Line: 1373)
Drupal\views\ViewExecutable->_build() (Line: 1262)
Drupal\views\ViewExecutable->build() (Line: 390)
Drupal\views\Plugin\views\display\PathPluginBase->execute() (Line: 180)
Drupal\views\Plugin\views\display\Page->execute() (Line: 1630)
Drupal\views\ViewExecutable->executeDisplay() (Line: 77)

```

I know that there are other questions like this one, but none of them are providing a detailed answer (only links).

I have setup my question to allow people who are facing the same issue to quickly find a path to solve it.

# Answer
As there are so many difficulties with base fields (sorting, displaying, filter etc in views), I decided to remove all of them and I re-created them back in the field UI.

To allow this, I set `fieldable = TRUE,` and `field_ui_base_route = some_path` in the annotations of my entity. This is of course poor design because each field will create a table on its own but I had no time to spend on this...

Feel free to provide a better answer... I think we need a real how-to to provide the same functionalities we have for fields created in UI then for base fields

Edit to add: I have created an issue to create an help item on this topic: https://www.drupal.org/project/drupal/issues/3213021
> 0 votes

---
Tags: views, entities
---


# Question
Title: How to get product name by id from commerce order?
How to get product name by id? I want send mail with product name to customer after confirm commerce order.

# Answer
A product is an entity, so you can use `entity_load()`.

```
$product = entity_load('commerce_product', $product_id);
$title = $product->title;

```

Commerce provides its own shortcut, though:

```
$product = commerce_product_load($product_id);
$title = $product->title;

```
> 3 votes

# Answer
The `entity_load()` is deprecated since 8.0.0. For Drupal 9 use:

```
// Several product ids to load.
$product_id_to_load = [34, 342, 567];

if (count($product_id_to_load) > 0) {
    $entity_manager = \Drupal::entityTypeManager();
    $products = $entity_manager->getStorage('commerce_product')->loadMultiple($product_id_to_load);
    foreach ($products as $product) {
        $titles[$product->product_id->value] = $product->get('title')->value;
    }
}

```
> 3 votes

---
Tags: commerce
---


# Question
Title: Get taxonomy field value in forum-list.html.twig
I am customizing the appearance of the forums.

I added all my forums and container. Additionally, I added a custom taxonomy field I need to show for each forum category.

>

How can I show the custom taxonomy field in forum-list.html.twig?

I know how to show content fields from nodes in node.html.twig, but how do I show custom taxonomy fields in forum-list.html.twig?

# Answer
Your question is very vague.

I suggest setting up xdebug (https://www.drupal.org/docs/develop/development-tools/xdebug-debugger) then using the function `devel_breakpoint()` to be able to see how to reach the values/fields of your entity.

If your taxonomy is attached to your topic, I'm assuming that the solution will be something like `forum.taxonomy_field.value`.

If your taxonomy is not attached to your topic, you should have a look to preprocess your topic to add the missing data by using `template_preprocess_forum_list()` I guess?

Here is the list of all preprocess hook, maybe another one with forum might do the trick: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/implementations/hook\_preprocess\_HOOK/8.2.x
> 0 votes

---
Tags: theming, nodes, 9
---


# Question
Title: How to debug and find variables on twig themes
I'm trying to create a theme for a drupal web site, but I find it difficult to get variables. Here is an example: to get an image form a view I wrote this line

```
row.content['#row']._entity.field_image.entity.uri.value

```

How can we define this path ? even with **vardumper** and **dump** it's not possible to get this information!! Is there any effective way to determine how variables are structred ?

# Answer
> 0 votes
The best way to debug a twig file is to use xdebug then `{{ devel_breakpoint() }}`

Here is how to install it: https://www.drupal.org/docs/develop/development-tools/xdebug-debugger.

Once you figured how to reach your variable using the debugger in PHP syntax, you just need to translate the arrows or get method to twig. It takes a bit of practice, but helps to reach your variable with ease.

But in your particular case, I think using what Views provides as formatter seems to be a better approach.

---
Tags: views, theming
---


title: Filter content type by media type

text:
# Question
Title: Filter content type by media type
I have a content type that has a media field that can contain audio, video or image, I created a view and I want to filter the view depending on the media type is that possible using Drupal views or do I need to make custom code for this

# Answer
> 0 votes
You can add more info about the referenced Media in your content Views through a Relationship for that Media field.

Add the Relationship (under Advanced Views settings) called something like **Media referenced from field\_mixed\_media** under the `Content` Category.

You can Require it if you only want to see nodes that have that Field filled in (not empty).

Once you add that Relationship you will see more options when adding new Fields and Filters.

In your case you'll want to add the Filter **Media type** from the `Media` Category, it will use the Relationship by default, and Expose it.

The Exposed filter will show as a drop-down select list. If you want it display as checkboxes you can use the Better Exposed Filters module.

---
Tags: views, media
---


# Question
Title: How to get a view result programmatically without exposed filters respected
I have some views of display page which I do not want to show to public if there would not be any result when accessed without any exposed filters set. I have a custom views access plugin and a custom access checking class which can handle the access granting.

My idea so far is that I would like to run the view a first time during access checking without exposed filters. In this way I could find out if the view would ever deliver any results. I tried it in the following way:

```
  $view = Views::getView($view_id);
  $view->setDisplay($display_id);
  $view->setArguments([$politician_id]);
  $view->execute();
  $result = $view->total_rows;

```

The problem is: as soon as an user comes to this page with query parameters in the url set by exposed filters these exposed filters are used for this view query as well. I did not find any way to tell the class in $view to execute without exposed filters. I even tried to set these exposed filters data in the following ways but even then the filter data in the query parameters is still used to filter the result set:

```
  $view = Views::getView($view_id);
  $view->setDisplay($display_id);
  $view->setArguments([$politician_id]);
  $view->initDisplay();
  $view->initHandlers();
  $view->setExposedInput([]);
  $view->exposed_data = [];
  $view->exposed_raw_input = [];
  $view->execute();
  $result = $view->total_rows;

```

I want to achieve that in this way because I want to use this logic for several views. It would be so smart to simply re-use the arguments and filters set in the views instead of hardcoding a new custom database query as the settings in the views might change. I hope someone can help me.

# Answer
> 3 votes
Thanks to 4k4 (see comments). The solution is to set some dummy exposed filter data:

```
  $view = Views::getView($view_id);
  $view->setDisplay($display_id);
  $view->setArguments([$politician_id]);
  $view->setExposedInput([
    'dummy' => ''
  ]);
  $view->execute();
  $result = $view->total_rows;

```

In this way it works.

---
Tags: 8, views
---


title: How to remove comments from all nodes

text:
# Question
Title: How to remove comments from all nodes
I want to remove the comment section from all my articles. Can this be done with an sql query or something so I don't have to do it manually by setting comments to disabled ?

# Answer
Delete the comment fields from the Article content type and uninstall the Comment module.
> 1 votes

---
Tags: comments
---


# Question
Title: How can I print the translated entity title in a template?
I have a reference field for nodes and I have a field template to render the the fields.

```
{{ item.entity.title.value }}

```

But I can't get the translated title of the node.

Can someone help?

# Answer
> 3 votes
If you configure the reference field to display the entity title it should be translated automatically, as @leymannx commented. But if you get the title from the entity directly you have to make sure the entity is in the correct language. If you don't want to use PHP you can do this with the help of Twig Tweak:

```
{{ item.entity|translation.title.value }}

```

See https://git.drupalcode.org/project/twig\_tweak/-/blob/3.x/docs/cheat-sheet.md#entity-translation

---
Tags: 8, theming
---


# Question
Title: How to create a view of Media images that do not have any Alt Text
For accessibility purposes I want to create a view of Media images that do not have any Alt Text.

Creating a view of Media images and also displaying Alt Text is not difficult, as explained is this d.o post Media alt text not available in Views

However I do not know of a way to create a filter of 'Alt Text is NULL' so that a view can be built which only returns images without alt text.

Any suggestions for how could this be accomplished? Ideally this would be a view of media entities so that other filters relating to media can also be used.

# Answer
There is the Filter called `Thumbnail (alt)` from the Media Category that is for the Alt text.

After you add the Relationship for the Image field the `Is empty (NULL)` Operator will become available. If the Relationship is not present only the string operators will be listed.

Add the Relationship `image from field_media_image` and then add the `Thumbnail (alt)` Filter with the `Is empty (NULL)` Operator.

It will filter out Media items that have the Alt field available in their structure but not filled in (empty), for example images, as opposed to Files that don't come with Alt fields in their structure.

---

On the other hand, using the `Is less than 1` Operator/value combination can help in situations when you need to filter out different Media types to show the items that don't have the Alt field in their structure at all like File types, while Images with empty alt don't satisfy that condition.
> 2 votes

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


# Question
Title: When doing a page preprocess, how do you know if the page is a form?
When doing a preprocess on a page (I need to conditionally change something at the page template level) is there a way to tell if the page is going to render a form? The xdebug output didn't show any variables that would tell me this in an obvious way.

# Answer
Since I wanted to apply a change to the page.html.twig template based on if it was a form, I looked first for the form suggestions I was given. Since I couldn't find a way to generically apply a template to all forms, I instead created a template that I would then tell all of the forms that I have to use this template. I used a hook\_theme\_suggestions\_HOOK\_alter to add my new template and check the existing suggestions to see if the forms I want to use are part of the current suggestions:

```
function listed_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  $forms = [
    'page__user__register',
    'page__admin__people',
  ];
  foreach ($forms as $form) {
    if (in_array($form, $suggestions)) {
      $suggestions[] = 'page__forms';
    }
  }
}

```

From here, I can add additional forms as they are needed to use this single template. So, this solution doesn't exactly answer my original question, but it solves my original problem.
> 0 votes

---
Tags: theming, forms
---


# Question
Title: How do I set up an article view that validates both article and category?
I'm working with Drupal 7, and trying to get a view set up that will display blog categories and articles based on their category.

The category is a Taxonomy - Blog Categories - let's assume it's:

* rock-and-roll
* pop
* jazz
* other

I'm hoping for the following path behavior:

1. `/blog/` should list all articles.
2. `/blog/rock-and-roll/` should list articles that have the rock-and-roll taxonomy set.
3. `/blog/non-existant-term/` should show page not found
4. `/blog/rock-and-roll/real-article-title` should show the relevant article
5. `/blog/rock-and-roll/fake-article-title` should show page not found

I've tried a ton of different combinations of relationships and contextual filters, but I just can't get it to work. The closest I can get is where all of the 'proper' urls work... I get category lists, or I get article displays... but I also still get a page when I go to a path with either an invalid taxonomy term or an invalid article name.

It seems like it should be something with the Contextual Filter validation stuff... but anything I've tried with like validation based on a taxonomy or whatever just stops anything from working. I no longer get listings or articles properly.

I'm not sure what other information to include - I'm trying to avoid adding any modules (because I've basically been told not to) and I'm trying to avoid making it multiple views.

-------- EDIT --------

I've tried some of the stuff suggested by prkos but I'm not having any more success. I've attached some screenshots of my configs... with a little bit of censored stuff. It probably doesn't matter, but I'm expected to be circumspect. The original URL/Taxonomy I used isn't actually the final stuff, it was just example... so there might be some mismatch there.

So, with these changes in place... now if I go to url/news2/ I get a Page not found. url/news2/all seems to work, but then url/news2/validterm doesn't work. validterm doesn't get any results in the view preview thing either... where it did before.

# Answer
You *can* make the Validation through the Contextual filter.

When dealing with 2 Contextual filters it's always best to first fully configure each independently, make sure they work before you add both to work together.

1. First create the Category Contextual. Since you want to use term names, and not term IDs (only term IDs are stored in ER fields), you have to add the Relationship first for the ER field (require it if you want to show only the results that have this field filled in).
2. Once you add the Relationship you can add the Term **Name** Contextual fiter, it will use the Relationship, and configure it:
`When the filter value is NOT available`
**Provide default value**
**Taxonomy term ID from URL**
**Load default filter from node page, that's good for related taxonomy blocks**
**Limit terms by vocabulary**
**Category**
**Filter to items that share any term**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term name**
**Category**
**Transform dashes in URL to spaces in term name filter values**
**Action to take if filter value does not validate**
**Hide view**

Adjust the `Case` options, and any other option to your needs.
3. Test that it's working by entering a name of your category into the View **Preview** field `jazz` and checking the results only show nodes with that term. (Preview only tests that Views filtering is working correctly, but it doesn't test passing of the argument to Views because you're feeding them manually, that needs to be tested on a live page.)

Test single word categories first, if they work test complex ones with dashes and adjust the settings if necessary until you get the desired result.

Test that you can bypass it by entering `all` into Preview, it should show all Views results (you can change it to something else in Contextual settings).

Entering a wrong word (`notmycategory`) should display `No query was run` in Views, which means you would get Page not found in live conditions.
4. Now create the second Contextual, for the Title. You don't have to remove the first one to test the second one without interference.

Bypass the first filter by always entering the `all` as the first argument into Preview. Once you add the second Contextual you will have to enter two arguments into Preview to test it (`all/some-title`, or `jazz/all`, or `all/all` to bypass both contextual filters).

`When the filter value is NOT available`
**Provide default value**
**Raw value from URL**
**3**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Basic validation**
**Action to take if filter value does not validate**
**Show "Page not found"**

Adjust the `Case` and other options to your needs.
5. Test the second Contextual by entering various titles in your appropriate Case in Preview: `all/my-title` and entering the wrong title `all/notmytitle` to get the "No query was run".
6. Test that the two Contextual filters are working together, although if they work on their own there shouldn't be any problems combining them (`jazz/some-title`, `notcategory/title`, `jazz/not-title`, etc.)
7. Once it's working in Views Preview, test everything on the live page to make sure arguments are passed through correctly.

Once all this is said, if all you need is path control in your site you can do that with Pathauto module to create aliases for your nodes based on categories and their titles.

Views only creates lists of content, it doesn't affect the core paths. You will still have the `node/ID` paths active on your system, and any path aliases you might have. You should take care not to create duplicate paths for the same content, as it can be considered duplicate content by search engines (it dilutes in any case), and it's confusing to users.
> 1 votes

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


# Question
Title: I can't unverify the new owner on Google Search Console
I received a notification about a new owner into search Console. I have tried to un-verify the new owner who has been verified via meta tags. I have cleaned the website, but I can still see the meta tag, but I can't find it looking at the source code of the page.

Your help will be highly appreciated.

# Answer
I checked all my files; then I found some weird code on includes/boostrap.inc which apparently was setting the meta tag to verify the owner. After I removed that code, I was able to un-verify that owner.
> 1 votes

---
Tags: 7, meta-tags
---


# Question
Title: How do I use the mail manager without the $to value?
I want to send an email for multiple users without a *to* address. Setting `$to` `NULL`, and empty string `'undisclosed-recipients:;'` doesn't work.

How can I send an email with just BCC recipients?

# Answer
I would suggest that you avoid this approach as messages with lots of recipients in the bcc field are more likely to trigger spam filters on the receiving mail server.

I would loop through each email address and send them a separate email instead, if there are a lot of emails to send then consider moving them into a batch operation.
> 1 votes

---
Tags: 8, emails
---


title: How do I hide static media file URLs?

text:
# Question
Title: How do I hide static media file URLs?
I have developed a website in Drupal 7. Right now I have a requirement: A page should display a PDF file (already generated). Only authenticated users should have access to view or download this file, but anyone with direct access to this static file link can view it and download it.

Is there any method I can use to prevent this and redirect them to the login page? What kind of logical programming needs to be applied in this case?

# Answer
> 0 votes
As @Clive and @prkos mentioned in comments above, Drupal has different stream wrappers for public and private file systems:

https://www.drupal.org/node/15368

I know you are using Drupal 7, but the Drupal 8 docs on the topic mention:

> In Drupal 8, you can no longer set private file system via UI. You set it in your `settings.php` file.

So you might find it convenient that you can configure this in the Drupal 7 admin UI ( "Private file system path" under admin/config/media/file-system) without any edits to your site's codebase.

If you have configured the private stream wrapper correctly, you can prevent anonymous users from downloading those files and instead respond to their attempts with an HTTP error 403.

The remaining desired functionality is provided by the community-contributed module that @Clive mentioned:

https://www.drupal.org/project/r4032login

The module is available for Drupal 7, 8, and 9. Its project page will explain its usage, but basically it redirects users to the login page when they ask to access a restricted resource, and redirects them to their intended destination once they log in successfully.

---
Tags: 7, media, uri
---


# Question
Title: Integrate webform submissions with Google sheet
How do I integrate webform submissions with google sheet in Drupal 9? I've found a way using Zapier but that allows only a limited number of submissions per month. Is there any way I can achieve it programatically to overcome this limitation?

# Answer
I've figured it out! Posting my solution here for anyone trying to integrate google sheets with webform. Enable the Google API PHP client module and follow the setup steps provided in the Documentation to setup your API.

Create a custom module and place this code in the .module file

```
    function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
        if ($form['#webform_id'] == 'your-webform-id') {
            // add an AJAX callback to the form submission
            $form['actions']['submit']['#ajax'] = array(
                'callback' => 'processFormSubmission',
                'event' => 'click',
                'progress' => [
                    'type' => 'none',
                ],
            );
        }

    }

    function processFormSubmission(array &$form, FormStateInterface $form_state){
        //Get the values from webform to store it in google sheet
        $first_name = $form_state->getValue('first_name');
        $last_name = $form_state->getValue('last_name');
        $email = $form_state->getValue('email');
        // Load the account
        $google_api_client = \Drupal::entityTypeManager()->getStorage('google_api_client')->load(your_client_id);
        // Get the service.
        $googleService = \Drupal::service('google_api_client.client');
        // Apply the account to the service
        $googleService->setGoogleApiClient($google_api_client);
        // Fetch Sheets object.
        $object = $googleService->getServiceObjects();
        // $object['sheets'] is a object of Google_Service_Sheets
        $sheets = $object['sheets'];
        $single_sheet = $sheets->spreadsheets_values;
        $spreadsheetID = "your spreadsheet id form url";
        $range = 'Sheet1';//Correct here for your sheet name
        $values = [
            [$first_name,$last_name,$email],
        ];
        $body = new Google_Service_Sheets_ValueRange([
            'values' => $values
        ]);
        $params = [
            'valueInputOption' => 'RAW',
        ];
        $insert = [
            "insertDataOption"=> "INSERT_ROWS",
        ];
        $single_sheet_update = $sheets->spreadsheets_values->append($spreadsheetID, $range, $body, $params, $insert);
    }

```

I've used hook form alter to insert an ajax call on submit and when submit button is clicked, I get the values from the webform and an API call is made to the Sheets API and store the values in the google sheet.
> 1 votes

---
Tags: webforms, 9
---