title: Redirect after purchasing

text:
# Question
Title: Redirect after purchasing
How can I perform a redirect after purchasing a product? I tried to create a custom checkout pane for this purpose, but it doesn't work as the form is not submited:

```
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
  if ($this->getStepId() == 'complete') {
    $form_state->setRedirect('<front>');
  }
}

```

Is there any possibility to do this with a pane or do I have to create an event subscriber and redirect on the checkout event?

# Answer
In your "submitForm" method write below code:

```
$form_state->setRedirect('<front>');
return;

```

To redirect you can also use the following code:

```
//after the namespace
use Drupal\Core\Url;

//In your "submitForm"
$url = Url::fromRoute('<front>');
$form_state->setRedirectUrl($url);

```

To redirect you can also use the following code:

```
//after the namespace
use Symfony\Component\HttpFoundation\RedirectResponse;

//In your "submitForm"
global $base_url;
$response = new RedirectResponse($base_url);
$response->send();
return;

```
> 1 votes

# Answer
Examining CheckoutFlowBase::redirectToStep() taught me that this could be accomplished in a checkout pane like this:

```
use Drupal\commerce\Response\NeedsRedirectException;
use Drupal\Core\Url;

...

  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    throw new NeedsRedirectException(Url::fromUri('internal:/mydestination')->toString());
  }

```

Here's a configurable checkout pane for this purpose:

```
<?php

namespace Drupal\your_module\Plugin\Commerce\CheckoutPane;

use Drupal\commerce\Response\NeedsRedirectException;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Provides the redirection pane.
 *
 * @CommerceCheckoutPane(
 *   id = "redirection",
 *   label = @Translation("Redirect"),
 * )
 */
class Redirection extends CheckoutPaneBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
        'destination' => 'internal:/',
      ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationSummary() {
      return $this->configuration['destination'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['destination'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Redirect to'),
      '#description' => "URI of the destination. For example 'internal:/search' or 'http://google.com'.",
      '#default_value' => $this->configuration['destination'],
    ];
    return $form;
  }

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

    if (!$form_state->getErrors()) {
      $values = $form_state->getValue($form['#parents']);
      $this->configuration['destination'] = $values['destination'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    throw new NeedsRedirectException(Url::fromUri($this->configuration['destination'])->toString());
  }

}

```
> 1 votes

# Answer
I was able to achieve the redirect by setting the redirect in the submitPaneForm instead of the buildPaneForm function and attaching a JS to automatically submit the pane form.

I would prefer a solution without JS.
> 0 votes

# Answer
If you need this feature just for some product variations then install the *Commerce Quick Purchase* module and create a block for each of those variations and in the block settings define whether you want a customer `Add to cart` product at all or just redirect to a product page or a Shopping cart page or checkout page. See more: https://github.com/drugan/commerce\_quick\_purchase#redirection
> 0 votes

---
Tags: 8, commerce
---


title: Programmatically resize images uploaded

text:
# Question
Title: Programmatically resize images uploaded
When uploading images to D8 programmatically the setting for **Maximum image resolution** will be ignored and images will not be scaled down. Some of the images i have to upload are even larger then 10MB.

I am currently using this code.

```
$file_type = explode('.', $image)[1];
$data = file_get_contents($image);
$path = 'public://images/';

if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {

  $file = file_save_data($data, $path . md5($image) . '.' . $file_type, FILE_EXISTS_REPLACE);

  $node = Node::create(array(
    'type' => 'image',
    'title' => $image,
    'field_image' => array(
      'target_id' => $file->id(),
    ),
  ));
  $node->save();

}

```

I've tried to work with `ImageStyle::load('max_2600x2600')`, but that will only create a style in styles directory.

It would be possible to use a custom shell command but i would love to use the Drupal 8 way. How to make sure original images will get resized?

# Answer
You can Use Image style before save the node.

```
$original_image = 'public://images/image.jpg';

// Load the image style configuration entity.
use Drupal\image\Entity\ImageStyle;
$style = ImageStyle::load('max_2600x2600');

$uri = $style->buildUri($original_image);
$url = $style->buildUrl($original_image);

```

Here some links may helps you

Drupal 8 - Create an Image and ImageStyle Programmatically

Drupal 8 images with image style

Flexible image style system
> 4 votes

# Answer
I ran into the same thing. This code ended up working for me

```
      use Drupal\file\Entity\File;
      use Drupal\image\Entity\ImageStyle;
      use Drupal\node\Entity\Node;

      $fileName = 'example.jpg';
      $destination =  "public://images/" . $fileName;
      $temporaryFile = 'temporary://' . $fileName;
      file_save_data($photoData, $temporaryFile, FILE_EXISTS_REPLACE);

      $style = ImageStyle::load('thumbnail');
      $style->createDerivative($temporaryFile, $destination);

      $file = File::create([
        'uid' => 1,
        'filename' => $fileName,
        'uri' => $destination,
        'status' => 1,
      ]);
      $file->save();

      if ($file) {
          $node->get('field_photos')->appendItem([
              'target_id' => $file->id(),
              'alt' => 'Alt text goes here',
          ]);
      }

      ...

      $node->save();

```
> 1 votes

---
Tags: 8, media
---


title: Theme hook not found

text:
# Question
Title: Theme hook not found
I have a custom module that implements a webform handler. I'm seeing this error in my Watchdog log when I navigate to admin/structure/webform/manage/myform/handlers:

> Theme hook webform\_handler\_myform\_form\_handler\_summary not found.

I must have missed something when creating my module, but what? What needs to be added? Searches for "webform handler theme hook" haven't been fruitful.

# Answer
As seen in webform\_example\_handler

You need to add:

mymodule/**mymodule.module**

```
<?php

/**
 * @file
 * Provides a custom webform handler.
 */

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'webform_handler_myform_form_handler_summary' => [
      'variables' => ['settings' => NULL, 'handler' => []],
    ],
  ];
}

```

mymodule/templates/**webform-handler-myform-form-handler-summary.html.twig**

```
{#
/**
 * @file
 * Default theme implementation for a summary of an example webform handler.
 *
 * Available variables:
 * - settings: The current configuration for this email handler:
 *   - message: The message.
 *   - debug: Debugging flag.
 * - handler: The handler information, including:
 *   - id: The handler plugin id.
 *   - handler_id: The handler id.
 *   - label: The handler label.
 *   - description: The handler description.
 *
 * @ingroup themeable
 */
#}
{% if settings.debug %}<b class="color-error">{{ 'Debugging is enabled'|t }}</b><br />{% endif %}
<b>Message:</b> {{ settings.message }}

```

Clear/flush the cache so your new hook & template file gets picked up.
> 1 votes

---
Tags: hooks, webforms
---


# Question
Title: How do I log in if I can not get the login prompt page to come up as it should?
I am having some issues with my Drupal 7.

Because of a different bug I am having with component or panel, one that is taking over pages and hiding other parts of a page somehow, my login page has been corrupted.

what is supposed to be my /user and/or user/login page looks completely as it should not look. The username and password prompt and input fields are missing because of a component which needs to be removed. This component has somehow managed to cover or hide the thing I need.

The bug that has caused this problem is beyond the scope of this post but I believe that it is probably a requirement to log into the admin panel in order to fix the issue.

How do I log in if I can not get the login prompt page to come up as it should?

# Answer
> ### Drush
>
> To get one-time login for the specific user, use this syntax:
>
> ```
> drush uli <user>
>
> ```
>
> Where `<user>` is either uid (e.g. `1`), user name, or email address for the user.
>
> ### Custom code
>
> You can use `user_pass_reset_url()` function in your custom code.
>
> Generates a unique URL for a user to login and reset their password.
>
> Ex:
>
> ```
> $uid = 1;
> $account = user_load($uid);
> $link = user_pass_reset_url($account);
>
> ```

Source: Kenorb's answer to How to get one time login for all the users?
> 1 votes

# Answer
From a browser window append

```
/?q=user

```

to the end of the url

If you've trashed the theme somehow, you might try resetting the theme to default garland with this https://www.drupal.org/node/200774
> 1 votes

---
Tags: 7
---


# Question
Title: Change content of views_field_view field using hook_views_pre_render
I am using the views\_view\_field module for embedding a view inside another view.

I want to concatenate some text with that field in `hook_views_pre_render` based on a condition.

But when I printed the `$view->result` array, that field is not there.

So How can I do this?

# Answer
Try using template\_preprocess\_views\_view\_fields

If you still can't access that field there then:

/sites/all/themes/THEMENAME/**template.php**

```
function THEMENAME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  foreach ($view->field as $id => $field) {
    if ($something == 'some condition') {
      $vars['fields']['nothing']->content = 'some string' . '<br><br>' .
        views_embed_view('view_name', 'view_machine_name', $contextual_filter_value);
    }
    else {
      $vars['fields']['nothing']->content = views_embed_view('view_name', 'view_machine_name', $contextual_filter_value);
    }
  }
}

