# Question
Title: Setting fallback values for a template based on a parent entity via entity reference
I have a node content hierarchy of Chain (parent) and Property (child), related by an entity reference (ER) on the Property back to Chain.

Each of these node types has an ER to a Skin (custom entity) - these Skins furthermore contain ERs to Slides (another custom entity) but I don't think that's important right now (Shirley!) This is all held together with Inline Entity Form.

I have a situation that I can't work out after many attempts. There is a multi-value field on the Property create page:

* Make a new Skin (use the IEF on this page)
* Use the parent values (use the Chain's skin)
* Use fallback mechanism (where Property has no value set, use the Chain value)

This means I need to either:

* process & inject the Chain's Skin into the Property's Skin template as an additional variable, and perform the either/ors in there based on the multi-value
* preprocess the Skin so that the correct values are already present in the template so I can just "go ahead and render" based on the multi-value.

Ideally, I'd like to be able to just use the normal {{ content }} variables in the end template, either way. The first suggestion I tried, but I have got no idea, I've tried lots of things. The second looks like it might work with some sort of hook\_entity\_view\[\_alter\] or similar, but I have been unable to deduce the correct approach or find a suitable example to copy.

# Answer
> 0 votes
Had to post an answer as I need to put more code.

The desired outcome is I can do this: `{% if property.multivalue.value is fallback %}
 {% if property.somevalue is set %} {# check property for a value #}
 {{ content.field_image }} {# from property's skin entity #}
 {% else %}
 {{ chain.field_image }} {# FALLBACK value, from chain's skin entity #}
 {% end %}
{% end %}`

I've got as far as this in code:

```
function tap_preprocess_skin(&$variables) {
  // on skins where the owner node is a Property
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->getType() === 'property') {

      // set a flag to decide how to handle this skin (content = inherit|fallback|new)
      $variables['skin_source'] = $node->field_property_skin_source[0]->getString();

      // additionally set a parent (chain) skin in the template
      $variables['chain_skin'] = $node->field_ref_chain[0]->entity->field_skin[0]->entity;
    }
  }
}

```

This gives me a scenario where I have the raw entity in the child skin template. For example, in any given node, I have {{ content }} and also there is a {{ node }}. Here, I have (for my skin), {{ content }} and {{ skin }} and {{ chain\_skin }} (latterly, as per above code). However this means I have to render the fields manually, and some of the contents of the skin is more ERs and I don't really want to have to do some massive coding exercise when there's blatantly a way to make a preprocess take #skin from Chain and make let's say {{ chain\_skin\_content }}, rather than the raw {{ chain\_skin }}.

I'd be perfectly happy at this stage to do the logic in the preprocess but I've had no luck there either. I'm sure there's some sort of entity API function that is the right point to tap into but I've not been able to deduce it.

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


# Question
Title: Attach custom css library to entity print output
I need to attach custom css library so entity\_print module uses it to generate the final PDF.

The goal is to get custom css effect the generated PDF at `/print/pdf/node/{{NID}}`

I have set the PDF engine to mpdf under entity print configuration

I tried the following 2 methods unsuccessfully :

1. Attach to node.html.twig file using `{{attach_library('THEMENAME/library_name')}}`
2. Attach it to `entity_print` at `THEMENAME.info.yml` file per described at https://www.drupal.org/node/2706755

I don't see the attached css at `/print/pdf/node/{{NID}}/debug` when inspecting elements

Any help or pointers are appreciated.

# Answer
> 4 votes
I am answering my own question for the ones who might probably face similar issues.

The 2nd method as described at https://www.drupal.org/node/2706755 where we attach the library to `entity_print` works.

I had a custom `entity-print--node.html.twig` in which I **missed** printing the css styles using the variable `{{ entity_print_css }}`

---
Tags: 8, theming
---


# Question
Title: Replace username with unique hash when users delete their own accounts
When users delete their own accounts (with the core function), I don't want the username to be replaced by *anonymous*, but with a hash string, for example anonymous-dhjf4ued.

I tried doing it with the Rules module, and I looked for modules that could do it, but I couldn't figure it out.

The reason this would be useful is because I have sites with a forum and threads are much more readable if you can still identify which users are the same (who responds to who) if there are two cancelled user accounts in a single thread.

# Answer
> 0 votes
You can use hook\_user\_cancel() like below:

```
  /**
   * Implements hook_user_cancel()
   */
    function example_user_cancel($edit, $account, $method) {
      // Define in which method you are canceling the account, else remove it and
      // proceed with below code by removing this if condition.
      if ($method == 'user_cancel_block') {
        $user_load = user_load($account->uid);
        $user_load->name = 'anonymous-'.time();// Here you can add your random number.
        user_save($user_load);
      }
    }

```

---
Tags: 7, users
---


# Question
Title: I'm writing a custom module, and I am able to upload an image but unable to update image in edit
```
function my_custom_table_edit_form($form, &$form_state){

  $id = arg(3);
  $result = db_query('SELECT * FROM {custom_table} WHERE id = :tid', array(':tid' => $id));
  /* foreach($result as $val){
       $record = $val;
     }
  */
  $record = $result->fetchObject();
  // now I add a text field to the form
  // with a label and fixed dimensions (you never know…)
  $form['my_custom_table_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#value' => t($record->title),
    '#description' => t('The Title of the My Custom Table.'),
    '#size' => 40,
    '#maxlength' => 120,
    '#required' => TRUE,
  );
  // Textarea for the body
  $form['my_custom_table_description'] = array(
    '#type' => 'textarea',
    '#rows' => 10,
    '#columns' => 40,
    '#title' => t('Description'),
    '#value' => t($record->description),
    '#required' => TRUE,
    '#description'=> t('The text of My Custom Table .'),
  );
  $form['my_custom_table_image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image'),
    '#default_value' => t($record->image),
    '#size' => 40,
    '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    '#upload_location' => 'public://firoz_uploads/'
  );
  // hidden for the body
  $form['id'] = array(
    '#type' => 'hidden',
    '#value' => t($id),
  );
  // Checkbox to indicate.
  $form['my_custom_active'] = array(
    '#type' => 'checkbox',
    '#title' => t('Status'),
    '#description' => t("Indicates whether the active or inactive."),
  );
  // now I add also a button
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
  // and now I assign a my function as handler of the submit event
// $form['#validate'][] = 'my_custom_table_submit_handler';
  $form['#submit'][] = 'my_custom_table_edit_submit_handler';
  return $form;
}

function my_custom_table_edit_submit_handler($form, &$form_state){
  // this function will be executed after the click
  // event of the user on the "submit" button.
  // here I only print a message
  // you can access a database, redirect, or whatever you want, obviously
  $error = 1;
  if ( !isset($form_state['values']['my_custom_table_title']) || !isset($form_state['values']['my_custom_table_title'])) {
    $error = 0 ;
  }
  if($error){
    $id = $form_state['values']['id'];
    $my_custom_table_title = $form_state['input']['my_custom_table_title'];
    $my_custom_table_description = $form_state['input']['my_custom_table_description'];
    $my_custom_table_image = $form_state['input']['my_custom_table_image'];
    if (isset($form_state['input']['my_custom_table_image'])) {
        $file = file_load($form_state['input']['my_custom_table_image']);
        $file->status = FILE_STATUS_PERMANENT;
        $my_image_file_name = $file->filename;
        file_save($file);
    }
    $data = array(
        'title' => $my_custom_table_title,
        'description' => $my_custom_table_description,
        'image' => $my_image_file_name,
    );
    $num_updated = db_update('custom_table')
    ->fields($data)
    ->condition('id', $id, '=')
    ->execute();
    drupal_set_message(t('Record has been Updated!'));
  }
}

```

During submit I have checked that File element returns the empty/NULL.

Here $form\_state\['values'\]\['my\_custom\_table\_image'\];

# Answer
> 0 votes
There are some corrections in your code.

1) $id in submit handler. use $id from $form\_state\['values'\] rather than input. As upload happens in ajax, $id will be replaced by "**ajax**".

2) Save FID in the table rather than filename

3) use default values only if there is any data in your table for that TID.

4) Use db\_merge rather than db\_updat. Initially, you don't have any values to update using ID as the condition.

Made some changes in your code hope this helps you.

