# Question
Title: Views fields not displaying for anonymous users
I am trying to create a View in Drupal 8 which displays the list of Username,Email,Role,Created Date and Status in a tabular format.

I am able to create the view and display all the fileds for administrator user but my problem is I cant display all the fileds for the anonymous user . Only Username,Role and Created fields are being displayed.

I cant figure it out why the other fields are not being displayed for anonymous user.

I have tried to check the permissions related to the users and can only find that `View user information` is relevent but enabling it for anonymous user does nothing other than giving hyperlink to Username.

Can anyone please help me to solve the issue.

My view configurion can be found here.

// views.view.users\_list.yml

```
    uuid:
    langcode: en
    status: true
    dependencies:
      config:
        - user.role.administrator
        - user.role.anonymous
      module:
        - user
    _core:
      default_config_hash:
    id: users_list
    label: 'Users List'
    module: views
    description: 'Provides Users List View'
    tag: ''
    base_table: users_field_data
    base_field: uid
    core: 8.x
    display:
      default:
        display_plugin: default
        id: default
        display_title: Master
        position: 0
        display_options:
          access:
            type: perm
            options:
              perm: 'access user profiles'
          cache:
            type: tag
            options: {  }
          query:
            type: views_query
            options:
              disable_sql_rewrite: false
              distinct: false
              replica: false
              query_comment: ''
              query_tags: {  }
          exposed_form:
            type: basic
            options:
              submit_button: Apply
              reset_button: false
              reset_button_label: Reset
              exposed_sorts_label: 'Sort by'
              expose_sort_order: true
              sort_asc_label: Asc
              sort_desc_label: Desc
          pager:
            type: mini
            options:
              items_per_page: 10
              offset: 0
              id: 0
              total_pages: null
              expose:
                items_per_page: false
                items_per_page_label: 'Items per page'
                items_per_page_options: '5, 10, 25, 50'
                items_per_page_options_all: false
                items_per_page_options_all_label: '- All -'
                offset: false
                offset_label: Offset
              tags:
                previous: ‹‹
                next: ››
          style:
            type: table
            options:
              grouping: {  }
              row_class: ''
              default_row_class: true
              override: true
              sticky: false
              caption: ''
              summary: ''
              description: ''
              columns:
                name: name
              info:
                name:
                  sortable: false
                  default_sort_order: asc
                  align: ''
                  separator: ''
                  empty_column: false
                  responsive: ''
              default: '-1'
              empty_table: false
          row:
            type: fields
          fields:
            name:
              id: name
              table: users_field_data
              field: name
              entity_type: user
              entity_field: name
              label: ''
              alter:
                alter_text: false
                make_link: false
                absolute: false
                trim: false
                word_boundary: false
                ellipsis: false
                strip_tags: false
                html: false
              hide_empty: false
              empty_zero: false
              plugin_id: field
              relationship: none
              group_type: group
              admin_label: ''
              exclude: 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_alter_empty: true
              click_sort_column: value
              type: user_name
              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
            mail:
              id: mail
              table: users_field_data
              field: mail
              entity_type: user
              entity_field: mail
              plugin_id: field
          filters:
            status:
              value: '1'
              table: users_field_data
              field: status
              plugin_id: boolean
              entity_type: user
              entity_field: status
              id: status
              expose:
                operator: ''
              group: 1
          sorts: {  }
          title: 'Users List'
          header: {  }
          footer: {  }
          empty: {  }
          relationships: {  }
          arguments: {  }
          display_extenders: {  }
        cache_metadata:
          max-age: -1
          contexts:
            - 'languages:language_content'
            - 'languages:language_interface'
            - url.query_args
            - user.permissions
          tags: {  }
      users_list_view:
        display_plugin: page
        id: users_list_view
        display_title: Page
        position: 1
        display_options:
          display_extenders: {  }
          path: users/list
          fields:
            name_1:
              id: name_1
              table: users_field_data
              field: name
              relationship: none
              group_type: group
              admin_label: ''
              label: Name
              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: user_name
              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: user
              entity_field: name
              plugin_id: field
            mail:
              id: mail
              table: users_field_data
              field: mail
              relationship: none
              group_type: group
              admin_label: ''
              label: Email
              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: basic_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
              entity_type: user
              entity_field: mail
              plugin_id: field
            roles_target_id:
              id: roles_target_id
              table: user__roles
              field: roles_target_id
              relationship: none
              group_type: group
              admin_label: ''
              label: Roles
              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
              type: separator
              separator: ', '
              entity_type: user
              entity_field: roles
              plugin_id: user_roles
            created:
              id: created
              table: users_field_data
              field: created
              relationship: none
              group_type: group
              admin_label: ''
              label: Created
              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: timestamp
              settings:
                date_format: medium
                custom_date_format: ''
                timezone: ''
              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: user
              entity_field: created
              plugin_id: field
            status:
              id: status
              table: users_field_data
              field: status
              relationship: none
              group_type: group
              admin_label: ''
              label: 'User status'
              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: boolean
              settings:
                format: default
                format_custom_true: ''
                format_custom_false: ''
              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: user
              entity_field: status
              plugin_id: field
          defaults:
            fields: false
            style: false
            row: false
            access: false
          style:
            type: table
            options:
              grouping: {  }
              row_class: ''
              default_row_class: true
              override: true
              sticky: false
              caption: ''
              summary: ''
              description: ''
              columns:
                name_1: name_1
                mail: mail
                roles_target_id: roles_target_id
                created: created
                status: status
              info:
                name_1:
                  sortable: false
                  default_sort_order: asc
                  align: ''
                  separator: ''
                  empty_column: false
                  responsive: ''
                mail:
                  sortable: false
                  default_sort_order: asc
                  align: ''
                  separator: ''
                  empty_column: false
                  responsive: ''
                roles_target_id:
                  sortable: false
                  default_sort_order: asc
                  align: ''
                  separator: ''
                  empty_column: false
                  responsive: ''
                created:
                  sortable: false
                  default_sort_order: asc
                  align: ''
                  separator: ''
                  empty_column: false
                  responsive: ''
                status:
                  sortable: false
                  default_sort_order: asc
                  align: ''
                  separator: ''
                  empty_column: false
                  responsive: ''
              default: '-1'
              empty_table: false
          row:
            type: fields
            options: {  }
          access:
            type: role
            options:
              role:
                anonymous: anonymous
                administrator: administrator
          display_description: ''
        cache_metadata:
          max-age: -1
          contexts:
            - 'languages:language_content'
            - 'languages:language_interface'
            - url.query_args
            - user.roles
          tags: {  }

```

https://www.hastebin.com/yorotapuge.sql

I searched and found out there was a similar question for D7 but the solution is not much helpful to me.

Show user email from the user entity to anonymous users

View Images for administrator and anonymous user can be view in below :

\[Admin View\]

\[Anon View\]

**Edit**: Feature is now in core. Refer change record

# Answer
> 2 votes
I used the following approach to solve the problem.Instead of patching the core.

I created a new using `hook_views_data_alter` hook.I created a new custom View field using the above hook and wrote the logic to retrieve data.

My Code is as follows:

**my\_module.views.inc** file which is placed in the root directory of the module folder.

```
<?php
/**
 * Implements hook_views_data_alter().
 */
function my_module_views_data_alter(array &$data) {

  //Add new fields to Users views
  $data['users']['email_id_field'] = array(
    'field' => array(
      'id' => 'email_id_field',
      'title' => t('Email Id'),
      'help' => t('Custom field to display Email Id.'),
    ),
  );

}

```

**EmailIdField.php** file which is placed in `my_module\Plugin\views\field\` directory.

```
namespace Drupal\my_module\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * Default implementation of the base field plugin,
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("email_id_field")
 */

class EmailIdField extends FieldPluginBase {

  /**
   * @{inheritdoc}
   */
  public function query() {

  }

  /**
   * @{inheritdoc}
   */
  public function render(ResultRow $values) {

    $EmailId = $values->_entity->get('mail')->getValue();
    $result = $EmailId[0]['value'];

    return $result;
  }
}