```

If your view does not need a contextual filter, then it's:

views\_embed\_view('view\_name', 'view\_machine\_name');
> 0 votes

---
Tags: 7, views
---


# Question
Title: "admin/content" filters not available anymore
In the Content page (/admin/content), in Drupal 7 there was a feature allowing to filter by content type, status or language:

>

It doesn't seem to be available anymore in Drupal 8.

>

Someone know if there is a module recreating this feature?

# Answer
You need just to install the Views module that is part of Drupal core. Once you install it, that page appears as the following, which is how I see it in my site.

>

If I uninstall the Views module, that page appears like the following.

>

Now that the Views module is in core, there are many pages that have been converted into views. As you see from the first screenshot, there is a new *Files* tab which is a view.

If you don't see the Views module listed between the modules, download again Drupal, because that means the archive used for the installation is missing some Drupal files, or they have not been correctly copied.
> 6 votes

# Answer
You might have deleted the Content view by mistake. To re-import it, setup a new or another Drupal 8 site. In the new site goto `Configuration > Configuration synchronization > Export Tab > Single Item`, `Configuration type: View`, `Configuration name: Content (content)`. And then copy the contents of the "Here is your configuration". In your original site goto `Configuration > Configuration synchronization > Import tab > Single item`, `Configuration type: View` and paste into "Paste your configuration here" and press Import.
> 5 votes

# Answer
Goto Configuration \> Configuration synchronization \> Import tab \> Single item, Configuration type: View and paste into the code below into "Paste your configuration here" and press Import.

```
uuid: 4095ee08-6690-4d23-a401-fca549d2e42a
langcode: en
status: true
dependencies:
  module:
    - node
    - user
_core:
  default_config_hash: tS8PbpJX90aRFC3-UTgXzdqkq7_2frk2pz4TMijEebM
id: content
label: Content
module: node
description: 'Find and manage content.'
tag: default
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_options:
      access:
        type: perm
        options:
          perm: 'access content overview'
      cache:
        type: tag
      query:
        type: views_query
      exposed_form:
        type: basic
        options:
          submit_button: Filter
          reset_button: true
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: full
        options:
          items_per_page: 50
          tags:
            previous: '‹ Previous'
            next: 'Next ›'
            first: '« First'
            last: 'Last »'
      style:
        type: table
        options:
          grouping: {  }
          row_class: ''
          default_row_class: true
          override: true
          sticky: true
          caption: ''
          summary: ''
          description: ''
          columns:
            node_bulk_form: node_bulk_form
            title: title
            type: type
            name: name
            status: status
            changed: changed
            edit_node: edit_node
            delete_node: delete_node
            dropbutton: dropbutton
            timestamp: title
          info:
            node_bulk_form:
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            title:
              sortable: true
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            type:
              sortable: true
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            name:
              sortable: false
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: priority-low
            status:
              sortable: true
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            changed:
              sortable: true
              default_sort_order: desc
              align: ''
              separator: ''
              empty_column: false
              responsive: priority-low
            edit_node:
              sortable: false
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            delete_node:
              sortable: false
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            dropbutton:
              sortable: false
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            timestamp:
              sortable: false
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
          default: changed
          empty_table: true
      row:
        type: fields
      fields:
        node_bulk_form:
          id: node_bulk_form
          table: node
          field: node_bulk_form
          label: ''
          exclude: false
          alter:
            alter_text: false
          element_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          plugin_id: node_bulk_form
          entity_type: node
        title:
          id: title
          table: node_field_data
          field: title
          label: Title
          exclude: false
          alter:
            alter_text: false
          element_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          entity_type: node
          entity_field: title
          type: string
          settings:
            link_to_entity: true
          plugin_id: field
        type:
          id: type
          table: node_field_data
          field: type
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Content type'
          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: target_id
          type: entity_reference_label
          settings:
            link: false
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: type
          plugin_id: field
        name:
          id: name
          table: users_field_data
          field: name
          relationship: uid
          label: Author
          exclude: false
          alter:
            alter_text: false
          element_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          plugin_id: field
          type: user_name
          entity_type: user
          entity_field: name
        status:
          id: status
          table: node_field_data
          field: status
          label: Status
          exclude: false
          alter:
            alter_text: false
          element_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          type: boolean
          settings:
            format: custom
            format_custom_true: Published
            format_custom_false: Unpublished
          plugin_id: field
          entity_type: node
          entity_field: status
        changed:
          id: changed
          table: node_field_data
          field: changed
          label: Updated
          exclude: false
          alter:
            alter_text: false
          element_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          type: timestamp
          settings:
            date_format: short
            custom_date_format: ''
            timezone: ''
          plugin_id: field
          entity_type: node
          entity_field: changed
        operations:
          id: operations
          table: node
          field: operations
          relationship: none
          group_type: group
          admin_label: ''
          label: Operations
          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
          destination: true
          plugin_id: entity_operations
      filters:
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: group
          admin_label: ''
          operator: contains
          value: ''
          group: 1
          exposed: true
          expose:
            operator_id: title_op
            label: Title
            description: ''
            use_operator: false
            operator: title_op
            identifier: title
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
              anonymous: '0'
              administrator: '0'
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: string
          entity_type: node
          entity_field: title
        type:
          id: type
          table: node_field_data
          field: type
          relationship: none
          group_type: group
          admin_label: ''
          operator: in
          value: {  }
          group: 1
          exposed: true
          expose:
            operator_id: type_op
            label: 'Content type'
            description: ''
            use_operator: false
            operator: type_op
            identifier: type
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
              anonymous: '0'
              administrator: '0'
            reduce: false
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: bundle
          entity_type: node
          entity_field: type
        status:
          id: status
          table: node_field_data
          field: status
          relationship: none
          group_type: group
          admin_label: ''
          operator: '='
          value: '1'
          group: 1
          exposed: true
          expose:
            operator_id: ''
            label: Status
            description: ''
            use_operator: false
            operator: status_op
            identifier: status
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
          is_grouped: true
          group_info:
            label: 'Published status'
            description: ''
            identifier: status
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items:
              1:
                title: Published
                operator: '='
                value: '1'
              2:
                title: Unpublished
                operator: '='
                value: '0'
          plugin_id: boolean
          entity_type: node
          entity_field: status
        langcode:
          id: langcode
          table: node_field_data
          field: langcode
          relationship: none
          group_type: group
          admin_label: ''
          operator: in
          value: {  }
          group: 1
          exposed: true
          expose:
            operator_id: langcode_op
            label: Language
            description: ''
            use_operator: false
            operator: langcode_op
            identifier: langcode
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
              anonymous: '0'
              administrator: '0'
            reduce: false
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: language
          entity_type: node
          entity_field: langcode
        status_extra:
          id: status_extra
          table: node_field_data
          field: status_extra
          operator: '='
          value: false
          plugin_id: node_status
          group: 1
          entity_type: node
      sorts: {  }
      title: Content
      empty:
        area_text_custom:
          id: area_text_custom
          table: views
          field: area_text_custom
          empty: true
          content: 'No content available.'
          plugin_id: text_custom
      arguments: {  }
      relationships:
        uid:
          id: uid
          table: node_field_data
          field: uid
          admin_label: author
          required: true
          plugin_id: standard
      show_admin_links: false
      filter_groups:
        operator: AND
        groups:
          1: AND
      display_extenders: {  }
    display_plugin: default
    display_title: Master
    id: default
    position: 0
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - user
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }
  page_1:
    display_options:
      path: admin/content/node
      menu:
        type: 'default tab'
        title: Content
        description: ''
        menu_name: admin
        weight: -10
        context: ''
      tab_options:
        type: normal
        title: Content
        description: 'Find and manage content'
        menu_name: admin
        weight: -10
      display_extenders: {  }
    display_plugin: page
    display_title: Page
    id: page_1
    position: 1
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - user
        - 'user.node_grants:view'
        - user.permissions
      max-age: 0
      tags: {  }

```
> 1 votes

# Answer
I didnt have the synch option, so I just uninstalled views and re-installed it. That recreated the missing views that I lost somehow.
> 0 votes

---
Tags: 8
---


# Question
Title: why filters are not working in view query alter?
why filters are not working in view query alter here is my code what i am doing wrong:

```
     if ($view->id() == 'answer_key_form' && $view-
     >getDisplay()->display['id'] == 'page_2') {

     $competetive_array=array('234','235' );

           foreach ($query->where as &$condition_group) {
           foreach ($condition_group['conditions'] as
            &$condition) {

            if ($condition['field'] == '

 node__field_akf_select_product.field_akf_select_product_target_id') {

      $condition = array(
        'field' => 'node__field_akf_select_product.field_akf_select_product_target_id',
        'value' => $competetive_array,
        'operator' => 'IN',
      );

    }
  }
}

```

if my url arguments are www.test.com/field\_akf\_select\_product\_target\_id=234 its giving me same result if i pass any random no in url parameter like field\_akf\_select\_product\_target\_id=886 still its giving same result it should show no result found..

# Answer
> 0 votes
I solved it by myself ,i have added condition for operator where i was doing mistake ,on first page load **"IN"** operator will work then **"=" on selection of select list :**

```
  function get_purchased_product_id() {
  //Get current user id
  $user_id = \Drupal::currentUser()->id();

  $uid = ($user_id ==1)? 267 :$user_id;

  $query_get_product_name =  db_select('commerce_order', 'c');
  $query_get_product_name->join('commerce_order_item', 'ci', 'c.order_id = ci.order_id');
  $query_get_product_name->join('commerce_product_variation_field_data', 'cf', 'ci.purchased_entity = cf.variation_id');
  $query_get_product_name->fields('c', ['uid']);
  $query_get_product_name->fields('ci', ['purchased_entity']);
  $query_get_product_name->fields('cf', ['product_id','title']);
  $query_get_product_name->condition('c.uid', $uid,'=');
  $query_get_product_name->condition('c.state', 'completed','=');
  $result = $query_get_product_name->execute();

  $arr_var=array();

  foreach ($result as $value ){
  $arr_var[]= $value->product_id;
   }
  return $arr_var;

 }

 function classroom_common_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

if ($view->id() == 'answer_key_form_management' && $view->getDisplay()->display['id'] == 'page_2') {
  //function call to get product id of purchased item by current user
  $arr_product_id = get_purchased_product_id();

  $product_target_id = Drupal::request()->query->get('field_akfp_select_product_target_id');
  if(!empty($product_target_id)){
     $arr_product_id = $product_target_id;
  }
  $operator = !empty($product_target_id) ? '=' : 'IN';

foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'node__field_akfp_select_product.field_akfp_select_product_target_id') {

          $condition = array(
            'field' => 'node__field_akfp_select_product.field_akfp_select_product_target_id',
            'value' =>  $arr_product_id,
            'operator' => $operator,
          );

        }
      }
    }
}

