# Question
Title: How do I throw values calculated back to buildForm()?
I am trying to throw back values that are calculated in `submitForm()` to `buildForm()`.

How do I add more state values into it?

```
    /**
     * @file
     * Contains \Drupal\resume\Form\ResumeForm.
     */
    namespace Drupal\resume\Form;

    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;

    class ResumeForm extends FormBase {
      /**
       * {@inheritdoc}
       */
      public function getFormId() {
        return 'resume_form';
      }

      /**
       * {@inheritdoc}
       */
      public function buildForm(array $form, FormStateInterface $form_state) {
         $form['number1'] = array(
          '#type' => 'textfield',
          '#title' => t('number 1'),
          '#required' => TRUE,
        );

        $form['number2'] = array(
          '#type' => 'textfield',
          '#title' => t('number 2'),
          '#required' => TRUE,
        );

        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
          '#type' => 'submit',
          '#value' => $this->t('Save'),
          '#button_type' => 'primary',
        );

  $header = array(
    'total',
  );
  $output = array();
  foreach ($form_state->getValues() as $key => $value) {
     $output['total'] = $total;
  }
  $form['mytable'] = array(
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $output,
    '#empty' => t('No Data'),
  );

        return $form;
      }

      /**
       * {@inheritdoc}
       */
      public function submitForm(array &$form, FormStateInterface $form_state) {

        foreach ($form_state->getValues() as $key => $value) {
          drupal_set_message($key . ': ' . $value);
        }

$total = $form_state->getValue('number1') * $form_state->getValue('number2');

    $form_state->setValue('total',array($total));

           }
        }

```

# Answer
You can add the following code:

```
/**
 * {@inheritdoc}
 */
  public function buildForm(array $form, FormStateInterface $form_state) {
     ...
     if (!empty($form_state->get('total')) {
       $form['total'] = array(
         '#type' => 'markup',
         '#markup' => '<p> Total is: <strong>' . $form_state->get('total') . '</strong></p>',
       );
     }
    //$header = array(
    //  'total',
    //);
    //$output = array();
    //foreach ($form_state->getValues() as $key => $value) {
    //   $output['total'] = $total;
    //}
    //$form['mytable'] = array(
    //  '#type' => 'table',
    //  '#header' => $header,
    //  '#rows' => $output,
    //  '#empty' => t('No Data'),
    //);
    return $form;
   }

```

Add the following code to your submit handler:

```
/**
 * {@inheritdoc}
 */
 public function submitForm(array &$form, FormStateInterface $form_state) {
   ...
    $total = $form_state->getValue('number1') * $form_state->getValue('number2');
    $form_state->set('total', $total);
    $form_state->setRebuild(TRUE);
    return $form
 }

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Where can I find the form API reference?
Form API Reference gives information about which properties to use for a form array, for Drupal 7.

Where can I see what properties I can use in `buildForm(array $form, FormStateInterface $form_state)`, such as #type, #title, #required, and other possible properties?

Actually I'm using the Drupal 7 information in Drupal 8, and it works, but there should/must be an updated page, I guess.

# Answer
Many of the form element properties are listed in the documentation for the `FormElement` class. The properties described there are:

* `#after_build`
* `#ajax`
* `#array_parents`
* `#default_value`
* `#description`
* `#disabled`
* `#element_validate`
* `#field_prefix`
* `#field_suffix`
* `#input`
* `#parents`
* `#process`
* `#processed`
* `#required`
* `#states`
* `#title`
* `#title_display`
* `#tree`
* `#value_callback`

Form and render elements shows a list of the form and render elements implemented by Drupal core, with a link to the class implementing them.

>

It contains also the following sentences. (Emphasis is mine.)

> Each form and render element type corresponds to an element plugin class; each of them either extends `\Drupal\Core\Render\Element\RenderElement` (render elements) or `\Drupal\Core\Render\Element\FormElement` (form elements). Usage and **properties are documented on the individual classes**, and **the two base classes list common properties shared by all render elements and the form element subset**, respectively.

There isn't a single page describing all the form element properties, but there is a page for each plugin class that implements a form element.
> 10 votes

---
Tags: 8, community-official-site
---


# Question
Title: How to create custom view/display for few content_types?
*EDIT: see two paragraphs below to what I managed to get*

I can't find a way to use single template for few but not all content\_types. Let's say I have content\_types A, B, C and D. I want to use default node.html.twig for A and B and node--other.html.twig for C and D. Later, when I add content\_type E and F, I want E to use default template and F to use custom template. If I understand things properly, neither node--page.html.twig nor node--content\_type.html.twig help me. I want proper template selected when user visits http://server/node/N without any other combinations.

It could be solved very easily if templates allowed wildcards and template called node--special%.html.twig would match all content\_types with name starting with "special", and node.html.twig would be used for all other types.

**Big thanks to Hudri.**

I implemented his suggestions, I've added my\_module\_theme() hook (?) and it *nearly* works. The problem is that I don't get any data on this page. I'm using bootstrap theme. I copied node.html.twig into my\_module/templates, renamed it to node--dynview.html.twig. I added:

```
node.f: {{ node.field_parm_eht }} cont.body.0: {{ content.body.0 }}

```

to see if it works. "node.f" and "cont.body.0" are displayed, but no other data is present. My hook\_theme() looks like this:

```
function abc_theme() {
  $theme['node__dynview'] = [
          'template' => 'node--dynview'
  ];
  return $theme;
}

```

I've seen that there is 'variables' key available, but no matter what I pass there I don't get any content. I understand that what I put there are default values for my variables accessible to the template (I checked and they are available), but how can I tell Drupal to pass my all default variables for node.html.twig template (like content, node and what not).

**FINAL UPDATE**

I got it. I changed hook\_theme to be:

```
function abc_theme() {
  $theme['node__dynview'] = [
    'template' => 'node/node--dynview',
    'render element' => 'elements',
    'base hook' => 'node',
  ];
  return $theme;
}

```

And it works as expected. Great.

*EDIT: Question rewritten to give **less** details.*

I need to override template for /node/n to present nodes of some content\_type differently. content\_type is not known in advance. I don't want to create separate view for each content\_type. I don't want to override default node.html.twig from theme, as theme can change. How can it be done?

**OLD QUESTION**:

I have the following scenario: administrator creates new content\_type (and possibly marks it somehow, whatever works). This content\_type is just a representation of something else, lets say stock-exchange listings for some company. I don't want to keep this data in my database, but I want to display this information when this entity is displayed (so some View like Content (/node) page). I believe that I should do something like this:

* mark created content\_types *somehow*
* create custom Twig template
* again *somehow* force Twig to used this new template to display only marked content\_types
* use javascript to fetch data from external source using passed node's fields as information what should be fetched

My questions are:

* how should I mark my content\_types (new ones can be created by administrator) so that they are picked up by this mechanism
* and most importantly, how should I name my template? I'm completely lost as to how Twig picks templates in Drupal 8 and it seems that documentation is scarce.

Thanks in advance.

EDIT: More explanation.

