# Question
Title: How do I display an error message on a basic page when the user does not have permissions to see the nested view inside the basic page?
I have a basic page, and inside of that basic page I have a view "newsletters". The view "newsletters" has permissions set on it based on role, so only admin and subscribers can see it. How can I display "You must be a subscriber to view this content" on the basic page when the user does not have permissions to view "newsletters".

Currently, if the user cant see "newsletters" my basic page just shows an empty page. I want it to display "You bust be a subscriber to see this content".

I tried creating another view "redirected page" that is only visible to anonymous users but it is not showing up for some reason.

The reason I made a basic page with a view nested inside it is because I wanted users who don't have permission to view the page to still see the link in the menu bar.

# Answer
You can create a basic Block with your text message and set up Visibility to *only* Anonymous users, and to show on your basic page.

This way anonymous will see the Block, authenticated will see the Views block.
> 0 votes

# Answer
Not a very elegant solution but a quick solution for your situation. You could add a basic block just below your view block with your "You must be a subscriber to view this content" text

Then in css do:

```
.myviewblock + .mynewbasicblock {
  display: none;
}

```

So that means if your view block is coming out on the page (Which only would if they have permission) then hide your basic block.

But this relies on you keeping those blocks next to each other. And also means the "You must be a subscriber to view this content" content is always on the page but just hidden.

Your alternative could be to instead use a node access module that restricts access to the nodes rather than the view so that the view wouldnt have permissions but the nodes would
> -1 votes

---
Tags: views, 8, users, redirection
---


title: Handling access denied result

text:
# Question
Title: Handling access denied result
In Drupal 8, what is the correct way of returning access denied to a user (outside of access requirement on a controller)?

I'd say it is to throw an `AccessDeniedHttpException` most of the time, but I have seen modules set an event response to `403`, or do a redirect response to `system.403`.

# Answer
> 3 votes
Generally, the correct way is to `throw new AccessDeniedHttpException()` over setting a 403 or a redirect response, which bypasses the exception handling, so that it's no longer possible to configure a different handling of 403's in contrib or custom code. Unless you want to bypass this intentionally, for example if you want to produce a faster 403.

However, in most cases it is preferable to control the access as route requirement. The main effect is the same, the routing system throws an exception as well. But it does other things, like controlling the visibility of menu links, which you don't get when you throw the exception in custom code.

---
Tags: 8, http-request, event-subscribers
---


title: How to upload a file in Drupal 8?

text:
# Question
Title: How to upload a file in Drupal 8?
I'm a brand new Drupal user and I just installed and started configuring a Drupal 8 instance. I've had no problem tweaking the theme, and creating text content, but I can't seem to find the button to upload a file. I doesn't exist on *admin/content/files* where I would expect it, and Googling quickly points me to modules I could include.

I was hoping to upload a few images to use on some of my "basic page" content entries.

Is there not a simple "file upload" button in this CMS?

# Answer
> 3 votes
"Content entity" types like nodes (content) are field-able, so you can choose what data are attached to them.

The "basic page" content type only comes with a body field out of the box, but it's a cinch to add new ones:

1. Visit /admin/structure/types
2. Click "Manage fields" for the "basic page" type
3. You'll see a list of the fields currently attached to the content type. Click "Add field"
4. Select a field type; "Image" would probably make most sense for your needs
5. Follow the rest of the wizard and choose suitable values (should all make sense)

When you visit the node add/edit page for a "basic page", you'll see the new field, and you'll be able to upload your images.

Next you'll probably want to visit the "Manage display" tab to choose how the images are rendered, and the "Manage form display" tab to choose which widget is used.

# Answer
> 2 votes
I suggest you install and enable Admin Toolbar if you haven't already.

Out of the box for Articles, there are two options where you can add images (see screenshot)

Now, basic page does not come with the bottom option, but you can easily add it.

Go to basic page manage fields.

Click on Add Field. Now you can re-use an existing image field (as seen/used in Articles)

OR create a new image field

# Answer
> 2 votes
The question is not how to add a file to another content type... I think the issue is that there doesn't seem to be a way to upload a stand alone file as there is on Drupal 7

---
Tags: 8, files
---


# Question
Title: Webform entity select submission displaying different result than element
I have a webform in Drupal 8 with an entity select element. The element is populated from an entity reference view. I have a book content type with information about the book such as title and author. I also have a field collection in book containing more specific details such as ISBN and format. The entity reference view displays title-isbn-format. For example:

Dune - 9780441013593 - Paperback

Dune - 9780143111580 - Hardcover

I applied the view entity reference patch posted here. The form correctly displays the output of the view. How do I get the same display in the form submission? If I set the form display to value and select Dune paperback the result is "MyBookFieldCollection 0 of Dune (9)."

I tried using tokens but I can only get the field collection info, not the book info.

Here is the source for the element:

```
book_title:
  '#type': entity_select
  '#title': 'Book Title'
  '#select2': true
  '#format': custom
  '#format_html': '[webform_submission:values:book_title:node:title] - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#format_text': '[webform_submission:values:book_title:node:title] - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#target_type': field_collection_item
  '#selection_handler': views
  '#selection_settings':
    view:
      view_name: entity_reference_for_form
      display_name: entity_reference_1
      arguments: {  }

```

This correctly displays the ISBN and book format but not the book title.

# Answer
> 0 votes
I was able to get the desired result for the book title by using twig and string manipulation.

I noticed {{ item.label }} returns MyBookFieldCollection 0 of Dune. MyBookFieldCollection is the name of the field collection and 0 represents the selected item. There will not be more than five items in a given collection. I can remove the start of the string using {{ item.label\[27:\] }} and this returns a value of Dune.

Here is the modified element source:

```
book_title:
  '#type': entity_select
  '#title': 'Book Title'
  '#select2': true
  '#format': custom
  '#format_html': '{{ item.label[27:] }} - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#format_text': '{{ item.label[27:] }} - [webform_submission:values:book_title:entity:field_isbn_13] - [webform_submission:values:book_title:entity:field_format]'
  '#target_type': field_collection_item
  '#selection_handler': views
  '#selection_settings':
    view:
      view_name: entity_reference_for_form
      display_name: entity_reference_1
      arguments: {  }

```

This outputs Dune - 9780441013593 - Paperback in the form submission.

---
Tags: webforms
---


# Question
Title: How do I add an anchor attribute to a route?
I've created a route:

```
regions.taxonomy_term.edit_form_header:
  path: '/taxonomy/term/{taxonomy_term}/edit'
  defaults:
    _entity_form: 'taxonomy_term.default'
    _title: 'Edit term'
  options:
    _admin_route: TRUE
  requirements:
    _entity_access: 'taxonomy_term.update'
    taxonomy_term: \d+

```

But now I can't add to path anchor attribute.

For example:

```
path: '/taxonomy/term/{taxonomy_term}/edit#header'

```

# Answer
Thanks everyone!

I have solution my for problem. You just had to add it to this **my\_module.links.contextual.yml** file.

```
regions.taxonomy_term.edit_form_header:
  title: Edit this block
  group: region_taxonomy_term
  route_name: regions.taxonomy_term.edit_form_header
  weight: 10
  options:
    fragment: 'edit-group-header'

```
> 4 votes

# Answer
This is not possible because the anchor tag is never sent as part of the HTTP request by any browser, it is only interpreted locally within the browser.

> RFC 1808 Section 2.4.1 - "Note that the fragment identifier is not considered part of the URL."
> 1 votes

---
Tags: 8, routes
---


# Question
Title: Programmatically / by Rules, remove reference of a deleted user from contents created by that user.
A user \[content\_editor\] got deleted and the content created by this user is referring to anonymous user. While an administrator is editing that content, administrator is receiving user doesn't exist. The error goes off when we re-assign the content to administrator or an existing user. As the user has created paragraphs, nodes etc how do we track contents created and referred by the user as user id is already deleted?

How can we remove these references and save the content without error message.

I thought we can use Rules API to create a simple rule which will force save any entity if an admin is saving the content, then save the content. But the rules API is providing me only nodes and not entities which means paragraphs will still refer to old deleted user. How can I overcome this. Is there a programmatic solution to this problem?

# Answer
> 1 votes
supposing the content you want to reassign is of node type, here is how to do it programatically (in a hook\_update\_N() per example or /devel/php or drush ev...)

```
  $deleted_uid = 42;
  $reassigned_uid = 80;
  // Reassign nodes (current revisions).
  module_load_include('inc', 'node', 'node.admin');
  $nodes = \Drupal::entityQuery('node')
    ->condition('uid', $deleted_uid)
    ->execute();
  node_mass_update($nodes, ['uid' => $reassigned_uid], NULL, TRUE);
  // Reassign old revisions.
  db_update('node_field_revision')
    ->fields(['uid' => $reassigned_uid])
    ->condition('uid', $deleted_uid)
    ->execute();

```

hope this helps

---
Tags: users, rules
---


# Question
Title: Feeds importer imports only some of the nodes
In D7.59 I have to import .csv file and there are all the mappings prepared for that. The file has 500 records, that will become nodes of a content type "record". There are no nodes of this content type in Drupal before the import (all nodes are deleted). When I start the import after it finishes I get the result, that 334 nodes were created and 266 nodes were updated.

Log does not show any errors by the way.

I presume that there are some kind of feeds cache that has to be cleared, to make sure that it does not think that some of the nodes are still in the site. Can someone tell me what SQL tables I should truncate, or maybe there is another way to solving this?

# Answer
Feeds keep track of previously imported items in the feeds\_item table. This also includes items that were only updated by Feeds, but not originally created by Feeds.

Under normal circumstances, when you delete an entity imported/updated by Feeds, Feeds will delete the corresponding import meta data from the feeds\_item table. There can be occasions where this does not happen. These are:

* During the deletion of the entity, a PHP fatal error occurred which prevented Feeds from cleaning up the import metadata. Non-fatal errors should not cause this, as Drupal would then perform a rollback of the deletion.
* Feeds is disabled when deleting the entity.

Feeds doesn't clean up orphaned items from the feeds\_item table. To clean this up, you'll need to execute a query on that table. The `id` column represents the importer ID and `feed_nid` the feed node ID (the latter is only used when you have attached your importer to a content type and you need to create a node to import content).

Example query to delete all import metadata for the importer 'my\_importer':

`DELETE FROM feeds_item WHERE id = 'my_importer';`

