title: Create a user and set the password

text:
# Question
Title: Create a user and set the password
How can I set up the user password when I create a new user using the Rules module?

# Answer
You can do it by `PHP` rule action, first create a function in your custom module as example

```
function _yourfuction_user_change pass($account,$pass){
    user_save($account,array('pass'=>$pass));
}

```

Then in your rule in action section select `php` action and in it's field enter

```
 _yourfuction_user_change pass($account,'111111'); //your password=111111 and $account = available account parameter in field

```

and another solution is create your on action
> 1 votes

# Answer
Use the Rules Passwords module.
> 1 votes

# Answer
```
$pass = 'static_word_' . rand(10,999); //generates a password like "static_word_734" where the 3 numbers are random.
$edit = array(
'pass' => $pass,
);
user_save($entity_created, $edit); //$entity_created must be replaced with your own variable if you used something else than rules' standard.
//The following part also sets the author of the node to the newly created user.
$uid = $entity_created->uid;
$node->uid = $uid;
$node->is_new = FALSE;
node_save($node);

```
> 0 votes

# Answer
Unfortunately there is no way to create a password with Rules (believe me, I know). What you can do is create the user, and e-mail them the one-time login link with the **\[entity-created:one-time-login-url\]** token so that they can login and create their own password.

HTH,

K.
> 0 votes

# Answer
Make a custom module named "rules\_set\_password" and place this code inside rules\_set\_password.rules.inc, it will add a custom action in rules UI named 'Set a user password', is located at 'user' group, it will prompt you with 'account' object and a 'text' variable to be used to set new password value. Do not forget to add your rules\_set\_password.info file.

```
    /**
 * Implement hook_rules_action_info()
 * Declare any meta data about actions for Rules
 */

/**
 * Custom Rules Actions.
 * https://www.drupal.org/forum/support/post-installation/2011-11-07/creating-user-with-rules-how-to-set-password
 */
function rules_set_password_rules_action_info() {

  $actions['set_user_password'] = array(
    'parameter' => array(
      'account' => array(
        'type' => 'user',
        'label' => t('User'),
      ),
      'new_password' => array(
        'type' => 'text',
        'label' => t('New password'),
      )
    ),
    'group' => t('user'),
    'label' => t('Set a user password'),
    'base' => 'rules_set_password_rules_action_set_user_password',
  );
  return $actions;
}

/**
 * Action: Set a user account password.
 */
function rules_set_password_rules_action_set_user_password($account, $new_password) {
  $edit = array('pass' => $new_password);
  user_save($account, $edit);
}

```
> 0 votes

# Answer
I can't comment yet, or I would put this in a comment. It is not advisable to set user's passwords. The best practice is to send them a one time login link through their email that directs them to set their own password.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Drupal update to specific version (not dev) with git
I have a Drupal folder made with command:

```
git clone --branch 7.x https://git.drupalcode.org/project/drupal.git

```

Now I want to update it to the actual version (7.67). When I run

```
git pull origin 7.x

```

or

```
git pull origin 7.67

```

Every time I get the 7.68-dev version, not 7.67. What am I doing wrong? I know how to get the specific version with composer, but in this situation I need to get it with git pull command.

# Answer
Just to expand on this for future reference:

Releases in git are created as tags. To see the available releases, do the initial pull from the repo, then you can see the available tags with the command:

```
git tag

```

To check out the specific release, do:

```
git checkout [tag-id]

```

You will see a message about previous head and current head.

Check that you are on the correct tag with:

```
git status

```

It should indicate that you are currently in a headless state.
> 0 votes

---
Tags: updating
---


# Question
Title: Making a custom views field handler click sortable (getting an error when clicked)
When I make my custom handler click sortable and subsequently click the label in the table heading of the view I get the following error:

> SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'unknown' in 'order clause'

My handler is defined as below. This is a render only handler that performs a calculation on some other field data and outputs.

UPDATE:

Am I right in thinking that because this data is not stored in the database that I can't make it click sortable because there is no column to order by in the SQL statement that is generated?

Is there a way around this? Any help appreciated.

```
function rate_calc_views_data() {

$data = array();

$data['node']['rate_calc_handler_result'] = array(
    'title' => t('Standard Deviation'),
    'help' => t('Calculates the voting result standard devaition'),
    'field' => array(
      'handler' => 'rate_calc_handler_result',
      'click sortable' => TRUE,
    ),
    'sort' => array(
       'handler' => 'views_handler_sort',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter',
     ),
);  return $data; }

```

# Answer
> 2 votes
This is old, but there is some misinformation here so I thought I'd contribute.

Make sure you expose your pseudo field to Views. **Don't overdo this and confuse yourself, just add what is required.** The handler doesn't need to be defined in here cause you can use annotations.

```
/**
 * Implements hook_views_data_alter().
 */
function hook_views_data_alter(array &$data) {
  $data['shift']['shift_time'] = array(
    'title' => t('Total Shift Time'),
    'field' => array(
      'title' => t('Total Shift Time'),
      'help' => t('Calculates a shift length.'),
      'id' => 'shift_time',
    ),
  );
}

```

My field class is defined like so, note the annotations.

```
/**
 * Field handler for pseudo shift time field.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("shift_time")
 */
class ShiftTime extends FieldPluginBase {

```

Then, in my field class `ShiftTime` I have a clickSort method (NOT click\_sort - must be camelCase!);

```
function clickSort($order) {
  $alias = $this->query->addField(NULL, "(finish_time - start_time)", 'shift_time');
  $this->query->addOrderBy(NULL, NULL, $order, $alias);
}

```

As you can see you can simply write an expression or formula as a field and then sort by that. If you need to you can write an entire sub query.

Some API links;
addOrderBy()
addField()

