# Question
Title: How to set additional node type options programmatically?
When creating a node type programatically, *some* node type options can be set in `hook_node_info`, including `name`, `base`, `description`, `has_title`, `title_label`, `has_body`, and `help`. As far as these node options go, using `hook_node_info` is cleary the canonical way of doing it.

However, some additional node type options *cannot* be set using this hook, and I have not yet found any *canonical* documentation that explains how do do this.

The options I look for a method of setting programatically include:

* whether commenting by default are open or closed;
* whether the node should be published, promoted, sticky and/or have revisions enabled upon creation;
* whether it should display author and date information.

The solution I *currently* use is to set the appropriate database variables in `hook_install` for the module that creates `my_nodetype` to the defaults I want, e.g.:

```
variable_set('comment_my_nodetype', COMMENT_NODE_CLOSED);
variable_set('node_options_my_nodetype', array('status','promote'));
variable_set('node_submitted_my_nodetype', FALSE);

```

I figured out this solution by reading the source code to discover that these database variables determine behavior at runtime. I've not found documented anywhere how one *should* go about setting these additional node type options.

Is there a *better* way of doing this than the improvised soluton I currently use?

# Answer
> 2 votes
> Is there a better way of doing this than the improvised soluton I currently use?

I don't think so. Also I don't find it improvised.

---

Here's a D7 module I once made that creates a new content type: https://github.com/leymannx/drupal-personality-test/blob/master/personality\_test.install

```
/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  node_types_rebuild();
  $types = node_type_get_types();

  // Add a body field
  node_add_body_field($types['MY_CONTENTTYPE']);

  // Add custom fields
  add_custom_fields();

  // Default to not to be promoted
  variable_set('node_options_MY_CONTENTTYPE', array('status'));

  // Disable comments
  variable_set('comment_MY_CONTENTTYPE', COMMENT_NODE_CLOSED);

  // Hide date and author information
  variable_set('node_submitted_MY_CONTENTTYPE', FALSE);

  // Disable node preview
  variable_set('node_preview_MY_CONTENTTYPE', 0);

  // Disable menu entry
  variable_set('menu_options_MY_CONTENTTYPE', array(0));
}

```

I experienced just the same and solved it exactly like you via `hook_install`. If I remember it right, I probably found the code in core when looking how the `article` and `page` node types get created.

---

Related: How to set node type options programmatically (where another tiny module gets recommended you'd need to have everything together in `hook_node_info`).

---
Tags: 7, nodes
---


# Question
Title: Is there a reliable autosave function for nodes?
We're working with dirty forms to at least warn users before they leave an unfinished page before they save. It kind of works. Would enabling revisions control work? At least in that case an admin could recover the last version. Is there an automatic autosave ... say every 30 sections -- to be sure work is properly saved even if the user forgets to hit save?

# Answer
Autosave

> The Autosave module automatically saves a snapshot of your content type form using AJAX. If the user's browser or machine dies while editing a node; the edits will be presented to the user the next time they return to the node. The user may toggle back and forth between the last saved version and the version with the edits that were lost and select which of these they would like to continue with.
>
> How often a form is autosaved as well as which content types to enable autosave for are admin configurable.
> 5 votes

# Answer
There is a Drupal 8 module: Autosave Form

We have tested it. It basically works, but is not stable and has open bugs for complex forms.

> The "Autosave Form" module provides an autosave feature for all forms (entity forms inclusive). Currently the autosave submit will be triggered every 60 seconds, but this approach might be exchanged later through a solution listening for DOM changes.
> 1 votes

---
Tags: forms, nodes
---


# Question
Title: How can I translate months of date field?
How to translate date field in Drupal 8?

I am not able to figure out how to translate **months** of date field into french language .

I have created a view of content **news listing** in which news content are listed, i have added date field from backend with custom date format (22 may, 2018) in views,enabled translation for date field also created custom date format for both languages, but month are showing in default language english.

By default its showing in english language (jan,feb,march....).

So I just want to translate the months of date fields into french language like April=avril , I am using default core translation module that is provided by Drupal 8.

# Answer
> 5 votes
You're not supposed to do this yourself.

What you need to do, is to enable the core **Language** and **Interface translations**, select French as the site's language, and update the site's tranlations (this will take some time if its the first time you do this). After doing all that, all long date fields should display the month names in French.

This is how it looks at my siste:

---
Tags: 8
---


# Question
Title: REST GET ResourceResponse returns encoded json
I have a decoupled drupal project with an angular 5 front end that is utilizing a restful api to store data. Because this API needed a key that we didn't want to expose we have created a restful endpoint in the Drupal code that acts as a sort of proxy. The front end hits Drupal, Drupal adds the key, hits the api, and then Drupal returns the api's response to the front end.

When I hit the API directly, I get clean JSON:

```
{"total":610,"results": .....

```

But when I use the proxy, I get encoded json:

```
"{\u0022total\u0022:610,\u0022results\u0022:[{\u0022_id\u0022:\u .....

```

My Angular request:

```
get(): Observable<RecipePreview[]> {
    let encryptedAuthorizationString = 'BLAHBLAHBLAH';
    const headers = new HttpHeaders()
        .set("Content-Type", "application/json")
        .set("X-CSRF-Token", this._HttpServiceService.csrfToken)
        .set("Authorization", "basic " + encryptedAuthorizationString)
    ;

    let u = this.filter.url();

    return this._http.get(u,{headers})
        .map(res => {
                return res;
            }
        )
    ;
}

```

The Drupal RESTful endpoint code looks like this:

```
/**
 * Responds to entity GET requests.
 * @param $data
 * @return \Drupal\rest\ResourceResponse
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
public function get() {
    $url="BLAHBLAHBLAH";

    $client = \Drupal::httpClient();
    try {
        $request = $client->request('GET', $url, [
            'headers' => [
                'Content-Type' => 'application/json',
                'apikey' => "BLAH-BLAH-BLAH"
            ],
        ]);

        $file_contents = $request->getBody()->getContents();
    }
    catch (RequestException $e) {
        //An error happened.
        $file_contents = "There was an error.";
    }

    \Drupal::logger('Proxy API')->debug($file_contents);

    return new ResourceResponse($file_contents);
}

```

I'm pretty sure that ResourceResponse is doing something to the json, and there has got to be a way to tell it to not do it anymore? But how? Thoughts?

I'm also using the same final end point in a drupal content migration from source and I believe this formatting is causing issues with that as well.

Thanks so much for helping me out with this!

# Answer
Kevin was on to it. It was being double encoded. I have to return a response, so I decode the results from the first api, then return it as a json response:

```
return new JsonResponse( json_decode($file_contents) );

```
> 0 votes

---
Tags: 8
---


# Question
Title: Pass variables from controller to existing node template file
In the Drupal 8 documentation I have found a way how to pass variable from controller to custom twig template

https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-from-custom-module

test\_twig.module

```
function test_twig_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'variables' => ['test_var' => NULL],
    ],
  ];
}

```

TestTwigController

```
class TestTwigController extends ControllerBase {
  public function content() {

    return [
      '#theme' => 'my_template',
      '#test_var' => $this->t('Test Value'),
    ];

  }
}

```

But is there a way to pass variables from controller to already existing node template, for example to node--custom\_content\_type.html.twig

# Answer
> 0 votes
I believe that node--custom\_content\_type.html.twig is referring to template overriding. In template overriding, you are still using the default theme with it's defined variables. If you are generating the render block in your controller, you can set the variables defined in the default theme. These are generally listed in the default template.

An alternative to passing variables into templates is to use the specific theme preprocess hook.

Finally, if you set up your local site to deal with debugging twig, you will see information about the template and available hooks for various parts of the output. See the docs for how to set this up.

# Answer
> 0 votes
Your custom controller is not a node so it doesn't make sense why you would pass custom values to a node template. If you are wanting to override a node itself then you would look into hook\_preprocess\_node and providing that value in the template through that means.

---
Tags: 8, theming, page-controller
---


title: Pass custom variable to block.html.twig

text:
# Question
Title: Pass custom variable to block.html.twig
I have a customer who requires the correct set of responsive classes for his block in a given theme depending on its position and count. In my `theme_preprocess_page(&$vars)` I can identify the blocks in this region and build up an array for each block using its plugin\_id and save it to `$variables['highlighted']`.

In my **page.html.twig** I use `{{ highlighted }}` and the array shows up wonderfully. Because **block.html.twig** by default is set up to be looking for `{{ plugin_id }}` I expected that I can test if plugin\_id is `in_array()` and add these classes to that instance of the block.

But `{{ highlighted }}` in **block.html.twig** returns null in this theme, suggesting that `$variables['page']` works for the page, but not block? Twig has a way to pass off variables to an arbitrary twig file but I do not know how to do this in Drupal. For instance, my **page.html.twig** is using `{{ highlighted }}` to pull in these blocks from `$variables`.

**So my question is how does Drupal 8's adaptation the Twig source determine which variables are passed (plugin\_id, content, attributes, id, etc) and how I can add mine?** I've looked through the twig.engine and searched the Twig source, but it's not clear to me which class controls what variables are passed to blocks? My other avenue is to find a way to pass this array of classes to `theme_preprocess_block` but every attempt I made to try this ends up with `theme_preprocess_block` returning NULL for this array, suggesting that `preprocess_page()` and `preprocess_block()` are working separtely.

# Answer
> 0 votes
You will need to preprocess the block instead of the page. Preprocessing pages will not pass a variable to the block. See hook\_preprocess\_block. If you are needing to determine values based on how many times a block is rendered you can look into using drupal\_static to store variables that can be reused during the rendering process.

Drupal static example:

```
$first_row = &drupal_static('first_row');

if ($first_row == 2) {
  // I equal 2
}

// Since I am passed by reference I can alter and will keep my value.
$first_row++;

```

---
Tags: theming
---


# Question
Title: Display a Media Entity Image from other (referencing) node in a Twig template
Seems that all found in the Internet does not work for my case. :/ In general, I need to display an Image and a Project, referenced by the node that has a reference field to my node.

I have:

* a node of CT Idea (here I want to display my content)
* a node of CT Example, which has:

1) a ref field to Idea 2) a ref field to a Media, Image 3) a ref field to a CT Project

I want to display Examples on an Idea page, each Example displays: Description, Image, Project link

I've managed to display the Description, but can not display Image and Project.

Here is the code

in the `*.theme` file:

```
function showcase_lite_preprocess_node__idea(&$variables) {
  $current_node = $variables['node'];
  $current_node_id = $current_node->id();

  $query = \Drupal::entityQuery('node');
  $query->condition('type', 'example');
  $query->condition('status', 1);
  $query->condition('field_example_ideas', $current_node_id);
  $nids = $query->execute();
  $relatednodes = Node::loadMultiple($nids);

  if (!empty($relatednodes)) {
    foreach ($relatednodes as $related_node) {
      $related_node_image = $related_node->field_example_image->value;
      $related_node_description = $related_node->field_example_description->value;
      $related_node_project = $related_node->field_example_project->value;

      $variables['related_node_image'] = $related_node_image;
      $variables['related_node_description'] = $related_node_description;
      $variables['related_node_project'] = $related_node_project;
    }
  }
}

```

In the `node--idea.html.twig` file:

```
{% block content %}
    {{ content }}
    {{ related_node_description }}
    {{ related_node_image }}
    {{ related_node_project }}
{% endblock %}

```

This displays only the Idea content and the Example Description.

It seems to me that the problem is that the format of `$related_node_image` and `$related_node_project` does not correspond to what Twig is expecting. But I can not check what is inside the variable, because Kint gives an error of memory limit.

Drupal version: 8.5.3.

# Answer
To get a renderable output for Twig use EntityViewBuilder::viewMultiple()

```
    $variables['related_nodes'] = \Drupal::entityTypeManager()
      ->getViewBuilder('node')
      ->viewMultiple($relatednodes, $view_mode, $current_node->language()->getId());

```

and configure the three fields in the view mode you've specified here.
> 2 votes

# Answer
Does this necessarily need to be done in Twig? As you can achieve this without any coding with just field formatters and view modes. It will even cover the publication status.

Apart from that, you don't need to fire a query to get the referenced node IDs. You already have the node IDs as `target_id` in the reference field's values.

```
$nids = [];
if (!$node->field_example_ideas->isEmpty()) {
  $references = $node->field_example_ideas->getValue();
  foreach ($references as $reference) {
    $nids[] = $reference['target_id'];
  }
}
// This will give you all node IDs.
ksm($nids);

```

---

Approach without any code:

You have content type `A` and content type `B`. Content type `A` has a node reference field, referencing content type `B`. Content type `B` has an image and now - for simplicity - let's say you want that content type `A` only displays the image and nothing else of content type `B`.

1. Go to Structure \> Content types \> `B` \> Manage display tab \> and add a new view mode (on the very bottom), or use an existing one, let's say `Teaser`. There you hide all fields except the image field.
2. Go to Structure \> Content types \> `A` \> Manage display tab \> and here for your reference field choose "Rendered entity", then click on the small gear icon and select a view mode. Now it should say "Rendered as Teaser".
3. Done :)

---

### Avoid editing templates when it can be done from the UI

There are other alternatives as well, codeword "Pseudo Fields", that prevent using templates to override the UI and therefore make the UI useless in the end. Drop a comment, if the above isn't sufficient.
> 1 votes

---
Tags: theming, entities, media
---


title: How many times each value was selected?

text:
# Question
Title: How many times each value was selected?
I have a content type with 6 select-list fields. Each field has several available values, multiple selections allowed via checkboxes. A group of users each submit the content once.

**Select List Field 1**

```
user001 answered     | user002 answered     |user003 answered
1|oranges            | 1|oranges (x)        | 1|oranges (x)
2|apples (x)         | 2|apples (x)         | 2|apples
3|bananas (x)        | 3|bananas            | 3|bananas
4|mangos             | 4|mangos (x)         | 4|mangos (x)

```

**Select List Field 2**

```
user001 answered     | user002 answered     |user003 answered
1|eggs               | 1|eggs (x)           | 1|eggs (x)
2|fish (x)           | 2|fish (x)           | 2|fish (x)
3|nuts (x)           | 3|nuts               | 3|nuts
4|berries            | 4|berrries (x)       | 4|berries (x)

```

Views, showing Content of type, contextually filtering on the group id, displays selections from each user in the group. A list of all selected values is shown, including many duplicates.

Apples
Bananas
Fish
Nuts

Oranges
Apples
Mangos
Eggs
Fish
Berries

Oranges
Mangos
Eggs
Fish
Berries

Instead of showing this list (above), I would like to display the number of times each value was selected in total by that group of users.

```
Fish     (3)
Apples   (2)
Berries  (2)
Eggs     (2)
Mangos   (2)
Oranges  (2)
Bananas  (1)
Nuts     (1)

```

I have tried Views aggregation, but so far have only been able to count how many values were chosen for a given field, instead of counting how many times each specific value was selected.

It seems like this should be easy to accomplish, like I am missing something simple. How can I achieve this?

# Answer
> 0 votes
I ended up:

Creating a Content Pane for each question.

Added a duplicate set for each field result in the that pane.

For instance one, I set aggregation to "Group results together", which gave me the labels.

For instance two of that same field, I set the aggregation to "Count", which gave me the number of times that value has been selected.

Excluded the above fields from display.

Added a Global Text field for styling, using the tokens from the above fields for **Label: (Value)**

---
Tags: views
---


title: Test complex method that uses a service

text:
# Question
Title: Test complex method that uses a service
I have a method of a class that returns me the list of fields that have been created outside of core Drupal. The method is the following.

```
/**
   * @param $contentType
   * @return array $fields
   */
  public function getContentTypeFields($contentType) {
    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $entityManager */
    $entityManager = \Drupal::service('entity_field.manager');
    $fields = array();

    if (!empty($contentType)) {
      $fields = array_filter(
        $entityManager->getFieldDefinitions('node', $contentType),
        function ($fieldDefinition) {
          return $fieldDefinition instanceof FieldConfigInterface;
        }
      );
    }

    return $fields;
  }

```

It accepts a content type name and returns an array of fields that aren't the default Drupal fields.

How can I write a unit Test for this method?

# Answer
> 1 votes
Resurrecting this. The first method would be to include the EntityFieldManager as an argument to your function or constructor, so you can send a mock object in.

The second would be to look at some of the tests in core. Specifically core/tests/Drupal/Tests/Core/Config/Entity/ConfigEntityStorageTest.php where the container is mocked and dependencies set up.

```
$container = new ContainerBuilder();
$container->set('entity_type.manager', $entity_type_manager->reveal());
...
\Drupal::setContainer($container);

```

---
Tags: services, testing
---


title: Is the finished callback mandatory?

text:
# Question
Title: Is the finished callback mandatory?
I checked the documentation about the callbacks used from the batch API, but I didn't find any information about the *finished* callback being mandatory or not.

Is that callback mandatory or optional?

# Answer
> 1 votes
Finished callback is a optional function to show a message error, or even save the result.
Drupal core verifies if there is the *finished* callback, so there aren't problems if that callback is not defined.

```
/**
 * Ends the batch processing.
 *
 * Call the 'finished' callback of each batch set to allow custom handling of
 * the results and resolve page redirection.
 */
function _batch_finished() {
  $batch = &batch_get();

  // Execute the 'finished' callbacks for each batch set, if defined.
  foreach ($batch['sets'] as $batch_set) {
    if (isset($batch_set['finished'])) {
      // Check if the set requires an additional file for function definitions.
      if (isset($batch_set['file']) && is_file($batch_set['file'])) {
        include_once DRUPAL_ROOT . '/' . $batch_set['file'];
      }
      if (is_callable($batch_set['finished'])) {
        $queue = _batch_queue($batch_set);
        $operations = $queue->getAllItems();
        call_user_func($batch_set['finished'], $batch_set['success'], $batch_set['results'], $operations, format_interval($batch_set['elapsed'] / 1000));
      }
    }
  }

```

---
Tags: batch-operations
---


# Question
Title: Feeds import - If title has "=" at the end, check whether duplicate content exists
I have an XML to import products to Drupal Commerce site. But some products are duplicates. Duplicate products are having "=" at the end of their title, but NOT all products with "=" at the end of their title are duplicates.

What I need is, on importing XML, check whether product exists, if exist, do not import (easy), if product has "=" at the end of title, check whether product WITHOUT "=" at the end of the title exist. If exist, do not import, else import.

I am totally lost how to do that, should I write some feeds tamper module to handle such a behaviour or go completely outside the drupal and parse XML, compare it to current product database of drupal and export new XML to import to drupal? Any advice would be greatly appreciated!

# Answer
### Set product title as unique

First, you'll need to set the product title as unique. This way, Feeds will only import one product per title.

Is the "=" at the end important to the product title? If not, you'll need to find a way to remove that sign from the product title. This way, Feeds will treat a product title with an "=" as equal to the same product title without the "=".

### Find replace Tamper plugin (D7 and D8)

If you are certain that the sign "=" is only used at the end of the product title (or meaningless if it appears anywhere else), you can use the easiest solution: Use the Tamper plugin "Find replace" to replace "=" with "". This plugin is available for both D7 and D8.

### Find replace REGEX Tamper plugin (currently D7 only)

If the "=" sign can appear elsewhere in the product title and is important there, you'll need to use the "Find replace REGEX" tamper plugin. In the field "REGEX to find", enter a regex that matches strings ending with a "=":

```
/\=$/

```

And replace with an empty string.

### D7 or D8?