```

---
Tags: 8
---


# Question
Title: Programmatically auto-submit a Webform after visiting its URL
I am wondering whether it's possible to programmatically auto-submit a Webform after visiting its URL and to save the user from a 'submit' button click.

The below webform can be accessed via `/form/my-invoices`:

and has 3 elements:

* Key: invoice\_number
* Key: amount
* Key: seller\_name

**Use Case:**

I have paper invoice with a printed barcode and a barcode reader device.

When a user will scan the barcode on the paper invoice, The barcode result will be generated and the user will be redirected to:

```
www.example.com/form/my-invoices?invoice_number=123456789&amount=1200&seller_name:john-smith

```

I want to **auto-submit the Webform** when the above link will be visited !

**So in steps, below what will really happen:**

1. A user will scan the barcode.
2. Barcode will then redirect the user to `www.example.com/form/my-invoices?invoice_number=123456789&amount=1200&seller_name:john-smith`
3. **AUTOMATICALLY, the elements of the webform (form/my-invoices) will be populated from the link query parameter and the webform will be auto-submitted without having the user to click on the "Submit" button.**
4. After auto submit of the webform, the user will be redirected to: `/specific-url` and with a confirmation message something similar to: "the webform has been auto-submitted on your behalf".

So in summary, how to programmatically auto-submit a webform when the webform url with query parameters is visited ?

Thanks!

---

**UPDATE #2 (edit #2):**

After changing the route path to: `/form/my-invoices/autosubmit` and visit that page, the webform is indeed successfully submitted by **there is no value validation occured**:

**autosubmit\_barcode\_results.routing.yml**

```
autosubmit_barcode_results.autosubmitform:
  path: '/form/my-invoices/autosubmit'
  defaults:
    _controller: '\Drupal\autosubmit_barcode_results\Controller\AutoSubmitBarcodeController::autosubmitform'
  requirements:
    _permission: 'access content'

```

**AutoSubmitBarcodeController.php**

```
<?php

namespace Drupal\autosubmit_barcode_results\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\webform\Entity\Webform;
use Drupal\webform\WebformSubmissionForm;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

class AutoSubmitBarcodeController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   */
  public function autosubmitform() {

// Get and prepare variables.
$request = Request::createFromGlobals();
$invoive_number = $request->query->get('invoive_number');

// Get submission values and data.
$values = [
  'webform_id' => 'my_invoices',
  'entity_type' => NULL,
  'entity_id' => NULL,
  'in_draft' => FALSE,
  'uid' => '1',
  'langcode' => 'en',
  'token' => 'pgmJREX2l4geg2RGFp0p78Qdfm1ksLxe6IlZ-mN9GZI',
  'uri' => '/webform/my_invoices/api',
  'remote_addr' => '',
  'data' => [
    'invoice_number' => $invoice_number,
  ],
];

// Validate submission.
  $errors = WebformSubmissionForm::validateFormValues($values);

// Check there are no validation errors.
  if (!empty($errors)) {
     $message = $errors['invoice_number'];
     $message = drupal_set_message($message, 'error');
     return $message;
  }
  else {
// If no validation errors, then Submit values and get submission ID.
    $webform_submission = WebformSubmissionForm::submitFormValues($values);

// Redirect the user.
return new RedirectResponse('/all-my-scanned-invoices');

// Show a success message to the user on the redirected page.
 $mesagesuccess = 'New invoice has been successfully scanned.';
 $mesagesuccess = drupal_set_message($mesagesuccess, 'status');
 return $mesagesuccess;

    }
  }
}

```

**However when an invoice is scanned twice,** the `$error` is being displayed properly but along with another error:

```
You have already scanned this invoice once, please scan another one!

User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core\lib\Drupal\Core\Render\Element.php).
Drupal\Core\Render\Element::children(Array, 1) (Line: 408)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 450)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

# Answer
You can do it basically in 3 steps:

1.Get and prepare your variables:

```
use Symfony\Component\HttpFoundation\Request;
$request = Request::createFromGlobals();
$invoice_number = $request->query->get('invoice_number');
$amount = ...;
$seller_name = ...;

```

2.Create a submission when `/form/my-invoices` is requested and all of three variables are present/valid. (meet whatever conditions applicable to your case). This step can be done in various ways, such as a controller/service, or a preprocess hook...Well, step 1 and 3 are actually all part of this function.

The preprocess function (mymodule\_preprocess \_page(&$var)) can go into the `my_module/my_module.module` file, while a controller can go into `my_module/src/Controller/FormSubmitController.php` file.
Preprocess function does check all incoming requests, but as long as you `return` early, it's not too bad IMO... However the Drupal8 OOP elegant way is to provide a route and trigger the controller when route is active. You can look up some tutorials on that topic. For validating your webform, search for webform validation tutorials.

3.Upon successful creation, use

```
use Symfony\Component\HttpFoundation\RedirectResponse;
return new RedirectResponse('http://yoursite.com/specific-url');

```

Do a security check on the variables before the submission creation if necessary and you should be all set.

**Update about validation question:**

First of all, if your barcode is capable of generating unique invoice numbers, and as long as you make sure it doesn't get altered before the submit function is triggered, we don't necessarily have to validate it.
In this specific case, I believe all you need to do is going into the webform build page, and check the `unique` box for the invoice\_number field. The great Webform module already has it built in so if there's an duplicate, it will not submit, and you will have something in the `$error` variable. You can get the error message and display it however you want.

Check this page for all the methods you can use on \Drupal::messenger()

```
// Validate submission.
  $errors = WebformSubmissionForm::validateFormValues($values);

// Check there are no validation errors.
  if (!empty($errors)) {
    //$message = $errors['invoice_number'];
    // \Drupal::messenger()->deleteAll(); use this if you don't want to show the field level error message. It delete all messages.
    \Drupal::messenger()->addError(t('An error occurred and processing did not complete'));
    $render = [
        '#type' => 'StatusMessages', // use this render array type to display messages.
    ];
    return $render;
  }
  else {
// If no validation errors, then Submit values and get submission ID.
    $webform_submission = WebformSubmissionForm::submitFormValues($values);
    \Drupal::messenger()->addMessage(t('New invoice has been successfully scanned.'));
    return new RedirectResponse('/all-my-scanned-invoices');
  }

```
> 1 votes

---
Tags: 8, forms, webforms, uri
---


# Question
Title: How to disable views pager programatically in certain cases
I have a paragraph which shows a view. The editor may set some options as argument filters, sort and show/hide pager. "Normal" fields are used to collect these options and `template_preprocess_paragraph__PARAGRAPH_TYPE` actually builds the view. The filtering works well, but I am not able to get rid of the pager if the editor desires to disable it while limiting the amount of items shown at the same time (`$view->setItemsPerPage(0);` is not an option here). Here is some simplified code from mytheme.theme:

```
function mytheme_preprocess_paragraph__content_list(&$variables) {
  $view = Views::getView('content_list');
  if (!$view) {
    return;
  }

  // Simulate user input:
  $order = 'DESC';
  $disable_pager = TRUE;
  $items_per_page = 12;
  $filter_args = [1,2,3,4];

  $display_id = 'embed_content_list_title';
  $view->setDisplay($display_id);
  $view->setHandlerOption($display_id, 'sort', 'title', 'order', $order);

  if ($disable_pager) {
    $display = $view->getDisplay();
    $pager = [
      'type' => 'none',
      'options' => [
        'offset' => 0,
        'items_per_page' => 50,
      ],
    ];
    // This doesn't work:
    $display->setOption('pager', $pager);
    $display->setOverride('pager', $pager);
    // This neither works:
    $view->display_handler->setOption('pager', $pager);
    $view->display_handler->setOverride('pager', $pager);
    // I also had no luck with:
    $view->pager = NULL;

    $view->setItemsPerPage($items_per_page);
  }

  $view->execute();
  $variables['content']['content_list'] = $view->buildRenderable($display_id, [$filter_args]);
}

```

How can the pager be disabled in above code? A workaround might be using different displays, one with pager enabled and another with pager disabled. But I would prefer to solve it with just one display (as I already have multiple displays and would have to build both versions for each display).

# Answer
Piggybacking off How to set views pager item size programmatically? and looking at PagerPluginBase.

To change values

```
if ($disable_pager == FALSE) {
  $view->setOffset(0);
  $view->setItemsPerPage($items_per_page);
}

```

---

Now to answer your question

> How can the pager be disabled in above code?

You can disable it by setting items per page to zero.

```
$view->setItemsPerPage(0);

```

If you want to limit the amount of items without pager, all you have to do is unset it.

