title: Drop UserMailRequired constraint

text:
# Question
Title: Drop UserMailRequired constraint
In my Drupal site, only administrators create users. And users are created without an email. Users can edit themselves some of their account fields, but the email is not one of them.

But the user module adds a `UserMailRequired` constraint to the User entity email field. On submit, the user module's validator `UserMailRequiredValidator` adds a violation if the current user is not an administrator :

```
class UserMailRequiredValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    /** @var \Drupal\Core\Field\FieldItemListInterface $items */
    /** @var \Drupal\user\UserInterface $account */
    $account = $items->getEntity();
    $existing_value = NULL;
    if ($account->id()) {
      $account_unchanged = \Drupal::entityManager()
        ->getStorage('user')
        ->loadUnchanged($account->id());
      $existing_value = $account_unchanged->getEmail();
    }

    $required = !(!$existing_value && \Drupal::currentUser()->hasPermission('administer users'));

    if ($required && (!isset($items) || $items->isEmpty())) {
      $this->context->addViolation($constraint->message, ['@name' => $account->getFieldDefinition('mail')->getLabel()]);
    }
  }

}

```

So, none of my user can edit its profile. On submit, they get an error message "Email field is required". Even if the field's `#required` property is set to false (using hook\_form\_alter) and the field not displayed (`#access` = false) in the form render array.

How can I drop this constraint from a custom module ? (using a hook for example)

# Answer
For those that find themselves here trying to make User Emails Optional, use hook\_validation\_constraint\_alter. You're not extending core's, you're creating a new constraint and using it instead of core's. In my case, I replace core's with... an empty function to achieve what I want.

Something like this in .module

```
function optional_account_email_validation_constraint_alter(array &$definitions) {
  $definitions['UserMailRequired']['class'] = '\Drupal\my_module_name\Constraint\OverrideUserMailRequired';
}

```

Then a copy of the two UserMailRequiredValidator.php and UserMailRequired.php files changed to your liking.

The module administerusersbyrole has a working example of this.

I'll see if I can get around to putting my custom module onto drupal.org in the coming months.
> 4 votes

---
Tags: 8, users, forms
---


title: Why is my migration status table empty?

text:
# Question
Title: Why is my migration status table empty?
I wanted to delete all migration modules because of that I use

```
drush config-delete migrate_plus.migration.ID

```

After that, I create a new migration module and enable it with

```
drush en migrate_NAME

```

and rebuild the cache. I look at the status table with

```
drush migrate:status

```

but the table shows no migration. If I enable the migration again I get the message "Already enabled". When I try to import something I get the message "No migrations found". Does anyone have any idea why this might be?

# Answer
> -1 votes
I think that you are mixing up things. By doing

```
drush config-delete migrate_plus.migration.ID

```

you are just deleting migration\_plus configuration but you are not disabling the module, it is still enabled. If you really want to disable the module and of course the configuration, you'll have to `drush pm migrate_plus`.

Concerning the "No migrations found" message, your custom module has to define correctly the new migrations (.yml files).

---
Tags: migrations
---


title: Required fields

text:
# Question
Title: Required fields
I'm doing a migration from csv to Drupal 8 and I'm not sure how to handle the required fields.

My content type "Department" has 8 required fields, should I use the plugin "skip\_on\_empty" in every migration field? There is a simpler way to do this?

The point is prevent empty required fields. Thanks all.

# Answer
This is actually a business decision and not a Drupal related question. You have three solutions

1. Bring in the data as is and end up with a corrupted database
2. Skip rows that do not answer to your requirements
3. Give default values to the required fields
> 1 votes

---
Tags: 8, migrations
---


# Question
Title: How do I change the Views (Entity Reference) filter via AJAX?
I have an entity form that allows an admin to select a content type (checkbox) and an autocomplete field that is tapped into a VIEWS Entity Reference (via the Reference Method).

Goal: What I would like is to have the views entity reference filter dynamically change based off the end-user selection. Contextual Filters would have worked but I think Filters is better because of the multiple selection.

So far I have a view with entity reference and it is pulling the correct data for content 1-4. When I use the autocomplete it does what it's supposed to. I think the next step is to use AJAX to change how the autocomplete pulls from the view by changing the FILTER.

Can you help me figure out how I can change the views filter via AJAX/JS?

# Answer
I am going to answer my own question in hopes this ccan help someone. However I am welcome to hear other options :)

What I ended up doing was attach a javascript that updates the autocomplete's path. Meaning when a user clicks on the checkbox it updates the input box for the autocomplete's attribute. The attribute called `data-autocomplete-path`. I appended a query string without messing with the functionality of it. This extra value gets sent to `hook_views_pre_view`.

This worked for me
> 0 votes

# Answer
The core issue for this is Add AJAX support to fields using Dynamic Views Arguments via Tokens, but at the time of this writing the only option available without custom coding is Business Rules' dependent field functionality.

However, there are still unresolved problems with multi-valued fields. See Multi-valued dependent child fields are not saved for more information.
> 0 votes

---
Tags: views, 8, entities, hooks, ajax
---


# Question
Title: Drupal 8 - Use the current node ID (on node edit form) to filter an entity-reference view as a contextual filter
I've got this view I just created, which lists all the events && publications related to a program (field\_program, an entity-reference field) on my website (Drupal 8). Call it "view\_program\_related\_contents".

I've got this content type (program), with a entity-reference field (field\_promoted\_contents). About this field, I want to use a view, because I don't want the webmaster to be able to promote events|publications related to any program but the one he's editing, so I have to filter the results based on the field\_program field.

I did set a contextual filter (field\_program) on my view. When this filter is not available, I fill it whith a default value : "Content ID from URL".

I can't manage to get my field\_promoted\_contents field populated with the well-related contents. If I set a static value (node id 1) in the contextual filter, it works, I only have the contents related to this first program. But when I set this "Content ID from URL".. I get no results :(

Do I have to pass a token (such as \[node:nid\]) as an argument to the view in the entity-reference field configuration ? Is there a module for that ?

# Answer
> 1 votes
This might not be THE answer. But for my specific need, and because we already are late on this project. I found a "quick-fix" solution.. waiting for a more drupalistic one.

Assuming that this entity-reference-1 view display is always called from a node/:nid/edit page, I should always have a HTTP\_REFERER on each request to the view (I guess ^^). Well, I check that for insurance.

Inside a hook\_views\_pre\_view hook, I pass the node-id from the HTTP\_REFERER to the view, like this :

```
<?php

use \Drupal\node\Entity\Node;

/**
 * Implements hook_views_pre_view()
 *
 * Alter the contextual filters for my view :
 *
 * When the HTTP_REFERER is a node/:nid/edit pattern and the view-display is an entity-reference
 *  then I fetch the node ID from the URL, I load the node to check the node type
 *  and I pass this nid to the view as an arg
 */
function MYMODULE_program_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'view_program_related_contents' && $display_id == 'entity_reference_1') {
    if (isset($_SERVER['HTTP_REFERER'])) {
      $referer_url = parse_url($_SERVER['HTTP_REFERER']);
      $path = htmlspecialchars($referer_url['path']);
      if (preg_match('/node\/(\d+)\/edit/', $path, $matches)) {
        $node = Node::load($matches[1]);
        if ($node instanceof Node) {
          if ($node->getType() == 'program') {
            $args[] = $node->id();
          }
        }
      }
    }
  }
}

```

Again, I think I'm missing something in my entity-reference field definition, or my view configuration.. but I don't have enough time to spend on this.

I hope this helps..

# Answer
> 0 votes
> Do I have to pass a token (such as \[node:nid\]) as an argument to the view in the entity-reference field configuration?

Yes.

> Is there a module for that?

No, but this will work in core with a patch from Dynamic Views Arguments via Tokens.

If you'd like the depending field to update automatically whenever the dependent field changes, see Add AJAX support to fields using Dynamic Views Arguments via Tokens.

---
Tags: views, 8, entities
---


# Question
Title: Deployment using Composer replacing old style install but issues with legacy Drush
I took a Drupal project that was created awhile back via downloading a tar file and recreated it on a local via composer with drupal-project.

The recommended files were committed to git (i.e. no contributed modules, etc.) and cloned on the server. The composer install was clean.

At the point of doing a `$ drush sqlc` to load the database, it became evident that there was an issue - Drush error message below. I believe the issue is that Drush was already installed.

`$ which drush` outputs `/home/me/.composer/vendor/bin/drush`.

The error message when I attempt to run `drush sqlc` or `drush status` from the project, even with `--root`, is the following.

> PHP Warning: require(/var/www/html/drupal/d8/vendor/composer/../../load.environment.php): failed to open stream: No such file or directory in /var/www/html/drupal/d8/vendor/composer/autoload\_real.php on line 70 PHP Stack trace: PHP 1. {main}() /var/www/html/drupal/d8/vendor/drush/drush/drush:0 PHP 2. require() /var/www/html/drupal/d8/vendor/drush/drush/drush:4 PHP 3. include\_once() /var/www/html/drupal/d8/vendor/drush/drush/drush.php:56 PHP 4. ComposerAutoloaderInit6220513682b217c143f76d07878222a3::getLoader() /var/www/html/drupal/d8/vendor/autoload.php:7 PHP 5. composerRequire6220513682b217c143f76d07878222a3() /var/www/html/drupal/d8/vendor/composer/autoload\_real.php:60 PHP Fatal error: require(): Failed opening required '/var/www/html/drupal/d8/vendor/composer/../../load.environment.php' (include\_path='/var/www/html/drupal/d8/vendor/pear/pear\_exception:/var/www/html/drupal/d8/vendor/pear/console\_getopt:/var/www/html/drupal/d8/vendor/pear/pear-core-minimal/src:/var/www/html/drupal/d8/vendor/pear/archive\_tar:.:/usr/share/php') in /var/www/html/drupal/d8/vendor/composer/autoload\_real.php on line 70 PHP Stack trace: PHP 1. {main}() /var/www/html/drupal/d8/vendor/drush/drush/drush:0 PHP 2. require() /var/www/html/drupal/d8/vendor/drush/drush/drush:4 PHP 3. include\_once() /var/www/html/drupal/d8/vendor/drush/drush/drush.php:56 PHP 4. ComposerAutoloaderInit6220513682b217c143f76d07878222a3::getLoader() /var/www/html/drupal/d8/vendor/autoload.php:7 PHP 5. composerRequire6220513682b217c143f76d07878222a3() /var/www/html/drupal/d8/vendor/composer/autoload\_real.php:60