```
  function my_custom_table_edit_form($form, &$form_state){

    $id = arg(3);
    $result = db_query('SELECT * FROM {custom_table} WHERE id = :tid', array(':tid' => $id));
    /* foreach($result as $val){
      $record = $val;
      } */
    $record = $result->fetchObject();
    // here set default values.
    if ($record) {
      $title = t($record->title);
      $description = t($record->description);
      $image = t($record->image);
    }
// now I add a text field to the form
// with a label and fixed dimensions (you never know…)
    $form['my_custom_table_title'] = array(
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#value' => isset($title) ? $title : '',
      '#description' => t('The Title of the My Custom Table.'),
      '#size' => 40,
      '#maxlength' => 120,
      '#required' => TRUE,
    );
// Textarea for the body
    $form['my_custom_table_description'] = array(
      '#type' => 'textarea',
      '#rows' => 10,
      '#columns' => 40,
      '#title' => t('Description'),
      '#value' => isset($description) ? $description : '',
      '#required' => TRUE,
      '#description' => t('The text of My Custom Table .'),
    );
    $form['my_custom_table_image'] = array(
      '#type' => 'managed_file',
      '#title' => t('Image'),
      '#default_value' => isset($image) ? $image : '',
      '#size' => 40,
      '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
      '#upload_location' => 'public://firoz_uploads/'
    );
// hidden for the body
    $form['id'] = array(
      '#type' => 'hidden',
      '#value' => t($id),
    );
     // Checkbox to indicate.
   $form['my_custom_active'] = array(
      '#type' => 'checkbox',
      '#title' => t('Status'),
      '#description' => t("Indicates whether the active or inactive."),
   );
   // now I add also a button
   $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
   );
   // and now I assign a my function as handler of the submit event
   // $form['#validate'][] = 'my_custom_table_submit_handler';
   $form['#submit'][] = 'my_custom_table_edit_submit_handler';
   return $form;
  }
}

function my_custom_table_edit_submit_handler($form, &$form_state) {

// this function will be executed after the click
// event of the user on the "submit" button.
// here I only print a message
// you can access a database, redirect, or whatever you want, obviously
  $error = 1;
 // use your ID by getting it from dorm state values, as your image upload is in ajax, $id will be replaced.
  $id = $form_state['values']['tid'];
  if (!isset($form_state['input']['my_custom_table_title']) || !isset($form_state['input']['my_custom_table_title'])) {
    $error = 0;
  }
  if ($error) {
    $my_custom_table_title = $form_state['input']['my_custom_table_title'];
    $my_custom_table_description = $form_state['input']['my_custom_table_description'];
    $my_custom_table_image = $form_state['input']['my_custom_table_image'];
    if (isset($my_custom_table_image)) {
      $file = file_load($my_custom_table_image['fid']);
      $file->status = FILE_STATUS_PERMANENT;
      // **Use FID here rather than filename.**
      $my_image_file_name = $file->fid;
      file_save($file);
    }
    $data = array(
      'title' => $my_custom_table_title,
      'description' => $my_custom_table_description,
      'image' => $my_image_file_name,
    );
    // use DB merge as you dint have any data to update initially
    $num_updated = db_merge('custom_table')
      ->key(array('id' => $id))
      ->fields($data)
      ->execute();
    drupal_set_message(t('Record has been Updated!'));
  }
}

```

---
Tags: commerce
---


# Question
Title: Hook to compare the already saved value of moderation state of node and updated value
I'm using Workflow state on a content type. What is the correct HOOK should I use in my custom module to check if the workflow state of the node changed from value to another value to add some actions.

# Answer
I Used hook\_entity\_presave and compared values by using `$entity->original`

and `$entity`
> 0 votes

---
Tags: 8, entities, hooks, workflows
---


title: Link media images

text:
# Question
Title: Link media images
We've transitioned to the media module for our Drupal 8 site. However, after extensive futzing, I can't figure out how to add a link to an embedded media image.

When you click on the media image, the image is highlighted, and you can right-click to get a menu. However, when I highlighted the image with a single-click, and then clicked on the link icon for the link dialog, the link was created just above the image.

I've also tried to click+drag my the cursor over the image, to highlight it (and whatever else I might get), and then use that multi-selected area, but I still get the same behavior.

How can I turn my media image into a clickable link?

**Edit** I thought this issue, Linking media thumbnail image to internal/external url might be about my situation. But, the patch (about a year old) doesn't apply anymore:

```
/core/modules/media
$ patch -p1 < 2873754-8.patch
patching file src/Plugin/Field/FieldFormatter/MediaThumbnailFormatter.php
Hunk #1 FAILED at 11.
Hunk #2 succeeded at 66 (offset 4 lines).
Hunk #3 FAILED at 106.
Hunk #4 FAILED at 121.
Hunk #5 succeeded at 132 (offset 4 lines).
Hunk #6 succeeded at 163 with fuzz 2 (offset 7 lines).
Hunk #7 FAILED at 177.
Hunk #8 succeeded at 214 with fuzz 2 (offset 14 lines).
4 out of 8 hunks FAILED -- saving rejects to file src/Plugin/Field/FieldFormatter/MediaThumbnailFormatter.php.rej

```

# Answer
> 1 votes
I found this issue, which has a series of patches and perhaps a module. I'm about to go into testing; perhaps-- hopefully-- coming out with a solution, but for now, there is not a clear solution.

**Edit** I applied the patch from comment #47, and it seems to work. At the time of writing, it's only 9 days old, but we're rolling with it since we need to link images.

---
Tags: 8, wysiwyg
---


# Question
Title: How is domain_taxonomy_access module configured?
I am trying to use the domain\_taxonomy\_access module, but I do not know how it is configured.

How I do so that the user of a certain domain can manage their newsletters?

I am trying to implement the solution shown here: https://www.drupal.org/project/domain/issues/558692

Thanks

# Answer
> 0 votes
I have found the solution by myself.

I use domain access with simplenews, i need the Domain Simplenews to,

What you have to do, is go to:

```
structure / taxonomy / [yourtaxonomynewsletter]

```

Then `edit some term` of the taxonomy and at the end of the configuration called `Term source domain` there is an option to set the domain to the taxonomy.

---
Tags: 7, domain-access
---


# Question
Title: Translated content not accessible / wrong links
At the moment I am working on a multilingual page (German/English). I finished adding my German content, and want to add my English version, so I can access it like `examplesite.com/examplepage` (German) --\> `examplesite.com/en/examplepage` (English).

The steps I did so far:

* I enabled the right custom language settings for translation
* I added the needed pathauto-patterns
* added a path-prefix-configuration for English "en"

My problem now is the fact, that I can't access these pages after adding the translations.

This means when I access a German site in the front end, and click the language switch to the English version, it won't link me to the translated content but only refreshes the page.

The same weird behaviour is shown in the backend on the content-overview page. The translated pages all exist in the list and if I hover over the title it will show me the right URL like e.g. `examplesite.com/en/examplepage` but when I open the url it will just show me a 404. It seems that the content is not connected to the right, translated urls.

Am I missing something?

# Answer
In addition to the Regional and language configuration (as listed in the other Answer) it is really important to **flush the cache** for the configuration to take effect properly.

Flushing cache through the Admin links is problematic because of the same issue we're trying to solve, the link to flush cache is also affected by content not being refreshed to follow the new language settings. You can delete the language prefix manually from the browser addressbar yourself and then `Enter` to actually flush the cache. But it can still be confusing and difficult to know whether this had an effect.

The way to go in this case is to use Drush script, because it doesn't depend on the internal Drupal language configuration (cache-rebuild for Drupal 8):

`$`**`drush cr`**

or through the Performance page (Administration \> Configuration \> Development \> Performance (`/admin/config/development/performance`)) button **`Clear all caches`**.
> 0 votes

# Answer
In addition to enabling "URL" Detection method (path prefix or domain) and positioning it to be used first, you also have to **Configure** it.

1. Set German as your **Default** language under Administration \> Configuration \> Regional and language
2. Go to the Language `Detection and Selection` page and enable the "URL" Detection method
3. On the Language `Detection and Selection` page click through the **Configure** button for the URL (`/admin/config/regional/language/detection/url`)
4. Select "Path prefix" as the " Part of the URL that determines language" option
5. **Delete** the `de` from the "German (de) path prefix (Default language)" option
6. Clear cache! This can be tricky through the interface if you're using the admin module because the `/de/` might linger on the menus but will lead to a Page not found. Delete the `/de/` in your browser Location bar from the flush cache link to make it work.

After this you should have the correct Home in German, without the `/de`, German content and links without the prefix and English content and links with `/en/`.
> 0 votes

---
Tags: 8
---


title: Node content is not listing for author

text:
# Question
Title: Node content is not listing for author
I have a view page with url user/%/plans.Which listing contents by a particular user.But listing can be seen only for the administrator when visit their dashboard(from admin/people)(screenshot 1). But logged in user(content author) cannot see the list(screenshot2).

I gave all the permission to the author to view his content.But it is not working.Can any one give suggestions to solve this issue? This is my views(screenshots 3 & 4)

# Answer
> 0 votes
Your Contextual filter should use `Validator` **Current user ID matches argument value** instead of **User**:

---
Tags: nodes
---


# Question
Title: Which hook can I use before or after submitting a webform form?
I created a webform form with drupal 8.

I would like to populate a database table with information from my form before or after submitting.

I guess there must be a hook like hook\_webform\_pressave () or hook\_webform\_insert () but I have not found the solution.

Thank you for your help

# Answer
Take a look at the answer to Add a custom submission handler to a form. This will tell you how to add a submit handler to a form. You can use the same approach to add a custom submit handler to the webform and then perform the operations you want from the submit handler.
> 2 votes

---
Tags: hooks, webforms
---


# Question
Title: What's the difference between content type and node?
I have been reading information about what is a content type and what is a node. I understand what a content type is (a collection of fields), but I don't know exactly the difference between a node and a content type.

In drupal website, I can read:

> A **node** is any piece of individual content, such as a page, poll, article, forum topic, or a blog entry
>
> **Content-Type** is a pre-defined collection of data types (Fields) which relate to each other by an informational context

For example, I think an article is a content-type, but it seems that, at the same time, it's also a node. So I don't understand the difference.