```
   $view = Views::getView('content_list');
   $display_id = 'embed_content_list';
   $view->setDisplay($display_id);
   $view->setItemsPerPage(12);
   $view->execute();
   unset($view->pager); // must put this unset after the $view->execute();
   $variables['content']['content_list'] = $view->buildRenderable($display_id, [$filter_args]);

```
> 1 votes

---
Tags: views, 8, paragraphs
---


# Question
Title: Multiple path aliases based on taxonomy term
I have taxonomy terms from A-Z and each article can belong to multiple terms.

for an example, when I create a new article, I have a multi select list for terms. Therefore a particular node should work for multiple URLs.

example.com/categories/a/planning
example.com/categories/g/planning
example.com/categories/s/planning

Please let me know if this can be achieved using a contributed module or can it be built with a custom module?

# Answer
> 1 votes
You can use pathauto module. After installing the pathauto module, please configure the path of `article` content type from here `admin/config/search/path/patterns`.

**Note:** To use pattern require token module.
Then use like following pattern:

```
categories/[node:field-token-of-term-reference-field]/[node:title]

```

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


# Question
Title: How can I ensure automatically that a module is disabled on my live site?
I'm using a development -\> staging -\> live server workflow, and all three sites run off the same Git repository. The repository contains a few modules (a custom module for Selenium testing, etc.) that I never want to run on the live site.

Is there a way (in `settings.php`, perhaps?) to block a module from ever being enabled? I suppose I could also remove it from the repository, but my workflow is easier if I keep everything together.

# Answer
> 5 votes
In the standard Drupal deployment methodology, only *code* is move from dev -\> stage -\> prod, and only the *database* moves from prod -\> stage -\> dev. Since modules' enabled state is stored in the database, if you follow this workflow, you do not need to worry about your dev modules becoming enabled in production.

Your problem then becomes the inverse: how to insure that your dev modules are automatically enabled for you when you move your database to dev. If you use Drush sql-sync to move your database, then the example file sync\_enable.drush.inc shows how to enable dev modules as a post-sql sync task. You can also automatically disable production-only modules such as securepages if you wish.

# Answer
> 8 votes
You can hide modules from the admin UI by using the `hidden` property in the module's `.info` file:

```
hidden = TRUE

```

This method might be useful if you want to make sure the module is never enabled via the UI.

In case you're interested in how to do the opposite (stop a module from being disabled), it's also done in the `.info` file by setting the `required` parameter:

```
required = TRUE

```

Once you've done that Drupal will see the module as a 'core' module and stop it from being disabled through the admin UI.

# Answer
> 3 votes
There is a module that does almost exactly what you ask: Environment Modules. The only difference is that is does not *disable* modules based on the environment (dev/staging/production), but it *enables* them. That means that your normal site configuration should contain only the modules you need on the live site, and you configure Environment Modules to enable additional development modules only on the dev server.

If you decide to try/use this module, I'd like to hear how it works for you.

# Answer
> 1 votes
I'm not aware of a supported way to "block" a module. You could attempt to force the issue by having a module with a high weight that does

```
db_query("DELETE FROM system WHERE name IN ('module 1', 'module 2')");

```

but that seems like risky business.

I would do it in some form of deployment script, that you probably have anyway to handle the dev-\>stage-\>production workflow. My team keeps a build configuration with each site that is used to deploy the site. It would then be easy to have a list of modules that should be removed after each deploy on the production server.

# Answer
> 1 votes
Checkout the Habitat module. It allows you to set modules that should be enable or disabled on the different environments you have. You can set this in settings.php. I use a settings.php that loads an environment specific settings.php and in these I have the habitat setting for each environment.

# Answer
> -2 votes
You can check it with `module_exists`

```
if (module_exists('mymodule', 1.2) {
  if($myliveip == 'myliveip')
   drupal_uninstall_module('mymodule');
}

```

And call this in your modules `hook_init` API

---
Tags: 7
---


# Question
Title: Link to content in views doesn't translated to fr
I made a content ( type = article). I made a view ( list of articles) and i add link to content. I activate fr language in the site =\> so

www.example.com/liste-des-articles =\> english page.

www.example.com/fr/liste-des-articles =\> french page.

My problem is the link to content doesn't work correcly in french =\> when i click to it =\> redirection to english page.

what shall i do ??

Thanks for the response.

# Answer
One way to solve this would be to construct the "Link to content" field on your own, using Views. You will need to:

1. Add 2 fields to your view:
    * a "Content: Node ID (Node ID)" field
    * a "Content: Translation language (Translation language)" field.
2. Exclude the "Content: Node ID" field from display.
3. Rewrite the "Content: Translation Language" field as a custom link.
The text in the "Rewriting" would look something like this:
***Link path: {{ langcode\_value }}/node/{{ nid }}***

Hope this helps!
> 6 votes

# Answer
Until the core issue gets resolved here is a **SIMPLE** workaround that produces aliased URL

1. add ID as field and exclude from display
2. use the following code whereever you want the translated node url

`{{ path('entity.node.canonical', {'node': nid}) }}`
> 3 votes

# Answer
it seems to be a bug in Drupal 8.3 views module at the time

but based on @Stefanos answer I suggest using `Content: Path` field and then exclude it from display, following Stefanos answer instead of:

> Link path: `{{ langcode_value }}/node/{{ nid }}`

you can just try `{{ path }}`

it's better this way just too keep your URL aliases working
> 2 votes

# Answer
The solution of @Sohail is better, because it is generating the URL Alias of a content instead of the poor "/en/node/1" Drupal native link.

However, if you need to also translate the link text, and are not afraid of editing your twig template, you can use the twig path() function :

* Add the nid (Content ID) field to your view, and exclude it from display
* Edit your fields template\[views-view-fields.html.twig\], using overriding if possible
* Add the following code for your link :

\< a href="{{ path('entity.node.canonical', {'node': fields.nid.content|striptags|trim }) }}"\>{% trans %}Text to translate{% endtrans %}

Infos :

* The {% trans %}XXX{% endtrans %} twig block allow string translation.
* The fields.FIELD\_NAME.content allow you to print only one field value
* The striptags filter is to avoid HTML tags (nice if you use theme debug)
* The trim filter is to remove all spaces left
> 2 votes

# Answer
Currentlhy there seems to be a working patch about this core issue

Make sure the patch from comment #24 is the latest working patch and apply as follows using drush

```
cd DRUPAL_ROOT_DIR
wget https://www.drupal.org/files/issues/2018-08-06/2877994-57.patch
git apply -v 2877994-57.patch

```
> 1 votes

# Answer
Some of us have multilingual sites where the main language uses no language code in the URL, but translations do. In such cases the /{{ langcode }}/node/{{ nid }} solution doesn't work.

Currently in Drupal 8.5 Views won't let you select that Title field's URL in a rewrite, but you can get around this with JavaScript and CSS. You then just hide that linked Title field with CSS, and use JS to set link 'read more' text to that linked Title field's URL. For example:

1. Add a linked Title field (rather than "Link to Content"), and then exclude it.
2. Add a Custom HTML field. Let's suppose it has a field class of views-field-nothing
3. Add JavaScript to run on .ready:

$(".some-custom-class-view .views-row").each(function(){ var thislink = $(this).find(".views-field-title a").attr("href"); $(this).find(".views-field-title a").hide(); $(this).find(".views-field-nothing").(''); });
4. Add CSS: .some-custom-class-view .views-field-title{display: none;}
> 0 votes

# Answer
There's a bug in core that shows a link to the same language when your label field (title/name) isn't translatable.

See https://www.drupal.org/project/drupal/issues/2447821
> 0 votes

---
Tags: views, 8
---


# Question
Title: Display a view block with a list of content excluding the one currently displayed on the page
I sometimes use contextual filters to display fields matching the content ID from url

In that case , i would like to display a list of content as a view block , except the one that is displayed

It would require to :

* negate the condition " Content ID from URL contextual filters "

or

* being able to choose the 'content id from url' as value of a view filter

I don't know how to do the first option. That token conditions module would do for the second option but is not stable https://www.drupal.org/project/token\_conditions

How can i possibly do that then except JS?

# Answer
Considering the first option, it is simple :

add a contextual filter of type "ID: Content" with the following configuration :

* WHEN THE FILTER VALUE IS NOT AVAILABLE \> provide a default value \> content id from url
* Go all the way down in the "more" section, expand it and check "exclude".
* Then click apply
* And save the views

That's it !
> 3 votes

---
Tags: views, 8, blocks
---


# Question
Title: How to create a rule and inject mysql code?
Can I create a rule on my drupal 7 website and that rule will:

Whenever a user is logged in (only logged in users can see this content) and a certain content is clicked I want to write a mysql update statement to my database. The user name of that person and what content was clicked.

I know I can execute PHP code for my action but not sure if I need to somehow convert mysql and php together? please if anyone knows and could give a fairly detailed instructions I would appreciate it greatly!

# Answer
> 0 votes
Instead of creating a security breach in your site (logged in user is not bullet proof and relies maybe a bit too much on trust of user's sense of responsability considering keeping strong password and clean browsers, closing sessions...), I would suggest to look into the existing statistics module and match the objective by configuration and customisation. It is not possible to give you the right answer because it depends on a lot of variables, but here are a few links to dig and find your solution:

Statistics documentation:

Google Analytics modules:

I think you could do pretty much what you want with GA + Rules: https://www.drupal.org/node/37694,

Other statistics modules:

EDIT : Also you could use views to generate an output of the necessary information and an export in csv to make it even better

# Answer
> 0 votes
Yes you can use PHP within some custom rule, and then include your SQL statements. But that requires PHP code to be stored in your Drupal database ... which is ***bad*** (repeat: ***bad***).

I recommend you to not go that path. But instead you should use the Message module, to create the equivalent of those database records you want to create.

Have a look at my answer to "How to create audit trails/order revisions?", which is like a variation of your question, and which explains how the Message module integrates with the Rules module to get this to work. Did I mention zero custom (PHP) code?

---
Tags: 7, database, rules
---


# Question
Title: Migrating body text from 7 to 8, markup displays until edited and saved
I'm migrating nodes and have run into a problem with the text formats when mapping our old site's input formats to the new site's input formats. (We're simplifying!)