There is an issue to let Feeds automatically clean up orphaned feed items: https://www.drupal.org/project/feeds/issues/1394320

For more information about the feeds\_item table, see https://www.drupal.org/node/1768352
> 2 votes

---
Tags: feeds
---


# Question
Title: access denied feed/[id]/import for a feed item
I am dealing with an older d8 site that has a feed item of a custom type with custom processor. When I go to admin/content/feed and click on an existing one and I go to feed/id/import I get access denied. If I add a new one I do not get the same error but I am trying to understand what defined support for the "import" operation for a feed?

# Answer
Feeds locks a feed when you start an import from it. As soon as the import finishes, the feed gets unlocked again.

When a feed is in a locked state, you cannot initiate another import. Therefore feed/id/import results into an access denied page.

There can be occasions in which an import failed to finish. This can for example be caused by bugs in Feeds or other modules. An other possible cause is that the database server restarted or stopped in the middle of an import. If you use periodic import on the feed, it may be that the import did not fail to finish, but just needs a few more cron runs.

To unlock a feed, go to the feed page and click on the "Unlock" button or go to feed/id/unlock. If you see no button or get access denied for that path as well, try to clear caches. Drupal caches access to menu paths (Feeds does clear the cache for the paths in question when a feed gets locked or unlocked).
> 3 votes

---
Tags: feeds
---


# Question
Title: How do I properly add a custom source for RSS feed import?
I am setting up the mappings for a Feed entity, but I cannot figure out how to properly set custom sources for fields.

In this case, I am grabbing records from an XML document ("RSS/Atom" option) and importing them into an *Article* content type.

I have a custom tag in the XML document, `<alert>`, with a value that maps to the Alert Flag Type (`field_alert_flag_type`) field on Article nodes. I set up a custom source called "Alert" (machine name `alert`), and when I attempt to import a feed with this new custom source specified, I get the following error(s):

```
The content [XYZ] failed to validate with the following errors:
    Alert Flag Type (field_alert_flag_type): This value should not be null.

Please check your mappings.

```

If the XML tag is `<alert>`, the source name is "Alert", and the source machine name is `alert`, what am I doing wrong?

# Answer
The RSS/Atom parsers only work with predefined sources. The custom sources in this case are only useful when using them in combination with Feeds Tamper (or alike).

If you want more control about selecting data from a XML file, try the XML parser from Feeds extensible parsers instead. With that parser, you can select data from a XML file using XPath queries. So you are free to select about anything from a XML file. It would be good idea to learn more about XPath before using the XML parser. I think that the XPath tutorial from W3Schools is a good resource for this.
> 2 votes

---
Tags: 8, feeds
---


# Question
Title: Primitive Error when saving a custom field with a text_format widget
I am trying to make a custom field with one normal textarea and 1 text\_format widget. The textarea functions perfect but if I try to use the text\_format widget I get an primitve error when I am trying to save.

This is the error message:

> This value should be of the correct primitive type

This is my formElement:

```
 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $element['date_text'] = [
  '#type' => 'text_format',
  '#title' => 'text',
  '#format' => 'full_html',
  '#default_value' => isset($items[$delta]->date_text) ? $items[$delta]->date_text : NULL,
  '#placeholder' => t('Data Text'),
  '#element_validate' => array(
      array($this, 'validate'),
    ),
];
  $element['date_table'] = [
  '#type' => 'textarea',
  '#default_value' => isset($items[$delta]->date_table) ? $items[$delta]->date_table : NULL,
  '#placeholder' => t('Data Table'),
];
return $element;

```

}

and this is my schema:

```
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
$schema = [
  'columns' => [
   'date_text' => [
      'type' => 'text',
      'size' => 'medium',
    ],
    'date_table' => [
      'type' => 'text',
      'size' => 'medium',
    ],
  ],
];

return $schema;

```

}

It seems, that text\_format returns an array instead of a single value and thus cant be saved in my text column. The array consists of the text and the format, i dont need the format, so I would need to replace the array with the text value.

How and where could I accomplish this?

Xdebug is not working on scripts that are executed when I click save, so I really have no clue what is really going on.

thanks

# Answer
Here is what solved the issue:

I used messageFormValues in my Widget.php to override the Array with the text value, so it could be stored in my database.

```
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
  foreach($values as $key => $value) {
    $values[$key][date_text] = $value[date_text][value];
  }
  return $values;
}

```

To unescape the html for my twig template(so it is displayed as html and not as text on the site) I used the `raw` attribute.

With this solution no Text-Format will be saved, but it was not necessary for my custom field anyway.
> 3 votes

# Answer
Thanks to Matt's solution I was able to save a text\_format element that's part of a custom field, but I also wanted to store the chosen format so I did this:

```
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    foreach($values as $index => $value) {
        $values[$index]['body'] = json_encode($value['body']);
    }
    return $values;
}

```

When re-populating the edit form, I can json\_decode as applicable to get the value and text format out of the string.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Configure connection to mongodb for querying only
We have an external mongodb instance and we need to query data from it and bring it to Drupal 8 site.

On shell this is how we connect (mongodb is running in a different container than drupal) `mongo --host docker_mongo --ssl --sslCAFile=/etc/ssl/mongodb-cert.crt`

Adding the following at settings.php does not work and status report shows "No database aliases found in settings. Did you actually configure your settings ?"

```
$configureMongoDb = function (array $settings): array {
  $settings['mongodb'] = [
    'clients' => [
      // Client alias => connection constructor parameters.
      'mymongo' => [
        'uri' => 'mongodb://docker_mongo:27017',
        'uriOptions' => ['ssl=true&sslCAFile=/etc/ssl/mongodb-cert.crt'],
        'driverOptions' => [],
      ],
    ],
    'databases' => [
      // Database alias => [ client_alias, database_name ].
      'tutorial2' => ['mymongo', 'tutorial2'],
    ],
  ];

  return $settings;
};

```

Could anyone suggest how to connect to a mongodb instance?

Cross-posting this question at drupal-mongodb issue as well

# Answer
> 0 votes
You don't need to set a function in settings.php to define the connection. The documentation lists this as an example:

https://fgm.github.io/mongodb/install/#settings-configuration

```
// In sites/default/settings.local.php.
$settings['mongodb'] = [
  'clients' => [
    // Client alias => connection constructor parameters.
    'default' => [
      'uri' => 'mongodb://localhost:27017',
      'uriOptions' => [],
      'driverOptions' => [],
    ],
  ],
  'databases' => [
    // Database alias => [ client_alias, database_name ]
    'default' => ['default', 'drupal'],
    'keyvalue' => ['default', 'keyvalue'],
    'logger' => ['default', 'logger'],
  ],
];

```

---
Tags: 8, database
---


# Question
Title: How can I change a page's title for each page individually?
I am wondering if there is a way that I can change the page titles so that users can see a nice title but that at the same time, the internal title of that same page be different?

# Answer
You can use a module that allows you to change it each time or use a different pattern than default Drupal:

Metatag

This module allows you to control a lot more than just the Page title.
> 1 votes

# Answer
You can modify the title via a preprocess function in .theme file. For example a theme\_preprocess\_page function
> 0 votes

---
Tags: meta-tags
---


title: Facebook does not use article image

text:
# Question
Title: Facebook does not use article image
We installed the metatag module,
and we activated all metatag entries on the *modules* administration page.
On the module settings
we selected content type *Node:article* and went to *Open Graph*.
We edited the tag *image* with the value **\[node:field\_image\]**,
the same for tag *image url*

In the page source, we checked the meta properties:
"og:image" content="https://*domain name*/sites/default/files/field/image/*name of image*.jpg"
"og:image:url" content="https://*domain name*/sites/default/files/field/image/*name of image.jpg*"
Using this internet address directly in the browser, the article image is displayed as expected.

Meanwhile, Facebook still does not show the article image. The main logo image is shown, even after emptying the cache of the Drupal site and the cache of the browser.

What does go wrong?

# Answer
Having been through this before with OG tags and Facebook, if your site has been up and you verified the OG tags are in the source and work, then the likely culprit is that Facebooks crawler cached the page before you added the tag and you will need to wait a while.

If the image url resolves and the tag is right, it just takes time.

Perhaps try to look into using the Facebook debugger, something like in this article: https://www.braveriver.com/how-to-clear-facebook-open-graph-and-twitter-cards-cache-on-demand/

We saw this behavior with both Facebook and Twitter. IIRC it took about 3-6 hours to see them "appear" after initial attempts.
> 1 votes

---
Tags: media, meta-tags, social-network
---


# Question
Title: View of taxonomy terms that are used giving duplicates, even with distinct
I am trying to make a view of taxonomy terms that are used in content.

I created a test content type with a taxonomy term field, and used devel to generate content.

I've created a view of taxonomy terms, and added a relationship to the content with that taxonomy field:

*Edit* As stated above, I created a taxonomy view. I don't think these symptoms are caused by `nodes` being the base table

And, naturally, it duplicated a row for the taxonomy term for each content that contains that term:

I just want a list of the taxonomy terms used, with no duplicates, which would be this:

```
rudusteueph
dacigiwucl

```

So I made the relationship required:

which got rid of `spathew`. Then I removed the title field from the view. However I was still getting duplicates of each content by each term:

Since I don't want any duplicates, I checked `Distinct`:

However, I am still getting duplicates. How can I get a true `DISTINCT` result set?

# Answer
> 4 votes
Try using aggregation. Turn on aggregation and try Group Results Together on your term name field.

# Answer
> 1 votes
Besides other already proposed solutions you could also add a Contextual filter to your Views and set it to display a `Summary` of term names and choose not to display the ones without results.

I haven't tries this on a `Taxonomy term` views, but you could probably get it to work either way.

# Answer
> 0 votes
Your base table is node content. You should create a taxonomy view and add the relationship to content with the entity reference field pointing to the taxonomy vocabulary. You can then try distinct. If that doesn't work for your, then group the results by the taxonomy field

---
Tags: views
---


# Question
Title: Feeds remove item with certainly conditions
Good day

I have a problem with the side of developer

with certainly conditions i need remove a item from source. for example i have in source

nid and phone1 and phone2

but if phone2 is the same that phone1 remove, all this is in updates nodes