# Answer
> 1 votes
Because this data is not stored in the database (it's just a dummy field that returns the result of some calculations) you can't make it click sortable as there is no database column to 'order by' in the SQL statement generated by the view.

There must be a way around this but it's likely quite complicated and beyond me at the moment.

If you have a custom handler that does something to change the way you display existing field data you can make it click sortable by overriding the click\_sort($order) function in your handler class.

My mymodule.views.inc now looks like the below (where 'real field' is the name of the field included in the view, before the custom field created by my handler, but excluded from display)

```
<?php

function mymodule_views_data() {

    $data = array();

    $data['node']['mymodule_handler_myname'] = array(
        'title' => t('Score'),
        'help' => t('Makes score values human readable'),
        'real field' => 'value',
        'field' => array(
          'handler' => 'mymodule_handler_myname',
          'click sortable' => TRUE,
        ),
    );

    return $data;

}

?>

```

and my mymodule\_handler\_myname.inc looks like

```
<?php

class mymodule_handler_myname extends views_handler_field {

    /**
    * Loads additional fields.
    */
    function query() {

    }

    function click_sort($order) {

        $this->query->orderby[] = array(
            'field' => 'field_name', // here may be a field, or some SQL clause e.g. FIELD(str, str1, ...)
            'direction' => strtoupper($order),
        );

    }

    /**
    * Renders the field handler.
    */
    function render($values) {

        if (isset($values->field_name)){

            switch ($values->field_name){
                case 2:
                    $vote = 'Yes';
                    break;
                case 0:
                    $vote = 'No';
                    break;
                default:
                    $vote = 'Maybe';
                    break;
            }

            return t($vote);

        }
    }
}

?>

```

This wrecked my head for a full day so hopefully it's helpful to someone in the future.

---
Tags: views
---


# Question
Title: How to filter a node view on a paragraph field
I have a content type "Lunch" containing a paragraph type field named "Ingredients". This is a multiple values field which store a prapgraph type named "Ingedients" =\> Taxonomy term + Quantity

**LUNCH**

|- **Ingredient1** (Term1 reference + quantity1)

|- **Ingredient2** (Term2 reference + quantity2)

I have created a view displaying the tiles of my 3 encoded lunches. Until here, everything is fine.

Now, I would like to add an exposed filter to get all lunches congtaining a specific ingredient. For this I have added a relationship on the ingredient field:

```
Paragraph referenced from field_ingredients

```

Doing this is fine, because now, I can add an exposed filter using this relationship

AND

Doing this is bad, because as soon as I have added this relationship the number of rows in my view has been multiplcated by the number of ingredients... even if I check distinct in the SQL parameters

Any hint to solve this issue?

**EDIT TO ADD**: I could solve this by removing the duplicates in `hook_views_pre_render` but is it really the best thing to do?

**REAL SOLUTION BASED ON prkos ANSWER:**

1-In the advance\>Other section I have enabled the aggregation

2-I have added my Ingredient field in the field section (exclude from display)

=\>This is the taxonomy reference field of my Paragraphs field named "Ingedients". In other words, I have a paragraph type with 2 fields (Ingredient and quantity) and I selected "Ingredient". Do not select the paragraph itself.

3-In the aggregation parameter of this added field, I selected `ID of the entity`

# Answer
> 1 votes
Adding Relationships often causes duplicate rows in the results.

You can "remove" the duplicates using the Aggregation in Views (enable it under `Advanced`).

Then adjust the Aggregation settings for some Fields, specifically the `Group column` option. You may need to change it from `Value` to `Entity ID` or vice versa. The exact combination of settings depends on your particular case, I haven't tried it with Paragraphs.

When duplicates are introduced through Taxonomy reference field that is using a Relationship then all those Taxonomy fields need to have the **Entity ID** and not the `Value`.

If the field is a direct Entity Reference field and isn't using a Relatinship then again it needs to be **Entity ID** instead of, in this case, `target_id`.

Be careful with Sort criteria when using Aggregation, some of them can mess up the Aggregation. It's best to remove all Sort criteria while adjusting the Aggreation, then when you have it working add them and test that everything is still working as expected.

Some modules offer more advanced Aggregation settings, try looking into that if you need to, for example: Views Aggregator Plus,

---
Tags: views, 8, paragraphs
---


# Question
Title: Menu tree from taxonomy terms and nodes which belong to them
i need to create a collapsible menu tree from taxonomy terms and nodes which belong to them (not nested terms, but content pages) i'm totally stuck about it i've found solutions for nested taxonomy terms only, but not for combined with content pages from the term. meaning menu tree like this:

# Answer
> 0 votes
It's very simple to create the tree structure output you're looking for:

1. Create the Content type Views,
2. add the Taxonomy term Field next to the Title field,
3. under `Format` Views settings choose to group by the Taxonomy field `Grouping field Nr.1`

On the Taxonomy field choose `Exclude from display`.

This will give you a list of nodes that are displayed in groups by their taxonomy terms.

To make that structure collapsible you can use some special option for the Format, for example Views Accordion or Views tree.

# Answer
> 0 votes
That's probably an opinion-based thing and actually also a too broad question. But here's what I'd do:

1. Programmatically create a new block.
2. Provide a `hook_theme` and your own template to later render the output the way you want.
3. Follow one answer from How to get all node entities tagged with a specific term? to get the data you need.
4. In the block's `build()` function pass the data to your custom template and build the markup you need.
5. Optional: Improve performance by either storing the data from step 3. in some Drupal variable that can be purged from some admin settings form button click. Or add some custom cache tags that get invalidated as soon as taxonomy or node CRUD operations take place.

---

You probably can achieve what you want with some Views voodoo, and maybe should try that first, depending on your programming skills.

# Answer
> 0 votes
I have a view set up that sounds similar to what I think you are trying to accomplish:

1. Create your **content view** filtering by taxonomy.
2. Create your **taxonomy view**.
3. Go back to your **content view** and use "no results behavior" under "advanced" and insert your **taxonomy view** into your **content view** as a "global view area".

Now where there is no content assigned directly to the parent term, your term view appears displaying child terms. You are basically using parent terms and % arguments in your path to set the depth of the "tree".

You will also have to set your child "term page display" under "manage display" to show the **content view**. It's pretty complicated but VERY functional! I hope this helps!

---
Tags: views, nodes, taxonomy-terms, navigation
---


title: How to get taxonomy term values?

text:
# Question
Title: How to get taxonomy term values?
In my user entity, I have a term reference. In that vocabulary, I have a regular field. How can I fetch that field's value? I tried the below in devel/php to no avail.

```
$user = Drupal\user\Entity\User::load(17);
$dept = $user->field_department->entity;
\dpm($dept->field_administrator_e_mail->value);

```

My end goal is to send the email to the department's administrator when a user is created.

UPDATE: I also tried the below:

```
$user = Drupal\user\Entity\User::load(17);
$dept = $user->field_department;
\dpm($dept->name);

```

# Answer
Your missing link is the `entity` function, which returns the referenced entity object:

`$host_entity->host_field->entity->remote_field->value`
> 0 votes

---
Tags: 8, entities
---


# Question
Title: I want to make a Drupal 8 view with contextual filter
I want to make an intelligent view and want to pass contextual filter. If the contextual filter value is passed in the url so only display the article having the id like `http://example.com/article/2`. So show only the node with the id 2. And If the id not pass so`(http://example.com/article/)` show all the articles. I can do this by creating 2 views **but I want all this in a single view**

# Answer
> 2 votes
Goto **admin/structure/views/add** and add a view like below:

After adding view, go to view edit page and Under "ADVANCED", select "Contextual filters", and add "Content: Id". Under "WHEN THE FILTER VALUE IS NOT IN THE URL" check "Display all results for the specified field". In the same block, under "Exceptions", Exception value should be null. Check below image.

Now if you go to http://example.com/article you will see all the articles. And go to http://example.com/article/123 you will see related article.

---
Tags: views, 8
---


# Question
Title: Is there a way to render a node with view mode via token?
Is there a way to render a node with view mode via token? Like:

```
[node:5:teaser]

```

# Answer
> 3 votes
So the question is how to insert *something like* `[node:5:teaser]` into a formatted text area and get the teaser view of node 5.

This can be done with a combination of modules:

## Token Filter (D7,D8)

> Token Filter is a very simple module to make token values available as an input filter.

So (after adding that filter to the text format), **for the current node**, we can use e.g. \[node:title\] in formatted text.

## Token Entity Render (D7, D8 Issue)

> Provides tokens (\[entity\_type:render:view\_mode\_name\]) that render full entities using view mode specified.

## Advanced Entity Tokens (D7, D8 Issue)

> Through AET you can query the DB for entities using Tokens. Examples: \[aet:node:1\]

## Putting it together

In the end you should be able to use `[aet:node:5:render:teaser]` in your formatted text.

---
Tags: 8, entities, tokens
---


# Question
Title: How can I read config schema from a config entity?
I need to read the schema definition from a config entity, which is located in config/schema. For example the schema from a node type defined in node.schema.yml:

```
node.type.*:
  type: config_entity
  label: 'Content type'
  mapping:
    name:
      type: label
      label: 'Name'
    type:
      type: string
      label: 'Machine-readable name'
    description:
      type: text
      label: 'Description'
    help:
      type: text
      label: 'Explanation or submission guidelines'
    new_revision:
      type: boolean
      label: 'Whether a new revision should be created by default'
    preview_mode:
      type: integer
      label: 'Preview before submitting'
    display_submitted:
      type: boolean
      label: 'Display setting for author and date Submitted by post information'

```

How can I do this?

# Answer
> 3 votes
Found, it can be done by using **config.typed** service:

```
$typed_config_manager = \Drupal::service('config.typed');
$node_type_definition = $typed_config_manager->getDefinition('node.type.*');

```

---
Tags: 8, configuration
---


# Question
Title: Generate automatic URL alias removing words
I'm trying to create a topic page for "internet of things", but each time I create the page I notice the URL slug removes the word "of" in it. By default **Generate automatic URL alias** is checked. The only solution I have found is to uncheck the *Generate automatic URL alias* option and giving custom url alias. This is a problem since we have alot pages and it's difficult to update it manually. (Some people who make these pages don't have permission to open drupal and push changes from our website). We also run into an issue with symbols # or + or character 'a'.This is restricting the SEO for pages like C#

# Answer
> 1 votes
With just the Path module you can only edit each alias one by one manually.

If you want more control than the Path module allows you can use the Pathauto module. That module has a setting listing all words to exclude from the generated paths. Delete the `of` and `a` from that list if that is what you need. There are also options about how to deal with many special characters under `Punctuation` settings.

Be very careful with the `#` since it has meaning in URLs, it denotes an ID of an anchor on that page.

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


# Question
Title: How can I print the vocabulary name instead of the referenced term in a node template?
Let's say I have a content type article with a field "taxonomy".

The vocabulary is "fruits".

The terms are "apple", "orange", "bananas"

The article belongs to "orange".

I can easily print in my twig template the term of the article :

```
{{ content.field_taxo_fruit }}

```

Result is "orange".

But I don't find an easy way to print the vocabulary : "fruits".

On an other project, I used `views field` and I used "rewrite result". But here, I use twig template like `node--article--teaser.html.twig`

# Answer
You can install Devel's submodule Kint, and then in your template print `{{ kint() }}` to get a pretty-printed dump of all available variables.

Unfortunately I couldn't find the vocabulary label/name in there. Only the field label:

```
{{ content.field_taxo_fruit['#title'] }}

```

@4k4's answer below only prints the vocabulary's machine name. But not the label/name. But I finally got hold of the vocabulary name in a preprocess function in `MYTHEME.theme` from where I sent it over to Twig:

```
function MYTHEME_preprocess_node__article(&$variables) {

  $node = $variables['node'];

  $vid = array_values($node->field_taxo_fruit->getSettings()['handler_settings']['target_bundles'])[0];

  $vocabulary = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->load($vid);

  $variables['taxo_fruit_vocab'] = $vocabulary->label();
}

```

And in `node--article.html.twig` then it's:

```
{% if taxo_fruit_vocab %}
  <div class="taxo-fruit-vocab">
    Vocab: {{ taxo_fruit_vocab }}
  </div>
{% endif %}

```
> 2 votes

# Answer
The vocabulary machine name is the bundle ID of the term, which you can get through the node object:

```
{{ node.field_taxo.entity.bundle }}

```

To load the label of the vocabulary:

```
{{ node.field_taxo.entity.vid.entity.label }}

```

This works only when the field has content. For an empty field you would have to dig into the field definition you get from the same field object and check whether the field is restricted to a single target bundle.
> 3 votes

---
Tags: 8, theming, taxonomy-terms
---


# Question
Title: How do I implement the equivalent of hook_url_inbound_alter()?
I'm working on a module which will resolve URLs to entities by altering inbound URLs so that if they contain an entity ID with following pattern "-{entity\_id}" user will be redirected to correct URL.

A working example of the above:

Final URL:

I researched for a while; I found out there was `hook_url_inbound_alter()` in Drupal 7 which could solve this problem.

I also found that there is `InboundPathProcessorInterface` in Drupal 8.

I thought about implementing `InboundPathProcessorInterface` and use it in `EventSubscriberInterface` implementation which will subscribe on `KernelEvents::REQUEST`.

I wonder if this approach is correct. Are there any other ways of doing this in Drupal 8?

# Answer
The `PathProcessorAlias()` class is probably your best example.

* Create a module with a class the implements `InboundPathProcessorInterface`.
* Create the service definition in your module.
* Make sure your service has the `path_processor_inbound` service tag. This will mark it for collection and tie it to the path processor. You may need to play with the priority to change where it runs.

Your class will need to have some injected dependencies for looking up the entity. `EntityManager()` got broken up recently, and I forget which ones you will really need. You may also need/want the `PathValidator()` service.
> 15 votes

# Answer
Here is a concrete example of what code needs to be written so that when hitting a url such as :

www.my-website.com/my-pretty-alias

You actually display the content of the following page :

www.my-website.com/my-technical-needed-path/such-as/node/8

but my-pretty-alias is displayed in the url bar

In my\_module.services.yml file :

```
services:
  my_module.my_service_identifier:
    class: Drupal\my_module\Service\MyServiceName
    tags:
      - { name: path_processor_inbound }

```

In my\_module/src/Service/MyServiceName.php file :

```
<?php

namespace Drupal\my_module\Service;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

class MyServiceName implements InboundPathProcessorInterface {

  public function processInbound($path, Request $request) {

    if (strpos($path, '/my-pretty-alias') === 0) {
      $path = preg_replace('#^/my-pretty-alias#', '/my-technical-needed-path/such-as/node/8', $path);

    }
    return $path;
  }

}

```
> 2 votes

---
Tags: 8, entities, routes
---


# Question
Title: Benefit of config entities over regular config entries?
In Drupal 8 it is possible to store configuration in "config entities".

However, the same can also be achieved with non-entity config entries.

E.g. one example for a config entity schema, from core.entity.schema.yml:

```
core.entity_view_display.*.*.*:
  type: config_entity
  label: 'Entity display'
  mapping:
    id:
      type: string
      label: 'ID'
    targetEntityType:
      type: string
      label: 'Target entity type'
    bundle:
      type: string
      label: 'Bundle'
    mode:
      type: string
      label: 'View or form mode machine name'
    content:
      type: sequence
      ...
    hidden:
      type: sequence
      ...

```

The same information could be stored in entries with `type: mapping`, like so:

```
core.entity_view_display.*.*.*:
  type: mapping
  label: 'Entity display'
  mapping:
    content:
      type: sequence
      ...
    hidden:
      type: sequence
      ...

```

In fact, we would not even have to store the 'targetEntityType', 'bundle' and 'mode' as properties, because these are already part of the key (the asterisks in the schema key). We could also omit the 'id', because the key is already a unique identifier, making the id redundant.

Obviously, one would not use entity crud components to deal with those config entries, but call directly the config API, e.g. `\Drupal::configFactory->get(..)`.

Also, one would not inherit from EntityForm, but have custom form classes. But it seems all doable.

## Question

So: What would we miss by not using config entities? In which cases would a simple "mapping" be sufficient?

To stick with the example: What can we currently do with 'entity\_view\_display' entities, that would not be possible if these were just 'mapping' entries?

## Background / Use case

My original use case was this one: Custom entries in entity view modes?, which came up when I wanted to port entdispfieldui to Drupal 8.

This question was very specific, so I wanted to ask a more general question about the benefits of config entities.

In this case I decided to use non-entity config entries. One reason was that config entities caused recursion in hook\_entity\_extra\_field\_info().

I am going to port more modules to Drupal 8, where the same question will come up, but where I don't have to worry about hook\_entity\_extra\_field\_info(). E.g. cfrpreset.

# Answer
> 0 votes
A config entity is useful when there need to be multiple variations of the configuration, think views, image styles, or node bundles. If there is no need to create variations, as in system.site which stores the site's basic information or core.extensions which stores the list of enabled modules, a basic config entry is appropriate.

---
Tags: 8, entities, configuration
---


# Question
Title: Update fields to use a different FieldFormatter during an update hook
I have a drupal.org module that has changed its fieldformatter ID in a later version and I need the update hook to update all isntance of the content to use the new formatter, but cant seem to figure out how to do this.

e.g.

```
/**
 * Plugin implementation of the 'field_example_simple_text' formatter.
 *
 * @FieldFormatter(
 *   id = "example_field_formatter",
 *   module = "example",
 *   label = @Translation("example"),
 *   field_types = {
 *     "example_field_type"
 *   }
 * )
 */

```

has changed to

```
/**
 * Plugin implementation of the 'field_example_simple_text' formatter.
 *
 * @FieldFormatter(
 *   id = "new_example_field_formatter",
 *   module = "example",
 *   label = @Translation("example"),
 *   field_types = {
 *     "new_example_field_type"
 *   }
 * )
 */

```

I need to update the content/fields to be using the new formatter as it overwrites the previous one.

# Answer
The plugin definitions you've posted are for new fields to build the options when configuring a field formatter in UI. For existing fields you have to update the field formatter in config.

For example:

```
use Drupal\Core\Entity\Entity\EntityViewDisplay;

function mymodule_update_8001() {
  foreach (EntityViewDisplay::loadMultiple() as $display) {
    foreach ($display->getComponents() as $name => $options) {
      if (isset($options['type']) && $options['type'] == 'old_formatter') {
        $options['type'] = 'new_formatter';
        $display->setComponent($name, $options)
          ->save();
      }
    }
  }
}

```
> 0 votes

---
Tags: plugins
---


title: How do I create a file download URL?

text:
# Question
Title: How do I create a file download URL?
The function `file_entity_download_uri()` seems to no longer exist in Drupal 8.4, and I need to build a download URL for a file. I would not like to directly expose the file location.

# Answer
If you used a Media field, I built a module for this purpose: http://drupal.org/project/media\_entity\_download \- it will take file(s) in a media object and give them an instant download uri. It will not show the actual file path to the user.

If you just have a file field, you're basically looking at what private files option does.

In the end, you'd need a solution that ensures a `BinaryFileResponse` from a controller, you can see an example in my module.
> 5 votes

# Answer
If you just have a static file(s) on your server that you want users to download, such as in the /files dir (suggest using /files/downloads/\[filename\]). You will want to create a route and controller for this. Then render the link via the route in a block. You could also have a form whos submit handler calls the route with required filename.

This should also not show the actual filepath to the user, just the filename and that its from your site http://example.com

Also note: I added this here due to the title of the OP issue... Might save someone some time in the future when googling 'Drupal 8 file download link'.

example.routing.yml

```
example.download.file:
  path: '/download/file/{file_name}'
  defaults:
    _controller: '\Drupal\example\Controller\Download::downloadFile'
  requirements:
    _permission: 'access content'

```

src/Controller/Download.php

```
<?php

namespace Drupal\example\Controller;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

/**
 * Handle /download/file/ URLs to redirect to content download based on filename.
 */
class Download extends ControllerBase {

  /**
   * Download file.
   *
   * @param string $filename
   *   The filename.
   */
  public function downloadItemTypeExport($filename) {

    // Do some file validation here, like checking for extension.

    // File lives in /files/downloads.
    $uri_prefix = 'public://downloads/';

    $uri = $uri_prefix . $filename;

    $headers = [
      'Content-Type' => 'text/csv', // Would want a condition to check for extension and set Content-Type dynamically
      'Content-Description' => 'File Download',
      'Content-Disposition' => 'attachment; filename=' . $filename
    ];

    // Return and trigger file donwload.
    return new BinaryFileResponse($uri, 200, $headers, true );

  }
}

```

src\Plugin\Block code

```
<?php

namespace Drupal\example\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Url;

/**
 * @Block(
 *   id = "example_download_files",
 *   admin_label = @Translation("Example Download Files"),
 *   category = @Translation("Example")
 * )
 */
class ExampleDownloadFiles extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $items = [
      'Foo' => 'foo.csv',
      'Bar' => 'bar.csv',
      'Herp' => 'herp.csv',
      'Derp' => 'derp.csv'
    ];

    foreach ($items as $item => $filename) {
      $url = Url::fromRoute('example.download.file', ['file_name' => $filename]);
      $links[$item] = [
        '#title' => $this->t($item),
        '#type' => 'link',
        '#url' => $url
      ];
    }

    $file_download_list = [
      '#theme' => 'item_list',
      '#items' => $links
    ];

    $build['file_downloads'] = [
      '#type' => 'container',
      'file_downloads_prefix' => ['#type' => 'html_tag', '#tag' => 'p', '#value' => $this->t('Download the csv:')],
      'file_downloads_list' => $file_download_list,

    ];

    return $build;

  }

```
> 8 votes

# Answer
if you are using media this code might work for you :

`$file = Media::load(your_file_id);
 $file_uri = $file->field_file->entity->getFileUri();
 $file_downloadable_link = file_create_url($file_uri);`
> 3 votes

---
Tags: 8, files
---


title: How to customize entity print pdf

text:
# Question
Title: How to customize entity print pdf
I've installed Entity Print in order to create PDF files. I've read the documentation to enable a twig template to customize the pdf output, but I don't know how to do simple things, in the twig file, like add a page header and footer, add a front page, etc. Are there any docs about how to customize it?

# Answer
> 3 votes
It depends on which print engine you're using. I am using the following entity-print.html.twig with the dompdf engine.

```
<html>
<head>
    <meta charset="utf-8">
    <title>{{ title }}</title>
    {{ entity_print_css }}
</head>
<body>
{# The footer is repeated on all pages and must be printed first. #}
<footer>
    {{  footer  }}
</footer>
{%  if cover_page  %}
<div class="cover-page">
    {{ cover_page }}
</div>
{%  endif  %}
{# The header is repeated after the cover page for all pages. #}
<header>
    {{  header  }}
</header>
<div class="page">
    {{ content }}
</div>
</body>
</html>

```

The header and footer must be styled with position: fixed, after which they are displayed on every page.

I haven't found any great combined reference for the entity print module, but searching for what you want to accomplish along with your print engine's name should be helpful.

---
Tags: 8
---


# Question
Title: Enable users to view their own profile, without enabling "View user profiles"
This may be a really stupid question, but we can't see how to make it work.

We have a Drupal 7 site with several different rôles and one of them should not be able to see the user profiles of the others. Now I thought that would be simple, by unchecking the "View user profiles" permission in the People admin.

But that prevents them accessing their own profiles as well. From what I can gather, there isn't a simple way of making this be the case, so I'm looking for any sensible suggestions on how I can make it happen -- code edits, modules, whatever.

Thanks everyone! (And let me know if I need to provide more information about our configuration or Modules we have installed.)

# Answer
You could do this with a custom rule, as follows:

```
{ "rules_users_view_own_profile_only" : {
    "LABEL" : "Users View Own Profile Only",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_view" ],
    "IF" : [
        { "NOT user_has_role" : { "account" : [ "site:current-user" ], "roles" : { "value" : { "3" : "3" } } } },
        { "AND" : [] },
        { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : [ "account:uid" ] } }
    ],
    "DO" : [ { "redirect" : { "url" : "http:\/\/www.yourdomain.com\/denied" } } ]
    }
}

```

That basically checks to make sure the user isn't an admin or on his own account page before directing to yourdomain.com. If you use the CustomError module, you can redirect to an access denied page.

You might also want to check out the Edit own user account permission module - you might be able to enable that and disable "View user profiles" and get the results you want, although I haven't tried that.
> 4 votes

# Answer
For this trick you can use chain\_menu\_access module. Code below.

```
/**
 * Implements hook_menu_alter().
 */
function hook_menu_alter(&$items) {
  chain_menu_access_chain($items, 'user/%user', '_mymodule_check_permission');
}

function _mymodule_check_permission() {
  global $user;

  $own_profile = $user->uid == arg(1);
  $has_access = user_access('administer users');

  return (!$has_access && !$own_profile) ? FALSE : TRUE;
}

```

In your case, you can use different permission instead 'administer users'.
> 2 votes

# Answer
You can accomplish this with Page Manager. You basically create different variants for the "User profile template" under: admin/structure/pages/edit/user\_view ( /user/%user ) and there you give the access permissions through "selection rules". For example: choose from the context drop down: "User: compare" and set it to "User being viewed is Logged in user". You can do the same for a plethora of contexts and therefore also roles, so you can combine them and create your access permissions like that. Finally, I advise you to create a variant that redirects if someone wants to view another user's profile page or instead of adding custom content in your "content" tab on the variant, set a response code "403 Access Denied" for example to be safe. Now you have full control of which fields show and which don't and what happens when visitors or users access their own or other users' profile pages.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Create the FooTable functionality by using only views
I noticed by using FooTable display on one of my view on a Drupal 8 site, it is increasing the load time of the view by more than 2000 ms.

The main idea i am using Footable is because of the ability to hide fields within the table row and make them visible once you click on that table row (collapsable fields).

Can I build using only views such table with collapsable fields without having the Footable module installed ?

Any help suggestions just to make me start !

Below is an image of what i am trying to build using only views core module:

Note: The responsiveness of the table is not important in my case !

I want the table to always display 4 columns (one field in each column) and when the "See More" link is clicked, the other fields will show/hide inside a collapsible accordion.

# Answer
A module that provides the "collapsible" functionality is Views Accordion so maybe you can try it and see if it performs better.

But it doesn't change the layout depending on the browser width.

The proper way of addressing this is with CSS. You can use CSS grid to make the fields appear as a table on wider widths, and stacked one below the other on narrow widths. You can even recreate the accordion look where some fields are hidden initially, you click on the visible ones to show all the rest. I expect this solution would score highest in performance, but I'm not aware of any contributed modules that provide it for D8, you can build it yourself in your subtheme.

For D7 there is Views CSS Tables.

The CSS route may not support some older browsers so it depends on your project's visitors stats if it's safe to go that way.

**Edited:** Yes, I think it can be done, although I've never tried it in Views like that, and it's definitely not trivial. The concepts you need to learn are about:
> 0 votes

---
Tags: views, 8, performance
---


# Question
Title: How can I export Image Crop configuration with an Image Style for custom module?
I have a custom module I'm re-using on other projects and I want to include an image style with an image crop configuration.

Under the configuration menu, I export a single crop item:

```
langcode: en
status: true
dependencies: {  }
label: 'Head Shot Crop'
id: head_shot_crop
description: 'Cropping for image head shot.'
aspect_ratio: '1:1'
soft_limit_width: null
soft_limit_height: null
hard_limit_width: null
hard_limit_height: null

```

I strip out the UUID value for that to be set on new installs. However, for the image style export:

```
langcode: en
status: true
dependencies:
  config:
    - crop.type.head_shot_crop
  module:
    - crop
name: head_shot
label: 'Head Shot'
effects:
  ce7f0752-c37c-4ff6-945d-96c298663365:
    uuid: ce7f0752-c37c-4ff6-945d-96c298663365
    id: crop_crop
    weight: 1
    data:
      crop_type: head_shot_crop

```

I strip out the UUID value as well, but the associated crop configuration seems to be tied to the image style via UUID under the effects key, which also has a UUID value.

How can I pair an image style configuration with a crop configuration configuration so they exist on new module installs?

# Answer
> 1 votes
Please see: https://www.drupal.org/project/drupal/issues/2247257

The `uuid` under the effects array is used as a "unique ID" for the effect.

Seems technically it "works as designed", but as you can see from the linked project task, there is talk about if it's designed correctly.

Fortunately, the `uuid` under the effects array is scoped to that effects namespace, so it is safe to have the same `uuid` under any effects array you have regardless of the image style.

Example:

```
langcode: en
status: true
dependencies: {  }
name: 136x91
label: '(35mm Film 96dpi) 136 x 91'
effects:
  42cf8d4f-246c-4a6d-835f-868e5bcea297:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500779 // <- could be any uuid value
    id: image_scale_and_crop
    weight: 35
    data:
      width: 136
      height: 91
      anchor: center-center

```

Just note that if you have two effects in one image style, they will each need a unique `uuid` key.

Example:

```
langcode: en
status: true
dependencies: {  }
name: teaser_290x163
label: 'Teaser Image 290 x 163'
effects:
  bdd99645-b55a-47b4-9337-89453c12658e:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500779 // <- same as above
    id: image_scale_and_crop
    weight: 1
    data:
      width: 290
      height: 163
  4f4a1ff4-f127-4693-af57-d8f0cf3c9de0:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500780 // <- needs to be unique
    id: image_resize
    weight: 2
    data:
      width: 290
      height: 163

```

So remove the `uuid` from the first line for the image style itself, but leave the `uuid` under the effects array when you export.

---
Tags: 8, configuration, media
---


# Question
Title: Why isn't my controller returning AccessResult::forbidden()?
I'm working on a node access module. I've set up my logic. I can't seem to get my code to return AccessResult::forbidden(). I can't even get \dpm to run in access method. What am I doing wrong? Below are my routing.yml and controller.

```
/* nodeaccess.routing.yml */
nodeaccess.people:
  path: '/user/{uid}/edit'
  defaults:
    _controller: '\Drupal\nodeaccess\Controller\NodeaccessController::content'
    _title: 'Dashboard'
  requirements:
    _custom_access: '\Drupal\nodeaccess\Controller\NodeaccessController::access'

/* src/Controller/NodeAccessController.php */

<?php

namespace Drupal\nodeaccess\Controller;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Defines the Dashboard controller.
 */
class NodeaccessController extends ControllerBase {

 /**
  * Returns content for this controller.
  */
 public function content() {
   $today = date("l");
   if ($today == "Thursday") {
     // Return 403 Access Denied page.
     \dpm("You are not allowed.");
   }
 }

 /**
  * Checks access for this controller.
  */
 public function access(AccountInterface $account) {
  $current_user = User::load(Drupal::currentUser()->id());
  $user = User::load(explode("/", $_SERVER["REQUEST_URI"])[1]);
  if ($current_user->field_department->target_id != $user->field_department->target_id) {
    return AccessResult::forbidden();
  }
  return AccessResult::allowed();
  }
}

```

# Answer
> 0 votes
There is a syntax error here `Drupal::currentUser()->id()` should be `\Drupal::currentUser()->id()` and also `explode("/", $_SERVER["REQUEST_URI"])[2]` gives you only `people` not the user id, to use `User::load`.

---
Tags: 8, routes, page-controller
---


# Question
Title: Undefined index: und on .tpl.php for content type
How can i fix the error message?

> the error message is Notice: Undefined index: und in include() (line 9 of /var/www/html/sites/all/modules/custom/theme/icons.tpl.php).

my code is:

```
<?php
global $language ;
global $base_url , $base_path ;
$lang = $language->language;
$count = 0;
foreach ($data as $kay => $node_obj) {
    $node = node_load($node_obj->nid);
if (isset($node->field_description[$lang])) {
    $img_url = $node->field_icon['und'][0]['uri'] ;
$count++;

```

?\>

# Answer
> 1 votes
I fix it by

add

```
!empty( )

```

like this

```
$img_url = !empty($node->field_icon['und'][0]['uri']) ;

```

---
Tags: 7
---


# Question
Title: How do I let non-admin user approve comments?
I'm looking for a way to allow a non-admin user to approve comments. I thought a Flag/Rules combination might be a solution but I can't figure it out.

I added a content-moderator role, then I created a view listing comments awaiting moderation. After that, I set up a flag to approve comments and added the flag link within the view, bu there is no Rules action that approves comments once the flag is clicked.

Do you have any idea?

# Answer
> 2 votes
You need to give the "Administer comments and comment settings" permission to the role and then it will be able to approve the comment.

# Answer
> 0 votes
You also can write a tiny module and add this Rule Action, to do that you will need a .info file, an empty .module file and a .rules.inc file, in this file you will need to implement hook\_rules\_action\_info to tell drupal about your custom Action and at last you will need a function to do the job for you.

here is a simple code which will do the job for you:

```
/**
 * @file MODULE_NAME.rules.inc
 * Contains custom code for Rules module.
 */
/**
 * Implements hook_rules_action_info().
 */
function MODULE_NAME_rules_action_info() {
  return array(
    'MODULE_NAME_action_approve_comment' => array(
      'label' => t('Approve Comment'),
      'group' => t('Comment'),
      'parameter' => array(
        'account' => array(
          'type' => 'integer',//cid of comment will be passed to function
          'label' => t('Comment ID'),
        ),
      ),
    ),
  );
}
/**
 * Rule action comment approve.
 */
function MODULE_NAME_action_approve_comment($cid) {
  $comment->status = COMMENT_PUBLISHED;
  db_update('comment')
    ->fields(array(
      'status' => $comment->status,
    ))
    ->condition('cid', $cid)
    ->execute();
}

```

---
Tags: 7, rules, comments
---


title: Quick Start site is not reachable

text:
# Question
Title: Quick Start site is not reachable
I'm trying to launch a Quick Start distro on macOS with MAMP:

```
[519] : php core/scripts/drupal -vvv --verbose  quick-start

 Select an installation profile [Install with commonly used features pre-configured.]:
  [standard  ] Install with commonly used features pre-configured.
  [minimal   ] Build a custom site without pre-configured functionality. Suitable for advanced users.
  [demo_umami] Install an example site that shows off some of Drupal’s capabilities.
 > demo_umami

Creating file: sites/default/settings.php
18/18 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓]
Congratulations, you installed Drupal!
Username: admin
Password: hIuWCqqnaD-TostT
Drupal development server started: <http://127.0.0.1:8888>
This server is not meant for production use.
One time login url: <http://127.0.0.1:8888/user/reset/1/1560664888/oDldybNCOH_0nRc1n4YXZWm2NwEehXnN63rWHq_Isqo/login>
Press Ctrl-C to quit the Drupal development server.
Browser command: open 'http://127.0.0.1:8888/user/reset/1/1560664888/oDldybNCOH_0nRc1n4YXZWm2NwEehXnN63rWHq_Isqo/login?destination=%2F'
Server command: '/Applications/MAMP/bin/php/php7.2.1/bin/php' '-S' '127.0.0.1:8888' '.ht.router.php'

```

Unfortunately the given URL returns with HTTP error code 500. Also I added `-vvv` and `--verbose` no additional error messages are visible.

When I change from MAMP to OS X standard PHP installation the browser shows:

```
Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

Fatal error: Unknown: Failed opening required '.ht.router.php' (include_path='.:') in Unknown on line 0

```

Actually there's no `.ht.router.php` from where I started the quick-start command.

Any ideas?

# Answer
Well that was a nasty one. I downloaded and unpacked the latest Drupal version as instructed. But then made a copy using Finder. Unfortunately this leaves out the all files starting with a `.`.

After copying the files on the comannd line everything works as ecpected. Thanks to @leymannx for pushing me into the right direction.
> 2 votes

---
Tags: installation
---


# Question
Title: how to get valid URL in combination of text and field content in VIEWS
Field HOSTNAME returns IP Adress. I have to overwrite the field output . Is there a way to modify this with an given URL like this: 'www.ip-tracker.org/locator/ip-lookup.php?ip=' and adding the field content of HOSTNAME to get an valid URL?

# Answer
Yes you can use the `Rewrite results` option on your Field settings. Use the **Output this field as a link** option and enter only the URL with the field token replacement pattern at the end of it.

You can look up the token under `Replacement patterns` under the `Rewrite results` option.

If you need some more control over the link HTML you can use the `Rewrite the output of this field` where you construct the entire link HTML `<a href="...`.
> 1 votes

---
Tags: views
---


# Question
Title: How do I change drupal_core_path to /public instead of /web?
I use Drupal VM and I have to change the folder from *{{ drupal\_composer\_install\_dir }}/web* to *{{ drupal\_composer\_install\_dir }}/public*.

When I do it and I run `vagrant up`, I get this error.

> An exception occurred during task execution. To see the full traceback, use -vvv.
> The error was: OSError: \[Errno 2\] No such file or directory: '/var/www/jb-inflatables/public'
> fatal: \[jb-inflatables\]: FAILED! =\> {"changed": false, "failed\_when\_result": true, "module\_stderr": "Traceback (most recent call last):
> File \\"/home/vagrant/.ansible/tmp/ansible-tmp-1560461183.6-73909259621121/AnsiballZ\_command.py\\", line 114, in `<module>`
> \_ansiballz\_main()
> File "/home/vagrant/.ansible/tmp/ansible-tmp-1560461183.6-73909259621121/AnsiballZ\_command.py", line 106, in \_ansiballz\_main
> invoke\_module(zipped\_mod, temp\_path, ANSIBALLZ\_PARAMS)
> File "/home/vagrant/.ansible/tmp/ansible-tmp-1560461183.6-73909259621121/AnsiballZ\_command.py\\", line 49, in invoke\_module
> imp.load\_module('**main**', mod, module, MOD\_DESC)
> File "/tmp/ansible\_command\_payload\_KaNSZF/**main**.py", line 327, in `<module>`
> File "/tmp/ansible\_command\_payload\_KaNSZF/**main**.py", line 263, in main
> OSError: \[Errno 2\] No such file or directory: '/var/www/jb-inflatables/public', "module\_stdout": "", "msg": "MODULE FAILURE See stdout/stderr for the exact error", "rc": 1

How do I have to change the config.yml file so that Drupal is installed in /public instead of /web?

# Answer
The default `drupal-vm setup` use drupal-composer/drupal-project which use `/web` directory.

If you need another directory for your dependencies (e.g. `/public_html`, `public`), you have to make a composer setup (`composer init`) without drupal-composer/drupal-project. See this page for more information.

Then you can choose the folder structure yourself.
> 0 votes

# Answer
You should be able to create a symbolic link to web called public. `ln -s web public` Your server will find the contents of web/ inside of public/ and vagrant will find what it needs in web.
> 0 votes

---
Tags: virtual-machine
---


# Question
Title: Form with manged_file filed is not submitted?
I have a form in my drupal module. in my form, I have used manged\_file field. form name is "difference\_form" and I have created two functions. one is "function diffence\_form" for form definitions. here is code:

```
function difference_form() {
  $validators = [];
  $form['new_image'] = [
    '#type' => 'managed_file',
    '#name' => 'new_personal_image',
    '#title' => 'New Image',
    '#description' => theme('file_upload_help', [
      'description' => 'Please insert your new image.',
      'upload_validators' => $validators,
    ]),
    '#upload_location' => $path,
    '#default_value' => variable_get('new_image', ''),
    '#upload_validators' => $validators,
  ];

  $form['submit'] = [
    '#type' => 'submit',
    '#value' => 'submit',
  ];

  return $form;
}

function difference_form_submit($form, &$form_state) {
  drupal_set_message('test_form_submit called');
}

```

and also I have created a block for this form in hook\_block\_view.

```
function customize_block_view($delta = '') {

  $block = NULL;
  $block['content'] = drupal_get_form('difference_form');
  $block['subject'] = 'Difference Form';
  return $block;
}

```

Form is rendered correctly, but when I click on submit button, submit function is not called.

I tried to debug my codes. I found if I remove file\_managed field from form definition, submit function works.

also if I found if I renamed all difference\_form to another name for example "test\_form"

drupal\_get\_form('test\_form'); function test\_form(){....} and function test\_form\_submit(......

submit function works. it seems system is sensitive on "difference\_form" only

I am thinking might the expression "difference\_form" be blocked in database or somewhere else ?

# Answer
I found the reason of this problem finally. It was as a result of jQuery code mistakes.

in form submission, I tried to disable submit button immediately after clicking. I had to change the coding because set button disable causes this problem.
> 0 votes

---
Tags: forms, files
---


# Question
Title: How to attach media item created during migration to media field in node
I am migrating content from Drupal 7 to Drupal 8. There is an audio field that I am currently moving to media via a custom process during migration.

When I get the id of the new media created I can't seem to get it to attach to my new media reference field in the also newly created node.

Can anyone tell me what is wrong with the import below?

```
field_audio_fileinfo:
-
  plugin: sub_process
  source: field_audio_fileinfo
  process:
    target_id:
      -
        plugin: migration_lookup
        method: process
        source: fid
        migration: upgrade_d7_file
      -
        plugin: my_custom_process
        destination: field_media_audio

```

In my custom process I can save the media and get it's ID via:

```
$media_id = $audio_media->id();
$arr[] = array(
  'target_id' => $media_id,
  'display' => NULL,
  'description' => NULL
);
return $arr;

```

But it doesn't seem to populate the destination field.

This is also the case if I just return the ID directly from the process.

# Answer
There was a fault with my migration yaml.

The destination field in Drupal 8 was **field\_media\_audio** but as you can see in the question I had it trying to save to **field\_audio\_fileinfo** which was the Drupal 7 source. Silly me.

Once I realised and corrected the destination it all worked and now media is created and referenced in the one pass of my migration script.

```
  field_media_audio:
-
  plugin: sub_process
  source: field_audio_fileinfo
  destination: field_media_audio
  process:
    target_id:
      -
        plugin: migration_lookup
        method: process
        source: fid
        migration: upgrade_d7_file
      -
        plugin: my_custom_process

```
> 0 votes

# Answer
When I have done a similar type of migration at that time I did the following steps:

* First I created media type Audio in Drupal 8 and it's fields.
* Then I exported all audio file details and FID from D7 and created csv file.
* Written migration script to import audio into media.

Example:

```
source:
  plugin: csv
  path: 'csv file path'
  header_row_count: 1
  keys:
    - fid
  type: audio
  constants:
    bundle: audio
process:
  mid: fid
  bundle: constants/bundle
  langcode:
    plugin: default_value
    source: language
    default_value: und
  name: filename
  uid: uid
  created: upload_date
  changed: upload_date
  field_media_audio_file/target_id: fid
destination:
  plugin: 'entity:media'
  migration_dependencies: {  }
migration_dependencies: null

```
* The same csv I used to import data into file entity and written migration script.

Example:

```
source:
  plugin: csv
  path: 'csv file path'
  header_row_count: 1
  keys:
    - fid
process:
  uid: uid
  fid: fid
  filename: filename
  created: upload_date
  changed: upload_date
  filemime: mime
  uri: uri
destination:
  plugin: 'entity:file'
  source_path_property: filepath
  destination_path_property: uri
migration_dependencies: {  }

```
* After that, I attached the FID to my node field.

> ```
> process:
>   field_audio/target_id: fid
>
> ```
>
> I am keeping media id, FID of Drupal 8 same as FID of Drupal 7. So we can attach the same FID to the node directly.
> 0 votes

---
Tags: 8, media, migrations
---


# Question
Title: Retrieving value of paragraph type with entity reference revision through preprocessor
I have created a paragraph type which has field of type entity reference, link, plain text.

Now I want to fetch the values present in these through the preprocessor.paragraph.inc and display it in the custom template(twig).

Can anyone please let me know how do i do this?

I have written a hook function in the preprocessor, but unable to fetch values of paragraph types.

Eg of my paragraphs type:

1. Section
2. Box

In the section contains 2 fields, first is the title which is a plain text and second is the box, which is an entity reference revision

The box, is a paragraph type which has many fields like

1. Link
2. Image
3. text field
4. Wysiwig

Now how do i access values present in these through the hook function and display the same in twig template.

# Answer
> 0 votes
Every paragraph can be preprocessed with `template_preprocess_paragraph` or even more specific with `template_preprocess_paragraph__PARAGRAPH_TYPE`.

Check this sample below, where I get the value of `field_foobar` of the paragraph type `box` and pass it to the Twig template. It's a little bit redundant as this value can be accessed from the template itself, but you wanted to know how to pass values from a preprocess function to Twig. Here's how:

```
function MYTHEME_preprocess_paragraph(&$variables) {

  $paragraph = $variables['paragraph'];

  if ($paragraph->getType() === 'box') {
    if (!$paragraph->field_foobar->isEmpty()) {

      $variables['foobar'] = $paragraph->get('field_foobar')->first()->getValue();
    }
  }
}

```

And then in `paragaph.html.twig`:

```
{% if foobar %}
  <div class="foobar">{{ foobar }}</div>
{% endif %}

```

---

Same principle applies for other preprocess functions and templates. On node level, on page level, even in fields or views. See How to load paragraph entity on node object? It's just that you need to get hold of the entity ID your paragraph field is referencing, load the paragraph from that ID and then you get every field you want. For example inside `template_preprocess_html`:

```
function MYTHEME_preprocess_html(&$variables) {

  $node = \Drupal::routeMatch()->getParameter('node');

  if ($node instanceof \Drupal\node\NodeInterface) {
    if ($node->bundle() === 'article') {

      $my_paragraphs = $node->get('field_paragraphs')->getValue();

      foreach ($my_paragraphs as $item) {

        $paragraph = \Drupal\paragraphs\Entity\Paragraph::load($item['target_id']);

        if ($paragraph->getType() === 'box') {
          if (!$paragraph->field_foobar->isEmpty()) {

            $variables['foobar'] = $paragraph->get('field_foobar')->first()->getValue();
          }
        }
      }
    }
  }
}

```

Now you can access `{{ foobar }}` in `html.html.twig`.

---

You may want to install Devel's submodule Kint. Then you can dump all variables in templates with `{{ kint() }}` or in PHP with `ksm($variables)`. Then check the dump for what values or methods you get and then use them in your code.

---
Tags: 8, theming, paragraphs
---


title: Creating an image upload input field

text:
# Question
Title: Creating an image upload input field
I'm creating a image upload input field in blockForm which will output to Twig later. But got stuck due to some stuff.

```
public function blockForm($form, FormStateInterface $form_state){
        $form['image_file'] = [
            '#type' => 'managed_file',
            '#title' => $this->t('Upload Your Image'),
            '#default_value' => (isset($this->configuration['image_file']) ? $this->configuration['image_file'] : ""),
            '#weight' => '1',
            '#upload_location' => 'public://',
            '#upload_validators' => [
                'file_validate_extensions' => ['gif png jpg jpeg'],
            ],
        ];

       return $form;
    }

```

First thing is the `'#upload_location'`, there are a lot of different answer online and the only difference is the path after `public://`, so I want to know what should I actually deal with it.

Second is the `use`, is there something missing or it is enough for achieve my goal.

The code I have now:

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormBuilder;
use Drupal\Core\Link;
use Drupal\image\Entity\ImageStyle;
use Drupal\paragraphs\Entity\Paragraph;

```

Hope someone can answer and help. Many Thanks.

# Answer
> 0 votes
As i understand you could use something like this `'#type' => 'file'`

```
  $form['image_file']=array(
    '#type' => 'file',
   '#title' => t('Upload YourImage'),
    '#upload_validators' => array(
    'file_validate_extensions' => array('gif'),),

        );
return $form;

```

---
Tags: 8, media
---


# Question
Title: Why is the button to install a new module missing in the admin interface?
I am new to Drupal and am attempting to install pathauto. But when I click on "extend," I don't have a "install new module" button.

Any suggestions?

# Answer
> 5 votes
This drove me crazy till I figured it out. Goaddy techsupport is also pretty clueless.

Under Drupal 8.x this option is no longer accessible through the 'Appearance' menu.

Instead, you'll find it under: Reports menu \>\> Available Updates, as an: "+Install new module or theme" button.

(The breadcrumb will read: Home \>\> Administration \>\> Reports)

A side note: in the Reports, if you see any errors, such as opcache missing, you're advised to enable it from the PHP configuration page, and also enable Update manager in drupal.

Irony of ironies, once you've installed the new theme, from the appearance menu page, the "Install new theme" button starts displaying there. aargh.

# Answer
> 4 votes
You need to enable the core Update Manager module:

> Checks for available updates, and can securely **install or update modules and themes via a web interface**.

Emphasis mine.

Also make sure the user you're logging in as has the *Administer software updates* permission granted. If it's user 1, you already have access.

# Answer
> 1 votes
Some possible causes for this issue (partially inspired by "Can't Find the "Install new module" Link in Drupal?)":

* It could be a theme related issue. To check if that's the case, set "Seven" as the administration theme, and verify if that button shows up.
* Some hosting companies won't allow you to upload modules via the Drupal interface. As an example, here is a quote from "Installing a Drupal module on Acquia Cloud":

> One of the most common tasks you'll accomplish while developing or maintaining a Drupal application is adding a Drupal contributed module. If you are used to working in a local installation of Drupal, you may be used to doing this directly in the Drupal admin interface, using the core Update Manager module, or perhaps with Drush, using the drush dl command. If your application is hosted on Acquia Cloud, the module directories are part of the code repository, which is not directly writable. This means that you can't directly add a module using the Update Manager, drush dl, or SFTP. Instead, you must commit your changes using a version control system (Git).
* Check your settings.php file allows it, i.e. ensure it contains a line that looks something like this: `$conf['allow_authorize_operations'] = TRUE;` (or as a variation: `#$conf['allow_authorize_operations'] = FALSE;`, so make sure it is commented out, to not set to `FALSE`).

---
Tags: 8, installation
---


# Question
Title: How do you prevent twig variable from last instance of template overriding those that go before it?
I am creating a module that will allow editors to display nodes as "cards" using the summary from the node for the card text and a field (field\_hero) as a background image to the card, the user can then click-thru to the actual content from the card. The editor can also define, via the layout builder the colour behind the text for the card and also where the text appears (top, left, right, bottom).

If I add several of these cards to a page using the layout builder, all of the cards use the values for position and colour from the last instance placed on the page.

My code block plugin code is:

```
  public function build() {
if ($entity_id = $this->configuration['entity']) {
  if (($entity = $this->entityStorage->load($entity_id)) && $entity->access('view')) {
    $render_controller = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
    $view_mode = isset($this->configuration['view_mode']) ? $this->configuration['view_mode'] : 'default';

    if (isset($this->configuration['card_colour'])) {
      $entity->card_colour = $this->configuration['card_colour'];
    }
    if (isset($this->configuration['card_layout'])) {
      $entity->card_layout = $this->configuration['card_layout'];
    }

    return $render_controller->view($entity, $view_mode);
  }
}

return [];

```

}

And my twig template is (ignore the empty url() in the style attribute):

```
{%
    set classes = [
        'node-card',
        'card-' ~ node.card_layout|clean_class,
        node.card_colour|clean_class,
        'clearfix'
    ]
%}
<article{{ attributes.addClass(classes) }}>
    <div{{ content_attributes.addClass('bg-img', 'clearfix') }} style="background-image: url()">
        <div class="summary">
            {{ content.body }}
        </div>
    </div>
</article>

```

# Answer
> 0 votes
$render\_controller-\>view() invokes hook\_ENTITY\_TYPE\_view() and this would be a better place to add custom values to the entity view.

Although probably not good practice you could get your approach working by cloning the entity before modifying the field values:

```
$entity = clone $entity;

```

In any case you need to adjust caching so that you store for each variant a different cache item in the render cache. For example by adding cache keys to the build array before returning it:

```
$build = $render_controller->view($entity, $view_mode);
if (isset($entity->foo)) {
  $build['#cache']['keys'][] = $entity->foo;
}
return $build;

```

---
Tags: theming
---


# Question
Title: Drupal 8 & Solr 8.1: No search results, error: "The datasource with ID '' could not be retrieved for index..."
I have Drupal 8.7.1, Solr 8.1. My Solr Server is running and my content is indexed.   But I have no results (with a query or without) in my view, and an error: `Drupal\search_api\SearchApiException: The datasource with ID '' could not be retrieved for index 'Solr search index'. in Drupal\search_api\Entity\Index->getDatasource() (line 365 of C:\Users\Oksana\Documents\sites\drupal2\modules\search_api\src\Entity\Index.php)`.

The function that produces this error in the indicated file is:

```
 /**
   * {@inheritdoc}
   */
  public function getDatasource($datasource_id) {
    $datasources = $this->getDatasources();

    if (empty($datasources[$datasource_id])) {
      $index_label = $this->label();
      throw new SearchApiException("The datasource with ID '$datasource_id' could not be retrieved for index '$index_label'.");
    }

    return $datasources[$datasource_id];
  }

```

As I understand, the Search API module receives no results from Solr.

If I type `http://localhost:8983/solr/first_solr_core/select?indent=on&q=` in browser, I get:

```
{
  "responseHeader":{
    "status":0,
    "QTime":1,
    "params":{
      "q":"",
      "indent":"on"}},
  "response":{"numFound":0,"start":0,"docs":[]
  }}

```

Which means, as I understood, that Solr has no results.

How can I find where is the problem (what happens with results after contents are indexed, and where results disappear)?

Thank you

# Answer
> 2 votes
Possible problem: "Search API Solr" module 8.x-2.7 does not support Solr 8.

Solution:

1. Remove "Search API Solr" module 8.x-2.7 using 'composer remove drupal/search\_api\_solr'
2. Install "Search API Solr" module 8.x-3.1 using 'composer require drupal/search\_api\_solr'
3. Find Solr modules in Drupal BO ("Extend" \> "List") and click "Install" button
4. Add Solr Server in Drupal BO. I used solr path "/".
5. Download the configs zip folder from Drupal BO, copy files from the folder to the conf directory of the Solr core. (See details in INSTALL.md file in the module directory).
6. Restart solr server.
7. In Drupal BO in my Index configs select the name of my Solr server.
8. Go to the Index in Drupal BO. Click to run the index of content.
9. Go to my previously confiured view. See search results and search!

---
Tags: search
---


# Question
Title: How can I remove or overwrite the YAML validation from a Webform Entity?
I am currently building a module that parses raw HTML into a webform using YAML, however I am running into an issue where the `name='SomeName'` on form elements is causing an error in the YAML keys.

The form relies on the name attribute in order to accurately map the data so I need it to be case insensitive. I can force a save programmatically with

```
$webform = new \Drupal\webform\Entity\Webform::create(
// stuff here
);

$webform->save();

```

However when someone attempts to edit the form in the UI and saves, there is an error preventing save that comes from `docroot/modules/contrib/webform/src/WebformEntityElementsValidator.php`

This error prevents saving due to casing errors.

`The element key contact_Name on line 1 must contain only lowercase letters, numbers, and underscores.`

I have tried

```
function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $forms_array = ['webform_ui_element_form', 'webform_source_form'];
  if (in_array($form_id, $forms_array)) {
    $form['actions']['submit']['#limit_validation_errors'] = [];
    $form['actions']['submit']['#_validate_form'] = FALSE;
  }

}

```

However it seems that for some reason this prevents saving a new element.

Any help is appreciated.

# Answer
I was able to achieve this, thanks to some guidance in the comments, by overriding a service.

This involved work in two custom module files. The first was modules/custom/mymodule/src/MymoduleFormParserServiceProvider.php

Within that file I used `::alter` to alter which class is called for a particular service.

```
<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;

/**
 * Replace Webform validator service.
 */
class MymoduleServiceProvider extends ServiceProviderBase implements ServiceProviderInterface {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('webform.elements_validator');
    $definition->setClass('Drupal\mymodule\MymoduleWebformElementsValidator');
  }

}

```

What this does is tell Drupal that when the `webform.elements_validator` service is called, use the `MymoduleWebformElementsValidator` class instead.

The second piece of the puzzle was to create that class. I did that by extending the original class `WebformEntityElementsValidator` with my own `MymoduleWebformElementsValidator` class and doing the logic there. That way I was able to keep most of the validation from the original, but make the changes to the validate method that were needed.

I was able to find many of the answers after googling override service thanks to the comment on the question by @jrockowitz
> 1 votes

---
Tags: webforms
---


# Question
Title: Assign different taxonomy terms to translations of content
I've got some custom content translated with entity translation with custom taxonomy also translated. Actually taxonomy terms are correctly shown inside the content page. The problem is I need different taxonomy terms for different translation. When I change the taxonomy terms in the translation edit page every translation of the content gets updated with the terms variation.

The logic behind would be:

```
- content A (english) --> taxonomy term 1 (english)
- content A (french)  --> taxonomy term 2 (french)
- content B (english) --> taxonomy term 2 (english)
- content B (french)  --> taxonomy term 3 (french)

```

# Answer
> 0 votes
If you don't want the node translations to share the terms they are tagged with you need to make the Taxonomy term reference field **translatable**. Then you will be able to enter different values into that field depending on which language you're editing.

You can enable the translations for Fields under `Configuration > Regional and language > Content language and translation` (`/admin/config/regional/content-language`).

Tick the box for your Taxonomy field and hit the "Save configuration" button at the bottom of the page.

After that you'll be able to save the translations with different values for that field than the original. The translations in languages other than the default one will probably have that field empty before you edit them, they will not "inherit" the values from the default translation out-of-box.

---
Tags: taxonomy-terms, i18n-l10n
---


title: Views, how to construct multiple joins

text:
# Question
Title: Views, how to construct multiple joins
I have a node `activity` with fields referencing the node `location` and a node `sport_type`. As in, for each activity I need to add a location and a sport type.

On the other hand I also have a node `admin` with references to `location` and `sport_type`. As in, I can create an admin for each sport\_type and each location.

How can I create a view which results in the admin when an `activity` nid is given?

In SQL I would write something like:

```
SELECT  admin.name
FROM    admin
JOIN    activity ON activity.location_id = admin.location_id
        AND activity.sport_type_id = admin.sport_type_id
WHERE   activity.nid = :nid

```

I try to create a similar query using the ui of views, where the `activity_id` would be passed in through the url path. I don't know how to implement the join though... Any tips? (Using Drupal 7)

# Answer
What you're looking for is often called "siblings".

When sharing the same Taxonomy terms there are Contextual filters `Has taxonomy term` that can be used and this can work in a lot of cases.

But there are cases even with shared Taxonomy that needs to go a different route (possibly when using Aggregation or Multilingual sites). That second "sibling" route is also what you need to use when the connection is done through an Entity Reference field that isn't Taxonomy, like it is in your case.

The solution is done with the help of two Relationships and one Contextual filter.

1. Create the Content type Views showing Admin nodes. You first add the Relationship for your ER Location field, this introduces info about the referenced node into the Views. In your case this is the info about Location node referenced from Admin nodes.
2. Then you add the **reverse** Relationship to the first one, it will use the first Relationship by default, this is where the matching happens. The second Relationship introduces info about the content that is using that ER field. In your case this is all the Activity nodes that point to the same Location.
3. Add the Contextual filter for Node ID and make it use the **second** Relationship. Set it the usual way, default value and ID from URL, validate against Activity Content type.
4. If this is a Block Display set it to display in a theme region on Activity nodes and adjust its Contextual filter settings. Now when you visit an Activity node you will see listed all the Admin nodes that share the same Location ER.

Repeat the procedure for the second ER field Sport type. You will have 4 Relationships and 2 Contextual filters in the end. Don't build everything at once, test step by step and build it all for only one ER field first.

When building for the second ER field you can use the keyword `all` in Views Preview to "shortcircuit" the first Contextual filter so you can test the second one directly, without interference from the first one (you enter values into Preview separated with `/` for each Contextual filter you have, for example `all/34` to bypass the first Contextual, `all/all` to bypass both Contextuals, or `34/34` to test for the Activity node with the NID 34).

This answer has a bit more details for a similar example: Entity Reference widget selctor in view referring same reference
> 0 votes

---
Tags: views
---


# Question
Title: How can I pass parameters to a Services endpoint?
I have installed Drupal 7 and enabled Services in it. I have also created an endpoint `/api/v2/` and in resources, I have allowed nodes to be listed as JSON.

I have sent a `GET` request using browser or POSTMAN to `/api/v2/node` then I am getting following results.

```
 [
 {
 nid: "3143",
 vid: "3932",
 type: "event_calendar",
 language: "en",
 title: "EVENTS STILL APPEAR ON FRONT PAGE WHEN EVENT HAS ENDED - with or w     ithout an END DATE ",
 uid: "139",
 status: "1",
 created: "1560282811",
 changed: "1560282922",
 comment: "1",
 promote: "0",
 sticky: "0",
 tnid: "0",
 translate: "0",
 uuid: "",
 uri: "http://..../api/v2/node/3143"
 },
...
 ]`

```

If I send a request to `http://..../api/v2/node/[nid]` then I am getting an individual record of that node. Now I want to get post parameters to the endpoint. For example, I want to get all nodes with type = event\_calendar.

I have tried posting parameters like `http://..../api/v2/node?type=event_calendar` but unfortunately, It is still showing list of all nodes. I have tried thing using POSTMAN and browser.

# Answer
You need to use `http://domain/api/v2/node?parameters[type]=event_calendar`

any of the identifiers need to use inside parameters\[\]

Also, you can use services views module to expose the data and create new identifiers like `type` on your own.
> 1 votes

---
Tags: 7, services
---


title: Replacing tokens in Newsletter

text:
# Question
Title: Replacing tokens in Newsletter
I'm trying to create a custom template using the Drupal Newsletter module.

I need to populate the newsletter with existing content. For this, I think I need to replace a token like *\[node:nid\]* in the newsletter body (which is created with CKEditor). However, I have been unsuccessful.

When I use the token filter module, I'm only able to replace global tokens like date or *\[site:url\]* and not tokens involving a node. Can someone please help me out?

# Answer
> 0 votes
Tokens are contextual based on where they are used, so it's not possible to reference arbitrary content. If you can add fields to the newsletter, the ideal way to resolve this would be to add a node reference field, then create your tokens by doing something like \[newsletter:field\_node\[0\]:entity\].

---
Tags: nodes, tokens
---


title: How to use tokens in the Completed URL?

text:
# Question
Title: How to use tokens in the Completed URL?
I need to send data in the URL to the receiving server so that two fields from a survey form is put in the Completed URL string. It looks like it should be possible to use tokens for this, but I can't seem to figure out the correct syntax to use.

I need to send the response to a URL on the form

https://server.tld/sub/value1/value2

where value1 and value2 are fetched from form fields and the rest is static.

According to https://www.drupal.org/project/webform/issues/3021818 this should be possible, if I only could find the correct syntax to use to add the tokens.

**Background** The user gets a link to the survey form in a text message. After filling in the form, the Remote Post handler functionality in Webform should post the results to an external server that expects the survey ID and user alias as parts of the URL (for reasons unknown to me, but apparently expensive and difficult to change) for the purposes of knowing when the user has filled in the survey so as to avoid sending out a reminder.

**What I have tried** I have tried formatting the Completed URL string in various ways; like for example

http://example.com/%value\[my\_fieldset\]\[a\_value\_in\_the\_form\]

and

http://example.com/%value

but I just get a URL invalid error response when I try to save the setting.

# Answer
I managed to get it going using the standard tokens so in Completed URL I had https://URL/API?query=\[webform\_submission:values:fieldname\] \- so just swap out fieldname for the key in the webform you want to pass
> 0 votes

---
Tags: webforms
---


# Question
Title: Do custom theme suggestions execute on every page load and does that impact performance?
I've been working with Drupal for a little while now and one nagging question I've had is about whether or not logic in my \*.theme or \*.module files have any impact on server load.

Let's say I have this bit of code in my \*.theme file:

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

  if(\Drupal::routeMatch()->getRouteName() == 'entity.node.edit_form' && \Drupal::routeMatch()->getParameter('node')->bundle() === 'blog_general') {
    $suggestions[] = 'page__no_sidebars';
  }
}

```

This bit of code adds a template theme at the page.html level. I only need this for about 1% of my site and it bothers me a little that this would need to execute on every page load just so 1% of my site can templated correctly.

So my question is, would this code get executed on every page load? Or does the caching take care of it? If it does execute on every page load then this one bit of code might be trivial. However, I'm slowly building up a lot of these types of altering hooks and it's bugging me that they could be taxing the server.

I appreciate any insights. Thanks!

# Answer
> 1 votes
To answer your questions:

1. Yes, it executes on every page load.
2. It won't impact your server load any noticeable amount.

The amount of processing power for that one function is extremely low. You could probably run it 1000 times without causing a noticeable performance it.

---
Tags: 8, theming, performance
---


# Question
Title: How do I populate fields in content type not in feed when importing?
I have a content type that contains a couple of required fields that do not have a mapping counterpart in the csv feed. When I import the csv feed, the process fails because of the required fields. What plugin can I use in a custom module to 'finish' the import by providing the values for the other fields? Is this even possible?

# Answer
You can use the Feeds Tamper plugin "Set value or default value".

1. Install the modules Tamper and Feeds Tamper.
2. Go to the mapping page.
3. Select a target that you want to set a default value for.
4. On the source selector that appears, select "New CSV source". Type in a source name that does *not* appear in your CSV file.
5. Repeat step 2 and 3 for every field you want to set a default value for and save the mappings.
6. Go to the 'Tamper' page.
7. For each target you want to set a default value for, click on "Add plugin". From the selector that appears, select "Set value or default value".
8. A field called "Value" appears. Fill in the default value and click "Submit".
> 1 votes

---
Tags: 8, feeds
---


# Question
Title: Is there a difference in the use of hook_preprocess_HOOK()
Is there a difference in the use of hook\_preprocess\_HOOK()?

In Drupal 8 when I use :

* hook\_preprocess\_page
* hook\_preprocess\_node
* hook\_preprocess\_block

All my Implements for page, node or block work good.

But when I use **hook\_preprocess\_menu** some staff don't want to work, what work in preprocess function up.

For example:

This work perfect

```
function theme_name_preprocess_page(&$variables) {
  $variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
}

```

But this don't work.

```
function theme_name_preprocess_menu(&$variables, $hook) {
$variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
  }

```

# Answer
> 4 votes
If you use:

```
function theme_name_preprocess_menu(&$variables, $hook) {
  $variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
}

```

The hook is **menu**, so Drupal will look for `menu.html.twig`, if you define any var inside this preprocess you only be able to use in `menu.html.twig`. Look the Hook at your theme suggestions comments, if you see 'block' you will need use `theme_name_preprocess_block` instead.

# Answer
> 0 votes
I think you need to check the file-suggestion by enabling in services.yml debugging, after that you will find the right Hook name. Then you can use....

function theme\_name\_preprocess\_Hook\_name(&$variables, $hook) { $variables\['logopath'\] = '/' . drupal\_get\_path('theme','theme\_name') . '/logo.png'; }

---
Tags: 8, theming
---


title: ReferenceError: Drupal is not defined

text:
# Question
Title: ReferenceError: Drupal is not defined
I am working on a production site, moving settings from a development site for a mobile environment. However, I am receiving the above error. I can not figure out what is causing this error. It does not matter what theme I change my jquery mobile environment too. I've checked all the modules and they seem to be the same versions. The only thing I can see that is different is in the development site I can uncheck/check the block cache, on the production environment I can not do this.

# Answer
> 13 votes
Sounds like an issue with the ordering of the javascript files. Drupal is defined in

`/misc/Drupal.js`

```
var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} };