Relevant yaml:

```
  body:
    plugin: sub_process
    source: body
    process:
      value: value
      format:
        plugin: static_map
        bypass: true
        source: body_format
        map:
          'plain_text': basic_html
          'basic_tags': basic_html
          'minimal_formatting': basic_html
          'filtered_html': basic_html
          'extended_tags': full_html
          'full_html': full_html

```

When I run this, all the content and formats are imported correctly, but the nodes all display the markup on the page until each node is edited and saved.

What could be causing this and how might I go about fixing it?

# Answer
```
source: body_format

```

should have been

```
source: format

```

Turning off "bypass: true" let me see that it was just dumping them in with NO input set, opening and saving changed it to the default for that field.
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: How to change image style using hook_views_pre_render()
I am trying to adapt the following Drupal 7 code to Drupal 8, in order to set a different image style to every image in a view:

```
// Assigns a random style name to each image
function <MODULE_NAME>_views_pre_render(&$view)
{
  if($view->name == 'SOME VIEW')
  {
    $styles = array('thumbnail', 'medium', 'large');
    foreach($view->result as &$result)
    {
      $result->field_field_image[0]['rendered']['#image_style'] = $styles[array_rand($styles)];
    }
  }
}

```

Right now I have:

```
function <MODULE_NAME>_views_pre_render(ViewExecutable $view)
{
  if($view->id() == 'SOME VIEW')
  {
    $styles = array('thumbnail', 'medium', 'large');
    foreach($view->result as &$result)
    {
      $image = $result->_entity->get("field_media_image");
      $image->SOME_FUNCTION('#style_name') = $styles[array_rand($styles)];
    }
  }
}

```

However, I can't figure out what SOME\_FUNCTION would be -- There does not appear to be any way to access the render array from an ImageItem object.

# Answer
I gave up on `hook_views_pre_render` and wound up meeting my requirements with `template_preprocess_image_formatter` as follows:

```
function <TEMPLATE_NAME>_preprocess_image_formatter(&$variables) {
  $styles = array('thumbnail', 'medium', 'large');
  if ($variables['image']['#style_name'] === 'medium') {
    $variables['image']['#style_name'] = $styles[array_rand($styles)];
  }
}

```
> 2 votes

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


# Question
Title: User error: "1" is an invalid render array key in Drupal\Core\Render\Element::children()
I want to print "your\_variable" (array) in my twig template, but i have errors.

I have .theme in my theme :

```
function MYTHEME_preprocess_views_view_fields(&$vars) {
   $tempstore = \Drupal::service('user.private_tempstore')->get('evenementrimouski');
   $some_data = $tempstore->get('nid');
   $vars['your_variable'][] = array(3,4,5,6);
}

```

My "views-view-field" twig :

```
{% for  value in your_variable %}
    {{ value }}
{% endfor %}

```

The code work but i have errors :

```
User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

User error: "1" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

```

Someone have idea to resolve this problem ?

I use Drupal 8

# Answer
Remove the brackets after the `['your_variable']` part as your variable holds only 1 array:

```
function MYTHEME_preprocess_views_view_fields(&$vars) {
   $tempstore = \Drupal::service('user.private_tempstore')->get('evenementrimouski');
   $some_data = $tempstore->get('nid');
   $vars['your_variable'] = [3,4,5,6];
}

```

Also use the short array syntax. It's part of the new coding standards: https://www.drupal.org/node/2135291
> 3 votes

# Answer
To answer your question, the error you are seeing is because `$vars['your_variable']` is an array containing an array. `var_dump($vars)` would output the following.

```
array(1) {
  ["your_variable"]=>
  array(1) {
    [0]=>
    array(4) {
      [0]=>
      int(3)
      [1]=>
      int(4)
      [2]=>
      int(5)
      [3]=>
      int(6)
    }
  }
}

```

In that case, the array is expected to be a render array. That is way you get the error you see.

I assume you aren't showing the code you are using, though, since defining a literal array in a preprocess function to print it with Twig doesn't make much sense. At least, you could do that directly in Twig.

```
{% set your_variable = [3, 4, 5, 6] %}
{% for  value in your_variable %}
    {{ value }}
{% endfor %}

```

Does `$tempstore->get('nid')` returns an array of integers that you need to assign to `$vars['your_variable']`, and print it with Twig? Just use the following code.

```
function MYTHEME_preprocess_views_view_fields(&$vars) {
   $tempstore = \Drupal::service('user.private_tempstore')->get('evenementrimouski');
   $vars['your_variable'] = $tempstore->get('nid');
}

```

Are you creating an array of integers by merging different arrays of integers? Merge `$vars['your_variable']` with the other arrays.

```
// Before you initialize $vars['your_variable'] to an empty array.
// $vars['your_variable'] = [];
$vars['your_variable'] = array_merge($vars['your_variable'], $your_other_array_of_integers);

```

Are you adding integers to `$vars['your_variable']`, which will be an array of integers?

```
// Before you initialize $vars['your_variable'] to an empty array.
// $vars['your_variable'] = [];
$vars['your_variable'][] = $your_integer;

```
> 0 votes

# Answer
Often is a situation that you would need to iterate an array by keys, so in this context, be sure to create the multidimensional array ( keep the appended \[\] ) and then use a key to iterate, such as:

```
{% for key,collection in collections %}
  <div>
    {{ collection[key] }}
  </div>
{%  endfor %}

```

And the preprocess function would look something very similar as written in the original question where 'your\_variable' in this case would be collections, and the collections array would be populated using a for/foreach within that function such as:

```
 function mytheme_preprocess_node(&$vars) {
   $collection = $vars['content']['field_story'];
   $item_count = $collection['#items']->count();
   for ($i=0 ; $i < $item_count ; $i++) {
     $vars['story_title'][] = $collection[$i]['#title'];
   }
 }

```

...
> 0 votes

---
Tags: views, theming
---


# Question
Title: How to set time limit only for one php file?
I have a script which walks through database table, makes some checks and based on them it makes notifications for website users. It works for a pretty long time. Currently in dev it takes a minute for every user. So I think I need to set max execution time(.htaccess, php etc) to 0 for this one.

Currently it's launched from "drupal page with form", later I'll be launching it with `cron`. Drupal is not letting me set `set_time_limit(0)` because it's not the beginning of file where I can put it. But I don't want to `set_time_limit(0)` for whole website.

Is there a way bypass this limitaion? Maybe some external script execution? I'd like to remain Drupal functionality in it.

# Answer
Don't do this. While it is possible to do this, using `set_time_limit(0)` is giving your server free rein to execute indefinitely; you're setting yourself up for server instability.