My understanding of Drupal is such that each there are multiple "views" on content. And these views are suitably named Views in Drupal parlance. Also I understand that Views mainly present multiple items, not necessarily, but usually of the same content\_type. So there is for example View for all (or some according to some criteria) Articles or Products. There are also displays - I *think* that they are meant to represent single content\_type - again e.g. Article or Product. Basically what I want is to create custom display for content\_type - this would include some custom Javascript code (and things not normally available in Drupal, like dynamic charts updated in real time), so I suppose it can't be simply configured from inside Drupal admin panel and some code must be written. If I'm not mistaken, such display should be created using Twig templates. It seems that if I'm simply interested in such custom display (view? page? - I can't grasp the difference yet), I can create template called "node--MYTYPENAME.html" and place it in proper folder (I don't know where yet, but this can be read in tutorials and I can check how other modules do it). Template variables would be used to provide data about Node (object) that should be display, and all other things I talked about (dynamic charts) would be implemented in Javascript and would fetch data from proper source using fields from this Node.

This seems *relatively* easy and I believe that if I spend some time on it I'll be able to do it. But this is only part of what I need to do. Here comes part two.

This content\_type is not the only one content\_type with this behavior, there are other types. Of course I could copy this template and use it repeatedly, such things are done everyday. But site will be operated by an administrator that has no access to the code, and he needs an ability to add other content\_types that should use exact same page (data sources, values and their meaning is different, but mechanisms can stay the same as long as returned values are date/value pairs). I checked and content\_types *must* be different, this is out of the question. So next part of my question is *how to use single template for multiple content\_types. I have written above that I could create "node--MYTYPE.html" template, but it won't work - MYTYPE is single content\_type*.

My current favorite solution is (but I also don't know how to do it, yet) to create custom page (so probably add route and some PHP code behind it) that accepts any NID (NodeId if I'm not mistaken), checks it's content\_type (so loads object and calls bundle()) and if it starts with for example "dynobj\_" it should load my custom template passing this object as an argument (and template does its own thing), otherwise it should call default template.

Or maybe I should somehow replace default template for all nodes and place there only logic that would include original template if content\_type name does not start with "dynobj\_" and include my custom template otherwise.

I hope this explains my problem better.

# Answer
You can create your own template suggestions based on any logic you want:

```
function MYMODUDLE_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $node = $variables['elements']['#node'];

  if (strpos($node->bundle(), 'SPECIAL_NAME') === 0) {
    $MY_SUGGESTION = CALCULATE_SOMETHING($node->bundle());
    array_splice($suggestions, 3, 0, 'node__' . str_replace('-', '_',$MY_SUGGESTION ) . '__' . $variables['elements']['#view_mode']);
    array_splice($suggestions, 3, 0, 'node__' . str_replace('-', '_',$MY_SUGGESTION ));
  }
}

```

Replace UPPERCASE stuff with your own needs. The `array_splice(...)` part is needed to properly weight your new suggestion (your new suggestion should be chosen over `node--BUNDLENAME.html.twig` but not over `node--ID.html.twig`).

```
<!-- FILE NAME SUGGESTIONS:
   * node--ID--VIEWMODE.html.twig
   * node--ID.html.twig
   * node--MY_SUGGESTION --VIEWMODE.html.twig
   x node--MY_SUGGESTION .html.twig
   * node--BUNDLENAME--VIEWMODE.html.twig
   * node--BUNDLENAME.html.twig
   * node--VIEWMODE.html.twig
   * node.html.twig
-->

```

You can also do the same procedure based on a field value, e.g. `$node->get(...)->value` (but check for `$node->hasField(...)` first)
> 1 votes

---
Tags: views, 8, nodes
---


# Question
Title: How do I implement hook_views_post_execute
I am attempting to modify the output of view programmatically using hook\_views\_post\_execute.

I created the usual module structure (in this case using drupal generate:module.

I am able to use other hooks (such as hook\_entity\_view)successfully.

However, hook\_views\_post\_execute causes blows up the website with the message

> The website encountered an unexpected error. Please try again later.

The code block is right out of api.drupal.org.

```
/**
 * @param ViewExecutable $view
 */
function idm_views_post_execute(ViewExecutable $view) {

  // If there are more than 100 results, show a message that encourages the user
  // to change the filter settings.
  // (This action could be performed later in the execution process, but not
  // earlier.)
  $temp = $view;

  if ($view->total_rows > 100) {
    \Drupal::messenger()
      ->addStatus(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}

```

# Answer
> 3 votes
My guess is you did not include the `use` statement at the top of your file that tells the application how to locate the class `ViewExecutable`. This is a PHP construct and not Drupal specific, which is why it is not always mentioned explicitly in the documentation.

At the top of your file, add:

`use Drupal\views\ViewExecutable;`

The incoming argument to the hook is of type `ViewExecutable`, but PHP does not know how to find that class, so it errors out unless you either use the `use` statement, or change the function signature to:

```
function idm_views_post_execute(Drupal\views\ViewExecutable $view)

```

Clear cache and reload. If the error persists, you'll need to provide log(s) to indicate what the actual error that occurred was.

If you copied and pasted the code here for `hook_entity_view` that would explain why that worked for you:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_entity\_view/8.6.x

The example here has the full path in the argument list.

```
hook_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode)

```

---
Tags: 8, hooks
---


# Question
Title: Aegir no longer seems to be adding SSL info to apache config files for sites
I am using hostmaster 7.x-3.171 and I am using the legacy SSL option (apache SSL - not apache HTTPS)

When i check the apache entry for the site in question at

/var/aegir/config/server\_master/apache

it is missing the 443 entry and only has an entry for port 80 stuff.

I have double checked the site settings in aegir and SSL is enabled and a certificate is selected. I have tried to verify the site and no errors are presented. This seems to happen only if I try to verify a site that has SSL enabled. Maybe an update broke this somehow? I haven't done anything to mod the aegir set up that i can think of.

Has anyone had a similar problem recently in aegir? Any help would be appreciated!

# Answer
Is there any particular reason why you're using the legacy option, and not Aegir HTTPS?

The legacy option is no longer supported so my recommendation would be to follow the documentation to switch.
> 2 votes

---
Tags: aegir
---


# Question
Title: How to migrate one type of contents to other type having same fields?
I have 2 content types having same fields and I have many contents added by cleint in both the types,now I want to change some of the node's type A other type.. How can i achieve this?

# Answer
You can probably prepare a view that filters the nodes that you want to migrate using Rest Export display and than create a migration to import the previous Export as described in this tutorial
> 1 votes

---
Tags: 8, nodes, migrations
---


# Question
Title: Serve compressed JS and CSS with S3 as filesystem
We have a Drupal 8 site using S3 file system integrated via the S3 File System module.

The aggregated CSS and JS are uploading on S3, however I am not seeing any configuration to serve compressed files.

Can someone suggest a way or any configuration that I am missing?

# Answer
As Clive mentioned there is no config on s3 which could automatically compress the assets on s3.

The way we fixed it in our case was to add cloudflare CDN service(already in use) in front of s3 file system.

In order to route the s3 assets request via CF we added a proxy subdomain for our drupal origin. So if Drupal site was running on site-url.com we added a proxy subdomain as `s3-<env>.site-url.com`. We added a page rule in CF to override host to s3 bucket for any request to `s3-<env>.site-url.com/*`.

Now, the challenge was to override s3 hostname configuration in Drupal to spit out resources on `s3-<env>.site-url.com/*` instead of s3 bucket url. Big thanks to S3FS module maintainers for providing easy configuration to override that by adding following in settings.php

```
  $config['s3fs.settings']['use_cname'] = TRUE;
  $config['s3fs.settings']['domain'] = 's3-<env>.site-url.com';

```
> 0 votes

---
Tags: 8, performance
---


# Question
Title: Allow authenticated users to update submissions
Drupal 8.6.5 and Webform 5 here

I have a webform in which I have enabled Signature Pad (I mean https://github.com/szimek/signature\_pad). I would like to implement a workflow such that:

* An authenticated user submits the form, and an email is sent to another authenticated user with a link to the webform submission (this second user is chosen by the first user by filling a field in the form)
* The second user is able to follow the link, authenticate and update the first user's submission (he adds his signature to the submission)

This is easy to accomplish when the second user is known (just a matter of access permissions), but how can I implement such a thing when he is not known/predetermined?

# Answer
> 0 votes
You might want to implement an application evaluation workflow and the Webform module includes a 'Webform Demo: Application/Evaluation System' module.

The demo has an evaluation form attached the application form using a block.

For the email routing, you should be able to use a user entity reference token in email handlers 'To' field.

---
Tags: webforms
---


# Question
Title: How can I filter a view by Content Type -or- Taxonomy Term and have both sets of items show?
I have a basic view that works great. It shows a list of nodes that are filtered by content type.

To that list of allowed content types, I want to add a taxonomy term. That is, the view should show anything that is a certain special content type, but ALSO include any node that has a certain special taxonomy term, no matter what the content type is.

The view that already works fine has its filter setup this way:

FILTER CRITERIA:

`Content: Content type (is one of: Blog, IM, PI)`

Easy, no problem. To add the taxonomy term, I set it up this way:

FILTER CRITERIA

```
    Content:  Content type (is one of: Blog, IM, PI)  OR
    Content: Has taxonomy term (= News Release) | Settings

```

Here's where it went all wrong on me. As soon as I added the taxonomy term filter, the items that should be there by Content Type completely disappeared. Only items with the taxonomy term show up in the view now. If I remove the taxonomy term filter, then items in the Content type pop back in again. It's like the taxonomy filter suppresses the content type filter in some way.

I tried:

* using `Content: Resource Type (= News Release) | Settings` which was an alternate way of listing the taxonomy, "Resource Type" being the vocabulary
* using `AND` instead of `OR` but, as you would expect, that returned no results at all because I do not have any of the special three content types that are *also* labeled as the special taxonomy "News Item". They are separate use cases.
* using filter groups, listing the content type, an OR, and a content type AND taxonomy:

```
Content:  Content type (is one of: Blog, IM, PI)
OR
Content: Content type (= Article) AND
Content: Has taxonomy term (= News Release) | Settings

```

To be clear, either the node is a special content type OR the node is a regular content type with a special taxonomy term. Never both. Both types of nodes should appear side-by-side in this view.

Am I not allowed to make a view that shows stuff filtered by taxonomy alongside stuff filtered by content type at the same time? Can anyone suggest something for me to try?

# Answer
> 1 votes
For others Solution is adding a views relationship see Documentation: https://www.drupal.org/docs/8/core/modules/views/add-a-relationship-to-a-view

# Answer
> 0 votes
This is a bug, there are patches for different Drupal releases to fix the issue:

ManyToOneHelper ignores group configuration for some cases and forces INNER joins

Please report back in that Issue after you test so it can be marked as tested and included in the next release.

---
Tags: views, 8
---


# Question
Title: Copy installed modules and configuration to new installation
I have a Drupal 8 application with mysql as database. I installed bunch of third part modules such as domain, search\_api, pdf etc... Most I installed using composer and a very few using "Install module". Configured few content types, created few views, pages, configured apache solr for search indexing...

Now I have requirement to set up everything in a higher environment using oracle as database. I was able to setup a blank drupal 8 application with oracle database.

**Question: Installing all the modules in new installation ?** My thoughts -\> Edit the composer.json to add modules and run composer update and manually install rest of the modules or Is there a better way to import all the installed modules to new app.

**Question: Configuration migrate ?** I was thinking of using configuration \> development \> Configuration synchronization to export and import all the configurations.

**Question: Data migrate ?** I used migration module to import content and upload files. If everything works till here, data migration is the last priority. Good to have. I have one custom module too created for migration purposes. I used this migration module to migrate csv data to druapl8-mysql application. If everything works, I want to migrate the same csv content to drupal8-oracle application.

This exercise will help us to migrate and duplicate setup to test environments too. Please suggest an ideal process for the migration.

# Answer
> 3 votes
**Question: Installing all the modules in new installation**

Answer: Yes add all modules to root composer.json file so only have to run composer install or later composer update

**Question: Configuration migrate**

Answer: Configure your sites sync folder 'in settings.php' and run `drush cex` to export the current sites config (then you can git commit the changes and deploy to new environment) and run `drush cim` on new environment to import changes.

**Question: Data migrate**

Posable Answers: now this one can get kinda tricky and have a lot of options for this ... which depends largely on what you want to keep / what you don't.

Simple option: copy database - good old fashion export database and then import it.

Content migration option: look in to https://www.drupal.org/project/default\_content\_deploy its like config import/export only for entity data (which again can be commited to repo and deployed) eg `drush default-content-deploy:export` and `drush default-content-deploy:import`

use normal migrate api option. use a seed database option.

really should just have all the stuff you need in a git repo then you just tag the release ... push to the environment and run some commands or have some automated scripts to run the commands for you look in to stuff like... https://chromatichq.com/blog/drupal-8-deployments-jenkins-github-slack and https://hernani.pt/automatic-update-drupal8

---
Tags: 8, migrations, configuration
---


# Question
Title: How can I access/arrange elements in the {{ content }}?
I am relatively new to Drupal and have just successfully pulled out a field value and used it to display a custom icon on the page.

Coming from a HTML/CSS only kind of world, I am finding it hard to understand how to do simple things, such as take variables I've created and insert them within the {{ content }} area.

In my specific application, I have a page that NOW looks like this:

Custom Icon 3, Custom Icon 4, Custom Icon 5

{{ content starts here }}

Node Title

Node Subtitle

Custom Icon 1, Custom Icon 2, Custom Icon 3

Image

(page continues)

{{ content ends here }}

What I'd like to do is have the Custom Icons all in a nice line together beneath the Subtitle, but since the 3, 4, and 5 were generated by code, they're outside the {{ content }} block. Icons 1, 2, and 3 are created by hiding the text value (which is either there or not) and displaying a background image...a totally different method that doesn't work for 4, 5, and 6 because in those cases the value isn't binary, it's got several different values.

I'm not married to any specific method to accomplish this but am curious about how I can "best" make these all line up nicely together, one after another, in that order 1, 2, 3, 4, 5, 6.

I believe it's relatively easy to do it like this:

1, 2, 3, 4, 5, 6

Node Title

Node Subtitle

Image...etc.

But that's not really what I'd like to do. This is how I'd like it:

Node Title

Node Subtitle

1, 2, 3, 4, 5, 6

Image...etc.

This would be relatively easy to do with CSS if I had better access to the inside of the {{ content }} and could make a div, assign it a class, place it in the "4" position, and style it to show as with 1, 2, and 3. But I don't see how to actually accomplish that when the variables are OUTSIDE that immutable {{ content }} block.

Any help to better understand this process? Even if it is to say that I did everything bass-ackward and should simply make these icon fields images and upload the right image into the field each time. I have a site with a large amount of content on it but not so large I couldn't redo this Content Type from scratch the *right* way. It just seems so strange to me that something so easy to accomplish with a little PHP has been so difficult to get right in this case.

I've done CONTENT with Drupal for years, but this is the first time I've been delving deeper into the development side. Most of the documentation assumes a level of D7 knowledge that I don't have, and the explanations are aimed at people who have been developing D7 sites and need to know the differences, rather than at someone coming in fresh. Or instructions are for D7 entirely.

# Answer
> 1 votes
You don't have to use `{{ content }}` only - this is a variable made up of all the renderable elements in the entity being rendered.

For instance, if you have 4 fields, Field A, Field B, Field C, Field D, you can dictate how/where they are output in the entity template like so, by rendering individually:

```
<div class="section-main">
  {{ content.field_a }}
  {{ content.field_b }}
</div>

<h4>{{ content.field_c }}</h4>
<p>{{ content.field_d }}</p>

```

The most common thing most people will encounter in theming will be the theming of fields and entities (like node).

If you wanted the markup within the field, you'd create/edit the appropriate `field--` template in your theme and move it there. Lets say you wanted to move the `h4` into the Field C template:

`field--field-c.html.twig`:

```
{% for item in items %}
  <h4>{{ item.content }}</h4>
{% endfor %}

```

Now anytime that field is rendered, it is wrapped with an h4 (per value, if it is a multivalue field - check `field.html.twig` for more info).

Then, back in the node template you remove the h4:

```
{{ content.field_c }}

```

The `h4` is still in the page, it's just in the field template now. You can break it down any number of ways that is suitable for you.

Let's say you did a `mytheme_node_preprocess` in your themes `mytheme.theme` file and created some new variables for the node template. Now that you know how to break down the content variable, you can intersperse custom variables with that:

```
<h1>{{ title }}</h1>

<h2>{{ content.field_subtitle }}</h2>

{{ custom_var }}

{{ content.field_a }}

<h6>{{ custom_var_2 }}</h6>

{{ content.field_b }}

```

and so on.

Here is a real example from a project of mine to demonstrate a little further:

`node--collection.html.twig`

```
{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
    'hl__full-template__page-content',
    'hl__full-template__page-content--full',
    'hl__collection-details'
  ]
%}

<article{{ attributes.addClass(classes) }}>
  {{ title_prefix }}{{ title_suffix }}

  {% if node.field_featured_image %}
    <div class="hl__collection-details__main-image">
      {{ content.field_featured_image }}
    </div>
  {% endif %}

  <section class="hl__rich-text">
    {{ content.body }}
  </section>

  <div class="hl__collection-details__columns">
    <div class="hl__collection-details__divider"></div>
    <div class="hl__collection-details__how-to">
      <section class="hl__rich-text hl__rich-text--small">
        <h2 class="hl__comp-heading">Accessing These Materials</h2>
        {{ content.field_how_to_use }}
      </section>

      {% if view_records %}
        <div class="hl__collection-details__how-to-button">
          {{ view_records }}
        </div>
      {% endif %}
    </div>
    <div class="hl__collection-details__ctas">
      <section class="hl__contact-list">
        <div class="hl__contact-list__container">
          <h2 class="hl__comp-heading ">Contact</h2>
          <div class="hl__contact-list__items">
            <section class="hl__contact-info">
              {% if node.field_contact_person.target_id %}
                {{ content.field_contact_person }}
              {% else %}
                {% include '@mytheme/misc/freeform--contact.html.twig' %}
              {% endif %}
            </section>
          </div>
        </div>
      </section>

      {% if node.field_call_to_action.target_id %}
        {{ content.field_call_to_action }}
      {% endif %}
    </div>
  </div>

  {% if node.field_related_collections.target_id or node.field_related_how_tos.target_id %}
    <hr class="hl__section-divider" />
  {% endif %}

  {% if node.field_related_collections.target_id %}
    <section class="hl__overlay-promo-grid">
      <div class="hl__overlay-promo-grid__container">
        <h2 class="hl__comp-heading hl__comp-heading--left">Related Collections</h2>
        <div class="hl__overlay-promo-grid__grid">
          {{ content.field_related_collections }}
        </div>
        {% if node.field_see_all_collections %}
          <div class="hl__overlay-promo-grid__see-all">
            {{ content.field_see_all_collections }}
          </div>
        {% endif %}
      </div>
    </section>
  {% endif %}

  {% if node.field_related_how_tos.target_id %}
    <section class="hl__staggered-type-list">
      <div class="hl__staggered-type-list__list-wrapper">
        <div class="hl__staggered-type-list__list">
          {{ content.field_related_how_tos }}
        </div>
      </div>
    </section>
  {% endif %}
</article>

```

The more you try things, the more you are going to learn. You cannot do any PHP in Twig templates, which is why that has to be deferred to preprocess functions in the theme file, custom field formatters etc that tell Drupal what to do with the data you are about to output.

edit: the `{% if node.field_name.value %}` lines are simply checking in the node object that the field has an actual value before we output markup and render the field for it. `node` and `content` are two separate things.

---
Tags: 8, nodes
---


# Question
Title: Using Drupal Commerce Product Reference Field, missing products
I've followed instructions here: https://drupalwatchdog.com/volume-1/issue-1/building-drupal-commerce-product-display

When I create my Product Display, the list of products to choose from is missing most options, as can be seen here:

I have many more products under "Dips" added, but they aren't showing up. Any ideas why?

# Answer
Check the setting of this field. It looks like it is set to 10. Just make it blank and it should allow for all of the products to be shown.
> 0 votes

# Answer
My experience is that this module appears to have a hidden default of showing only 10 products, even though it says "Leave blank to show unlimited." In my product display content type, for the product reference field, I set the Options list limit to 100, even though I only have 16 products. Voila!! All my products are showing now to select for product reference.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to create a theme function for overriding Address Field theming?
How do you create a theme function for overriding the formatting of an Address Field in Drupal 7? I didn't want to create a CTools plugin or work with render arrays.

# Answer
> 0 votes
1. Download & enable the Addressfield Tokens module (https://www.drupal.org/project/addressfield\_tokens). This will provide additional tokens and theme functions for Addressfield.
2. Set the field in question to display using the "Address components" format.
3. Select all the fields you wish to display. Note that the separator does not matter, unless you choose to use it in your theme function.
4. Create a theme function named `THEMENAME_addressfield_formatter__components`, where `THEMENAME` is the name of your theme. Here is an example I created in my template.php to add microdata for XHTML+RDFa: https://gist.github.com/evandonovan/d47a3874e26151c4c07f6c20b7edc204. It is designed especially with the United States in mind, so may not work as well on other countries.
5. Clear the theme registry for your theme function to take effect. If you have Drush, you can use `drush cc theme-registry`. Otherwise, see https://www.drupal.org/node/173880#theme-registry for other means to clear.

---
Tags: theming, commerce, location
---


# Question
Title: Using content type fields within page.html.twig
I am new to Drupal 8, and relatively new to Drupal templating in general.

Here's what I am trying to do: I have a content type, called "Property" with a "header\_color" field. When I add a property, I set the color that I want for that property's header. When I then navigate to that node, the background color of the page's header would be whatever I set the color to.

My understanding is that this needs to take place in page.html.twig, and that there is a way to grab the data from the content type and use it within page.html.twig, using:

`{{ node.field_header_color.value }}`.

This is the tag I have in my page.html.twig:

```
<header id="header" class="header" role="banner" aria-label="{{ 'Site header'|t }}" style='background-color:{{ node.field_header_color.value }}'>

```

When I inspect it in the Chrome Dev, it shows:

`"style='background-color:''"`

Can someone give me some guidance on what I am doing wrong here?

I am using Drupal 8.6.4

# Answer
> 1 votes
In the preprocess\_page set up the variable

```
if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
 $variables['bg_color'] = $node->field_header_color->value;

```

} and use this in ur twig file

```
<header id="header" class="header" role="banner" aria-label="{{ 'Site header'|t }}" style='background-color:{{bg_color}}'>

```

---
Tags: theming
---


# Question
Title: Accessing Drupal REST endpoint using Oauth 2 token
I have successfully installed the Simple OAuth module on my website. I am also able to authenticate to it using Postman. I am getting the `access_token` and the `refresh_token` when authenticating. However, am not able to figure out how I can use this token to access Drupal's default REST endpoints or the endpoints provided by JsonAPI module.

I tried sending the token in the header with `Authorization` as key and `Bearer {{the token }}` as the value with no success. What is the right way to use the token for communicating with Drupal?

# Answer
Just follow the steps given in https://dev.acquia.com/article/decoupled-drupal-authentication-oauth-20 , once you get the access token in postman you will also see tokens for the user details you have given at admin/config/people/simple\_oauth/oauth2\_token. Just copy the access token from postman and add it to Access Token field of Authorization tab(New version of Postman) by selecting Type as oauth2 (Dont't use the access token from the path given above).

Also make sure in permission page under RESTful Web Services section you will see your custom api listed and permission for authenticated user was given.

I followed the same and it worked for me.
> 0 votes

---
Tags: 8, authentication-authorization
---


# Question
Title: How many libraries is too much before there is a performance issue?
We are using Paragraphs module to allow for selecting of up to 15 different `Paragraph Types`. As part of this, each one requires its own `CSS` and `JS` since they are vastly different. We already have a common set of `CSS` and `JS` that can be shared (`25%` overall), but there is a large percentage (`75%`) that is unique to each `Paragraph Type`.

We were able to combine lots of the `CSS` and `JS`, which resulted in the creation of `10` libraries and `1` general library to help with the management of these `types`. We are concerned that if we add more `Paragraph Types` the number of libraries could increase to anywhere between `20-30` as newer `Paragraph Types` are needed.

**How many libraries is too much for a custom subtheme before it cause a performance issue (if any)?**

Since there is no extra preprocessing needed per `Paragraph Type`, we simply add them using the `{{ attach_library('mytheme/name') }}` in `twig templates`. The only `hook` that is used is the one to add the `general` library.

`mytheme` is a subtheme and is set as `default and enabled`

Examples:

`paragraph--carousel.html.twig`

```
{# this is the paragraph type specific library #}
{{ attach_library('mytheme/carousel') }}

<div class="carousel__wrapper">
  <div class="carousel__title"> {{ content.field_title }} </div>
  <div class="carousel__subtitle"> {{ content.field_sub_title }} </div>
  <div class="carousel__text"> {{ content.field_description }} </div>
  <div class="carousel__image"> {{ content.field_image }} </div>
  <div class="carousel__dots"> </div>
</div>

```

`paragraph--jump-menu.html.twig`

```
{# this is the paragraph type specific library #}
{{ attach_library('mytheme/jump-menu') }}

<div class="jmenu__wrapper">
  <div class="jmenu__tab"> {{ content.field_title }} </div>
</div>

```

`mytheme.module`

```
function mytheme_preprocess_paragraph(&$variables) {
  // Add general library for paragraphs.
  $variables['#attached']['library'][] = 'mytheme/global';
}

```

# Answer
In Drupal, the best way to do your CSS is to keep it componentalized, and attach the CSS using #attached directly to the item to which it belongs. This way, the CSS is only ever attached when needed, and if a user overrides the render array further down the pipeline, removing the element to which the assets are attached, the assets will not be attached to the page, including unnecessary CSS.

Then you turn on CSS aggregation (or even better, use the ADVAGG module), and Drupal will handle the heavy lifting, aggregating the files as needed for the page.

So the answer to your question is that there aren't too many libraries. What is more important is effective management of the CSS/JS you are attaching.
> 0 votes

---
Tags: hooks, theming
---


# Question
Title: Where is the the site name and slogan set?
In the page--front.tpl.php template, I have the following code for site logo.

```
<img src="<?php print $logo ?>" alt="example.com logo" title="<?php print $site_name_and_slogan ?>" id="logo" />

```

Where is the title set in Drupal 7? Right now the title is showing blank in the production site.

# Answer
> 1 votes
In your active theme's template.php, check `template_preprocess_page()` function and add following lines:

```
$site_name = variable_get('site_name');
$site_slogan = variable_get('site_slogan');
$variables['site_name_and_slogan'] = $site_name . ' ' . $site_slogan;

```

Assuming that you have used $variables as argument in `template_preprocess_page()` function.

Now `$site_name_and_slogan` can be used in page tpl files.

If you have not implemented `template_preprocess_page()` function, then replace template word with your theme name and add the function as mentioned below:

```
function THEMENAME_preprocess_page(&$variables){
  $site_name = variable_get('site_name');
  $site_slogan = variable_get('site_slogan');
  $variables['site_name_and_slogan'] = $site_name . ' ' . $site_slogan;
}

```

# Answer
> -1 votes
Have u tried these?

```
    <?php print $site_name; ?>
    <?php print $site_slogan; ?>

```

You can use it as

```
    <img src="<?php print $logo ?>" alt="example.com logo" title="<?php echo $site_name.$site_slogan; ?>" id="logo" />

```

---
Tags: 7
---


# Question
Title: Which method is more efficient, database query or taxonomy term controller?
I tried to find a method to verify if the current taxonomy item page has a parent or children, now I get two but I don't know which one is better for the efficiency.

**approach I: use taxonomy item controller**

```
$tid = \Drupal::routeMatch()->getRawParameters('taxonomy_term');
$term = taxonomy_term_load($tid);
$items = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadChildren($tid,$term->getVocabularyId());

```

**approach II: database query**

```
$db = \Drupal::database();
$query = $db->select('taxonomy_term__parent','ttp')->condition('ttp.parent_target_id',$tid)->fields('ttp',['entity_id']);
$result = $query->execute()->fetchAll();

```

Both method can satisfy my initial demand, but which one is better in efficiency? And what about the general case, when we need to check some data, using the data object method or database query, which is better?

# Answer
> 1 votes
Do you need to load all of the children? Otherwise, loadChildren() will be performing the same query but also loading the full term -- which is a performance dent. The API on the entity storage won't make much of a difference here, honestly.

Have you looked at https://www.drupal.org/project/taxonomy\_term\_depth? This would be more performant. It caches the depth level in a new base field. If a term's depth is greater than one, you know it is a child.

I would even borrow the concepts from taxonomy\_term\_depth to add a new base field that is a boolean which caches if the term has children or not. That way you only need to work with the current term entity.

# Answer
> 0 votes
If you only want to know which method is *quicker*, you need to benchmark them in the context of how they're being used in your particular site.

But generally speaking, using the API is always better:

* It improves performance over time by enabling you to use the entity cache (direct querying obviously doesn't give you that)
* You're programming to the interface, and not the implementation. The underlying database structure could theoretically change with the next release, leaving you with a load of code to update if you choose not to use the API.

---
Tags: 8, database
---


# Question
Title: views_embed_view not working with multiple values argument
I'm trying to embed views like this:

```
 views_embed_view('articles_list', 'block_1', '11+13');

```

If I type 11 in arguments, it does take the argument. It works good if I preview the view and enter '11+13' in "Preview with contextual filters" field... But if I write '11+13' in the views\_embed\_view() function, it just takes the value of 11. How can I make it work and take both values: 11 and 13?

# Answer
> 2 votes
From `views_embed_view` doc comment block:

> * @param ...
>     + Any additional parameters will be passed as arguments.

That means any params comes after params `$name` and `$display_id` will consider as contextual filer so you should call `views_embed_view` like:

```
views_embed_view('articles_list', 'block_1', '11', '13');

```

Take a look at Twig Views Module do the same.

---
Tags: views, 8
---


# Question
Title: Specify ids for a migration yml file from nested json array
Given following jsons file

```

{
  "data": {
    "uuid": {
      "value": "ed64784-cjjhd6",
      "patient": false
    },
    "name": {
      "value": "Name",
      "patient": false
    },

```

how to select the **uuid** value and set it as **ids** in the migratin definition yml file?

here is my migration yml file: I really don't know how to select the value of the uuid as **ids**

```

id: migrate_json_file
label: Migrate content from local json file
source:
  plugin: source_url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls: data/data.json

  ids:
    value:
      selector: uuid/value
      type: string
  item_selector: /data
  fields:
  - name: uuid
    label: 'uuid'
    selector: uuid

  - name: title
    label: 'title'
    selector: name

destination:
  plugin: entity:node

  process:
    type:
      plugin: default_value
      bundle: produkt

    title: name
    field_uuid: uuid

  sticky:
    plugin: default_value
    default_value: 0
    uid:
      plugin: default_value
      default_value: 0

    migration_dependencies:
      required: {}
      optional: {}

    dependencies:
      enforced:
        module:
        - migration_json_file

```

Thank you in advance

Sincerely

Hermann

# Answer
> 0 votes
This worked for me:

The solution for the question: based on the json structure I provided, I could fetch the ids using the following pattern:

```

id: migrate_json_file
label: Migrate content from local json file
source:
  plugin: source_url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls: data/data.json

  ids:
    **uuid**
      type: string

  item_selector: /data
  fields:
  - name: uuid
    label: 'uuid'
    **selector: uuid/value**

  - name: title
    label: 'title'
    **selector: name/value**

destination:
  plugin: entity:node

  process:
    type:
      plugin: default_value
      bundle: produkt

    title: name
    field_uuid: uuid

  sticky:
    plugin: default_value
    default_value: 0
    uid:
      plugin: default_value
      default_value: 0

    migration_dependencies:
      required: {}
      optional: {}

    dependencies:
      enforced:
        module:
        - migration_json_file

```

# Answer
> 0 votes
The migration template should include top level `source`, `process` and `destination` sections

It appears in this case you are missing the `process` section for the field value assignment there.

More info: https://www.drupal.org/docs/8/api/migrate-api/migrate-api-overview#etl

---
Tags: migrations
---


# Question
Title: How to add term programmatically in Paragraph field?
I have a paragraph with a taxonomy reference (autocomplete) field and I want to populate it when I create programmatically a pararagraph item. I checked the option "Create referenced entities if they do not already exist" in this field.

I use this code, but I don't know how to find more informations to do that without Term::create (if it's possible) :

```
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

        foreach ($field_value as $creator_type => $creator_name) {

            $paragraph = Paragraph::create(['type' => '_zotero_ref_creators']);
            //text field
            $paragraph->set('field_nom_prenom_createur', $creator_name);
            //taxo reference field
            $paragraph->set('field_type_createurs', $creator_type);

            //$paragraph->isNew();
            $paragraph->save();

            $paragraphn_field_value = array(
              'target_id' => $paragraph->id(),
              'target_revision_id' => $paragraph->getRevisionId(),
            );

            $node_reference->set('field_liste_contrib', $paragraphn_field_value);
          }

```

# Answer
> 2 votes
First load the node already created. Second, create a paragraph like you did but for taxonomy term add "target\_id" and for value choose a term id. Set the paragraph value to your field of type paragraph from node. Also you need to save the node.

```
    $node = Node::load($nid);
     $paragraph = Paragraph::create([
            'type' => 'gallery_image',
            'field_type_createurs' => ['target_id' => $value],
          ]);
          $paragraph->save();

          $current[] = [
            'target_id' => $paragraph->id(),
            'target_revision_id' =>$paragraph->getRevisionId(),
          ];

   $node->set('your_field', $current);
   $node->save();

```

Varible $value is a term id.

Hope to help you.

# Answer
> 0 votes
It took awhile for this to sink in. Thinking of it as creating a paragraph entity on the node helped me with `Paragraph::create`. A first I was thinking of `Paragraph::create` as creating the paragraph type, which, of course, I had already created.

Here's some more example code that is mostly a repeat of @OPTASY's code. All the data is sanitized and, hopefully, the keys give a clear idea which fields are being referenced and when.

```
$node = Node::load($nid);

$current = [];
  $paragraph = Paragraph::create([
    'type' => 'my_paragraph_type',
    'field_from_my_paragraph_type' => ['target_id' => 1]
  ]);
  $paragraph->save();

$current[] = [
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ];

$node->set('field_from_my_content_type', $current);
$node->save();

```

---
Tags: 8, taxonomy-terms, paragraphs
---


# Question
Title: Add FILTER CRITERIA in Views Programmatically
I want to add/modify a `filter criteria` programmatically.

For example, for a view, I added an "Email Address" filter whose value is needed to change dynamically, it is needed to set to the current logged in user's email id.

How to achieve that? Please see attached image for more details. Please help.

# Answer
Use the Devel module and `dpm($view)` and `dpm($query)` after you put like "test@email.com" into the "value" field found in your pic. See the object/array structure of the view and query from the devel output.

Then use the function `hook_views_query_alter(&$view, &$query)` in your module to target the WHERE condition filter condition and set it to the value you want.

Something like:

```
function MYMODULE_views_query_alter(&$view, &$query) {
  global $user;
  dpm($view, __FUNCTION__);
  dpm($query, __FUNCTION__);
  if ($view->name === 'your_view_machine_name') {
    // This will only work as-is if you always have something in the filter by
    // default, I guess. This hook runs always so you could just put
    // 'test@test.com' as the email to filter by in views and this
    // will always override it. I'm sure there is a cleaner way to put
    // the filter dynamically at runtime. But i think thats more complex
    // php that customizes a view.
    //
    // The index 2 below is the index of the condition for the email filter.
    // Your $query structure may be different in your dpm() of the View $query.
    $query->where[1]['conditions'][2]['field']['value'] = $user->email;
  }
}

```
> 27 votes

# Answer
Here's an alternative:

```
$view = views_get_view('view_machine_name');
$view->init_display('default');
$view->display_handler->display->display_options['filters']['your_filter_name']['default_value'] = 'your_value';
$view->is_cacheable = FALSE;
$view->execute();
print $view->render();

```

I know you should probably set this using some esoteric, convoluted method, but if you just want quick and dirty access without messing around this will get you there.
> 7 votes

# Answer
It would be preferable to alter these in hooks rather than at render time so that you are not undermining site performance and caching. Took me age to figure out that hook\_views\_pre\_build() fires too late, you need hook\_views\_pre\_view().

I found reference to using $view-\>add\_item() but struggled for examples, below was my solution for filtering a set of taxonomy terms to only include certain vocabs:

```
function MODULENAME_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name == 'VIEWNAME' && $display_id == 'DISPLAYID') {
    // Add all the terms of a vocabulary to the terms listing widget select field
    $vids = array();
    $vocab = taxonomy_vocabulary_machine_name_load('vocab_name');
    $vids[ $vocab->vid ] = $vocab->vid;

    // Get the existing filters
    $filters = $view->display_handler->get_option('filters');

    if (empty($filters['vid'])) {
      // There is no vid filter so we have to add it
      $view->add_item(
        $view->current_display,
        'filter',
        'taxonomy_term_data',
        'vid',
        array(
          'operator' => 'in',
          'value' => $vids,
          'group' => 1
        )
      );
    }
    else {
      // Add to pre-existing filter
      foreach($vids as $vid) {
        $filters['vid']['value'][ $vid ] = $vid;
      }
      $view->display_handler->override_option('filters', $filters);
    }
  }
}

```

**Edit note**: This comment on d.o group helped me figure out how to get the views filters using `$view->display_handler->get_option('filters')` and to then override them using `$view->display_handler->override_option('filters', $filters);`.
> 7 votes

# Answer
I've had a similar issue but where trying to pass in multiple arguments to a filter. I have used the "views\_get\_view" method, but passing in arguments to the view. I hope it helps someone. You can substitute any argument type or value for your needs:

I have added contextual filters to the view itself (from the advance view settings fieldset). The first one is a "content: has taxonomy term ID". The 2nd one is "content: nid" with "allow multiple" checked and "exclude" checkbox checked (from the 'more' fieldset in the contextual filter pop-up).

```
args[] = '1'; // Term ID
args[] = '1+2+3'; // Node IDs to exclude/include

$view = views_get_view($view_name);
$view->init();
$view->set_display($display);
$view->set_arguments($args);
$view->execute();
$view->result

```

Update: I forgot to mention, within the contextual filter values, you may need to select php code and return the view arguments passed in. Eg:

```
return $view->args[1];

```
> 4 votes

# Answer
In Drupal 8 you can use `ViewExecutable::setHandler($display_id, $type, $id, $item)` to set a filter programmatically.
> 3 votes

# Answer
Here's an example on how filter criteria can be added programmatically in Drupal 8:

```
/**
 * @param ViewExecutable $view
 * @param QueryPluginBase $query
 *
 * Sets a custom custom filter criteria (takes current language into account)
 */
function MODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->storage->id() === 'my_view_id') {
    $query->addWhere(0, 'node__field_custom_criteria.field_custom_criteria_value', \Drupal::languageManager()->getCurrentLanguage()->getId(), '=');
  }
}

```

The above query will add a criteria that filters nodes where the `field_custom_criteria` field equals the currently selected language.

More info can be found in the docs: hook\_views\_query\_alter
> 1 votes

# Answer
Based on @Duncanmoo's answer above that I felt was best, I added the following filters to my view - thought these would be useful examples in case you weren't trying to filter based on a referenced taxonomy but instead on a referenced entity or a NID:

```
function [MYMODULE]_views_pre_view(&$view, &$display_id, &$args) {
  if (($view->name == '[your view name]') && ($display_id == '[your display id]')) {
    // Get referenced service - example for entity reference.
    $node = menu_get_object();
    $node_wrapper = entity_metadata_wrapper('node', $node->nid);
    $referenced_service = $node_wrapper->field_service_ref->value();
    // Add service id as a filter to view.
    $filters = $view->display_handler->get_option('filters');
    if (empty($filters['field_service_ref_target_id'])) {
      // Only display operations nodes that reference the same service.
      $view->add_item(
        $display_id,
        'filter',
        'field_data_field_service_ref',
        'field_service_ref_target_id',
        array(
          'operator' => '=',
          'value' => ['value' => $referenced_service->id],
          'group' => 1
        )
      );
    }
    // Add nid as a filter to view - example for NID filter
    if (empty($filters['nid'])) {
      // Don't include current operation in list of related operations.
      $view->add_item(
        $display_id,
        'filter',
        'node',
        'nid',
        array(
          'operator' => '!=',
          'value' => ['value' => $node->nid],
          'group' => 1
        )
      );
    }
  }
}

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to skip specific tables with drush sql-dump?
I have a drush config file ~/.drush/drushrc.php:

```
if (!isset($options['structure-tables']['common'])) {
  $options['structure-tables']['common'] = array(
    'cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog'
  );
}

$options['structure-tables']['common'] = array_merge($options['structure-tables']['common'],
  array('ctools_css_cache', 'ctools_object_cache', 'logz', 'views_object_cache')
);

```

And I have a bash script file:

```
/usr/bin/drush sql-dump --root="/home/username/domains/sitename/www" --skip-tables-key="common" --gzip --result-file=/home/username/backup/$year/$month/dbname_$date_now_time.sql

```

But when I execute it the backup file still have data in cache tables. What am I doing wrong?

And second question is - If I put this into crontab do I need to put configuration file somewhere else?

I use Drush version 8.

# Answer
Dump all tables except the `cache` table and tables starting with `cache_`.

```
drush sql-dump --skip-tables-list=cache,cache_* > dumpfile.sql

```

Database structure only. No data at all.

```
drush sql-dump --extra=--no-data > dumpfile.sql

```

Data only. No cache data and no cache structure.

```
drush sql-dump --skip-tables-list=cache,cache_* --data-only > dumpfile.sql

```

No cache data but dump in their structures.

```
drush sql-dump --structure-tables-list=cache,cache_* > dumpfile.sql

```

sql-dump documentation
> 42 votes

# Answer
For some reason cache\_\* did not work for me with drush 9+ until I omitted the underscore. However, this may be specific to my (server) bash/terminal. What worked for me:

```
drush sql-dump --skip-tables-list=cache*

```

and you can always add the `--verbose` to see the actual mysql dump and it's --ignore parameter.
> 1 votes

# Answer
Sorry I can't help you much with your first question ...

Your 2nd question asked:

> And second question is - If I put this into crontab do I need to put configuration file somewhere else?

The drush documentation site links to drushrc.php example file that says where you may place the rc file:

https://raw.githubusercontent.com/drush-ops/drush/master/examples/example.drushrc.php

> Rename this file to drushrc.php and optionally copy it to one of the places listed below in order of precedence:
>
> 1. Drupal site folder (e.g. sites/{default|example.com}/drushrc.php).
> 2. Drupal /drush and sites/all/drush folders, or the /drush folder in the directory above the Drupal root.
> 3. In any location, as specified by the --config (-c) option.
> 4. User's .drush folder (i.e. ~/.drush/drushrc.php).
> 5. System wide configuration folder (e.g. /etc/drush/drushrc.php).
> 6. Drush installation folder.

For Cron the documentation recommends that Drush be configured to run as the same user that runs your webserver. That being said I recommend you place your rc file in location (5), a system-wide configuration folder. Yes, more localized Drush rc files will then need to override your system-wide configuration file as needed (oh well).
> 0 votes

---
Tags: drush, backups
---


# Question
Title: Create a X discount for every Nth product from the same category
I know this is pretty complex task, I don't expect a solution, but a guide on where to start.

(Drupal 7 is in question)

I need to apply X% discount for every Nth products that are in the same category. Category, X and N needs to be imputed by user.

So far, I was able to make a rule (with fixed X, N and category) that calculates a needed total discount that needs to be subtracted from total amount. How can I apply that number (or should I do something different?), and how to get user's input for X, N and category?

Thank you for any help.

# Answer
> 0 votes
Depending on how you've constructed your product data model, the *Per-quantity category discount (% off)* offer type supplied by the Commerce Discount Extra module should just work. It lets you specify how many products of which product category must be present on an order before the next one is discounted by any percentage (e.g. buy 2, get 1 free - 100% off). It's repeatable, meaning you can apply the discount any number of times on the same order so long as the right quantity is present, and you have some rudimentary sorting options - e.g. discount the cheapest or most expensive first.

If that solves it for ya, mark this answer as accepted. If you need a little more detail, feel free to add a comment and I'll help if I can. : )

---
Tags: 7, commerce, rules
---


# Question
Title: How to automatically post a message with the discount on the site?
I have a store with Commerce 2 and Drupal 8.

In my store I created a reminder of 20% on the whole site.

I want a message to be posted on my site with the conditions, the percentage, the end date and the description of the discount.

A bit like this :

How can I do this ?

Thank you

# Answer
There is no tool for general messages like this, because every site will construct its front-end differently. If this is only an occasional matter, you'd be best just creating the content manually. If it's going to happen with some regularity, you may just be best using custom code to define a template that can load a promotion entity and fill in the offer details from its fields.
> 0 votes

---
Tags: 8, theming, commerce
---


# Question
Title: Prevent delete content before it is removed in external index
This is my use case. We have a Drupal 8 installation that we used as decoupled, so one external API retrieve all content and them indexed. So, this external API update indexed content when Changed date is updated. But, if the content is missing it doesnt do nothing. The content is removed from index only when content is unpublished.

I was thinking in deny users to delete content, and add an state or a field value to notify that the node need to be deleted in external index. Then a while delete content with a cron.

# Answer
> 0 votes
The plan was **prevent users** to delete content, then **unpublished** content, save.. then **index will remove** content after a while. Time later we can **remove unpublished** content.

What I did

1. Remove permission to delete for all roles(without admin). So no body can delete content directly.
2. I enabled Content Moderation (core) module. Here I added a State "To Delete"(unpublished) to all CTs. So we add the option to erase a content later.
3. When external index check content unpublished and erase it.
4. I added a cron that check content with State "To Delete" that have more than 1 week without been updated. Then we delete those nodes.

```
function MODULE_cron() {

  $nids_to_delete = getIdsByModerationState('to_delete');

  // @todo verify if empty array
  // @todo verify default language
  $query = \Drupal::entityQuery('node')
    ->condition('nid', $nids_to_delete, 'IN')
    ->condition('changed', strtotime('-1 week'), '<=')
    ->condition('status', NOT_PUBLISHED);
  $nids = $query->execute();
  // @todo test entity_delete_multiple('node', $array);
  foreach ($nids as $nid) {
    $node = Node::load($nid);
    $node->delete();
  }

}

function getIdsByModerationState($moderation_state) {
  $query = \Drupal::database()->select('content_moderation_state_field_data', 'ms');
  $query->join('node_field_revision', 'nf', 'nf.nid=ms.content_entity_id AND nf.vid=ms.content_entity_revision_id AND nf.langcode=ms.langcode');
  $query->fields('ms');
  $query->condition('ms.moderation_state',$moderation_state);
  $results = $query->execute()->fetchAllAssoc('content_entity_id');
  $array_result = array_keys($results);
  return $array_result;
}

```

---
Tags: nodes, 8
---


# Question
Title: How create Menu items by permissions for a view page?
My client wants a menu with a link for each content type.

* Each item will displayed if the user have permission to create that content type.
* Each item will show a list of content only for that content type.

To accomplish this, I create a view page that have a filter for bundle. In that way I can use same view page for all content types. I tried too, to use same view page like **/admin/content** but I need to pass the content type to filter for that machine name.

What I trying to do, is create a menu item for each content type, and set permission for each item(link) using the permission that have each content type.

E.g.: My menu have a Item Article. You should see this item only If you have right to create an Article. When you click here you will see all the content Articles(like /admin/content).

**It suppose that a user or role, that have permission to create a content type.. should see the item.**

**How can I create menu items with permission to a view?**

There is my issue, because it use the permission in the view page, and not in the route.

.links.menu.yml

```
content_types.admin_1:
 title: 'Articles'
 parent: content_types.admin_menu
 route_name: content_types.admin_1
 route_parameters:
  type: article
 description: 'Content articles'

content_types.admin_2:
 title: 'News'
 parent: content_types.admin_menu
 route_name: content_types.admin_2
 route_parameters:
  type: nouvelle
 description: 'Content news'

```

.routing.yml

```
content_types.admin_1:
  path: '/admin/view-test'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Articles'
  requirements:
    _permission: 'create article content'

content_types.admin_2:
  path: '/admin/view-test'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'News'
  requirements:
    _permission: 'create nouvelle content'

```

As you see I added \_permission: 'create article content' but it didn't do anything.

admin/structure/views/view/view\_test?destination=/en/admin/structure/views

The role for the user that I'm using doesn't have permission to create article or news.

**UPDATED:**

I created a .permissions.yml and used \_permission: 'access menu item 1' but it display the item even if this permission is not ticket for that role.

.permissions.yml

```
'access menu item 1':
  title: Access Menu MTL 1
  description: Allow users to access menu MTL

```

Any suggestion?

**UPDATED: January, 2019**

The issue is try to use same view page(/admin/content) for each Content type with different permissions. You dont set permissions to each link, instead you set permission to the view (or item) that you are trying to access.

# Answer
> 0 votes
**What I did:**

I tried using dynamic menus. But it isn't functional for my purpose. Because, each link menu could have different access by roles.

Then I realized that I needed to create a view for each type of content to be able to manage an individual permission.

Therefore I need to create a view each time that I create a CT, so the is no sense to do it dynamically.

**How I did:**

1. I create a view for each CT with a filter content by type. And also I set permission for each view for same CT. And a custom route.
2. Create one item menu for each CT and set as route same as is in the view.

.links.menu.yml

```
    vdm.tc_sujet:
     title: 'Sujets'
     parent: system.admin_content
     route_name: vdm.tc_sujets
     description: "Content type subject."
     weight: -1

```

.routing.yml

```
    vdm.tc_sujets:
     path: '/admin/content/sujet'
     defaults:
       _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
       _title: 'Sujets'

```
3. As result if user have access to that view the item menu will be displayed.

**Note**: I think that dynamic menus it fix great for add link item to nodes.

---
Tags: views, 8, users, navigation
---


# Question
Title: Set value of file field using entity_metadata_wrapper non working
I have a custom entity with a file field accepting multiple values. I would like to set file values according to https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers#example-value-set-save but none of the two methods are working here. I always get this error

```
error  php  Error: Call to a member function set() on null in include().

```

I am running Drupal 7, `file_entity` module enabled. Here follows the code:

```
$file = file_load(8172);
$wrapper = entity_metadata_wrapper('sys_ind', 13718);
$wrapper->field_allegati->file->set( $file );
$wrapper->save();

```

# Answer
> 1 votes
Fixed! Thanks to this post Save a new value with entity\_metadata\_wrapper to an entity field which is an array

```
$file = file_load(8172);
$node = entity_load('sys_ind', array(13718));
$wrapper = entity_metadata_wrapper('sys_ind', '13718');

$wrapper->field_allegati[NULL]->file->set( $file ); # This worked

$wrapper->save();

```

so the fix is using `NULL` (at least in multivalue field like mine is), not 0 or any other index nor `[]`.

# Answer
> 0 votes
Try this to see if it works:

```
$wrapper->field_allegati[0] = (array) $file;

```

The wrapper seems to struggle with file fields

---
Tags: entities, files
---


# Question
Title: Embedding a view for search and redirection
I have set up a view for searching using Search API. In my specific setup, I need this search to be context sensitive, i.e. I have several pages /foo/search, /bar/search, ... and these return different results.

Currently, I do this by making a content type which has a field containing the necessary information and additionally a search processor, which alters the query accordingly.

Additionally, I use Twig Tweak to embed the search view in this content type as described here. This works if I load the search with the query string, e.g. localhost/foo/search?search\_api\_fulltext=something.

My problem is now that if I click the "Apply" button in the search, I am being redirect to the page created by the view. This page is lacking the content type's data and I no longer get the context sensitive search results.

Is it possible to change this behaviour of the view's Apply button or do you know another way this could be implemented?

Thanks!

# Answer
Following this reply on drupal.org and this answer on SO, I added a hook:

```
function my_module_views_pre_build(ViewExecutable $view) {
  if ($view->id() == 'my_view_id') {
    $view->override_url = Url::fromRoute('<current>');
  }
}

```

Some of the assumptions in Drupal and the workarounds are *so* annoying. Days wasted. :(
> 0 votes

---
Tags: views, 8, search
---


# Question
Title: Add another button removes the default values from my fields on node form
I have a node form on which two fields are displaying. One is a list of radio buttons which is required field.

I am getting a value from url using `arg(3)` and setting the default value of that field

```
$form['field_test'][LANGUAGE_NONE]['#default_value'] = arg(3);

```

I have a link field which is a multi valued field. It means this field as `add another button`.

When I click on this `add another button` and then submit the form, I see an error of Test field is required, and that default value of `test field` gone.

Without clicking the `add another button` everything works fine.

How can I set a default value of the test field in this case?

Code:

```
if (!$form['nid']['#value']) {
  if (arg(3)) {
    // Select the default value.
    $tg = arg(3);
    $form['field_test'][LANGUAGE_NONE]['#default_value'] = $tg;
  }
}

  // Make the field readonly.
  $form['field_test'][LANGUAGE_NONE]['#attributes']['disabled'] = 'disabled';

```

# Answer
Ok. I found the solution. Let me share my code here.

I stored the argument in the `$form_state['storage]` so that it can be preserved during the ajax call.

```
if (arg(0) == 'node' && arg(3)) {
    $form_state['storage']['field_test_value'] = arg(3);
}

// Only on node creation.
if (!$form['nid']['#value'] && isset($form_state['storage'])) {
    $form['field_test'][LANGUAGE_NONE]['#default_value'] = $form_state['storage']['field_test_value'];
}

$form['field_test'][LANGUAGE_NONE]['#attributes']['disabled'] = 'disabled';

```

Hope this will help someone.
> 0 votes

---
Tags: 7, nodes, forms
---


# Question
Title: How to upcast webform submission in custom routes resp. controller?
Using this route:

```
confirm:
  path: '/node/{node}/submission/{webform_submission}/confirm'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MymoduleController::confirm'
    _title: 'Confirm your submission'
  requirements:
    _permission: 'confirm webform submission'

```

And visiting `node/15/submission/15/confirm` I get the error:

> RuntimeException: Controller "Drupal\mymodule\Controller\MymoduleController::confirm()" requires that you provide a value for the "$submission" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one. in Symfony\Component\HttpKernel\Controller\ArgumentResolver-\>getArguments()

What am I doing wrong? Why doesnt it load the submission 15? It does exist.

Edit: this is my Controller, the second argument is always null:

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\Controller\EntityViewController;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Entity\EntityInterface;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\WebformSubmission;

/**
 * @todo
 */
// class MymoduleController extends ControllerBase { // doesnt make a difference
class MymoduleController extends EntityViewController {
  public function confirm(EntityInterface $node = null, EntityInterface $submission = null) {

    debug($submission);

    $response = new Response( 'test' );

    return $response;
  }
}

```

# Answer
You probably just need to declare the parameter type:

```
confirm:
  path: '/node/{node}/submission/{webform_submission}/confirm'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MymoduleController::confirm'
    _title: 'Confirm your submission'
  requirements:
    _permission: 'confirm webform submission'
  options:
    parameters:
      webform_submission:
        type: entity:webform_submission

```

The parameter names also need to match, so update your controller accordingly:

```
public function confirm(EntityInterface $node = null, EntityInterface $webform_submission = null) {

```
> 3 votes

---
Tags: 8, routes, webforms
---


# Question
Title: How to show a specific amount of multivalue fields depending on a value of the parent node?
I need to show a specific amount of multivalued fields on a comment **depending on the value of the node** (field\_optionsamount) that the comment is attached to. There are modules that allow to set the number of fields shown (e.g. https://www.drupal.org/project/multivalue\_extras) but the limit is the same for all fields and does not depend on the node.

The code below removes the add more fields button and provides the amount of fields that need to be shown. I don't know how to show x fields though.

```
function customisations_form_comment_form_alter(&$form,&$form_state,$form_id) {
     $parentNode = $form['nid']['#value'];
     $node_data = node_load($parentNode);
     $amountOptions = $node_data->field_optionsamount['und'][0]['value'];
     drupal_set_message("Amount: ". $amountOptions);
     unset($form['field_toinvest']['und']['add_more']); //hides the add more button
}

```

# Answer
> 0 votes
Don't know what the proper way is to handle answers where the solution comes from another posting. So I only make the reference here: https://drupal.stackexchange.com/a/140861/24957

The code below works perfectly and only shows $amountOptions fields.

```
if (!isset($form_state['build_info']['args'][0]->field_toinvest[LANGUAGE_NONE][0]['value']) && !isset($form_state['default_fields'])) {
for ($i = 0; $i < $amountOptions; $i++) {
// First field is already in form.
  if ($i > 0) {
    $form['field_toinvest'][LANGUAGE_NONE][$i] = $form['field_toinvest'][LANGUAGE_NONE][0];
  }

  // Set form values
  $form['field_toinvest'][LANGUAGE_NONE][$i]['value']['#default_value'] = 0;
  $form['field_toinvest'][LANGUAGE_NONE][$i]['value']['#value'] = 0;

  // Set row weight
 $form['field_toinvest'][LANGUAGE_NONE][$i]['_weight'] = array(
  '#type' => 'weight',
  '#title' => t('Weight for row ' . ($i + 1)),
  '#title_display' => 'invisible',
  '#delta' => $i,
  '#default_value' => $i,
  '#weight' => 100,
 );
}
$form_state['default_fields'] = 1;
$form_state['field']['field_toinvest'][LANGUAGE_NONE]['items_count'] = amountOptions - 1;
}

```

---
Tags: 7
---


# Question
Title: Filter view list items by user property and item property
I have a view where I want to output a list of content node teasers. At the moment all content nodes are used, but I want to filter the output to only contain nodes that have a certain value in a taxonomy field property they have, check if the current user has a certain role that is similar to the property and only then show them in the output.

So far I've tried to programmatically filter the output in the hook mytheme\_preprocess\_views\_view\_unformatted of my theme with the following code

```
function mytheme_preprocess_views_view_unformatted(&$variables) {
    $result = $variables['view']->result;
    $entity = $result->entity;
}

```

but that crashes the site and doesn't give me the results to filter.

Is there a way to filter the content nodes programmatically or view the view settings and if so how?

# Answer
> 3 votes
I think I understand what you're describing, and it is theoretically possible to handle in the hook as you've started, with something like this:

```
/**
 * Implements hook_preprocess_views_view_unformatted().
 */
function mymodule_preprocess_views_view_unformatted(&$variables) {
  if (isset($variables['view'])) {
    $view = $variables['view'];
    // You'll want to check the ID && possibly the current_display so as not to fire on every View!
    // In this example, my View is called "test", and I have a page display called "page_1".
    if ($view->id() == "test" && $view->current_display == "page_1") {
      $result = $view->result;
      // You mentioned doing something regarding the user, so you could grab that here.
      $current_user = $variables['user']->account;
      // The $result will be an array of ResultRow entities.
      foreach ($result as $key => $resultRowEntity) {
        // Do some customized logic on each row.
        // You can access the entire entity here if needed like this:
        $row_entity = $resultRowEntity->_entity;
        // In my case this is a Node, so can do something to get a term field from it.
        // In this example, getting the "some_field" and the first delta of it as a string value.
        $some_field_on_the_node = $row_entity->get('field_some_field')->getValue();
        // You could do some sort of logic here to determine whether or not to unset this row.
        // In this example, I'll say if the field doesn't equal 2, OR the user ID is not equal to 1, unset the row.
        // This would remove it from the result.
        if ($some_field_on_the_node != "2" || $current_user->uid != 1) {
          // You'll want to unset it from 'rows' to not display it.
          unset($variables['rows'][$key]);
        }
      }
    }
  }
}

```

I think the takeaway is to use "isset" to avoid those nasty PHP errors, and I highly recommend using XDebug, or at the least the `devel` && `kint` modules, so that in your code, you can put things like `ksm($variables['view'])` to get some insight into what variables you have available to use. PHP can be very finicky when you try and reference things that don't exist!

Even though this might *technically* work, it's worth noting that a better approach would be to implement a relationship in Views to bring in the taxonomy term entity being referenced on your node, and that would allow you to add View filters in the UI to massage out the data that way. You could also add a role that could be associated with viewing your particular content type, and this would automatically exclude it from Views results regarding the user if they didn't have this role.

Of course, I may me misunderstanding the complexity of your use case. Another "better practice" approach would be to implement a custom Views filter, which could then be added via the Views UI and maintained separately in a custom module, and would possibly allow for a cleaner implementation - It's somewhat of a broad topic, but I think this is a great intro to the topic: https://www.webomelette.com/creating-custom-views-filter-drupal-8.

I hope this helps point you in the right direction!

---
Tags: views, 8
---


# Question
Title: Rules Conditions to check changed Developer app field
I want to create a rule that takes an action whenever the overallStatus field of a Developer App is changed. But how do I do this since I think I cant use app-unchanged to compare the before and after state of the field?

Does anyone know how to do this?

This is an export of my current rule so far:

```
{ "rules_update_api_key_after_approval" : {
    "LABEL" : "Update API Key after Approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_http_client", "devconnect_developer_apps" ],
    "ON" : { "devconnect_developer_app_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "app" ], "type" : "developer_app" } },
      { "AND" : [
          { "entity_has_field" : { "entity" : [ "app" ], "field" : "field_status" } }
        ]
      }
    ],
    "DO" : [
      { "request_url" : {
          "USING" : {
            "url" : "My Company URL",
            "method" : "GET",
            "data" : "cred_status=[app:credentialStatus]\r\noverall_status=[app:overallStatus]\r\nstatus=[app:status]"
          },
          "PROVIDE" : { "http_response" : { "http_response" : "HTTP data" } }
        }
      }
    ]
  }
}

```

Note: Wwhen I access it from data comparison the field exists in app:overallStatus but when I use entity has field and choose app on the data selector, on the field selection it only shows taxonomy\_forums, comment\_body, body, etc and no overallStatus field. And it is Drupal 7.6.

# Answer
> 1 votes
Piece of cake:

* add a Rules Condition like "Entity has field" (for your `overallStatus` field), which will make that field available for testing in subsequent Rules Conditions and/or Rules Actions.
* add a Rules Condition (*after* the previous one, important!) to verify if the `unchanged` value of your `overallStatus` field is yes or no equal to the value of your `overallStatus` field (which is the value that would be saved).

PS: I'm assuming your question is about D7.

---
Tags: rules
---


# Question
Title: Webforms: pages 1,2 of 4 not being displayed
I'm developing my first Drupal 8 Webforms application. It had three pages to start with and I had managed to get it to do what I wanted it to. I have also developed a WebformHandler to go with it.

I needed to add an extra page between the old 1st and 2nd page. I created this using the "build" tab and it was created in 4th position in the list of pages, so I dragged it up to 2nd position and did "Save Elements".

But then, when I used the "View" tab to try out the form, the dialogue started at the 3rd page (the old 2nd page). I have now deleted the new 2nd page and appear to have the same old configuration that worked, but using the "View" tab still ignores the first page.

I have flushed all the caches; I have looked in the database for anything obvious (but not found anything); I have looked at the YAML files in the module I created for the Webform; I have even rebooted the server.

I have tried to scan the entire Drupal file tree looking for files that have been modified in the last couple of hours (since the webform last started correctly), but I haven't managed to find anything, except the WebformHandler, but that isn't called before the initial page is shown.

Using a different browser (Safari instead of Chrome) produces the same result, so I guess the problem is on the server and not the client.

Somewhere, something is holding information about my webform: could anyone help me to locate it?

# Answer
I was looking in the wrong places...

The element editor in Webforms includes an `Access` tab. For the pages that were not being shown I had removed all the permissions, which included the permissions of ‘Administrator’, the user I was logged in as. So – obviously – those pages were not shown.

Duuhh.
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: "Expand all menu links" Menu Block selection shows all menu items in block not just active trail items
I have a menu block that I have setup with Initial visibility level = 2 and Number of levels to display = Unlimited. When I check the "Expand all menu links" checkbox and view my menu block it is displaying ALL menu items at visibility level 2 VS the menu items in the active menu trail.

What's the be way to display only the active trail menu items without going into each menu item and setting them as "Show as expanded" individually.

I'm using Drupal 8 and a customized Bootstrap theme

# Answer
Found a patch that does the trick: https://www.drupal.org/project/menu\_block/issues/2811337
> 1 votes

---
Tags: 8, blocks, navigation, bootstrap-theme
---


# Question
Title: How to insert fields into a link field in twig?
We have several fields on our `Article` content type, one of which is a `Link` field. In a `twig` template we would like to display a `<section>` such that all of it is clickable with different fields inside of it.

Current `node--article.html.twig`

```
<section>
  <a href={{ url }}>{{ label }}</a>
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
</section>

```

Modified `node--article.html.twig` template to make entire `<section>` clickable (desired output).

```
<a href={{ url }} >
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
</a>

```

**Is there another way I should be doing this?**

I was looking for something similar to below. It would output what is under the `Modified node--article.html.twig` (above)

```
{{ link(label, url)|insert(content.body, content.field_subtitle, content.field_category) }}

```

# Answer
I don't see anything for the `insert` tag in Twig or Drupal, but you can preprocess the `url` variable in `mytheme.theme` and pass it to the template, giving you what you want:

```
<a href="{{ url }}" >
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
</a>

```

The `url` variable would be created in the preprocess function.

If its a standard link field, you could try:

```
$link = $node->get('field_link')->getValue();

if (!$external) {
  $variables['url'] = Url::fromUri($link['uri'])->toString();
}
else {
  $variables['url'] = $link['uri'];
}

```

Edit: totally forgot the line that checks if it is external.
> 1 votes

# Answer
You can use something like `{{ node.field_link.0['#url'] }}` to get the absolute value of a url in a link field.

You can use `{{ dump(_context) }}` temporarily to get exact array key names and values out of twig debug.
> 0 votes

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


# Question
Title: How to use language-specific menu items in URL aliases
I'm working on a site with internationalization from the source language, English, into a few other languages. Translating the pages has worked out fine; however, I'm running into trouble with URL aliases.

Some of our pages have different menu labels vs. page titles (e.g. Terminals as the menu label vs. Terminal Information as the page title), and since the client wanted the shorter menu labels in the URL, my default path pattern (set using the Pathauto module) is `[node:menu-link:parents:join-path]/[node:menu-link:title]`.

Menu items are also set per language – so while Terminals is the English version of the menu item for that page, when viewing the site in French, I have a menu item labeled Aérogares that's used only when the site is translated into French. This means that when the URL is constructed for a page called Maps in English and Plans in French whose parent is Terminals/Aérogares, the English URL alias is `/terminals/maps`, but the French alias is `/fr/aérogares/plans`.

Another part of the problem I'm facing is that when I save a translation of the page, this menu pattern ignores the source language and resaves every language's alias as that of the language of the translation (when saving a French translation, the English alias becomes `/aérogares/plans`, the Arabic alias becomes `/ar/aérogares/plans`, etc.).

I've tried a few different tokens as part of the URL alias options to see if they'd work, but without success:

* `[node:source:menu-link:parents:join-path]`
* `[node:source:menu-link:title]`
* `[node:source:title_field]`

There are a few different options that would be acceptable in the end, listed here from most to least desirable:

* Foreign-language URL aliases use that language's menu structure, e.g. Terminals/Maps is `/terminals/maps` in English and `/fr/aérogares/plans` in French, and saving one language doesn't affect the others
* Foreign-language URL aliases use the language code followed by the full English path, e.g. Terminals/Maps is `/fr/terminals/maps` in French
* Foreign-language URL aliases use the language code followed by the current page's English title, e.g. Terminals/Maps is `/fr/maps`

I'm running Drupal core version 7.61. Here's a list of relevant translation- and menu-related modules I currently have in use:

* Entity Translation 7.x-1.0
* Entity Translation Menu 7.x-1.0
* Internationalization 7.x-1.26
* Menu translation 7.x-1.26
* Pathauto 7.x-1.3
* Token 7.x-1.7
* Translation Management (tmgmt) 7.x-1.0-rc3

How can I accomplish one of the desired URL structures and keep them language-independent when saving revisions to content?

# Answer
Your configuration is too complex to be able to say with certainty, but your menu tokens seem to support "languages", so it may be the Path that needs some extra support.

Have you enabled Path translation or tried Pathauto i18n?
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: How to create entity relation of counselor to client?
I'm trying to create a relation in D8 between a counselor and clients. The counselor would have to record counseling hours for each client. I've looked at the group module, even building the relation using RedHen CRM. Just curious, anyone have suggestions?

# Answer
> 0 votes
You seem to need two relations/references; one to connect clients with counselors, assuming that doesn't change for each new session, and then a session node (Session Content type) related to either the client or the councelor, depending on what makes more sense in your case.

Or you might orient it around sessions, where you have two user reference fields, one to the counselor and the other to the client. Although that seems less likely to make sense.

If the hours is the only thing that needs to be recorded maybe you can get away with only the reference between counselor and clients, with the added Hours field to the reference field, with unlimited values so with each new session another value is added. You can use Views to summ them up.

You haven't said anything about privacy and permissions requirements and how the data is maintained. There are modules that can control access through references made between entities. Maybe explore that to find the right combination for you.

Group module can also be used, although it may be an overkill depending on your requirements.

Which modules/structures to use and build becomes obvious once you have all your requirements clarified.

---
Tags: 8, entities, taxonomy-terms, group
---


# Question
Title: How to append options and classes into a custom attribute in Twig?
In our twig template we have a need to wrap certain fields with a `Link` field. In the existing `twig` template there already exist an `attributes` variable (accessed by adding `attributes`), but we have a need to have a custom one. Couldn't find any documentation on if you can pass options and attributes from one field to a custom `twig attribute`.

**Is there a way to append all `options` and `classes` from a field's `attributes` into a custom attribute in a `Twig` template without any `hook_preproceess_hook`?**

Existing `node--article.html.twig`

```
<section {{ attributes }}>
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
  {{ content.field_link }} /* has its own options and attributes */
</section>

```

Desired output

```
/* pass the options and attributes from field_link into the a_attr */
/* This did not result in what we wanted */
{% set a_attr = create_attribute(content.field_link.0['#attributes']) %}
<a href="{{ content.field_link.0['#url'] }}" {{ attributes }}>
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
  <div> {{ content.field_link.0['#title'] }} </div>
</a>

```

# Answer
> 2 votes
According to the syntax your declaration is a little off. The function is also `create_attribute`, not `create_attributes`.

The `{{ attributes }}` variable in a node twig template won't hold what you think it holds for the link tag. So, you will need to create a new one.

https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

You probably want something like this:

```
{% set link_attributes = create_attribute() %}
{% set link_href = content.field_link.0['#url'] %}
{% set link_title = content.field_link.0['#title'] %}

<a{{ link_attributes.setAttribute('href', link_href).setAttribute('title', link_title }}>
  <div>{{ content.body }}</div>
  <div>{{ content.field_subtitle }}</div>
  <div>{{ content.field_category }}</div>
  <div> {{ content.field_link.0['#title'] }} </div>
</a>

```

Unfortunately, since you are wrapping fields with the value of a link field, this might be more manual than you would prefer. This is because Drupal is not rendering the field, you are creating html on the fly - link fields in particular are tricky because there is often the case of wrapping data with an anchor in say, a card display format or a clickable CTA. I am not sure if anyone has found better methods of achieving this.

I wonder if anyone has written an extension that will in fact let you render a link field but intake other fields in a tag like you mentioned in another question, so you could wrap them.

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


title: Navigation for book collections

text:
# Question
Title: Navigation for book collections
I'm working in a projet where I have to show a collection of books. In this website I managed using the books navigation block, for one collection with many books, with css I managed to set a tree view and indication where you are, but only allows one collection of books. The problem is that I have to make as least 23 collections, each of them belonging to a province.

Is there a way to replicate that book navigation for each collection? Could I make them with block menu with tree view and the same CSS style? I think the concept of book collections is missing, from the editorial point of view.

# Answer
I'd rather try to use the Views Accordion module. Here is a screenprint of what you can get from it (from its project page):

If your question is about D7, you may also want to add the Views Nested Accordion module. Here is a screenprint of what you can get from it (from its project page):
> 1 votes

---
Tags: nodes, navigation
---


# Question
Title: How to select only time without attaching a date?
Is there a field in Drupal 8 that lets you select a time without actually selecting a date? Or should you just use datetime?

# Answer
You can use datetime element and disable date widget:

```
$widget['time_container']['time'] = [
  '#type' => 'datetime',
  '#title' => $this->t('Time'),
  '#size' => 20,
  '#date_date_element' => 'none', // hide date element
  '#date_time_element' => 'time', // you can use text element here as well
  '#date_time_format' => 'H:i'
];

```
> 2 votes

# Answer
Depending on what you want to select time for, you may want to try HMS field.

> The field stores values as integer. Both input and output can be formatted as Hours, Minutes and/or Seconds. Alter functions provide a way for developers to add their own format.

Please note that this is a great field for "time durations," but not so good if you are trying to capture a time of day with PM/AM.

Timefield was a good option for capturing just time of the day, BUT it has not been ported to Drupal 8.
> 1 votes

# Answer
Hi you can use https://www.drupal.org/project/time\_field module. Easy and perfect fit.
> 1 votes

---
Tags: 8, datetime
---