```
function custom_feeds_before_update($source, $item, $entity_id){

  $entity = node_load($entity_id);
   if (isset($item['phone 2'])) {
      if($entity->field_phone_1['und'][0]['value'] == $item['phone 2']){
         unset($item['phone 2']);
      }
  }
}
function custom_feeds_presave($source, $item, $entity_id){

  $entity = node_load($entity_id);
   if (isset($item['phone 2'])) {
      if($entity->field_phone_1['und'][0]['value'] == $item['phone 2']){
         unset($item['phone 2']);
      }
  }
}

```

something i make wrong? none working never unset if i make dpm in item no appear the item but if i see the node appear update, is other hook

thanks for any help

# Answer
> 1 votes
To alter the source items for the D7 version of Feeds, implement the hook `hook_feeds_after_parse()`.

```
/**
 * Implements hook_feeds_after_parse().
 *
 * Removes duplicate phone numbers for importer 'myimporter'.
 */
function mymodule_feeds_after_parse($source, $result) {
  if ($source->importer->id == 'myimporter') {
    foreach ($result->items as &$item) {
      if (isset($item['phone 1']) && isset($item['phone 2']) && $item['phone 1'] == $item['phone 2']) {
        // If phone 1 and phone 2 are the same, do not import phone 2.
        unset($item['phone 2']);
      }
    }
  }
}

```

---
Tags: 7, hooks, feeds
---


# Question
Title: How do I add a "Please select"/ "none" option to a required select input in a form?
I cant find anything about that in the drupal 8 form api on how to add an option "Please select" to a select element. The form item is mandatory so you must select something. Of course, selecting "Please select" should invalidate.

```
$select['#options'] = $options;
$select['#required'] = true;

```

# Answer
As they explain in the documentation URL provided in your question you should add the `#empty_option` or `#empty_value` property to the render array of the select button.

> * `#empty_option`: (optional) The label to show for the first default option. By default, the label is automatically set to "- Select -" for a required field and "- None -" for an optional field.
> * `#empty_value`: (optional) The value for the first default option, which is used to determine whether the user submitted a value or not.
>     + If `#required` is `TRUE`, this defaults to `''` (an empty string).
>     + If `#required` is not `TRUE` and this value isn't set, then no extra option is added to the select control, leaving the control in a slightly illogical state, because there's no way for the user to select nothing, since all user agents automatically preselect the first available option. But people are used to this being the behavior of select controls.
>     + If `#required` is not `TRUE` and this value is set (most commonly to an empty string), then an extra option (see `#empty_option` above) representing a "non-selection" is added with this as its value.
> 4 votes

# Answer
You should use #empty\_value :

```
$select["#empty_value"] = "";

```

And if you want to custom the label of empty value use :

```
$select["#empty_option"] = "My custom label";

```
> 4 votes

---
Tags: forms, 8
---


# Question
Title: How do I remove product duplicates in a view?
In my view I have duplicate entities for my product list, this is different from Drupal 7 as you could use the distinct module.

How can I remove the duplicates from my commerce product views in Drupal 8?

# Answer
> 1 votes
Drupal Commerce has duplicate entities because a product is referenced from multiple variations, any field you add to a variation type will find multiple duplications in your view most notably in images but could be any field in example t-shirt size.

An easy way to remove these is to set in your view:

```
FILTER CRITERIA
Product: Variations:delta (= 0)

```

---
Tags: views, 8, commerce
---


title: Execute drush commands from UI?

text:
# Question
Title: Execute drush commands from UI?
So i wrote a lot of custom code which is executed form custom drush commands from the command line/terminal, works fine, but now the client changes his mind and want to execute the code from the UI, the admin panel.

Is there any way i can run those drush commands from that level or not?

Thanks, Will

# Answer
in php you can do something like :

> shell\_exec("drush status");

if this is temporary, you can execute it from devel/php, but if it's a production site solution that you need, you can per example add a custom form that does this in its submit method
> 3 votes

---
Tags: drush
---


# Question
Title: Unable to set default value for checkbox form element inside tableselect
I've created a custom table using a `tableselect` element, and within each row, I have a checkbox form element that should populate the checkbox from a checkbox field in the node. I've tried every possible format of `#default_value` (setting it to `1`, `array(1)`, etc), to no avail. Since in HTML it's the `checked` attribute that causes a checkbox to show as checked, I came up with this option:

```
  foreach($translations as $locale => $locale_data) {
    // Get data for other fields...

    // Get data for Staging Only checkbox
    $staging_only = isset($entity->field_pub_staging_only[$locale]) ? (int)$entity->field_pub_staging_only[$locale][0]['value'] : 0;

    $row = array(
     'language_locale' => $locale_link,
     'status' => $status,
     'stage_url' => $stage_url,
     'start_date' => array(
       'data'=> array(
         '#type'=>'textfield',
         '#value'=> $new_start_date,
         '#title' => 'Start Date',
         '#title_display'=>'invisible',
         '#name'=> 'start_date[' . $locale . ']',
         '#id'=>  'start-date[' . $locale . ']',
         '#attributes' => array('class' => array('datepicker')),
         '#size' => 10,
         '#maxlength' => 10
       ),
     ),
     'end_date' => array(
       'data'=> array(
         '#type'=>'textfield',
         '#value'=> $new_end_date,
         '#title' => 'End Date',
         '#title_display'=>'invisible',
         '#name'=> 'end_date[' . $locale . ']',
         '#id'=> 'end-date[' . $locale . ']',
         '#attributes' => array('class' => array('datepicker')),
         '#size' => 10,
         '#maxlength' => 10
       ),
     ),
      'staging_only' => array(
        'data'=> array(
          '#type'=>'checkbox',
          '#title' => 'Staging Only',
          '#title_display'=>'invisible',
          '#name'=> 'staging_only[' . $locale . ']',
          '#id'=> 'staging_only[' . $locale . ']',
          '#default_value' => $staging_only
        ),
      ),
      'display_title' => $title
    );

    if ($staging_only) {
      $row['staging_only']['data']['#attributes'] = array('checked' => array('checked'));
    }

    $options[$locale] = $row;
  }

  $header = array(
    'language_locale' => t('Language Locale'),
    'status' => t('Status'),
    'stage_url' => t('Stage URL'),
    'start_date' => t('Start Date'),
    'end_date' => t('End Date'),
    'staging_only' => t('Staging Only'),
    'display_title' => t('Display Title')
  );

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No content available.'),
    '#attributes' => array('id' => array('locale-table')),
  );

...

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

  return $form;
}

```

where I'm basically manually added the `checked` attribute to the element when it's checked. It works, but it seems sort of hackish, since it's not using what would normally be used to set a form element value with Form API. Is there a better way to do this with the usual Form API settings?

**CLARIFICATION** It appears that my question wasn't clear, based on the answers I've received so far. The issue is not whether the tableselect row checkbox is checked by default; the issue is attempting to mark as checked the `staging_only` checkbox, which is a separate from api element within the tableselect row.

# Answer
> 1 votes
I remember struggling with this for a moment ! The documentation is not so explicit..

The *tableselect* element takes a `#default_value` array as a multiple *select* element would do, that is at the same level as the `#options` array, and with each selected option key being mapped to a truthy value, usually integer `1`.

In the foreach, you would do something like this :

```
if ($staging_only) {
  // $row['staging_only']['data']['#attributes'] = array('checked' => array('checked'));
  $selection[$locale] = 1;
}

```

And then :

```
$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#default_value' => $selection,
  '#empty' => t('No content available.'),
  '#attributes' => array('id' => array('locale-table'))
);

```

Non present options in the selection array default to false so you can ignore unchecked values.

# Answer
> 0 votes
Use the `#default_value` key of the form. This key will reference an array of the same shape as the values in `$form_state`, which will have only the rows checked. Each item will have a key the same as its value, these keys/values will be the key of each row in the table. Sounds complicated but it is not. Check these two examples.

**Rows with sequential key**

```
$rows =  [
  [ 1, 'first value'], // row 0
  [ 2, 'first value'], // row 1
];

// will select the first row
$selection = [0 => 0];

$form['table'] = [
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $rows,
  '#default_value' => $selection,
  '#empty' => t('No content available.'),
  '#attributes' => ['id' => ['locale-table']]
];

```

**Rows as an associative array**

```
$rows =  [
  'r11' => [ 123, 'first value'], // row 0
  'k22' => [ 243, 'first value'], // row 1
];

// will select the first row and the second row
$selection = [
  'r11' => 'r11',
  'k22' => 'k22',
];

```

---
Tags: 7, forms
---


# Question
Title: How to get a count of number of nodes created per month in views
I have created a view using aggregation which counts the number of nodes created of a certain content type. I want to be able to group these by month i.e. Jan - 10, Feb - 15, Mar, 20 and so on. At present it is just a count of all nodes created.

How do I do this with views? I've looked around and cant seem to find any information how to do this. Any help would be appreciated. thanks

# Answer
> 7 votes
I just figured it out:

* Create a view for all nodes (filtered by type or status if necessary).
* I use a table layout, enabled aggreation, added field "nid" with "Count distinct".
* I then add a sort by "post date" with "monthly" granularity.
* Then I added a "post date" field with custom format "M-Y". I select "min" instead of "group results together. That's important, otherwise it will not group the results by month

# Answer
> 1 votes
Look into using the "group by" function in views. You will need to add a date field such as "node: updated date" to use to group by (you can optionally exclude from display).

Then on this date field use custom date format eg just month (m) which will give you a range for that month and it will group any content from that month.

You can then change your aggregation function to count per group and display in the group header by updating the views-x.tpl.php file.

# Answer
> 0 votes
I think you need to use views\_date\_format\_sql

---
Tags: views
---


# Question
Title: How to find where are defined tokens for Redirect?
After enabling *Token* and *Redirect* modules, I've found at `/admin/help/token` that I can use *Redirect* tokens. For example:

However, I've got the problem finding the place where and how these tokens are defined (which file and hook or class).

Any ideas?

---

I've tried to search inside all files in docroot, e.g.