If you have a large workload that you need to execute in a Drupal context, use its Queue API. This API will let you queue up a list of items to process (i.e. the table rows you're checking) and process them with a queue worker (i.e. the task that "does the checks" and generates user notifications).

You can find many examples of creating a queue and a queue worker by searching Google for \[drupal 8 queue api\].
> 1 votes

---
Tags: 8
---


# Question
Title: Get node form inside preprocess_views_view_fields()
how can I get the node id through the : preprocess\_views\_view\_fields()

# Answer
> 1 votes
You can get nid (node id) from $vars as like following:

```
$vars['row']->nid

```

You can also check the `$vars` to view the structure of the object as like following:

```
dpm($vars);

```

To use `dpm();` you have to install devel module.

---
Tags: views
---


# Question
Title: How do I alter webform values before submission?
I am trying to add some values to a hidden field in my webform before submission. Is there any hooks to access webform submission in Drupal 8? I tried How do I modify a webform submission field right before it is saved? without luck.

# Answer
The answer linked is mostly right, just a couple of updates to get it working. In a custom .module add:

```
use Drupal\Core\Form\FormStateInterface;

function MODULENAME_form_alter(&$form,$form_state, $form_id) {
  if ($form_id == 'FORMID') {
    $form['actions']['submit']['#validate'][] = 'MODULENAME_form_validate';
  }
}

function MODULENAME_form_validate($form, FormStateInterface $form_state) {
  $form_state->setValue('hidden_id', 'Value for Hidden field');
}

```
> 7 votes

# Answer
To alter webform values before submission -

In my code, I am changing the timestamp from "Y-m-d HH:MM:SS" to "Y-m-d" format and changing it before saving to DB. Also, i am creating a custom module name as "webform\_presave"

```
/**
 * Implements hook_ENTITY_TYPE_presave().
 */

function webform_presave_webform_submission_presave(\Drupal\webform\Entity\WebformSubmission $submission) {
  $submissionCreated = $submission->getCreatedTime();
  $submissionCreatedChnaged = format_date($submissionCreated, 'custom_date');
  $a = strptime($submissionCreatedChnaged, '%Y-%m-%d');
  $timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
  $submission->setCreatedTime($timestamp);
}

```
> 2 votes

---
Tags: 8, webforms
---


title: Image styles do not work

text:
# Question
Title: Image styles do not work
I am struggling to find a solution for image styles not getting generated. The original pictures get uploaded to the server but no styles or thumbnails are generated.

I have checked folder permission and set it to 775 and even 777 (temporarily) for the /styles/ and its subfolders.

I even set `$conf['image_allow_insecure_derivatives']` to `TRUE`.

Yet I still get access denied for the anonymous users (not verified when I upload images and no styles or thumbnails).

Any suggestions are greatly appreciated.

# Answer
Drupal version 8.5.3 Local dev with Aquia Dev Desktop.

I've tried all combinations with `.htaccess` (root, in `/files` and in `styles`) with no success.

Also tried with:

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

```

No results.

Even though I had a `settings.local.php` **solution** was to uncommment this line in `settings.php`:

```
$settings['file_public_path'] = 'sites/default/files';

```
> 6 votes

# Answer
I also had problems with image styles not generating and it turns out it was because mod\_rewrite wasn't enabled in my apache2. Hope it helps someone
> 4 votes

# Answer
This worked for me

added these lines in `settings.php`

```
$settings['file_public_path'] = 'sites/default/files';
$config['image.settings']['suppress_itok_output'] = TRUE;
$config['image.settings']['allow_insecure_derivatives'] = TRUE;

```
> 4 votes

# Answer
By adding this line in setting.php this problem will be resolved and image will appear.

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

```
> 3 votes

# Answer
I have spent more than 48 hours looking for a solution for a Drupal 8 site and I have finally **SOLVED** it. I have tried any possible nginx config suggested everywhere, including this and the one found here. Also checked any possible permissions issues on files and folders on the whole project to no avail...

What I found is that when uploading an image the system never got to write it to the image style folder... I discovered this when I created a new image style I realised the folders for that image style created correctly and the demo image was placed correctly as well.

Hinted by another user I turned my efforts to the temporary folder which drupal passes images through to generate image styles. I found that I have accidentally set a temporary folder within drupal filesystem, the setting was: `temp` in *Configuration \> File system \> Temporary directory*. This folder probably had wrong permissions and maybe it was the linux t permission also known as sticky bit that drupal needed for this. When I changed the temp folder location to `/tmp` (I'm on centos) image styles worked like a charm again immediately!!

Hope this helps someone...

---

## Update

I run into this problem again, but the solution was a bit different. If the above does not work for you and you use nginx, make sure you have the correct nginx directives which can be found here: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/
> 2 votes

# Answer
I've tried this /tmp folder trick and it didn't work for me; what did though is this: In .htaccess file in /sites/default/files folder i've changed this:

```
Options -Indexes -ExecCGI -Includes -MultiViews

```

to this

```
#Options -Indexes -ExecCGI -Includes -MultiViews
Options +SymLinksIfOwnerMatch

```

Have no idea if it has a security issue or anything else, since i'm total zero in this things, but it worked :) Well, I also have all the folders in /sites/default/files 775'd, including files itself.

**UPDATE #1!** Actually, only commenting the first line like this

```
#Options -Indexes -ExecCGI -Includes -MultiViews

```

works for me, so one of those options standing on our way to image styles. I don't know exactly which one, please feel free to play with them.

**UPDATE #2!** Actually, the update #1 works only in conjunction with the following setting in the hosting panel for my domain:

```
Use Apache instead Nginx for handling the static files like .jpg .gif .js .css .rar .exe .mp3 etc.

```

Yes, I have this setting in the hosting panel.

So, seems like it's final - the two things - ***commenting Options in the .htaccess and use Apache instead of Nginx***
> 1 votes

# Answer
As for me, the issue with broken thumbnails was fixed in nginx config

when I added "location" directive below

```
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$
{
    try_files $uri @rewrite;
    expires max;
    log_not_found off;
}

```

and restarted server, it was never appeared

( using drupal 8.6.13 )

permissions of `sites/default/files/styles` are 777 for nginx user (owner of it)
> 1 votes

---
Tags: media
---


# Question
Title: How to add a condition for an array on an entity query for a config entity?
I want to execute an entity query on a config entity type. However when I want to add an `IN` condition on a property which is an array I am getting an error.

For example, I want to retrieve all user roles that have the `administer nodes` permission:

```
$query = \Drupal::entityTypeManager()->getStorage('user_role')->getQuery();
$query->condition('permissions', ['administer nodes'], 'IN');
$query->execute();

```

This gives the following error:

```
PHP Warning:  mb_strtolower() expects parameter 1 to be string, array given in core/lib/Drupal/Core/Config/Entity/Query/Condition.php on line 166

```

# Answer
A config entity doesn't use a normalized table structure, so the normal array conditions which use JOIN don't work. Instead do a condition on `property.*`:

```
$query = \Drupal::entityTypeManager()->getStorage('user_role')->getQuery();
$query->condition('permissions.*', 'administer nodes');
$query->execute();

```
> 1 votes

---
Tags: 8
---


# Question
Title: How do I convert "entity:node/9 in a link?
I need to get some values from a custom block I've created, and I am using the following code.

```
// Get the block
$block = \Drupal\block\Entity\Block::load('hightlight');

// Get the block content
$uuid = $block->getPlugin()->getDerivativeId();
$block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);

// Get the field value
$field = $block_content->get('field_link')->getValue()[0];

```

The problem is that the field contains *entity:node/9*. Is it possible to convert that value in a link?

This is the content of the field.

# Answer
You have to rewrite

```
$value = $block_content->get('field_link')->getValue()[0];

```

to something like this:

```
$value = $block_content->get('field_link')->first()->getUrl()->toString();

```

See What is the correct way to get the link url?
> 0 votes

---
Tags: 8, blocks
---


title: Failed User Login

text:
# Question
Title: Failed User Login
I have developed a website in Drupal 8 and have deployed it to production. I have created 7-8 other accounts for my content management team and have granted them limited privileges for creating, editing and deleting content.

Of late, I am facing a problem with the user login form, wherein the login works sporadically. Sometimes I am able to log in as the administrator in the first attempt, sometimes I am not. In the latter case, I have to reset my password via email using the reset password option. However, this approach works only temporarily for a single session, which means that as soon as I log out, I am unable to log in. My content managers are also experiencing the same problem.

I have tried the below things but no luck.

1. Truncating the flood, session and all the cache tables and flood table manually from the database.
2. Disabling the Recaptcha module in the login form.
3. Enabling and disabling the HTTP Basic Authentication module.
4. Disabling server proxy configuration through the `settings.php` file.
5. Performing Drupal updates by running the `update.php` file.

The incorrect username and/or password error in the login has not been handled. When an incorrect username/password is entered the page only refreshes without displaying any custom message.

Please help!

# Answer
> 0 votes
Okay, after much banging my head over the wall for nearly a week, I have found a workarpund solution to this problem by uninstalling Internal Dynamic Page Cache and Internal Page Cache modules.

The problem was that the user login form was getting cached after one successful login. Using the Chrome developer tools the following response header was getting set and sent by Drupal.

```
X-Drupal-Dynamic-Cache: HIT

```

To elimnate this I had to uninstall the above two modules.

However this is just a workaround and not a solution, since disabling these two modules will have a tradeoff with the site performance.

Anyone who knows the solution to this problem, please post it here. I shall try them and update this space.

Thank you in advance.

---
Tags: configuration
---


# Question
Title: Contextually filtering a view using values from a completely separate table?
I have a table "user\_connections"

```
id | uid1 | uid2
1  | 1    | 2
2  | 3    | 1
etc

```

So, if the current user has uid = 1, then according to my table, he is "connected" to use 2 and 3. So I just want to be able to do something like:

```
select uid1 from user_connections where uid2 = :currentUserUid

```

Then pass these uids as a parameter to the view. So that it is ultimately used as a "where in" condition.

Any ideas how to do this? Or what is the best way?

# Answer
> 1 votes
Make sure you check mark allow multiple values on your contextual filter's "More" settings.

Use hook\_views\_pre\_view to pass your uid's to the arguments (contextual filter).

```
/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() == "view_name" && $view->current_display == 'page_1') {
    $uids = [2, 19]; // hard coded example, you would query db here.
    if (is_array($uids)) {
      $uids = implode('+', $uids);
    }
    $args[0] = $uids;
  }

}

```

You will also need to disable the view's caching or add a cache tag if you created one for your other table query.

---
Tags: views, 8
---


# Question
Title: How can I use a content type field on the body of the e-mail message template on the Webform module?
For usability matters, I would like to let the editor create his own confirmation message on my Event content type. So I create a field for that. I also have another field to select which webform is going to be used as a reference (I am doing that the same way that was done on the Event Demo that comes on the module).

Is there a way to use this content type field on the e-mail handler on the webform as a token or something like that?

# Answer
> 0 votes
After looking more the examples, I found this token:

```
[webform_submission:node:field_name_of_the_field]

```

I needed only to replace field\_name\_of\_the\_field with the field I want to use.

---
Tags: 8, forms, webforms
---


# Question
Title: Why is Twig not outputting this correctly?
I have

```
function hook_theme_preprocess(array &$variables, $hook) {
    $variables['bla'] = ' AA <strong> BB </strong> CC ';
}

```

In my template I have:

```
{{ bla }}

```

The problem is, in some cases the html is stripped. Even if I do this:

```
{{ bla | raw }}

```

This works fine on all pages where this template is used, except on the home page. On the home page, for some bizarre reason, it strips the HTML.

Any idea as to why there would be different behaviour depending on which page I am on?

# Answer
It's unsafe to use the `|raw` filter. Put HTML markup in a `#markup` element instead:

```
$variables['foo'] = [
  '#markup' => ' AA <strong> BB </strong> CC ',
];

```

Then outputting this variable in Twig should work:

```
{{ foo }}

```
> 2 votes

---
Tags: 8, theming
---


title: Change html tag in template file tpl

text:
# Question
Title: Change html tag in template file tpl
I have this template file for a view:

```
views-view--ir-news--page.tpl.php

```

But right now, I need to use Google AMP only for this view (Machine name: ir\_news) What I want to know is if something like this it's possible:

```
html-views-view--ir-news.tpl.php

```

Because I need to change, for this view the html tag from this to this only for this view.

Is this possible? Is that the way? Thanks for the answers.

# Answer
if you want to use AMP for specific pages, you might want to take a look at the AMP module.

But if you still want to add the `amp` attribut to the `<HTML>` tag manually, here's one way:

Overwrite the `html.tpl.php` template by copying the original tpl file (modules/system/html.tpl.php) to your current theme (sites/all/themes/your\_theme/). Then add the following code at the top of the file:

```
$amp = '';
if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load($nid);
    $amp = $node->type == 'ir_news' ? 'amp' : '';
}

```

Then, you just print the $amp variable inside the `<html>` tag.

The `amp` attribute will only be added to your ir\_news pages.
> 0 votes

# Answer
This is my html.tpl.php

```
<?php global $base_url, $theme_path ?>
<!DOCTYPE html>
<html class="no-js" lang="<?= $language->language ?>" dir="<?= $language->dir ?>"<?= $rdf_namespaces, !empty($schemaorg) ? $schemaorg : ''; ?>>
    <head>
        <?= $head; ?>
        <!-- Set the viewport width to device width for mobile -->
        <meta name="viewport" content="width=device-width">
        <meta name="format-detection" content="telephone=no">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <title><?= $head_title; ?></title>
        <?= $styles; ?>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <?= $scripts; ?>
        <?php dri_config_output_gtm_head() ?>
    </head>
    <body class="<?= $classes; ?>" <?= $attributes; ?>>
    </body>
</html>

```

And this is what I need exclusively for this view: *views-view--ir-news--page.tpl.php*

```
<?php global $base_url, $theme_path ?>
<!doctype html>
<html amp lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>">
  <head>
    <meta charset="utf-8">
    <title><?php print $head_title; ?></title>
    <?php print $head; ?>
    <?php include $theme_path_file . '/templates/amp-css/amp-boilerplate-styles-min.inc' ?>
    <?php if (!empty($ampsubtheme_path_file)): ?>
      <style amp-custom>
        <?php include $theme_path_file . '/css/amp-custom-styles.css' ?>
      </style>
    <?php endif; ?>
    <script async src="https://cdn.ampproject.org/v0.js"></script>
  </head>
  <body class="<?php print $classes; ?>" <?php print $attributes;?>>
  </body>
</html>

```

And finally I need to add this function for replace the img tag for a

```
function theme_image($variables) {
  // Remove RDF properties incompatible with AMP specification.
  if (isset($variables['attributes']['typeof'])) {
    unset($variables['attributes']['typeof']);
  }

  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      if (empty($attributes[$key])) {
        $attributes[$key] = $variables[$key];
      }
    }
  }

  return '<amp-img' . drupal_attributes($attributes) . '></amp-img>';
}

```

But I'm not sure if I can add this function to this file **views-view--ir-news--page.tpl.php** or it's only for the *template.php* file.

Thanks for the answers. Sorry for my english.
> 0 votes

---
Tags: 7, views, theming
---


title: Why isn't this module library loaded?

text:
# Question
Title: Why isn't this module library loaded?
I am using the following code.

### wk\_elastic.info.yml

```
name: Blablabla
description: Blablabla
package: BlaBlaBla

type: module
core: 8.x

libraries:
  - wk_elastic/list-js

dependencies:
  - block

```

### wk\_elastic.libraries.yml

```
list-js:
  js:
    js/list.js: {}
  dependencies:
    - core/jquery

```

### wk\_elastic.module

```
function wk_elastic_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'wk_elastic/list-js';
}

```

The library is not being loaded.

What can I do to fix this?

# Answer
Instead of attaching in preprocess\_page you already attached the library in your theme file:

### wk\_elastic.info.yml

```
libraries:
  - wk_elastic/list-js

```

You may also want to define the version in your libraries file, make sure that your .js file exists (js/list.js) and that there's no module with the same name as your theme:

### wk\_elastic.libraries.yml

```
list-js:
  version: 1.x
  js:
    js/list.js: {}
  dependencies:
    - core/jquery

```
> 1 votes

# Answer
Switch the active theme to a core theme. If the library loads now then make sure that your custom theme has `<js-bottom-placeholder token="{{ placeholder_token }}">` and `<js-placeholder token="{{ placeholder_token }}">` in the `html.html.twig` template.

Another pitfall is an incorrect reference to the library. Although it does not apply to the original question I'll state it anyway because it solved the problem for me. If your `my_module.libraries.yml` looks like this

```
my_libraries.my-library:
  js: ...

```

then you have to use

```
['#attached']['library'][] = ['my_module/my_libraries.my-library']

```

instead of

```
['#attached']['library'][] = ['my_libraries.my-library']

```
> 2 votes

# Answer
Try renaming "list-js" to "list\_js". I've had problems with using hyphens before in naming.
> 1 votes

# Answer
One more possible case causing described issue is if you have a module/profile named the same as a theme or vice-versa.

See: https://www.drupal.org/project/drupal/issues/371375
> 1 votes

---
Tags: 8, theming
---


title: Is it compatible with PHP 7.2?

text:
# Question
Title: Is it compatible with PHP 7.2?
We have a Drupal 7 site running Drupal Commerce. Our host has now informed us that they will be updating PHP from 5.6.3 to PHP 7.2.

Is Drupal Commerce for Drupal 7 compatible with PHP 7.2? I have tested Drupal 7 with PHP 7.2 on another domain; for most of the part, it appears to work. However, I have not been able to test Commerce on PHP 7.2, yet.

# Answer
> Compatible with PHP 7.2?

Yes, currently the only issue I see in the issue queue is:

PHP 7.2 Warning: A non-numeric value encountered in commerce\_currency\_amount\_to\_decimal()

You'll have to apply this patch yourself since it has not been committed.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Editing contents of custom block referenced in paragraph type, doesn't reflect changes in node where displayed
So, I have a Custom Block type, let's call it **Sidebar Links Block**. In an Article, we have a Sidebar paragraph type that allows quite a few different entities, one of which is the **Article Sidebar Links** paragraph type.

The *Article Sidebar Links* ¶ type (which is one of the fields of our **Article** type) contains a single entity reference to a Custom Block type, the aforementioned *Sidebar Links Block*.

If I change, say, the Title of the *Sidebar Links Block*, that change is not reflected in the paragraph type's output. In other words, when viewing an Article where we changed the contents of one of the referenced Custom Block types, it still shows the old contents, before the change.

Even clearing the Drupal caches in the usual way, does nothing. What I have to do, instead, is:

* Edit the Article
* Move any ¶ type up or down, then move it back (this triggers the form's JS that detects changes, allowing you to re-save with essentially no real changes)
* Re-save the Article

This finally causes the Title to update in the *Article Sidebar Links* ¶ type where the *Sidebar Links Block* is referenced and displayed.

Is there any way around this? Currently, whenever we update a Custom Block, we have to apply this manual fix to *every single Article* where it's referenced. I have a hunch that it has something to do with cache tags, but I don't know enough to be able to investigate. Does anybody have any ideas as to how this can be fixed?

# Answer
So the way that I ended up fixing this, was to use Twig Tweak to output the content block directly, like so:

```
{{ drupal_entity('block_content', content_block_id) }}

```

This ends up bypassing Drupal cache. Barring a better fix, this is the one I'm going with.
> 0 votes

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


# Question
Title: How to display articles based on group combinations of various group types?
I looked at the group module. Defining permissions based on user and entity memberships would suit my needs very well, but sometimes I would need a combination of various group memberships to define if a user is able to see an article.

Example:

There are two group types: site and department.

The user is a member of the group "Paris" and the department "sales". The article is a member of both groups as well.

The user should only see articles which are member of BOTH groups. He should not see the articles which are member of the group "Paris", but not member of the group "sales".

Is this possible?

# Answer
I think your understanding of *membership* is not correct. So first a clarification:

* Users can be member of one or more groups.
* Content, such as articles, can be assigned (= belong to) a single group.

With that in mind, you may want to try an approach like so:

* Create a group type of, say, *Regional departments* (a single group type should be enough for your case).
* Create various groups, of group type *Regional departments*, named something like so (with names that should be self explaining):

+ Paris - Sales
    + Paris - Support
    + Paris - Accounting
    + Paris - R&D
    + Paris
    + Nice - Sales
    + Nice - Support
    + Nice - HRM
    + Nice
* For any user, create group memberships depending on their region (Paris or Nice), and depending on their (what you call) departement (Sales, Support, etc). Special case: for each user, also create a group memberships depending on their region (Paris or Nice).
* Whenever you create content (articles), you assign it to the appropriate group. Special case: if you assign it to (e.g) group Nice, then any Nice departement has access to it.

That's really it. But on top of that, you can optionally:

* Change to which group an article belongs (e.g from 'Paris - Sales' to 'Nice - Sales', eg when sales territories get reorganized).
* Grant or revoke access for selected user(s) to specific content (articles), simply by changing their group memberships (e.g if a user gets tranfered to another departement).
> 1 votes

---
Tags: 8, group
---


title: amp-img tag, replace to simple img

text:
# Question
Title: amp-img tag, replace to simple img
I need to change this tag `<img>` to `<amp-img>`, I've been researching about this and I have this function for change the img tag.

```
function amptheme_image($variables) {
  // Remove RDF properties incompatible with AMP specification.
  if (isset($variables['attributes']['typeof'])) {
    unset($variables['attributes']['typeof']);
  }

  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      if (empty($attributes[$key])) {
        $attributes[$key] = $variables[$key];
      }
    }
  }

  return '<amp-img' . drupal_attributes($attributes) . '></amp-img>';
}

```

This function should change `<img>` to `<amp-img>` but it's not working.

I think it's maybe for the name of the function. My theme's name is bartik, but the function example it's **amptheme\_image**.

I just did tried like this **bartiktheme\_image**, also **bartik\_theme\_image**, but it's the same error.

I also tried like this, **theme\_image**, but boom error cause there's another function with the same name.

Thanks for the answers and suggestions.

# Answer
> I think it's maybe for the name of the function. My theme's name is bartik, but the function example it's amptheme\_image.

Without more info it's hard to be sure, but it sounds like you're adding this code to the core bartik.theme file? If so then yes, that's why it's not working. You need to create a subtheme, add your code to its .theme file, and then enable that theme on the front end.

The function must be named `<themename>_image`, so to use your existing code exactly as-is, you should make sure the machine name of your subtheme is `amptheme`.

Once you've done that and rebuilt the cache, your image elements should start using the override you've setup.
> 0 votes

---
Tags: meta-tags
---


# Question
Title: Using MYTHEME_page_attachment_alter does not alter the favicon
Based on other similar stackexchange questions and documentation, I've implemented the following in the MYTHEME\_page\_attachment\_alter function in MYTHEME.theme file to change the favicon based on the url (inside a condition statement):

```
    foreach($page['#attached']['html_head_link'] as $k => $v) {
        if (array_key_exists('rel', $v[0]) && $v[0]['rel'] == 'shortcut icon') {
            unset($page['#attached']['html_head_link'][$k]);
            $page['#attached']['html_head_link'][$k] = array(
                array(
                  'rel' => 'shortcut icon',
                  'href' => '/themes/fu/favicon_urbana.png',
                    'type' => 'image/png',
                ),
            );
        }
    }

```

Using Kint::dump($page) confirms that the shortcut icon is indeed updated. Why then will the tab for the page not show the updated favicon? I've cleared the cache, ran drush cr multiple times, etc yet the page continues to show the theme's favicon.

Am I missing something? Any advice would be greatly appreciated.

On a side note, we had this working successfully in Drupal 7 in MYTHEME\_html\_head\_alter() and I am migrating this to Drupal 8.

# Answer
It turns out I was missing

```
<head-placeholder token="{{ placeholder_token|raw }}">

```

in the head section of html.html.twig. Once I put that in there, the tags appeared and the favicon gets updated properly.
> 0 votes

# Answer
If its not a browser cache issue perhaps you should try modifying it with a hook called later namely `THEMENAME_preprocess_html`

```
function THEMENAME_preprocess_html(array &$variables) {
  $test = "";
  $variables["page"]["#attached"]["html_head_link"][0][0] =
    array(
      'rel' => 'shortcut icon',
      'href' => '/themes/fu/favicon_urbana.png',
      'type' => 'image/png',
    );
}

```
> 0 votes

# Answer
You can change the favicon with `MYTHEME_page_attachment_alter`.
First you should remove the favicon added by the theme with. `unset($attachments['#attached']['html_head_link'][0]);` as mentioned here then add you favicon here is a code sample works for me.

```
/**
 * Implements hook_page_attachments_alter().
 */
function MYTHEME_page_attachments_alter(array &$attachments) {
  // Remove the default favicon.
  unset($attachments['#attached']['html_head_link'][0]);
  // add new favicon.
  $attachments['#attached']['html_head_link'][][] = array(
    'rel' => 'shortcut icon',
    'href' => '/themes/fu/favicon_urbana.png',
    'type' => 'image/png',
  );
}

```

Result:
> 0 votes

---
Tags: 8, theming, hooks
---


# Question
Title: Which hook to use for updates of all nodes of a particular type
This question is about Drupal 7. For a particular node type, let's take three examples:

* a) book
* b) article
* c) customcontenttype