At the moment of writing, the Tamper plugin "Find replace REGEX" has not been ported to D8 yet (see https://www.drupal.org/project/tamper/issues/2975179 for the status). If you are using D8 and the Tamper plugin "Find replace" does not suffice, you'll to create a custom module and listen to the Feeds parse event in order to apply modifications on the product titles.

Example:

```
namespace Drupal\mymodule\EventSubscriber;

class ProductFeedSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[FeedsEvents::PARSE][] = ['afterParse', FeedsEvents::AFTER];
    return $events;
  }

  /**
   * Act on parser result.
   */
  public function afterParse(ParseEvent $event) {
    // Check if this is the feed we want to edit.
    $feed_type_id = $event->getFeed()->getType()->id();
    if ($feed_type_id != 'myfeedtype') {
      // Not the feed type we want to edit. Abort.
      return;
    }

    /** @var \Drupal\feeds\Result\ParserResultInterface */
    $parser_result = $event->getParserResult();

    /** @var \Drupal\feeds\Feeds\Item\ItemInterface */
    foreach ($parser_result as $item) {
      // Get product title.
      $title = $item->get('title');

      // Remove "=" sign from the end if there is any.
      $title = preg_replace('/\=$', '', $title);

      // Set title back on item.
      $item->set('title', $title);
    }
  }

}

```

Be sure to replace "myfeedtype" in the example above with the name of the feed type that you created for importing products.

An event listener always needs to be declared in your module's 'services.yml' file:

```
services:
  mymodule.product_feed:
    class: Drupal\mymodule\EventSubscriber\ProductFeedSubscriber
    tags:
      - {name: event_subscriber}

```

In the D7 version, you would need to implement the hook `hook_feeds_after_parse()` to alter the parsed result.
> 1 votes

---
Tags: feeds
---


# Question
Title: Check content type of node in preprocess hook
I have a series of variables I want to make available on twig templates for specific content templates.

In `MYTHEME.theme` I have:

```
function MYTHEME_preprocess_node(&$variables) {

  if (isset($variables['node'])) {

    $mycustomblock = \Drupal::service('plugin.manager.block')
      ->createInstance('myblock', []);

    $variables['mycustomblock'] = $mycustomblock->build();

    $headertext = \Drupal::service('plugin.manager.block')
      ->createInstance('headertext',
        [
          'text-align-submit'  => 'right',
          'uppercase-submit'   => TRUE,
          'header_size'        => 'h4',
          'header-size-submit' => 'h4',
          'grid-size-submit'   => 6,
          'header-title'       => 'This is a test',
        ]
      );

    $variables['headertext'] = $headertext->build();
  }
}

```

This allows me to use `{{ headertext }}` and `{{ mycustomblock }}` in content type templates like `node--contenttype1.html.twig` and `node--contenttype2.html.twig`. But I'd rather not build the `'headertext'` and `'mycustomblock'` variables for every single node type when I only need each one for one content type. It'd be nice to have a switch or if statement that checks which content type it is before generating a variable with a block.

Is there a way that I can check the content type of the node?

I've tried

```
$type = $variables['node']->type;

```

But that did not work.

# Answer
> 18 votes
To get the content type of a node, you just use `$variables['node']->getType()` or `$variables['node']->bundle()`. The first method just calls the second, so calling one or the other one doesn't make much difference.

```
public function getType() {
  return $this->bundle();
}

```

The only difference is that `bundle()` is defined for every entity, since the concept of bundle is common for all the entities, while content type is the property Drupal used for nodes before changing them in one of the entities Drupal core modules implement; using `bundle()` makes easier to adapt the code for other entity types, but I don't think it is the case for the code you are using.

# Answer
> 5 votes
You have to use `$variables['node']->getType()`. Also if you need it on some view modes only, consider doing a check on this as well, with `$variables['view_mode']`

# Answer
> 3 votes
You can add the node (and view type) to your hook function name:

```
function MYTHEME/MYMODULE_preprocess_node__nodetype__display(&$variables) {
  // ...
}

```

For example, for the `page` node type in `full` mode:

```
function MYTHEME/MYMODULE_preprocess_node__page__full(&$variables) {
  // ...
}

```

---
Tags: nodes, 8, hooks
---


title: Cache_page table gets massive

text:
# Question
Title: Cache_page table gets massive
My cache\_page table fills up immensely. I see that the expiry field has values = -1. I assume that means it never expires. Which could be why the table fills up so much.

I wrote a hack to get around this, but would really like to know why this is happening so I can fix the root cause instead of adding a hack?

# Answer
You can set a lower limit than the default 5000 for the number of cache items that are stored in the page cache bin:

*settings.php:*

```
$settings['database_cache_max_rows']['bins']['page'] = 500;

```

See this change record: Database cache bins are now fixed size — no more unlimited growth
> 10 votes

---
Tags: 8, caching
---


# Question
Title: What is the most recent and stable version of Zen theme?
I am searching for the most recent and stable version of the Zen theme.

Any help would be greatly appreciated!

# Answer
For Drupal 7: 7.x-6.4 relased on 2016-06-04.

For Drupal 8 there are only alpha releases, most recent 8.x-7.0-alpha14 released on 2016-06-02.

See: https://www.drupal.org/project/zen (or https://www.drupal.org/project/zen/releases) and https://cgit.drupalcode.org/zen
> 1 votes

---
Tags: theming
---


# Question
Title: Allow markup inside drupal 8 Link function
I always try to use the core functions for linking in drupal, but I'm not able to add html markup like `<a href="..."><span>Link text</span></a>`. Any ideas?

# Answer
> 6 votes
Use the Markup class:

```
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Render\Markup;

$url = Url::fromUri('http://www.example.com');
$linkText = 'My link <br> containing tags';
$linkMarkup = Markup::create($linkText);
$link = Link::fromTextAndUrl($linkMarkup, $url);
$link = $link->toRenderable();

```

# Answer
> 6 votes
If you build a render array for the link you can simply place the html markup in `#markup`:

```
$build['my_link'] = [
  '#type' => 'link',
  '#title' => [
    '#markup' => 'My link <br> containing tags',
  ],
  '#url' => Url::fromUri('http://www.example.com'),
];

```

# Answer
> 0 votes
If this is a Drupal field, I find it easier and cleaner to do it in `hook_preprocess_field`:

```
  if ($variables['field_name'] == 'field_myfield') {
    foreach ($variables['items'] as $key => $item) {
      $variables['items'][$key]['content']['#options']['attributes']['class'][] = 'hl__button';
      $variables['items'][$key]['content']['#options']['attributes']['title'] = t('Visit link for "@title"', ['@title' => $item['content']['#title']]);

      $variables['items'][$key]['content']['#title'] = new FormattableMarkup('<span class="hl__button__text">@title</span>', [
        '@title' => $item['content']['#title'],
      ]);
    }
  }

```

That way you can affect other attributes or add more.

---
Tags: 8, theming
---


# Question
Title: Allowed HTML tags in "Allowed value list" are not working
I'm working on a select list content type which is essentially check boxes with words on one side. The issue appears to be that the html tags I put in that are allowed are stripped out when I go to save. I checked both text formats and it appears that all html is allowed, Any idea where I can look to see why the html is stripped out of the list?

Edit: The allowed values list has tags and I also am testing with a tag, when I save the settings and refresh the view that has these check boxes and text, the text doesn't change according to the html assigned to it. I've looked and text formats (WYSIWYG, HTML, and plain text) do not have the "limit allowed HTML tags" check box checked. So I am not sure why the tags are being filtered out any ideas? thank you.

# Answer
According to your question comments, you are trying to create a form with an options list element using the core select element widget.

This widget is intended for creating select lists. Markup within select list options is considered invalid HTML. That's why the select options widget has a sanitizing function for its option labels, namely OptionsSelectWidget::sanitizeLabel(). This sanitizer is used on each widget settings form submit and cleans your labels from any HTML.

If you really require an options element with HTML in the option labels, you have three choices:

(1) Choose another widget type for the list field that supports HTML markup natively. Obviously you choose the select widget. Choosing checkboxes or radios as widget type in the "manage form view" tab will use the less restrictive satitizing function of the the abstract OptionsWidgetBase class.

(2) If you need an entirely unfiltered list, create a custom field widget for your list field. Make sure to also implement a form element different from select that supports HTML in its labels.

(3) Leave the sanitized labels in the Core widget configuration as is and use hook\_field\_widget\_form\_alter() to add your markup to the labels of the element you intend to replace the Core elements with.
> 0 votes

---
Tags: views
---


title: How to hide the block title?

text:
# Question
Title: How to hide the block title?
We have a block on some pages which we like it without title, but when using \< none \> or leave it blank, it just showing the page title on the block title !

So how can we hide the block title ?

# Answer
> 1 votes
@Rishi answer is perfect for hiding the block-title and it should work.

From your question, I can guess you are confusing the page title with the block title, or you want to hide the page title and the block title.

Let me give you an example. I created a page where I show a simple block with its body (four lines). The page has just its title.

In the following screenshot, I didn't hide the block title, so both the page and block title appear.

>

In the following screenshot, I hide the block title, so only the block body appears, together the the page title. Hence, it looks like the block title is replaced by the page title. Is this your issue?

>

First you need to understand, how pages and blocks work. They are two completly different things.

Now, I placed the trial block in the content region as shown in the following screenshot, which shows the page, with its title and content. After that, it shows the block with its title and content.

>

Hiding the block title setting it to `<none>` in the block configuration page works fine: It hides the block title as shown on the second screenshot from top. At this stage, it looks like the page title takes the place of the block title, and hiding the block title is not working. And that is your question. So, this myth is totally wrong. The page title is there, where it was. The block title got hidden by `<none>`, and the block body is where it should be.

Your question should be how to hide both the page and the block title.

For the block title, you can use `<none>`. For the page title, you need the Exclude node title module, which is the module I used to hide the page title as shown in the following screenshot.

>

The following screenshot shows the page after hiding block and page title.

>

See the differences between the first, second, and fifth screenshot.

# Answer
> 3 votes
In the *Block title* field, use `<none>` to display no title. Go to admin/structure/block/manage/system/main/configure: You will find the following description.

> Override the default title for the block. Use `<none>` to display no title, or leave blank to use the default block title.

# Answer
> 0 votes
Removing the block title is easy, using CSS styles. You can add them with the CSS Editor module.

```
.block-title {
    display: none;
}

```

That will remove all the block titles. So if you want your block to have a custom title, you have to put it in the block, instead of using the block title, or block description when you create your blocks.

---
Tags: theming
---


title: hide empty exposed filters

text:
# Question
Title: hide empty exposed filters
I have a view with an exposed filter that searches nodes for taxonomy terms. For example there are 10 terms but the nodes only use 7 of them. When the view is shown on a page the 10 terms show in the filter. 3 of the terms in the filter will yield zero results. I want to hide those terms (because they have zero results) and not make them available in the filter.

# Answer
You can simply use Views Selective Filters Module for that.

Here is an introduction about this module :

> This module allows to have an exposed filter only show options that belong to result set.
>
> The options are calculated real-time with the current View's configuration, including the filters selected by the user so you get dynamic dependent filters, that is, when the value of one filter is changed, the list of options of the selective filters are updated accordingly to the trimmed down result set.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to shadow a core function used in two different tests files?
I have two tests files with tests that need to shadow the t() function in the Node Revision Delete project, one test file is placed in:

tests/src/Unit/Utility/TimeTest.php

And the other in:

tests/src/Unit/NodeRevisionDeleteTest.php

At this time I shadow the `t()` function with the same code at the end of each test file because the `t()` function is needed to run tests in both files.

```
namespace Drupal\node_revision_delete\Utility;

/**
 * Shadow t() system call.
 *
 * @param string $string
 *   A string containing the English text to translate.
 *
 * @return string
 *   The translated string.
 */
function t($string) {
  return $string;
}

```

When I run each test file all is working fine, but when I run all the project tests I get an error as I have declared the `t()` function twice:

> PHP Fatal error: Cannot redeclare Drupal\node\_revision\_delete\Utility\t() (previously declared in /Users/adriancid/Sites/drupal84-test/modules/drupal.org/node\_revision\_delete/tests/src/Unit/NodeRevisionDeleteTest.php:357) in /Users/adriancid/Sites/drupal84-test/modules/drupal.org/node\_revision\_delete/tests/src/Unit/Utility/TimeTest.php on line 195

The only way that I found to make these works is to pass the tests that need the `t()` function from one test file to the other, but doing this I will have a mix of tests from diferent classes and I won't be able to use the `@covers` section in the test definition.

So, what is the correct way to shadow a core function used in two different tests files?

# Answer
> 5 votes
Wrap it in a !function\_exists()

See core/tests/Drupal/Tests/Core/Render/Element/MachineNameTest.php for example:

```
<?php

namespace Drupal\Core\Render\Element;

if (!function_exists('t')) {

  function t($string, array $args = []) {
    return strtr($string, $args);
  }

}

```

That said, t() as a specific example is deprecated and should not be used in classes, use the StringTranslationTrait/service instead and you can actually inject it.

---
Tags: 8, testing
---


# Question
Title: Field template for display mode of referenced paragraph
I have a custom field `field_platform` (referencing a the custom paragraph type `platform`) and a template for my field: `field--field-platform.html.twig`. Is there a way to override this for a specific display mode of the referenced paragraph type? I have a mode named `cover_view` for the custom paragraph type `platform` I want to override the field template for.

I found Field template for display mode but the template suggestion is for the display mode of the content, not the referenced paragraph.

Drupal 8.5.6, Paragraphs 8.x-1.3

Thanks in advance!

# Answer
> 1 votes
Implement `hook_theme_suggestions_alter` like in the other answer and you can find everything you need in the `$variables`.

---

The following snippet will add the template suggestion for the view mode of the referenced paragraphs. Note that this will probably only make sense as long as you use *only one* paragraph type OR all multiple paragraph types have the same view mode configured.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_field_alter(array &$suggestions, array $variables) {

  $element = $variables['element'];

  if ($element['#field_type'] == 'entity_reference_revisions') {

    foreach ($element as $key => $value) {
      if (is_numeric($key) && isset($value['#paragraph'])) {

        $paragraph = $value;
        $suggestions[] = 'field__' . $element['#field_name'] . '__paragraph__' . $paragraph['#view_mode'];
      }
    };
  }
}

```

Seems you can implement that from you theme's `*.theme` file as well.

---

I guess the same logic works for any entity (node etc.) reference as well.

---
Tags: 8, theming
---


# Question
Title: Hierarchy in entity reference view display
I have a hierarchical taxonomy vocabulary of page categories:

```
Category A
  - Category A1
  - Category A2
Category B
  - Category B1

```

I would like to list some of them (conditionally) as options on my **Page** content type. For that, I am using an Entity Reference field, with the "Views" reference method.

I created a **Taxonomy view** with the **Entity Reference display** for that, but this way, the categories display as options without hierarchy:

Is there any way to selectively display taxonomy terms as field options on a content type, maintaining the hierarchy?

# Answer
I just came across this question, because I had the same issue. The solution I've found is to use a Relationship; no extra modules required.

1. Add a Relationship and choose "Parent Term". Check on "Require this Relationship" in the dialog box.
2. In the "Filter Criteria" section of the view, add the "Term" field (NOT the "Parent" field\*). If you want, you can choose to show the hierarchy in a dropdown, in prep for choosing the term in step 4.
3. Choose the created Relationship in the "Relationship" field of the filter dialog box.
4. Choose the Parent term in that same filter dialog box (to use your example, say "Category A").

Now your view should output only the children of that parent term. (Again, using your example, if you chose Category A, your view would output:

Category A1
Category A2

\*there is a "Parent" field in the Filter field options, and it seems intuitive to use that, but using that only outputs the top-level hierarchy of the Taxonomy, even when combined with an AND with the Taxonomy field. Maybe a bug?
> 1 votes

# Answer
IMHO, the best module to show hierarchical taxonomy options on a form is Term Reference Tree.

Unfortunately, the D8 version development has stalled out a bit. But it is still useful. I recommend the dev version with the patch from this issue:

Allow to configure widget settings
> 0 votes

---
Tags: views, 8
---


# Question
Title: Migration from source YML: implode all values of each array element nested inside an parent array
We are trying to pull in some data from an outside source that serves JSON.

The structure of said json is like this:

```
[
    {
        "name":"something",
        "desc":"some kind of desc.",
        "tags": [
            {
                "order":"3",
                "displayName":"Tag1"
            },
            {
                "order":"13",
                "displayName":"Tags 101"
            },
            {
                "order":"28",
                "displayName":"Dogs"
            }
        ]
    }, ...

]

```

We want to implode all tags.displayName values into one string. I'll use the body field as an example. In the UI, if you view the content, "body" would be:

```
Tag1|Tags 101|Dogs

```

In the "fields" section of my migration source yml file:

```
name: tagsCollection
label: "tagsCollection"
selector: tags

```

Then, in the process section of the YML file I've tried this:

```
body:
    plugin: concat
    delimiter: "|"
    source:
     - stepsCollection

```

I've also looked into the iterator plugin. Nothing seems to click.

If I do this in the process section of the yml file:

```
body: stepsCollection

```

body will be "Array" in the UX. So it is aware that there is an array in that var.

What am I missing?? Many thanks

# Answer
> 0 votes
The documentation examples of concat plugin use a flat, non-associative array of strings as source, you are trying to concat a nested array of JSON objects. You could try to subprocess your `tags` to only fetch/concat the `displayName` from them

---
Tags: 8, migrations
---


# Question
Title: How to add css class to a field from a select list before rendering?
I have a select list which has the following values where the key values are the same name as the css class name.

List1:

* prim-blue|Blue
* prim-black|Black
* prim-orange|Orange

We also have a text field which is surrounded by the following div tag below. Before the page renders, we want to take the value from list1 and assign it as a class to the div tag. We need assistance in figuring out how to get this to work using a preprocess hook.

```
/*css*/
prim-blue {
   //some attribute
}
prim-black {
   //some attribute
}
prim-orange {
   //some attribute
}

/*field div tag */
<div id="target-element"> <h1> Some text values </h1> </div>

```

Desired results (when page renders):

\**Assume list1 is set to Blue (key: prim-blue)

```
<div id="target-element" class="prim-blue"> <h1> Some text values </h1> </div>

```

Note (to provide more context):

**I am using the paragraph module** which a bundle that has a background color for list1 and the text field. Then on the basic page content type, i added a paragraph field.

Paragraph bundle fields:

1. text (field\_text)
2. background color (field\_bkg\_clr) \<-- the drop down list1

Basic Page content type:

1. Header (field\_pr\_hdr, which is of type paragraph)

# Answer
I have used the Field Formatter CSS class module for the same task. The client wanted to have predefined colors for heading elements in paragraph bundles. I have to admit this seems like an amendable approach, but it worked.

I had set up a vocabulary for the color names list and referenced this in the paragraph bundle as a select list (taxonomy term reference). In the display settings for the field is css-class selected. The format settings are set to target tag = entity.

This results basically in following markup:

```
<div class="entity entity-paragraphs-item paragraphs-item h1-colorclass-red">
    <div class="field-name-field-heading">This is a headline</div>
</div>

```

CSS:

```
.h1-colorclass-red .field-name-field-heading {
    color: red;
}

```
> 1 votes

# Answer
If you are fine with adding the classes to some wrapper all you need is `hook_preprocess_HOOK`.

This one adds the class retrieved from a select list field of the paragraph item to the paragraph item wrapper. I guess that's exactly what Field Formatter CSS Class is doing.

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

  $my_field_name = 'field_MYSELECT';
  $my_paragraph_bundle = 'foo';

  $element = $variables['elements'];
  if ($element['#entity_type'] == 'paragraphs_item' && $element['#bundle'] == $my_paragraph_bundle) {
    foreach ($element[$my_field_name]['#items'] as $item) {
      $variables['classes_array'][] = $item['value'];
    }
  }
}

```
> 0 votes

---
Tags: entities, theming
---


# Question
Title: how to get css "background-color" value from content types
I have a custom type, and I want to set background-color of it,when end user choose the color in add content page, example : set background-color : black , I want get this value from database, and set style in my theme. how to do this?

# Answer
> 1 votes
### Drupal 7

What you can do is have a field or just for an example a simple textfield and you can use `hook_node_view()` or `template_preprocess_node()` to get the color value and use `drupal_add_css()`. An example would be like:

**OPTION 1 - Module layer**

```
/**
 * Implements hook_node_view().
 */
function YOURMODULE_node_view($node, $view_mode) {

  // We check if the user is viewing the node/page in it's full view
  if ($view_mode == 'full' && $node->type == 'page') {

    $field = field_get_items('node', $node, 'field_background_color');

    // Check if the field has a value
    if ($field) {

      $color = field_view_value('node', $node, 'field_background_color', $field[0]);

      // We specify the type to inline and group so it would override any style.
      drupal_add_css("#main-wrapper { background: {$color['#markup']}; }",
        array('type' => 'inline', 'group' => CSS_THEME)
      );
    }
  }
}

```

**OPTION 2 - Theme layer**

```
/**
 * Implements template_preprocess_node().
 */
function YOURTHEME_preprocess_node(&$variables) {

  // We check if the user is viewing the node/page in it's full view
  if ($variables['view_mode'] == 'full' && $variables['type'] == 'article') {

    // Get the node object to be used later
    $node = node_load($variables['nid']);

    $field = field_get_items('node', $node, 'field_background_color');

    // Check if the field has a value
    if ($field) {

      $color = field_view_value('node', $node, 'field_background_color', $field[0]);

      // We specify the type to inline and group so it would override
      drupal_add_css("#main-wrapper { background: {$color['#markup']}; }",
        array('type' => 'inline', 'group' => CSS_THEME)
      );
    }
  }
}

```

# Answer
> 0 votes
As an addition to @Leoland Tan's answer I'd like to mind that probably all that needs to happen here is to add the value of the "Background Color" field as a CSS class to the node. And then do the styling inside your CSS files.

---

### Drupal 7

Inside `template_preprocess_node` you first have to retrieve the corresponding field's value and then add it to the `['classes_array']` of the `$variables` to let that happen dynamically.

In the following sample I retrieve the value of a select list and then add it as CSS class.

```
/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {

  $field_name = 'field_select_list';

  $node = $variables['elements']['#node'];
  $field = field_get_items('node', $node, $field_name);
  if (is_array($field)) {
    foreach ($field as $item) {
      $variables['classes_array'][] = $item['value'];
    }
  }
}

```

Presuming the select list field had `foobar` selected, this is what the node wrapper then looks like:

```
<div id="node-3" class="node node-article node-promoted foobar node-full clearfix" about="/node/3" typeof="sioc:Item foaf:Document">

```

---

### Drupal 8

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

  $field_name = 'field_select_list';

  $node = $variables['node'];
  if ($node->hasField($field_name)) {
    $field = $node->{$field_name}->getValue();
    if (is_array($field)) {
      foreach ($field as $item) {
        $variables['attributes']['class'][] = $item['value'];
      }
    }
  }
}