It seems that a node is a super-category while a content-type seems to be a sub-category. Is it right? How would you explain to me as simple as possible?

# Answer
> 0 votes
In an easy to understand way:

**Node** is a page.

**Content type** is the page type or page fields & page structure.

For example, you could create a new content type called "Blog". Here you can add the fields that you would like blogs to have. The other content type "Articles" may not have the same fields that "Blogs" have.

So when you go create a node, you choose which one you would like, "Blog" or "Article".

# Answer
> 3 votes
Newcomers to Drupal who aren't tech savvy often struggle with the concept of Content types and Nodes.

I find it beneficial to remind them of the real world equivalent—**forms** and **filling in forms**.

Remember in the olden days when you were given a piece of paper out of a whole stack of them, with labels and boxes and you used a pen to fill in your information by hand (name, address, DOB, etc.) when applying for a college or anything?

The Drupal equivalent to a real-life stack of blank sheets of preformatted forms is a Content type. When you're creating a Content type in Drupal, you're actually designing a form of blank fields. You're designing a structure, it holds no data.

In the digital world, we don't have to have multiple copies of Content types, one is enough because it doesn't have to be printed on paper. It is printed on the screen and we can always use the same "source". That's way we only have one “Create article” form and not thousands of them like you have to in paper form.

When you fill in one sheet of paper in ink with your specific information it is considered one form submission. The Drupal equivalent to this one filled-in sheet of paper is a Node. Node is the actual data entered into the structure defined by the Content type. You can create many Nodes (data submissions) for a Content type.

When you want to publish an Article you are first presented with a form to fill—Create Article page. This is the Content type form. Once you enter specific data into it and Save, you have created one submission of that form, one Node. You can create many nodes, with different data, as submissions to the same form.

---
Tags: nodes
---


title: Google OAuth Login Solutions?

text:
# Question
Title: Google OAuth Login Solutions?
Can anyone recommend a Google OAuth solution for D8?

I've done some looking, the only real viable solution that I can find is the OneAll Social Login module. This would potentially work for us, but we don't necessarily need something with 35+ login options. There seem to be other modules out there, but either seem to be confined to D6/D7 or have very low usage stats.

I'll explain what we are attempting to do. We have a dashboard that our customers login to, they can then launch into their various services from there. We'd just like to provide the option to login & associate a Google account with your existing D8 account to streamline the process.

EDIT: @drastik provided links to the Social API Stack module and it works without any issue. This is exactly what we wanted.

# Answer
> 3 votes
It looks like the Social API stack is the solution going forward in D8:
https://www.drupal.org/project/social\_api
https://www.drupal.org/project/social\_auth
https://www.drupal.org/project/social\_auth\_google

Good luck!

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


# Question
Title: How to use URL query parameter on a View Exposed Filter?
We have a View which has the following settings. How can we setup the view to use a query parameter from the URL to filter the results?

Article Content Type (fields):

1. Title
2. Body
3. Category (field\_category) --\> taxonomy
4. Type (field\_type) --\> taxonomy

View Exposed Filters (values)

1. Category (All, Security, IoT, Wifi, Network)
2. Type (All, Blog, Press Release, Breaking News)

Desired output:

* When the URL is `www.mysite.com/news?type=Blog`, then set filters Type=Blog and Category=All to return results of all Article pages where type=Blog and Category can be any (not null)
* When the URL is `www.mysite.com/news?type=Blog&Category=Security` then filter results to return all Article pages where type=Blog and Category=Security

We tried adding a contextual filter with the following settings only but it did not work.

# Answer
> 3 votes
Views Exposed filters already work this way, no need for any Contextual filters.

In the settings for each Exposed filter there is an option to type in `Filter identifier`. That is the text that will be used for that field in the query.

In your case set the `Filter identifier` of the Category to `Category` and of Type field to `type`.

If you configure the Exposed filter `Selection type` settings for those two filters to `Dropdown` then you'll have to use term IDs in the link to make the filter work (I'm assuming your Security term has ID 6):

`www.mysite.com/news?Category=6`

## Use `Autocomplete` to get term names in query

But if you set the Exposed filter `Selection type` settings to `Autocomplete` you will be able to use term names, which is what you want.

`www.mysite.com/news?Category=Security`

or

`www.mysite.com/news?Category=Security+(6)`

Drupal 8 adds the term ID next to the term name when choosing from the autocomplete suggestion list, but that part isn't necessary. You can construct the link with Category name only and it will work. If the Category name has spaces in it, replace them with `+` in query.

If you have more than one Exposed filter they get combined, for all types:

`www.mysite.com/news?Category=Chemistry`

or

`www.mysite.com/news?Category=Chemistry&type=`

and for some specific type in addition to Category:

`www.mysite.com/news?Category=Chemistry&type=Blog`

or change order:

`www.mysite.com/news?type=Blog&Category=Chemistry`

# Answer
> 0 votes
When using the labels of entities in filters, instead of the id, I need to "Specify validation criteria" and select the appropriate option. In this case I would "Taxonomy term name" validator. These options appear in the "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" group.

Update: I didn't realize you were using Exposed and Contextual filters when I originally posted -- I thought you were just using Contextual. Also, I do think it's not a "best practice" to use contextual and exposed filters for the same filtering, but I think it's fine (if you're seeing the behavior you want) because I don't know of a way to use just Exposed Filters and get the label in the url like you want. I'm bet there's a way using custom code, but I don't know it.

---
Tags: 8, views
---


title: View of attached files to a node

text:
# Question
Title: View of attached files to a node
I use D8 Editor File upload to add files to a node. But i want an overall view from all the files in that node, but only in that node. I can create a view for all the files but i can't filter on the nid of the current page.

The project: attachment\_links seems to kinda do what i want but its only for Drupal 7. Does anyone know of a similar Drupal 8 project or a way do code it manually into a block?

# Answer
> 1 votes
The D8 Editor File upload is using the Drupal file system, so the files uploaded through module do have FID and can be listed in Views.

Here are steps to create a block to show only the files used on the currently visited node:

1. Create a View of type `File` with a Block display showing Filename (you probably have this already)
2. Add a Contextual filter in your Views Block Display called **Entity ID** from the `File Usage` Category.
3. Adjust the settings for that Contextual filter:
`When the filter value is NOT available`
**Provide default value**
`Type` to **Content ID from URL**
`When the filter value IS available or a default is provided`:
**Specify validation criteria**
`Validator` to **Content**
`Content type` \[choose appropriately\]
Leave the rest as default
4. Place the Block in a region you like, adjust the Block options `File Usage: Entity ID` to **Node from URL** and restrict to display only on relevant Content types.

Now when you visit nodes of the types you selected in Block and Contextual filter settings will list only the files uploaded to those nodes.

---
Tags: views, 8, files
---


# Question
Title: Drupal 7 - Node specific template not working
I have done some research and everything I see to create a node specific template says to name the template file, for example, page--node--676.tpl.php

However when I clear the cache and load the file it still shows the old template. What could I be missing?

# Answer
If you haven't already done so, I'd recommend enabling theme debugging feature of Drupal 7.

In the **settings.php** file, or preferably in **settings.local.php** file if you have one, add the following line, and clear the cache once more.

```
$conf['theme_debug'] = TRUE;

```

> When debugging is enabled:
> \- The markup of each template is surrounded by HTML comments that contain theming information, such as template file name suggestions.
> \- Note that this debugging markup will cause automated tests that directly check rendered HTML to fail.
>
> For more information about debugging theme templates, see https://www.drupal.org/node/223440#theme-debug.
>
> Not recommended in production environments.

This should give you the available template name suggestions in the generated HTML.
> 2 votes

---
Tags: theming
---


title: How to show summary in node view?

text:
# Question
Title: How to show summary in node view?
While adding article, I am having an option to enter summary for article. But this summary is not displaying in node view. I wanted summary to be displayed in full node view.

Any ideas how can I show summary in full node view?

-- Many thanks for your time.

# Answer
Solved it by overriding node template for my content type.

1) Copied `node.tpl.php` of my theme and renamed it to `node--content_type.tpl.php`.

2) Put the following code at desired place:

```
<div class="fullmode_summary">
    <?php if ($view_mode == 'full'): ?>
      <?php print render($node->body[$node->language][0]['safe_summary']);  ?>
    <?php endif; ?>
</div>

```

May help someone having same issue.
> 2 votes

# Answer
I did this a bit differently as I had 8 content types that needed the summary and they were displayed in different places in the node. first add a dynamic field in display suite, choose node:tokens then summary. then add this code to template.php

```
function themename_preprocess_node(&$vars) {

//adding the summary field to the node via DS results in a field that displays 'summary or trimmed'
//what is needed is 'summary or nothing' because the body is already displayed
if($vars['view_mode'] == 'full') {
    $object = entity_metadata_wrapper('node', $vars['node']);
    if(!empty($vars['content']['body'])) {
        //get the value of the summary field
        $summary_value = $object->body->summary->value();
        //if there is no summary remove the trimmed body text from the summary field
        if(empty($summary_value)) {
            unset($vars['content']['summary']);
        }
    }
}
}

```
> 0 votes

# Answer
Use 'display suite'.

1. enable display suite extras
2. map the summary field.

In addition to display suite, this requires the token module.

Map by, adding a custom field via the tabs on the bottom left of *manage display*