In addition to Drush being in both `~/.composer/vendor` and `<root>/vendor`, I note that `~/.composer` contains

```
autoload.php
composer
phpdocumentor
phpunit
symfony
bin
doctrine
phpspec
sebastian

```

How do I go about cleaning this up so that the project root is the sole repository of these files and Drush can find what it's looking for?

# Answer
As @Jaypan commented, globally you only need the Drush Launcher as phar file. And remove the old globally installed Drush version, this install method via `composer global require` is no longer supported. If you still need a legacy Drush version for other Drupal sites, download it the same way as phar file, see http://docs.drush.org/en/8.x/install. Which then can act as launcher by the way, so you don't need the Drush Launcher in this case.
> 3 votes

# Answer
If you need global drush for legacy sites, and local drush for drupal-composer projects, then this may work for you.

I keep a copy of drush from Github, and fetch and checkout the latest 8.X.Y tag periodically. This executable is on my bash path.

For drupal-composer projects, I use direnv, and then put the following in my .envrc

```
PATH_add /home/mpdonadio/my-drupal-site/vendor/bin

```

Then when you cd into that directory, the vendor/bin for that project gets prepended to PS1, and that version of drush gets used. This lets me use Drush 9 for newer projects, and when combined with webflo/drupal-core-strict and drupal-core-require-dev you can avoid most dependency problems.

This approach also allows better control of drupal console, phpunit, and other dev executables; they gets added to the path and will pull in the same dependencies, and avoid update issues.
> 1 votes

---
Tags: drush
---


# Question
Title: using form_state->set() inside ajax callback but cannot get the value back outside the callback
I want to add some arbitrary variable to store it in the form\_state and use it again so in one of my ajax callback functions I set a property named var:

```
public function MyFunctionCallback(array &$form, FormStateInterface &$form_state) {
....
$terms = array('1'=>'one','2'=>'two');
$form_state->set('var', $terms);
....
}

```

it works and the storage array of the form\_state has var element

unfortunately when trying to get the var back inside another callback function it returns null. actually with debugging the storage array of the form\_state is empty

```
public function MyOtherFunctionCallback(array &$form, FormStateInterface &$form_state) {
....
$terms = $form_state->get('var');
....
}

```

# Answer
> 0 votes
You can't change `$form` or `$form_state` in an ajax callback. There is no more code coming after the callback, that could process this. The only purpose of the ajax callback is to prepare and return an ajax response.

# Answer
> 2 votes
As 4k4 mentioned, you cannot change the form state inside an ajax callback function.

You can, however, change it in the ajax button submit function.

```
$form['ajax_button']['#submit'][] = [static::class, 'ajaxButtonSubmit'];

public static function ajaxButtonSubmit($form, $form_state) {
  //...
}

```

# Answer
> 0 votes
I would like to avoid using PHP session variables here since it is easy to get mixed with other forms. Especially if the user wants to keep this form open and tried to open another form.

Instead of PHP session variables, you may try to change the logic and move your code to a validation callback for the whole form. And from there you can set form state values.

```
$form['#validate'][] = '::handleInputs';

```

Since probably what you need is part of validating the user inputs and showing specific options depend on user inputs.

---
Tags: forms, 8, ajax
---


# Question
Title: How to deal with Bubbleable Metadata when there's no rendering context and no render array
Since Drupal 8.0.0-beta12 "all rendering must happen in a render context", as stated by this change record.

This is to avoid bubbleable metadata lost. So far, so good.

Let's say I'm implementing a Commerce payment notification. The important part is a server calls a Drupal URL to notify something. The controller, as far as I know, doesn't need any rendering context because the answer is simple (almost just a status response). Good.

Let's say I want to send an email on this event. I create an EventSubscriber that subscribes to the payment event that happens on this callback. I hook on the event, gather the email data, and call the send function. During sending, Drupal renders the content (is an HTML email!) and I got the error: since there's no rendering context Drupal throws an exception. The point the error is triggered is when Token::replace() is called:

```
$body = $this->token->replace($this->getBody(), $this->getTokenData());

```

**How to fix this?**

Option 1: Use the `BubbleableMetadata $bubbleable_metadata` fourth param of Token::replace(). This param docs states:

> An object to which static::generate() and the hooks and functions that it invokes will add their required bubbleable metadata.
>
> To ensure that the metadata associated with the token replacements gets attached to the same render array that contains the token-replaced text, callers of this method are encouraged to pass in a BubbleableMetadata object and apply it to the corresponding render array.

But because `$body` is just a plain string I guess the bubbleable metadata is lost, so what's the point of caring?

Option 2: Follow the change record suggestion and use RenderContext::executeInRenderContext(). In that case I'd wrap the whole process:

```
$renderer = \Drupal::service('renderer');
$context = new RenderContext();
$that = $this;
$response = $renderer->executeInRenderContext($context, function() use ($that, $recipient) {
  $that->mailer->send($recipient);
  });

```

Again, I'm discarding the cacheable metadata.

I guess discarding that cacheable data is ok because the email is totally uncacheable, the whole body and its parts (because the replaced strings with tokens have URLs that would change on every email).

Are both approaches ok? Is one better than the other? Is there a third approach more suitable for this problem? I guess the problem can be summarized as how to deal with Bubbleable Metadata when there's no rendering context and no render array.

# Answer
Yes, when rendering email data you have to take care that you don't bubble up metadata to the render context of the main response.

There is a third option, and in most cases the best option: The method Renderer::renderPlain, which not only discards bubbleable metadata, but also makes sure your email doesn't contain leftover placeholders:

> Renders final HTML in situations where no assets are needed.
>
> Calls ::render() in such a way that placeholders are replaced.
>
> Useful for instance when rendering the values of tokens or emails, which need a render array being turned into a string, but do not need any of the bubbleable metadata (the attached assets and cache tags).
>
> Some of these are a relatively common use case and happen *within* a ::renderRoot() call, but that is generally highly problematic (and hence an exception is thrown when a ::renderRoot() call happens within another ::renderRoot() call). However, in this case, we only care about the output, not about the bubbling. Hence this uses a separate render context, to not affect the parent ::renderRoot() call.
>
> (Can be executed within another render context: it runs in isolation.)

And it's always a good idea to build a render array to produce HTML. For example if you have a formatted text field then build a processed text render element: How to safely render node body on a custom variable?
> 5 votes

---
Tags: 8, caching, page-controller
---


# Question
Title: How to prevent executing .php files in sites/default/files directory for nginx+php7.0-fpm?
URL to Drupal.org article Preventing execution of untrusted PHP

By default `.htaccess` inside `sites/default/files` contains:

```
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

Adding `mod_php7.c` version doesn't fix.

Temporary solutions are:

```
ProxyPassMatch ^/(.*\.php(/.*)?)$ "fcgi://127.0.0.1:9000/var/www/drupal"

```

And

```
<FilesMatch \.php$>
   SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>

```

But they are not recommended and they are overrideable.

There is a Drupal Core issue for adding `mod_php7.c` to `.htaccess`, but it's only for Drupal 8 (so how is this solved in Drupal 7 then?) https://www.drupal.org/node/2455465

There is solution for Apache How to disable PHP files from being run in the sites/default/files directory? but not `nginx` and `php7.0-fpm`.

So what is the solution?

(I'm running Security Review module that reports PHPs are executable within sites/defaul/files)

Screenshots:

Permissions:

```
www-data:www-data 755 for dirs / 644 for files

```

.htaccess:

```
# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

<IfModule mod_php7.c>
  php_flag engine off
</IfModule>

```

I did restart nginx and php7.0-fpm.

# Answer
Since Nginx doesn't use .htaccess files, you have to place all your directives into the /etc/nginx/sites-available/yoursite.tld.vhost file. To prevent executing .php files, add the following lines.

```
location ~ \..*/.*\.php$ {
    return 403;
}

```

Place those lines before these lines.

```
location / {
    try_files $uri /index.php?$query_string;
}

location ~ '\.php$|^/update.php|^/cron.php' {
    fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
    include fastcgi_params;
    # Block httpoxy attacks. See https://httpoxy.org/.
    fastcgi_param HTTP_PROXY "";
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param QUERY_STRING $query_string;
    fastcgi_intercept_errors on;
    fastcgi_read_timeout 180;
    # PHP 7 socket location (change it to fit your config)
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}

```

If there's a request for */anything/../file.php*, it will return a 403 error, since PHP files rarely should be accessible from outside (except for index.php, update.php, and cron.php).
> 0 votes

# Answer
This is what works for nginx and only targets files directory:

```
location ~ /files/.*\.php$ {
    return 403;
}

```

This is more generic and wont let any php file in a directory execute directly:

```
location ~ /.*/.*\.php$ {
    return 403;
}

```

WARNING, this is posted all over the web but only works for hidden directories:

```
location ~ \..*/.*\.php$ {
    return 403;
}

```
> 5 votes

# Answer
How the Nginx site shows it done:

```
# Block access to scripts in site files directory
location ~ ^/sites/[^/]+/files/.*\.php$ {
    deny all;
}

```

The full reference file is here:
https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/
> 1 votes

---
Tags: 7, .htaccess
---


# Question
Title: Need to force #default_value for AJAX tableselect checkboxes
I built a drop-down ajax pager that replaces a tableselect with the requested page of rows. The array of selected item IDs is stored in a hidden field and that logic is working across entity load/save and AJAX replacements.

When the form initially loads, my tableselect #default\_value operates correctly and checks the selected rows on the first page. But after AJAX paging through the big list to a different page and back, the checkboxes aren't checked again.

I think this has to do with #default\_value only working before the form has been submitted. How can I reset the state so that my updated tableselect #default\_value is used after AJAX?

# Answer
Just before the tableselect's array in the form builder function, put the following code:

```
unset($form_state['input']['my_tableselect']);