```
$ grep -r "The URL of the redirect" .
(nothing)
$ grep -r "The URL of the" .
(returns everything apart of redirect, no matching placeholders found)
$ grep -r token modules/contrib/redirect/
modules/contrib/redirect/config/install/views.view.redirect.yml:          tokenize: false
modules/contrib/redirect/modules/redirect_404/config/install/views.view.redirect_404.yml:          tokenize: false
modules/contrib/redirect/modules/redirect_404/redirect_404.routing.yml:    _csrf_token: 'TRUE'
modules/contrib/redirect/src/EventSubscriber/RouteNormalizerRequestSubscriber.php:      // Strip off query parameters added by the route such as a CSRF token.
$ grep -r redirect modules/contrib/token/
modules/contrib/token/src/Controller/TokenCacheController.php:   * Clear caches and redirect back to the frontpage.
modules/contrib/token/src/Controller/TokenCacheController.php:    return $this->redirect('<front>');
$ find modules/contrib/redirect modules/contrib/token -name "*.tokens.inc"
modules/contrib/token/tests/modules/token_module_test/token_module_test.tokens.inc
modules/contrib/token/token.tokens.inc (Note: nothing here for redirect)

```

So basically I couldn't find the source which module is defining those. This can help me in order to find out, why some of them aren't working as expected.

---

The main reason I ask this, because I would expect for redirect URL such as `/foo/XXX`, to return `XXX` when using `[redirect:url:args:last]`, but these tokens aren't populated at all.

# Answer
> 0 votes
As Clive mentioned, since Redirect is an entity, those tokens are automatically generated by the Token module's token.tokens.inc.

I suggest you read Custom Tokens in Drupal 8 to understand how they are declared & work.

---
Tags: 8, redirection, tokens
---


# Question
Title: Parent module to link to sub modules - generated by sub-module
I've got a parent module that shows a list of functionality available from its sub modules. I'd like the links shown related to sub-modules to be added by the sub-modules themselves rather than being hard coded into the parent module (although they are generated using the route name).

The reason for this is so sub-modules are responsible for showing their functionality through the parent based on the users permissions and that work is self contained. Also means if a sub-module is disabled there won't be any dead links in the parent.

# Answer
> 1 votes
This is an opportunity to create your own hook.

In the parent module, let's say the function responsible to provide the list of functionalities is your hook function.

In this function, you need to invoke modules providing the functionalities, thus meaning your submodules have to implement the hook in order to expose their features.

For example, in your main module :

```
/**
 * Shows a list of functionalities available from other modules
 */
function mainmodule_get_functionalities_list () {
  $list = \Drupal::moduleHandler()->invokeAll('list_functionalities');
  # Here filter the list based on user permissions, unless you have a good reason
  # to do it in each submodule (like if the permission is provided by the submodule,
  # the parent may not be aware of it, or it means harcode).
  return $list;
}

```

And in a submodule :

```
/**
 * Implements hook_functionalities_list
 */
function submodule_functionalities_list () {
  return [
    'some functionality',
    'awesome submodule functionality',
    #'etc.'
  ];
}

```

Note : hook\_functionalities\_list implementation is not restricted to submodules. If you really need to, you might want to invoke submodule "manually", that is : using `\Drupal::moduleHandler()->getImplementations($hook);`, filter the implementation list based on (sub)module naming, and foreach one make the call.

---
Tags: 8
---


# Question
Title: Validation constraints on form fields ignored
Trying to figure out custom validation with constraints, but no luck yet. Right now, my form posts content and gives no errors when form is filled out incorrectly.

(Please avoid suggesting validation modules -- I know those exist.)

Maybe somebody knows what I'm missing? Or maybe it's done different when I'm doing specific fields? Or maybe this isn't how to do it on a back-end content submission form? Here's what I have so far:

I built a module called "custom\_validation." It contains custom\_validation.module:

```
  <?php

/**
 * @file
 */

/**
 * Implements hook_entity_type_alter().
 */
function custom_validation_entity_type_alter(array &$entity_types) {

  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */

  $entity = $entity_types['node'];
  $entity->addConstraint('BlogpostError');
}

```

Then, in subfolder src/Plugin/Validation/Constraint, I've got two files. BlogpostErrorConstraint.php contains:

```
namespace Drupal\custom_validation\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Prevent article creation if errors.
 *
 * @Constraint(
 *   id = "BlogpostError",
 *   label = @Translation("Added blog post category instead of story author in author field", context = "Validation"),
 *   type = "string"
 * )
 */
class BlogpostErrorConstraint extends Constraint {

  /**
   * {@inheritdoc}
   */

    public $notByline = '%value is a blog post type. Please add a byline';

    public $noImageSource = 'need image source';

}

```

BlogpostErrorConstraintValidator.php contains:

```
namespace Drupal\custom_validation\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the BlogpostError constraint.
 */
class BlogpostErrorConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {

    if (!isset($items)) {
      return;
    }

    // limit this to 'blog entries' content type
    if ($items->bundle() == 'blog_entry') {

      // now loop through each field...
      foreach ($items as $delta => $item) {
        // an array of phrases we don't want in the field
        $bad_bylines = [];
        array_push($bad_bylines,"Value one","value two","abc123");

        // adding validation...
        //byline field
        if (in_array($item['field_byline'], $bad_bylines)) {
           // not sure of syntax here
           $this->context->addViolation($constraint->notByline, ['%value' => $item->value]);
        }

        //main image source field...
        if ($item['field_main_image_source'] == '') {
           $this->context->addViolation($constraint->noImageSource, ['%value' => $item->value]);
        }
      }

    }

  }

}

```

# Answer
> 0 votes
Turns out I was trying too hard. Typical beginner mistake. :) I threw out the code above, and started from scratch. I replaced everything with the code examples in this tutorial: https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint

Within the validator, I replaced `if (!is_int($item->value))` with `if ($item->value == "Value one" || "value two")`, to get what I needed to validate on. Then I modified the variable names, field names and error messages to suit my needs. It only handles one field, but gets me closer to what I need.

---
Tags: 8, forms
---


title: Firefox can't download private PDFs

text:
# Question
Title: Firefox can't download private PDFs
I have an issue with FireFox where it can't download generated private file PDFs, yet Chrome has no such issue.

We populate PDF files with TCPDF and they get moved and copied into a few different directories. But ultimately, they're in directories in the private files directory behind the document root, with Drupal configured to look at this directory.

If I move any of these PDFs into the root of the site and access them directly with the URL, it works fine, but I wouldn't rule out the PDFs being corrupted in some small way. I've looked at the response headers when the file's downloading and all is in order, until I get this `NS_ERROR_NET_PARTIAL_TRANSFER` message and it fails.

I've run with xdebug enabled and stepped through hook functions of hook\_file\_download and the headers generated there all seem ok too.

Other private PDFs that aren't generated can be downloaded no problem.

I'm really running out of ideas of what it could be regarding FireFox and the private files system.

# Answer
> 2 votes
Hudri's comment ultimately led me to the answer, so huge thanks!

The real issue is the mismatch between the file's real size on the server and the size Drupal stores in the file\_managed table, filesize column. Firefox will only download files that have matching values for the HTTP response's Content-Length header and the real length of the file sent to the browser. As to why the value's greater than the real one I'm still finding the answer to.

---
Tags: 7, files
---


# Question
Title: Capturing cache metadata from file_create_url?
I'm writing a Drupal 8 controller which takes in a media entity, and returns a redirect response to the actual file URL.

It works by finding the file associated with the media entity, and then does this:

```
      $url = file_create_url($file->getFileUri());

      $response = new CacheableRedirectResponse($url);
      $response->addCacheableDependency($media);
      $response->addCacheableDependency($file);

      return $response;

```

However, this results in a LogicException: "The controller result claims to be providing relevant cache metadata, but leaked metadata was detected"

Ok, so what's happening is that file\_create\_url() ends up generating cache metadata, and that cache metadata is not being attached the response object. But it doesn't seem possible for me to do that, because file\_create\_url just returns a string and not the cache metadata object.

Here's my current workaround, but I'm not sure if this is correct either:

```
      $context = new RenderContext();
      $url = \Drupal::service('renderer')->executeInRenderContext($context, function () use ($file) {
        return file_create_url($file->getFileUri());
      });

      $response = new CacheableRedirectResponse($url);
      $response->addCacheableDependency($media);
      $response->addCacheableDependency($file);
      if (!$context->isEmpty()) {
        $metadata = $context->pop();
        $response->addCacheableDependency($metadata);
      }

      return $response;

```

Anyone with more experience with cache metadata know if this is the correct way to handle this situation?

Thank you

# Answer
> 1 votes
This code seems to be OK to me until `file_create_url()` is transformed into a service which can handle cacheable metadata like `UrlGenerator`.

An easier way to avoid this error message would be to return an uncacheable `RedirectResponse`:

```
  $url = file_create_url($file->getFileUri());
  $response = new RedirectResponse($url);
  return $response;

```

---
Tags: 8, caching
---


title: file name constraint in form

text:
# Question
Title: file name constraint in form
I've got a basic field constraint figured out (per question here: Validation constraints on form fields ignored )

Next, I want to constrain the main image field to limit the file name. For example, if someone uploads a file named "1234-shutterstock.jpg" I want to detect that the file name contains "shutterstock" and add that violation.

But I have no clue how to tackle the syntax for this. Maybe someone can point me in the right direction?

I've started with something like this. I know this is wrong.

```
            <?php
            namespace Drupal\custom_validation\Plugin\Validation\Constraint;

            use Symfony\Component\Validator\Constraint;
            use Symfony\Component\Validator\ConstraintValidator;

            /**
             * Validates the Image constraint.
             */
            class MainImageConstraintValidator extends ConstraintValidator {

              /**
               * {@inheritdoc}
               */
              public function validate($items, Constraint $constraint) {
                foreach ($items as $item) {
                  if (strpos($item->value, 'shutterstock') !== false) {
                    $this->context->addViolation($constraint->wrongImageName, ['%value' => $item->value]);
                  }

                }
              }

            }

```

# Answer
> 0 votes
Per Clive's comment above, it works with this:

```
        namespace Drupal\custom_validation\Plugin\Validation\Constraint;

        use Symfony\Component\Validator\Constraint;
        use Symfony\Component\Validator\ConstraintValidator;

        /**
         * Validates the Image constraint.
         */
        class MainImageConstraintValidator extends ConstraintValidator {

          /**
           * {@inheritdoc}
           */
          public function validate($items, Constraint $constraint) {
            foreach ($items as $item) {
              if (strpos($item->entity->filename->value, 'shutterstock') !== false) {
                $this->context->addViolation($constraint->wrongImageName, ['%value' => $item->value]);
              }

            }
          }

        }

```

---
Tags: 8, forms
---


# Question
Title: Display entity as options_select multi-select
Below is my code for the view. I have tried multiple = true, multiple\_values=true, multiple = multiple. None have worked.