1. List item
2. Then *add a code field*
3. Add a label
4. Bind it to *Node*
5. Enter the text \[node:summary\]
6. Check the *Token* box

You can then add the field you just created to your display.
> -1 votes

---
Tags: 7, nodes, entities
---


# Question
Title: How to make diffrent registration form for diffrent role
I want to make a registration form that be different for efferent role. At the first I use the auto assign role for that the user can choose the role. At now the user can choose him-self's role. I want if he(or she) choose role "A": He should answer some field like phone number and if he(or she!) choose role "B" He should answer some other field like home address but he cant answer the "phone number" by choosing this role What should I do? Is there any module?

# Answer
Multiple Registration module is the answer. I haven't tried it, but here is what it says

> This module adds ability to create role-specific registration pages. Example of situation when this module could help you:
>
> You need to create two user registration pages. One for general users and one, let's say, for hosters. You need to add several specific fields for hoster registration page and these fields should not be available on general user registration page. Furthermore, if you need some hosters fields only on user edit page, without showing these fields on registration page, this module could help you too.

Profile2 is another option. It lets you add different fields for different roles which are not part of user entity as opposed to above module.
> 1 votes

# Answer
Try the Conditional Fields Module. This module allows you to hide or show fields based on other fields.
> 0 votes

---
Tags: users
---


# Question
Title: Apply text filter (not text format) in Twig
Is it possible to apply a specific text filter (not a whole text format) to a string in Twig?
(Or at least in template preprocess, if not possible in Twig)

Use case:

I've a special block for hand-picked, trusted editors that allows them to inject unfiltered HTML (for social widgets like Facebook posts, TripAdvisor reviews, etc) into the homepage. Basically it is just a custom content block with a text field, and printed using `|raw` to avoid style and script tags being from filtered:

`{{ content.body.0['#text']|raw }}`

This does already work as expected.

Now I've got the additional requirement to apply the text filter from the LinkIt module on this field. The editors want to provide a link to a node, and the link to the node should be printed using the correct language prefix and the SEO-friendly URL alias. E.g. I've got a text field containing something like

```
<script src="https://external.com/social_widget.js" async defer>
<div id="#placeholder_social_widget"><!-- External widget does it's magic in here</div>
<script>/* some scripts from us */</script>
<a data-entity-substitution="canonical" data-entity-type="node" data-entity-uuid="whatever-123-abc-def">Link with correct language prefix and SEO-friendly URL-alias</a>

```

and I want to run the LinkIt replacement on that field and then output it, but without filtering or escaping any of the JS or CSS.

# Answer
My issue was a misunderstanding of how the filter "Display any HTML as plain text" works: I thought enabling it would allow me to enter *all* HTML code, but in fact it does the exact opposite, it does not allow *any* HTML code.

After disabling the "Display any HTML as plain text" filter, the LinkIt filter worked as expected, I could use a normal text format printed with `{{ content.body }}` without any post-processing like `|raw` or similar.
> 0 votes

# Answer
If those HTML are *mostly* or all static, you could consider implementing your own tokens via hook\_token\_info() and hook\_tokens() in your custom module.

This way, you would avoid any potential risks, and accidentally malformed markup... and would have to full control on the replaced and returned markup.

Your authors would add a token like this in the content: `[custom:facebookpost:12345]`

... and your token could return an embedded Facebook post markup in return.

In my experience this method works much better than any other alternatives, mostly because:

1. those embed widgets usually have custom tags and/or tag attributes which may not be compatible with CKEditor settings, text formats, etc.
2. embedding those widgets directly, would make maintaining content much harder on the long run.
3. provider(s) may change the embed markup. (Consider updating 100s or thousands of content entries via find & replace vs. updating the embed markup in token definition only)
4. and it's not a hack.
> 0 votes

---
Tags: 8
---


title: Protect drupal code injection from url

text:
# Question
Title: Protect drupal code injection from url
Recently my drupal site is hacked. When i see website log from drupal admin panel someone trying to inject code from url. I searched my website(drupal) directory lots of code in page appended and new files are created.

**My question is that**

1. Is this possible to inject code from url
2. If use how to protect them in drupal

**log image**

# Answer
> 5 votes
The logged requests are clearly attacking the security vulnerability SA-CORE-2018-002. But this is not your main concern now when you've already been hacked, because most hackers close the vulnerability after they take over your site to not get hacked again by other hackers. You probably need to restore your site from a backup before SA-CORE-2018-002 (but then of course go online only after applying the security updates) or if you have no backup available setup the site from scratch, because it's nearly impossible to clean a hacked site from all malicious code and data.

See Drupal core - Highly critical - Remote Code Execution - SA-CORE-2018-002 and the FAQ.

# Answer
> 3 votes
* Yes, it's possible to inject code from URL it that is not properly Sanitized. Check this link for how to prevent database injection attacks and write secure code.
* Always give proper permissions to files for anonymous users.
* Upgrade to latest version of Drupal for new security releases (**Test it before moving to production**)
* Look at all the roles on your site. What permissions do they have? Which have advanced permissions that could be used to take over a site? Perhaps there is a new role you know you didn't make. Is there one user with that role? Check fo this.
* **Plan for the Worst**

While no one wants to consider that their site could be vulnerable, you must hope for the best but plan for the worst. This means making frequent backups that you can upload in the event that someone hacks into your Drupal site. Backup and Migrate is one such module that allows you to schedule backups and import saved databases.

See this link for more info on "**Remote Code Execution**"

---
Tags: users, files, debugging
---


# Question
Title: How to use Entityfieldquery with two field conditions for the same field
I need to make a query where the same filed must have one value OR another. Basically:

```
->fieldCondition($field_example, 'tid', (array) $var1) ... OR
->fieldCondition($field_example, 'tid', (array) $var2)

```

Already saw some examples using TAG but I really don't understand how it's done. In alternative, can I use dbquery? Or should I avoid it?

Thanks!

# Answer
> 1 votes
You should be able to use `db_or()`, something like this:

```
$or = db_or()
  ->fieldCondition($field_example, 'tid', (array) $var1)
  ->fieldCondition($field_example, 'tid', (array) $var2);
$query->condition($or);

```

More info here.

# Answer
> 1 votes
In EFQ, `db_or()` is not possible to add. So both the top answers are wrong!

By adding a TAG to the query and later altering it seems to be the best possible way. However I've found that using basic `db_select` instead of EFQ for those cases serves me good.

But who wants to add OR to EFQ: Using OR with EntityFieldQuery

---
Tags: database
---


title: Sending user edit form to user profile

text:
# Question
Title: Sending user edit form to user profile
I'm trying to send user edit page to the user profile page (/user), so I can get user profile informations and user edit form on the same page.

```
function hook_preprocess_user_profile(&$vars) {
  global $user;
  $account = user_load($user->uid);
  $vars['form'] = drupal_get_form('user_profile_form', $account);
}

```

Then in user-profile.tpl.php I have the following :

```
<?php print drupal_render($form['field_user_address']); ?>
<?php // Print necessary validation fields and remove others
      unset($form['field_user_society_id']);
      unset($form['field_user_locations']);
      unset($form['locale']);
      unset($form['account']);
      print drupal_render($form);
 ?>

```

It works well, I have my form, the datas are coming into it but when saving it, even if I get status message "Changes have been saved" actually no datas are saved.

I tried to put `module_load_include('inc', 'user', 'user.pages');`in a hook\_init() and in a form\_alter, but no way to get the form datas saved.

Thanks for helping.

# Answer
> 0 votes
So, the solution was quite simple.

I just needed to remove the call to `$form['field_user_address']`

```
//<?php print drupal_render($form['field_user_address']); ?>
<?php // Print necessary validation fields and remove others
      unset($form['field_user_society_id']);
      unset($form['field_user_locations']);
      unset($form['locale']);
      unset($form['account']);
      print drupal_render($form);
 ?>

```

---
Tags: 7, users, forms
---


title: Database contents

text:
# Question
Title: Database contents
complete drupal(7) noob question: I'm wondering if my site's contents are kept entirely on the db or perhaps also on the file system of my host.

In other words, suppose I want to migrate a site from one host to another, would it be enough to copy the sql db? or do I need to bother with additional files?

# Answer
It would be best to grab a copy of the website files/code base as well in almost every case.

For example the code that manipulates the look of the site is contained in the file structure.
Most of the text that is found on pages are in the sql DB.
The way content is displayed on some pages and not others could be in DB or the way the files manipulate the DB.

Therefor the standard practice is to take a snapshot of the code base as well as the database, as a pair, to the new hosting environment.

I would strongly suggest that you have a really good look at the D7 migration manual. It may look lengthy, but there are so many things that could derail your move, it's definitely worth it to know what's going on if things go funny.
> 3 votes

# Answer
The file system contains: contrib modules, themes, and uploaded images.

Therefore, if you have added any of these and if you were to just move the DB, you will get errors.

**Important**

*sites/all/default/settings.php* contains the connection to the DB. So either you edit this file and update the settings, or don't bring this file with you. In your new host, you will get the Drupal installer when you try to see the site (since settings.php is missing). Install Drupal, then clear the DB and import your DB.
> 2 votes

---
Tags: database
---


# Question
Title: Can Drupal 8 Form #states API be used to expand/collapse <details>
Given a checkbox field with two options:

* "Closed" (selected by default)
* "Open"

I'd like to expand or collapse the `<details>` container of a different field (in our specific case an Address field). In HTML terms, this means adding the `open` HTML5 attribute to the `<details>` tag and adding `aria-expanded=true` to the `<summary>` tag when the "Open" radio button value is clicked, and ensure it is removed when that radio option is not selected (which means by default at page load time as well).

I've found a few older semi-related issues and the documentation page for Drupal 8's `drupal_process_states`, but it's looking like this isn't possible with the Form `#states` API in Drupal 8. The docs do not include "open" in the list of valid states that may be applied to an element.

The valid states are:

* enabled
* disabled
* required
* optional
* visible
* invisible
* checked
* unchecked
* expanded
* collapsed

One would think that maybe the `expanded` and `collapsed` options could work, however this does not seem to be the case with my sample code below:

```
function mymodule_form_node_<type>_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_address']['#states'] = [
    // Expand address field container when the Trigger field is 'Open'.
    'expanded' => [
      ':input[name="field_trigger"]' => [
        'value' => 'open'
      ],
    ],
  ];
}

```

Replacing 'expanded' state with 'open' in the above does not work, nor does the inverse logic using 'collapsed' state work:

```
function mymodule_form_node_<type>_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_address']['#states'] = [
    // Collapse address field container when the Trigger field is 'Closed'.
    'collapsed' => [
      ':input[name="field_trigger"]' => [
        'value' => 'closed'
      ],
    ],
  ];
}

```

# Answer
> 2 votes
Unfortunately, I'm going to answer my own question: **`expanded` and `collapsed` states *do work* for the `<details>` type**.

My problem was operator error. I was adding the `#states` array at the level of the `'#type' => 'container'` but the container has a widget inside of it that holds the `'#type' => 'details'`. Fun times with Form API!

The working code is this:

```
<?php
// In mymodule.module
use \Drupal\Core\Form\FormStateInterface;

function mymodule_form_node_<type>_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_address']['widget'][0]['#states'] = [
    // Expand location field when the Type is 'On-site'.
    'expanded' => [
      ':input[name="field_trigger"]' => [
        'value' => 'open'
      ],
    ],
    // Collapse location field when the Type is 'Online'.
    'collapsed' => [
      ':input[name="field_trigger"]' => [
        'value' => 'closed'
      ],
    ],
  ];

  // Load edit form with Location field either open or closed, based
  // on the value of the Trigger field.
  $form['field_address']['widget'][0]['#open'] = ($form['field_trigger']['widget']['#default_value'] == 'open') ? 1 : 0;
}

```

# Answer
> 1 votes
Rather than using **expanded/collapsed** use **open/close** like below:

```
function mymodule_form_node_<type>_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_address']['#states'] = [
    // Expand address field container when the Trigger field is 'Open'.
    'open' => [
      ':input[name="field_trigger"]' => [
        'value' => 'open'
      ],
    ],
    'close' => [
      ':input[name="field_trigger"]' => [
        'value' => 'closed'
      ],
    ],
  ];
}

```

---
Tags: 8, javascript, forms
---


title: Adding a css file to a custom theme

text:
# Question
Title: Adding a css file to a custom theme
I'm a very beginner in drupal and I just want to add a css file to my custom theme.

So I created a `upjv.libraries.yml` in `themes/upjv` and I added :

```
global-styling:
version: '8.4.4'
css:
   theme:
       css/styles-upjv.css: {}

```

And I have created a `styles-upjv.css` in `themes/upjv/css`. On my index page, my file isn't loaded and I don't know if it's because I created the file in a wrong place, if the content of my libraries.yml is correct. Can anyone help me on this little problem please ?

# Answer
You have to add the following in your `upjv.info.yml`:

```
libraries:
  - upjv/global-styling

```

Make sure to clear cache after that by navigating to `configuration > Development > Performance` then clicking on `Clear all caches` under `CLEAR CACHE`.
> 3 votes

---
Tags: theming
---


# Question
Title: Getting a blank screen after copying project in my server
I am fairly new to Drupal.

I just got an already existing Drupal project and want to install it.

I copied it to: /var/www/html/myprojects/mydrupalproject

Then I got this error in my error.log from apache2:

> \[Thu May 03 17:55:41.603774 2018\] \[php7:notice\] \[pid 11604\] \[client 127.0.0.1:41930\] PHP Notice: Constant DATE\_RFC7231 already defined in /var/www/html/myprojects/mydrupalproject/includes/bootstrap.inc on line 258, referer: http://127.0.0.1/myprojects/
>
> \[Thu May 03 17:55:41.604601 2018\] \[php7:error\] \[pid 11604\] \[client 127.0.0.1:41930\] PHP Fatal error: require\_once(): Failed opening required '/var/www/html/myprojects/mydrupalproject/profiles/clusters\_public/modules/contrib/apc/drupal\_apc\_cache.inc' (include\_path='.:/usr/share/php') in /var/www/html/myprojects/mydrupalproject/includes/bootstrap.inc on line 2632, referer: http://127.0.0.1/myprojects/

So I tried to use the original .htaccess info in case it was the problem but I still get exactly the same error in the log. Any help?

# Answer
> 1 votes
Few things to check 1- Check what PHP version on your server, you will need PHP 5 not PHP 7.

2- Make sure you update the $base\_url in you settings.php file, assuming you copied that from your local

---
Tags: 7
---


title: Discard unsaved changes to view in D8

text:
# Question
Title: Discard unsaved changes to view in D8
I made a bunch of changes to a D8 view and have not saved it yet. I decided I don't want to go through with these changes and I want to discard all unsaved changes. How do I do this?

# Answer
You simply need to click on the **Cancel** button nearby the **Save** button
> 2 votes

---
Tags: views
---


title: db_select orderRandom With range

text:
# Question
Title: db_select orderRandom With range
I'm trying to query a random node from the last 10 that were created.

So far I've used this but it doesn't produce the right results:

```
 $query = db_select('node', 'n');
 $query->fields('n', array('text','created_time'))
   ->orderBy('n.created', 'DESC')
   ->range(0, 10)
   ->orderRandom();
$result = $query->execute()->fetchAll();

```

How can I get the data I want?

# Answer
> 1 votes
The `node` table doesn't have a `text` or `created_time` column so I'm not sure what data you're trying to select. Regardless, here are a couple of examples that use a subquery to select the `title` and `created` columns for a single random node from a pool of the ten most recent:

1. Subquery in the `FROM`:

```
$subquery = db_select('node', 'n')
  ->fields('n', ['title', 'created'])
  ->orderBy('n.created', 'DESC')
  ->range(0, 10);

$query = db_select($subquery, 'n2')
  ->fields('n2', ['title', 'created'])
  ->orderByRandom()
  ->range(0, 1);

```

Which is roughly equivalent to:

```
SELECT n2.title, n2.created
FROM (
  SELECT n.title, n.created
  FROM node n
  ORDER BY n.created DESC
  LIMIT 10
) AS n2
ORDER BY RAND()
LIMIT 1

```
2. Subquery in the `WHERE`:

```
$subquery = db_select('node', 'n2')
  ->fields('n2', ['nid'])
  ->orderBy('n2.created', 'DESC')
  ->range(0, 10);

$query = db_select('node', 'n')
  ->fields('n', ['title', 'created'])
  ->condition('n.nid', $subquery, 'IN')
  ->orderByRandom()
  ->range(0, 1);

```

Which is roughly equivalent to:

```
SELECT n.title, n.created
FROM node n
WHERE n.nid IN (
  SELECT n2.nid
  FROM node n2
  ORDER BY n2.created DESC
  LIMIT 10
)
ORDER BY RAND()
LIMIT 1

```

And the code:

You could also try a `JOIN` approach, it's worth trying a few methods to see which has the best performance.

---
Tags: nodes
---


# Question
Title: drupalLogin in functional JavaScript tests passes locally but fails on Drupal.org?
During functional JavaScript testing one can create and login a user by using the following code:

```
$this->testUser = $this->drupalCreateUser(['permission']);
$this->drupalLogin($this->testUser);

```

This works fine when testing locally with PhantomJS. However after uploading this code to drupal.org it keeps failing randomly (sometimes 1 test, sometimes 2) with the following error:

> User dOGIV5Iu successfully logged in.
>
> Failed asserting that false is true.

This appears to be coming from the assertion in BrowserTestBase::drupalLogin, which should normally check that the user is logged in correctly.

```
$this->drupalGet('user/login');
$this->submitForm([
  'name' => $account->getUsername(),
  'pass' => $account->passRaw,
], t('Log in'));

// @see BrowserTestBase::drupalUserIsLoggedIn()
$account->sessionId = $this->getSession()->getCookie($this->getSessionName());
$this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));

```

How come that a test function does work locally, but not on Drupal.org? Even stranger is that this function is used throughout multiple core tests without issues. And why is this assertion failing randomly?

# Answer
After reading through the Jenkins results for the nth time, it finally occurred to me that during Drupal core (and other contrib) tests all JavaScript tests always run separately from the other tests. All my tests however were in the same list.

This happened because all test classes started originally as functional tests, but as I went ahead some of them were changed into functional javascript tests. Class extending was changed into `JavascriptTestBase` and the tests were working perfectly fine. At least, when running individually. Running multiple tests at the same time made them somehow interfere with one another.