```
> 4 votes

# Answer
For those ones experiencing the same case in Drupal 8, this is the equivalent solution:

```
$user_input = $form_state->getUserInput();
unset($user_input['my_tableselect']);
$form_state->setUserInput($user_input);

```
> 0 votes

---
Tags: forms, ajax, theming
---


title: node access permission

text:
# Question
Title: node access permission
i have created a custom block where i retrieve few fields value from a content of specific content-type(called project)and display it as a card in the site. but i don't want users who have logged into the site to see the actual content of that content type. to do this i have enabled node access permission and disabled access to view content through node ui for that content-type. the issue is the custom block doesn't get the values from the content. how can i fix this?

# Answer
> -1 votes
i did this $nids = $query -\>addMetaData('account', user\_load(1)) -\>execute(); and it fetched the value as an admin.

---
Tags: blocks
---


# Question
Title: Delete multiple entites without loading them - running out of memory
I'm deleting multiple nodes like this:

```
$nids = [21,12,45,67]; // Just an example, this data comes from elsewhere
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
\Drupal::entityTypeManager()->getStorage('node')->delete($nodes);

```

Drupal is running out of memory when deleting just 6 nodes.

I'm having this problem in general, not just when deleting, but any time I work with multiple nodes. The PHP memory\_limit is 256MB and the server admin is reluctant to increase this. Even if it is increased, it's just postponing the problem - it might fail on 12 or 16 instead of 6.

Is there another way, e.g. to delete based on nid without loading the full node object and all of its fields? The deprecated `entity_delete_multiple` appears to load the entities before deleting anyway. I suspect it has to because various hooks have to be called and it has to delete revisions and field data.

Or is there some special way I can code it to delete one node at a time and free each object afterwards to keep memory usage low?

# Answer
> 8 votes
Loading/deleting one at a time may use less memory:

```
use Drupal\node\Entity\Node;

$nids = [21,12,45,67];
foreach($nids as $nid)
{
  $node = Node::load($nid);
  $node->delete();
}

```

Each loop will overwrite the previous instance of `$node`, releasing the memory.

# Answer
> 8 votes
You could also chunk the array of ids into smaller chunks in order to use less memory and avoid looping once for every single node:

```
$nids = [
   // Some big list of nids...
];
$storage = \Drupal::entityTypeManager()->getStorage('node');
foreach (array_chunk($nids, 50) as $chunk) {
  $nodes = $storage->loadMultiple($chunk);
  $storage->delete($nodes);
}

```

---
Tags: 8, nodes
---


title: Image uploads seem to be timing out

text:
# Question
Title: Image uploads seem to be timing out
I hate asking a vague question like this but I'm really at loss as to my current problem. I'm setting up a new site and image uploads fail on my production site (both in custom and content type forms). The failure occurs when a file is sufficiently large (greater than ~4mb). I believe the failure has more to do with something timing out rather than a limit to file size. At my office where the connection is good I can upload an 8mb image but on my slower home connection I can't upload more than a 4mb image. The upload seems to consistently timeout at about 20 seconds.

When the upload fails the form itself doesn't provide any feedback. The little blue spinner just disappears and the remove button never appears. The only feedback I receive is through the browser's console. I'm getting a `HTTP Result Code: 400` error. Paths are good because like I said I'm able to successfully upload when the image or file is sufficiently small.

My relevant php settings are:

```
max_execution_time 300
max_input_time -1
post_max_size 18M
upload_max_filesize 16M

```

I'm able to confirm these php settings through a phpinfo.php page so I'm reasonably confident it's not this.

I'm running Drupal 8.7.6 on CentOS7 with PHP 7.2.21.

Does anyone have a good guess as to what my problem could be? I'm sorry this is vague and most likely not an issue with Drupal. Thanks, I appreciate any hints you might provide.

# Answer
Set your max\_execution\_time 300 to -1 which is unlimited or can increase according to your need. And memory\_limit to 1024M or more.
> 0 votes

---
Tags: 8
---


title: The site crash when add a server

text:
# Question
Title: The site crash when add a server
I'm trying to use Search\_api\_solr and search-api. I install the required modules and run the solr server and create a core. But when I'm trying to add a server to my drupal 8 site, an error appears `Solarium\Exception\UnexpectedValueException: Neither collection nor core set. in Solarium\Core\Client\Endpoint->getBaseUri() (line 299 of /var/www/html/vendor/solarium/solarium/src/Core/Client/Endpoint.php).`

I try to change the following block in Endpoint.php file to my data but it's not working.

```
protected $options = [
        'scheme' => 'http',
        'host' => 'xx.xx.xx.x',
        'port' => 8983,
        'path' => '/solr/',
        'collection' => null,
        'core' => 'my_core',
        'timeout' => 5,
        'leader' => false,
    ];

```

also, should the host include the http:// or only the ip address? However, I try all above with no luck. Any advice. Thanks in advance.

# Answer
> -1 votes
Collection is required in solr configuration. You'll need to create a collection you want to use for your site. Create using below command or by user interface of solr, then use the same name for the collection.

> sudo su - solr -c "/opt/solr/bin/solr create -c COLLECTION\_NAME -n data\_driven\_schema\_configs" // Only for ubuntu

Replace COLLECTION\_NAME with the name of your collection you want.

---
Tags: 8, search
---


title: Display content from a remote URL

text:
# Question
Title: Display content from a remote URL
is there a way to show content from an external URL (e.g. from GitHub) in a page?

I was using PHP code but because of security reasons I would prefer to use a module instead.

```
$c = curl_init();
curl_setopt($c, CURLOPT_URL, "https://raw.githubusercontent.com/foo/bar/master/file1.txt");
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
echo htmlspecialchars(curl_exec($c));
curl_close($c);

```

I am looking to something similar to https://www.drupal.org/project/url\_embed but without WYSIWYG. I just need to add some tags with the URL in the appropriate place on the page to display it.

# Answer
Creating a custom module for this in Drupal would be quite easy if you focused on your specific use case. You can find more info on that here: https://www.drupal.org/docs/8/creating-custom-modules

More specifically, you may want to look at a custom block implementation:

https://www.drupal.org/docs/8/creating-custom-modules/creating-custom-blocks
> 0 votes

---
Tags: 8
---


# Question
Title: Trying to filter a View based on a Paragraph entity reference
I want to filter a View by content type 'Article' and only content that is referenced to a specific node id 123. I have a Paragraph in Article content type. Inside the Paragraph is an entity reference 'my\_field' to content and also a few other text fields. In my View I added a relation: Paragraph referenced from my\_paragraph\_field. I can now add a normal View field - my\_field and use the relation. But it doesn't display results of the field. I can also add a filter - my\_field and make it equal to nid '123'. But it doesn't filter on the result? How can I make this work. Is this related to this issue. I can create a new View that displays Paragraphs and I can filter on that reference field without adding a relation.

# Answer
The way to list nodes that reference the one you're currenty viewing is by adding a **Contextual filter** for the Entity reference field that connects them.

You have one more connection in between - the Paragraph. You already added the Relationship to it so you're half way there.

Now that you have the 'my\_field' available you need to add the Contextual filter for that field. Configure it to `Provide default value`, `Content ID from URL`, and set the other options in a way that makes sense in your particular case.

This will give you a Views Display that is sensitive to the context of the node you're currently viewing, and it will show all the other nodes that reference this node through their Paragraphs.

Usually this Views Display is a Block that you then put in a region of your theme to be displayed on Articles only, and don't forget to set the Block contextual option too.

If you're using regular Filters like you mentioned to filter only node 123, the normal fields will display *its* info, and not the info from the node that refereces node 123. To display "the child" node info that references the filtered node you have to make the fields use the Relationship for it. Either add the 'my\_field' Field (it will automatically use the Paragraph Relationship), and if that won't work you need to add another Relationship that introduces that node info into the Views, then you'll be able to add the Title field for example, and make it use the second Relationship to show the node that references the current node.
> 2 votes

---
Tags: views, 8
---


# Question
Title: How do I get the email of the one submitting contact form in the "reply to"?
Drupal 8 site. I'm using the core Contact module for basic "Contact Us" form.

How can I get the email of the person submitting the form to be in the From field? And a follow-up: How do I get the email of an authenticated user to show in the body along with the username?

**Site and users:**

The site is an association website. There are about 100 user accounts.

**Domain and email:**

The site domain is not the same as the email domain in account settings: the site is theirsite.org and the email is theiremail@gmail.com

**From & To in email**

When the email came in from authenticated user or anonymous user, the From and the To are both showing theiremail@gmail.com - the site email.

**What shows in body of email:**

The email from the authenticated user does not show in the body of email; only the user name and the link to their user account /user/\[user-number\]

When I submit a form as an anonymous user the email does show in the body.

P.S. I do not want to use the Webform module.

# Answer
> 0 votes
If the person submitting the form is an anonymous visitor the form will be empty and the visitor will have to fill in every field.

If the visitor is logged in (authenticated user) the name and email address are already pre-filled from their user profile.

Are you sure you're not testing this while being logged in as an admin account that has the same email address as the site? Then it's expected to see that email there.

Try to login as a different user, and also test as anonymous to see that the email is now from that different user/empty respectively for those two cases.

If you're constantly seeing the site email as From in all three cases then it's a bug and you should try to see where it's coming from. I haven't seen any problems with the Contact module, it's showing the correct "From" value every time.

---
Tags: webforms
---


title: Installing in a sub-folder of Angular

text:
# Question
Title: Installing in a sub-folder of Angular
I have an Angular 2+ application running. I would like to install Drupal in a subfolder and have my Angular application to iframe the contents.

Ideal Folder Structure:

```
/             - Angular
/content      - Drupal

```

I have an existing rewrite rule to rewrite all URLs to index.html. Drupal works fine with pages like http://myapp.com/content/admin, but if I am accessing a page like http://myapp.com/en/page, it will be redirected to the index.html file of the Angular application.

How do I configure Drupal to make it add /content to its URLs?

I am hosting them on IIS. These are the rewrite rules I have now.

```
<rewrite>
  <rules>
    <clear />
    <rule name="HTTPS Redirection" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" />
    </rule>
    <rule name="Angular Routes" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="./index.html" />
    </rule>
  </rules>
