# Question
Title: Migration Source YML File import date string into date and time field of content type
I have a json file full of data exported from a wordpress site, one field being a string representing a date and time: "03/15/2012 14:46:19". I would like to import that string into a date and time field of a drupal 8 content type.

I am using a Migration from Source YML file.

```
fields:
 -
  name: date
  label: 'Date'
  selector: date

```

Then in process:

```
process:
  field_press_release_date: date        # is it as easy as this?

```

Is there a special plug in I'm not seeing listed on: https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins

I see format date, but couldn't get any format to work. I have complete control over the format of the date string, I have to do some processing of data from wordpress before drupal so I can do pretty much whatever is needed, if it really is as easy as setting the date\_field to the date\_string from the fields list, what format does date\_string need to be in?

I cannot find a simple example of importing a string into a date and time field, thank you for any assistance!

# Answer
The migrate plugin that handles this is FormatDate. It looks like you are missing the input and output date formats. For date-only, you would do something like

```
process:
  field_date:
    plugin: format_date
    from_format: 'm/d/Y'
    to_format: 'Y-m-d'
    source: event_date

```

and for date+time, it would look something like

```
process:
  field_datetime:
    plugin: format_date
    from_format: 'm/d/Y H:i:s'
    to_format: 'Y-m-d\TH:i:s'
    source: event_time

```

When migrating into the core datetime/daterange fields, the `to_format` needs to be those strings (these were written to be generic, not just for those field types). The `from_format` gets adjusted to your input source. If you look at the references below, there is also a way to specify time zone.

That plugin is unit tested, so core doesn't provide any YAML example, but you may be able to glean samples from FormatDateTest.

References:
> 0 votes

---
Tags: 8, datetime, migrations
---


# Question
Title: How to get form values in URL as keys of an array
I have a custom form with min and max price value:

```
    $form['price']['min'] = [
      '#type'          => 'hidden',
      '#default_value' => isset($_GET['price']['min']) ? $_GET['price']['min'] : '',
      '#attributes'    => ['id' => 'price-min'],
    ];

    $form['price']['max'] = [
     '#type'          => 'hidden',
     '#default_value' => isset($_GET['price']['max']) ? $_GET['price']['max'] : '',
     '#attributes'    => ['id' => 'price-max'],
    ];

```

and I would like the URL after the form is submitted to look like this:

```
/search?price%5Bmin%5D=5000&price%5Bmax%5D=10000

```

but actually it's coming out like this:

```
/search?min=5000&max=10000

```

How can I get the form values to appear in the URL in the required format?

# Answer
> 2 votes
Try adding:

```
$form['price']['#tree'] = TRUE;

```

This tells the form builder you want to nest field names. Otherwise it will just use the most immediate element keys for the field names, as you have found.

This is actually useful behaviour most of the time, as it means you can group fields in containers such as fieldsets without affecting their name attributes.

---
Tags: 8, forms
---


# Question
Title: How come I cannot fetch the name of the taxonomy term from term id?
We are using the following code to fetch all the taxonomy term values in the *term\_category* vocabulary.

```
$db = \Drupal\Core\Database\Database::getConnection();
$term_categories = $db->query('select tid, vid from taxonomy_term_data where vid ='\'term_category\'');

foreach($term_categories as $category) {
  $category_term = (\Drupal\taxonomy\Entity\Term::load($category->tid));
  ksm($category_term->label()); // returns NULL.
  ksm($category_term->getName()); // returns NULL.
}

```

When we run it, we get `NULL` as label.

The *Article* content type has a *field\_category* field that is an entity reference for the *term\_category* vocabulary. Currently, no *Article* node has any value populated for that field, as it is optional.

Why I cannot get the taxonomy term name from its ID?

# Answer
Currently your problem is that you're trying to call entity class methods on a `stdClass` object - directly querying the database means you're not using the API any more, the results you get aren't entities.

Unless there's a particular reason to do so, though, you shouldn't have to do it that way.

For example, the same query can be executed like this through the API:

```
$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadByProperties(['vid' => 'term_category']);

foreach ($terms as $term) {
  $name = $term->getName();
}

```

It's quicker (loading in one go, not single loads in a loop), fewer lines of code, and when you bring caching into it, probably more performant.
> 2 votes

# Answer
Try This:

```

$term_category = 'term_category';
$term_data = [];
  $terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($term_category);
  foreach ($terms as $term) {
    $term_data[] = array(
      'title' => $term->name,
      'description' => $term->description
    );
  }
ksm($terms);

```
> 1 votes

# Answer
The `Term` object has a method for `getName` and `label`.

https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/function/Term%3A%3AgetName/8.6.x

Therefore, if this is a real term entity, it will have a name accessible via `getName`.

You should debug `$category` in the loop to see you are accessing the right property.
> 1 votes

---
Tags: 8, taxonomy-terms, hooks
---


# Question
Title: How to redirect an exposed filter query to a views results page that lives in another panel page?
My setup: Drupal 7.2, Panels 7.x-3.0-alpha3, Views 7.x-3.0-beta3, Chaos tool suite 7.x-1.0-beta1

Say I want to create a fruits directory website. In views I have a content pane "fruits" with exposed filters based on taxonomies "color". The website is supposed to have two panel pages. The first panel page displays only the exposed filter box "search a fruit" with a dropdowns for "color" and a search button. Upon choosing from the dropdown and clicking the search button the user is supposed to get redirected to the second panel page that includes the view's content pane displaying a list of fruits that match the filter (color).

The problem is: the exposed filter box on first page won't redirect to the result page after clicking the apply button. How do I set up views and panels to achieve this?

# Answer
```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='views_exposed_form') {
    global $base_url;
    $form['#action'] = $base_url.'/path_that_you_want';
  }
}

```
> 8 votes

# Answer
I'm not sure if there is a "right" way but I have made this happen by writing a hook\_form\_alter for the exposed filter form to change the destination.

Not ideal, but I got the results I needed.
> 0 votes

# Answer
Simplest solution is to

* Create a views page
* Create an exposed view
* Under Advanced \> exposed form. Set "exposed form in block: Yes"
* Add the block "Exposed form:..." to the required front page.
> 0 votes

# Answer
> Simplest solution is to Create a views page Create an exposed view Under Advanced \> exposed form. Set "exposed form in block: Yes" Add the block "Exposed form:..." to the required front page.

Interlated's above formual got me half way with exposed filter block working to open and display results on new page.

However, I also needed the filter block to be on that results page. So I attached the form (exposed filter block) via view area in the header. Then I encountered recursive behavior when both displays in same view.

To solve, I separated the two displays (page & block) into their own respective views - created one block as the exposed filter which included fields for results, then an entirely new view for page to have a URL to be reached. Page view has one field (title) that is overwritten as whitespace (mainly because results would be redundant but also inaccurate - I found results were accurately displayed from fields in exposed filter block). I kept the same filtered settings between both displays and used better exposed filters using ajax on both displays.

I did this in D8 but likely would be same on 7.
> 0 votes

---
Tags: 7, views, panels, input-formats
---


title: Is the current form an entityform form?

text:
# Question
Title: Is the current form an entityform form?
I am using entityform module on subscribing certain organic groups forms. I only need to add some custom submit logic when unsubscribing the form if the subscribe form was created with entityform.

Depending on if the subscribing form was generated by entityform, when unsubscribing I need to do some custom logic to clean up the DB from entity data not covered by entityform.

I am using hook\_formID\_alter, and this is my $form array:

The thing is I need to do a database clean up if it was submited with entityform in the first place, even though I understand the unsubscribe form is not a entityform.

Therefore, this doesn't work: `if (isset($form['#entity_type']) && $form['#entity_type'] === 'entityform')`

Can you help me identify programmatically which kind of form is the form?

# Answer
> 1 votes
Just to sum up the existing answers both `hook_form_alter` and `hook_form_BASE_FORM_ID_alter` can be used to identify Entityform forms. The output in your question comes from some Organic Group unsubscribe form, identifiable by `$form['#form_id']` which equals `og_ui_confirm_unsubscribe`. A totally different form. You probably have to go to example.com/eform/submit/MYENTITYFORM to fetch some actual form output.

Although I must admit I don't understand what exactly you want to do there, both of the following snippets will work. Place them in your custom module or theme, replace `MYMODULE` with your module's or theme's machine name, flush cache, code on!

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#entity_type']) && $form['#entity_type'] === 'entityform') {
    dpm($form);
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_entityform_edit_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}

```

---

To distinguish if any arbitrary form is placed on a certain URL you can do the following by using just `arg()` or the path alias:

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

  // AFAIK all Entitforms URLs start with /eform.
  // You can simply broaden this request to match
  // more advanced patterns.
  if (arg(0, drupal_get_path_alias()) === 'eform') {
    dpm($form);
  }
}

```

# Answer
> 1 votes
Assuming you are trying to implement a `*_form_alter()` function in a module (which is what I got out of your post), you can implement `hook_form_BASE_FORM_ID_alter()`, which in this case would be `hook_form_node_form_alter()`. If you implement this, it will only be executed if/when you are on a node form, and therefore you will know you are in a node form.

# Answer
> 0 votes
You can check entity form as

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#entity_type'] == 'entityform') {
    // YOUR CODE HERE.
  }
}