```

Presuming the select list field had `foobar` selected, this is what the node wrapper then looks like:

```
<article data-history-node-id="5" data-quickedit-entity-id="node/5" role="article" class="contextual-region foobar node node--type-article node--promoted node--view-mode-full clearfix" about="/node/5" typeof="schema:Article" data-quickedit-entity-instance-id="0">

```

---
Tags: theming, nodes
---


# Question
Title: How can I dynamically remove an entity constraint?
I'm working on a single-sign-on module for D8 and would like to disable the password fields on the user edit form, since passwords should be managed by the outside identity provider and not through Drupal.

Drupal adds a "current password" field to the edit page which is required if the user wants to change their email address. I can remove the field easily in a hook\_form\_alter, but there's a form constraint, `ProtectedUserFieldConstraintValidator`, that runs and fails validation if the password field is not filled out.

How can I remove this form constraint dynamically?

Things I've looked at so far:

* In my hook\_form\_alter setting `$form_state->getFormObject()->getEntity()->_skipProtectedUserFieldConstraint = TRUE`. This is a property that this constraint checks and when TRUE will skip it, but changes to the entity here are tossed since `ContentEntityForm::validateForm` rebuilds the entity just before validation.
* Looking at the `BaseFieldDefinition` class to see if there's a way to *remove* an existing constraint, but there are no API methods available to do so.

EDIT: It seems once possible approach is to extend `ProfileForm`, overwrite the `buildEntity` method to set `_skipProtectedUserFieldConstraint = TRUE`, and then tell core to use my forms instead. Thought a downside here is that I'm just disabling the constraint in the context of a form, but not in other contexts where the entity may be updated, like in a REST API.

# Answer
> 4 votes
Validation constraints are plugins with an alter hook: `hook_validation_constraint_alter()` (the hook name can be seen in `\Drupal\Core\Validation\ConstraintManager::__construct()`).

That means you can alter that plugin and replace it with your own class that doesn't do anything, or only under some conditions.

Note that constraint plugins are special, unlike everything else, they consist of two classes, the plugin class is just the definition and strings, and then here is a $classname . 'Validator' class that contains the actual logic. So you need two classes, first the constraint class, `Drupal\yourmodule\Something` and then an overriden version of the Validator as `Drupal\yourmodule\SomethingValidator`.

# Answer
> 0 votes
In this case you could alter base field definitions for User entity and set your custom constraint for password field.

---
Tags: forms, 8
---


title: Views slideshow z-index

text:
# Question
Title: Views slideshow z-index
I have view slideshow setup (with views slideshow module) to display some fields (image, title, node teaser) on very top of content area on front page. Also i have drop-down menu setup (with nice menu module). Now, when menu is expanded it goes over slideshow fields, but when slideshow auto-rotates it then position it self in front of menu and never go back again (until i reload page). I tried to solve this with z-index with no luck.

here is a screen shot when image go in front of menu.

Any one had same problem? Can any one point me in right direction?

# Answer
Try adding a "display: relative" to the outer div that wraps the slideshow.
> 1 votes

# Answer
Update your CSS by setting the position to relative and the `z-index` to `-1`, refer this code:

```
#views_slideshow_cycle_main_special_collection_slideshow-block {
    position: relative;
    z-index: 1;
}