</rewrite>

```

# Answer
> 0 votes
Finally got it working, the following are the changes I've made. I am writing this here in case anyone faces the same problem.

1. I noticed there was another `web.config` file **in root of Drupal folder** (`/content`) and it contains a few rewrite rules.
I've changed the last rewrite rule which rewrite all requests to `index.php`, it now looks like this:

```
<!-- Pass all requests not referring directly to files in the filesystem to index.php. -->
<rule name="Short URLS" stopProcessing="true">
  <match url="^(.*)$" ignoreCase="false" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
    <add input="{URL}" pattern="^/favicon.ico$" ignoreCase="false" negate="true" />
  </conditions>
  <action type="Rewrite" url="/content/index.php" /> <!-- CHANGES IN THIS LINE, ADDED '/content'/ in front of index.php -->
</rule>

```
2. Modified `.htaccess` file in root of Drupal folder and added this line `RewriteBase /content`, below this line `# RewriteBase /`
3. Modified the `web.config` file in **root folder of Angular App** (`/`) to the following:

```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- Install IIS url rewrite module. -->
  <system.webServer>
    <rewrite>
      <rules>
        <clear />
        <rule name="Angular Routes" stopProcessing="true">
          <match url="(.*)" negate="false" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{URL}" pattern="^/content/(.*)$" negate="true" />
          </conditions>
          <action type="Rewrite" url="./index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

</configuration>

```

---
Tags: 8, iis
---


# Question
Title: How to use term edit page instead of view page?
On the terms list page, each term is linked to the view page (i.e. `term/[tid]`). As I don't have any details in the view page, I would like to link it to edit page. (.i.e `term/[tid]/edit`). How to alter this behavior?

# Answer
> 1 votes
There are a few ways we could achieve this:

Option 1: Introduce a route subscriber in a custom module with below code:

```

    $route = $collection->get('entity.taxonomy_term.edit_form');
    $collection->add('entity.taxonomy_term.canonical', $route);

```

This code would replace the edit\_form to the canonical route.

**Note**: Might need to update the local task to remove the `view` tab as it is confusing to see the edit form in the `view` tab (as below).

Option 2: Extend `Drupal\taxonomy\Form\OverviewTerms` form and overwrite `buildForm` method and use `$term->toUrl('edit-form')` as below:

```
      $form['terms'][$key]['term'] = [
        '#prefix' => !empty($indentation) ? $this->renderer->render($indentation) : '',
        '#type' => 'link',
        '#title' => $term->getName(),
        '#url' => $term->toUrl('edit-form'),
      ];

```

However, it might not be a good idea considering how complex `buildForm` method is and the effort to keep up with any core changes.

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


# Question
Title: Define a normalizer just for a specific use case
I try to create a custom API with custom endpoints where API users can receive entity data from our page. We want to have flat arrays for most of the fields and some additional custom data added so I tried to implement some custom normalizer classes. I found out that `supportsNormalization()` is the place where the decision is made if my normalizer is used, but I have no context. I just have the object which needs normalization and the format on which I can say *Yes, please use my normalizer.* As I don't want to force all my entities everywhere in the project be normalized with flat array this is too restrictive for us. I want to use my normalizer only when the entities should be normalized for delivering it in a specific API. Is there a way to achieve this?

# Answer
The **supportsNormalization** method comes from the Symfony Serializer component, and for this reason it is up to the implementation to decide what to do with these items.

However Drupal core serialization module provides a nice base class, ComplexDataNormalizer, which is probably the class your Normalizer should extend when you need to normalize a complex data type such as an Entity, Map or a list of those things.

Classes that extend the base class should provide a unique interface to target: `ComplexDataNormalizer::$supportedInterfaceOrClass`.

With the Symfony service locator, as long as the normalizer weight is adjusted for any conflicts, then it will be used. A good example of this is to look at the core hal module.

So for instance, in my module `xero`, I provide my own Typed Data data types to interact with a third party API and the top-level data types I have my own interface.

Example:

```
class XeroNormalizer extends ComplexDataNormalizer implements DenormalizerInterface {

  protected $supportedInterfaceOrClass = 'Drupal\xero\TypedData\XeroTypeInterface';

```

You can read more about how the Drupal serialization module works in the documentation: https://www.drupal.org/docs/8/api/serialization-api/how-the-serializer-works
> 0 votes

---
Tags: 8
---


title: Problem when agreggating CSS/JS files

text:
# Question
Title: Problem when agreggating CSS/JS files
I'm working on a small D8 site. When turning the option "Aggregate CSS files" (`admin/config/development/performance`) on **localhost**, everything works fine. However, doing so when on my **test server** completely breaks the site presentation, both on the front (public pages) and back-end (admin).

It appears that when this option is on, the URL for the aggregated CSS is incomplete: the filename is not present, as well as most of the path, actually. Which means I have something like:

```
<link rel="stylesheet" href="/dpfolder/?okfo8d" media="all" />
<link rel="stylesheet" href="/dpfolder/?okfo8d" media="all" />

```

(the site lives in "dpfolder", although it's temporary.)

This happens with both the admin theme (seven) and the public theme (a custom theme based on Classy).

And it only happens when the option "aggregate" is ON. When it's OFF, everything displays fine (but then the CSS files are included via @import rules in a style element, and not via a link element like above).

Any idea what's causing this?

# Answer
As a comment suggested, sounds like your server does not have a writable files folder. That folder should and is by default excluded from git, you need to create it and make sure that the apache user (or whatever user the processes run as) has write permissions to that.
> 2 votes

# Answer
I know this is old, but if anyone else has this problem here what I needed to do:

Following this guide: https://www.tecmint.com/install-drupal-in-centos-rhel-fedora/ I realized I was running SELinux, so there's an extra step to make the files directory writable:

```
13. Importantly, set the SELinux rule on the folder “/var/www/html/drupal/sites/” as below:

~ chcon -R -t httpd_sys_content_rw_t /var/www/html/drupal/sites/

```

This allows the sites directory to be writable. You should never have the permission set to 777 for a production server. Instead use:

```
~ chmod 770 -R /var/www/html/drupal/sites/
~ chown root:webgroup -R /var/www/html/drupal/sites/

```

Where webgroup has any users (maybe a developer) and apache.

```
~ groupadd webgroup
~ usermod -a -G webgroup apache

```
> 0 votes

---
Tags: 8, css-js-aggregation
---


# Question
Title: How can I make entityQuery('commerce_order') return completed orders?
Under Drupal Commerce 8.x-2.13 I find that the query

```
Drupal::entityQuery('commerce_order')

```

with no conditions attached returns ONLY incomplete orders (when called in the context of an API endpoint) - and if I apply any parameters exclusive of incomplete orders such as

```
$query->condition('state', 'completed');

```

it returns nothing. How can entityQuery be made to retrieve data on completed orders?

# Answer
> 2 votes
The solution is apparently to add `$query->accessCheck(FALSE);`.

---
Tags: entities, commerce
---


title: Custom entity custom cache tags

text:
# Question
Title: Custom entity custom cache tags
I've created a custom entity and having trouble providing proper caching.

When you create custom entity, by default it has only one cache tag `entity_type:id`.

Problem is, I need to display same entity to different users (by role) in a different way.

So I think I need cache tags, such as `entity_type:id:user_role`? How do I go with this?

# Answer
To add a cache dependency on user roles you don't need a cache tag, but a cache context `user.roles`.

However, you rarely need this context, because there is already a default render context for the hashed user permissions `user.permissions`, set in the container variable `required_cache_contexts`, which is applied on all render arrays:

*default.services.yml:*

```
parameters:
  renderer.config:
    # Renderer required cache contexts:
    #
    # The Renderer will automatically associate these cache contexts with every
    # render array, hence varying every render array by these cache contexts.
    #
    # @default ['languages:language_interface', 'theme', 'user.permissions']
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

```
> 0 votes

---
Tags: 8
---


# Question
Title: How can I hide or show fields using states with hook form alter
We have been using Field States UI module with some success, but the Comparison Value does always not work for multiple values, I have tried to modify the valuse right in the entity\_form\_display.node yml file but no luck. I will also try the Conditional Fields module for D8. I also want to try to do this using code. I am trying an example using hook form alter taken from this post. But I cant get it to work. https://stackoverflow.com/questions/35380720/drupal-8-conditional-field. Should I be using drupal\_process\_states instead? Here is my code, I have two term reference fields field\_test2 and field\_test3. If you select the term id 15 from field\_test2 then field\_test3 will become visible.

```
use Drupal\Core\Form\FormStateInterface;

function mymodule_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_page_form' || $form_id == 'node_page_edit_form') {
    return;
  }

  if (isset($form['field_test2'])) {
    $states_when_category_is_design = array(
      'visible' => array(
        ':input[name="field_test2"]' => array('value' => '15'),
      ),
    );

    if (isset($form['field_test3'])) {
      $form['field_test3']['#states'] = $states_when_category_is_design;
    };
  }
}

```

# Answer
It seems you re using the Drupal 7 syntax. For Drupal 8 this is slightly different.

You can implement hook\_form\_alter() as follows to change the visibility state of a form element as follows:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'node_article_edit_form') {
    $form['field_other']['#states'] = [
      'visible' => [
          'select[name="field_reason"]' => ['value' => 'other']
      ]
    ];
   }
 }

```

This will make the **field\_other** field visible if the **other** option is chosen in the **reason** select list.
> 8 votes

# Answer
I use this to display or hide fields with dependency in a dropdown select list.

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
  if ($form_id == 'node_CONTENT_TYPE_form' || $form_id == 'node_CONTENT_TYPE_edit_form') {
    conditional_field_select(
      $form,
      'field_target',
      'field_controller',
      ['value_a', 'value_b', 'value_c'],
      'visible'
    );
  }
}

function conditional_field_select(array &$form, $targetField, $controlledBy, array $values, $state = 'invisible', $cond = 'or') {
  if (isset($form[$targetField]) && isset($form[$controlledBy])) {
    $form[$targetField]['#states'][$state] = [];
    foreach ($values as $value) {
      array_push($form[$targetField]['#states'][$state], ['select[name=' . $controlledBy . ']' => ['value' => $value]]);
      if (end($values) !== $value) {
        array_push($form[$targetField]['#states'][$state], $cond);
      }
    }
  }
}

```