The problem was that I had never changed the namespace from `Functional` into `FunctionalJavascript`. The Drupal testrunner makes sure that all FunctionalJavascript tests are ran one by one, but performs other tests in parallel.

After changing the namespace, the tests were listed separate from the rest, ran after each other and finally showed up green on Drupal.org
> 1 votes

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


# Question
Title: views_get_view() not accepting arguments?
Code without arguments works, but with arguments I run into an error of `EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at commerce_line_item()->commerce_product: . in EntityDrupalWrapper->set()`

This does not work:

```
    $array = array('228');
    $view = views_get_view('commerce_wishlist_page');
    $view->set_display("default");
    $view->pre_execute($array);
    $view->execute();
    print $view->render();

```

This works:

```
    $view = views_get_view('commerce_wishlist_page');
    $view->set_display("default");
    $view->execute();
    print $view->render();

```

Did they changed something? Because according to documentation this should work. I can confirm view work in views UI, also with handwritten contexual filters in UI. How can I solve this?

# Answer
> 0 votes
View "commerce\_wishlist\_page" was created by module itself. There appeared to be some problem with the view configuration itself, because when I re-created the view with exactly same values the error is gone. I think this is the module problem and possible typo somewhere in hook\_install()

---
Tags: views
---


# Question
Title: How to limit the maximum length of the title of a node?
I have a content type with a title that shouldn't be more then 10 characters long. This title field is read only.

What is the recommended way to limit the length of that title to 10 long?

# Answer
Try Maxlength module to do this.

> Maxlength allows you to set maximum length of any field on any form making use of the form API. This includes fields created using the UI. (Example: any text field on a node) In D6 Maxlength allows you to set maximum lengths to the body, title and CCK textfields of any content type (node).
>
> When the maximum length is enforced for a field, while editing content of that type some Java Script will countdown how many characters are left, also if the Javascript is turned off, it falls back to form API validation.

Automatic Nodetitles : I haven't try this. Try once, hope this module solve your issue.

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.
> 2 votes

# Answer
As per my comment to Nishan's answer :

if it it not possible to edit the node title length with Maxlength module, you can turn your content type nodes titles into *regular UI* fields first with the Title project.

Then Maxlength module should do the same job as on any other field.
> 1 votes

# Answer
There is now a module available that provide min/max character and word length options. It's called Node Title Validation and allows you to customize the title attributes for each Content Type independently.
> 1 votes

# Answer
I found a solution with a sub module called **Property Validation** in the field validation module, after reading this comment.
And I added a jquery line to resize the node title.

```
    $('.page-node-add-conteneur #edit-title').attr('size',10);

```
> 0 votes

---
Tags: entities
---


title: Panels content wrapper

text:
# Question
Title: Panels content wrapper
I realised that this was a horribly verbose question, so decided to edit it and try again!

I am trying to find a way of wrapping a set of three (or more) Panels content areas with a div - is that possible?

# Answer
> 1 votes
Try Panels Extra Styles module. You can wrap panes or panes in HTML

# Answer
> 6 votes
You can definitely use the Panels Extra Styles module to wrap multiple panes in as many tags as you need.