I would like to be able to capture the moment of an update of an existing node of this type.

I would like to know if there is a way to target only that node type directly from the hook and not to have the hook triggered for all nodes and then checking the node type.

I've seen some internet articles talking about

1. mymodule\_node\_update - for me this is a general hook for all nodes
2. mymodule\_book\_update or mymodule\_article\_update or mymodule\_customcontentype\_update
3. mymodule\_form\_book\_node\_form\_alter or mymodule\_form\_article\_node\_form\_alter or mymodule\_form\_customcontenttype\_node\_form\_alter

Which one of the three above hooks should I use? all of them? if none of them are good then which hook to use?

Many thanks

# Answer
> 1 votes
> I would like to know if there is a way to target only that node type directly from the hook and not to have the hook triggered for all nodes and then checking the node type.

Node hooks aren't that granular, they're invoked for all nodes and there isn't a system in place to make that selective based on the type. If you're worried about performance, don't be; the difference between the hook being invoked for all nodes, and a system to allow it to be selective would be negligible.

If you want to react to existing nodes being update, `hook_node_update()` is definitely the right choice.

You just need to test the type in that function:

```
function MYMODULE_node_update($node) {
  if (in_array($node->type, ['book', 'article', ...])) {
    // Do something.
  }
}

```

---
Tags: hooks
---