It can easily be changed to input.

```
array_push($form[$targetField]['#states'][$state], [':input[name=' . $controlledBy . ']' => ['value' => $value]]);

```
> 4 votes

# Answer
I am using #states for in a node form, with this code for Drupal 8 this is slightly different.

You can implement hook\_form\_alter() as follows to change the visibility state of a form element as follows:

```
/**
*Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'node_article_edit_form') {
  $form['field_other']["widget"][0]['#states'] = [
    'visible' => [
      'input[name="field_reason[value]"]' => ['checked' => TRUE]
    ]
  ];
 }
}

```

This will make the field\_other field visible if the checked option is chosen in the reason checknox.
> 4 votes

---
Tags: 8, javascript
---


# Question
Title: Views view unformatted and outputting taxonomy custom field
Original problem I had was I setup a taxonomy called Category. I added some vocabulary to my Category taxonomy. Some of the terms I added have contain spaces. The labels should have spaces so I want to keep them there. I want to remove the spaces from the Category name when they are output in the views view unformatted templated.

This would solve all of my problems if I can get those spaces out of the category names. I setup a custom field on the taxonomy terms to handle this, but I don't know how to access the custom fields of the taxonomy term from the views-view-unformatted.html.twig template. Is there a preprocesser function that can do this? Something where I can convert the category and just remove the spaces or change the value output from label to field\_nospace\_category ?

**More experimenting**

I setup a view of type page to display the articles in my content type Articles. I'm using using the unformatted list and I created a custom template called views-view-unformatted--my\_view\_id.html.twig. I see that this is the template that is outputting on my page.

I'm trying to output the taxonomy terms custom field as a class on the div that has {{ row.attributes.addClass(row\_classes) }}

The div should end up looking like this:

...

I've tried several variations to try to get to the values. Inside of the for row in rows loop, i put:

```
{{ node.category.entity.field_category.value }}
{{ row.content['#node'].field_category.getValue().0.target_id }}
{{field_category}}
{{row.content['#elements'].field_category.getValue().0.target_id}}

```

I have tried to debug using Kint, Dump but my install keeps either throwing errors (out of memory) or blank white page.

Please help. Thank you in advance.

# Answer
> 1 votes
Finally got it to work! Here is how you do it. Assuming your field is called field\_category. My template is called views-view-unformatted--my\_view\_id\_name.html.twig.

```
{% set my_category_id = row.content['#row']._entity.field_category.0.target_id %}

```

It does seem pretty silly to me that it has to be that long. It would be very cool if it was something more like this and that all values associated to a post (since that is what is being output) are available and exposed to the view.

```
row.content.field_category.id

```

And if all taxonomies that are added would follow the same path. Seems unneccesary to have it in #row, then in \_entity, then needing to add a 0 and use some oddly named thing called target\_id.

I'm new to Drupal coming from Wordpress. There are nice clean functions in wordpress for getting taxonomy ID and names. Not too many hoops you need to jump through.

---
Tags: views, taxonomy-terms
---


# Question
Title: delete scheduled tasks fails when task identifier is account:uid
I have an action set as a scheduled task that deletes a user, that seems to be working fine:

```
{ "rules_delete_unregistered_user" : {
    "LABEL" : "Delete unregistered user",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "user", "type" : "user" } },
    "ACTION SET" : [ { "entity_delete" : { "data" : [ "user" ] } } ]
  }
}

```

and I also have a rule, that should delete this action set, but it fails:

```
{ "rules_user_accepted" : {
    "LABEL" : "user_accepted",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "account:field-accepted" ], "value" : "1" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_delete_unregistered_user",
          "task" : [ "account:uid" ]
        }
      }
    ]
  }
}

```

now I do not have any idea what should I use as a task identifier to delete that action set.

**EDIT:**

the rule that schedules the action set:

```
{ "rules_create_new_user_after_registration_form" : {
    "LABEL" : "create_new_user_after_registration_form",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "new user based on webform" ],
    "REQUIRES" : [ "webform_rules", "rules", "php", "rules_scheduler" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form-id" ],
          "selected_webform" : { "value" : { "webform-client-form-104" : "webform-client-form-104" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_field_lastname" : "[data:lastname1-value-raw]",
            "param_field_firstname" : "[data:firstname-value-raw]",
            "param_name" : "[data:email-value-raw]",
            "param_mail" : "[data:email-value-raw]"
          },
          "PROVIDE" : { "entity_created" : { "new_user_request" : "new_user_request" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "user",
            "property" : "uid",
            "value" : [ "new-user-request:uid" ]
          },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched entity" } }
        }
      },
      { "schedule" : {
          "component" : "rules_delete_unregistered_user",
          "date" : { "select" : "site:current-date", "date_offset" : { "value" : 60 } },
          "param_user" : [ "user-fetched:0" ]
        }
      }
      }
    ]
  }
}

```

this actually works fine.

# Answer
> 0 votes
If you go to /admin/config/workflow/rules/schedule you will see a table of your scheduled components. One of the columns in that table is the task identifier - that's the string you will have to use to delete the scheduled task. You didn't post any details related to the scheduling, so I don't know what you used as a task identifier. The task identifier is necessary because one component may be queued to execute many many times, each time with a different identifier. The component name is not unique. The task identifier is.

# Answer
> 0 votes
Anonymus was right I did not provide identifier, so I had to update the rule, and now it is working:

```
{ "rules_create_new_user_after_registration_form" : {
    "LABEL" : "create_new_user_after_registration_form",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "new user based on webform" ],
    "REQUIRES" : [ "webform_rules", "rules", "php", "rules_scheduler" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form-id" ],
          "selected_webform" : { "value" : { "webform-client-form-104" : "webform-client-form-104" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_field_lastname" : "[data:lastname1-value-raw]",
            "param_field_firstname" : "[data:firstname-value-raw]",
            "param_name" : "[data:email-value-raw]",
            "param_mail" : "[data:email-value-raw]"
          },
          "PROVIDE" : { "entity_created" : { "new_user_request" : "new_user_request" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "user",
            "property" : "uid",
            "value" : [ "new-user-request:uid" ]
          },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched entity" } }
        }
      },
      { "schedule" : {
          "component" : "rules_delete_unregistered_user",
          "date" : { "select" : "site:current-date", "date_offset" : { "value" : 60 } },
          "identifier" : [ "new-user-request:uid" ],
          "param_user" : [ "user-fetched:0" ]
        }
      }
      }
    ]
  }
}

```

---
Tags: 7, rules
---


# Question
Title: Change page title from Views preprocess function
I want to be able to change the main **page title** based on some value that I get in a views preprocess function.

The View is displayed as a page.

```
function MYTHEME_preprocess_views_view(&$variables) {

  // Can I set the page title from here?
}

```

The title I am trying to override is the title printed by the `/templates/content/page-title.html.twig` below:

```
{#
/**
 * @file
 * Theme override for page titles.
 *
 * Available variables:
 * - title_attributes: HTML attributes for the page title element.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title: The page title, for use in the actual content.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 */
#}
{{ title_prefix }}
{% if title %}
  <h1{{ title_attributes }}>{{ title }}</h1>
{% endif %}
{{ title_suffix }}

```

# Answer
I don't think hook\_preprocess\_views\_view() or hook\_preprocess\_page\_title() is good ways in your case. You can use hook\_views\_pre\_render

```
/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(ViewExecutable $view) {

  if ($view->id() == 'VIEW_ID') {
    $arg = $view->args; // Argument from view.
    $default_title = $view->getTitle(); // Get view title.
    $view->setTitle('New title'); // Set new title
  }
}

```

All variables you need in here.
> 4 votes

# Answer
Easiest to preprocess the page title is `MYTHEME_preprocess_page_title(&$variables)` and then use `$variables['title'] = 'New Title';` to set a new page title.

Inside there you can load your view by its ID and do whatever you need to do to have the title manipulation fired.

```
use Drupal\views\Views;

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

  // Replace MYVIEWID with you view ID.
  $view_id = 'MYVIEWID';

  if (\Drupal::routeMatch()->getParameter('view_id') === 'content') {

    $view = Views::getView($view_id);

    // ksm($view);

    // Do whatever you need to do and then set the page title.
    $variables['title'] = 'New Title';
  }
}

```
> 2 votes

---
Tags: views, 8
---


title: Xdebug not working over Drush

text:
# Question
Title: Xdebug not working over Drush
I'm using Drupal VM and the Drush Launcher (0.6.0). Whenever I try to Xdebug, PhpStorm notices, but it never actually reaches my Drush command. It stops at running Drush. This seems to have started recently.

My command looks like:

```
XDEBUG_CONFIG="remote_enable=On remote_connect_back=Off remote_host=192.168.90.1" PHP_IDE_CO
NFIG="serverName=example.wizonesolutions.com" drush -l example.com module:custom-command

```

# Answer
From https://github.com/drush-ops/drush-launcher#xdebug-compatibility:

> Drush Launcher, like Composer automatically disables Xdebug by default. This improves performance substantially. You may override this feature by setting an environment variable. `DRUSH_ALLOW_XDEBUG=1 drush [command]`

So to make Xdebug reach the rest of your code, add `DRUSH_ALLOW_XDEBUG=1` to the environment variables in front of your command.
> 8 votes

---
Tags: drush
---


# Question
Title: Get array number of paragraph item in TWIG
I have a paragraph (Entity reference revisions) with multiple items.

I would like to display the item list rendered.

I only get the paragraph as element\['#object'\] (in a pseudo field).

Unfortunately: entity\_reference\_revisions\EntityReferenceRevisionsFieldItemList cannot be printed.

I thought about looping a Twig Tweak rendering: {{ drupal\_entity('paragraph', ID, 'default') }}

But than I would have to get the individual ID of each item in the loop.

How could I manage this? Or is there a better solution at all?

# Answer
> 4 votes
The field item list belongs to a field, so you need to render the list in a field template.

Here's a basic example of a field template that renders each item keyed by its position in the list:

```
{# field--yourfieldname.html.twig #}
<ul>
  {% for item in items %}
    <li data-index="{{ loop.index }}">
      {{ item.content }}
    </li>
  {% endfor %}
</ul>

```

The field item list cannot do anything to `item.content` because it has already been rendered into HTML.

If instead you want to render each paragraph item keyed by its entity ID (as opposed to its list index) then you should do that in the entity template:

```
{# paragraph--yourparagraphtypename.html.twig #}
<div data-pid="{{ paragraph.id() }}">
  {{ content }}
</div>

```

Note: the paragraph entity doesn't know its position in the field item list.

---
Tags: theming, paragraphs
---


# Question
Title: How to remove tags from display in form?
I have this form tempate

```
<div class="a">
    {{ form.card.a }}
</div>
<div class="a">
    {{ form.card.b }}
</div>

```

and I want to to frame it with tag like this.

```
<a href="/card?id={{ form.card.card_link }}">
    <div class="a">
        {{ form.card.a }}
    </div>
    <div class="a">
        {{ form.card.b }}
    </div>
</a>

```

so I made

```
$form['card']['card_link'] = [
  '#type' => 'item',
  '#markup' => $this->getCardLink(), //returns integer
];

```

But it still doesn't show what it supposed to. It inserts `<div id="edit-card-link" class="some stuff">needed integer</div>` inside `href="<here>"`

How should I fix this?

# Answer
> 0 votes
The `item` element type is a form element, `Drupal\Core\Render\Element\Item`.

This means that it gets a form element wrapper by default.

Rather than rendering the `<a>` wrapper in the Twig template, you could include it in the render array, and add `form.card.a` and `form.card.b` as its children:

```
// In your form handler class

function buildForm($form, $form_state) {
  // ...

  $form['card_link'] = [
    '#type' => 'html_tag',
    '#tag' => 'a',
    '#attributes' => [
      'href' => '/card?id=' . $this->getCardLink()
    ],
  ];

  $form['card_link']['a'] = array_merge($form['card']['a'], [
    '#prefix' => '<div class="a">',
    '#suffix' => '</div>',
  ]);

  $form['card_link']['a'] = array_merge($form['card']['b'], [
    '#prefix' => '<div class="a">',
    '#suffix' => '</div>',
  ]);

  // ...
}

```

The template then simplifies to this:

```
{{ form.card_link }}

```

---
Tags: 8
---


# Question
Title: Ajax validation only works when I am logged in as an administrator
I have created a custom contact form and I have set up an ajax inline validation. My form works very well. But Ajax validation only works when I am connected. When I am not logged in as an administrator, ajax validation does not work.

Also I created a block to display the form in my footer. This form does not appear when I am logged in as an administrator. When I am connected I have access to the form only through the path I defined in module.routing.yml. And when it appears (so when I'm not logged in and I'm just a visitor), Ajax doesn't work on this block form either.

Does anyone have any idea what could cause this? Please help me.

# Answer
> 0 votes
I finally found the solution on the Drupal forum. I put it here, maybe it will help in the future a novice who will be in my case.

What was missing was simply a list of essential javascripts for anonymous users. It seems that at one time it wasn't necessary, but now we have to add them otherwise they wouldn't be loaded for anonymous users.

So what I needed to do was add this to my *theme.libraries.yml* file

```
my_scripts:
  version: VERSION
  js:
    js/scripts.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

```

# Answer
> 0 votes
These kind of errors often happen when you have not attached the proper library to your form. So one thing to check is if you have `$form['#attached']['library'][] = 'core/drupal.dialog.ajax';` in your form's `buildForm()`.

---
Tags: theming, forms, ajax
---


# Question
Title: Use REPLACE in update query using db_update
I need to run an update query that involves using the SQL REPLACE and LEFT functions, and I need to do it with three different queries for multiple tables, so I'd like to do it in a loop. The problem I'm having is getting the REPLACE function to be interpreted properly. The query I need to run is this:

```
UPDATE field_data_field_myfield
SET field_myfield_value =
REPLACE(field_myfield_value,
'old_value', 'new_value');

```

From what I've found, I need to use the expression function like so:

```
foreach ($tables as $table => $field) {
  $num_updated_1 = db_update($table)
    ->expression($field, 'replace(:field, :old, :new)', array(
      ':field' => $field,
      ':old' => 'old_value',
      ':new' =>  'new_value',
    ))
    ->execute();
}

```

However, when I run it like this, the field just gets updated with the field name as a string for every field.

What do I need to change for this to work?

# Answer
> 2 votes
The replace function doesn't work when the field is a placeholder. This will insert the field string as new value in the database. I've solved this problem removing the placeholder. Check it out:

```
foreach ($tables as $table => $field) {
  $num_updated_1 = db_update($table)
    ->expression($field, 'replace(' . $field . ', :old, :new)', array(
      ':old' => 'old_value',
      ':new' =>  'new_value',
    ))
    ->execute();
}

```

This way the code will work perfectly. I hope this may help someone.

# Answer
> 0 votes
Correct way to replaced value if use Drupal 7 PDO:

```
db_update('field_data_field_myfield')
  ->expression('field_myfield_value', 'replace(field_myfield_value, :old, :new)', array(
    ':old' => 'some old text',
    ':new' =>  'some new text',
  ))
  ->execute();

```

In your example error in this string use placeholders:

> ':field' =\> $field,

Field name cannot be passed to placeholders.

---
Tags: database
---


# Question
Title: Removing entity queue entries from a view
I have a list of 100 projects. I have set 10 projects as featured projects using Entity Queue module.

I have a projects page that shows has two views:

* First view: 10 projects from entity queue
* Second view: all 100 projects

The issue is the 10 projects are showing up twice on the page, is there a way to remove the entity queue featured projects from the second view?

Any help?

# Answer
Yes that should be easy enough. In your view with the 100 projects you need to:

1)Add a relationship to the entity queue but DON'T make it required

2)That will make a filter called "Content In Queue" be available for you to add

3) Set that filter to "No"

And that's it any entities that are in the queue won't come out in that view now
> 2 votes

---
Tags: views, 8, blocks
---


# Question
Title: WSOD while sending headers, probably Cache-related
I have a very strange problem with a fresh Drupal install: On some pages, I receive a WSOD with `ERR_EMPTY_RESPONSE`:

It happens for instance when on `admin/config/development/performance` I click *Clear all caches*. (But also other pages are affected – for instance the Layout Builder page of a Node type.)

Interestingly, I could isolate the bug down here: If in `vendor/symfony/http-foundation/Response.php::sendHeaders()` I tweak the code so that it unsets a lot of the headers to be sent (actually, all of them but `X-Generator` and `X-Frame-Options`), the error disappears.

```
...
$headers = $this->headers->allPreserveCaseWithoutCookies();
unset($headers['Cache-Control']);
unset($headers['Content-language']);
unset($headers['Date']);
unset($headers['X-Drupal-Dynamic-Cache']);
unset($headers['X-UA-Compatible']);
unset($headers['X-Content-Type-Options']);
unset($headers['Expires']);
unset($headers['Vary']);
foreach ($headers as $name => $values) {
  ...

```

Based on the headers I unset, it seems that it is a caching-related problem. (However, Caching is switched off, *Browser and proxy cache maximum age* is set to `<no caching>`.)

My setup:

* installed Drupal 8.7.5 via composer
* on my local machine, a MacBook Pro with macOS High Sierra
* installed via Homebrew
    + PHP 7.3
    + Apache 2.4
    + MySQL 5.7.24

Any idea what the problem might be?

**Edit:** Regarding Apache error logs: I first had no entries there but now I debugged again and saw such one:

```
[core:notice] [pid 92592] AH00052: child pid 98466 exit signal Bus error (10)

```

Googling gave the suggestion to `apc_clear_cache();` but it's not available in PHP7. So I ran opcache-reset().

Result: Problem is still there, now already when opening the page `admin/config/development/performance`.

Now the error logs say:

```
 [core:notice] [pid 7428] AH00052: child pid 7446 exit signal Segmentation fault

```

Google suggests this is likely caused by a syntax error in `php.ini` or some included extension there. Thus I have taken out all extensions, including

```
zend_extension=/usr/local/opt/php/lib/php/20180731/opcache.so

```

but the problem remains.

**Edit 2:** Here's the output of my `php -i` (It uses the same `php.ini` file as `phpinfo()` in localhost). https://pastebin.com/ppvCpPA6

# Answer
Now I could solve it myself. My Apache error logs did show

```
AH00052: child pid 7363 exit signal Segmentation fault (11)

```

so it must have been a problem with the Apache config.

I took the opportunity to **reinstall Apache and configure it with FCGI/FPM** according to this and now the problem is gone.
> 1 votes

# Answer
I have same issue with set debug mode when run

```
drupal smo dev

```

Problem will gone If I set to prod mode

```
 drupal smo prod

```

After sometime debug I found problem because cache tag header. And I change

```
http.response.debug_cacheability_headers: true

```

to

```
http.response.debug_cacheability_headers: false

```

It's working again.
> 0 votes

---
Tags: caching, wsod, http-request
---


# Question
Title: Admin page to show 2 blocks (or page+block) with 1 filter that affects both blocks
I am new to Drupal and would love some guidance on how best to achieve the following:

An admin page that has (top-down):
\- a date selector, defaulting to today's date
\- a section displaying Arrivals for the date selected (this selects custom content type 'Bookings' with filter of arrivalDate = dateselected)
\- a section displaying Departures for the date selected (this selects custom content type 'Bookings' with filter of departureDate = dateselected)

I'm interested in how **conceptually** an experienced Drupal developer would approach this with Views.
Note: The project uses Drupal 7.

My approach so far:

1. One view with Page display that lists the Arrivals and uses an Exposed Filter for the date
2. One view with block display that lists the Departures and uses a hidden filter for the date
3. The block display (2) is shown in the Footer of page display (1)
4. The mymodule\_views\_pre\_build hook is used to set the exposed filter date in (1) and hidden filter date in (2)

The initial load of Page (1) is working fine. Changing the date via the Exposed Filter in (1) correctly updates the Arrivals list; but not the Departures. I'll need to update the hidden filter in (2) somehow.