```

---
Tags: 7, forms
---


# Question
Title: How to add a view of product fields to a product display so that it changes when add-to-cart form is updated via ajax?
In Drupal 7/Commerce, I would like to display a view of product fields attached to a product so that when the add-to-cart selection is updated and product fields are updated via ajax, the view is also updated (as with typical product fields).

In my case, I want to create an entity reference field ("included hardware") referencing other products attached to a product and use a view to display the result. This must happen at the product level, and not with the product's display node.

I have tried EVA. These fields don't appear on Product Display View Mode configuration.

I have attempted Display Suite (block field). When I select a display template for the product I see the fields on the product type display, but they don't show up on the Product Display node.

Can anyone point me to a solution for displaying a view within a product display that changes when a new product is selected?

# Answer
> 1 votes
The fields that change on a product display as different variations are selected on the Add to Cart form are updated via a series of Ajax commands returned by the form's refresh handler. It's about as complicated as the Forms API gets, to be honest, but it lets us do things like render the related fields and return them with instructions to the JavaScript client on where to place the HTML snippets to reflect the updates.

Because your View isn't associated with the product in the same way, you really need to trigger a refresh of its contents yourself. I'm not aware of any modules that will do that for you unless you can try / rule out Views Field. That *may* work with the product refresh system to support replacing the View alongside other fields.

That said, that's kind of overkill and would require a rearchitecture of your product displays. I would just hook into **hook\_commerce\_cart\_attributes\_refresh\_alter()** yourself, re-render the View using the product ID stored in $form\['product\_id'\]\['#value'\], and return a command to drop it into place similar to how the other product fields are updated.

---
Tags: commerce
---


# Question
Title: Module Library JS Some In Header Some In Footer
I have read that Drupal 8 by default loads library-defined files into the footer. My module libraries.yml file makes use of the "header: true" property as several JS files are needed to load in the header. However, now I need to add another JS file to the library, but this new file must load in the footer / just before the closing of the body tag.

How do I modify my libraries.yml file to make this JS file the only footer-loading one?

```
modulename:
  version: 1.x
  header: TRUE
  js:
    headerfile1.js: {}
    headerfile2.js: {}
    footerfile1.js: {}
  css:
    component:
      css/style.module.css: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal

```

# Answer
> 3 votes
Just add it to your `*.libraries.yml` as an additional library this time **without** `header: TRUE`. And maybe better place all your JS files in a subfolder named `/js`.

```
headerlibs:
  version: VERSION
  header: TRUE
  js:
    js/headerfile1.js: {}
    js/headerfile2.js: {}
  css:
    component:
      css/style.module.css: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

footerlibs:
  version: VERSION
  js:
    js/footerfile1.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

```

Then attach everything as usual:

```
/**
 * Implements hook_page_attachments().
 */
function MYMODULE_page_attachments(array &$attachments) {

  $attachments['#attached']['library'][] = 'MYMODULE/headerlibs';
  $attachments['#attached']['library'][] = 'MYMODULE/footerlibs';
}

```

---

From the docs:

> ### Asset loading order
>
> As you would expect, the order in which the files are listed is the order in which they will load. By default, all JS assets are now loaded in the footer. JS for critical UI elements that cannot be shown unless their corresponding JS has run can be loaded in the header if needed like so:
>
> ```
> js-header:
>   header: true
>   js:
>     header.js: {}
>
> js-footer:
>   js:
>     footer.js: {}
>
> ```
>
> Set the `header` property to `true`, to indicate that the JavaScript assets in that asset library are in the 'critical path' and should be loaded from the header. Any direct or indirect dependencies of libraries declared in this way will also automatically load from the header, you do not need to declare them individually for them to be available. This is the meaning of the phrase 'critical path', once an asset is declared to be in the header it is 'critical' for that asset and all of its dependencies to load first.

---
Tags: 8, javascript
---


# Question
Title: How do I create a field template or template override for a specific display mode?
Because in the Drupal 7 Commerce module, the fields, 'sku,' 'title,' and 'status' aren't editable by Display Suite field wrappers, I'm unable to edit the field wrapper via the Drupal front end, I need to use a template to update "commerce-product-title.tpl.php" with an H2 wrapper, but I only need this for the 'product\_full' view mode on all products. Is there a way to target this field in this display mode only with a template or theme function?

# Answer
### Fields

You have to add the theme hook suggestion yourself, first. For fields it's just the same as for nodes. Simply place the following snippet in your theme's `template.php` or your module's `*.module` file and replace `MYTHEME/MYMODULE` with your theme's or module's machine name.

Now copy the `/modules/field/theme/field.tpl.php` file over to your theme's `/templates` directory and name it along one of the following patterns:

* field--field-name--view-mode.tpl.php
* field--field-name--bundle--view-mode.tpl.php

---

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_field(&$variables) {

  $view_mode = $variables['element']['#view_mode'];
  $field_name = $variables['element']['#field_name'];
  $bundle = $variables['element']['#bundle'];

  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $view_mode;
  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $bundle . '__' . $view_mode;
}

```

---

### Commerce Product title

For Commerce' product titles though things are a little bit different, as you don't get the view mode or the referencing entity from within its preprocess hook. But you can simply use your own logic to add your template suggestions. For example a pattern in the URL alias or something like that.

Then copy the `/sites/all/modules/contrib/commerce/modules/product/theme/commerce-product-title.tpl.php` file over to you theme's `/templates` directory and rename it along your desired pattern.

* commerce-product-title--foo.tpl.php

---

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_commerce_product_title(&$variables) {

  // The following suggestion only gets added when there's
  // a certain keyword at the third position in the URL alias
  // as in /myproducts/overview/foo/myproduct.
  if (arg(2, drupal_get_path_alias()) === 'foo') {
    $variables['theme_hook_suggestions'][] = $variables['theme_hook_original'] . '__' . 'foo';
  }
}

```
> 4 votes

---
Tags: 7, commerce
---


# Question
Title: How to get the value of a taxonomy term from entity reference using a token?
We have an Entity reference field on `Basic Page` content type that is set to `Articles`. The `Articles` content type has a field, `field_category` that is a taxonomy term.

What is the correct token to get the value of the `field_category`?

Basic Page:

* `field_articles` -\> entity reference to `Article` content type.

Article page:

* `field_category` -\> taxonomy term field.

Goal:

* Return the `field_category` label from the `Article` node that is set on the `Basic Page`

Example:

Basic Page -\> `page1(nid=0)`

1. `field_articles` = articlePage1 `(target_id = 1)`

Article page -\> `ArticlePage1 (nid = 1)`

1. `field_category` = `Cloud` (tid = 10)

Token should return `Cloud` for `page1`.

We tried the following but it didn't work.

```
[node:field_articles:entity:field_category]

```

# Answer
You try use hook\_tokens

```
    /**
     * Implements hook_tokens().
     */
    function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
$replacements = array();
// $type is token type
      if ($type == 'node' && !empty($data['node'])) {
        foreach ($tokens as $name => $original) {
      // to do
        $replacements[$original] ='xxx';
       }
      }
      return $replacements;
    }

```

See more api hook\_tokens()
> 0 votes

---
Tags: 8, hooks, tokens
---


# Question
Title: Can tokens be used to set values of other fields and in modules which use tokens?
I am finding the Metatag module rather unwieldy, and I want to create fields in the content type from which Metatag values will be set.

Are there tokens available for the fields of any arbitrary content type, that can be used, or a set formula for creating them?

# Answer
> 1 votes
You try use hook\_tokens()

```
/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'key_token' && !empty($data['node'])) {
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      $replacements[$original]='Some_value';
      }
    }
  }
  return $replacements;
}

```

See more document hook\_tokens()

---
Tags: 7, nodes, tokens
---


# Question
Title: select list sending old value in ajax request
I have a select list on custom module form, on it's select giving ajax call and populating the second select list. But when I select the value from the first list, it is passing old value (previously selected) to the callback function (It should send currently select value). Following is my code.

```
  function get_subject($form, &$form_state) {
    $form['students'] = array(
      '#type' => 'select',
      '#options' => $student_array,
      '#title' => t('Students'),
      '#id' => 'students',
      '#value' => ($students != '') ? $students : '',
      '#required' => TRUE,
      '#ajax' => array(
        'callback' => '_subject_loader',
        'wrapper' => 'subject_div',
      ),
    );
    $form['subject'] = array(
      '#type' => 'select',
      '#options' => $subject_list,
      '#title' => t('subject'),
      '#id' => 'subject',
      '#prefix' => '<div id="subject_div">',
      '#suffix' => '</div>',
      '#value' => ($subject != '') ? $subject: '',
      '#required' => TRUE
    );
    $form['submit'] = array(
      '#type'=>'submit',
      '#value'=>'Submit',
    );
    return $form;
  }

  function _subject_loader($form, $form_state) {
    return $form['subject'];
  }

```

# Answer
> 1 votes
Use Form state input rather than using values in ajax call back like below:

```
if (isset($form_state['input']['students'])) {
    $student = $form_state['input']['students'];
  }

```

# Answer
> 0 votes
If you return the `$form['subject']` you will be returning an array most likely, as the `$form` is a render array. You need to access the lists inside $form\_state which hold the values of the submited form.

```
function _subject_loader($form, $form_state) {
  $user_input_values = $form_state->getUserInput();
  return $user_input_values['student'];
}

```

---
Tags: 7, ajax
---


title: Update the block through ajax

text:
# Question
Title: Update the block through ajax
I have added a block which shows the no of items added to an entity. I want to refresh the block through ajax as the items are added to an entity through ajax form so whenever I add an item, it will refresh or re-render the block content too.

I found some of the modules, but they are in Drupal 7 and not available for D8 so I want to make it done with my custom module but didn't find anything useful.

**UPDATED**

I have added the class attribute with the block and whenever I add any items, I made an ajax request through javascript which calls the respective controller and at the same time, I run this too--

```
// This is a part of the controller function from where I am calling below defined methods.
$this->updateBlock();