```

Check Drupal.js is added to your HTML source, prior to when that variable is requested.

# Answer
> 9 votes
In drupal 8 you might have to add core/drupal as a dependency of your module.

```
your-custom-module:
  version: 1.x
  js:
    js/your_custom_module.js: {}
  dependencies:
    - core/drupal
    - core/drupalSettings

```

# Answer
> 1 votes
I've experienced the same problem installing a drupal 7 web site from a dump.

The original `default` folder was provided empty for sizes management. After pushing in the `settings.php` file and the `files` directory the `Drupal is not defined` error was there.

Originally the developers had two other folders inside the `default` folder.

When restored this folders the error was solved.

# Answer
> 0 votes
As mentioned by @David Thomas, this is an issue with file `misc/drupal.js`. Drupal by default puts it into the correct order. So most likely, the file is not accessible by your web server. Create its URL and try accessing it in your browser, and you will see.

In my case, this was due to using PHP-FPM (which runs with user rights similar to `mod_suphp`), and forgetting that static files (\`png, jpg, css, js etc.) are still served by apache2 in my case. So these needed to be world-readable.

---
Tags: caching, javascript
---


title: Other twig syntax in templates

text:
# Question
Title: Other twig syntax in templates
In some twig templates of the commerce modules, I can see the use of an alternate syntax:

Ex. in `commerce-cart-flyout-offcanvas-contents-items.html.twig` :

```
<% _.each(cart.order_items, function(orderItem, key) { %>

```

or

```
<%= orderItem.total_price.formatted %></td>

```

I can't see any doc on this and as I am curious, I would like to know from where it is coming and what is the difference.

# Answer
> 2 votes
> In some twig templates of the commerce modules, I can see the use of an alternate syntax:

This is only in one module - Commerce Cart Flyout. These are Underscore.js templates. These are used to customize the JavaScript progressively decoupled cart flyout. These are not actually Twig templates.

It was a design decision I regret to try and enable end-users to customize Flyout without needing to learn how to override JavaScript.

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


# Question
Title: How to use hook_views to add calculation to a field?
In a custom module (assoc), I have a custom Content Entity (Person) with these fields:

```
$fields['lastname'] = BaseFieldDefinition::create('string')
$fields['firstname'] = BaseFieldDefinition::create('string')
$fields['email'] = BaseFieldDefinition::create('email')
$fields['cellphone'] = BaseFieldDefinition::create('telephone')
$fields['balance'] = BaseFieldDefinition::create('integer')

```

I use Views to display a table of the persons. Here is the corresponding Views preview:  Before displaying the output, I'd like to add some value to the field 'balance':
`balance = balance (of content entity) + somecredit - somedebit`
'somecredit' and 'somedebit' being calculated by a query to the database.
What is the hook\_views I should use ?
And how do I do?

# Answer
Finally, after some (!!) digging, I did it in `assoc_views_post_execute`

```
function assoc_views_post_execute(ViewExecutable $view)
{
  switch ($view->id()) {
    case 'assoc_persons':
      if ($view->current_display == 'page_1') {
        $database = \Drupal::database();
        foreach ($view->result as $key => $value) {
          $person = $value->_entity->get('id')->value;
          $solde = $value->_entity->get('balance')->value;

          some code to calculate credit with database query
          $credit = $result[0]->credit;

          some code to calculate debit with database query
          $debit = $result[0]->debit;

          $solde = $solde + $credit - $debit;
          $value->_entity->set('balance', $solde);
        }
      }
      break;
    default:

  }
}

```
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: How do I pass a response from a Webform custom handler back to Drupal to display on the confirmation page
I have created a custom module for a custom Webform handler. The custom handler submits to an external SOAP api. There are various response options that are received back from the SOAP api that currently I am printing to screen (for testing purposes). But when using this module in production, I obviously want these responses to be displayed at the top of the confirmation page.

Is there some way to populate a token (possibly the Webform Handler Response token?), which I can then use to print the information on my confirmation page?

F

# Answer
Your two options are…

OPTION 1: Add the SOAP API's response value as a hidden element's value using something like

```
$webform_submission->setElementData('response_value', $response->value);
$webform_submission->resave();

```

OPTION 1: Store the response in $\_SESSION and use

```
\Drupal\webform\Plugin\WebformHandlerInterface::confirmForm
\Drupal\webform\Plugin\WebformHandlerInterface::preprocessConfirmation

```

to alter the confirmation message or page.
> 0 votes

---
Tags: webforms
---


title: GraphQL query not returning data

text:
# Question
Title: GraphQL query not returning data
I have 5 different content types and I've added content / nodes. I'm using graphQL to fetch the data, however in 1 of the content types the data is not being returned. This is the latest content type I've added, so I can query data from all 4 other content types and get the data I expect without any problems using fragments.

My query for the new content type is simple.

```
{
  nodeQuery {
    entities {
      ...on NodeGlobalContent {
        title
        body {
          value
        }
      }
    }
  }
}

```

The empty result is the following.

```
{
  "data": {
    "nodeQuery": {
      "entities": [
        {},
        {},
        {},
        {},
        {},
        {},
        {},
        {},
        {},
        {}
      ]
    }
  }
}

```

If I query the node by ID, I get the following data.

```
query {
  nodeById(id: "20") {
    entityLabel
    entityBundle
  }
}

{
  "data": {
    "nodeById": {
      "entityLabel": "test",
      "entityBundle": "global_content"
    }
  }
}

```

Why can't I retrieve the data using a fragment?

# Answer
> 0 votes
The answer is to filter by content type:

```
{
  nodeQuery(
    filter: {
      conditions:[
        {operator: IN, field: "type", value: ["global_content"]},
      ]
    }
  ) {
    entities {
      ...on NodeGlobalContent {
        title
        body {
          value
        }
      }
    }
  }
}

```

---
Tags: 8
---


title: What is a "link template" in a token?

text:
# Question
Title: What is a "link template" in a token?
When configuring a webform submission URL by using tokens, I noticed this entry that specifies a **link template**:

> ```
> [webform_submission:url:?]
>
> ```
>
> The URL of the webform submission. Replace the '?' with the link template. Defaults to 'canonical' which displays the submission's data.

What is a link template? Can I customize or define my own? How would I know what other tokens can be used in place of '**canonical**'?

# Answer
> 3 votes
Link templates are defined in the entity class. For webform\_submission:

```
 *   links = {
 *     "canonical" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}",
 *     "access-denied" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/access-denied",
 *     "table" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/table",
 *     "text" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/text",
 *     "yaml" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/yaml",
 *     "edit-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/edit",
 *     "notes-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/notes",
 *     "resend-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/resend",
 *     "duplicate-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/duplicate",
 *     "delete-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/delete",
 *     "collection" = "/admin/structure/webform/submissions/manage/list"
 *   },

```

Source: https://git.drupalcode.org/project/webform/blob/8.x-5.x/src/Entity/WebformSubmission.php

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


# Question
Title: Modify token used in path URL alias generation
We would like to have the URL pattern for `Article` content type to use `article/[node:field_short_description]`. In the scenario where `field_short_description` is not populated, we would like for the URL pattern to be `article/[node:title]` as a fallback.

**Questions**

1. Is it possible to use the `field_short_description` field if populated, else use the `title` field without custom code?
2. How would we do this without custom code?

We tried to use `article/[node:field_short_description]|[node:title]` but when both fields are populated, then both are added to the URL.

# Answer
We found the solution using the sample found on How To Create A Custom Token In Drupal 8?

Code

```
/**
 * Implements hook_token_info().
 */
function my_module_token_token_info() {
  $info = [];
  $info['types']['my_token_group'] = ['name' => t('Custom Group'), 'description' => t('Custom Group')];
  $info['tokens']['my_token_group’][‘my_token’][] = 'A token to extract desired characters from Node body to be used in meta descriptions';
  return $info;
}

/**
 * Implements hook_tokens().
 */
function  my_module_token_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'my_token_group') {

    foreach ($tokens as $name => $original) {
      // Find the desired token by name.
      switch ($name) {
        case ‘my_token’:
          $node = $data['node'];
          if(is_object($node) && !$node->myFieldName->isEmpty()) {
            $token_value = $node->myFieldName->value; // or something similar.
          }
          else {
            $token_value = $node->label();
          }
          $replacements[$original] = $token_value;
          break;
      }
    }
  }
  return $replacements;
}