# Answer
The described scenario doesn't need custom coding as it is shipped with Drupal 7 Views module.

The approach to use a views block in a views page that shares the same filter can be done using the "Attachment" view.

You can find more about views attachment here

Also, there is an answer to place the attachment in a different page region here

Hope this answers your question.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to update route cache when saving an entity?
I have added a custom access check to the `/user/{user}` route:

```
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.user.canonical')) {
      $route->setRequirement('_profile_access', '\Drupal\mymodule\Access\ProfileAccessCheck::access');
    }
  }

}

```

with some starter checks:

```
/**
 * Determines access to user profile based on conditions.
 */
class ProfileAccessCheck implements AccessInterface {

  /**
   * Checks if this profile is publicly visible.
   *
   * @param \Drupal\Core\Routing\RouteMatch $routeMatch
   * @return \Drupal\Core\Access\AccessResultAllowed|\Drupal\Core\Access\AccessResultForbidden
   */
  public function access(RouteMatch $routeMatch) {
    $requested_profile = $routeMatch->getParameter('user');
    $show_profile = (bool) $requested_profile->field_show_profile->value;

    if ($show_profile === TRUE) {
      return AccessResult::allowed();
    }

    return AccessResult::forbidden();
  }

}

```

This appears to work fine, although it seems that the "View" tab does not hide/show in the admin when saving a user. If I clear the site cache, the tab is there on a user edit (or not, depending on value). Is there a way to get it to bind to the user or is it not worth while?

# Answer
Turns out I just had to chain it to the `AccessResult` like so:

```
AccessResult::allowed()->addCacheableDependency($requested_profile);

```

Same for `forbidden()`. Now the 'View' tab is visible appropriately.
> 2 votes

---
Tags: 8, routes, caching
---


# Question
Title: How to Give abilty to filter content by geography, separate from language?
I'm not sure if this is feasible, or how to go about it. I want a dropdown (and use IP detection) to provide users with content based on Region - Not Language. Because we will Also be using the normal Language functionality in Drupal 8 to provide translated content, if they choose to read it in another language. Because languages and countries are not synonymous.

I want the same functionality that's in language filtering, where a user can select "Spain" from a dropdown field and they get page content and blocks that are related to the region. Then, if they desire, also an ability to filter by language.

**Here's a scenario:**

1. User, in the U.S., goes to Website.com They see content that is related to the general global market, in English because they were auto-detected as a U.S. based IP.
2. User chooses Sweden from the dropdown. Page reloads as Website.com/Sweden/English (or maybe just website.com/Sweden ?) Now home page reloads the page, with content specific to Sweden. Similar to how language filters.. but filtered BY COUNTRY.
3. Now, the user DOES want to change the language. They choose Swedish from a second "language" dropdown on the page, and the home page reloads again with Sweden-related content, translated into Swedish, with this url. website.com/Sweden/Swedish

Any thoughts on this? I know the language modules can do half of this, but how do I also provide a way for the user to view site content by region. I know views can do some of this, but I'm not sure Views is the appropriate way to present the Entire website.

Maybe someone can clear my head on this.

# Answer
> 0 votes
This is a really broad and quite opinion-based request. But what I'd suggest is you completely keep Drupal's core internationalization functionality and just add languages including their region subtag:

* `es-AR`
* `es-ES`
* `es-MX`
* ...

You then can decide to use just the region as their label, which will then be displayed by the built-in language switcher.

A really positive side effect of this is you'd already have your content optimized for SEO pretty well (given that the region specific content actually are translations of each other).

Resources

---

Another approach would be to just go for one Drupal language and instead introduce a new field "Region" or "Country" to the node type you need this filtering for and build your own View with filters to display nodes or teasers of nodes matching the selected country or region.

---
Tags: 8
---