```
->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 0,
    'settings' => [
        'match_operator' => 'CONTAINS',
        'size' => '60',
        'autocomplete_type' => 'tags',
        'placeholder' => '',
    ],
])

```

# Answer
> 1 votes
The `options_select` widget will automatically be multi-select if the cardinality of the field is multiple. Make sure your field is created as such, e.g.

```
use Drupal\Core\Field\FieldStorageDefinitionInterface;

...

$fields['foo'] = BaseFieldDefinition::create('entity_reference')
  ...
  ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
  ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 0,
    'settings' => [],
  ])
  ...

```

Incidentally, `options_select` has no settings, so you can provide an empty array instead of the autocomplete settings you're currently using.

---
Tags: 8, entities, forms
---


# Question
Title: How to override views title using values from several contextual filters?
I have a view where the user can filter by using contextual filters in the URL, like this:

```
timeline/%year/%month/%day

```

I then use these contextual filters:

```
Content: node.field_daterange (year)

Content: node.field_daterange (month)

Content: node.field_daterange (day)

```

Users can use this path to get all events in a year, e.g:

```
timeline/1945

```

Or to get all events on a specific month in a year they can use

```
timeline/1945/05

```

Now I want to dynamically build the title of the view. If only the year parameter is used it should the title "Timeline YEAR" and if both year and month is set I want it to have title "Timeline MONTH YEAR".

In the contextual filter, there is an alternative named "Override title" (under the box "When the filter value IS in the URL or a default is provided")

It is written "Override the view and other argument titles. You may use Twig syntax in this field." But how can I now catch back the `%year`, `%month` or `%day` argument to use it in the title?

# Answer
> 5 votes
There is a `Replacement patterns` fieldset below it that you can copy the patterns from. You need to edit each contextual filter and override the title with the pattern that makes sense in each of those contexts.

---
Tags: views, 8
---


# Question
Title: Get all fields for a content type using REST
Is there any way to get all fields attached to an entity in D8 (including widget types), using REST services? I've tried the following endpoints, but none of them had the list of fields:

```
/entity/node_type/{node_type}
/entity/entity_form_display/{entity_form_display}
/entity/entity_form_mode/{entity_form_mode}

```

I need this if for an app that will generate dynamic forms, based on what's defined in the Drupal backend.

# Answer
The /entity/entity\_form\_display/{entity\_form\_display} should works.

Example:

`/entity/entity_form_display/node.article.default?_format=json`

It will return json like this:

```
{
"uuid": "058dd73d-366d-466d-9393-ad0d5d44e928",
"langcode": "en",
"status": true,
"dependencies": {
    "config": [
        "field.field.node.article.body",
        "field.field.node.article.comment",
        "field.field.node.article.field_image",
        "field.field.node.article.field_location",
        "field.field.node.article.field_tags",
        "image.style.thumbnail",
        "node.type.article"
    ],
    "module": [
        "comment",
        "image",
        "path",
        "text"
    ]
},
"id": "node.article.default",
"targetEntityType": "node",
"bundle": "article",
"mode": "default",
"content": {
    "body": {
        "type": "text_textarea_with_summary",
        "weight": 1,
        "region": "content",
        "settings": {
            "rows": 9,
            "summary_rows": 3,
            "placeholder": ""
        },
        "third_party_settings": []
    },
    "comment": {
        "type": "comment_default",
        "weight": 20,
        "region": "content",
        "settings": [],
        "third_party_settings": []
    },
    "created": {
        "type": "datetime_timestamp",
        "weight": 10,
        "region": "content",
        "settings": [],
        "third_party_settings": []
    },
    "field_image": {
        "type": "image_image",
        "weight": 4,
        "region": "content",
        "settings": {
            "progress_indicator": "throbber",
            "preview_image_style": "thumbnail"
        },
        "third_party_settings": []
    },
    "field_location": {
        "weight": 121,
        "settings": [],
        "third_party_settings": [],
        "type": "options_select",
        "region": "content"
    },
    "field_tags": {
        "type": "entity_reference_autocomplete_tags",
        "weight": 3,
        "region": "content",
        "settings": {
            "match_operator": "CONTAINS",
            "size": 60,
            "placeholder": ""
        },
        "third_party_settings": []
    },
    "path": {
        "type": "path",
        "weight": 30,
        "region": "content",
        "settings": [],
        "third_party_settings": []
    },
    "promote": {
        "type": "boolean_checkbox",
        "settings": {
            "display_label": true
        },
        "weight": 15,
        "region": "content",
        "third_party_settings": []
    },
    "status": {
        "type": "boolean_checkbox",
        "settings": {
            "display_label": true
        },
        "weight": 120,
        "region": "content",
        "third_party_settings": []
    },
    "sticky": {
        "type": "boolean_checkbox",
        "settings": {
            "display_label": true
        },
        "weight": 16,
        "region": "content",
        "third_party_settings": []
    },
    "title": {
        "type": "string_textfield",
        "weight": 0,
        "region": "content",
        "settings": {
            "size": 60,
            "placeholder": ""
        },
        "third_party_settings": []
    },
    "uid": {
        "type": "entity_reference_autocomplete",
        "weight": 5,
        "region": "content",
        "settings": {
            "match_operator": "CONTAINS",
            "size": 60,
            "placeholder": ""
        },
        "third_party_settings": []
    }
},
"hidden": []
}

```
> 3 votes

# Answer
You have to define your own endpoint to implement this, core does not offer this information.
> 0 votes

# Answer
You can access bundle definitions via and export with https://www.drupal.org/project/bundle\_copy. This could be modified or permissions could be used to access them from a client-side app or static generator.
> 0 votes

---
Tags: 8, entities, services
---


title: Pass list from Jquery to form

text:
# Question
Title: Pass list from Jquery to form
I have an AJAX form that I've created into a block exposed on my current page. I will have an interface that will allow the users to select an indefinite amount of content to be used within the submit function of the form.

All the variables that will be passed to my form are node ID numbers, but there could be 1, there could be 50.

I have the Jquery action ready to update my ID numbers but I don't know how to get my ID number from Jquery into a variable, which can then be read when the AJAX form is submitted.

I've been looking at this - How to pass Javascript variable with form on submit?

and this - How to trigger a form and pass variables to $form\_state with jQuery?

And I've been looking at the responses to both, but neither seem to give me access to the data I need, or are only speaking about a single variable, I need to pass a list or an array.

Would it be best to write something to trigger the form rebuild when I provide a new ID and allow the ID to be written into the form via that method?

# Answer
> 0 votes
For anyone looking to an answer to this, it really depends on whether or not you're working with an AJAX form or not. Ideally I wanted to avoid just populating a text area with my updated field to be submitted, so thankfully, since it was using the AJAX form, I was able to pass it information dynamically through Jquery.

In your javascript

```
// whatever your function is to get the information you want to pass
....
Drupal.ajax['edit-save'].options.data._my_vars = JSON.stringify(myList);

// Where 'edit-save' is the ID of my save button in my form
// you can console.log(Drupal.ajax) to see what options you have

```

Then in the callback for your AJAX request, the return request is stored in

```
$form_state['input']['_my_vars'] // or whatever variable name you passed above

```

Then you can check whether or not the response has comeback empty by using

```
 if (empty(json_decode($form_state['input']['_my_vars']))) {
   form_set_error('save'); // You can set the error to be any form element
 }

```

and in your callback code you can make your own error handling by doing

```
if (form_get_error() !== null) {
  // fail code
} else {
  // success code
}

```

Hope this helps someone else down the line

---
Tags: 7, forms, ajax
---


# Question
Title: 8 - How do I load a Term entity from an EntityReferenceItem?
I have a content type with a taxonomy term. I can load the first `EntityReferenceItem` using

`$node->country->get(0)`