On the first pane of your new group click the option cog and, under the Style section (which should read No style), choose 'Change'. Change the selected style to Wrapper:Raw and enter your opening tags in the text area 'Content prefix'. Leave the suffix area blank (as you don't want to close any tags yet)

Save the changes and then do the same with the last pane you want to group. This time close all the tags opened in the first pane by entering them in the 'Content suffix' text area.

Save and update your panel page and et voila! Your panes are grouped with your own HTML!

# Answer
> 0 votes
There is a way without additional modules using custom Panels content.

* Add a custom content pane where you want to start the wrapper, add the opening tag as body, make sure to not use WYSIWYG Editors which may add additional markup and don't add a title.
* Set style to: *No markup at all*
* Add another custom content pane analogous to the first one where you want to end the wrapper with the closing tag.

Thath's it, after saving the panel content you will see the grouping produced by the wrapper, as shown in the attached screenshot.

---
Tags: views, panels, theming
---


# Question
Title: Setting entity reference field value in Drupal 8 programatically
I have this following code that creates a node in the page.

```
$data = array(
  'type' => 'post',
  'field_post' => [
      'value' => 'test',
      'format' => 'basic_html',
    ],
  'field_visibility' => 1,
  'user_id' => $uid
);
$node = Drupal::entityManager()
  ->getStorage('post')
  ->create($data);
$node->save();

```

I have another field `field_pattern` that is an entity reference for another content type. How can I properly set it inside my code?

Since with creating the content from the site when dealing with Entity reference field selects autocomplete to Title, then I tried to test this but fails. Meaning no value is set to entity reference.

```
$title = $entity->label();
$data = array(
  'type' => 'post',
  'field_post' => [
      'value' => 'test',
      'format' => 'basic_html',
    ],
  'field_pattern' => $title, // this is the entity reference field
  'field_visibility' => 1,
  'user_id' => $uid
);
$node = Drupal::entityManager()
  ->getStorage('post')
  ->create($data);
$node->save();

```

# Answer
If you are creating a node with reference field, see below code:

```
 use \Drupal\node\Entity\Node;
 $node = Node::create([
   'type' => 'post',
   'field_post' => [
     'value' => 'test',
     'format' => 'basic_html',
   ],
   'field_pattern' => [
      'target_id' => $ID_REFERENCE_ENTITY, // Here just provide referenced entity id.
   ],
   'field_visibility' => 1,
   'user_id' => $uid
 ]);
 $node->save();

```

If you are are not creating node then just replace your field\_pattern like below:

```
'field_pattern' => [
   'target_id' => $ID_REFERENCE_ENTITY, // Here just provide referenced entity id.
],

```
> 5 votes

---
Tags: 8, entities
---


# Question
Title: How to test an exception have been logged instead of thrown?
I have the following code that throws catch an exption:

```
  public function deliverPrintable(array $entities, PrintEngineInterface $print_engine, $force_download = FALSE, $use_default_css = TRUE) {
    try {
      $renderer = $this->prepareRenderer($entities, $print_engine, $use_default_css);
    } catch (\InvalidArgumentException $e) {
      watchdog_exception('entity_print', $e);
      return FALSE;
    }
  }

```

The test below will fail because it's expecting an exception to be thrown:

```
  /**
   * Test that you must pass at least 1 entity.
   *
   * @covers ::deliverPrintable
   * @expectedException \InvalidArgumentException
   * @expectedExceptionMessage You must pass at least 1 entity
   */
  public function testNoEntities() {
    $print_engine = $this->container->get('plugin.manager.entity_print.print_engine')->createInstance('testprintengine');
    $this->container->get('entity_print.print_builder')->deliverPrintable([], $print_engine, TRUE);
  }

```

I took out the exception part of the method and left and just tested the returned value. But I would like to test that an exception have been logged is this possible?

```
  /**
   * Test that you must pass at least 1 entity.
   *
   * @covers ::deliverPrintable
   */
  public function testNoEntities() {
    $print_engine = $this->container->get('plugin.manager.entity_print.print_engine')->createInstance('testprintengine');
    $return = $this->container->get('entity_print.print_builder')->deliverPrintable([], $print_engine, TRUE);
    $this->assertFalse($return);
    // @TODO test that an exception have been logged?
  }

```

# Answer
> 2 votes
There is no standard test feature to assert a logged message.

The simplest approach is to just install dblog in your test and then inspect the watchdog table for the expected record.

Alternatively, You could write your own log backend that stores it in memory and then access it from there if you don't want to install the necessary database tables in the test.

Or, don't use watchdog\_exception() but an injected logger service that you can mock and then configure that to expect the call.

---
Tags: 8, testing
---


# Question
Title: convert node/id to node/path-alias in content body
I added a link to a content body from ck editor as `/node/7`. When viewing this page I want to show `www.sitename.com/example/alias`.

This is working fine in drupal 7 (earlier version of my site), but not sure which module does this work.

I have installed `pathauto`, `redirect`, `pathologic` modules. I also configured the text format at `admin/config/content/formats` and set pathologic filter as first priority. But no luck.

After installed redirect module, if I hit `node/7` in browser it automatically redirect to expected alias. But I want is the content page should show only `url alias` even If entered `/node/7` in ckeditor.

Am I missing any configurations in any of the above module? or am I missing any module?

# Answer
> 3 votes
I found a hook in `Pathologic` module as `hook_pathologic_alter` and I used it to convert node path to URL alias.

I used this hook as follows

```
/**
 * Implements hook_pathologic_alter().
 */
function mymodule_pathologic_alter(&$url_params, &$parts, &$cached_settings){
    if ($parts['path'] != '<front>') {

        //get the alias for the path and assign it in path
        $alias = \Drupal::service('path.alias_manager')->getAliasByPath('/'.$url_params['path']);

        //Url::fromUri which Pathologic uses need a path without slash at first, so trim it
        $url_params['path'] = ltrim($alias, '/');
    }
}

```

This converts a node path to alias and pass it, so Pathologic will form a URL with alias.

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


# Question
Title: How do I call function inside .module file from linux system crontab?
my module add queue item from hook\_cron(). Now i want to execute one by one queue item with custom function \[mymodule\_indexing\_queue()\] inside mymodule.module file.

Like:

```
in mymodule.module
---------------------------------------------------------------
function mymodule_indexing_queue() {
  $mymodule_queued = DrupalQueue::get('my_indexing_walker');
  $numberOfIndexQueueItems = $mymodule_queued->numberOfItems();

  if ($numberOfIndexQueueItems > 0) {
    $action = $mymodule_queued->claimItem();
    if ($action) {
      process_queue_start_walking($action->data);
      $mymodule_queued->deleteItem($action);
    }
  }
}

```

Now i want to call mymodule\_indexing\_queue() function from crontab -e without hook\_cron().

How can i do that?

# Answer
> 0 votes
Use `drush eval`. You can call your function like: `drush eval "mymodule_indexing_queue();"`

There are probably better ways to do what you're trying to do though. You can write your own drush commands, use drupal's built in batch processor, or even just use the same hook\_cron function with some conditions for time checking to run the queueing/executing work separately.

See:

# Answer
> 0 votes
You could create a menu item for your function using hook\_menu in your .module file. Then you can add that menu path to your crontab using wget or however you want to do it

---
Tags: 7
---


title: Secure Drupal User Profile Information

text:
# Question
Title: Secure Drupal User Profile Information
I need to secure the user profile information, which contains predefined & custom fields such as username, profile picture & phone number.

I do need to encrypt & store it in DB. And then decrypt to display output.

Do anyone know, does encryption for fields is possible?

# Answer
Yes it's possible only if you do it programatically for this. You can use hook\_entity\_presave() and update encrypted values while saving user. And while retrieving data/fields you can decrypt with the key that you used for encryption and show in profile view page. Example:

```
/**
 *
 * @param array $edit
 * @param type $account
 * @param type $category
 */
function example_user_presave(&$edit, $account, $category) {
  $name = $edit['name']; // Get value of field.
  $edit['name'] = encrypt($name); // Encrypt and save.
}

/**
 * Returns encrypted string
 */
function encrypt($pure_string) {
  $encryption_key = 'SECRET';
  $encrypted_string = openssl_encrypt($pure_string, "AES-128-ECB", $encryption_key);
  return $encrypted_string;
}

/**
 * Returns decrypted original string
 */
function decrypt($encrypted_string) {
  $encryption_key = 'SECRET';
  $decrypted_string = openssl_decrypt($encrypted_string, "AES-128-ECB", $encryption_key);
  return $decrypted_string;
}

```
> 2 votes

# Answer
Have a look at this https://www.drupal.org/project/field\_encrypt

> This module adds options to encrypt field values.
>
> The goal of this module is to create a method for encrypting field values when stored in the database.
>
> This module depends on the Encrypt module (http://drupal.org/project/encrypt) for encrypting and decrypting strings.
>
> Install this module like any other module. Field encryption settings are made on the field edit page.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Setting Simple Sitemap Values Programmatically not reflected in form
I'm trying to set some Simple Sitemap settings programmatically. I'm using the following to set whether or not a specific node is indexed:

`\Drupal::service('simple_sitemap.generator')->setEntityInstanceSettings('node', $node->get('nid')->value, ['index' => FALSE]);`

This works fine and I was able to see the results reflected in my sitemap. However, this is only reflected in the "Simple Sitemap" form of that node if the value is set to `TRUE`. If `FALSE` neither radio button is selected.

This is confusing to others who are editing the site. How can I get this reflected in the form?

# Answer
I figured this out, but in case anyone else runs into this. The documentation in the readme.md file shows the following format the settings:

`setBundleSettings('node', 'page', ['index' => TRUE, 'priority' = 0.5])`

Instead of using `TRUE/FALSE` I changed the index setting to `0/1` and this was successfully reflected in the form as expected.

`\Drupal::service('simple_sitemap.generator')->setEntityInstanceSettings('node', $node->get('nid')->value, ['index' => 0]);`
> 2 votes

# Answer
I have created an issue for you on drupal.org and fixed it. Please use the boolean values when using the API instead of the integers.

The fix along with many other improvements can be found in branch 3.x.
> 0 votes

---
Tags: 8, xml-sitemap
---


# Question
Title: Why does RELAXed Web Services Not appear in the module list?
I have created a new Drupal 8 site with docker. I created it with composer and installed the `drupal/deploy` and `relaxedws/replicator` modules. The `drupal/deploy` module and all of its dependencies seem to be installed correctly, they show up in the `Extend` area of Drupal, and they seem to work properly. The `relaxedws/replicator` does not show up as expected. I expect to see it in the Web Services section of the Extend page in Drupal.

The `relaxedws/replicator` module shows up on the file system in the `vendor` folder in the Drupal root.

It seems like I'm missing something.

Dockerfile:

```
    FROM drupal:latest

    RUN apt-get update && apt-get install -y \
        curl \
        git \
        mysql-client \
        vim \
        wget

    RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \
        php composer-setup.php && \
        mv composer.phar /usr/local/bin/composer && \
        php -r "unlink('composer-setup.php');"

    RUN wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.4.2/drush.phar && \
        chmod +x drush.phar && \
        mv drush.phar /usr/local/bin/drush

    RUN rm -rf /var/www/html/*

    COPY apache-drupal.conf /etc/apache2/sites-enabled/000-default.conf

    WORKDIR /app

    RUN composer create-project drupal-composer/drupal-project:8.x-dev /app --stability dev --no-interaction

    RUN mkdir -p /app/config/sync

    RUN chown -R www-data:www-data /app/web

    RUN composer require relaxedws/replicator:dev-master

    RUN composer require drupal/deploy

```

Resulting `composer.json`

```
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6",
        "drupal-composer/drupal-scaffold": "^2.2",
        "drupal/console": "^1.0.2",
        "drupal/core": "~8.5.3",
        "drupal/deploy": "^1.0@beta",
        "drush/drush": "^9.0.0",
        "relaxedws/replicator": "dev-master",
        "vlucas/phpdotenv": "^2.4",
        "webflo/drupal-finder": "^1.0.0",
        "webmozart/path-util": "^2.3"
    },
    "require-dev": {
        "webflo/drupal-core-require-dev": "~8.5.3"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": ["load.environment.php"]
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold",
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"]
        }
    }
}
```

\** EDIT 1 I attempted the fix mentioned by @sonfd (and say thanks for the answer). I changed my `extra.installer-paths` to the following but the path for the installed package didn't change.

```
    "extra": {
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "web/modules/{$name}": ["relaxedws/replicator"]
        }
    }

```

# Answer
> 1 votes
Composer installs things based on the informations in `extras.installer-paths` in your composer.json, or to the vendor directory by default. You can place the package anywhere you want by following the steps at How do I install a package to a custom path for my framework?. Basically you need to update your `extra.installer-paths` area to look something like:

```
"extra": {
    "installer-paths": {
        "web/core": ["type:drupal-core"],
        "web/libraries/{$name}": ["type:drupal-library"],
        "web/modules/contrib/{$name}": ["type:drupal-module"],
        "web/profiles/contrib/{$name}": ["type:drupal-profile"],
        "web/themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"],
        "path/to/desirable/package/location": ["relaxedws/replicator"]
    }
}

```

Note the additional line for `relaxedws/replicator` at the bottom.

**Note:** I would `composer remove relaxedws/replicator` before updating the installer paths and then reinstall with `composer require relaxedws/replicator`. I don't think composer will move the package to the new location otherwise, but maybe it would with some form of a `composer update` command.

# Answer
> 0 votes
I found the answer to my problem. It didn't have to do with package placement, but package selection. I was not adding the correct package. As I stumbled and grumbled, the packagist website did not show the package I was looking for. `https://packagist.org/packages/?q=drupal%2Frelax&p=0`

What helped me find it was getting a few packages incorrect when adding them with `composer require <some_non_existent_package_name>`. When you do this composer will offer suggestions as to what you might be looking for. I then used this to search for packages.

In the end, the package I was actually looking for was called `drupal/relaxed`. The package I mentioned above in the question `relaxedws/replicator` is a prerequisite and not the actual Drupal package.

`composer require drupal/relaxed`

Back story: This was all in an effort to get Drupal 8 Deploy working. The documentation never points to installing this package. Hopefully this helps.

https://www.drupal.org/docs/8/modules/deploy/drupal-to-drupal-deployment-between-two-or-more-sites

---
Tags: 8, composer
---


title: How to generate a link as 'href="#"'?

text:
# Question
Title: How to generate a link as 'href="#"'?
In my theme, I have to output a toggle link like this:

```
<a class="hl__link-tag hl__link-tag--with-arrow js-show-more-text-link" href="#" title="Click to show more / less text" aria-expanded="false" aria-controls="showMoreText{{ paragraph.id() }}"><span class="hl__link-tag__toggle-text">Show Less</span><span>Show More</span></a>

```

Its not a real field or anything like that. Is there a way I can use `link` or `path` functions to generate this output instead? I am guessing since the title has two spans in it that I cannot, but lets assume there were no spans, I'd like to know if this is possible.

I tried:

```
{{ link('Show More', 'internal:#') }}

```

and

```
{{ link('Show More', '#') }}

```

The first one creates an empty href, which does not work. The second throws a fatal error.

# Answer
You could just type it into the template and dont have to do anything clever or twig based? e.g.

```
<a href="#">Show more</a>

```

The core html.html.twig quite happily does this for the #main-content link:

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21html.html.twig/8.2.x
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Read data using countries module in view
I am using the countries module to add **countries** in my content type **project**.

I create a view with **type = Default node index** to display my content.

I added the **Indexed Nœud: Countries (Countries)**

But the data saved in my field\_countries is not displaying yet it is displayed well in the details page (node project).

Any idea to display the countries data in my view?

Thank you

# Answer
While adding relationship with countries, **the most important**, Check the checkbox **Require this relationship** and then add **Countries: Name** as fields you want.

It works for me (see) and hope for you too
> 0 votes

---
Tags: 7, views
---


# Question
Title: CKEditor filtered HTML body field is not showing for non-administrator users when editing
I am on drupal 7.56.

Something really disturbing happens.

I have created a **custom content type** named "**Information**" that uses the **default body field**. I granted access to this content to **Administrator** and to a newly created role that is "**editor**".

I made wrights configuration for both roles :

* "Editor" and "Administrator" can "**Edit own, Edit any**" information ;
* "Editor" and "Administrator" can "**Edit own, Edit any**" field body for that Information content type.

But only "Administrator" sees the body field in **editing mode**.

I am also using field\_permission and content\_access modules to make sure everything is fine in detail.

**Still the same**. On any browser, "Administrator" can see the body in edit mode but not the editor. Notice that body field text shows normally when displaying the node(s).

A **help** will be welcome!

# Answer
The commonest reason for this problem (and OP has confirmed it in this case) is as follows.

1. The field that is inaccessible to some users has a filtered text format
2. The formats that can be set on that field include one or more that are not permitted to all users (typically "full html")
3. The content item in question has been edited by a user that *has* access to the restricted format and they have saved it with the field set to that format.
4. Now only users that have that privilege can edit the item because that field won't load for those who don't.

The solution is for a privileged user to edit the item and change the format and save it again, though that *may* result in the HTML changing in a way that's undesirable. If the item needs "special" HTML then it may not be possible for it to be maintained by the less privileged users.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Where do I find the "Security code" to test "Commerce PayPal WPP Credit Card" with my "sandbox buyer account"
I am on Drupal 7.59 and using Commerce and Commerce PayPal modules.

I am at testing step, using my PayPal sandbox accounts (buyer and facilitator) to check if my PayPal classic and **PayPal Credit Card** payment methods work fine.

1. On PayPal classic I used WPS, and it works well
2. On PayPal Credit Card, I am using WPP, but **something is missing somewhere**.

**About my PayPal WPP Credit Card (2)**

All configuration is good, all the API credential that I have is correct. But one is missing : the **Security code**. In all tutorial I've watched, nobody talks about that field "Security Code". But it is a **required field**!. Whithout it I can not continue payment process which PayPal CB.

Can't anybody help ?

# Answer
Just put in any number that matches the card type - e.g. 111 or Visa / Mastercard / Discover or 1111 for American Express. As far as I know, the PayPal API will accept any value. It should just be the card number and expiration date that have to match your sandbox test card details.
> 0 votes

---
Tags: commerce, payment-gateways
---


title: Drupal.behaviors.customCKEditorConfig

text:
# Question
Title: Drupal.behaviors.customCKEditorConfig
I am trying to use the Disallowed Content configuration from Ckeditor. https://docs.ckeditor.com/ckeditor4/latest/guide/dev\_disallowed\_content.html I am using Drupal 8.5.3 Lightning 8.x-3 and the built in Ckeditor v4.8

I have placed this js in my theme and the js is loading when I am in page edit mode.

```
(function ($, Drupal) {
  Drupal.behaviors.customCKEditorConfig = {
    attach: function (context, settings) {
      if (typeof CKEDITOR !== "undefined") {
        config.disallowedContent= 'div span';
      }
    }
  }
})(jQuery, Drupal);

```

But this is not working. I have tried with the Allowed HTML tags enabled and disabled. I got this information from these sources. http://drucafe.blogspot.com/2016/02/adding-custom-styles-to-ckeditor-in.html and https://tutel.me/c/drupal/questions/183036/allow+empty+tags and Drupal 8 CKeditor behaves LTR in an RTL site.

I have tried the filter 3 different ways

```
editor.filter.disallow( 'span div' );
config.disallowedContent( 'span div' );
config.disallowedContent= 'div span';

```

# Answer
> 1 votes
This is working.

```
use Drupal\editor\Entity\Editor;

function MYMODULE_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats'][$name]['editorSettings']['disallowedContent'] =
'h1 h2 h3';
  }
}

```

This supersedes any allowed tags in the drupal GUI. But you must enable Allowed HTML tags enabled for this to work. I took the idea from this.drupal-8-ckeditor-behaves-ltr

---
Tags: 8, wysiwyg
---


# Question
Title: how to attach existing images(image field) to node in drupal 7?
I use the following code to upload images

```
$node  = node_load($nid);
$file  = (object) array(
  'uid' => $v['uid'],//@todo from query
  'uri' => 'public://'.$v['filename'],//@todo from query
  'filemime' => $v['filemime'],//@todo from query
  'status'   => $v['status'],//@todo from query
  'fid' => $v['fid'],
  'filesize' => $v['filesize'],
  'timestamp' => $v['timestamp'],
  'type' =>'image',
  'metadata' => array('height' =>1200,'width'=>1099),
  'height' => 1200,
  'width'  => 1099,
);
$node->field_image[LANGUAGE_NONE][0] = (array) $file;
node_save($node);

```

This does not work, I am not able to figure out the error in the code which prevents from image upload

# Answer
> can u provide me an example of how to upload image programmatically provided I have an image url on the public path in D7

This should do the trick

```
$node  = node_load($nid);
$image = file_get_contents('public://images/folder_name/image_name.jpg');
$file  = file_save_data($image, 'public://images/folder_name/image_name.jpg', FILE_EXISTS_REPLACE);
$node->field_image[LANGUAGE_NONE][0]['fid'] = $file->fid;
node_save($node);

```
> 1 votes

---
Tags: 7, nodes, entities, media
---


# Question
Title: Webform - Show/Hide fields based on day of the week selected from Datepicker
I have a little issue with a webform. I am setting a booking system and some items are only available on some days of the week. I have modified the date field to be a textbox with popup calendar I need to show/ hide some field based on the Day of The Week selected ( if Day is Tuesday or Day is Friday then Show the fields, otherwise, hid them) Any help is welcome, because with the conditionals, i can only do it based on date not on the day itself.

thank you

# Answer
The easiest solution is probably with jQuery. To get the datepicker field value, and convert it to a weekday, you can follow these steps.

* Add this function to the JavaScript file

```
// Accepts a Date object or date string that is recognized by Date.parse()
function getDayOfWeek(date) {
  var dayOfWeek = new Date(date).getDay();
  return isNaN(dayOfWeek) ? null : [0, 1, 2, 3, 4, 5, 6][dayOfWeek];
}

```
* Use this code to get the value from the datepicker field

```
var datepicker = $('#your_datepicker_id').datepicker("getDate");
var today = new Date();
if (!today.getDay() == getDayOfWeek(datepicker)) {
  $('.field-names-to-hide').hide();
}

```
> 0 votes

---
Tags: webforms
---


# Question
Title: How to set different cache mobile and desktop based on header HTTP for one URL?
Here is the problem we're facing :

I have one url : `www.example.com/my-page` with a different HTML footer for mobile and desktop.

To know which HTML to use we look for HTTP Headers sent by one CDN (Akamaï) =\> `$_SERVER['HTTP_X_AKAMAI_DEVICE_CHARACTERISTICS']`.

What we want to achieve is to have cache for both mobile and desktop based on that HTTP Header since the URL is the same. Is it possible ? And if yes, how to do it ?

Having both HTML in the DOM is not an option here, for performance reasons.

We played with `contexts` in the `#cache` array but no success here. Maybe with using `tags`, but not sure about how to use it.

Any help would be greatly appreciated.

# Answer
You have to add a cache context to the page:

```
/**
 * Implements hook_preprocess_HOOK() for the page template.
 */
function mymodule_preprocess_page(&$variables) {
  if ( ... ) {  // check if this is the page
    $variables['#cache']['contexts'][] = 'headers:X-Something';
  }
}

```

This adds probably too many variations, so you might need a custom cache context to only vary by two conditions, mobile or desktop. Extend `RequestStackCacheContextBase`, so that the request stack is already injected and return either 'dc.mobile' or 'dc.desktop':

```
  public function getContext() {
    $request = $this->requestStack->getCurrentRequest();
    $header = $request->headers->get('HTTP_X_AKAMAI_DEVICE_CHARACTERISTICS');
    if (...) {   // check $header for mobile
      return 'dc.mobile';
    }
    else {
      return 'dc.desktop';
    }
  }

```

This is a tagged service (tag name: `cache.context`). See the documentation for more information https://www.drupal.org/docs/8/api/cache-api/cache-contexts, especially the warning about the Internal Page Cache in the last chapter concerning anonymous traffic. In most cases it should be a better option anyway to handle this edge side or even better client side in js, not server side.
> 1 votes

---
Tags: 8, caching
---