```
> 0 votes

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


# Question
Title: How to Restrict some special character in password field
I'm very new in Drupal, I would like to restrict some special characters from user password field Is there any way to edit configuration of core modules i'm trying to create preg\_match modules . i would like to allow only these character in password fields.

```
preg_match('/[^ A-Za-z 0-9 ,.-()]/'), $edit-pass-pass1

```

# Answer
Don't re-invent the wheel if these will solve your needs and hopefully wants.

https://www.drupal.org/project/password\_policy

also worth looking into https://www.drupal.org/project/password\_strength

If those don't work, I think you're looking at a form alter related to validation. Drupal 8 is the wonderful world of Form Alters... so look into those even if the above solves your needs.
> 0 votes

# Answer
Read you comments on my other answer. Here's how I would start tackling in your situation. I think you're going down a Form Alter method. Start off simple. Create a new module with just an .info and .module. In the .module, add code to find what you're looking for. KSM will show you the array and you can dig in.

```
/**
 * Implements form_alter().
 * form_id : node_check_in_form
 */
function yourmodulename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  ksm($form_id);
  switch ($form_id) {
    //turn off the ability to edit 'type' after creation per spec
    case 'yourcasehere':
      ksm($form);
      break;
...

```

Basically, figure out your form name. Then see what the form is. You can alter the form to have new validation.

https://www.drupal.org/docs/8/api/entity-api/entity-validation-api/providing-a-custom-validation-constraint
> 0 votes

---
Tags: 8, theming, users, configuration
---