then I can `tid` doing `->target_id` (and then manually load the Term object via `Term::load`.

But is there a function of EntityReferenceItem that I can call to get it to load the corresponding term? I'm thinking something like:

```
  $node->country->get(0)->getReferenced()

```

I don't see anything at the Drupal API reference

# Answer
> 7 votes
```
$node->country->entity.

```

See http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet, where it lists the properties of common field types.

If you want to see the properties of a field type, one way to do that is by looking at the propertyDefinitions() method of the field type class, in this case EntityReferenceItem.

# Answer
> 0 votes
Update code for 8.6, following example of term reference field

```
$tid = $para->get('field_category')->getString();
$tname = $para->get('field_category')
      ->get(0)
      ->get('entity')
      ->getString();

```

---
Tags: entities, 8
---


# Question
Title: Export views result as json, xml, csv etc?
In Drupal 7 we had

Can Migrate in Drupal 8 replace these, for example to export view results with Migrate as JSON, CSV, etc?

# Answer
There are some options to export Views data in CSV format in Drupal 8

1. Views Data Export Module

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV Microsoft
> * XLS (or really simple HTML understood by Excel)
> * Microsoft DOC
> * Basic TXT

2. VBO Export Module it adds CSV export feature for Views Bulk Operations Moule

> The module adds 2 new Views Bulk Operations actions: Export to csv and export to Excel.

3.CSV Serialization Module

This module provides a CSV encoder for the Drupal 8 Serialization API. This enables the CSV format to be used for data input and output in various circumstances. For example:

> Drupal 8's REST module can accept or return data in CSV format Views can output CSV data via a 'REST Export' view Module developers may leverage CSV as a format when using the Serialization API
> 8 votes

---
Tags: views, 8, migrations
---


# Question
Title: How to send a custom Solr Distance Query with SearchApi
My nodes have a geofield and my search query should find all the nodes within a range.

I've managed to create a search form against my Solr Server with views. But I want to do the request by myself (having my own form and submit method). There's a solution for D7 here: How to send a custom Solr Query using Search API Solr but none of that seems to be usable with the D8 modules.

I believe there must be something like

```
$result = SolrSearchService('myServer', 'myIndex')->request(['title' => 'Test']);

```

But I can not find anything.

The views-built search page renders a query against my Solr Server like

```
path=/select params={q=(phonm_rendered_item:nintendo^1+tm_title:nintendo^8)&json.nl=flat&pt=48.1371079,11.5753822&d=50&omitHeader=true&fl=ss_search_api_id,ss_search_api_language,score,fts_field_geo_koordinaten__distance:geodist()&start=0&fq=%2Bindex_id:default_solr_index+%2Bhash:ozztjn&fq={!geofilt}&rows=10&sfield=locs_field_geo_koordinaten&wt=json}

```

Apparently there are some parameters responsible for the distance calculation:

* pt=48.1371079,11.5753822 - it's where I am
* d=50 - it's the max distance
* field\_geo\_koordinaten - it's the geofield in the node
* geodist() - the function ?

How can I render such a query with Search API?

# Answer
Debugging around I found the solution:

```
$index = Index::load('default_solr_index');
/* @var \Drupal\search_api\Query\Query $query */
$query = $index->query();
$query->keys($form_state->getValue("keys"));
$location_options = (array) $query->getOption('search_api_location', []);

$location_options[] = [
      'field' => "field_geo_koordinaten",
      'lat' => 48.1371079,
      'lon' => 11.5753822,
      'radius' => 50,
    ];

$query->setOption('search_api_location', $location_options);
$results = $query->execute();

```

Thanks for pointing me in the right direction.
> 2 votes

---
Tags: 8, location, search
---


# Question
Title: How to manage catalog display of images for Commerce 2 product variation
I have created a custom product type and its variations are created with attribute 'Size'. If I create a new product with its multiple images, then the catalog view shows these multiple images instead of a single image.

Below is the Product type variation 'Manage display' settings.

# Answer
> 0 votes
In future anyone need the answer, The image fields's format to be set to 'Image delta'. If image delta value set to 0 then the first image will be displayed and if it is set to 1 then the second image is displayed and so on.

Delta appears for the fields that has multiple values and delta refers to the order by which it appears.

---
Tags: 8, commerce
---


# Question
Title: How to change the background color of blocks?
I just want to change the background color of a block on the “Sidebar First” region in Drupal 8.

How can I do that?

# Answer
> 1 votes
If you are doing this from your own theme or modifying an existing theme and you will have to understand how to find the relevant block id or class using the browser inspector

Lets assume you are changing the search block you could do something like this in the stylesheet of your theme

```
#block-bartik-search {
  background-color: red
}

```

# Answer
> 0 votes
Try the Block Class module:

https://www.drupal.org/project/block\_class

This will allow you to add classes to any block through the block's configuration interface. Then, you can use CSS to style that class.

To add CSS to your theme, follow the documentation here:

https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

There's one catch, though.

This supposes that you are editing your own theme. If you are using a theme from Drupal core (like Bartik) then you should make a sub-theme first and modify that:

https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme

Since it sounds like you are very new to website design in general, and not merely a newcomer to Drupal, I sympathize if this seems like overkill to make a small change.

However, it's very important to use a sub-theme so that your changes aren't wiped out the next time you upgrade. Gradually, you'll make more and more changes, until the theme is truly yours.

---
Tags: 8, theming, blocks
---


title: Entity reference multi-select

text:
# Question
Title: Entity reference multi-select
I'm trying to make an entity reference field a multi-select options select but I can't seem to find out how to make that happen. Any help is appreciated. Below is the code I'm using.

```
$fields['some_field'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Some Field'))
  ->setDescription(t('This is a field.'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'other_entity')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ])
  ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 0,
    'settings' => [
      'options_select' => 'multiple',
      'placeholder' => '',
    ],
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setRequired(FALSE);

```

# Answer
Ultimately this was answered in a different but similar question I asked. The answer is the code below attached to the field in my entity.

```
use Drupal\Core\Field\FieldStorageDefinitionInterface;

->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)

```
> 2 votes

# Answer
You can by using BaseFieldDefinition::setCardinality

> Sets the maximum number of items allowed for the field.

By adding:

```
->setCardinality(0)
// 0 means unlimited. Put 3 if you only want to allow up to 3 values

```
> 0 votes

---
Tags: 8, entities
---


title: Add custom config to ckeditor

text:
# Question
Title: Add custom config to ckeditor
I'd like to customise the CKEditor config, by using the removePlugins setting to disable the *elementspath* plugin, so that `body p` etc. isn't displayed in the status bar (here's a similar, old question for D7).

I created the following CKEditor plugin, which returns an additional setting via the getConfig() method. It has no effect on my editor fields (I've verified the plugin ID is being matched).

What's the right approach - if not this - for a config change, given I'm not loading a new plugin JS file or adding buttons?

```
<?php

/**
 * @file
 * Definition of \Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin\RemoveElementsPath
 */

namespace Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "Remove Elements Path" plugin.
 *
 * @CKEditorPlugin(
 *   id = "remove_elements_path",
 *   label = @Translation("Remove elements path"),
 *   module = "ckeditor_remove_elementspath"
 * )
 */
class RemoveElementsPath extends Pluginbase implements CKEditorPluginInterface {

  /**
   * {@inheritdoc}
   */
  function getDependencies(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  function getLibraries(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function isInternal() {
    return false;
  }

  /**
   * {@inheritdoc}
   */
  public function getFile() {
    return false;
  }

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return [ ];
  }

  public function getConfig(Editor $editor) {
    return [
      'removePlugins' => 'elementspath',
    ];
  }

}

```

# Answer
I had a look at the CKEditor API docs and the other classes I might extend - it didn't seem to be any of:

* `CKEditorPluginButtonsInterface`
* `CKEditorPluginContextualInterface`
* `CKEditorPluginCssInterface`

…though perhaps `CKEditorPluginConfigurableInterface`, if I wanted to configure the settings form per text format?

*Then*, I found a module called ckeditor\_config, so I adapted it's plugin class, which extends `CKEditorPlugin/Internal`:

```
/**
 * @file
 * Definition of \Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin\RemoveElementsPath
 */

namespace Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin;

use Drupal\ckeditor\Plugin\CKEditorPlugin\Internal;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "Remove Elements Path" plugin.
 *
 * @CKEditorPlugin(
 *   id = "remove_elements_path",
 *   label = @Translation("Remove elements path from CKEditor status bar")
 * )
 */
class RemoveElementsPath extends Internal {

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    // Get default config.
    $config = parent::getConfig($editor);

    $config['removePlugins'] = 'elementspath';

    return $config;
  }

}

```

**Edit:** And here's my module if anyone finds it useful.
> 1 votes

---
Tags: 8
---


# Question
Title: Webservice args types automatic validation
It's a Drupal 7 with Webservices module, and there is a service with something like this (example):

```
'create-product' => array(
  'operations' => array(
    'create' => array(
      'help' => t('Add Product'),
      'file' => array(
        'type' => 'endpoints.inc',
        'module' => 'custommodule',
        'name' => 'custommodule',
      ),
        'callback' => 'custommodule_create_product',
        'args' => array(
            array(
                'name' => 'appID',
                'type' => 'int',
                'description' => t("App ID"),
                'source' => array('data' => 'appID'),
                'optional' => FALSE
            ),
            ...

```

Okay, so the type here is "int". Is it possible to make Drupal return some error automatically, if it's not an int that is being sent as appID. Like if it's a string being sent, then it will throw an error. I can't make it work. Why else is there a "type" key-value?

# Answer
Although it appears Services doesn't validate the incoming data based on the `type`, you can use an `access callback` to build your own validation.

Add something like this to your Service Resource definition:

```
// ...
'access callback' => '_example_resource_access',
'access callback file' => array(
  'type' => 'inc',
  'module' => 'example',
  'name' => 'example.resource-access',
),
'access arguments' => array('foo bar'),
'access arguments append' => TRUE,
// ...

```

Then create a file called `example.resource-access.inc` with a function like this:

```
function _example_resource_access($op, $args = array()) {
  if ($op == 'foo bar' && !is_numeric($args[0])) {
    return services_error(t('That is not an integer.'), 406);
  }
  return TRUE;
}

```

Note, `$args[0]` will likely come in as a string representing an integer, so using `is_numeric()` should be accurate, unless you specifically use `(int)` to cast `$args[0]` beforehand, then you can run it through `is_int()` for validation instead.
> 1 votes

---
Tags: 7, services
---


# Question
Title: How can I always have the node title display on top of a background image?
With Drupal 8, the page title is available through a block now. We have several content types where we have an Image field (field\_image) and we constantly have to write templates per content type to place the title on top of the image.

It would be nice if we could use the view modes of each content type or some module to do this. Basically, something that does "take the field image, set it as a background, and place the title on top."

Is there a better way to do this programmatically as we cannot find any other way to do this?

# Answer
> 1 votes
There is several ways to solve this

## 1 make your own module

to do what you described

## 2 add theme templates

for each content type as you described

## 3 Use background\_image module

The module is available for Drupal 8 promises to do just this (I meant to use it but have not actually)

According to the the project description provides a way to insert token values

> Token - Provides a way to view which tokens are available to use when adding overlay text for a background image.

So you can probably use it with a field token to accomplish what you need

# Answer
> 1 votes
Background Images Formatter is another option for accomplishing this, especially when you might want different images on different pages.

> This module provides an image formatter that allows you to set an image in background of a tag. The images are from a field of an entity and not from a configuration page or a custom entity or something else, so it's very easy to setup and manage.

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


title: Open Shortcut in new browser window

text:
# Question
Title: Open Shortcut in new browser window
drupal 7.61 adminimal\_menu I need to have two shortcuts on the shortcut bar open in a new browser window instead of the default same window without having to "right-click". Users are sometimes forgetting to right click

# Answer
> 0 votes
You cann't set/configure it from admin panel (admin/config/user-interface/shortcut/link) because there are no option in Shortcut module configuration.

Now you can use any one of following modules:
https://www.drupal.org/project/menu\_attributes
https://www.drupal.org/project/extlink

or following jQuery script to your page.tpl.php

```
$(document).ready(function(){
$('#id').children(":first").attr("target", "_blank");
});

```

---
Tags: theming
---


# Question
Title: How can I modify the "Password policy constraints" text?
I'm looking for the easiest possible way to modify or alter the password policy constraints error text. The following is the default the users see.

> The password does not include enough variation to be secure. Password must contain characters of at least 3 different types (lowercase, uppercase, digit or punctuation). Password must contain at least one digit.
> Password must be at least 8 characters in length.
> Password must contain at least one lowercase character.
> Password must contain at least one punctuation (not whitespace or an alphanumeric) character.
> Password must contain at least one uppercase character.

I would like to modify it to the following text.

> Password must: • Be at least 8 characters
> • Have at least one lowercase character
> • Have at least one uppercase character
> • Have at least one digit
> • Have at least one punctuation character

Would this be possible using `hook_form_alter()` or other methods?

# Answer
> 0 votes
**Short answer:**

Of course there is a module for that.

Actually, more than one:

https://www.cmsdrupal.com/blog/how-implement-custom-password-policy-drupal https://dev.acquia.com/blog/password-policies-and-drupal/03/04/2017/17856

**Longer answer:**

Since you don't just want to change the policy (you want to change the form markup too) you might also need to use `hook_form_user_login_block_alter(&$form, &$form_state, $form_id)`.

---
Tags: 7, forms
---


# Question
Title: Are all my nodes publicly available at their respective links (ie example.com/node/25)?
I'm new to Drupal and working on a pre-built Drupal site. There seems to be a large number of pages that are public with the `/node` domain path. For example, something like the link `example.com/node/10`, which appears to be publicly available so that anyone can go to it. I'm wanting to disable these nodes from being public.

I tried going to Content in the menu and then unchecking "Published" under Publishing Options. That seems to shut off the node where it appears on other pages, which is not what I want to do.

What I want to do is to prevent users from being able to access links like `example.com/node/50`, which appear to just display specific nodes isolated.

# Answer
> 1 votes
The Rabbit Hole module addresses this very thing:

https://www.drupal.org/project/rabbit\_hole

I just learned about this one a little while ago.

Good luck!

# Answer
> 2 votes
You can try following modules:
Rabbit hole
Internal nodes
Restrict node page view

Comparison among modules:
'Rabbit Hole' apply restrictions/control on per bundle and per entity but 'Internal Nodes' and 'Restrict node page view' only control user access to page. https://www.drupal.org/project/restrict\_node\_page\_view/issues/1558216

A tutorial about rabbit hole:
https://www.lullabot.com/articles/module-monday-rabbit-hole

---
Tags: nodes
---


title: Programmatically save coordinates

text:
# Question
Title: Programmatically save coordinates
I have read in a lot of sources that I should use the `geofield_compute_values()` when trying to programmatically save coordinates in Drupal, but it does not work for me. That function doesn't exist in Drupal 8.5.2.

I've installed the Geofield module using Composer and I can use it as usual in the admin area. There are no problems with saving.

This is the code I tried, which returns an error about a not existing function (`geofield_compute_values()`).

```
$geofield_data = geofield_compute_values(['lat' => $lat, 'lon' => $lon    ], GEOFIELD_INPUT_LAT_LON);
$cbisProduct->set('field_koordinater', $geofield_data);

```

I have also tried this out with no successful result and no errors.

```
$geofield = [
  'geom' => "POINT (" . $lon . " " . $lat . ")",
  'geo_type' => 'point',
  'lat' => $lat,
  'lon' => $lon,
  'left' => $lon,
  'top' => $lat,
  'right' => $lon,
  'bottom' => $lat,
];
$cbisProduct->set('field_koordinater', $geofield);

```

I also tried the solution given in How to save LNG and LAT progamatically in a geofield, but it didn't work either.

How can I programmatically save coordinates?

# Answer
> -1 votes
Try this:

```
$entity->set('field_geofield_name', [sprintf("'POINT (%s %s)'", $longitude, $latitude)]);

```

Cheers!

---
Tags: 8
---


# Question
Title: How do I programmatically save longitute and latitude?
I am using the Geofield Map module which depends on the geofield and I want to save lng and lat pragmatically in the geofield via my controller. I have tried the methods below and they didn't work:

```
$WayPointEntity->field_geo_field->setValue("POINT(" .$waypoint['lng']." " .$waypoint['lat'].")");

```

I also tried:

```
$WayPointEntity->field_geo_field = array(
                  'input_format' => GEOFIELD_INPUT_LAT_LON,
                  'geom' => array('lat' => $waypoint['lat'], 'lon' => $waypoint['lng']),
              );

  $WayPointEntity->save();

```

# Answer
> 0 votes
Try this :

```
$point = [
  'lat' => $lat,
  'lon' => $lon,
];
$value = \Drupal::service('geofield.wkt_generator')->WktBuildPoint($point);
$WayPointEntity->field_geo_field->setValue($value);

```

# Answer
> 1 votes
The reason why your first attempt failed is because you forgot to add the array square brackets to your setValue:

```
$WayPointEntity->field_geo_field->setValue(["POINT (" .$waypoint['lng']." " .$waypoint['lat'].")"]);

```

---
Tags: 8
---


# Question
Title: How do I enable PHP extensions on CentOS to finally finish installing/configuring Drupal?
I am trying to install Drupal 8.0.5 (a standard profile) on Apache 2.4.6 on CentOS 7, with PHP 5.6.19. But in the GUI, I get a problem on the requirements page. It says "PHP extensions disabled. Drupal requires you to enable the PHP extensions in the following list... gd"

I have installed, with yum install these packages: gd, gd-devel, php-gd, php-pdo php-mbstring, php-xml.

I have installed various other packages. I have no reason to think that PHP gd extensions have not been enabled. They've certainly been installed. I've restarted Apache services and MariaDB services. I've rebooted the sever.

I reinstalled Drupal and PHP. I created a php.ini file with "extension=gd.so" as the content. A minimal installation fails for the same reason.

What should I do to get Drupal working for the first time? I have never done this before. How do I enable the PHP Extensions? Or is the message false? If it is, what should I do?

# Answer
> 0 votes
On CentOS, you should have an icon in cPanel for "PHP Selector":

In CloudLinux:

Make sure all of the PHP extensions installed by Yum are enabled & save the settings. Then create or open the info.php page for your domain to confirm the configuration. The problem should be fixed on the Drupal 8 status report.

Note: If you are having problems with installing PHP extensions for a web server running Drupal, consider installing Composer on CentOS. Composer is designed to streamline dependency management in PHP and manages the particular download files required by Drupal 8 modules specifically.

---
Tags: installation
---


# Question
Title: Ensure specific JS files always load last?
(I have looked at related answers, they provide no help because they make invalid assumptions.)

I'm working on a job where the front-end is component-based. I have no control over this. Some of the front-end requires JS and, if it doesn't load last, it screws up all the Drupal JS.

I need to force these three front-end JS files to load last and I would prefer to do it legally.

I have tried hacking the weights in `js_alter()` but apart from being a bad idea (it's not advised) it does not seem to have any effect.

I've tried setting the weights in the `theme.libraries.yml` file but it's impossible to set the weights to enforce what I need. (Set them too heavy and you get an exception.)

My final solution is to force the front-end theme library to be dependent on every Drupal library it conflicts with.

This works, BUT it forces the drupal JS to load on pages where it's not needed (because the theme JS is needed on every page\*).

Any ideas?

\*Technically it's *not* needed on every page but I am not in a position to request the front-end guys write their code better...

# Answer
Turns out I am an idiot.

There were two copies of jQuery so removing the Drupal jQuery and forcing the non-Drupal JS to load first solves the problem completely.

And no massive list of dependencies.

When I first implemented the suggested fix I made a mistake and then assumed it didn't work. Hence my crazy solution with dependencies.

```
/**
 * Implements hook_js_alter().
 */
function customtheme_js_alter(&$javascript, AttachedAssetsInterface $assets) {
  // Unset default modernizr as custom one is added from Fabric assets.
  unset($javascript['core/assets/vendor/modernizr/modernizr.min.js']);
  // Unset Drupal's jQuery as we aren't using it.
  unset($javascript['core/assets/vendor/jquery/jquery.min.js']);

  // Give build.js the lowest weight.
  $max_weight = 0;
  $min_weight = 0;
  foreach ($javascript as $key => $value) {
    if ($value['weight'] > $max_weight) {
      $max_weight = $value['weight'];
    }
    if ($value['weight'] < $min_weight) {
      $min_weight = $value['weight'];
    }
  }

  // Make modernizer custom run next followed by define-fix. (now in head)
  // Define-fix makes drupal define function calls match Fabric's define.
  if (isset($javascript['themes/customtheme/fabric/dist/scripts/build.js'])) {
    $javascript['themes/customtheme/fabric/dist/scripts/build.js']['weight'] = $min_weight - 1.0;
    $javascript['themes/customtheme/fabric/dist/scripts/modernizr.custom.js']['scope'] = 'header';
    $javascript['themes/customtheme/js/define-fix.js']['weight'] = $min_weight - 0.9998;
  }
}

```

And for completeness the "define-fix" code is:

```
defineReal = define;
define = function (name, deps, callback) {
  if(arguments.length === 2 ){
    defineReal(name, [], callback);
  }else{
    defineReal(name, deps, callback);
  }
};

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to render a media entity image (that uses a focal point image style) inside a paragraph twig file?
Originally I used a typical image field in my paragraph, now with the new updates for the media module I would like to use the image library to upload and reuse media entity images. I use focal point for my image styles, in the paragraph I use, the user can choose between a couple of image styles.

preprocess code for passing image styles to twig template:

```
function tekst_en_afbeelding_preprocess_paragraph__tekst_en_afbeelding(&$variables) {
    if (isset($variables['elements']['field_image']['#items'])) {
      $variables['img_223_x_308'] = ImageStyle::load('223_x_308')->buildUrl($variables['elements']['field_image']['#items']->entity->uri->value);
      $variables['img_326_x_450'] = ImageStyle::load('326_x_450')->buildUrl($variables['elements']['field_image']['#items']->entity->uri->value);
      $variables['img_560_x_308'] = ImageStyle::load('560_x_308')->buildUrl($variables['elements']['field_image']['#items']->entity->uri->value);
      $variables['img_1280_x_703'] = ImageStyle::load('1280_x_703')->buildUrl($variables['elements']['field_image']['#items']->entity->uri->value);
  }
}

```

This code does not work anymore for the media entity image.what do I need to change for this to work?

# Answer
> 1 votes
I've found the solution myself:

```
function tekst_en_afbeelding_preprocess_paragraph__tekst_en_afbeelding(&$variables) {

   if (isset($variables['elements']['field_media_entity_img']['#items'])) {
      $media_field = $variables['elements']['field_media_entity_img'];
      $media_entity = $media_field[0]['#media'];
      $field_media_image = $media_entity->field_media_image;
      $uri = $field_media_image->entity->uri->value;
      $variables['img_223_x_308'] = ImageStyle::load('223_x_308')->buildUrl($uri);
      $variables['img_326_x_450'] = ImageStyle::load('326_x_450')->buildUrl($uri);
      $variables['img_560_x_308'] = ImageStyle::load('560_x_308')->buildUrl($uri);
      $variables['img_1280_x_703'] = ImageStyle::load('1280_x_703')->buildUrl($uri);
    }
}

```

# Answer
> 5 votes
You'll run into troubles with this technique, because Media images are entities on their own, and have their own cache settings. So if you change the image style on paragraph level, the embedded media image will not know anything of this and instead returns the first, cached size.

Instead create multiple display view modes for your media entities, and let your editors choose the view mode on paragraph level. Below is the code I'm using in my own projects

```
function wtfrontend_base_preprocess_paragraph__image(array &$variables) {
  $paragraph = $variables['paragraph'];

  if ($paragraph->hasField('field_image_viewmode_image')) {
    $imageViewMode =  $paragraph->field_image_viewmode_image->value;
    if (isset($variables['content']['field_image']['0']['#view_mode'])) {
      $variables['content']['field_image']['0']['#view_mode'] = $imageViewMode;
      unset($variables['content']['field_image']['0']['#cache']['keys']);
    }
  }
}

```

Render the image normally with `{{ content.field_image }}`

---
Tags: theming
---


# Question
Title: How do I set up a site to use Redis as cache handler?
I'm trying to enable Redis on my Drupal site but when I check the status of the module I keep getting this warning message.

> No Redis client connected, this module is useless thereof. Ensure that you enabled module using it or disable it.

The steps I followed to enable Redis are the following.

1. I edited the config.yml file to add the following lines

```
installed_extras:
  - redis
  - php-redis

```
2. I enabled the Redis module
3. I edited the settings.php file to add the following lines

```
$settings['cache']['default'] = 'cache.backend.redis';
$settings['redis.connection']['interface'] = 'PhpRedis';
$settings['container_yamls'][] = 'modules/redis/example.services.yml';
$settings['container_yamls'][] = 'modules/redis/redis.services.yml';

```

I also tried to execute the following code in index.php and the cache appears to be working.

```
$redis = new Redis();
$redis->connect('127.0.0.1');
$cache = $redis->get('key');
if ($cache === false) {
  echo "miss";
  $cache = "test";
  $redis->set('key',$cache);
}
else {
  echo "didn't miss";
}
// At this point $cache is either the retrieved cache or a fresh copy, so echo it.
echo $cache;
exit();

```

It appears that Redis is working but for some reason it isn't used by Drupal.

How do I set up Drupal to use Redis as cache handler?

# Answer
For Drupal 8, use this code in the settings.php file:

```
$settings['redis.connection']['host'] = 'localhost';
$settings['redis.connection']['port'] = NULL;
$settings['cache']['default'] = 'cache.backend.redis';
$settings['redis.connection']['base'] = 101;

```

You can check whether or not Redis is running by viewing the status report at: /admin/reports/status
> 1 votes

---
Tags: 8
---


# Question
Title: How to get Webform Radio Option Value as a token value for email template?
I am trying to use my webform's radio field to choose between two departments, let's call them ABCDE and XYZ. On the webform display that the user sees, I want them to show up as ABCDE and XYZ. When I send the form as an email, I need these to show up as a similar 4 digit word such as ABCD and WXYZ.

I attempted to do this by setting the "Option Value" as the hidden 4 digit word and then have the actual text show up as "Option Text".

In the email template, I have this printed out as: \[webform\_submission:values:radioButtonName\]

This prints it out as the "Option Text" (ABCDE and XYZ) rather than the "Option Value" (4 digit ABCD or WXYZ) that I am looking for. Is there a way to print the "Option Value" of this radio button instead? I assume its done by changing the word "values" to something else, but I haven't been able to find this.

# Answer
> 1 votes
You need to append the `:raw` suffix to the token and change `[webform_submission:values:radioButtonName]` to `[webform_submission:values:radioButtonName:raw]`.

---
Tags: 8, webforms, tokens
---


# Question
Title: Display an uploaded image in a webform, rather than the filename
**Background**: I'm using the profile module to hold user data but that makes an unpleasant UX for updating user info. So I'm using a single-page webform to offer the editable user data. The user data is provided as default data before it's rendered and the webform does not store information, when submitted the data is copied back to the right profiles and the submission deleted.

**Problem**: The user's profile picture is displayed as the file name, and I want the picture but I can't see any setting for that under the image element. What I get is this:  What I want (with better styling, obviously):

**Is this possible with out-of-the-box webform elements?**

# Answer
You are going to have to either alter the output to the file-link.html.twig template. You can do this by replacing the `link` variable with an image via template\_preprocess\_file\_link.

\- or -

Alter the rendered output of the managed\_file element which is a little more difficult.

---

So I decided to investigate how one would add a preview to the managed file upload element. I realized that most of the needed functionality already existed in the Webform module. I created Issue #3018806: Allow authenticated users to preview file uploads and I should have a working patch in the next day or so.
> 2 votes

---
Tags: 8, webforms
---


# Question
Title: How to dynamically redirect user from /foo/X to /bar/X?
So far I did the following:

1. I've installed *Redirect* and *Token* modules.
2. I've applied the patch for *Redirect* module to support wildcards.
3. I've applied the patch for *Redirect* module to implement `hook_redirect_response_alter`.
4. I've defined the following `hook_redirect_response_alter` to support and parse the tokens.

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

/**
 * Implements hook_redirect_response_alter().
 */
function MYMODULE_redirect_response_alter(RedirectResponse $response, Redirect $redirect) {
  $uri = $redirect->getRedirect()['uri']; // "internal:/bar/[current-page:url:args:last]"
  if (!empty($uri) && strpos($uri, '[') !== FALSE) {
    $uri = \Drupal::token()->replace($uri); // "internal:/bar/"
    $external = UrlHelper::isValid($uri, TRUE); // bool
    $redirect->setRedirect($external ? $uri : explode('/', $uri, 2)[1]);
    $response->setTargetUrl($redirect->getRedirectUrl()->setAbsolute()->toString()); // "http://localhost/bar/"
  }
}

```
5. I've added the following redirect at `/admin/config/search/redirect`:

* From: `foo/*`
    * To: `/bar/[current-page:url:args:last]`

Based on the above, I'm expecting that typing `foo/X` will redirect to `bar/X`, and `foo/Y` to `bar/Y` accordingly, and so on. However, the above token is replaced with an empty string. Similar thing when using token such as `[current-page:url:args:value:2]`, it's not replaced at all. I've also learned here that using `[redirect:url:args:last]` won't work either, as the token is generated based on the entity type, so *Redirect* module isn't aware of it.

I've tried a few more tokens found at `/admin/help/token` which can potentially extract the second argument from the path, but I haven't found any suitable or working as expected for this task.

For example:

---

### More details

Applying `$redirect` context for token's `replace()` method, as suggested in the comments, didn't work as expected.

So the following line:

```
$uri = \Drupal::token()->replace($uri, ['redirect' => $redirect]);

```

populates some token with `redirect` prefix, however it wrongly replaces the current path, e.g. `[redirect:url:args:join:/]` becomes `admin/config/search/redirect/edit/25` for every page.

I've also tried to populate context for the `current-page` tokens, but it was requiring the current path exists, however during redirect the current path doesn't exist in the menu routing table, so it can't be loaded (I've tried `Url::createFromRequest()` and `\Drupal::request()`).

---

### Question

What I'm missing? Is there any easier way to achieve the same thing?

# Answer
> 2 votes
Since passing context for token's `replace` method didn't work as expected, I've defined a new token in my custom module to return the specific components of the Drupal path (using the following guide).

### `my_redirect.tokens.inc`

```
<?php

/**
 * @file
 * An include file defining custom tokens.
 */

use Drupal\Core\Render\BubbleableMetadata;

/**
 * Implements hook_token_info().
 */
function my_redirect_token_info() {
  $type = [
    'name' => t('Custom URL token for redirect'),
    'description' => t('Tokens helpful for redirect pages.'),
  ];

  $node['url-arg'] = [
    'name' => t("URL Argument"),
    'dynamic' => TRUE,
    'description' => t('Returns a component of the current Drupal path.'),
  ];

  return [
    'types' => ['my_redirect' => $type],
    'tokens' => ['my_redirect' => $node],
  ];
}

/**
 * Implements hook_tokens().
 */
function my_redirect_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {

  $replacements = [];

  if ($type == 'my_redirect') {
    if ($argTokens = \Drupal::token()->findWithPrefix($tokens, 'url-arg')) {
      foreach ($argTokens as $arg => $original) {
        $current_path = \Drupal::service('path.current')->getPath();
        if ($arg === "first") {
          $value = explode('/', $current_path)[1];
        }
        elseif ($arg === "last") {
          $value = end(explode('/', $current_path));
        }
        else {
          $value = explode('/', $current_path)[$arg ?: 0];
        }
        $replacements[$original] = $value;
      }
    }
  }

  return $replacements;
}

```

So after applying already mentioned patches, and above code, I can use the following Redirect rule:

* From: `foo/*`
* To: `/bar/[my_redirect:url-arg:2]`

---
Tags: 8, redirection, tokens
---


# Question
Title: Should modules be in source code management?
I am new to Drupal and I am using Drupal 7.61.

Should the Drupal modules folder be git ignored or included in the source code management for best practices and continuous integration sake?

# Answer
As Jaypan and leymannx say in the comments above, if you use Composer to manage dependencies, you can just include `composer.json` and `composer.lock` in your version control repository. Then you can use Composer to rebuild your project when you deploy. This has the advantage of keeping all third party code out of your repo.

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

The documentation linked above shows how to use Composer to install Drupal core, contrib modules, and even patches and libraries.

This approach is the emerging standard. But it has its pros and cons. Here are some Drupal and Composer "gotchas" to look out for:

https://www.jeffgeerling.com/blog/2017/composer-and-drupal-are-still-strange-bedfellows

If you *don't* use Composer, it's probably a good idea to keep core, contrib, patches and libraries in version control.
> 2 votes

# Answer
For Drupal, it is best practice to add settings.php, public, and private files to the `.gitignore` file like as following:

```
# Ignore configuration files that may contain sensitive information.
sites/*/settings*.php

# Ignore paths that contain user-generated content.
sites/*/files
sites/*/private

```

You can learn more about source code management by using git from here:
https://www.drupal.org/node/803746
> -2 votes

---
Tags: version-control
---