```
> 0 votes

# Answer
Set the z-index of wrapper tags (e.g. .navbar-collapse.collapse) to a value greater then 3.

None of the wrapper tags of the dropwdown menu should have a z-index of less then 4. I set .navbar-collapse.collapse to 20 to get it work.
> 0 votes

---
Tags: views, navigation, theming
---


# Question
Title: Why is redirect after login not working?
I use Ctools Modal to show the login form to users in an overlay. If a user enters right data then he is logged in and the page is refreshed.

**The code:**

```
function login_overlay_menu() {
  $items['login-overlay'] = array(
    'title' => t('Sign in'),
    'page callback' => 'login_overlay_callback',
    'page arguments' => array(),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
  return $items;
}

function login_overlay_callback($js = TRUE){
    ctools_include('modal');
    ctools_include('ajax');
    $form_state = array(
      'ajax' => TRUE,
    );
    $output = ctools_modal_form_wrapper('login_overlay_form', $form_state);
    if (isset($_GET['destination'])) {
        $output[] = login_overlay_redirect($_GET['destination']);
    }
    else {
        $output[] = ctools_ajax_command_reload();
    }
    print ajax_render($output);
}

function login_overlay_redirect($path) {
  global $user;
  if (isset($languages[$user->language])) {
    $options = array('language' => $languages[$user->language]);
  }
  return ctools_ajax_command_redirect($path, 0, $options);
}

```

**The Catch:**

It works well for right data entered at first attempt. However, if a validation fails, then the form is rebuild inside the overlay. and then if the user submits the form, he is logged in but **the page is not refreshed** (which is very important).

When I debugged the JS code I found that the value of `Drupal.settings.ajaxPageState.js` changing is the only difference before and after the validation fail.

Before: it is an object containing list of all js files loaded for that page. After: it is an empty array. `(Array[0])`.

**THE QUESTION**: I am not even sure if this is what causing the error. However if it is, then what may be causing this to happen? OR if not then what may be causing the page refresh to fail?

# Answer
> 0 votes
You can use this hook:

```
/**
* Implements hook_user_login().
*/
function my_module_user_login(&$edit, $account) {
 // $edit is empty with one time login
 if (!empty($edit)) {
   $_GET['destination'] = 'some-url';
 }
 // Or the form id is the password reset form
 if ($_POST['form_id'] != 'user_pass_reset') {
  $_GET['destination'] = 'some-url';
 }
}

```

# Answer
> 0 votes
In case anyone comes here looking for an answer after all this time, I believe the issue was that the JS files were not being correctly attached to the form.

When a cached form is reloaded (which happens after a validation failure) it does not go through all the processing that created it. Any attached files MUST be added using the '#attached' key. https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7.x#attached

Eg. from the ctools documentation:

```
$form['#attached']['js'] = array(ctools_attach_js('auto-submit'));

```

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


title: Create custom URL pattern

text:
# Question
Title: Create custom URL pattern
Using the pathauto module, we could have created custom URL patterns using the `hook_pathauto()`. I could not find any such way to achieve the same in D8.

ref. https://envisioninteractive.com/drupal/using-the-pathauto-api-drupal-module-a-simple-example/

Can someone please explain is this possible in D8 and if so how.

Thanks

# Answer
In Drupal 8, pathauto patterns are configuration entities. You have at least two choices to provide them with your custom module:

(1) Provide your pattern as YAML configurations in your module's `config/install` folder. They will be considered and installed to your Drupal, when your module will be installed. Easiest to create using the UI and doing a configuration export afterwards. Just remove the generated UUID of the pattern.

(2) On run-time or in your install/update hooks, you can use `Drupal\pathauto\Entity\PathautoPattern::create()` or the \Drupal::entityTypeManager() to create them dynamically:

```
$data = [
  'id' => 'my_pattern_machine_name',
  'type' => 'canonical_entities:node',
  'pattern' => 'my-path/[node:title]',
  'weight' => 0,
];
$pattern = \Drupal::entityTypeManager()->getStorage('pathauto_pattern')->create($data);

```

You can then use the returned pattern entity in `$pattern` to add selection conditions (e.g. bundles, language, ...) as required. Don't forget to save the entity afterwards, and - of course - check, if the pathauto module has been installed before or make it a dependency of your custom module.
> 4 votes

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


# Question
Title: How to change title of "Log in" link in account menu for anonymous users?
How to change title of "Log in" link in account menu for anonymous users in Drupal 8? Thanks for any suggestions.

# Answer
> 3 votes
EDIT: mediaashley suggested a much simpler solution of creating a new menu, and using the menu block. Not sure why I didn't think of that.

If you're talking about the default link that appears in the 'User account menu' block. You'll notice that you see the message

> This link is provided by the User module. The title and path cannot be edited.

There are several ways you can work around this. But I think the quickest and simplest would be to make your own custom blocks and put links to the account pages in there manually. First you'll need to remove the 'User Account Menu' block from the block layout. Then click on the 'Custom Block Layout' tab and click 'Add custom block'

From there you can make your own custom link like so

In this example I made a custom link for logged out users. Once you save it you'll have a series of options for conditions on whether the block should be displayed in the visibility section. Click on the role tab and check 'anonymous' if you want this block to show only for logged in users. And make sure you assign it to a region.

Once you've completed this you'll need to repeat the process except for 'Authenticated user's this time.

# Answer
> 10 votes
As described by @Matt in the answer the menu link is provided by the user module and you can simply decide not to use it and build your own links.

The link in the user module is a dynamic link where a menu link plugin generates a different title depending on whether the user is authenticated or not.

To change the title you can replace this plugin class:

```
/**
 * Implements hook_menu_links_discovered_alter().
 */
function mymodule_menu_links_discovered_alter(&$links) {
  $links['user.logout']['class'] = 'Drupal\mymodule\Plugin\Menu\MyLoginLogoutMenuLink';
}

```

and override the method getTitle() with your own content:

*mymodule/src/Plugin/Menu/MyLoginLogoutMenuLink.php:*

```
<?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\user\Plugin\Menu\LoginLogoutMenuLink;

class MyLoginLogoutMenuLink extends LoginLogoutMenuLink {

  public function getTitle() {
    if ($this->currentUser->isAuthenticated()) {
      return $this->t('My Log out');
    }
    else {
      return $this->t('My Log in');
    }
  }

}

```

A third option would be to change the title in an English to English translation, see How do I translate to English?

# Answer
> 1 votes
This was the quickest method for me; I had to run this code inside a custom module.

```
function mymodule_link_alter(&$variables) {
  if ($variables['text'] == 'My account') {
    $variables['text'] = t('Account');
  }
  if ($variables['text'] == 'Log out') {
    $variables['text'] = t('Sign out');
  }
}

```

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


# Question
Title: Checking for existence for a field on an an entity_metadata_wrapper
I am iterating through a field collection, and wrapping the field collection items with an entity\_metadata\_wrapper. I would like to check for the existence of field before calling its `value` method (which results in an error on fields that do not have a value), but I cannot find a way to do so.

```
$field_collection_item = field_collection_item_load($id);
$item_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

// this results in an error if the field_contrib_headshot field is empty
$headshot = $item_wrapper->field_contributor->field_contrib_headshot->value();

```

My current workaround is to use `field_get_items` to see if the field is empty, but i'd love to be able to do this through the metadata wrapper if possible.

# Answer
Simply call the PHP function `isset()`:

```
$headshot = array();
if (isset($item_wrapper->field_contributor->field_contrib_headshot)) {
  $headshot = $item_wrapper->field_contributor->field_contrib_headshot->value();
}

```

EntityStructureWrapper implements the `__isset()` function according the principe of Overloading.
> 27 votes

# Answer
Any time there is an entity reference or field collection, isset() has *never* worked for me. What does seem to work any time we have an entity reference is doing:

```
if($wrapped_entity->entity_reference_field->getIdentifier()) {
  // This code only fires if there is an entity reference or field collection set.
}

```
> 9 votes

# Answer
It looks like you have an `entity_reference` somewhere in there due to the method chaining. But, look at the \__isset() method for EntityStructureWrapper.

Check like:

```
$has_headshot = $item_wrapper->field_contributor->__isset('field_contrib_headshot');

```

and then use an `IF` block to do your logic ...

**EDIT:**

`$has_headshot` is now valid check desired.
> 4 votes

# Answer
```
$wrapper = entity_metadata_wrapper('node', 123);
if($wrapper->__isset('field_middle_name')) {
    // Do something awesome with the middle name.
} else {
    // Don't do anything awesome, they don't have a middle name.
}

```

Entity reference fields and field collections

```
// also check if there is an identifier, __isset alone is not enough!
if ($wrapper->__isset('field_project_number') && $wrapper->field_project_number->getIdentifier()) {
    $number =  $wrapper->field_project_number->field_project_number_complete->value();
    return $number;
}

```

Copied and pasted straight from http://dropbucket.org/node/1201 but seems to be a better example than any other answer so far...
> 1 votes

# Answer
For EntityMetadataWrapper:

If you've got blocks of code running that shouldn't or if you've come across PHP errors look at some of the examples below. This example uses the property nid.

MAY ALL ERROR

```
if ($wrapper->__isset('nid')) {
  $var = $wrapper->nid->value();
}
else {
  // Do something it's FALSE;
}

```

OR

```
if ($wrapper->__isset('nid')) {
  $var = $wrapper->nid->getIdentifier();
}
else {
  // Do something it's FALSE;
}

```

OR

```
if ($wrapper->nid->value()) {
  // Do something it's TRUE.
}
else {
  // Do something it's FALSE;
}

```

You may find that using isset like so might evaluate to true even if the nid is not present. The -\>getIdentifier(), or -\>value(), or -\>raw() may throw exceptions.

LIKELY ALWAYS TRUE

```
if (isset($wrapper->nid)) {
  // Do something it must be TRUE....Ah Hem wait.. this runs every time.
}

```

USE THIS INSTEAD

```
try {
  $var = $wrapper->nid->raw();
}
catch (EntityMetadataWrapperException $e) {
  $var = FALSE;
}

```
> 1 votes

# Answer
I've found that isset() cannot be used on the result of a function call. Since a Boolean is returned with the following statement, I was able to verify that the wrapped element, in fact, had a value.

```
if ( $wrapper->field_media_alternate[0]->value() ) {
  //...valid logic...
} else {
  //...not valid logic...
}

```
> 0 votes

# Answer
People often get this wrong. When you call isset on an entity metadata wrapper, you're checking whether the *entity bundle* supports that property. It has nothing whatsoever to do with the actual value of the field.

There isn't really an independent method for checking whether a value is set. You just have to evaluate value() or, preferably, raw(). (You can also call count() if it's a multi-value field, but raw() will return an empty array so it's not actually required.)

```
$w = entity_metadata_wrapper('node', $nid);
//Start by checking whether the node bundle supports field_entityref_myfield.
if (isset($w->field_entityref_myfield)) {
  //If we called value(), then that would cause the referenced entity
  //to be loaded, whereas raw() just gives us the entity_id if the value
  //is set, and Null if it isn't.
  if ($w->field_entityref_myfield->raw()) {
    //Do some things based on the entity-reference being set.
  } else {
    //Do some other things based on the entity-reference NOT being set.
  }
}

```

To reiterate, raw() is the value you should use to check whether a field exists. It's reliable and computationally cheap.
> 0 votes

# Answer
Here is my personal helper function to get a value from a potentialy not set chain of entity references:

```
function _get_wrapped_value_ifset($wentity, $field_chain){
  $root = $wentity;
  try{
    foreach ( $field_chain as $field_name ) {
      $root = $root->{$field_name};
    }
    return $root->value();
  }
  catch (EntityMetadataWrapperException $e){
    return null;
  }
}

```

$wentity is the wrapped entity , $field\_chain is an array of field\_names like so:

```
[
  'field_reference_from_the_wentity',
  'field_wanted_field_from_the_referenced_entity'
]

```

you may also do:

```
[
  'field_reference_from_the_wentity',
  'field_reference_from_the_referenced_entity',
  ...
  'field_wanted_field_from_the_N_referenced_entity'
]

```

it'll work !
> 0 votes

---
Tags: entities
---


# Question
Title: Adding HTML class attributes to Entity Reference field links in View
I have a view ("Tasks") that pulls in Task nodes, complete with sorting and filtering. Each Task can have multiple nodes attached via the "Related Articles" field (`field_related_articles`). I am trying to loop through each node (which can be a Video, Document, Article, etc.) and assign each link a class name depending on the type.

For example, a "Document" node attached to a Task would display a hyperlink with the `document` class. Video nodes will be `video`, and so on.

Here is my preprocess that is targeting the specific field:

```
function mytheme_preprocess_field__node__field_related_articles(&$variables) {
  $items = $variables['items'];

  foreach ($items as $index => $item) {
    $content_type = $item['content']['#options']['entity']->type->entity->label();
    $class_name = slugify($content_type); // custom function

    $variables['items'][$index]['attributes']['class'] = [$class_name];
  }

}

```

When I inspect the `$variables` array, I see the following, which looks okay to me (but I can't be sure):

As you can see, the `attributes` object now has a `class` value for each `items` value (I have two). However, in the HTML, the classes do not show up:

Is there something I'm doing wrong?

# Answer
So I finally figured out the problem.

I wasn't supposed to touch the `$variables['items'][…]['attributes']` *object*, I was supposed to **create** a `$variables['items'][…]['content']['#attributes']` *array* instead and put the class name(s) there.

Having done so, that now works.
> 0 votes

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


# Question
Title: Render custom block using block.html.twig template
I'm attempting to render a custom content block programmatically (created through the Custom Block Library UI) and I would like the block to render using block.html.twig as it would if I were to place it in a theme region. I have the block placed in a disabled region and I can get the block body field to render programmatically, but it is not wrapped in the usual block template and does not include the block title. I'm using the code to render a "content block" from the accepted answer here: How can I programmatically display a block?

```
$bid = ??? // Get the block id through config, SQL or some other means
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()->
getViewBuilder('block_content')->view($block);
return $render;

```

As I understand it, I need to render the instance of the custom block that I have placed inside the disabled region, so I would expect that I have to use the machine name of that instance. I've done a lot of searching and come up with nothing. It's strange that nobody else seems to want to render the block with the title in the block.html.twig template.

# Answer
> 3 votes
Ok, I was hoping for an answer that didn't involve installing a module because this seems like a simple task, but after some point you just have to give in. The Twig Tweak module can do what I'm asking very easily. After installing, in a template where you want to render the block, add this:

`{{ drupal_entity('block', 'BLOCK_CONFIG_MACHINE_NAME') }}`

where BLOCK\_CONFIG\_MACHINE\_NAME is the machine name of the block you have configured at /admin/structure/block/

This will render the block using `block.html.twig` and will render the title you have configured.

Documentation: https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak

# Answer
> 8 votes
BlockContent is the only entity in Drupal not having a template of its own. So you have to wrap it in a template yourself:

```
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
if ($block) {
  $content = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
  $build = [
    '#theme' => 'block',
    '#attributes' => [],
    '#configuration' => ['label' => 'My Block', 'label_display' => 'visible'],
    '#base_plugin_id' => 'block_content',
    '#plugin_id' => 'block_content:' . $block->uuid(),
    '#derivative_plugin_id' => $block->uuid(),
    '#id' => $block->id(),
    'content' => $content,
  ];
  return $build;
}

```

---
Tags: 8, blocks
---


# Question
Title: Why does updating the description of a custom block not update the block title?
When creating a custom block, an editor is required to complete a description field. The description is then used as the block title (if displayed), as well as being used also for admin purposes on the block layout page.

If the description is later changed, the block title does not update and to do so requires a separate action of also updating the block configuration.

This seems like bad UX and is very confusing for editors.

Is there a valid reason for why blocks work like this?

# Answer
> 2 votes
There isn't really a reason, that's just how it works, the title of the block\_content entity is an internal administrative title and while used as a suggestion for the initial block title, will then afterwards no longer have any effect on that.

You can place the same content block multiple times with different block titles.

While you think it's a bug, someone else might rely on it, it's not something that can be changed now, not by default anyway.

---
Tags: 8, blocks
---


# Question
Title: Issues migrating site config at various points in project lifecycle
Issues migrating site config at various points in project lifecycle

Hi

My team and I have begun a new project for our company using the very latest version of Drupal 8 (version 8.5.6)

We wanted to use config migration in order to carry config changes from one developer across to another seamlessly and across to staging and production environments.

We are in the middle of testing the migration workflow and have run into a problem.

I started off the project by doing a standard Drupal 8 installation. I then did a migrations export (`drupal ce`), committed this to the repository.

My colleague proceeded to install Drupal also, also a standard install, `composer install`, `drush cr` etc., and then pulled the latest changes and ran `drupal ci` and ran into an error, namely:

```
[ERROR] An error occurred while trying to write the config file: "Entities exist of type <em
     class="placeholder">Shortcut link</em> and <em class="placeholder">Shortcut set</em> <em
     class="placeholder">Default</em>. These entities need to be deleted before importing."

```

Prior to this we had an additional issue where Drupal complained about mismatched UUID’s. We got around this by updating his UUID as follows:

Error received:

```
[ERROR] An error occurred while trying to write the config file: "Site UUID in source storage does not match the target storage.

```

Fixed with:

```
drush config-set "system.site" uuid "42e3c541-5ebc-4ec9-a8f0-e8c6ad1ccfb7

```

The above UUID was gained from my installation.

So now we are left with the first error explained above.

We tried deleting the shortcuts manually, as suggested in several places on the internet, but this caused his system to completely break.

I also thought possibly that instead of him doing a clean, standard install at the start of the work that he should have used a snapshot of my initial installation, and when we move the app to staging and/or development it will follow suit that we use backups for the initial setup to ensure the DB is in sync with regard to UUIDs, but I am not convinced this is the correct way to do it.

So, we are a little lost on exactly what is the recommended workflow for migrations, with the view that we will be using the workflow going into production also, e.g. after launch we will want to use config migration export/imports to apply changes made locally.

# Answer
> My colleague proceeded to install Drupal also, **also a standard install**, composer install, drush cr etc., and then pulled the latest changes and ran drupal ci and ran into an error, namely:

Don't do that. Config import/export is meant to be used for the *same* site. That's exactly why the site UUID check exists, that's to tell you that what you are trying to do doesn't work.

Either you need to sync the database or you need to use something like https://www.drupal.org/project/config\_installer to install based on an existing set of configuration.

Usually the process is that content and configuration flow in opposite direction. You have your production site where new content is created, from time to time you want to sync the full DB down to your staging/development and then you have configuration changes that you are creating locally and then deploying to dev/staging/production.

See also presentations like https://events.drupal.org/vienna2017/sessions/advanced-configuration-management-config-split-et-al for example.
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: How to create a node from an other node template?
I would like to have a form for the creation of a node (let's name it news) when you are on the page of an other type of node (let's name it movie). So on /node/31 (of type movie) I would like to have the node content and a form to create a news

I thought about using a Webform but after all it felt like trying to hack the Webform with a trick. Moreover since the form already exists (at path node/add/node\_name), I might be able to reuse it but I don't know if it is really possible.

What should be the right way to do it ? With a webform ? By exposing the form for the specific node ? By creating a custom form ? Maybe an other solution I didn't think about ?

# Answer
Use Form Block

> Enables the presentation of user registration, site wide contact, or **node creation forms** in blocks

Select your content type for the form. Place block in region and for visibility select the other content type.

If you rather render the block using a template file, ex: node--movie.html.twig you can use Twig Tweak and print it out using `{{ drupal_block('block_id') }}`
> 1 votes

# Answer
That's actually a task for Inline Entity Form.

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced.

It will simply add some widgets for entity/node reference fields that then let you create and edit the referencing entities/nodes in a node form.
> 1 votes

# Answer
You may try `drupal_entity_form` provided by the Twig Tweak module.

```
{{ drupal_entity_form('node', values={type: 'news'}) }}

```
> 0 votes

---
Tags: 8, nodes, forms
---


title: How do I include a React app?

text:
# Question
Title: How do I include a React app?
We are moving towards a hybrid-headless model with Drupal 7. All our data is exposed through RESTful and I have successfully built React app using the data.

How can pull that app in as a block? I put the code in a block and the app loses much of its styling and 1 third of the data is hidden. The basic functionality still works, but that's not enough.

Is there some trick to getting the a the full app to run correctly in a block?

Thank you

# Answer
> 3 votes
I solved this as follows:

1. install react-app-rewired: npm i --D react-app-rewired -- this is important so you don't try to load react more than once
2. change package.json so build executes react-app-rewired build -- full instructions here: https://github.com/timarney/react-app-rewired
3. Pick a spot in your Drupal install for your react app -- I chose sites/all/react, it seemed right to me
4. load react into your template using the CDN links https://reactjs.org/docs/cdn-links.html
5. update package.json with homepage for your app to reflect where you are saving it for example: "homepage": "/sites/all/libraries/myapp/",
6. build your react app and copy the contents of the build folder to the location you chose for storing your app
7. build a simple module to load your app as a block (code below)
8. add the block to your page however you see fit

```
/* Adds the block to the block menu */
function my_app_block_info() {
  $blocks['my_react_app'] = array( //a new array for each new app
    'info' => t('My React App'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

```

/\* set the content for the block \*/

```
function my_app_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'my_react_app': //a new case for each new app
        $block['content'] = file_get_contents(libraries_get_path('appfolder').'/index.html');

        break;
     }
  return $block;
}

```

```
 /*
   file_get_contents loads the index.html page that loads
   the react app don't use libraries_get_path if you saved your app
   somewhere else
 */

```

---
Tags: blocks
---


# Question
Title: How to change views field value using a hook
I want to change `drupal 8` views field value before displaying. I am using below `hook_views_pre_render`

```
function MYMODULE_views_pre_render(ViewExecutable $view) {
  if ($view->id() == "demo1" && $view->current_display == 'page_demo1') {
     foreach($view->result as $value){
      $value->_entity->set('created', $value->_entity->get('created')->value . '-' .($value->_entity->get('changed')->value - $value->_entity->get('created')->value));
     }
  }
}

```

I want to time difference between `created` and `changed` date time.

but its not working...

# Answer
> 5 votes
You can convert them to int and work with them as integers. For example if you want to set `created` to `changed - created`. Here is a working example:

```

use Drupal\views\ViewExecutable;

function MYMODULE_views_pre_render(ViewExecutable $view){
  if ($view->id() == "views_id" && $view->current_display == 'view_display') {
    foreach ($view->result as $value) {
      $created = (int) $value->_entity->get('created')->value;
      $changed = (int) $value->_entity->get('changed')->value;
      //- If you want for example to set created time with changed -
      created.
      $value->_entity->set('created', $changed - $created);
    }
  }
}

```

---
Tags: views, 8
---


title: How to resolve File to Patch issue?

text:
# Question
Title: How to resolve File to Patch issue?
We are trying to apply a patch to a core module using Applying patches after updating Drupal core to 8.5.6. When running `patch -p1 < patchname-issuenum-version.patch` command, we get the following.

We tried entering `/core/modules/some/path/file.php` but that did not work. I ran the command from the `/core/modules/some/` directory, which is the module's root folder.

How do we resolve the `File to Patch` issue?

```
$ patch -p1 < patchname-issuenum-version.patch
(Stripping trailing CRs from patch; use --binary to disable.)
can't find file to patch at input line 5
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/core/modules/some/path/file.php b/core/modules/some/path/file.php
|index cb2e5754a..12354789 11111
|--- a/core/modules/some/path/file.php
|+++ b/core/modules/some/path/file.php
--------------------------
File to patch:

```

# Answer
> 2 votes
You need to run `patch -p1 < patchname-issuenum-version.patch` from the directory containing the *core* directory, not from core/mdoules/some/ or core/modules/some/. (I take *core/mdoules/some/* is a typo in the question body.)

Patches for Drupal core are created from the Drupal root directory, so when you apply a Drupal patch, you need to change directory to that one.

---
Tags: 8, version-control
---


# Question
Title: Prevent Quick Editing on certain DOM elements
I want to enable quick edit within a block which contains some JS libraries (such as slick). As slick changes the DOM, when I use quick edit it saves this altered DOM and then the slick library doesn't work.

Simplified example:

**Saved HTML (pre-page load)**

```
<div class="slick">
  <li>
    <ul>Tile 1</ul>
    <ul>Tile 2</ul>
  </li>
</div>

```

**Rendered HTML (page loaded)**

```
<div class="slick">
  <div class="slick-magic etc">
  <li>
    <ul>Tile 1</ul>
    <ul>Tile 2</ul>
  </li>
  </div>
</div>

```

As the slick JS code adds the extra DOM content, when the user saves something via quick edit, the extra DOM content is saved to the page. Subsequently, when slick is rendered again by the JS, we get a slider that doesn't work.

Is there a way to prevent quick edit from applying changes to anything within `<div class="slick">`? Alternatively, is there a place where I can use slick's `destroy` method to the object before the block changes to edit mode?

Note:

* Have tried using Bootstrap's carousel which doesn't alter the DOM but the functionality is too limited to match what slick can provide

**Edit:**

The JS object resides within a block. I still need to use quick edit to edit the block, but also to protect the JS object

# Answer
> Is there a way to prevent quick edit from applying changes to anything within

A quick fix is you can write a small jQuery snippet which gets trigger after QuickEdit apply its DOM changes. For example, suppose I do not want to allow quickedit on any node, i.e. it can be full display or teaser. Below code will find all `article` tags on page and remove its `data-quickedit-entity-id` attribute, so quickedit option won't be available for it.

```
$('article', context).removeAttr('data-quickedit-entity-id');

```
> 0 votes

---
Tags: 8, javascript, entities
---


# Question
Title: How do I set permissions for a subdirectory that Drupal creates when uploading a file?
I'm using Drupal 8 and the Flysystem module to configure remote file storage via SFTP. My question probably applies in general, though.

When a file is uploaded, and the file directory setting has a value, then Drupal creates a subdirectory if it doesn't already exist in the remote location. For example, the file directory defaults to \[date:custom:Y\]-\[date:custom:m\] to organize files by month. I need to set the permissions of these subdirectories. Currently, they're defaulting to 744. How do I change this? I'm hoping there is either a global setting, a hook, or a way to set the permissions in a module.

Thank you in advance for your help!

# Answer
A standard Drupal would use Core's FileSystem class to create directories and set permissions according to the `file_chmod_directory` setting, which you can adjust within your site's `settings.php` files:

```
/**
 * Default mode for directories and files written by Drupal.
 *
 * Value should be in PHP Octal Notation, with leading zero.
 */
# $settings['file_chmod_directory'] = 0775;
# $settings['file_chmod_file'] = 0664;

```

It defaults to 0775 and is therefore commented out in a regular installation.

However, you mentioned using the Flysystem stream wrapper module. A short look into it's code reveals, that it is indeed using the FileSystem::CHMOD\_DIRECTORY constant as default for local files. But the final directory permissions can vary depending on the Flysystem adapter plugin you are using. Something that is out of our control here at Drupal Answers. It's a contrib module anyway. So you will have to check yourself, of whether your adapter plugin supports the Core setting values/allows to configure it by other means. If not, you may wish to file an issue against the module that is providing the adapter you are using.
> 6 votes

---
Tags: files
---


# Question
Title: Form Submit Handler not firing on Page Reload with GET parameters
I have a simple form

```
function example_form($form, &$form_state) {
  $form['#attributes']['method'] = 'get';
  $form['button'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  $form['search'] = array(
    '#type' => 'textfield',
    '#required' => FALSE,
  );

  return $form;
}

```

and a submit handler

```
function example_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  drupal_set_message(t('Form Submitted'));
}

```

When I click the button, the form submits properly and the URL gets all the form parameters.

but when I reload the page with all those URL parameters, the `example_form_submit()` is not firing, how do I make my form submit/fire the submit hook when the URL is reloaded with GET parameters?

# Answer
The correct way to change the method to be used by a form is to use the `#method` element rather than by setting the attribute, as otherwise the form API will still expect to be triggered by a POST.

https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7.x#method
> 1 votes

---
Tags: views, hooks
---


# Question
Title: Contextual Filter not working wiht URL aliases
I have this issue with contextual filter. I have set the filter so it would get an ID of an article and based on that ID, it would show the name of the author. The problem is, it doesnt work with URL aliases. For example, when I put the ID of the node like **example.com/node/22**, it finds the author. But when I try to put the URL alias like **example.com/clanky/something-something-something**, it doesnt show anything. Any idea how can I solve this? Thank you for any reply.

# Answer
> 0 votes
Use Content ID from URL instead of Raw value from URL

---
Tags: views, 8, path-aliases
---


# Question
Title: Limit Entity Reference Options depending on one of the referenced content type fields value
I have two content types Cylinder Master and Association. Cylinder Master contains all the cylinder details and an Allocation status field(Allocated/Unallocated). In Association I am referencing the Cylinder Master fields but I want to just display the Unallocated cylinders list. How can I achieve this? Thanks

# Answer
Are you using Drupal 8?

For each content type you can manage the reference type for each field. Setting "Reference method" to "Views: Filter by an entity reference view" you can use different settings for different content types.

First create a view with entity reference list of Cylinder Master content filtered by allocation status, then set the Association content types reference method to use the view.
> 1 votes

---
Tags: nodes
---


title: HTML tags of an article not working

text:
# Question
Title: HTML tags of an article not working
I came across this issue. I wrote an article in editor and I put there basic HTML tags like `<strong>` and so on. The thing is, in editor it shows right, but when I publish the article, the HTML tags dont do anything and they are displayed just like normal text. Do you have any idea why is this happening? Thank you for any reply

# Answer
> 1 votes
i hope , you have used basic html filter. Basic filter doesn't support all of the tags of html. you have to use full html filter instead of basic html.

# Answer
> 1 votes
You need to configure the HTML accepted by the filter in use to match your wysiwyg settings, otherwise you are likely to get mismatches like this, where the editor generates HTML that is filtered out before display, or shown as plain text.

Fortunately the field data stored in the database will include the HTML, so you may be able to fix this purely by adjusting the settings of the filter.

Be careful, though, you also need to consider what different classes of users are allowed to do, so if you have a filter that's available to all users you probably want to keep it restricted in terms of the HTML. Configure (and add) filters and editor settings to match user requirements.

---
Tags: 8, nodes
---


# Question
Title: Twig: "for" does not display variable content without first displaying all variable content
I have found a very strange behavior.

My variable `related_nodes` contains a list of nodes. How it is displayed by Kint:

`related_nodes array(10)
'#sorted' => boolTRUE
'#pre_render' => array(1)
'8' => array(5)
'10' => array(5)
'11' => array(5)
'12' => array(5)
'13' => array(5)
'14' => array(5)
'15' => array(5)
'16' => array(5)`

If I first display the content the variable `{{ related_nodes }}`, it **displays** this all related nodes and then **them one by one in Divs** (with loop index before):

`{{ related_nodes }}
 {% for rel_node in related_nodes[2:] %}

{{ loop.index }} - {{ rel_node }}

 {% endfor %}`

But **when I remove the first display of the variable**: `{{ related_nodes }}`, it **does not display related nodes one by one in Divs** (it displays only the loop indexes):

```
        `{% for rel_node in related_nodes[2:] %}
           <div class="col-md-4 col-xs-6">{{ loop.index }} - {{ rel_node }}</div>
        {% endfor %} `

```

I also have 8 errors like this: " Notice: Undefined index: title in template\_preprocess\_node() (line 616 of C:\Users\Oksana\Documents\sites\drupal2\core\modules\node\node.module)" when the `{{ related_nodes }}` is removed.

When I removed the slice `[2:]`, it did not help.

Is there any need to pre-load a varible before I can iterate in it with the twig 'for'? Or what can be a reason for such behavior?

I need to remove this `{{ related_nodes }}` because it displays all vertically without formating in columns.

Drupal version: 8.5.3.

# Answer
In Twig you could re-use the pre render callback for each single node, see Cycle comments on field--comment.html.twig, but since you are responsible for the content of the twig variable you can do this when preparing the variable by replacing viewMultiple() with multiple view():

```
foreach ($related_nodes as $node) {
  $variables['related_nodes'][] = \Drupal::entityTypeManager()
    ->getViewBuilder('node')
    ->view($node, $view_mode, $current_node->language()->getId());
}

```

Then in Twig you can use a normal loop:

```
        {% for rel_node in related_nodes %}
           <div class="col-md-4 col-xs-6">{{ loop.index }} - {{ rel_node }}</div>
        {% endfor %}

```
> 4 votes

# Answer
Your `related_nodes` variable contains a render array. Once your entire template is rendered, the content of your variable will first be rendered and the rendered output inserted to your template.

The `#pre_render` key can contain a number of preprocessing functions that receive the contents of the render array just before rendering occurs and add additional information to it. This can be caching information, theme wrappers, or any other preprocessing that is required so the render engine knows how to create markup from the array information.

After you rendered the field first, all this information has been added to the render array. That is why you can print the single elements afterwards.

If you don't render your entire render array, you have to ensure that the preprocessing occurs before you loop through the single entities.

The best place to doing so is the hook\_preprocess\_HOOK() of your template, which you can place in your theme's `*.theme` file:

```
use Drupal\Drupal\Core\Render\Element;

/**
 * Implements hook_preprocess_HOOK() for my-template.html.twig.
 */
mytheme_preprocess_my_template(array &$variables) {
  $related_nodes = $variables['related_nodes'];

  if (isset($related_nodes['#pre_render'])) {
    foreach ($related_nodes['#pre_render'] as $callable) {
      if (is_string($callable) && strpos($callable, '::') === FALSE) {
        $callable = \Drupal::service('controller_resolver')->getControllerFromDefinition($callable);
      }
      $related_nodes = call_user_func($callable, $related_nodes);
    }
  }

  $variables['processed_nodes'] = array_intersect_key($related_nodes, array_flip(Element::children($related_nodes)));
}

```

You can then print the single items in your template by looping through the newly added `{{ processed_nodes }}` variable:

```
{% for rel_node in processed_nodes %}
  <div class="col-md-4 col-xs-6">{{ loop.index }} - {{ rel_node }}</div>
{% endfor %}

```
> 1 votes

---
Tags: theming
---


title: PHPUnit Checking file exists failing

text:
# Question
Title: PHPUnit Checking file exists failing
I'm using a Kernel test in Drupal to add a new instance of my custom entity. In the postSave() method of my entity, I generate a PDF using TCPDF. In the browser, this all works well and I can see the generated PDF in my file system. My issue is that when I run PHPUnit from the CLI, it produces my entity fine but it can't assert that the file exists.

```
class CustomEntityAddTest extends EntityKernelTestBase
{

  /**
   * A list of modules to be enabled to run this test
   *
   * @var array
   */
  public static $modules = ['block', 'datetime', 'custom_entity', 'entity_reference', 'file', 'migrate', 'options', 'system', 'taxonomy', 'text'];

  /**
   * The Directory where generated PDFs are stored
   */
  const FILES_DIRECTORY = \Drupal\custom_entity\Entity\CustomEntity::DP_DIRECTORY_BASE;

  public function setUp() {

    parent::setUp();
  }

  /**
   * Undocumented function
   *
   * @return void
   */
  public function testAdd() {

    $custom_entity = CustomEntity::create([
      'user_id' => 1,
      'status' => 0,
      'title' => 'First Test!',
      'inventco' => CustomEntity::generateSubmissionID(),
      'abstract' => 'Test abstract',
      'created' => time(),
      'changed' => time(),
    ]);

    $this->assertInstanceOf(CustomEntity::class, $custom_entity, "An entity was not created");

    $inventco = $custom_entity->get('inventco')->getString();

    // debugging
    $path = "/var/www/drupalvm/docroot/sites/default/files/private/{$inventco}/{$inventco}_frontpage.pdf";
    print_r(scandir("/var/www/drupalvm/docroot/sites/default/files/private/{$inventco}"));
    print($path);
    // Assert DP files exist
    $this->assertFileExists($path, "Generated PDF does not exist");
  }
}

```

How can I assert that the file was produced? I've checked that the filepath is correct.

# Answer
It was because I hadn't called the save method on the `$custom_entity` object.

Credit and thanks to Andy
> 0 votes

---
Tags: 8, testing
---