# Question
Title: How to import CSV feed into nodes with multiple taxonomy terms?
My question title says it all.

I have feeds for importing and tamper for editing the data before being put into my nodes.

I have my values delimited by commas and explode is making them into individual values. I've made sure of this by also assigning them to individual text fields.

The exploded values are not getting assigned to already created taxonomy terms. I've noticed that there are spaces in front of all terms except the first and after all terms except the last. I've tried to add additional options like trim or exact. Neither have had any affect.

To simplify things, I've removed all but one taxonomy terms and removed all spaces before and after commas from the .csv file. Still nothing shows up into my term field when I explore.

Additional I've tried to use the search term by name add-on for feeds, but it gives me a query error.

Since I'm obviously missing a step, I'm curious how to set up each step of the puzzle.

Content type field set up, mapping to the term reference field, and finally the tamper set up. Since mapping is fairly straight forward I'm only concerned with getting multiple taxonomy terms attached to the nodes I am trying to import.

I'm hoping to avoid trial and error of every combination of settings here as such, any and all help provided is appreciated.

# Answer
You just set **Search taxonomy terms by: Term name** in mapping at Node processor & uncheck **Auto create**.

Add **explode** plugin at Feed Tamper tab with **string operator** such as **||**.

Provide multiple value separated by your set string operator and it will work. It works for me at several places.
> 12 votes

# Answer
Here are a couple of screenshots to demonstrate settings:
> 0 votes

---
Tags: taxonomy-terms, feeds
---


# Question
Title: How to programmatically search content with a specific taxonomy term with Search API?
I'm working on programmatically searching content with the Search API module. Ideally I would like the ability to select which taxonomy term of a content type is being searched. For example, if I have a content type of 'restaurants' and three taxonomy terms representing the style of restaurants, lets say 'Italian', 'Chinese' and 'Fast Food'. I would then like the ability to search and get results of all the restaurants content entities associated with, lets say, just the Chinese taxonomy term.

Here is the code that I have so far:

```
$search_entry = $form_state->getValue('search');

$query = \Drupal\search_api\Entity\Index::load('forum_ct_search')->query();
$query->keys($search_entry);
$query->range(0, 5);

$result = $query->execute();
$items = $result->getResultItems();

```

This is working as far as I'm able to search the specific content type I'm interested. However I'm assuming there is a way to ask the Search API to just search by taxonomy terms. If it's possible, my best guess is that it is with the addCondition method, such as this:

```
$query->addCondition('type', ['article', 'snippet'], 'IN');

```

If this is the correct method for filtering by taxonomy term what are the correct parameters? If not how may I?

The other alternative would be to weed out the taxonomy terms from the results. This would work but it strikes me as cleaner to do it the other way.

Any ideas? Thanks!

(I'm running Drupal 8.6 with Search API 1.12)

# Answer
> 1 votes
Yes that's right to do addCondition here's a page with some examples https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

So you'd just need to do the machine name of your indexed taxonomy field

```
$query->addCondition('my_indexed_field', $myvalue)

```

# Answer
> 0 votes
Hey thanks for the reply, because of it I pushed a bit harder and tried a few more things and I got it working. My primary mistake was that I wasn't using the taxonomy term id as the value, I kept using the term name instead. Here is the code that I got working.

```
$search_input => $form_state->getValue('search')

$tax_field = 'field_taxonomy_name';    //Use Content field machine name.
$tax_term = 9;                         //Use Taxonomy Term ID (tid)

$query = Drupal\search_api\Entity\Index::load('forum_search_index')->query();
$query->setFulltextFields(['title', 'body']);
$query->keys($search_input);
$query->addCondition($tax_field, $tax_term);
$query->range(0, 50);

$result = $query->execute();
$result_items = $result->getResultItems();

```

Thanks again.

---
Tags: 8, search
---