# Question
Title: Changing the view mode of EntityReferenceFieldItems programmatically
I have a paragraph (I'm using the Paragraphs module) that contains an **entity reference field** that contains references to other pages.

The display settings are set to use a particular view mode, e.g. `teaser`. This renders an teaser image, title and link to the page.

I would like the editor to be able to set the view mode on a per-paragraph basis. I have created a "view mode" field in the paragraph with two options: `teaser`, and `teaser-text-only`.

How can I use the view mode set in the "parent" entity (the paragraph) to add a template suggestion when rendering the "child" entities (the pages)?

# Answer
> 8 votes
At this point it should be no problem to change the view mode in the render element of the referenced node. The node has yet to be built and will, hopefully, use the modified view mode.

You can try something like this in a paragraph preprocess hook:

```
function mytheme_preprocess_paragraph(&$variables) {

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

}

```

**Edit:**

To prevent that the node gets cached on it's own in the wrong view mode remove the cache key.

# Answer
> 0 votes
There is a module view\_mode\_selector that should allow for this now. There is currently a dev releases for D8.

> A small module which allows you to change the view mode of an entity.
>
> This module provides a new field type "View mode selector", so just go to "Manage fields" and create a field of that type and choose between a "select list" and a "radio buttons" widget. When you choose "radio buttons" it is possible to upload an icon which will be displayed instead of the view mode name.
>
> In order to display your referenced entities with the new "View mode selector" view mode don't forget to change the view mode on "Manage display" which is used for displaying them.
>
> If Display Suite is enabled, it can also display a live preview of the configured view mode layout. Here is an example:

# Answer
> 0 votes
Bit late to the party here but here's how I just did it using Drupal 7.

I have a paragraph type called Related Content (related\_content) with 2 fields: An entity reference field and a Select (text) field called field\_related\_content\_view\_mode

I have set the default display mode of the referenced entities / field\_related content in the field display of the related content paragraph and use hook\_field\_display\_alter() to alter the display mode to the one set by field\_related\_content\_view\_mode:

```
/**
 * Implements hook_field_display_alter().
 */
function mymodule_field_display_alter(&$display, $context) {
  if ($context['entity_type'] == 'paragraphs_item') {
    if ($context['field']['field_name'] == 'field_related_content') {
      $entity = $context['entity'];
      if (isset($entity->field_related_content_view_mode) && !empty($entity->field_related_content_view_mode)) {
        $view_mode = $entity->field_related_content_view_mode[LANGUAGE_NONE][0]['value'];
        $display['settings']['view_mode'] = $view_mode;
      }
    }
  }
}

```

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


# Question
Title: How can I filter entity titles in an autocomplete form and use the title as context for a View page?
I am trying to provide a form with a single autocomplete text field on the front page. The user can search for a title of the product (commerce\_product), and when they submit, they're redirected to a views page with the title as context.

These are baseball cards from multiple sellers, so there can be many cards and variations of a single card with the same name, e.g. multiple sellers sell a "Barry Bonds" card.

When the user enters the name of the card and submits, I need to redirect them to a views page to display all the cards for that particular title (card name).

The part I'm trying to figure out is how to use the selected title on the front page and send the user to a views page with that title so I can use it in a view. I assume that would be a Context, but I'm not having success finding how to do that. To clarify the flow:

1. User hits front page and searches for a product title.
2. The user submits and is redirected to a views page.
3. On the views page, the user can browse all the cards under that title.

# Answer
> 0 votes
Here's how I solved my problem:

1. Added an ID field (the ID from the source I'm pulling/validating player names) to my variation. On creation of a variation, I store the ID in the field when the user selects the player name during product creation, e.g. "Barry Bonds" is ID 35456 in my source.
2. I'm using a regular autocomplete route in my form instead of an entity\_autocomplete. My autocomplete handler does an entity query on cards (product variations) that are active and match the player name.
3. After the player is selected from the autocomplete, on form validation, I re-select the player to get the ID.
4. On form submit I pass the ID with the URL to my views page as a contextual filter, where it expects it as a field value in the URL, e.g. "/player-card-search/35456".

Creating the new ID field in my product variation feels redundant, but it got me to the solution.

---
Tags: views, 8
---


title: Counting each filter near its label

text:
# Question
Title: Counting each filter near its label
I've created a view in order to override the default search page form and results, then I've exposed the content type in order to have the possibility to filter by that, all now is working

How can I have the count of the relative content near each content type label on the filters?

# Answer
> 0 votes
I've found a solution with a different approach

With `form_alter` I've targeted the form and edited the filter labels, by adding a custom query and counting items from the search\_index table with a left join to the node\_field\_data table in order to get the node type

# Answer
> 1 votes
Sounds like you want to use search facets. Facets are ways of showing various search 'tag' information for the current results with/without counts. Note that this is slightly different from a filter which will show all values even if there is no result with the specified search criteria.

That said, there is a defunct facets core search module. As the module page says, the best way to approach this with Drupal 8 is to use the Facets module which requires the Search API module with the included Search API DB engine (no Solr required).

This will add a bunch of extra functionality that the core search will not handle. Stuff like full text search across multiple text fields, stemmed searches (e.g. search for work also finds working, works, and the like), ability to show extracts (were the word was found), and much more.

# Answer
> 1 votes
One way to create a filtering system that counts the results per category is by creating a **Contextual** filter for the **type** with the **Summary** option.

This will list all the types as links, and show the number of results next to each type name. When you click through those links you will see the results for that one filtered type under the Format you set in Views.

You can list all the results below the Summary if you use different displays as Blocks/Attachments and display them together. There are many different combinations how to configure this, details depend on your particular needs.

---

Another way to count the results according to some categorization is with Aggregation. When you turn it on in your Views all fields and filters get the neutral "group" setting. The field related to your rows (node ID, title, etc) can then be set to Count under Aggregation settings which will display the number instead of the actual field output. You have to be careful about the other fields you show because they can "break" the aggregation into individual rows instead of collapsing into one value of the counted items.

Sorting can affect Aggregation negatively so remove sort criteria while building the Aggregation.

After you get the count numbers, you can maybe group by the type field (under Format), and you can Rewrite output of fields to show the count where you want it, again it all depends on your needs.

---
Tags: views, 8
---


# Question
Title: How can I have a custom module checked for deprecated functions?
I created a custom module in Drupal 8 for a specific purpose.

How can I find out if it contains any deprecated functions?

# Answer
> 4 votes
Read Dries Buytaert's blog post on How to prepare for Drupal 9

### `drupal-check`

> If you work on a Drupal site as a developer, run `drupal-check`. Matt Glaman (Centarro) developed a static PHP analysis tool called `drupal-check`, which you can run against your codebase to check for deprecated code. I recommend running `drupal-check` in an automated fashion as part of your development workflow.

Link: https://github.com/mglaman/drupal-check

### Upgrade Status

> If you are a site owner, install the Upgrade Status module. This module was built by Acquia. The module provides a graphical user interface on top of `drupal-check`. The goal is to provide an easy-to-use readiness assessment for your site's migration to Drupal 9.

Link: https://drupal.org/project/upgrade\_status

---

Maybe also learn the background info of `drupal-check` reading Matt Glaman's blog post about Testing your Drupal code base for deprecated code usage with PHPStan.

---
Tags: 8
---


# Question
Title: How are clean URLs with 200 response codes being managed without doing a RewriteMap?
I would like to know how Drupal handles clean URLs without getting a redirection 302 response.

When you have clean URLs enabled, the `?q=123` part of the link goes to `/my-node-title` and you don't get a 302 redirect but a clean 200 response.

My question is about the code that enables this, and not about how to sort things from the UI.

I want to understand how it does work, because it should do a `RewriteMap` from apache, but in Drupal installations people don't usually get access to modifying Apache.

# Answer
The Apache mod rewrite module is used. `/some/path` is rewritten internally by Apache to `index.php?q=some/path` \[Credit: mpdonadio\].

`index.php` bootstraps Drupal. Drupal determines if it is able to generate a response for the path passed in the URL query `q` parameter - in this case `/some/path`. If the user has permission to access the path, the response is returned with a 200 HTTP status.

If Drupal is not able to generate a response for the path, it returns a 404 status. If it can generate a response, but the user has no permission, a 403 status is returned. Redirects send the appropriate status.

Custom modules are also able to specify status codes when returning responses.
> 5 votes

---
Tags: .htaccess
---


# Question
Title: AJAX Views with filter as path component
I have a view of Commerce products of type *Print*. The product type *Print* has a reference on a Taxonomy called *Category*. I setup the *Category* field as an exposed filter (dropdown) for my View page. The View uses AJAX and the URL is `/prints`.

If I want to load my View with a preselected category, I can go to `http://d8.local/prints?category=1` which displays the View already filtered and with the corresponding category selected in the dropdown.

I could setup a contextual filter and a relationship on the View and set the path to `prints/%` so that I could filter and access it as `http://d8.local/prints/landscapes` where *landscapes* is one of the vocabulary terms, which feels better than `?category=1`.

When I do so however, going to `http://d8.local/prints/landscapes` then using the exposed filter, it will filter the already filtered results. Also going to `/landscapes` doesn't select the option in the dropdown.

Is there a way to combine the 2 functionalities?

### Edit:

To summarize the functionalities I am after:

1. I should be able to filter the products by *category* by adding the vocabulary term name as a path component, ie. `/prints/landscapes`.
2. When accessing the View with the category as the path component, the appropriate *category* exposed filter dropdown option should be selected, ie. *Landscapes* should be selected in the dropdown if accessing `/prints/landscapes`.
3. I should be able to filter the View using AJAX when manually selecting another *category* from the exposed filter dropdown.
4. The main page title must be updated based on the category whichever way the view was loaded (page load and AJAX reload)
5. Ideally, I would update the URL when manually selecting a category from the dropdown, but I suppose that's a separate question and it shouldn't be too hard to handle.

# Answer
I tried many different complicated approaches, before I found a much easier solution that suits my needs so I am posting this as a solution.

I setup my `prints` View this way:

* *Category* is added as an exposed filter
* No contextual filter, no relationship
* Set the view path to `prints/%`
* Use AJAX: Yes

I created a module and used `hook_views_pre_build()` to get the category from the url parts, ie. get `landscapes` from the path `/prints/landscapes` then load the vocabulary term by name and if the term exists, set the exposed filter to the term id.

```
/**
 * Implements hook_views_pre_build().
 */
function MYMODULE_views_pre_build(\Drupal\views\ViewExecutable $view) {

  $view_ids = ['prints'];

  if (isset($view) && in_array($view->id(), $view_ids)) {

    // Get exposed input
    $exposedInput = $view->getExposedInput();

    // If exposed input is not set
    if (empty($exposedInput['category'])) {

      // Get current path
      $current_path = \Drupal::service('path.current')->getPath();
      $uri_segments = explode('/', $current_path);

      // 2nd uri segment is the category (term name)
      $current_category = isset($uri_segments[2]) ? $uri_segments[2] : NULL;

      if ($current_category !== NULL) {

        // Set vocabulary id
        $vid = 'photo_category';

        // Load term by name from vocabulary
        $term = \Drupal::entityTypeManager()
          ->getStorage('taxonomy_term')
          ->loadByProperties(['vid' => $vid, 'name' => $current_category]);

        // If term was found
        if ($term) {

          // Get first array element
          $term = reset($term);

          // Filter view by setting exposed input to term id
          $view->setExposedInput(['category' => $term->id()]);
        }
      }
    }
  }
}

```

This fixes filtering the view on page load when the category is in the URL.

As I also wanted to update the page title based on the selected category, I created an EventSubscriber for the AJAX response. All I do here is load the *Category* term name based on the exposed filter value, then use an `HtmlCommand` to update the page title.

```
<?php

namespace Drupal\MYMODULE\EventSubscriber;

use Drupal\views\Ajax\ViewAjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\taxonomy\Entity\Term;

/**
 * Response subscriber to handle View AJAX responses.
 */
class ViewAjaxResponseSubscriber implements EventSubscriberInterface {

  /**
   * Adds an AJAX command to ViewAjaxResponse.
   */
  public function onResponse(FilterResponseEvent $event) {

    $response = $event->getResponse();

    if ($response instanceof ViewAjaxResponse) {

      $view_ids = ['prints'];
      $view = $response->getView();

      if (isset($view) && in_array($view->id(), $view_ids)) {

        $titleSelector = '.page__header h1';

        if ($view->exposed_data['category'] !== 'All') {

          $term = Term::load($view->exposed_data['category']);
          $name = $term->getName();

          $title = 'Prints in category <em class="text-grey">' . $name . '</em>';

          $response->addCommand(new HtmlCommand($titleSelector, $title));
        } else {

          $response->addCommand(new HtmlCommand($titleSelector, 'Prints - All categories'));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
  }

}

```

I'll do the same for when I load the view with the category in the URL, using `hook_views_pre_render()`:

```
/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(\Drupal\views\ViewExecutable $view) {

  $view_ids = ['prints'];

  if (isset($view) && in_array($view->id(), $view_ids)) {

    if ($view->exposed_data['category'] !== 'All') {

      // Load category (term name) from View exposed filter data
      $term = Term::load($view->exposed_data['category']);
      $name = $term->getName();

      // Update View title with category (term name)
      $view->setTitle('Prints in category <em class="text-grey">' . $name . '</em>');
    }
  }
}

```

My last requirement was to update the URL when the view would be filtered with AJAX so in my module Javascript file:

```
Drupal.behaviors.viewsAjax = {

    attach: function (context, settings) {

        // Attach action to Drupal Ajax Views event
        $(document).once('#views-exposed-form-prints-page-1', context).ajaxSuccess(function (event, data) {

            if ($('#views-exposed-form-prints-page-1').length) {

                let stateUri = '/prints/' + $('#views-exposed-form-prints-page-1 select[name="category"] > option:selected').text().toLowerCase();
                window.history.replaceState('', '', stateUri);
            }
        });
    }
};

```
> 0 votes

# Answer
There are many ways to solve this, you can take different approaches to the filtering part, the URL part, and the contextual part, and how they play together to get you to your goal. Here's one of the possibilities, probably the easiest route:

1. This is solved by adding a Relationship for the category field, and then adding a Term "Name" Contextual filter (it will automatically use that Relationship). Be mindful how you configure the spaces/dashes options. This will give you the term name in the URL instead of the term ID.
2. To get the Exposed filter to match the Contextual you need to use the Views Filter Harmonizer module. There's no workable D8 version yet, you can try and help there, there is an issue open for it.
3. If you've set up the Exposed filter properly, and turned Ajax on, it should work without a page reload. The "harmonizer" module also claims to play well with that.
4. I might be missing something here, I wouldn't expect that the Addressbar updating without a page reload is easy, but again the "harnomizer" module claims to do just that, so it seems you're covered if you can get that module to D8.

Another module that might be relevant in another approach: (also no D8 yet) Query Parameters To URL , but similar outcome can be done through your server configuration.
> 1 votes

---
Tags: views, 8, ajax
---


# Question
Title: How to discover the currently active twig template
I need to find out the currently active Twig template from within my module preprocess function.

```
function mymodule_preprocess_field(&$variables, $hook) {
    // How do i retrieve the currently active Twig template?
}

```

I need to know whether it is `field.html.twig`, `field--field-example.html.twig` or some other template suggestion.

Is that possible?

# Answer
With the help of Clive's comment, I managed to identify the active theme suggestion. Code below.

```
function mymodule_preprocess_field(&$variables, $hook) {
  $theme_suggestions = mymodule_get_theme_suggestions($hook, $variables);

  $active_suggestion = mymodule_get_active_theme_suggestion($theme_suggestions);
}

function mymodule_get_theme_suggestions(String $base_hook, array $variables) {
  // Invoke hook_theme_suggestions_HOOK().
  $suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_' . $base_hook, [$variables]);

  // Invoke hook_theme_suggestions_alter().
  $hooks = [
    'theme_suggestions',
    'theme_suggestions_' . $base_hook,
  ];
  \Drupal::moduleHandler()->alter($hooks, $suggestions, $variables, $base_hook);

  array_unshift($suggestions, $base_hook);

  return $suggestions;
}

function mymodule_get_active_theme_suggestion($suggestions) {

  $theme_registry = theme_get_registry(FALSE);

  // Order by most specific first.
  $suggestions = array_reverse($suggestions);

  foreach ($suggestions as $candidate) {
    if ($theme_registry
      ->has($candidate)) {
      return $candidate;
    }
  }
}

```
> 0 votes

---
Tags: 8, theming
---