```

After creating new field I have added that field to Views field and thus it is made to display in the view.

Good examples can be found here

https://www.drupal8.ovh/index.php/en/tutoriels/293/create-a-view-plugin-without-using-database-field

and here

https://www.webomelette.com/creating-custom-views-field-drupal-8

# Answer
> 3 votes
This is by design, email addresses can be seen by admins only, but you can override it with `hook_entity_field_access()`: Add new permission to view user email field.

Maybe this module can help (not yet ported to D8): Show Email Address

## Use Contact form instead of revealing email address

Email addresses should never be revealed publically for various security reasons and spam scripts.

Usually, a Contact form is provided if a user should be reachable through email. That way the user email address isn't revealed but they can still be contacted through email, and the form can be spam-protected too.

There is a Contact module permission where you can allow Anonymous users to use the Contact form on all user profiles.

You can also include a link to the contact form in Views (`Contact link`) instead of showing the email address.

# Answer
> 2 votes
This is most likely a permissions issue. Rather than giving anonymous users the permissions to view all user account info you may want to use the "Disable SQL Rewriting" option within your View. This will bypass to permissions checking for the outputting of that View.

Go to "Query Settings" in the "Advanced" section of your View settings and check the box for "Disable SQL Rewriting"

---
Tags: views, 8
---


title: Conditional email is not sent

text:
# Question
Title: Conditional email is not sent
I have configured an email handler with the condition that an email message must be sent when a submission is updated by filling an image file field (the image file field has to be "filled"), but email message is not sent. The handler works if condition is removed

Core is 8.6.3 and Webform 8.x-5.0-rc26

Thanks

# Answer
This issue has been fixed in the latest dev release of the Webform module.

https://www.drupal.org/project/webform/issues/3015020
> 1 votes

---
Tags: 8, webforms, emails
---


# Question
Title: Display block content in current language
I have multilingual Drupal 8 site.

I want to display views block in home page.

It should display block contents in current site language.

Example:

1. I have content type called "Book". Which has translated content in EN & NL.
2. Created views block for "Book" content type.
3. Placed this block in Home page.
4. Enabled language switcher block in Home page.

When I visit my home page `mysite.com` & `mysite.com/nl` above views block shows always English contents.

When I visit site in NL language, I want to display this block in NL language.

# Answer
> 2 votes
Added language condition in Filter Criteria to fix it.

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


title: How do I create a multilingual export?

text:
# Question
Title: How do I create a multilingual export?
I have Drupal 8 site which interacts with a React component.

I want to expose one of my content type's content using REST export in views.

How do I set views path to create REST export for multilingual support?

For example, mysite/rest/export/data should give JSON data in English, while mysite/nl/rest/export/data or mysite/rest/export/data/nl should give JSON data in Dutch.

# Answer
Found solution in two ways.

**Method-1:**

Add language in filter criteria as mentioned below.

**Method-2:**

1) Add language in contextual filter

2) Provide a default value & select path component(I have selected 2)

3) Provide view path as `"rest/nl/export"` \- EN or NL provide your language code
> 2 votes

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


title: Rendering the add to cart form

text:
# Question
Title: Rendering the add to cart form
Is it possible to render the add to cart form programatically? Something like:

```
\Drupal::formBuilder()->getForm('Drupal\commerce_cart\Form\AddToCartForm', $product)

```

# Answer
Yes, possible and very easy.

**Short version**

You can use this render array.

This will render the Cart form if your product can be added to cart - if it has available variations bascially.

```
$combine = TRUE;
$langcode = 'en';
$view_mode = 'cart';

$build['add_to_cart_form'] = [
  '#lazy_builder' => [
    'commerce_product.lazy_builders:addToCartForm', [
      $product_id,
      $view_mode,
      $combine,
      $langcode
    ],
  ],
  '#create_placeholder' => TRUE,
];

```

---

**Full example with a Controller**

You can use a custom Controller to render your own *Add To Cart* form.

First, prepare the route in `mymodule.routing.yml`:

```
# Custom route to render Add to cart form.
mymodule.add_to_cart:
  path: '/mymodule/add_to_cart/{product_id}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CartController::addToCart'
    _title: 'Add to cart'
  requirements:
    _access: 'TRUE'
    product_id: \d+

```

Second, create your Controller:

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for cart routes.
 */
class CartController extends ControllerBase {

  function addToCart(int $product_id) {
    $build = [];

    if (!$product_id) {
      $build['error'] = [
        '#type' => 'item',
        '#markup' => $this->t('Wrong product ID'),
      ];
      return $build;
    }

    $build['add_to_cart_form'] = [
      '#lazy_builder' => [
        'commerce_product.lazy_builders:addToCartForm', [
          $product_id,
          'cart',
          TRUE,
          'fr'
        ],
      ],
      '#create_placeholder' => TRUE,
    ];

    return $build;
  }

}

```

Finally, add a link to open a modal on front end, as follow:

```
<a href="/mymodule/add_to_cart/1234" title="Add to cart" class="use-ajax" data-dialog-type="modal" data-dialog-options="{"width":700}">Add product to cart</a>

```

Clear cache

You should be good to go! :)
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: How to update a node after loadByProperties?
I search for a node with field value client id and I need to update values. How do I do that in drupal 8? I search with the following code

```
$profileNode = \Drupal::entityTypeManager()
          ->getStorage('node')
          ->loadByProperties(['field_user_id' => $id]);

```

I get an array in response to this which corresponds to this. How do I update the node value with this?

# Answer
> 2 votes
Assuming you response array will contain one node as suggested by the variable name `$profileNode`

here is a suggestion to make it :

```
$profileNode = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadByProperties(['field_user_id' => $id]);
// Get the node object.
$profileNodeObject = reset($profileNode);
if ($profileNodeObject) {
  // Make the changes we want : per example set the author to user 4.
  $profileNodeObject->setOwnerId(4);
  // Save the changes.
  $profileNodeObject->save();
}

```

---
Tags: nodes, updating
---


# Question
Title: Is there a downside of having too many features?
I have worked on or seen different D7 projects in the past, with different strategies for features:

1. One feature per view, content type, etc, with a consistent naming pattern. The result is many features with small or medium size. This has been my personal preference in the past.

Examples:

* `mysite_ft_vw_articles`, for an "articles" view.
    * `mysite_ft_ct_event`, for an "event" content type.
    * `mysite_ft_tx_categories`, for a "categories" taxonomy vocabulary.
2. Multiple elements grouped into the same feature, e.g. if they are related to a specific section of the site, a specific topic etc.

I am now in a new project where we have to pick the strategy we want to follow, and some team members prefer to have bigger features with more elements in them.

To me the only problem I can imagine with having too many features would be performance. Some operations in Drupal may get slower if more modules are enabled.

The main problem with less but bigger features would be git merge conflicts, and side effects of "drush fu" on unrelated functionality.

## Question

Am I missing something?

How big could the performance or memory impact be for e.g. 300 enabled feature modules?

What other downsides would it have?

Is there a recommended way / best practice?

## Related

When using features to manage deployment, should I break my functionality into many little features or one big feature?

This question is asking whether to have multiple features or one big feature. But the accepted answer still suggests to group a lot of things into one (e.g. all content types, all views, etc).

I am asking whether to have multiple features, or even more features.

Note: the sites where I did this so far had fewer content types and views, so if there was a performance impact it would have been smaller. Also I have not compared few or many features on the same project to see which is faster. This is a new employer, new team, new project, I want to do things the way I used to on other projects, but want to evaluate the pros and cons and have a good argument, before I force this on a team that used to work differently in the past.

# Answer
I'll jump in with an answer, though I agree with others that there is probably no single correct way.

My experience with features is that large features become very difficult to manage. Even one-feature-to-rule-all isn't a great answer, though it obviously reduces the conflicts possible, though that helps, because of the management of all those individual elements becomes hard.