protected function getBlock() {
    $block = $this->blockManager->createInstance('block_id', []);
    return $block;
}

public function updateBlock() {
    $block = $this->getBlock();
    $this->response->addCommand(new ReplaceCommand('.block--class', $block->build()));
    return $this->response;

```

}

But It is not updating the block.

# Answer
> 0 votes
Important part you left out is what kind of ajax, is it a form you are submitting or custom javascript which uses ajax to target a controller endpoint? As this is how we return the code of the block.

But the code you are looking for re-rendering a block is:

```
$id = '' // the number of the block_id
$block = \Drupal\block_content\Entity\BlockContent::load($id);
$render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
return $render;

```

---
Tags: 8, blocks
---


# Question
Title: How to display nodes of specific terms and expose only those terms to the user (out of many other terms)
I have created a view, where I display two content types. Both of them have field "Country". So in my view I want to display only nodes related to three particular countries, but additionally I want to add filter, so that the user is able to see content only for one country out of the three.

The problem is that when I specify in "Filter criteria" show nodes only for these three countries it works, but when I make this filter "exposed" the view renders absolutely all nodes.

At the same time I want my exposed filter to have only the 3 countries available available.

# Answer
> 1 votes
An exposed filter has no effect by default, so your simplest solution is to add another filter *that is not exposed* that limits the view to just the countries you want.

It's a useful trick with views to combine exposed and not-exposed filters and sorts.

# Answer
> 0 votes
Here is a setup that does not seem to create any trouble. The country is a `taxonomy term` field attached allowing only 1 country to be specified per node.

When the filter is exposed you can specify the countries to be displied/filterable and you can also limit the list to those countries

Here is a working setup

and here what you will see vising the page of this view

only the specified countries are displayed and it works as it should

---
Tags: views, 8
---


# Question
Title: Highlight code for code presentation in articles
What is the solution to highlight PHP, JavaScript, or Java code in Drupal 8 articles?

I googled and found some information about Geshi for CKeditor. I installed it, but it converted *\<* and *\>* into HTML entities.

I lost a few hours, and I was not able to fix it, not for Drupal 8 and the latest Geshi version.

I am looking for the ultimate full solution to present code. Do you have any suggestion?

# Answer
> 4 votes
There is CKEditor CodeSnippet, which has an integration module.

> This module enables the CodeSnippet plugin from CKEditor.com in your WYSIWYG. It includes the highlightjs library and all available styles for it. If you've ever wanted to drop code examples in your Drupal content and have it highlighted in a pretty format, this is for you. This project is available for Drupal 7 as WYSIWYG CodeSnippet. Since that project relies on WYSIWYG module, and this one only requires D8 core, it made sense to rename it.

Disclaimer: I am a maintainer of that module.

Edit: to clarify, CKEditor has a native plugin called CodeSnippet - the Drupal module linked above provides an integration to it.

---
Tags: 8, input-formats
---


# Question
Title: How to add custom class in custom module?
I am not able to add custom class in custom module, I need to add class "ajax-link" in the anchor link to make it ajax based page load .

```
function hook_node_view(array &$build, \Drupal\node\Entity\Node
$node, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display,
 $view_mode) {

 if ($display->getComponent('prevnext_next')) {
$build['prevnext_next'] = [
  '#theme' => 'prevnext',
  '#direction' => 'next',
  '#text' => t('Next'),
  '#nid' => $previous_next['next'],
  '#attributes' => array(
  'class' => array(
  'ajax-link'
      ),
    ),
  '#url' => Url::fromUserInput('/node/' . $previous_next['next']."?an=left")->toString(),
  '#void' => empty($previous_next['next']),
];
 }
   }

```

What am I doing wrong in the code ?

I want to create link something like this:

```
<a class="ajax-link" href="node/nid?an=left">Next</a>

```

# Answer
> 0 votes
you can try code :

```
  $url = Url::fromRoute('entity.node.canonical', ['node' => $previous_next['next'],'an'=>'left']);
  $url->setOptions([
      'attributes' => [
          'class' => ['ajax-link custom-class']
      ],
  ]);

  $build['prevnext_next'] = [
      '#type' => 'link',
      '#title' => t('Next'),
      '#url' =>  $url,
  ];

```

---
Tags: 8
---


title: How do I use an older jQuery version?

text:
# Question
Title: How do I use an older jQuery version?
Drupal 8.5 requires jQuery 3, which has some site breaking features. I would rather like to use version 2.2.4. I have tried the `libraries-override` approach suggested in How do I use a jQuery version different from the default one used by core? After applying that answer, the theme.libraries.yml file content is the following one.

```
global-styling:
  css:
    theme:
      css/main.css: {}

jquery-custom:
  remote: https://github.com/jquery/jquery
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true

global-scripts:
  js:
    js/plugins.js: {}
    js/drupal-main.js: {}
    js/vendor/modernizr-3.3.1.min.js: {}
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

```

The theme.info.yml file content is the following one.

```
libraries:
  - theme/global-styling
  - theme/global-scripts
libraries-override:
  core/jquery: theme/jquery-custom

```

However, it gives me a reference error saying that `jQuery` is not defined. I have checked the path and there is no problem there. What am I missing here?

Is there any other way to downgrade from jQuery 3 to jQuery 2 in Drupal 8?

I also tried using the following code, but I still getting a reference error.

```
jquery-custom:
  remote: https://github.com/jquery/jquery.js
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

global-scripts:
  js:
    js/plugins.js: {}
    js/drupal-main.js: {}
    js/vendor/modernizr-3.3.1.min.js: {}

```

# Answer
> 1 votes
I had the same issue with some older Google tags plugins that did not work with jquery 3.0. You basically have to use the D8 library override methods in your theme to do this.

This actually goes into the theme info.yml file. You need to have the other version of jquery defined in your library.yml file as well. Here's some excerpts from my theme files.

my\_theme.info.yml

```
libraries-override:
  #downgrade jquery / force jquery into header
  core/jquery: my_theme/jquery

```

The core/jquery was found by searching thru the core to find the jquery library definition.

my\_theme.libraries.yml

```
jquery:
  header: true
  remote: https://github.com/jquery/jquery
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

```

Note: The header: true loads jquery in the header and not the footer. Helps a bit with embedded jQuery code that complains that jquery does not exist. I have a local copy of jquery in the js directory of my theme as well.

This technique can override any CSS or javascript included by any module or core.

---
Tags: 8, theming, javascript, updating
---


title: Where are config dependencies stored?

text:
# Question
Title: Where are config dependencies stored?
I have this error when importing a single piece of config manually:

> Configuration foo.api depends on the MODULE extension that will not be installed after import.

There is no "MODULE" extension in the file system, `core.extension` config, the KeyValue table, config\_snaphot, or anywhere else that I'm aware of that would be related.

If I delete the config

```
\Drupal::configFactory()->getEditable('foo.api')->delete();

```

Then try the import, it works. Great.

But as soon as I go back to my config form and save foo.api, the next time I try to import, I get the same error all over again.

This leads me to believe that a dependency tree must be stored somewhere, and that it isn't cleared when config is deleted.

Is this true, and if so where is it? If not, how can I resolve this?

I guess this could also be rephrased as *How are module dependencies for basic configuration calculated, and how do you manually update them when they’re wrong?*

# Answer
> 3 votes
The error you see is output from `ConfigImportSubscriber::validateDependencies()`, which uses the following code.

```
  // Validate the dependencies of all the configuration. We have to validate
  // the entire tree because existing configuration might depend on
  // configuration that is being deleted.
  foreach ($config_importer
    ->getStorageComparer()
    ->getSourceStorage()
    ->listAll() as $name) {

    // Ensure that the config owner is installed. This checks all
    // configuration including configuration entities.
    list($owner, ) = explode('.', $name, 2);
    if ($owner !== 'core') {
      $message = FALSE;
      if (!isset($core_extension['module'][$owner]) && isset($module_data[$owner])) {
        $message = $this
          ->t('Configuration %name depends on the %owner module that will not be installed after import.', [
          '%name' => $name,
          '%owner' => $module_data[$owner]->info['name'],
        ]);
      }

```

The code assumes that for a name like *node.type.article* the owner is the Node module. If the owner is not one of the installed modules, Drupal gives the error you see.

To answer your question, the module name is assumed to be stored in the configuration filename.

---
Tags: configuration
---


# Question
Title: How can I get both "body" and "summary" fields to appear in a new article?
I'm defining a Drupal 7 content type using the "long text and summary" field. When a new story is created, I'd like both the "summary" and "body" text fields to be present in the creation form, instead of making the user click the "edit summary" link. Is there a way to do this through the basic Drupal content type tools (I've looked, but can't find anything), or do I need to write a hook\_form\_alter handler or something comparable for the content type? Thanks!

# Answer
I think you'll have to do it in a form alter hook as you suggest, I don't know of a way to do it in the UI.

Looking at the code for text summary fields the "Edit Summary" link and functionality are done completely through javascript, added in the form by setting an `#attached` property on the element, which includes a JS file (modules/field/modules/text/text.js).

All that JS file does is add that "Edit Summary" link so it would be completely safe to just get rid of it. This example uses the standard `page` content type:

```
function mymodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  unset($form['body'][LANGUAGE_NONE][0]['summary']['#attached']);
}

```
> 6 votes

# Answer
The above works as does hook\_js\_alter

```
    function mymodule_js_alter(&$javascript) {
      unset($javascript[drupal_get_path('module','field').'/modules/text/text.js']);
    }

```
> 1 votes

# Answer
You can also use hook\_field\_widget\_form\_alter(), for example:

```
/**
 * Implements hook_field_widget_form_alter().
 */
function example_field_widget_form_alter(&$element, &$form_state, $context) {
  if (
    isset($element['#bundle']) &&
    $element['#bundle'] == 'page' &&
    $element['#field_name'] == 'body'
  ) {
    if ($element['summary']['#attached']['js'][0] == 'modules/field/modules/text/text.js') {
      unset($element['summary']['#attached']['js'][0]);
    }
  }

}

```
> 1 votes

# Answer
The 2018 answer to this question is to use the Text Summary Options module, which now has a version for Drupal 8, and allows you to store settings on whether to require and/or expose by default the summary field on any long\_text\_with\_summary field, including the Drupal body field, but also any other custom fields as well.

There is also a patch for Drupal 8 core Issue #1704864: Add a "Required" and "Show by default" option for "Text area with a summary" widget.; I have not tested it though.
> 1 votes

# Answer
One note about Clive answer: you could need to remove only text.js by using this

```
function mymodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $attached_js = &$form['body'][LANGUAGE_NONE][0]['summary']['#attached']['js'];
  $attached_js = array_diff($attached_js, array('modules/field/modules/text/text.js'));
}

```
> 0 votes

---
Tags: theming, nodes
---


# Question
Title: Encode a line break in an HTML email sent by Rules?
I have a rule that sends out an email when a node gets edited in a certain way. The rule fills the body of the email with the value of a `<textarea>` field from the node that was updated.

The email is being sent out in HTML format (not plain text) and the `<textarea>` is set to plain text (not Filtered Text).

When the email gets delivered, the HTML line breaks (`<br />`) that I've entered into the `<textarea>` field are not respected (they get encoded); it just one big mass of text with no line breaks.

What do I have to put in the `<textarea>` field for line breaks to come out in the HTML email?

I've tried:

* `<br>`
* `<br />`
* \n
* \r
* \r\n
* `%0D%0A`
* `<br />`
* %3Cbr+%2F%3E

Any HTML I put in the field gets encoded and not processed as HTML. How do I put in `<br />` and have it stay as HTML?

# Answer
Have a look at my answer to "How to use Rules to send an eMail with a body containing all items of a field collection?". It includes a rule (in export format) which looks like so:

```
{ "rules_field_collection_msg_and_email_body" : {
    "LABEL" : "Field Collection msg and eMail body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The  list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E"
          },
          "PROVIDE" : { "variable_added" : { "variable_for_email_body" : "Variable to use in eMail body" } }
        }
      },
      { "drupal_message" : { "message" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E" } },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "article details item" },
          "DO" : [
            { "data_set" : {
                "data" : [ "variable-for-email-body" ],
                "value" : "[variable-for-email-body:value]\u003Cbr \/\u003E\r\nThe host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E"
              }
            },
            { "drupal_message" : { "message" : "The host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E" } }
          ]
        }
      },
      { "mail" : {
          "to" : [ "site:current-user:mail" ],
          "subject" : "Demo of an eMail with a body containing all items of a field collection",
          "message" : [ "variable-for-email-body" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Even though your question is not a duplicate of that question, this rule includes a solution which you could also apply in your case:

* A Rules Action `Add a variable`, with machine name `variable_for_email_body`.
* A Rules Action to actually populate the content of this `variable_for_email_body` (just replace that content to fit your needs, and include whatever HTML tags you want to use in our eMail body).
* A Rules Action `Send mail`, with Message body equal to ... `[variable-for-email-body]`.

***Done*** ...

PS: obviously, this is for D7 ...
> 1 votes

# Answer
You can try the code

```
/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  $headers = array(
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal'
  );
  foreach ($headers as $key => $value) {
    $message['headers'][$key] = $value;
  }
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

```
> 0 votes

---
Tags: rules, emails
---


# Question
Title: How to exclude multiple nodes based on their ID in taxonomy term view?
In taxonomy term view I want to exclude multiple nodes based on their id.

I tried to add a new CONTEXTUAL FILTER so I can handle multiple values in my Content: ID but the problem here is that it overwrites the url taxonomy/term/%/edit.

Also I have tried to add Content: ID filter in my FILTER CRITERIA but I cannot add multple values in "Not equal" field.

How can I solve that?

# Answer
## Add more than one ID Filter

You can simply solve it by adding as many **Content: ID** Filters as you need, each excluding only one node. As you already know set the `Operator` to **Is not equal to** and enter one value, then add another **Content: ID** Filter and so on for all the nodes you need to exlude.

## Use Regular expression

Or you can use the `Operator` **Regular expression** in a single **Content: ID** Filter. This way you can use a regex pattern that matches all the ID numbers you want to exclude.

For example the expression `(2[45])` matches two numbers, 24 and 25, so those two nodes would be filtered and shown in results.

In your case you need to *exclude* some numbers, so you would have to have a regex that excludes. That is a bit out of scope for this question so I won't go into it. There are online regex generators you can use to help you construct the expression, but I expect it would take some time, regex is notorious for being complex and mind-boggling.

For whole range of numbers take a look at this tool: Regex Numeric Range Generator. Don't forget you need to modify the expression to exclude the list!
> 1 votes

---
Tags: views, 8
---


# Question
Title: Views Grouped by *each* value of a content field (multivalue).
I am pretty new to drupal, so some terms I describe may not be accurate. Anyways, I know how to group things in views using single values (i.e. Group faculty members by their departments: engineering, biology, medicine, social science, etc).

**I want to create a view that groups items by a field which accepts multiple value (i.e. research areas)**. Suppose we have the **Research Areas** *A, B, C, and D*. Then, I want to group it such that each faculty member is displayed under *each* value of the multi-value field. Let's also suppose there are **Faculty Members** *John, Josh, Jack, Jasmine*, and their respective research areas are as follow (Note: omitted departments):

*John { research area: A, B }
Josh { research area: B, D }
Jack { research area: A, D }
Jasmine { research area: B, C }
Joyanne { research area: A, B }*

Then, the view should display as follows (desired output):

**Research Area A:
John
Jack
Joyanne

Research Area B:
John
Josh
Jasmine
Joyanne

Research Area C:
Jasmine

Research Area D:
Josh
Jack**

---------------------------------------------------------------
I have been using fields inside each faculty member to represent the research areas they fall under (check boxes for different research areas they focus on). And I have some how grouped them using the Research Area field; however, they are grouping as such:

Research Area A, B:
John
Joyanne

Research Area B, D:
Josh

Research Area A, D:
Jack

Research Area B, C:
Jasmine

I have also used Taxonomy Vocabularies, but to no avail.

Help SVP. Thanks for your time in advance.

# Answer
Grouping is done by the information you have in your results.

Fields with multiple values return results differently, depending on the **Multiple field settings** you set on them.

If you choose to **Display all values in the same row** then each node will show all "Research Areas" related to it, and if you enable grouping groups will reflect the option combinations from results. This is your current behavior.

If you **untick** the option **Display all values in the same row** each node will be displayed in a separate row showing only one "Research area" it belongs to, but it will be listed as many times as it has "Research areas" attached to it. When you enable grouping in this scenario each "Research area" option will behave "independently".

So to achieve your desired behavior you need to **untick** the option **Display all values in the same row** on your "Research Areas" Field (mind you this is under `Fields`, and not under `Format` where Grouping options are).
> 0 votes

---
Tags: views
---


# Question
Title: Create a field with options are a combination of taxonomy terms, and content types linked to those taxonomy terms, for which the content type is used
This is a decoupled drupal 8 back end with an angular front end connected over jsonapi and other custom restful inputs.

We have a coupon content type in out Drupal csm. It is exactly what it sounds like, a coupon.

We have a content type "products" and you can assign a coupon to that product when creating or editing said product.

We have a taxonomy term list of product categories and sub categories.

```
Category A
    Sub Category 1
    Sub Category 2
Category B
    Sub Category 3
    Sub Category 4
    Sub Category 5

```

An admin can go into a taxonomy term, and add a coupon to an individual taxonomy term, or to a product content type.

This is where it gets crazy.

We have a listing of coupons, on that list we want to give the admin the ability to display a "featured product" and ideally, in the CMS they have a field where the only options are either a taxonomy term or a product content type that said coupon has been applied to.

```
Product A (Product)                  # (content-type)
Product F (Product)                  # (content-type)
Category B (Category)                # (product taxonomy parent (weight 0) term)
subCategory 1 (Sub Category)         # (product taxonomy sub parent (weight 1) term)

```

only products ( a content type ) or taxonomy terms with this coupon are shown.

We will then need to build a link pointing to the correct front end page. The category list, the sub category list, or the actual product.

Thoughts on how to achieve this with no custom code? If the only way to do this is with custom code, what's the best way to approach the task?

Thanks a million and 1.

\[EDIT to change output options.\]

# Answer
There are some caveats in your question.

## Caveat—no info to pick from

One caveat is marking "featured" items, narrowing down your pick from an already narrowed down list. This means that you have to save a new Coupon twice to get to the Featured option, the first time you save you pick the terms or products, and then you edit again to pick the "featured" one from the list you narrowed down previously. You could probably come up with some Ajax voodoo to do it all in one Save, but that is out of scope here and not very straightforward.

I'll assume the double-save is acceptable, that it fits with your project processes.

## Caveat—Views don't mingle entities

To solve this without the custom code you need Views, but Views only ever list one type of entity (unless they're related, which in your care they aren't).

I'll assume it's ok to use two Fields then to mark your "featured", one to list terms, and the other for Products, and you'll have to rely on your admins to only select one of those, treat them like a single field even when it's not. (You ccould combine them with custom code, of course.)

## Use Entity reference Views Display

Create a Taxonomy term Views type with Entity reference Display and limit to your Category vocabulary. You'll have to use Parent term Relationship and Contextual filters to show both levels.

Then use the usual Views magic to Contextually filter out only those terms that are shared with the node currently being edited (this is your Coupon node that has already been saved with chosen Categories and Products).

Create a new Entity Reference Field on Coupon CT and make it use the Views you created previously as a Widget.

Then repeat the procedure for Products. Create a Views Display listing Products, but limit Contextually to the Entity reference you're using on your Coupon, so that when editing a Coupon only Products that have already been chosen show up to be selected as "featured". When you have it working create a new ER field on Coupon using that ER Display as a widget.

This question is too complex to answer step by step, try looking at similar answers for each part, maybe here: How do I create a list of Nodes within a list of taxonomy terms, within a node? and Entity Reference widget selctor in view referring same reference

## Links

I assume the links you mention are the links to the related Featured term or Product, showing on the Coupon list.

You can get this easily in Views by adding a Relationship (on the Coupon Views) to the ER "Featured" term, and then "Taxonomy Name" Field that uses that Relationship to show the related Category link.

Repeat similarly to show related "Featured" Product: add the ER "Featured" Product Relationship, and then "Title" Field that uses that Relationship. It will show the "featured" Product (the optin to make it a link instead of plain text are inside the Field settings).

## Only custom code will give polished experience

This is perhaps a bit crude but you can always polish with custom code, in various steps along the way, or even the entire set of features, depending on your needs and resources.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Why does the same form/field appear diffently depending on the browser?
I have a custom content entity created with Drupal Console and the corresponding CRUD forms.
In this entity there is a field defined this way:

```
$fields['startdate'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Membership Start Date'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => 'now',
  )))

```

The way this field appears when in edit mode is completely different depending on the browser (see screen captures).

The most 'annoying' being the displayed date format: mm/dd/yyyy with Firefox, yyyy-mm-dd with Safari. The only correct would be dd/mm/yyyy in Chrome.
Because the users of this site are french people that are used to dd/mm/yyyy...
Of course, the settings of my site (language, date and time, etc.) are 'French'.

Any idea how I can fix this and have the same behavior whatever the browser?

# Answer
> 2 votes
The primary confusion around this is that the widgets (the code responsible for field input) for datetime, datetime range, and timestamp fields use HTML5 date/time input elements (except when using the select list version). One for the date portion, and one for the time portion.

The browser, not Drupal, renders out HTML5 date/time input elements. So, the actual UI will vary from browser to browser, and OS-to-OS. In addition, not all browsers support these inputs.

When a browser encounters an input element type it doesn't recognize, it defaults back to plain text entry. In this case, Drupal provides a polyfill for the date portion based on the jQuery UI component. There is an issue for the time element, but it currently languishing in the queue.

It looks like from your screenshots, Safari is using the polyfill and the rest are using the browser versions of the inputs.

The "yyyy-mm-dd" format for Safari, is a side effect of the fallback. The HTML5 input elements require dates in that format, so that is how the widget gets configured and rendered out. The native elements are using a localized version of the inputs, and handling the conversion behind the scenes so that Drupal gets the right format.

---
Tags: 8, forms
---


title: Creating a custom field module

text:
# Question
Title: Creating a custom field module
I am trying to create a custom field module for views, but I keep getting this error when I add the field to the view.

> SQLSTATE\[42S22\]: Column not found: 1054
> Unknown column 'views\_report\_state\_field' in 'field list'

This is the code I am using.

### views\_report\_state.info

```
name = Views Report State
description = Turns short abbreviated states (ex: TX) into fully readable names (ex: Tx = Texas)
package = Views
core = 7.x

files[] = views/views_report_state_field.inc

```

### views\_report\_state.module

```
function views_report_state_views_api($module = NULL, $api = NULL) {
  return array("api" => 3);
}

```

### views\_report\_state.views.inc

```
function views_report_state_views_handlers() {
  $handlers = array(
    'info' => array(
      'path' => drupal_get_path('module', 'views_report_state'),
    ),
    'handlers' => array(
      'views_report_state_field' => array(
        'parent' => 'views_handler_field',
      ),
    ),
  );
  return $handlers;

function views_report_state_views_data() {
  $data = array();
  $data['views']['views_report_state_field'] = array(
    'title' => t('CRF: Convert US-State Abbreviations'),
    'help' => t('Converts State Abbreviations to their full name'),
    'field' => array(
      'handler' => 'views_report_state_field',
    ),
  );
  return $data;
}

```

### views\_report\_state\_field.inc

```
class views_report_state_field extends views_handler_field {

  function render() {
    return "working!";
  }

}

```

# Answer
views\_report\_state\_field.inc

```
class views_report_state_field extends views_handler_field {
  function query() {
    // Query
  }

  function render() {
    return "working!";
  }

}

```
> 1 votes

---
Tags: 7, views, nodes
---


# Question
Title: Load menu items from one menu in other menu
I want to load the menu items from the main menu in a other menu. I've read a dozen examples but I can't get it to render the items at all.

Here's my code from `my_theme.theme`

```
function my_theme_menu__secondary(&$menu, &$menu_name, &$suggestions) {
  $menu_name = 'main';
  $menu_tree = \Drupal::menuTree();
  $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
  $parameters->onlyEnabledLinks();
//  $parameters->setMinDepth(2)();
//  $parameters->setMaxDepth(2)();

  $tree = $menu_tree->load($menu_name, $parameters);
  $manipulators = array(
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );

  $tree = $menu_tree->transform($tree, $manipulators);

  $list = [];

  foreach ($tree as $item) {
    $title = $item->link->getTitle();
    $url = $item->link->getUrlObject();
    $list[] = Drupal\Core\Link::fromTextAndUrl($title, $url);
  }

  return $list;
}

```

Heres my `menu--secondary.html.twig`

```
{% import _self as menus %}

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if list %}
    {% for item in list %}
      {%
        set item_classes = [
          'expanded',
          'dropdown',
          item.in_active_trail ? 'active',
        ]
      %}
      {% if menu_level == 0  %}
        <li{{ item.attributes.addClass(item_classes) }}>
        <a href="{{ item.url }}">{{ item.title }}</a>
        </li>
      {% endif %}
    {% endfor %}
  {% endif %}
{% endmacro %}

```

Any help is appreciated :)

# Answer
you can add new module twig tweak, after rendering blocks menu with Twig Tweak on template.
> 0 votes

---
Tags: 8, hooks, navigation
---


# Question
Title: How to add image field to paragraph programmatically?
I am trying to programmatically add an image field value to a paragraph.

The field value of the image is as below

```
Array (
  [target_id] => 28
  [alt] => test images
  [title] =>
  [width] => 1440
  [height] => 557
)

```

This is, how I try to set the image field value:

```
$paragraph->set('field_image',  $para_array);

```

The image field is not being set. Where am I going wrong and what will be the way to implement it?

# Answer
> 2 votes
You can treat the field like a PHP array to add (and not replace) an image:

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

  $paragraph = Paragraph::load($paragraph_id);
  $paragraph->field_image[] = [
    'target_id' => $fid,
    'alt' => $alt,
    'title' => $title,
  ];
  $paragraph->save();

```

# Answer
> 1 votes
Don't set the complete array. You have to just pass target\_id to set the image field:

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

$paragraph = Paragraph::load($paragraph_id);
$paragraph->set('field_image',  $para_array['target_id']);
$paragraph->save();

```

# Answer
> 0 votes
You try the code.

```
    $images = [
      'target_id' => 1,
      'alt' => '',
      'title' => '',
      'width'=>1440,
      'height'=>557
    ];
    $paragraph = Paragraph::create([
      'type' => 'paragraph_type',
      'field_images' => $images
    ]);
    $paragraph->save();

```

---
Tags: 8, paragraphs
---


# Question
Title: Image widget crop not returning multiple derivatives in JSON API
I'm using below modules for image crop

```
https://www.drupal.org/project/image_widget_crop
https://www.drupal.org/project/cloudinary
https://www.drupal.org/project/consumers
https://www.drupal.org/project/consumer_image_styles
https://www.drupal.org/project/jsonapi

```

Returning data in JSON API.

Using multiple paragraphs for images. I have 1 image as logo & 1 image as content.

For 1 image it's showing correct image width & height, X & Y co-ordinates (derivatives).

But for multiple image it copy same height, width, x, y co-ordinates to other images.

So it's not showing image wise derivatives for multiple images.

Once image is uploaded it saved to cloudinary.

```
{
"meta": {
"derivatives": {
"box": "http://res.cloudinary.com/XXX/image/upload/s--CJHoE3mM--/c_crop,h_400,w_400,x_29,y_46/test.jpg?itok=4GARJEFS",
"thumbnail": "http://res.cloudinary.com/XXX/image/upload/s--vlxu-1hL--/c_fit,h_100,w_100/test.jpg?itok=hed-1-Mh",
"wide": "http://res.cloudinary.com/XXX/image/upload/s--4-Vk3FhO--/c_crop,h_200,w_356,x_76,y_86/test.jpg?itok=GOzme5ht"
}
}

```

Does anyone faced this issue?

# Answer
You can try the code

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

$filed_images = $paragraphs->get('field_image')->getValue();
 $images =[];
 foreach ($filed_images as $image) {
            $images[] = ImageStyle::load('273x273')
              ->buildUrl(File::load($image['target_id'])
                ->getFileUri());
          }

```
> 0 votes

---
Tags: 8, media
---


# Question
Title: Authentication providers: no token_bearer
I created a custom resource for a Drupal 8 REST call. For some reason, I can't see either basic\_auth or token\_bearer from the authentication providers. I installed simple\_oauth and still can't see either basic\_auth or token\_bearer.

>

The code I am using is the following one.

### config/install/rest.resource.sample\_index\_resource.yml

```
id: sample_index_resource
plugin_id: sample_index_resource
granularity: resource
configuration:
GET:
  supported_formats:
    - json
  supported_auth:
    - basic_auth
    - cookie
    - token_bearer

```

### src/Plugin/rest/resource/SampleResource.php

```
/**
 * Provides a Sample Index Resource
 *
 * @RestResource(
 *   id = "sample_index_resource",
 *   label = @Translation("Sample Index Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/sample-response/{category}/{alias}"
 *   }
 * )
 */
class SampleResource extends ResourceBase {
/**
* Responds to entity GET requests.
* @return \Drupal\rest\ResourceResponse
*/
public function get($category, $alias) {
  // Return response
}

```

The *HTTP Basic Authentication* module needs to be enabled to be able to use *basic\_auth* as authentication provider. I don't know which module I should enable to be able to use *token\_bearer*.

What module do I need to install to get *token\_bearer* as authentication provider?

# Answer
I think your yml syntax is wrong (or out-dated) look at rest.resource.entity.node.yml for a correct example. Or use the "REST UI" module to specify your resources.

It should look more like:

```
configuration:
  methods:
    - GET
    - POST
    - PATCH
    - DELETE
  formats:
    - hal_json
  authentication:
    - basic_auth

```
> 1 votes

---
Tags: 8
---


# Question
Title: Is it possible for 3rd Party Script to Create Users
Our company has many systems that require for users to have user names and passwords. We have been able to use SAML to cut down on the number of accounts we must manually create. With that said, we do currently manually create Drupal users.

Would it be possible to have an "external script" provide Drupal with the variables it needs to create a new user.

**Example:**

```
External system collects user information in one spot.
1) User is created in Drupal according to data passed
2) Users are simultaneously created in other systems.

```

If it were not Drupal, I would google "API" for the system but with Drupal, I think API can mean a lot of different things and I was not able to easily find anything that might point me in the right direction.

# Answer
> 1 votes
And also it's very simple to create users in D8 by program:

```
$newuser = \Drupal\user\Entity\User::create([
          'name' => $name,
          'pass' => $pass,
          'mail' => $mail,
          'status' => 1,  // or 0 if inactive
          'init' => $initmail,
          'created' => time(),
          'login' => 0,
          'access' => 0,
        ]);
      $newuser->addRole("myrole");
      $rc = $newuser->save();
      if ($rc == SAVED_NEW) {
    ...whatever...
    }

```

For bootstrapping external scripts, you can look i.e. here: Bootstrap from external script

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


# Question
Title: Is drush.wrapper used anymore for Drush 8? How to use for Windows?
We have 3 devs working on a Drupal 7 site. Drush 8 is provided via a local composer file `drush/drush:~8.0`. A `drush.wrapper` exists in the project root containing:

```
cd "`dirname $0`"
DRUSH_ALIAS_FILE="./drush/MYPROJECT.aliases.drushrc.php"
DRUSH_LAUNCHER="./vendor/bin/drush.launcher"

if [ ! -f $DRUSH_ALIAS_FILE ]; then
  echo "No Drush alias file was found at ./drush/MYPROJECT.aliases.drushrc.php"
  exit;
fi

if [ ! -f $DRUSH_LAUNCHER ]; then
  echo "Drush Launcher was not found at ./vendor/bin/drush.launcher. Have you ran 'composer install' from the project root?"
  exit;
fi

$DRUSH_LAUNCHER --local --alias-path=./drush "$@"

```

This works for everyone; except the one user on Windows. They get an error along the lines of "drush.php was not found". If he removes the file, drush works (but then it is using the globally installed drush). This of course would break it for everyone else.

I am confused by the docs. How does one properly supply Drush 8 with a Drupal 7 project via Composer and have 'drush' work as a command from the project? I see issues saying the wrapper file is not needed anymore and other posts saying you need one.

edit: We started over and installed drush launcher per the documentation with the Windows .bat file. It still gives the error:

"Could not open input file /usr/local/bin/drush"

# Answer
No, don't use `drush.wrapper`. There is a new tool in town - Drush Launcher. It works on Windows too since it's PHP based - just follow step 4 in the installation instructions. (Step 2 and 3 aren't relevant on Windows, and step 1 is just a normal file download on Windows.)

Added: You should remove/rename the global Drush if you have any. If you need it, check out the fallback option for Drush Launcher.

PS! Also the Linux/Mac people should use Drush Launcher.
> 1 votes

---
Tags: 7, drush
---


# Question
Title: Problem with remote sync because of wrong UUID
I have a problem with syncing my config to the remote server with Drupal 8. When I pull everything with GIT, and use drush to update the config via `drush cim` I get the following error:

```
Attempt to save a configuration entity 'field_bestand_en_' with UUID '' when this entity already exists with UUID
'b8bbd770-1533-4680-88cd-3409b0921d02&#039

```

So the problem is that the UUID doesn't match, the new file for some reason lost its UUID and is `null` now. I tried adding the given UUID by hand to the right yml file but on every new config update it gets overwritten.

So when I do `drush cex` locally, the UUID is null again. How can I fix this, I guess deleting the field and creating it will fix it but this is not really an option.

Thanks in advance

# Answer
I was synchronizing the configuration between local environment and remote repo, and after doing the Pull and drush cr, when using drush cim, I got a similar error.

In my case, the UUID (unique identifier of Drupal element), of the configuration entity was in NULL value. Since I didn't know the origin of this, I went to the remote repository and I saw that it was pushed like this. In origin, it seems an export failure (drush cex).

I solved it by getting the number and writting the UUID (it's the same one that announces the error of drush cim by console). I edit the field configuration file and change NULL for this value of the UUID and again drush cim works again. Next, it is important to commit this change to remote (git push) so that it can be modified there, otherwise it can be lost locally after a global "pull".
> 3 votes

# Answer
Drupal 8 configuration was designed to manage configuration on different instances of the same Drupal site. The best way to start local development is to copy the entire database from the remote site to your local site, e.g. using `drush sql-sync`.

If you do not wish to copy your entire live database on your local site, then you need to be sure to import your configuration at site-install time. There are two ways to do that:

* Using `drush site-install` with the `--config-dir` option
* Using the config installer

If you start off your local site like this, then your uuids will remain in-sync, and you will be able to export your config from the local site and re-import it on the remote site.
> 1 votes

---
Tags: drush, configuration
---


title: disable translatable route object

text:
# Question
Title: disable translatable route object
I've developed a module which generates and displays dynamic content. The title of the page is also generated dynamically in the controller as show below:

```
if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
  $route->setDefault('_title', strval($title))
}

```

This provoques each title is marked as untranslated text and fills the locales\_source table.

I tried to use this line to stop this

```
$route->setDefault('_disable_route_normalizer', TRUE)

```

but it doesn't work.

And I tried to use

```
['#title' => $title]

```

and it doesn't work.

How to avoid this?

# Answer
Create a "title" function in your controller and declare it in your route, like here ( \_title\_callback):

```
entity.node_type.edit_form:
  path: '/admin/structure/types/manage/{node_type}'
  defaults:
    _entity_form: 'node_type.edit'
    _title_callback: '\Drupal\Core\Entity\Controller\EntityController::title'
  requirements:
    _permission: 'administer content types'

```
> 1 votes

---
Tags: 8, routes, meta-tags
---


# Question
Title: How to call ctools modal window from mycustom.tpl.php?
I need to show a modal window on click from my mycustom.tpl.php

Here is my code in mycustom.tpl.php

```
<a href="/modal/nojs" class="ctools-use-modal ctools-use-modal-processed">False Positiv1e</a>

```

In my module file :

```
$items['modal/%ctools_js'] = array(
    'page callback' => 'modal_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

 return $items;
}

function modal_callback($ajax) {
    ctools_include('ajax');
    ctools_include('modal');
    ctools_modal_add_js();

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('MyModule Modal Form'),
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $output = ctools_modal_form_wrapper('modal_form', $form_state);
    // If the form has been submitted, there may be additional instructions
    // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();

}
function modal_form($form, $form_state) {
  $form = array();

  $form['new_link_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Link text'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

```

But when I am clicking on the button, Modal window Breaks and print $output array as below

# Answer
You have to include below code in your `mycustom.tpl.php` also.

```
ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();

```
> 0 votes

---
Tags: 7, chaos-tool-suite
---


# Question
Title: Access field object (not render array) in field templates
In most entity templates like `node.html.twig` or `paragraph.html.twig` I do get two major variables, the render array variable `{{ content }}`, but also the entity object variable like `{{ node }}` or `{{ paragraph }}`. Usually they are passed down to Twig in `template_preprocess_ENTITYTYPE` via `$variables['element']['#ENTITYTYPE']`.

I'm looking an equivalent for this in field templates, e.g. if I can do `{{ node.field_whatever.something }}` in `node.html.twig` I also want the get the same thing by using `{{ field.something }}` in `field.html.twig`

I guess I need the FieldItemList in `template_preprocess_field` to achieve this, but I don't know how to get it there.

# Answer
> 2 votes
The field template receives its values from the parent entities' view display build array. This build array doesn't contain separate keys for the original fields on their components build arrays.

But a field preprocess function receives enough information to extract them: The `'element'` item contains an `'#object'` key that holds the original entity, and a `'#field_name'` key that holds the name of the field. (Which is also available in the template as `field_name` thanks to template\_preprocess\_field().)

If you'd like to access the original field, you could do something like:

```
$element = $variables['element'];
$field_item_list = $element['#object']->get($element['#field_name']);

```

Which should return an instance of a class that implements FieldItemListInterface (FieldItemList, EntityReferenceFieldItemList, ...).

---
Tags: 8, theming
---


# Question
Title: Send email notification to node author with Rules
I am trying to notify the node author of a new comment on their node.

Using Drupal 8.3

Created new reaction rule.

Send to: comment.entity\_id.entity.uid.entity.mail.value

email address is not being picked up

I get this email from system:

A message that you sent contained no recipient addresses, and therefore no delivery could be attempted.

# Answer
> 1 votes
This worked.

As a workaround, you can use the data selection string as a token in the direct input textarea.

Switch to data selection and get your string, in my case content\_moderation\_state.uid.entity.mail.value

Switch to the direct input mode and paste the string with double braces {{content\_moderation\_state.uid.entity.mail.value}} to use the token replacement API.

As described here: https://www.drupal.org/project/rules/issues/2799569#comment-12376804

---
Tags: 8, rules
---


# Question
Title: Is it possible to get original configuration when another Config Split is activated? (CONDITIONAL SPLIT is used)
I have *dev* and *prod* environments.

I use payment getaway. There are different api keys for *dev* and *prod* envs, it's like *test* and *live* mode of the payment method.

There is active *dev* config split configuration which contains some config with *test* api keys (CONDITIONAL SPLIT).

So it means, there is also original config witch contains *live* api keys.

Is it possible to get programmatically both values (original and *dev*) for some specific configuration?

# Answer
This is a follow-up to my comment on your question with some references:

When using Configuration Split to distinctively use a certain conditional configuration on your environments, then you won't be able to access both, your development and production values at the same time (without reading in these splitted configurations manually).

The reason is, that configuration split hooks into the import/export process of your configuration. Once you import your configuration, the values for the respective environment will replace your database-stored configuration.

If you need to access both values within the same environment, you should change from config split to configuration overrides.

By keeping the production API value database stored across all your environments (in your configuration files that apply to all environments) and having your test API value defined as override within your e.g. `settings.local.php` file, you'd be able to access both values using Config::get and Config::getOriginal within your dev/staging environments, while only the database stored value will be available in your production site.
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: How can I add a span tag inside my menu link?
My twig file contains the following:

```
<li{{ item.attributes.addClass(classes) }}>
   {{ link(item.title, item.url) }}
</li>

```

Which outputs:

```
<li class="menu-item item--search">
    <a href="#search" title="Expand Search" data-drupal-link-system-path="<front>">Search</a>
</li>

```

But I really want to add a `<span>` tag around the text `Search` (for styling purposes and replacing the text with an icon image.

I tried replacing `{{ link(item.title, item.url) }}` with `<a href="{{item.url}}"><span>{{item.title}}</span></a>` but that loses valuable attributes provided by the `link` function (as well as the menu\_link\_attributes module). I'm not sure if I can do this in twig or I need to write some sort of function in my `.theme` file. Any help appreciated. Thank you.

# Answer
You can try this code:

```
{% set tmp = '<span>'~item.title~'</span>' %}
{% set link_text %}{{ tmp|raw }}{% endset %}
{{ link(link_text, item.url) }}

```
> 8 votes

# Answer
For adding markup to all links, you could implement hook\_link\_alter() in a custom module (in the following example named `mymodule`):

```
use Drupal\Component\Render\FormattableMarkup;

/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {
  if (!empty($variables['options']['span_added'])) {
    return;
  }

  $variables['text'] = new FormattableMarkup('<span>@title</span>', [
    '@title' => $variables['text'],
  ]);

  $variables['options']['span_added'] = TRUE;
}

```
> 2 votes

---
Tags: 8, theming, navigation
---


# Question
Title: Preserve views exposed filter options when back button is pressed
I have an ajax exposed filter in the views. When user select option from filter it loads content. But when I click on item on view and press browser back button, exposed filter resets and default option is selected. Same thing happen when I refresh the page.

Is there any way in view to preserve the last selected option? Same thing happens when I click on page number of views.

Thank you.

# Answer
You'll have to turn off ajax to get this to work until this issue is resolved. See http://drupal.org/node/1248332

Then edit your exposed filter(s) and check off "Remember last selection".
> 2 votes

# Answer
Thank you user2890. For anyone who comes across this, here is my improved version of user2890's code:

```
$('.views-exposed-widget select').each(function() {
    if (
        $(this).find(':selected').val() !==
        $(this).find('option[selected="selected"]').val()
    )
        $(this).trigger('change');
});

```

So this code would trigger 'change' event only if the selected option in the UI is different from the the option with `selected="selected"` attribute in HTML. As user2890 mentioned, you can put this code in `$(document).ready()`.
> 1 votes

# Answer
A better solution is to use some Javascript. If you're using AJAX, you're already reliant on it. Here's a one liner, using jQuery.

```
    if($('.views-exposed-widget select').length) {
        $('.views-exposed-widget select').trigger('change');
    }

```

That goes in a normal document.ready brace. It will fire a change event on the select element, thereby triggering it's AJAX event.
> 0 votes

---
Tags: 7, ajax, paging, views
---


title: How to add js to H5P embed.php file?

text:
# Question
Title: How to add js to H5P embed.php file?
H5P module creates iframes and shows content in the iframe. I need to add a js file in the iframe, but I'm not able to do it.

In the documentation there is an example how to add js to h5p:

```
/**
 * Add scripts to h5ps
 *
 * @param array $scripts
 *  Array of objects with properties path and version. Version is on the form
 *  ?ver=1.0.2 and is used as a cache buster
 * @param array $libraries
 *  Array of libraries indexed by the library's machineName and with an array
 *  as value. The value has the properties majorVersion and minorVersion
 * @param string $mode
 *  What mode are we in? Possible values are "editor", "div", "iframe" and "external"
 */
function hook_h5p_scripts_alter(&$scripts, $libraries, $mode) {
  if (isset($libraries['H5P.MultiChoice']) && $libraries['H5P.MultiChoice']['majorVersion'] == '1') {
    $scripts[] = (object) array(
      // Path relative to drupal root
      'path' => drupal_get_path('module', 'mymodule') . '/h5p-overrides.js',
      // Cache buster
      'version' => '?ver=1',
    );
  }
}

```

I have created a module, added that script in the .module file and created the overrides.js. But I am not able to get it working, the js file is not added. What else should I add in the .module file than this script above?

# Answer
You need to replace HOOK with your module name. As well as MYMODULE.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Conditional field display in node template
I have a specific content type that I am overwriting the template node--contenttype.html.twig.

This conent type has 4 fields.

* Title
* Body
* Image
* Video

I am trying to hide the image field from displaying if VIDEO field has value. Which I am doing by using this code in custom twig template.

```
{% if node.field_video is not empty %}
{{ content.field_video }}
{% else %}
  {{ content.field_image }}
{% endif %}

```

The only problem is that I get one of the fields printed as needed plus I get both fields shown.

Video filed is displayed, plus I get an image and video shown again. Wherever those fields are positioned in MANAGE DISPLAY.

If I disable the two fields in MANAGE DISPLAY then, nothing shows up at all.

How can this be fixed?

# Answer
You wrote that you are using Twig conditions to selectively print fields, but they show up twice now. This most likely is, because your template still renders the entire `content` variable somewhere like `{{ content }}`.

You can easily avoid the fields being rendered twice by using the without Twig filter. Locate the `{{ content }}` part in your template and alter it to

```
{{ content|without('field_video', 'field_image') }}

```
> 4 votes

---
Tags: 8, theming
---


title: Links to files breaking

text:
# Question
Title: Links to files breaking
I just wanted to see if anyone could offer some thoughts or opinions on an issue we are having.

We are running Drupal 8 multisite via Aegir. We have a production environment and an identical testing environment set up. In our test environment we have our Drupal 8 multisite using domains such as site1-testing.com.

The issue is the file structure is set like /sites/site1-testing.com/files/. This poses an issue when we migrate to our production domain which would be site1.com. Anywhere where we inserted a link to a file would still be referencing /sites/site1-testing.com/files/filename.pdf, which would of course, cause all of our production links to break.

We use linkit as well to insert the files into nodes. I've tried using pathauto, pathologic in conjunction with url aliases but ultimately the direct paths remain the same.

Any thoughts on how we could get around this?

# Answer
> 0 votes
Site internal links should always use URIs relative to your base URL. This would avoid your specific issue. (File entities actually do use URIs relative to the configured public files folder, so that - depending on how you created your file URLs within CKEditor - clearing your caches might help already.)

However, in a mirrored multi-site environment, you can also use the sites.php file to define the base URLs and their respective target site paths. If not configured otherwise, your files folder should use the configured target sites path and all your environments will use the same files location.

Place a `sites.php` file in your `[DRUPAL_ROOT]/sites` folder (e.g. by copying and renaming the existing `examples.sites.php` file) and configure the `$sites` array keys to your requirements. Example:

```
$sites['site1.com'] = 'site1.com';
$sites['site1-testing.com'] = 'site1.com';

```

---
Tags: 8, files, multi-sites
---


# Question
Title: Views hook_views_data add multiple joins to custom table based on row condition
I'm using `hook_views_data` to add a custom table and its fields to Views. The table relates to nodes, and looks like this:

```
+ node id   | my_value   | time_period  +
|-----------|------------|--------------|
| 1         | 100        | 1 year       |
| 1         | 200        | 1 month      |
| 2         | 300        | 1 year       |
| 2         | 400        | 1 month      |
+---------------------------------------+

```

I have defined an implicit relationship to my custom table, so I have a view with nodes as the base table and I can access the my\_value field from my custom table.

The `time_period` column is new, however. Now there are multiple rows per node, with different `time_period` values, and each of these results in a different output row in my view.

Rather than having a `my_value` field for each row, I would like to have `my_value (1 year)` and `my_value (1 month)` fields, so that each output row represents one node - i.e. rows for the same node are collapsed and their fields are separated.

I've cobbled together the SQL that achieves this, but I can't figure out how to accomplish this with `hook_views_data`:

```
SELECT
    node.title AS node_title,
    node.nid AS nid,
    custom_table_1month.my_value AS my_value_1month,
    custom_table_1year.views AS my_value_1year
FROM
    node
LEFT JOIN
    custom_table custom_table_1month ON custom_table_1month.node_id = node.nid AND custom_table_1month.time_period = '1 month'
LEFT JOIN
    custom_table custom_table_1year ON custom_table_1year.node_id = node.nid AND custom_table_1year.time_period = '1 year'

```

I have tried to add two base tables to views, called `custom_table_1month` and `custom_table_1year`, but these value names are used verbatim as the table name whereas I really want them as aliases, so Views complains that these tables don't exist, and I can't seem to specify the correct table name anywhere.

I'm feeling like this has to be possible, because I've got the SQL for it! I just can't for the life of me figure out how to do this with Views.

# Answer
You can try code

file `my_module.views.inc`

```
/**
     * Implements hook_views_data().
     */
    function my_module_views_data() {
      $data['custom']['views_handler_custom_field'] = array(
        'title' => t('Custom views field'),
        'help' => t('Field custom handler'),
        'field' => array(
          'handler' => 'views_handler_custom_field',
        ),
      );
    }

```

file `my_module.module`

```
/**
 * Implements hook_views_api().
 */
function my_module_views_api() {
  return array(
    'api' => 3
  );
}

```

file `views_handler_custom_field.inc`

```
class views_handler_custom_field extends views_handler_field{
  function query() {

    $this->ensure_my_table();
    $alias = 'custom_table';
    $this->query->add_field($alias,'node_id');

    // Month, you can copy it
    $aliasNode = 'node';
    $definition = array(
      'table' => $aliasNode,
      'field' => 'tid',
      'left_table' => 'custom_table',
      'left_field' => 'node_id',
      'type' => 'LEFT OUTER',
    );
    $join = new views_join();
    $join->definition = $definition;
    $join->construct();
    $join->adjusted = TRUE;
    $this->query->add_relationship($aliasNode, $join,$this->relationship);
    $formula ="";
    $this->query->add_field(NULL,$formula,'node_id');

  }

  function option_definition() {
    $options = parent::option_definition();
    $options['alter']['contains']['alter_text'] = array('default' => TRUE);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
  }

  function render($values) {
    var_dump($values);
  }
}

```

The API
> 0 votes

---
Tags: 7, views
---


# Question
Title: Update multiple rows (with different ids and different values) using one query
I want to update multiple rows in a custom table using just one query.

Each row has its own id (obviously) and different fields/values to update.

Given this question and this post, i think i can achieve it with a single `db_query`, similar to this one:

```
UPDATE {table} SET

`field1` = CASE `id`
    WHEN 1 THEN 'field1 value 1'
    WHEN 2 THEN 'field1 value 2'
    END

`field2` = CASE `id`
    WHEN 1 THEN 'field2 value 1'
    WHEN 2 THEN 'field2 value 2'
    END

WHERE `id` IN(1, 2);

```

Or:

```
INSERT INTO {table} (`id`, `field1`, `field2`)
VALUES
    (1, 'field1 value 1', 'field2 value 1'),
    (2, 'field1 value 2', 'field2 value 2'),
ON DUPLICATE KEY UPDATE
    `id` = VALUES(`id`),
    `field1` = VALUES(`field1`),
    `field2` = VALUES(`field2`);

```

But i'ld feel more confortable using `db_update` instead of `db_query`.

Any suggestions? Thanks

# Answer
> 0 votes
You can use below example to update:

```
    $items = array(1,2);
    db_update('your_table')->fields(array(
      'update_field_one' => $to_update_one,
      'update_field_two' => $to_update_two,
      'updated' => REQUEST_TIME,
    ))->condition('id', $items, 'IN')->execute();

```

# Answer
> 0 votes
You try the code update:

```
foreach ($updates as $key => $value) {
  $fields = array('some_field' => $value);
  db_update('your_table')->fields($fields)->condition('some_id', $key)->execute();
}

```

---
Tags: 7, database
---


# Question
Title: How to get a variable from FieldWidget in the same modules Template
I have module that is currently setup like this

```
module
  -signature.module
  -signature.info.yml
  -src
    -Plugin
      -Field
        -FieldWiget
          -SignatureWidget.php
  -templates
    -signature.html.twig

```

Everything in the module works correctly as is. I'm trying to pass a variable `$field_name = $items->getName();` from SignatureWidget.php to signature.html.twig (or signature.module so that I can then pass it to signature.html.twig). I'm trying to do this in order to apply ids generated from a variable in the widget to some of the markup in the template. How would one do this?

I understand how to do this from the .module file (Use a twig template instead of a render array in a custom module admin page), but can't seem to figure it out when it comes to plugin variables. The hook\_theme in module associated with the widget looks like this.

```
function signature_theme() {

  $theme = [];
  $theme['signature'] = [
    'render element' => 'element',
    'variables' => array('sign_src' => ''),
  ];
  return $theme;
}

```

The widget code from SignatureWidget.php looks like this

```
<?php

namespace Drupal\signature\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\ElementInfoManagerInterface;

/**
 * Plugin implementation of the 'field_signature_widget' widget.
 *
 * @FieldWidget(
 *   id = "field_signature_widget",
 *   module = "signature",
 *   label = @Translation("Signature Data"),
 *   field_types = {
 *     "field_signature"
 *   }
 * )
 */
class SignatureWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

    $file_upload_help = array(
        '#theme' => 'signature',
        '#sign_src' => $value,
      );
     $sign_thumb = array( '#type'   => 'html_tag',
                          '#tag' => 'img',
                          '#attributes' => array('src' => '', 'id' => 'signature_thumb', 'class'=>array('align-right'), 'width' =>'120px', 'height' => '60px' ));

$field_name = $items->getName();

    /*function getFieldName() {
      return $field_name;
    }*/

$text_area_id = 'signature_field_' . $field_name;

    $element += array(
      '#type' => 'textarea',
      '#default_value' => $value,
      '#attributes' => array(
        'id' => array('signature_data'),
                        ),
      '#attached' => array(
        'library' => array('signature/signature_pad'),
                        ),
    );
    $element['#attached']['library'][] = 'signature/signature_pad';
    $element['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help);
    $element['#suffix'] = \Drupal::service('renderer')->renderPlain($sign_thumb);

    return array('value' => $element);
  }

}

```

The template from signature.html.twig looks like this.

```
<div class="signature">
    <canvas width="450" height="200" class="sign-canvas">SIGNATURE CANVAS</canvas>
{% if(sign_src != '') %}
    <img src = {{sign_src}} class="sign-img"></img>
{% endif %}
     <button type="button" id="clear-sign" class="button clear" data-action="clear">Clear</button>
</div>

```

I'm trying to return the string value from $text\_area\_id in SignatureWidget.php from within signature.html.twig

# Answer
You already pass the template variable `sign_src` to your template. Now you want to pass an additional variable. You can easily do this by extending your hook\_theme implementation:

```
/**
 * Implements hook_theme().
 */
function signature_theme() {
  $theme = [];
  $theme['signature'] = [
    'render element' => 'element',
    'variables' => [
      'sign_src' => NULL,
      'text_area_id' => NULL,
    ],
  ];
  return $theme;
}

```

Then pass the ID into your template like this:

```
$value = $items[$delta]->value ?: '';
$text_area_id = 'signature_field_' . $items->getName();

$file_upload_help = [
  '#theme' => 'signature',
  '#sign_src' => $value,
  '#text_area_id' => $text_area_id,
];

```

And use it in your template like this:

```
{{ text_area_id }}

```

***Edit: Some further suggestions for your code snippets:***

Wherever possible, you should leave rendering to the theming engine and avoid manually calling the `\Drupal::service('renderer')->renderPlain()` method. Your description will do just fine with the render array. Your `#suffix` can be changed to a distinct child element of your widget element (note: there is no hash before):

```
$element['#description'] = $file_upload_help;
$element['suffix'] = $sign_thumb;

```

In your template, you can change the empty check to

```
{% if sign_src %}
  <img src="{{sign_src}}" class="sign-img" />
{% endif %}

```

And should wrap the src URL into quotes.

A final note about the URL itself: It seems to be a user given value. If so, consider using UrlHelper::stripDangerousProtocols before you pass it into the template.
> 2 votes

---
Tags: 8, theming, plugins
---