In the past I have attempted to keep one "feature-module" for each aspect-feature of the site - so for example one feature describing a content type, and the views using it, and the rules, etc. Sometimes this is essentially one page, sometimes more. I have also tried larger groupings - bad idea - but not so far smaller ones (one for the actual CT, another for the view, etc.

The aspect of 'too many modules' is real, though I have dealt with perfectly functional sites with \>200 (non-features) modules active. A mitigation you *could* use is for the live system to run with the features modules disabled, because their effect should be in the database and so the code is not needed. I haven't tried this, though.

From this experience I think that the choice should be to keep the scope of each feature small and very, very well defined. Most of the time I have got into trouble it has resulted from some aspect of a feature that is on the border between several elements -- it should probably have been its own thing not lumped into other things.

So: smaller features with very well defined scope for each.
> 2 votes

---
Tags: 7, features
---


# Question
Title: How to move comments section out of its parent div
How can we move or override the placement of the comments in a node. Usually the comment section is placed inside its content div. My aim is to place this comment section out of its parent div which is usually the node content.

```
<div class="content">
 <div property="schema:text" ...>
    <p>
        Some Node Contents ...
    </p>
 </div>
 <section rel="schema:comment" ...> <!--move this comment section from here -->
    <h2>Add new comment</h2>
    <span data-big-pipe-placeholder-id="..."></span>
 </section>
</div>
<!-- to here -->

```

I have my template overrides

* field--comment.html.twig
* comment.html.twig
* page.html.twig

Inside themes/contrib/mytheme/templates

# Answer
Depending on which container you want to escape, you need to use either `node.html.twig` (recommended) or `page.html.twig` (harder, unlike node you can't use `{{ content.field_comment }}` in page).

If you are using `node.html.twig` (or somehting like `node--BUNDLENAME.html.twig`) and you manually render `{{ content.field_comment }}`, then you can avoid double-rendering of comments by rendering the "normal" content using the without filter `{{ content|without('field_comment') }}`
> 3 votes

---
Tags: 8, theming
---


# Question
Title: Creat a test user with no access permisions
On a site where only authenticated users have the permision to access content, I want to set up one test user that can log in but not access any content.

How would I achieve this?

This user will only be used to test different authentication methods. After logging in the user shoud get a "acces denied" result for all content.

# Answer
I would say to create a role that has access to content, grant that to the existing users, then uncheck "access content" from the 'Authenticated' role. This will also allow the system to know that even if a user is logged in, this does not grant them special privilege until they have an elevated role assigned to them.

The authenticated role should be just a starting point for a user that logs in. I never leverage it for granting permissions in a way that would make it a 'unique' role - just make that role. Otherwise you are going to have to jump through hoops with code which can be easily avoided by creating a few roles.

You can assign a user multiple roles. During authentication, I take it you can figure out how or what role to assign to them. Every authenticated user will get the 'authenticated' role by default.
> 0 votes

---
Tags: users
---


# Question
Title: How to display the user's url in a template?
I created a template `user-comment.html.twig` to customize the rendering of the comments author.

I can not display the user account url:

```
user.url

```

does not work.

How to display the user's url in a template?

```
{#
/**
 * @file
 * Default theme implementation to present all user data.
 *
 * This template is used when viewing a registered user's page,
 * e.g., example.com/user/123. 123 being the user's ID.
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 *   print a subset such as 'content.field_example'. Fields attached to a user
 *   such as 'user_picture' are available as 'content.user_picture'.
 * - attributes: HTML attributes for the container element.
 * - user: A Drupal User entity.
 *
 * @see template_preprocess_user()
 *
 * @ingroup themeable
 */
#}
<article{{ attributes.addClass('user--comment') }}>

  {{ content.user_picture }}
  {{ user.label }}
  <div class="bs-field-status">
    {{ content.utilisateur_statut_entity_view_1 }}
    {{ content.utilisateur_statut_entity_view_2 }}
    {{ content.utilisateur_statut_entity_view_3 }}
  </div>

  <div class="bs-field-link">
    <a href="{{ user.url }}" title="{{ user.label }}"></a>
  </div>

</article>

```

# Answer
> 3 votes
You can use the `path` function in a Twig template:

```
<a href="{{ path('entity.user.canonical', {'user': user.id}) }}">{{ 'View user profile'|t }}</a>

```

I don't know if `user.url` is a thing.

---
Tags: 8, theming, users, uri
---


# Question
Title: Converting a drupal/drupal site to Work With Composer
At our company we have several sites that appear to have been made using the now deprecated method of `composer create-project drupal/drupal`. We've been fine using previously documented methods to remove the replace block in composer.json and move the drupal/core require statement to update drupal/core.

However, I'm now running into a strange issue with a very specific Contributed Module that is detecting the \`"name": "drupal/drupal" statement and version as 1.0, which then conflicts with dependencies it wants to install. I tried removing the name field since composer docs state it is only required for published packages, but this does not help resolve it.

Some other google results suggest that my drupal core is missing a .git repo that may be required to detect versions? How would I resolve this if it's the case? What else can I try?

Error, caused by `composer require drupal/csv_serialization`:

```
  Problem 1
    - remove drupal/drupal No version set (parsed as 1.0.0)|remove drupal/core 8.6.1
    - don't install drupal/core 8.6.1|remove drupal/drupal No version set (parsed as 1.0.0)
    - don't install drupal/core 8.6.1|remove drupal/drupal No version set (parsed as 1.0.0)
    - Installation request for drupal/drupal No version set (parsed as 1.0.0) -> satisfiable by drupal/drupal[No version set (parsed as 1.0.0)].
    - Installation request for drupal/core (locked at 8.6.1, required as ^8.6) -> satisfiable by drupal/core[8.6.1].

```

composer.json:

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "require": {
        "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "^1.4",
        "drupal/core": "^8.6",
        "drush/drush": "^9.4",
        "symfony/http-kernel": "^3.4",
        "symfony/http-foundation": "^3.4"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "drupal-phpunit-upgrade-check": "Drupal\\Core\\Composer\\Composer::upgradePHPUnit",
        "drupal-phpunit-upgrade": "@composer update phpunit/phpunit --with-dependencies --no-progress",
        "phpcs": "phpcs --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --",
        "phpcbf": "phpcbf --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ]
}

```

# Answer
There is a tool that helps convert old style Drupal 8 installs to composer managed ones: https://github.com/grasmash/composerize-drupal

This should help restructure the project to leverage Composer, which the vanilla tarball install is not geared toward.
> 1 votes

---
Tags: 8, composer
---


# Question
Title: Custom Block Twig: File field how to get direct link to file?
How can I get the direct URL to a file field in twig? I am able to do this for images, but with a file field, it comes up blank.

WORKS

```
{% set media_img_url = file_url(content.field_background_image.0['#item'].entity.uri.value) %}

```

DOESN't WORK

```
{% set media_file_url = file_url(content.field_cta_file.0['#item'].entity.uri.value) %}

```

# Answer
`#item` is as far as I know only added by the image field formatter, so it's unlikely you'll find it in other field types.

Instead you can use the block content entity to get field values, for example:

```
{{ elements.content['#block_content'].field_file.0.entity.uri.value }}

```

This works independently of field formatters and as commented by @Kevin also when a field is hidden.
> 1 votes

---
Tags: theming
---


title: Alter menu link if logged in

text:
# Question
Title: Alter menu link if logged in
I have a regular node in my main menu that:

1. if an anonymous user clicks on it, the node should be shown regularly
2. if a logged in user clicks on it, there should be a redirect to an external website

I tried

`HOOK_menu_link_alter` but that only is invoked on edit-and-save (if menu item is created via web)

`HOOK_node_view` that seems to work but does not seem like a good solution to load the complete node and check for the user just to redirect

# Answer
> 0 votes
Instead of altering the menu link per role (which is tricky considering the process with which menus are built and cached), I would suggest you go for adding redirects per role.

The Url Redirect module should be able to help you achieve it.

> * Url Redirect is a simple, flexible module for allowing user(s) / role(s) to redirect from one path to other.
> * Url Redirect is also handy to add / edit / delete url(s) , specify role(s) / user(s) for url redirect, set a message for url redirect, enable / disable.

---
Tags: hooks, navigation, redirection
---


# Question
Title: How do you clear cache on a block when node of certain bundle added or updated?
If you want to clear cache on a render array when any node is updated you can add as a cache\_tag, "node\_list":

```
  '#cache' => [
    'tags' => ['node_list']
  ],

```

But there isn't a way to do this when only nodes of a certain bundle are added or updated.

If you have a block, for example, and you'd like to clear the cache on it when any node with bundle "article" is added or updated, how would you do this?

# Answer
You can easily create a custom cache tag related to properties on nodes by invalidating it yourself.

Based on this article: https://www.drupal.org/project/views\_custom\_cache\_tag

I created a custom tag for each node type, that is invalidated on node update:

```
/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function mymodule_node_presave(Node $node) {
  // Allows for clearing of blocks based on node type.
  $tags = ['node_type:' . $node->getType()];
  Cache::invalidateTags($tags);
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function mymodule_node_delete(Node $node) {
  // Allows for clearing of blocks based on node type.
  $tags = ['node_type:' . $node->getType()];
  Cache::invalidateTags($tags);
}

```

Then in my build array for my block I added:

```
$build['#cache'] = [
  'tags' => [
    'node_type:article',
    'node_type:video'
  ],
];

```

This means this block will only refresh when nodes that are of type "article" or "video" are created or updated.

You could do the same process for any property on an entity, not just bundle. For example, if you want a list of nodes to stay cached unless the nodes within it change their url alias, you could add code that checks if the url aliases is changing and then invalidate your tag node:123:url\_alias".
> 13 votes

# Answer
For others with this same question to have cache tags based on bundle, there is a “handy” module Handy Cache Tags which works really well. https://www.drupal.org/project/handy\_cache\_tags
> 1 votes

---
Tags: 8, blocks, caching
---


# Question
Title: How do I redirect users to an external URL?
I implemented a controller class in Drupal 8, which redirects to an external site. If I use \Symfony\Component\HttpFoundation\RedirectResponse, I get this error.

> Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

Using \Drupal\Core\Routing\TrustedRedirectResponse, I get this error.

> The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early.
> Returned object class: \Drupal\Core\Routing\TrustedRedirectResponse

What should I do?

# Answer
> 4 votes
Define a controller and redirect to external URL.

Use `TrustedRedirectResponse` class in case you know that you want to redirect to an external URL. Example below:

```
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
class ExampleController extends ControllerBase {

  public function example() {
    return new TrustedRedirectResponse('https://google.com');
  }
}

```

# Answer
> 0 votes
**With a route name on a Controller:**

```
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return $this->redirect('user.page');
  }
}

```

With a absolute url:

```
return new RedirectResponse('https://google.com');

```

# Answer
> 0 votes
Alternatively implement `hook_redirect_response_alter()` (as per #2909182 patch).

Here is the example from `redirect_test.module`:

```
use Drupal\redirect\Entity\Redirect;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Implements hook_redirect_response_alter().
 */
function redirect_test_redirect_response_alter(RedirectResponse $response, Redirect $redirect) {
  $path = 'test/redirect/2/successful';
  $replace = 'test/redirect/other';
  if ($redirect->getRedirect()['uri'] == "internal:/" . $path) {
    $response->setTargetUrl(str_replace($path, $replace, $redirect->getRedirectUrl()->setAbsolute()->toString()));
  }
}

```

---
Tags: redirection, page-controller
---


title: Link field title from entity/route

text:
# Question
Title: Link field title from entity/route
I have a Drupal link field configured to allow both internal and external links and have the title field enabled, but optional.

I want users to be able to reference internal entities without having to specify anything in separate title field, and have the Link field's title pulled from the entity label. However it appears that when the field's internal `title` value is left null, Drupal ends up using the field's `uri` value as the link title. This behavior seems odd to me.

My question is this: **given an internal `uri` value that looks like: `entity:node/3500` how can I preprocess or alter the functionality of the Link field to load in the entity's title/label as the `title` when it is left empty by the content editors.**

I've searched for issues on drupal.org but didn't turn up much of anything useful. I found Get title from Route, which seems to recommend using the TitleResolver, but that depends on putting together a $request object, which seems extremely impractical.

Suggestions?

# Answer
> 1 votes
So, I've written a preprocess function to do this:

```
/**
 * Prepares variables for link fields.
 */
function mymoduleortheme_preprocess_field__link(&$variables) {

  // If the link is a reference to an internal entity and there was no
  // link title provided by the content editor, then use the entity
  // label as the link text.
  $i = 0;
  foreach ($variables['element']['#items'] as &$item) {
    if (empty($item->get('title')->getValue()) && $item->getUrl()->isRouted()) {
      $parameters = $item->getUrl()->getRouteParameters();
      if (!empty($parameters)) {
        foreach($parameters as $entity_type => $id) {
          if ($entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($id)) {
            $variables['items'][$i]['content']['#title'] = $entity->label();
            break;
          }
        }
      }
    }
    $i++;
  }
}

```

This is working with both the standard Link field formatter as well as the "Separate link text and URL" formatter provided by Drupal 8 core.

My only doubt here is that I'm not sure how safe it is to assume getRouteParameters() will always be keyed with an entity type name and a value of the entity id.

Would appreciate your help to review and vet this. Thanks!

---
Tags: 8, entities
---


# Question
Title: How to get term ID from translated term name?
I have a custom argument validator for Views, which expects a term name input and outputs the tid for the query. This works great in English, but I'm not sure what to do for translations. Is there any way to search for a term id from the translated term name?

Here's my code:

```
public function validateArgument($argument) {

  if(strpos($argument, '-')){
      $argument = str_replace('-', ' ', $argument);
  }
  $term = taxonomy_term_load_multiple_by_name($argument);
  $termId = key($term);
  $this->argument->argument = $termId;

  return TRUE;

}

```

# Answer
A suggestion :

```
$my_translated_term_name = 'astuce';

$query = \Drupal::database()->select('taxonomy_term_field_data', 'td');
$query->addField('td', 'tid');
$query->condition('td.name', $my_translated_term_name);
// For better performance, define the vocabulary where to search.
// $query->condition('td.vid', $vid);
$term = $query->execute();

$tid = $term->fetchField();

```
> 1 votes

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


# Question
Title: Pass additional variable into existing twig template (Book module)
I use the Drupal 8 Book module for books where each chapter has a different author.

The Book Navigation block uses book-tree.html.twig (core/modules/book/templates) to generate a book tree showing chapter titles. I want to show author names also.

I can subclass and edit book-tree.html.twig, but I don't know how to get the author name passed in so I can use it. How do I go about this? Only the title, the url, and some flags are passed in now.

As an alternative, I can get the id for each chapter node from its url as a string. Can I use this id to load the chapter node from within the twig template? If so, I can get the author name from the node directly.

# Answer
> 2 votes
Drupal offers preprocess functions where additional variables for templates can be set up.

The naming convention is THEMENAME\_preprocess\_THEMEHOOK(). In your case, you want to add a variable for book-tree.html.twig. The machine name for this is the first part of the template, with underscores replacing hyphens. In this case it would be book\_tree. So your function would be THEMENAME\_preprocess\_book\_tree().

Preprocessors receive a single argument, an array. The keys of this array become the variables available in your twig template.

```
THEMENAME_preprocess_book_tree(&$vars) {
  $vars['book_author'] = some_function_that_gets_the_author();
}

```

Now the variable `book_author` will be available to your template.

# Answer
> 0 votes
Just in case it may benefit others, here's the code from my .theme file based on the helpful suggestion from @Jaypan. It's different from what he suggested because instead of passing a single variable to a node twig template (as I explained in my simplified question), I'm actually passing an array of entity references (the authors of each book chapter) to the book tree template, which accepts an array of items, each item representing a book chapter.

```
function my_theme_preprocess_book_tree(&$vars)
{
    foreach ($vars['items'] as $id => &$chapter) {

        $node = \Drupal\node\Entity\Node::load($id);
        $authors = $node->get('field_authors');

        if (count($authors) > 0) {

            $chapter['authors'] = $authors;
    }
}

```

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


# Question
Title: What hook to use to update history table
What hook can I use to update the history table for my use case?

I am using the answers module. When viewing a question it appends a view of answers by format of view mode. The history table for the question type is updated, but not for the answer type. This has the effect that all comments on the answer are always tagged as new. I added code to the hook\_node\_view for the question type wherein I get all related answers and update the history table correctly for them. However, hook\_node\_view runs before hook\_comment\_view and now all comments do not get a tag at all. I probably need to alter the history table after hook\_comment has run. Any suggestions?

# Answer
You are looking for the node\_tag\_new() core function.

```
function node_tag_new($node) {
  global $user;
  if ($user->uid) {
    db_merge('history')->key(array(
      'uid' => $user->uid,
      'nid' => $node->nid,
    ))->fields(array('timestamp' => REQUEST_TIME))->execute();
  }
}

```

Normally you'd just pass the full node object to the function, but if you only have the nid, you can just pass a dummy object.

```
$node = new stdClass();
$node->nide = 1234;
node_tag_new($node);

```

Modifying the OP's own answer, this would be:

```
function answers_exit() {
  $router_item  = menu_get_object();
  if (isset($router_item) && $router_item->type == "answers_question") {
    if ($user->uid) {
      $results = db_select('field_data_answers_related_question', 'rq')
        ->fields('rq', array('entity_id'))
        ->condition('answers_related_question_target_id', $router_item->nid)
        ->execute();
      foreach($results as $row) {
        $node = new stdClass();
        $node->nid = $row->entity_id;
        node_tag_new($node);
      }
    }
  }
}

```

However you should probably be using EntityFieldQuery since it will handle all all the specifics about which tables/columns to use:

```
function answers_exit() {
  $router_item  = menu_get_object();
  if (isset($router_item) && $router_item->type == "answers_question") {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'answers')
          ->fieldCondition('answers_related_question', 'target_id', $router_item->nid);
    $result = $query->execute();
    if (isset($result['node'])) {
      foreach ($result['node'] as $answer) {
        node_tag_new($answer);
      }
    }
}

```
> 1 votes

# Answer
This seems to work:

```
function answers_exit() {
   $router_item  = menu_get_object();
  if (isset($router_item) && $router_item->type == "answers_question") {
    global $user;
    if ($user->uid) {
      $result = db_select('field_data_answers_related_question', 'rq')
        ->fields('rq', array('entity_id'))
        ->condition('answers_related_question_target_id', $router_item->nid)
        ->execute()
        ->fetchAssoc();
      foreach($result as $row) {
        db_merge('history')
          ->key(array(
            'uid' => $user->uid,
            'nid' => $result,
          ))
          ->fields(array('timestamp' => REQUEST_TIME))
          ->execute();
      }
    }
  }
}

```
> 0 votes

# Answer
**hook\_exit** gets called on every call, even cached pages. This can cause problems with anonymous users and caching. **hook\_post\_render** only gets called when the view is rendered.

```
/**
* Implements hook_views_post_render().
*/
function answers_views_post_render(&$view, &$output, &$cache) {

  if ($view->name == 'question_answers') {
    if (count($view->result)) {
      foreach ($view->result as $object) {
        node_tag_new($object);
      }
    }
  }

}

```
> 0 votes

---
Tags: comments
---


title: Webform CKEditor add color

text:
# Question
Title: Webform CKEditor add color
I would like to add the possibility to change color in CKEditor, mainly for Webforms. The instructions at https://www.drupal.org/project/colorbutton suggest to download manually the CKEditor colorbutton plugin and then add it to /libraries: would it instead be possibile to modify composer.libraries.json and install the plugin via Composer ? Thanks a lot

# Answer
> 0 votes
Yes. As Clive says in his comment above, you can certainly use Composer to manage other code besides Drupal core and contrib modules.

If you are keeping your code in version control such as `git`, this also has the advantage of keeping third-party code out of your project's version control repository. Just commit your `composer.json` and `composer.lock` and you can rebuild all your project dependencies when you deploy.

---
Tags: 8, webforms, composer
---


title: Multiple URLs for same node

text:
# Question
Title: Multiple URLs for same node
anyone know how to create a URL alias and not redirect the user? I have a node with its alias set to `/sign-up`, but I also want it accessible via `/caregiver/sign-up`. I created a URL alias, but it seems to just do a redirect to `/sign-up`.

I checked the current redirects list and the only redirect for `sign-up` I am seeing as for an old page that redirects from `/activate` to `/sign-up`

# Answer
* Get the node id that have /sign-up as alias (lets say it's node/42)
* Go to /admin/config/search/path/add
* Fill the form as mentioned in the description : Existing system path : /node/42 Path alias : /caregiver/sign-up
* Save the form
* you can now access the node with /caregiver/sign-up alias :)
> 0 votes

---
Tags: 8, uri, path-aliases
---


title: Programmatically add a footer to a view

text:
# Question
Title: Programmatically add a footer to a view
I need add a footer to a view based on certain conditions. I followed this article and as per my understanding this should work. But this is not giving me any result.

Here is my code:

```
function utility_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  $item = array(
    'id' => 'area_text_custom',
    'table' => 'views',
    'field' => 'area_text_custom',
    'relationship' => 'none',
    'group_type' => 'none',
    'admin_label' => '',
    'empty' => NULL,
    'tokenize' => NULL,
    'content' => array(
      'value' => "Footer content is great.",
      'format' => "basic_html",
    ),
    'plugin_id' => 'text',
  );
  $view->setHandler($display_id, 'footer', 'area_text_custom', $item);
}

```

Update: Using the above hook the footer is getting called but renders as `Array`

# Answer
> 5 votes
I was able to add a Views footer with some code in a custom module.

```
use Drupal\views\ViewExecutable;
function YOURMODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'view_machine_name' && $display_id === 'view_display') {
    $options = array(
      'id' => 'area_text_custom',
      'table' => 'views',
      'field' => 'area_text_custom',
      'relationship' => 'none',
      'group_type' => 'none',
      'admin_label' => '',
      'empty' => TRUE,
      'tokenize' => FALSE,
      'content' => ‘Footer content is great.’,
      'plugin_id' => 'text_custom',
    );
    $view->setHandler('view_display', 'footer', 'area_text_custom', $options);
  }
}

```

Reference: Drupal 8: Programmatically Adding a Views Footer

# Answer
> 2 votes
User area instead of area\_text\_custom, below solutions is working for me

```
$item = array(
  'id' => 'area',
  'table' => 'views',
  'field' => 'area',
  'relationship' => 'none',
  'group_type' => 'none',
  'admin_label' => '',
  'empty' => NULL,
  'tokenize' => NULL,
  'content' => array(
    'value' => 'Footer Text goes here',
    'format' => "full_html",
  ),
  'plugin_id' => 'text',
);

$view->setHandler('display_name', 'footer', 'area', $item);

```

# Answer
> 2 votes
You can attach a few other types of content also. Here is an example for a paragraph entity, but any entity type will be similiar.

```
/**
 * Implements hook_views_pre_view().
 */
function mytheme_views_pre_view(ViewExecutable $view, $display_id, array &$args)
{
  if ($view->id() == 'my-view-id') {

    // Load your entity however you want.
    $paragraph_entity = '[my-entity]';

    $item = [
      'id' => 'area',
      'table' => 'views',
      'field' => 'entity_paragraph',
      'empty' => TRUE,
      'target' => $paragraph_entity->uuid(),
    ];

    // This can be header, footer, etc. See ViewExecutable::getHandlerTypes();
    $type = 'header';

    // Handler ID.
    $id = 'paragraph_entity';

    // Finally, attach the handler to the view.
    $view->setHandler($display_id, $type, $id, $item);

  }
}

```

To understand better how to interface with handlers, see core/modules/views/src/ViewExecutable.php

`view->getHandler()` and `view->removeHandler()` are also useful.

---
Tags: 8, views
---


# Question
Title: How should I deal with a vocabulary with many terms?
I'm trying to use Drupal 8, but if Drupal 7 is better for that, I'm ready to go back to Drupal 7.

I have a vocabulary that must contain at least 10,000 terms, but they can also become more than 100,000. For the sake of simplicity, I chose to make only one vocabulary, without hierarchy.

I quickly reached the limits of my server, and I regularly get WSODs, especially when I try to edit the vocabulary.

I tried to increase the limits of memory (I am under MAMP), but I still have errors. Here is the error:

> Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes) in /core/lib/Drupal/Core/Entity/Sql/Sq

How can I avoid these problems?
Is it preferable to split the vocabulary?

# Answer
> 0 votes
Since i can't answer it in comment. i'll try to answer here. I've solve similar problem, my solution is using redis caching and entity cache module

Since then, my site going well with 256MB RAM configuration in php.ini.

---
Tags: taxonomy-terms, performance
---


# Question
Title: What is the easiest way to get the value of a string field in a twig template?
I'm using Drupal 8.5.4 and Bootstrap Paragraphs. I have a custom module `foo` and a custom paragraph type `bar` defined within. In the template for `bar`, I use `kint` to inspect the content of the variable. It turns out it has 17 properties, and **none** of them are the value of the field. The first 14 of them are in core/lib/Drupal/Core/Field, L#89-102. The last 3 are `0`, `#cache`, and `weight`.

Digging into the object, I found the field value in `content.bar.0['#context'].value`. Obviously using this method to access a simple field value is janky as hell, and I would prefer not to have to do this every time.

Two questions:

1. Is there a simpler way to access the field value? I don't mind using a twig filter if need be
2. Is there a way to configure my paragraph types to pass the context to the template, rather than all of the field data?

# Answer
You are referring to *paragraph--bar.html.twig*? Then this depends on what you want to do with the value.

Render the field value:

```
{{ content.field_example }}

```

Write code with it:

```
{% if paragraph.field_example.value == 'foo' %}
  <p>The field value is "foo".</p>
{% endif %}

```

See this blog post for *node.html.twig*, which applies here as well, only that the entity is `paragraph.` instead of `node.`: https://www.md-systems.ch/de/blog/techblog/2017/02/20/twig-and-entity-field-api-or-how-to-take-control-of-nodehtmltwig
> 0 votes

---
Tags: 8, theming
---


title: When to use list(text) or taxonomy?

text:
# Question
Title: When to use list(text) or taxonomy?
This may be a silly question, but I'm curious what the benefit is of using a list (text) multiple select field over a taxonomy term reference field. They both seem to fill roughly the same function of giving predetermined multiple choice options, but taxonomy has the added benefit of allowing you to add terms after content has been written to the database.

So is there any good guideline for one to use one or the other? (And particularly when list(text) makes more sense than taxonomy term reference?).

# Answer
Structure and dynamic are IMO the keywords for choosing taxonomy. I recently had this question come to me when tagging companies with geographical regions. My first choice was to prepare taxonomy with list of regions. Soon it turned out to be over-complication. The regions almost never change their names and almost never change their structure/parents. So I tossed out the taxonomy and decided to use a flat List (Text). It's now also much easier to maneuver the regions in a View. So - if your list is static and flat - go for a list.
> 11 votes

# Answer
Taxonomy has performance issues as it scales because the SQL queries get longer; if you are using views filters, select lists will be faster than taxonomy.
> 8 votes

# Answer
The key differentiations I learned were:

* do you want users to be adding to the list of values, not just site admins or, will adding to the list be a semi-regular need for even site admins?
* do you want to use the value as an organizing piece of content itself (as suggested above by @Artur, creating pages of all content that shares this term, with different layouts, like a product page: show all XL clothes; or news, show all Sports)
* is the data at all hierarchical? (eg: subcategories where you'll want to capture the parent category sometimes or the children separately at others)

If no to all of the above, use select/text. If yes, use taxonomy terms. You'll usually use select/text, in my experience. It always feels wrong, but it's usually right.
> 7 votes

# Answer
Clear winner in my opinion would be taxonomy term, more power, little downsides.
> 0 votes

---
Tags: 7, taxonomy-terms, entities
---


# Question
Title: Restoring tempstore with another session ID
I am building the functionality of sign in during payment checkout in Drupal 8, and I am storing all the values in Drupal 8's tempstore variable. I am capturing the session id for this anonymous user. After the user is signed in, his session ID changes, and I am not able to load the tempstore with the session ID of anonymous user. Is there a way to restore the private tempstore by another tempstore session ID?

So, the submit function of my custom sign in form looks something like this:

```
$anonymous_session_id = session_id();

$user = user_load_by_mail($form_state->getValue('username'));
$uid  = $user->get('uid')->value;
user_login_finalize($user);

$temp_store = \Drupal::service('user.private_tempstore')->get($anonymous_session_id . '_com_reg');

```

When I do `$temp_store->get('some_value');` it does not give me any result since I am not able to restore the values. Can someone please help in this?

# Answer
> 1 votes
I've experienced the same issue while trying to pass private.tempstore data through anonymous to authenticated user in Drupal 8.

The function

`user_login_finalize($user);`

Performs de migrate() method. This method migrates anonymous session to authenticated session, but only the Native Session Storage (Symfony).

Private.tempstore has to manually be migrated as Ekta tells.

If you can't or you d'ont know how to implement it, just store the data in native `$_SESSION['yourkey']`

The problem it's that native Session it's loaded every time a page it's called, and with Tempstore you have more control about this. For this reason it's not the better solutions!.

This could be a good issue for Drupal Core in a future, migrate the tempstore too when session login.

# Answer
> 0 votes
So, here is what I did. I was not able to restore the tempstore session key value pairs even when I had its id. I dumped the values of this session in an array, and destroyed this session. Once the user logs in, I populate the new tempstore session with all the values in this array. So, my code now looks something like this:

In custom Signin.php:

```
public function submitForm(array & $form, FormStateInterface $form_state) {
    //session for a logged out user - this already has some values set
    $tempstore = \Drupal::service('user.private_tempstore')->get(session_id());

    $temp_values = array();
    $temp_values = getFormValues();

    //optionally - write code to delete this session

    //login the user
    $user = user_load_by_mail($form_state->getValue('username'));
    $uid  = $user->get('uid')->value;
    user_login_finalize($user);

    //restore values in tempstore after login
    $temp_store = \Drupal::service('user.private_tempstore')->get(session_id());
    restoreValues($temp_values); //restore the values from array to a new session
    $form_state->setRedirect('payment.payment_form');
    return;
}

function restoreValues($tempValues){
    //this is a tempstore session with new session id after user logs in
    $temp_store = \Drupal::service('user.private_tempstore')->get(session_id());
    $sessionKeys = getSessionKeysForModule();
    foreach($sessionKeys as $index=>$key) {
        $temp_store->set($key, $tempValues[$key]);
    }
    return;
}

```

Custom module file:

```
//function to set all the session keys
function getSessionKeysForModule() {
    return array('_company', '_country', '_address1', '_address2', '_city', '_state', '_postal_code', '_restore_for_anonymous');
}

```

---
Tags: 8, users, sessions
---


# Question
Title: Error is raised when I try to redirect webform submission to external webpage with query string
Dear Drupal community,

I created a webform using the webforms module in Drupal 8 in order to add information to a webpage. Since I don't want to update the webpage manually I'd like to automatize this process by redirecting the information entered in the webform to a cgi script which then takes care of the rest (The target webpage is not based on drupal). So I used the \[webform\_submission:values:\<\>\] tokens and added them in the query string of the external url. In principle it works, but I noticed that for some fields in the webform entries spaces and special characters like " and ' are possible. In these cases I get an error message that the confirmation URL is not valid. I attached a .png. At the blue line you see a space, this seems to be what causes the problem. But if I enter the url manually in the browser my cgi script works as expected. So I only need to prevent drupal from stopping the redirect.

I appreciate any help.

best regards

ps. I created the same post over at the drupal.org forum. Strangely though, I don't see my post appearing at the forum.

pps. While the approach with the query string is probably an unsafe approach it's alright for my purpose since everything happens in an password protected internal area.

# Answer
> 0 votes
I think there's an easier way to achieve what you want.

In you webform go to "Settings \> Form" then you'll see near the bottom "Custom settings" with a dropdown for "method". There you can change it to "GET (Custom)" then enter the url for your third party site.

If you needed the get variable names to be something specific you might need to remake your fields with the right key to match your get variable names you need.

But that should do the trick and it will take care or encoding any special characters for you

---
Tags: webforms, redirection
---


# Question
Title: How do I migrate file entities into media entities?
I am using the Migrate module for a D7 to D8 migration and I am writing the whole migration manually in code (rather than use the built in D7 migrate module, as I wanted more granual control on the migration.)

I have the following structure: the D7 site has a image field where images are stored as File entities. On the D8 site, the image field is an entity reference to a Media entity (and the Media entity in turn has a Image field.)

Originally, I had the following for my Images migration:

```
id: image_files

source:
  plugin: legacy_images
  constants:
    source_base_path: http://example.com/

destination:
  plugin: 'entity:file'

process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
    -     constants/source_base_path
    -     uri
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status

```

Inside my article node migration file, I had the following:

```
'field_article_image/target_id':
plugin: migration
migration: image_files
source: field_article_image

```

but I realized that this would not work. The target\_id coming from the image\_files migration were really File Entity ID's, not media entity ID's. In the ideal world, I'd like to find a way to create a third migration, which would create this middle step, and migrate file entities into Media Entities and then map that migration to the Articles migration. However, I can't figure out a good way of doing this.

Plan B will simply be to create a process plugin for the images migration, which will manually create file entities, attach them to media entities, and pass that migration over to Articles (this removes the middle step). This would mean, though, that while Media entities can be rolled back, File Entities could not.

# Answer
I ended up chosing to do it slightly different - I create a regular file import, set that migration as the source for my media entity reference field, and then applied a second process plugin 'MediaGenerate' to translate the FID to the new media target\_id

```
<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\media_entity\Entity\Media;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Row;
use Drupal\migrate_plus\Plugin\migrate\process\EntityGenerate;

/**
 * Generate a media entity with specified metadata.
 *
 * This plugin is to be used by migrations which have media entity reference
 * fields.
 *
 * Available configuration keys:
 * - destinationField: the name of the file field on the media entity.
 *
 * @code
 * process:
 *   'field_files/target_id':
 *     -
 *       plugin: migration
 *       source: files
 *     -
 *       plugin: media_generate
 *       destinationField: image
 *
 * @endcode
 *
 * @MigrateProcessPlugin(
 *   id = "media_generate"
 * )
 */
class MediaGenerate extends EntityGenerate {

/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) {
if (!isset($this->configuration['destinationField'])) {
  throw new MigrateException('Destination field must be set.');
}
// First load the target_id of the file referenced via the migration.
/* @var /Drupal/file/entity/File $file */
$file = $this->entityManager->getStorage('file')->load($value);

if (empty($file)) {
  throw new MigrateException('Referenced file does not exist');
}

// Creates a media entity if the lookup determines it doesn't exist.
$fileName = $file->label();
if (!($entityId = parent::transform($fileName, $migrateExecutable, $row, $destinationProperty))) {
  return NULL;
}
$entity = Media::load($entityId);

$fileId = $file->id();
$entity->{$this->configuration['destinationField']}->setValue($fileId);
$entity->save();

return $entityId;
}

}

```
> 4 votes

# Answer
As Media is an entity type you should create its own migration. You can generate a new source from the file table. Here is an example

https://gist.github.com/jibran/8e7cd2319e873858dd49a272227a4fd2

Then with `migration_lookup` you can map the fields like this.

```
field_d8_media_image/0/target_id:
  plugin: migration_lookup
  migration: my_media_image
  source: field_d7_image/0/fid

```
> 3 votes

# Answer
I appreciated the accepted answer a lot, however it already had some deprecated definitions and did not support posting alt and title image properties. Thus, I enhanced it a bit to support that and to work smoothly with latest Drupal 8.6.x. Here is the code of MediaGenerate.php (the appropriate Yaml syntax is inside the doc comment):

```
<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\media\Entity\Media;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Row;
use Drupal\migrate_plus\Plugin\migrate\process\EntityGenerate;

/**
 * Generate a media entity with specified metadata.
 *
 * This plugin is to be used by migrations which have media entity reference
 * fields.
 *
 * Available configuration keys:
 * - destinationField: the name of the file field on the media entity.
 *
 * @code
 * process:
 *   'field_files/target_id':
 *     -
 *       plugin: migration_lookup
 *       migration: my_file_migration
 *       source: field_image/0/fid
 *     -
 *       plugin: media_generate
 *       destinationField: image
 *       imageAltSource: field_image/0/alt
 *       imageTitleSource: field_image/0/title
 *
 * @endcode
 *
 * If image_alt_source and/or image_title_source configuration parameters
 * are provided, alt and/or title image properties will be fetched from provided
 * source fields (if available) and pushed into media entity
 *
 * @MigrateProcessPlugin(
 *   id = "media_generate"
 * )
 */
class MediaGenerate extends EntityGenerate {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) {
    if (!isset($this->configuration['destinationField'])) {
      throw new MigrateException('Destination field must be set.');
    }

    // First load the target_id of the file referenced via the migration.
    /* @var /Drupal/file/entity/File $file */
    $file = $this->entityManager->getStorage('file')->load($value);

    if (empty($file)) {
      throw new MigrateException('Referenced file does not exist');
    }

    // Creates a media entity if the lookup determines it doesn't exist.
    $fileName = $file->label();
    if (!($entityId = parent::transform($fileName, $migrateExecutable, $row, $destinationProperty))) {
      return NULL;
    }

    $entity = Media::load($entityId);

    $fileId = $file->id();

    $destinationFieldValues = $entity->{$this->configuration['destinationField']}->getValue();
    $destinationFieldValues[0]['target_id'] = $fileId;

    $this->insertPropertyIntoDestinationField($destinationFieldValues, $row, 'alt', 'imageAltSource');
    $this->insertPropertyIntoDestinationField($destinationFieldValues, $row, 'title', 'imageTitleSource');

    $entity->{$this->configuration['destinationField']}->setValue($destinationFieldValues);
    $entity->save();

    return $entityId;
  }

  protected function insertPropertyIntoDestinationField(array &$destinationFieldValues, Row $row, $propertyKey, $configurationKey) {
    // Set alt and title into media entity if not empty
    if (isset($this->configuration[$configurationKey])) {
      $propertyValue = $row->getSourceProperty($this->configuration[$configurationKey]);
      if (!empty($propertyValue)) {
        $destinationFieldValues[0][$propertyKey] = $propertyValue;
      }
    }
  }
}

```
> 2 votes

# Answer
If you want to migrate files in Drupal 8 to media entities you can use this module: https://www.drupal.org/project/migrate\_file\_to\_media

It has a drush script, that automatically creates the media reference fields. Additionally it detects duplicate images using a binary hash. And it supports translations.
> 0 votes

---
Tags: 8, migrations
---


title: How to load absolute CSS and JS assets

text:
# Question
Title: How to load absolute CSS and JS assets
I would like to load CSS and JS from https://static.example.com . The typical page contains:

```
<link rel="stylesheet" href="/sites/default/files/css/css__wBfhyL83sORKzo__AgHv4HOGuOoSbIzIaa4clq9PXs.css?pik02l" media="all" />

```

and contains similar entries for JS. I would like to add https://static.example.com to the front of the `href="URL"` for both CSS and JS.

I'm am aware that this can be done with a contrib module. I would like to **find a hook** or some other way to add this to my custom module.

# Answer
> 1 votes
Even though you don't want to use a contrib module I will recommend the CDN module anyways. It does what you want, but if you don't want to use it you can still look at how they do it.

They define a lot of services, but the most interesting one is this one:

```
cdn.file_url_generator:
    class: Drupal\cdn\File\FileUrlGenerator
    arguments: ['@app.root', '@file_system', '@stream_wrapper_manager', '@request_stack', '@private_key', '@cdn.settings']

```

The class `FileUrlGenerator` then does checks for files to determine if they should be rewritten and rewrites them.

# Answer
> 0 votes
These are aggregated assets, so you need to find out how they get added there in the first place. Then you can alter them most likely via `hook_page_attachments_alter`. Similar to Make canonical URL in document HEAD absolute.

Problematic about this approach is that these assets should are aggregated with that cryptic hash in their name *per environment*. So you need to switch off your custom module everywhere else except on the live instance.

---
Tags: 8, theming, cdn
---


title: How config the single page site module

text:
# Question
Title: How config the single page site module
I have installed the Single Page Site module and I was follow the instructions but still don't works for me.

the module conf:

Menu: main

Menu class/id = #block-mainnavigation

Menu item selector = ""

Title: "Home"

Tag: h2

check: homepage

---

I have one item of my main menu called : "servicios", link to #servicios"

---

In my `page--front.html.twig`

i have a section with a element `<h2 name="servicios">Nuestros Servicios</h2>`

but don't works

any idea?

# Answer
Well, i found a best way to do a one page menu , using link attributes for add exceptions to the any menu item, and i used jquery one page nav than with a simple reference to the menu, works perfectly.
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: Facet blocks are not appearing, when indexed view block is called programmatically with views_embed_view
I have made an indexed view of my products. In that view, i have a page and a block. If I output the block from drupal/admin/structure/block the block view is shown together with the facet blocks.

Due to some conditions, I prefer to output the indexed view block programmatically, via page.tpl.php, and views\_embed\_view(), the indexed view block is shown correctly but then the facets are not displayed. Here is my code:

```
//level 2 webshop/categorie/subcategorie
            elseif( count($url_array)==4 && $url_array[1]=="webshop"){
                // if ($url=="/webshop/auto"){
                $tax_arr=taxonomy_get_term_by_name($url_array[3],"product_categorie");
                $tax=reset($tax_arr);
                $tax_chi=taxonomy_get_children($tax->tid);
                $tax_chi_tids = "";
                $counter=0;
                foreach ($tax_chi as &$child) {
                    if ($counter == 0){
                        $chtid =$child->tid;
                    $tax_chi_tids .=$chtid ;
                    }
                    else{$tax_chi_tids = $tax_chi_tids."+".$child->tid;}
                    $counter ++;
                }
                //echo views_embed_view('product_categorieen', 'block_1',$tax->tid);
                echo views_embed_view('view_products_index_product_hh','block_1',$tax_chi_tids);
            }

```

# Answer
> 0 votes
For now, i have fixed it, putting the facet blocks also in the page.tpl.php, for me in the first sidebar. I iterated all active facet blocks in the block table an d then displayed each one with this code:

```
        $block_facet = block_load($module, $delta);
        print render(_block_get_renderable_array( _block_render_blocks(array($block_facet))));

```

---
Tags: blocks, search
---


# Question
Title: Why is my theme library load on every page?
I'm beginning with D8, but I work a lot with D7 and Magento. I follow the developer documentation to add a library in my theme, and I don't understand why it's loading it on every page. I only want attach it to a brunch of page with a preprocess hook. Could you help me please?

In my theme.libraries.yml I add this at the end:

```
hover3d:
  js:
    js/hover3d.js: {}

```

In my theme.info.yml I add under libraries "theme/hover3d".

Here is specific information:

* I deactivated JavaScript/CSS compression in the back office and in my `settings.local.php` file
* My theme is a sub theme of bootstrap\_barrio
* My Drupal version is 8.6.3
* There is no custom / contrib modules yet
* I discover it by inspecting my page

* I don't really understand how JavaScript parts are loaded, but I suppose it's with lazy builders which are called placeholder and in D8 for rendering JavaScript there are two (or more) which are js-placeholder and js-bottom-placeholder. I see in my HTML structure that in the js-placeholder is only loaded modernizer and in the js-bottom-placeholder all the others. I don't know if this is a correct JavaScript rendering procedure, so I keep it here if it can help you.

# Answer
> In my theme.info.yml i add under libraries "theme/hover3d".

That's why it's loaded on every page. `libraries` in the theme info file is:

> A list of libraries (which can contain both CSS and JavaScript assets) to add to all pages where the theme is active.

To add it contextually, attach it to a relevant render array. For example:

```
function MYTHEME_preprocess_node(&$variables) {
  // Library will only be loaded when a node is rendered on the page.
  $variables['#attached']['library'][] = 'theme/hover3d';
}

```

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme for more information.
> 5 votes

---
Tags: 8, javascript
---


# Question
Title: Is it okay to expose .yml or .install files to public?
As per my knowledge the static files like css/js inside core/modules etc should be read by http server user. So normally I give read permission recursively to http user for directories like core, theme, modules etc. But these directory contains some .yml or .install files e.g `drupal/web/core/modules/user/user.install` which gets downloaded automatically when someone visits my site `example.com/core/modules/user/user.install` .

So is it okay to expose those files to public ? and what steps can be taken to avoid it ? I checked some popular sites they also expose those files. So bit confused.

Note: Drupal default .htaccess may take care of these thing for Apache server only but what about other servers like nginx ? However I think Drupal is hard coded to be used with Apache server only.

# Answer
> 1 votes
No.

The web server (e.g. via apache's directive) needs to be able to read (not write) the index.php file (and occasionally others such as update.php), and also static files such as .css/.js, pdfs and images.

The php interpreter is not limited by directives and so most other files required by php do not have to be visible.

As Hudri said, leave the .htaccess files as they are, configure the server to notice them (AllowOverrides) and refer to an appropriate guide, such as: https://www.drupal.org/docs/develop/local-server-setup/linux-development-environments/installing-php-mysql-and-apache-under

---
Tags: 8, security
---


# Question
Title: Render page with theme wrapper from custom controller?
I've created a page layout using panels in the Drupal admin UI (page\_machine\_id). I'm trying to load that page into a custom controller like so and render one of the variants (Drupal 8):

```
public function profile() {
    $page = \Drupal\page_manager\Entity\Page::load('page_machine_id');
    $variants = $page->getVariants();
    $pageVariant = end($variants);
    $viewer = new \Drupal\page_manager\Entity\PageVariantViewBuilder();
    $pageArray = $viewer->view($pageVariant);
    return new Response(render($pageArray));
}

```

This renders the page content correctly, but does not include the theme wrapper around it and I can't figure out how to get the theme to show.

Thanks.

# Answer
solution is

```
    return $pageArray;

```

Adding Response bypasses Drupals rendering.
> 0 votes

---
Tags: theming, entities, page-controller
---


# Question
Title: Show content that is tagged to both current node and translation source
I'm using Drupal 7, i18n, Views3, translated\_entityreference, and Entity Translation.

http://lingtransoft.info/apps/paratext

I have a content type: Training Resource, and each Training Resource is a member of another content type that is connected connected by Entity Reference (field\_translation\_ref) to the content type Application.

If I add Training Resources in English and choose the application Paratext, they get tagged to node 174, the Original content. If I add a Training Resource in French and Choose the application Paratext, it gets connected to node 399985, the nid of the French translation of the Paratext content.

The following View allows me to see all Training Resources tagged to Paratext(174).

I know that the "Content Translation: Source Translation" Relationship is supposed to give me access to the source node, and "Content: Entity translation: translations" has the potential to allow access to the translated node, but I can't figure out how to configure the view to use these values.

**What I want:**

Now I would like a view that dynamically aggregates and displays the resources tagged to both Paratext(714) \[The Translation Source\] and Paratext(399985) \[the translated node\].

On the English Application page: Show All Training Resources with Entity Reference to the current NID and also those connected to the Entity translation of this page in French.

On the French page: Show All training Resources with entity reference to the current NID, and also those connected with the source Translation.

If possible, I would prefer to use the interface and/or some existing modules to do this.

Thanks for any help you can give me. ~Matthew

# Answer
The problem isn't getting both the source and translation nodes into Views results, that's easily done.

The problem is when you apply the Contextual filter. Because the plain Entity reference field Contextual filter isn't translation aware.

But you can make it aware of translations with the help of the Relationship **Content translation: Translations**.

I don't know if your filter for Media to be in English will cause any trouble, so try to remove it if you see any problems.

Also as far as I can see you don't need the `Entity Reference: Application Ref` Relationship, you're not using it in any of the Fields and unless you need it for something not visible here you can safely remove it.

## List nodes referencing a node, along with nodes referencing its translations

Here are the steps you need to do on your Views to make it Contextually sensitive to not only the referenced entity, but also to that entity's translations:

1. You already have `Training materials` views showing some fields.

**Don't** include any language filters, unless you plan on allowing all the languages which defeats the filter's purpose anyway.
2. Add the **Content translation: Translations** Relationship and configure it:
Don't Require it (although I haven't noticed any difference)
`Translation option`: **All**
3. Add the **Content: Application Ref** Contextual filter and configure it:
Use the **Translation** Relationship!
`When the filter value is NOT in the URL`
\[whatever you like, All results or Default Content ID from URL\]
`When the filter value IS in the URL or a default is provided`
**Specify validation criteria**
**Content**
**Application**
**Node ID**

Now if you enter an Application node ID of any language, you will see all Training nodes referencing it AND all Training nodes referencing translations of the Application node.
> 0 votes

---
Tags: views, entities, i18n-l10n
---


# Question
Title: Load the value of an entity field type in another form
I have created a custom field and I wish to load the value dynamically in another form in relation to the specific node entity the value belongs to. I understand that to get the value I have to use/know the field\_name like this

```
$entity->get('field_name')->getValue();

```

What I want is to get the field\_name set via content configurations with only the type of node and the field name as defined in the fieldItem Plugin

```
$field_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node');

```

When I dump $field\_definitions am able to see all the fields array with all the details but I can't get my node.field\_name in relation to the fieldItem name defined in the specific field plugin, in my case field\_custom\_example

```
/**
 * Plugin implementation of the 'field_custom_example' field type.
 *
 * @FieldType(
 *   id = "field_custom_example",
 *   label = @Translation("Custom Example"),
 *   description = @Translation("Stores data for Custom Example Field"),
 *   default_widget = "custom_example_widget",
 *   default_formatter = "custome_example_formatter"
 * )
 */

```

that's where am stuck.

# Answer
Use the method FieldDefinitionInterface::getType:

> Returns the field type.
>
> **Return value**
>
> (string) The field type, i.e. the id of a field type plugin. For example 'text'.

In your case for example:

```
foreach ($field_definitions as $name => $definition) {
  if ($definition->getType() == 'field_custom_example') {
    // found field $name
  }
}

```
> 1 votes

---
Tags: entities, configuration, plugins
---


title: Link to outlook: protocol in Views

text:
# Question
Title: Link to outlook: protocol in Views
In my website, I'm creating a dynamic external link to open email from Outlook using `outlook:{Entry ID}` link. It should be like:

`outlook:000000006CD8BD6F1761654D9AD70F841783C591070062F134BA8C073B4296C8467090C20CF200000089D837000010EBA743D9305C4891225FE3E347AE1800003B82DF840000`

I tried to use:

1. "Rewrite the output of this field": `<a href="outlook:[guid]">open outlook</a>`

AND/OR

2. Output this field as a link, with link path: `outlook:[guid]` with options: "Use absolute path" and "External server URL" enabled.

The problem is no matter I use in Views field rewrite, the anchor's href `outlook:` replaced with `http://localhost/` or `http://localhost:8080/pms/outlook%3A`

What do I need to do to generate the link correctly in format `outlook:[guid]`?

# Answer
> 0 votes
The problem is that the URL code in Drupal doesn't recognise your "outlook:" prefix, and so is trying to make it a valid version of a protocol it does know. Option (2) explicitly invokes the URL code, so it is not surprising that it changes the href.

I am slightly surprised that the rewrite version didn't work, and can only assume you had other options set in the View which caused this -- or that the page was cached.

If you cannot get the rewrite to work, I suggest you override the field with a view-specific field template (see "theme information" in the theme config), in which you can do whatever you wish.

# Answer
> 0 votes
You don't seem to be using a valid protocol allowed in URL but I guess you're building something within a closed context. https://en.wikipedia.org/wiki/URL#Syntax

There are two things to consider here, one is how to control the output of the Drupal field, the other is how to construct a valid HREF.

## Drupal Rewrite results

Try the plain **Rewrite the output of this field**, without the `Output as link`. Since you're including the anchor code yourself in the Rewrite Text, you don't want Drupal to construct the link. Drupal will probably always assume and use the HTTP protocol, and you want a different protocol.

By setting up the Rewrite this way you won't have to override through views templates.

## Construct valid HREF

The `outlook:` prefix is only a Windows-specific preference for which application to use to open the link, it isn't a URI scheme/protocol. Without a protocol no application knows what to do with the link. You still have to provide either a valid internet link `outlook:http://blahblah` or a link to a local file `outlook:file://blahblah`.

Maybe Outlook does some special treatment and will know what to do with the link, I don't have any experience with that, try asking on MS-specific support sites about that part.

---
Tags: views
---


# Question
Title: How to setup Drush core development environment?
I would like to create a PR against Drush, so one of the core commands has additional options. But I'm not really sure, how should I setup my development environment, so I'm not losing my time moving code between my site-specific Drush and `master` branch I checked out elsewhere.

I see that Drush contains docker compose file (https://github.com/drush-ops/drush/blob/master/docker-compose.yml), but the `wodby/php` image apparently doesn't contain Drupal Core. I wasn't able to find any tutorial about this.

# Answer
a) Start by reading the following material (if you haven't already):

b) Fork the drush-ops/drush repository, so that you can track your work (and eventually start a PR from your fork back to the original repo).

c) Install the local dev environment provided using docker-compose:

```
git clone https://github.com/stefanospetrakis/drush.git
cd drush
git checkout -b YOUR_BRANCH
docker-compose up -d
docker-compose exec drupal composer install

```

At this point you have the source code of drush, equiped with tests. You can do your changes and additions to it and commit/push to your fork, as your project evolves.

d) You can test your changes at any time, against the official drush test suite to make sure you didn't break something:

```
docker-compose exec drupal composer test

```

e) Additionally, you can test your work in progress inside your own drupal projects, by replacing the standard drush in composer with your own fork, that would need three things:

* Adding an extra repository in your Drupal's composer.json, e.g.:

```
"type": "git",
"url": "https://github.com/stefanospetrakis/drush"

```
* Aliasing the "drush/drush" package, in order to pull from your current working branch in your repo, based on the exact version number found in composer.lock, e.g.:

```
require "drush/drush": "dev-YOUR_BRANCH as 9.5.2",

```
* Use source (git) for your drush package, e.g.

```
{
"config": {
    "preferred-install": {
        "drush/drush": "source",
        "*": "dist"
    }
}

```

}
* Possibly do manual pulls inside the `vendor/drush/drush` folder in order to get your latest work.

And as @greg\_1\_anderson mentioned in a separate answer, you will find Drupal Core under the `sut` directory of drush's source code.

Good luck!

P.S.: Replace https://github.com/stefanospetrakis/drush.git with the URL of your fork of drush-ops/drush repository, this is just an example.
> 6 votes

# Answer
The Drush test suite on the master branch makes its own Drupal 8 site install for you. Drush calls this site the System Under Test, or "SUT".

Copy `tests/phpunit.xml.dist` to `tests/phpunit.xml` and enter your database credentials there.

The SUT will be created when you run the tests via `composer functional`.

You may use the SUT in ad-hoc testing by using the provided aliases, e.g.:

`./drush @sut.dev status`

**UPDATE:** `phpunit.xml.dist` has been moved back to its original location in the `tests` directory.

**\*IMPORTANT:** The SUT is automatically destroyed at the end of each test run. `export UNISH_DIRTY=1` if you'd like Drush to keep it around for ad-hoc testing.
> 4 votes

# Answer
What I would do to start with is to create my drupal 8 site using the drupal-project composer action, as recommended.

Part of that will cause drush to be installed under /vendor. Convert that into a full clone of the repo and make your changes there.

You should be able to test inplace to some degree, but if you want to test the new drush code on your main site, make a softlink from vendor/drush to the new site's vendor/drush. These days drush always prefers to use the installation within a site folder.

Hope that helps.
> 1 votes

---
Tags: drush
---