# Question
Title: dpm() does not display any results on screen
I have the same problem as file\_scan\_directory() takes about 10 seconds to execute. I just tried the `dpm(func_get_args())` suggestion, and unfortunately it doesn't show anything to me.

I've cleared all the caches, and run the cron tasks. What am I missing?

# Answer
> 30 votes
Make sure you have `print $messages;` in your `page.tpl.php`template file. By default, devel (dpm) is configured to print it's content in the message area of the site. So if your template for some reason does not render the contents of `$messages`, you won't see anything.

# Answer
> 16 votes
1. Sometimes `krumo($variable)` might work when `dpm($variable)` doesn't.
2. Sometimes `print dpm($variable)` might work when `dpm($variable)` doesn't.
3. 2. might also be the solution when there's no `print $messages` in your `page.tpl.php` anymore. Maybe you can add it back.

# Answer
> 10 votes
You must be logged-in to the Drupal site, with the correct permissions to access Devel. Log in as admin should do it.

# Answer
> 9 votes
I'd highly recommend devel\_debug\_log. It requires the devel module, and it gives you the ddl() function. ddl adds a page to your reports in configuration, so it's similar to printing to watchdog, but you have a nice clean page where you can send your debug messages, and not worry about race-type conditions where your messages might get cleared before you have a chance to see them--or, as in your case, theme issues.

(This is also an EXTREMELY useful tool if you're trying to build out any sort of API, as all those requests would never show you any kind of dpm() messages.)

# Answer
> 7 votes
Ensure that you have enabled and installed the Devel module as `dpm()` is a function declared in this module.

`dpm()` description taken from here.

> Prints a variable to the ‘message’ area of the page using drupal\_set\_message(). You can use this function to keep track of one or more variables when you’re working on the code running your site. Because the Devel module now comes with Krumo, the output is compact and unobtrusive.
>
> `dpm($input, $name = NULL)`
>
> If, for some reason, you are not using Krumo, you can use the $name parameter to distinguish between different calls to dpm().

After you have downloaded and enabled Devel, try the answer from file\_scan\_directory() takes about 10 seconds to execute again and it should work.

# Answer
> 5 votes
If you want to print it from inside a function without touching (or having) a template file, try this:

```
$nid = 3;
$node = node_load($nid);
dpm($node);
print theme('status_messages');

```

# Answer
> 3 votes
This is sometimes a result of a resource on the page returning a 404.

Drupal renders the 404 page and in doing so fetches (and clears) the messages from the session and puts them on the 404 page that you don't see. Then when the main page fetches the messages there are none left.

You can open the network tab and check to see if any resources have a 404 status.

An easy solution here is to enable fast 404 by uncommenting this line in settings.php:

```
# drupal_fast_404();

```

Another good solution here is to use devel\_debug\_log as suggested by SlakeFistcrunch.

# Answer
> 2 votes
Sometimes the message can be cut or won't work in case of AJAX.

More reliable method is to do just (then remove after finish):

```
var_dump($data); die();

```

Or you can use `dd()` (part of Devel as well), e.g.

```
dd(func_get_args());

```

then check your log file (in temp folder), e.g.

```
$ tail -f /tmp/drupal_debug.txt

```

Using above method is more convenient, quicker and it may support AJAX or other request without breaking the current site rendering.

---

If you still like `dpm()`, try also using `kint()` (enable the included Kint submodule for these pretty print of variables).

# Answer
> 1 votes
If only some `dpm()` calls do not work, it can be due to `dpm()` crashing. I saw it happening in the following scenario in a custom form submit handler:

```
function mymodule_formid_submit($form, &$form_state) {
  dpm($form_state);
}

```

I believe the error condition was caught by an exception handler in `dpm()`, because the page was displaying fine, no WSOD or something, just no `dpm()` message either. The error is probably undetected recursion, because using `ddl($form_state)` instead resulted in browser maxing out on memory when watching the corresponding object in the report generated by the Devel Debug Log module.

As a workaround, try to print only a (relevant) part of the object, like `dpm($form_state['values'])` or `dpm(array_keys($form_state))`.

# Answer
> 0 votes
For **Drupal 8**

Make sure status\_messages is an **enabled** block in `/admin/structure/block` and inside a used region of your theme

And depending on your theme's setup you might have to actually print it manually inside your `page.html.twig` template

```
{{ page.status_messages }}

```

---
Tags: 7, debugging
---


title: Image Style issue

text:
# Question
Title: Image Style issue
I have created an Image style which I am applying in my Blog view. But the Images are not generated in the Blog View Image folder and hence it is not showing up because of the path issue.

`sites/default/files/blog/images/testing.jpg` \- This is the path where my images are getting stored.

`sites/default/files/styles/test/public/blog/images/testing.jpg` \- This is the path generated from my view.

Adding "`$config['image.settings']['allow_insecure_derivatives'] = TRUE;`" in `settings.php` solves my issue. But I prefer not to use this because of security risks.

Also, there are no PHP errors that I can notice.

Please suggest to me how the issue can be resolved.

# Answer
> 0 votes
Maybe you're trying to create the URL to the image style by string manipulation? There is a security check in place to ensure that image derivatives can't be used to DDoS (distributed denial of service) your site - basically spamming your server with image style requests.

> Drupal core's Image module allows for the on-demand generation of image derivatives. This capability can be abused by requesting a large number of new derivatives which can fill up the server disk space, and which can cause a very high CPU load. Either of these effects may lead to the site becoming unavailable or unresponsive.

For this all image style URL's now require a token in the query string in the form of `sites/default/files/styles/test/public/blog/images/testing.jpg?itok={token}` (note it's the itok querystring in the end).

You need to create the image style URL through various formatters or class methods provided in order to get a URL with the security token, otherwise you will get access denied on any URL without the itok. If you're using Views, then for the Image field in your view change the Formatter to "Image Style" and choose the style in the view's config.

To do this from code, you should use the ImageStyle entity to generate the URL's, which give you the URL with token as well. If you have a `$file` file entity or just a file URI string you can generate it like this:

```
$style_name = 'test';
$style = ImageStyle::load($style_name);
$file_uri = $file->getFileUri();
$image_style_url = $style->buildUrl($file_uri);

```

or single line:

```
$image_style_url = ImageStyle::load('test')->buildUrl($file->getFileUri());

```

See also: Drupal 7.20 release notes where this change happened.

---
Tags: media
---


# Question
Title: Force a single value base field to be in a separate table?
I have a custom entity type (eg: `myentitytype`), and I would like to add a new base field to it via `hook_entity_base_field_info()`. As I understand it, single value fields (with a cardinality of `1`) will create new columns in the `myentitytype_field_data` table, but multi-value fields will create a new table.

Is it possible to "force" a single-value field to be stored in its own database table, rather than adding columns to the *myentity\_field\_data* table?

# Answer
> 5 votes
`\Drupal\Core\Entity\Sql\DefaultTableMapping` is responsible for determining a separate field storage table; its `allowsSharedTableStorage()` method returns a Boolean value basing on four conditions.

```
public function allowsSharedTableStorage(FieldStorageDefinitionInterface $storage_definition) {
  return !$storage_definition->hasCustomStorage() && $storage_definition->isBaseField() && !$storage_definition->isMultiple() && !$storage_definition->isDeleted();
}

```

The only feasible solution would be to implement your own storage handler and use `"custom_storage" => TRUE`.

---
Tags: entities, database, 9
---


# Question
Title: How to change node field label for some specific conditions?
In preprocess\_node I wrote this and when I do kint($variables\['node'\]) I can see that label is set to "test", however on display it appears with the old label. How can I change the label name? Should it be in preprocess\_node or some other hook? Or what else I should update, so it is actually displayed with label replacement?

```
    $node = &$variables['node'];
    if ($node->getType()=='training') {
      $term = reset($node->get('field_training_type')->referencedEntities());
    }
    if($term instanceof \Drupal\taxonomy\TermInterface && $term->id() == 9) {
      $node->get('field_section_09')->getFieldDefinition()->setLabel('test');
      $variables['node'] = $node;
    }

```

# Answer
This doesn't work for two reasons. First, you shouldn't change objects unless you want to save the changes because they are shared across the entire Drupal application. Second, preprocess is for preparing variables printed in templates. Changing other variables has no effect.

So in `hook_preprocess_node` you can change only `$variables['content']`.

For most fields the label is stored in `#title` unless the field is built in a special way by callbacks:

```
$variables['content']['field_bar']['#title'] = 'Foo';

```

More straightforward, though, would be changing the label directly in `hook_preprocess_field`:

```
$variables['label'] = 'Foo';

```

which is then printed in the template as `{{ label }}`.

---

By the way, if you want to rewrite your code for field preprocess you find the node in this variable:

```
$node = $variables['element']['#object'];

```
> 3 votes

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


# Question
Title: How can I write an if else statement in Twig based on commerce stock quantity?
Building a D8 Commerce site and trying to hide the price if the product is out of stock. I can access the stock value with this:

```
{{ product.variation_field_stock_level.0 }}

```

I've tried this:

```
{% if product.variation_field_stock_level.0 > 0 %}
 {{ product.variation_price }}
{% else %}
 <p>Sold</p>
{% endif %}

```

...but it prints the price regardless of whether the stock value is 0 or 1 (or more). I've also tried:

```
{% if product.variation_field_stock_level.0 == 0 %}
  <p>Sold</p>
{% else %}
  {{ product.variation_price }}
{% endif %}

```

Regardless of what I try it just will not work.

# Answer
This is very close - but it seems you are missing the actual stock level value from the object. Start by doing something like:

```
{{product.variation_field_stock_level.0|json_encode}}

```

Run it through a json cleaner to make it readable, like: JSON Cleaner

You will see this:

```
{"#type":"html_tag","#tag":"p","#value":0}

```

Now the conditional will be:

```
{% if product.variation_field_stock_level.0['#value'] > 0 %}
    {{ product.variation_price }}
{% else %}
    <p>Sold</p>
{% endif %}

```
> 3 votes

---
Tags: theming, commerce
---


# Question
Title: Webform submission token for multivalue download field
I'm trying to setup a webform that sends links which can be accessed to download a file. It's working with the first file already, but I can't figure out how to create the token for the other files referenced in a multivalue field:

What's working (for one file):

`Here is your requested download: <a href="[webform_submission:node:field_gated_download:entity:field_media_file:entity:url]" target="blank">[webform_submission:node:field_gated_download:entity] </a>`

I have tried:

```
[webform_submission:node:field_gated_download:entity:field_media_file:entity:url:0]
[webform_submission:node:field_gated_download:entity:field_media_file:entity:url:und:0]
[webform_submission:node:field_gated_download:0:entity:field_media_file:entity:url]
[webform_submission:node:field_gated_download:und:0:entity:field_media_file:entity:url]

```

in almost every combination. It's not working.

Can someone lead me in the right direction?

# Answer
One approach to this issue is to interpret tokens on your own via hook\_tokens().

`hook_tokens()` is called every time a token is interpreted and gives you an opportunity to determine how that token is interpreted. Even though the token `[webform_submission:node:field_gated_download:entity:field_media_file:entity:url]` is already defined, it may be necessary to also implement hook\_token\_info() or hook\_token\_info\_alter() in order to define additional modifiers to the token.

It's possible that you might discover the exact token syntax that you need by inspecting the arguments passed into `hook_token_info_alter()`.

Here are two tutorials that cover using both `hook_token_info()` and `hook_tokens()` in order to perform custom token processing.
> 2 votes

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


# Question
Title: Disable caching for a front page path processor
I’m working on a project where users can create a book (core functionality). In a simple text field they can connect a domain to this book. This way the book is only accessible via this domain.

For example I have `Book A` with path `node\1` and with domain `a.book.com`. I also have `Book B` with path `node\2` and connected to domain `b.book.com`.

What I want now is if a visitor goes to `a.book.com` the frontpage is `node/1`. And if they go to `b.book.com` the frontpage should be `node/2`? I created a custom module for this `book_frontpage`.

For this I used large parts of the `PathProcessorFront.php` from core.

The code of my `book_front.services.yml` is:

```
services:
  book_frontpage.path_processor_front:
    class: Drupal\book_frontpage\PathProcessor\FrontPagePathProcessor
    tags:
      - { name: path_processor_inbound, priority: 300 }

```

The code of my `FrontPagePathProcessor.php` is:

```
<?php

namespace Drupal\book_frontpage\PathProcessor;

use Drupal\Core\Database\Database;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Path processor to replace 'node' with 'content' in URLs.
 */
class FrontPagePathProcessor implements InboundPathProcessorInterface{
  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request)
  {
    if ($path === '/') {
      //current domain
      $currentDomain = $_SERVER['SERVER_NAME'];

      //get nid of reader where domain is set
      $nid = Database::getConnection()->select('node__field_domain', 'd')
        ->fields('d', ['entity_id'])
        ->condition('field_domain_value', $currentDomain, '=')
        ->execute()
        ->fetchField();

      //get path
      $path = \Drupal::service('path_alias.manager')->getAliasByPath('/node/'. $nid);

      if (empty($path)) {
        // We have to return a valid path but / won't be routable and config
        // might be broken so stop execution.
        throw new NotFoundHttpException();
      }
      $components = parse_url($path);

      // Remove query string and fragment.
      $path = $components['path'];

      // Merge query parameters from front page configuration value
      // with URL query, so that actual URL takes precedence.
      if (!empty($components['query'])) {
        parse_str($components['query'], $parameters);
        array_replace($parameters, $request->query->all());
        $request->query->replace($parameters);
      }
    }

    return $path;
  }
}

```

Now when going to `a.book.com` I see `node/1` but when I go to `b.book.com` I also see `node/1`. When I clear cache and first go to `b.book.com` I get `node/2` but when going to `a.book.com` I also get `node/2`. So this looks like a cache problem.

How can I disable caching of this front page path?

# Answer
> 4 votes
As discussed here, Hide path on frontpage redirect, you need to make caching of route collections domain-specific. Other than the discussed overriding of the core service, since Drupal 8.8 you can use the service method addExtraCacheKeyPart().

Add this code in a request event subscriber:

*/src/EventSubscriber/RouteCacheDomainSubscriber.php*

```
<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class RouteCacheDomainSubscriber implements EventSubscriberInterface {

  public function onKernelRequest(RequestEvent $event) {
    $routeProvider = \Drupal::service('router.route_provider');
    $domain = \Drupal::request()->getHost();
    $routeProvider->addExtraCacheKeyPart('domain', $domain);
  }

  /**
   * {@inheritDoc}
   */
  public static function getSubscribedEvents() {
    // run before RouterListener (priority 32)
    $events[KernelEvents::REQUEST][] = ['onKernelRequest', 33];
    return $events;
  }

}

```

*mymodule.services.yml*

```
services:
  mymodule.route_cache_domain_subscriber:
    class: Drupal\mymodule\EventSubscriber\RouteCacheDomainSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

```

Also, you need to invalidate the cache tag `route_match` when book nodes are saved. See Is there a way to partially rebuild the router or invalidate a route cache?

---
Tags: caching, path-aliases, 9
---


title: Updating from core 8.7.9 to 8.8.0

text:
# Question
Title: Updating from core 8.7.9 to 8.8.0
I'm running into an issue when updating to Drupal core 8.8.0. I've removed both the vendor folder and the composer.lock file, as per instructions on this link https://www.drupal.org/node/2700999#s-special-considerations-for-upgrading-to-drupal-880-and-later

I run `composer require drupal/core-recommended:^8.8 --update-with-dependencies` and I get the following:

```
  Problem 1
    - Conclusion: don't install drupal/core 8.8.5
    - Conclusion: don't install drupal/core 8.8.4
    - Conclusion: don't install drupal/core 8.8.3
    - Conclusion: don't install drupal/core 8.8.2
    - Conclusion: don't install drupal/core 8.8.1
    - Conclusion: don't install drupal/core 8.8.0
    - Conclusion: don't install drupal/core 8.8.0-rc1
    - Conclusion: don't install drupal/core 8.9.0-beta2
    - Conclusion: don't install drupal/core 8.9.0-beta1
    - Conclusion: don't install drupal/core 8.8.0-beta1
    - Installation request for acquia/lightning 4.0.4 -> satisfiable by acquia/lightning[4.0.4].
    - Conclusion: don't install drupal/core 8.8.0-alpha1
    - Conclusion: don't install drupal/core 8.9.x-dev
    - acquia/lightning 4.0.4 requires drupal/claro ^1.0 -> satisfiable by drupal/claro[1.x-dev, 1.0.0-beta1, 1.0.0-alpha5, 1.0.0-alpha4, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1].
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.x-dev
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-beta1
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha5
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha4
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha3
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha2
    - don't install drupal/core 8.8.x-dev|don't install drupal/claro 1.0.0-alpha1
    - Installation request for drupal/core ^8.8.0 -> satisfiable by drupal/core[8.8.0, 8.8.0-alpha1, 8.8.0-beta1, 8.8.0-rc1, 8.8.1, 8.8.2, 8.8.3, 8.8.4, 8.8.5, 8.8.x-dev, 8.9.0-beta1, 8.9.0-beta2, 8.9.x-dev].

```

At this point, running `composer prohibits drupal/core:8.8.0` won't work because I removed `drupal/core` as per instructions in the link above.

I can successfully update to 8.7.13, so maybe I can settle for that for now. But our team wants to be ready for Drupal 9 and upgrading to 8.8 will make that transition easier, I hear.

Should I update to 8.7.13 first, before attempting to upgrade to 8.8?

**EDIT** I'm able to update to Drupal 8.8 by removing the vendor folder and composer.lock and removing acquia/lightning. I reinstalled acquia/lightning after Drupal core was added. I am now running into issues when running drush dbupdate.

# Answer
> 1 votes
In your `composer.json` file (found in the root of your drupal site) find the line `"drupal/core": "x.xx"` and change it to `"drupal/core": "~8.8"` and then run `composer update drupal/core --with-dependencies`

Also, don't forget to run your database updates after! (run `drush updb` or go to `your-drupal-site.com/update.php`)

# Answer
> 1 votes
I can see you're using `acquia/lightning` which is not a dependency from core but the other way around, so running that command with the dependencies flag will not work.

Run the command as follows:

```
$ composer update drupal/core acquia/lightning --with-dependencies

```

This will tell composer to update both Core and Lightning. Note, this is still constrained to having your `composer.json` not fixed to a specific version, so ensure they are specified with either a `^` or `~` accordingly.

Also note that you can still face individual constraints that need updating as dependencies from Lightning itself. If that happens, just include those packages to your update command.

You can also refer to https://github.com/acquia/lightning/releases for the release notes, as the maintainers usually include the required commands for you as per your version of Core accordingly.

**Final note:** never remove your `composer.lock` file and also never run `composer update` without any package specified, as that will update all packages.

---
Tags: updating, composer
---


# Question
Title: How can I add a Pathauto pattern for a content type depending on a reference field?
On my site I have a content type 'Article' that has a reference field to a taxonomy vocabulary 'Type of Article' containing terms like 'Blog', 'News', etc.

Now I would like to have Pathauto form a different URL for each type of Article. E.g. /blog/article-title, /news/article-title, etc. Is it possible to set a pathauto pattern depending on the settings of that reference field?

Earlier I used different content types, with which it was no problem to get a different Pathauto pattern for each. But as the fields in the content types were the same I would like to solve it like this.

# Answer
> 3 votes
Right beneath the pattern input you have a link that opens a popup to let you choose tokens to be put in the pattern. For field values it normally goes along the line of `[node:field_foobar:value]`. Depending on the field value you may also consider to either provide your own custom token or to alter the current token with an alter hook to replace the value with an URL-safe value (like to prevent the URL contains an Emoji for example).

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


title: Composer downgrading module version

text:
# Question
Title: Composer downgrading module version
I wish to move the bootstrap theme from the repository located in the folder `theme/custom` to be a dependency in `composer.json`

I've checked that the current version `drupal/bootstrap` is `3.16`

I perform `rm -rf web/theme/custom/bootstrap` `composer require drupal/bootstrap:8.x-3.16` ^^-\> wrong syntax and have decided to just `composer require drupal/bootstrap`

Now I need to downgrade the version of drupal/bootstrap in composer.json and perform `composer update --lock`

But I got an error:

```
Nothing to modify in lock file
Unable to find a compatible set of packages based on your non-dev requirements alone.
Your requirements can be resolved successfully when require-dev packages are present.
You may need to move packages from require-dev or some of their dependencies to require.

  Problem 1
    - Root composer.json requires drupal/bootstrap 3.16, found drupal/bootstrap[3.23.0] but it does not match the constraint.

```

Any hints would appreciate.

# Answer
> 0 votes
What that I have done to fix it is obvious from the question remove drupal/bootstrap from composer.lock and from composer.json `composer require drupal/bootstrap:3.16`

---
Tags: composer, version-control
---


# Question
Title: How to check if managed_file has uploaded a video and use it in states
I want to disable the submit button in a form for as long as there are no value/uploaded video in a managed\_file but I can't seem to find what form name or element property I have to check for in `#states`.

I have the following:

```
$form['file'] = [
  '#type' => 'managed_file',
  '#title' => t('File'),
  '#description' => $this->t('Choose video to upload.'),
  '#upload_validators' => $validators,
];
$form["submit"] = [
  "#type" => "submit",
  "#value" => t('Submit'),
  '#states' => [
    'enabled' => [
      ':input[name="file"]' => ['empty' => FALSE],
    ],
  ],
];

```

I've also tried using `value => true`, `:input[name="files[0]` and `:input[name="files[file]` without luck. How can I enable the submit button when file has been processed?

# Answer
> 0 votes
If you examine the comments in the documentation, there are several things to look out for:

1. You may need to target the element's widget, as mentioned in this comment. Most likely you would do this in a `#process` callback or in a form alter hook.

> This is a good nuance to understand - thanks! Targeting the widget worked for me on a number field. It gets ignored otherwise.

```
// My number field is hidden unless repeat is selected
$form['field_myfield_num']['#states'] = [
  'visible' => [
    ':input[name="field_myfield_select"]' => ['value' => (string) 'repeat'],
    ],
];

// My number field is set as required when repeat is selected.
$form['field_myfield_num']['widget']['0']['value']['#states'] = [
  'required' => [
    ':input[name="field_myfield_select"]' => ['value' =>  (string) 'repeat'],
  ],
];

```
2. In the same comment above, we also see that sometimes it helps to cast your candidate value to a string: `['value' => (string) 'repeat']`. I've also seen this explicitly mentioned elsewhere, but can't find the reference.
3. It is possible to test for a negation using `'!value'`, as seen in this comment:

> I had a form with a field of #type select\_or\_other, which renders like radios. I wanted to enable the submit button when the form element was not "none". The following worked for me:

```
$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Donate'),
  '#button_type' => 'primary',
  '#states' => [
    'enabled' => [
      ':input[name="amount[select]"]' => ['!value' => 'none'],
    ],
  ],

```

---
Tags: 8, forms, files
---


# Question
Title: Is it possible to return a form element AND an ajax response from the same ajax callback function?
I have an ajax callback function that needs to return a form element and also an ajax response. Is it possible to do both?

In my callback I need to set and return something like:

```
$form['fid'] = array(
  '#type' => 'textfield',
  '#value' => 1,
);
return $form['fid'];

```

And also something like:

```
   $response = parent::uploadAjaxCallback($form, $form_state, $request);
   return $response;

```

Is there a way that I can achieve return both a form element and an ajax response?

EDIT: Latest attempt is returning the form element for display but when I examine the $form from the form build function the value is still empty.

```
class MyManagedFile extends ManagedFile {

  /**
   * {@inheritdoc}
   */
  public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {

    $response = parent::uploadAjaxCallback($form, $form_state, $request);

    $form['fid'] = array(
      '#type' => 'textfield',
      '#prefix' => '<div id="fid">',
      '#suffix' => '</div>',
      '#value' => '1',
    );

    $response->addCommand(new ReplaceCommand('#fid', $form['fid']));
    return $response;

  }

}

```

Examining the $form from the form builder (dpm($form)) results in:

\[fid\] =\> Array ( \[#type\] =\> textfield \[#prefix\] =\>

```
        [#suffix] =>

    )

```

# Answer
If you want to do more than simply return new markup, then your response should be an instance of `Drupal\Core\Ajax\AjaxResponse`, to which you can append one or more AJAX commands via the `addCommand()` method.

A simplified version of this would be:

```
use Drupal\Core\Ajax\AjaxResponse;
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#my-wrapper-id', $form['fid']));
return $response;

```

I recommend checking out a tutorial, such as one of those below, for more information on using AJAX with FAPI:
> 1 votes

---
Tags: forms, ajax
---


title: Dependent Dropdown in Field Widget

text:
# Question
Title: Dependent Dropdown in Field Widget
I want to implement a Dependent Dropdown for a custom field widget.

I have a custom field with 5 select boxes. Each subsequent dropdown should populate based on values from previous Dropdown. I have a 5 functions that takes arguments to get the values.

I have implemented that, but I need to Ajaxify it, so that I can populate without page refreshes. Any pointers on how to do that?

Basically, I am trying to implement the below thing (from examples module) with FieldWidget.

https://cgit.drupalcode.org/examples/tree/ajax\_example/src/Form/DependentDropdown.php

# Answer
> 2 votes
You didn't deserve the downvote: this is a perfectly good question, one that has simply no answer anywhere on the web yet. All of them only speak about dependent dropdowns in forms, not custom fields where we have two extra problems: first, being out of real form context when setting up ourselves, second, potentially being multivalued.

It took me some time to figure it out but here it is. We're extending `WidgetBase`:

```
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $id = $this->fieldDefinition->getUniqueIdentifier();
  $wrapper_id = "XXX-$id-$delta-replace";

  $selected_value1 = $items[$delta]->value1 ?? 0;
  $element['value1'] = $element + [
    '#type' => 'select',
    '#options' => $value1_options,
    '#empty_option' => '---',
    '#default_value' => $selected_value1,
    '#weight' => 1,
    '#ajax' => [
      'event' => 'change',
      'method' => 'html',
      'callback' => [$this, 'getValues'],
      'wrapper' => $wrapper_id,
      'progress' => [
        'type' => 'throbber',
        'message' => NULL,
      ],
    ],
  ];

  $selected_value2 = $items[$delta]->value2 ?? 0;
  $element['value2'] = [
    '#type' => 'select',
    '#empty_option' => '---',
    '#default_value' => $selected_value2,
    '#options' => $this->loadOptions($selected_value1),
    '#prefix' => "<div id='{$wrapper_id}'>",
    '#suffix' => '</div>',
    '#validated' => TRUE,
    '#weight' => 2,
  ];

  $element += [
    '#type' => 'container',
    '#attributes' => ['class' => ['container-inline']],
  ];

  return $element;
}

```

Fill `$value1_options` with the options of your first dropdown. Change `$wrapper_id` as you please but we don't know the actual ID the `select` will receive, so we have to make sure we make it unique in some other way (note that there might be more than one of the same custom field type in the final form, so using the name and the delta only will not suffice).

Using `'#validated' => TRUE` is usually frowned upon but this is the only easy way to make sure the second select will not result in an "Illegal choice" validation error after we replace the options without the form being aware of the possible values. One standard advice is to pre-fill the second dropdown with the union of all possible values, making sure that later dependent lists always use a subset of that full list but this wasn't really feasible in my case (or any other really dynamic case). Dependent lists in custom forms can simply return the original form element, so this doesn't apply to them, but custom fields can't locate the actual corresponding `$form[]` element, so this is the best I could come up with. It works.

Next, the function that loads the options of the dependent dropdown, depending on the value selected in the master one:

```
private function loadOptions($id) {
  $options = [];
  if ($id) {
    // load whatever options belong to the value of $id
    $options = ...;
  }
  return $options;
}

```

And finally, the Ajax glue to hold it together:

```
public function getValues(array &$form, FormStateInterface $form_state) {
  $triggeringElement = $form_state->getTriggeringElement();
  $selected_value = $triggeringElement['#value'];
  $html = '';
  $options = $this->loadOptions($selected_value);
  foreach ($options as $key => $value) {
    $html .= "<option value='$key'>$value</option>";
  }

  $ajax_response = new AjaxResponse();
  $wrapper_id = $triggeringElement['#ajax']['wrapper'];
  $ajax_response->addCommand(new HtmlCommand("#{$wrapper_id} select", $html));
  return $ajax_response;
}

```

If you compare the whole lot to the custom form solution, it's mostly the same but there are small differences in how to identify the correct element and how to actually replace the options of the dependent list that make this work in the field case.

# Answer
> 0 votes
I ended up using an API call and using javascript to populate the fields. Its not the correct solution, but it works.

---
Tags: 8, entities
---


# Question
Title: validate a base field in a particular content type
Since `title` field is considered as base field in Drupal 8, I opted `hook_entity_base_field_info_alter` to add validation to it. But when I look at that hook.

```
hook_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type)

```

It doesn't holds a `$bundle` argument. So I couldn't add a validation for title field of a particular node type. How can I override it to be node type specific?

# Answer
Base fields are by definition not bundle specific, you can't add something for a specific bundle in that hook.

However, what you can do is save it as a base field override. See how NodeTypeForm::save saves different default values and labels for base fields as base field overrides.
> 3 votes

# Answer
You can check too node title validation https://www.drupal.org/project/node\_title\_validation

This module check unique titles, max & min characters and blacklist words.
> 0 votes

---
Tags: 8, nodes, plugins
---


# Question
Title: How do I add a leaflet provider to the list of geocoder providers?
I want configure the Leaflet geocoder provider, but I don't know how.

I have enabled the *Geolocation - Leaflet* sub-module of the Geolocation Field module, but visiting /admin/config/system/geocoder/geocoder-provider, I see an empty list.

>

The list of the geocoder implementations doesn't list the Leaflet one. How can I add it?

# Answer
> 0 votes
The *Geolocation - Leaflet* module that is part of the Geolocation Field module is a map provider, a provider that is able to show a map using data provided by a site/API (Google Maps API or Natural Earth, for example). The providers used from the Geocoder module (which is the module handling the setting page on /admin/config/system/geocoder/geocoder-provider) obtain a location from other data, for example an IP and the GeoIP database data.

There cannot be a Geocoder Leaflet provider, as Leaflet is for showing a map, not getting a location from other data.

---
Tags: 9
---


title: Can't log in as admin

text:
# Question
Title: Can't log in as admin
Someone let us know about an error on our site. I logged in (as an admin). I was able to move the site to maintenance mode and then went through the steps to clear the cache on the site. Once I did that, I am no longer able to log in or even get to the log in page. I went to our site: safefields.org/user and I get this error: safefields.org is currently unable to handle this request. HTTP ERROR 500 How can I fix any of this if I can't even log in?

# Answer
When you type in `safefields.org/user` your site immediately redirects to the login page `safefields.org/user/login` which I believe indicates that your Drupal site is running but gives you a WSOD (white screen of death). Usually that is because of a memory\_limit constraint.

**Things to investigate:**

* Try to use Drush to set the maintenance mode back to 0: `drush vset maintenance_mode 0` this should get your site visible again
* Check your settings.php and see if you have a memory\_limit set there, increase to 512M or higher clear cache (either via Drush or empty cache tables directly in the database)
* Check your php.ini file either in the root of your site's folder or in your public\_html folder and increase it in size.
* Google "Drupal 7 WSOD" as they say: add error reporting to your settings.php file to see what the errors are so you can search more effectively for what's causing your problem. https://www.drupal.org/node/158043

`error_reporting(-1);`
`$conf['error_level'] = 2;`
`ini_set('display_errors', TRUE);`
`ini_set('display_startup_errors', TRUE);`
> 0 votes

---
Tags: 7, users
---


# Question
Title: How do I get product variations in a preprocess function?
I'm trying to do something like this.

```
function clientname_preprocess_commerce_product(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  // Get the product variations and store them in $variations.
  if (!empty($variations)) {
    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */
    $variation = reset($variations);
    /** @var \Drupal\commerce_product\ProductVariationFieldRendererInterface $variation_renderer */
    $variation_renderer = \Drupal::service('commerce_product.variation_field_renderer');
    // Override the variation list price with the price of the variation.
    $product['variation_list_price'] = $variation_renderer->renderField('list_price', $variation);
  }
}

```

I am not sure how to get the product variations in `hook_preprocess_commerce_product()`.

What code should I use to get the product variations and store them in `$variations`?

# Answer
> 4 votes
```
  $product = $variables['elements']['#commerce_product'];

  $variations = $product->getVariations();

  foreach ($variations as $variation){
      $list_price = $variation->getListPrice();
    // Do something with the variation list price here...
  }

```

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


# Question
Title: Display multiple timezone values from a single date/time entry
In Drupal 7 Views Date/Time field, is there a way to generate multiple timezone values from a single event date, with start and end values?

For example, if an event is entered into the start/end Time fields with 4:00pm to 5:30pm (using PHP date format "g:ia"), is there any way to decrease or increase the rendered values to reflect different time zones, as in "4:00pm to 5:30pm EST / 1:00pm to 2:30pm PST"?

# Answer
I guess that could be done using jQuery (or a separate module that does the same) but to me, the easiest way would be jQuery.

So you load your date/time field a second time in your view, "Rewrite the output of this field" so you can give it a different HTML structure and different classes name e.g.

```
<div class="timezone2"><span class="gmt-label">GMT </span><span class="myOffsetTimezone">+10:00</span><div>

```

Here's a link on how you could do that: getTimezoneOffset via javascript
The great thing with "getTimezoneOffset" is that it accounts for daylight savings time as well.

Example of your Views Field:
> 1 votes

# Answer
Yes, of course Drupal can render your date in what ever other time zone you like, it doesn't depend on which time zone was used to enter the date.

Views allows you to select which time zone to use to display your Date field, you can find it under Field settings.

So if you need to display the same date in a different time zone you can simply add the same Field again, and choose a different time zone in its settings. You can add as many of the same fields as you like and set them to different settings.

If you don't like the styling and want to show all the date fields in one element you can "Exclude from display" all of the date fields, then add a Custom text Field or Rewrite the last date field and enter your own code in order in which you want it.

When Rewriting there is a section you can open that lists available patterns. You can copy tokens for each date from there.

If you want Drupal to print out the time zone of a field and you don't have it in any of the offered Date formats you can create your own new format (under Drupal Regional settings) that shows the time zone. Then adjust all the Field settings to use that Format and you won't have to do it manually in your Rewrite or in the Field Label.
> 1 votes

---
Tags: 7, views, datetime
---


title: How do I completely translate a page?

text:
# Question
Title: How do I completely translate a page?
I want to develop a site in two languages. How do I completely translate a page?

For example, the menu tab and other places cannot be translated. I just can translate using the *Translate* tab.

>

In the following screenshot, the parts highlighted with a red box cannot be translated.

>

The language switch tab appears as in the following screenshot.

>

# Answer
In the context of translations everything that is printed out on a Drupal page can be grouped under either **Interface** or **Content**.

Content (nodes, blocks) usually has the "Translate" tab/link visible somewhere near the other content editing links.

Interface text is most often translated through the **Translate interface \> Translate** page. You can find it under the "Regional and language" settings.

Some modules provide on-screen or within-context translation tools for the interface text, but they all work on top of that "Translate interface" tool, so you can find all interface strings there.

The "Translate interface" tool is capitalization sensitive, so you have to enter the **exact** string as is written in the database or a module. "My Menu Item" is *not* the same as "My menu item".

To be able to see a string in the search results in the "Translate interface" tool you first have to visit the page where that text is shown in a non-default language in order for Drupal to record that string and make it available for translation.

Drupal is super flexible when it comes to multilingual setup and it allows you to pick which parts you want to translate and which parts you don't need translated or localized. That's why there are different modules responsible for translations of different parts of the interface. So keep in mind which modules you need to enable so you can translate features you have on your website.
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Registration email showing default mail message as well new custom message
How to stop default mail , i want to override default mail with my custom body message?

Here is my code :

```
function mag_api_mail_alter(&$message) {
  // only alter register forms
  if (!empty($message['id']) && $message['id'] == 'user_register_no_approval_required') {

  // make it a bit neater to access fields

    $nids = \Drupal::entityQuery('node')->condition('type','email_template')->execute();
    $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);
    $data_fields = array();
    foreach ($nodes as $new_data){
        $data_fields[] = $new_data->get('body')->getValue();
    }
    $contact_message = $message['params']['account'];
    $first_name = $contact_message->field_first_name->value;
    $username_email = $contact_message->get('name')->value;
    $pass = 'test';
    $app_url = 'abcd.com';

    /*custom field added through configuration*/

    $to_replace_keys = array("[user_name]","[user_email]","[user_password]","[app_url]");
    $replace_keys =array($first_name,$username_email,$pass,$app_url);
    $success_email_msg = str_replace($to_replace_keys, $replace_keys,$data_fields[0][0]['value']);
    // Assigning new message to mail body.
    $message['body'][] = $success_email_msg;

   }
}

```

Its is working but i am not able to find out why is this showing default mail message as well new body message.

I just want to show my custom body message.

# Answer
> 2 votes
`$message['body'][] = $success_email_msg;` is appending your variable to the existing array. You'll need to remove the default content from the `$message['body']` array if you don't want it

e.g. `unset($message['body']['whateverkey'])` to remove a specific part. Or `$message['body'] = [$success_email_msg];` to reinitialise the variable as a new array

---
Tags: 8, emails
---


title: Pass User object to Token::replace

text:
# Question
Title: Pass User object to Token::replace
I've the following code (sample) that runs on Cron and sends SMS to users.

```
$token = \Drupal::token();
$message = Hey, [current-user:account-name];
$message_value = $token->replace($message);

```

When cron run, Getting the SMS text as '*`Hey Anonymous`*' This works correctly on site when user logins in. but not on cron.

So I tried to pass the user object to replace the token like follows but that doesn't work. Getting same result.

```
use Drupal\user\Entity\User;
$user = User::load($uid);
$message_value = $token->replace($message,['user' => $user]);

```

There are so many nodes created using this token. So I can't edit them all with new/custom token. So Is there any way to replace the user token, without writing a custom token? The other workaround is to use `str_replace` like follows, but there might exists other user tokens in the same text. so not preferable.

```
  $message_value = str_replace('[current-user:account-name]', $name, $message);

```

Any suggestions?

# Answer
The `current-user` token will always take its data from the current user, you can't override it with parameters. See `user_tokens`:

```
if ($type == 'current-user') {
  $account = User::load(\Drupal::currentUser()
    ->id());
  $bubbleable_metadata
    ->addCacheContexts([
    'user',
  ]);
  $replacements += $token_service
    ->generate('user', $tokens, array(
    'user' => $account,
  ), $options, $bubbleable_metadata);
}

```

If you need to control the account object used for the token, use `user` instead

```
$message = 'Hey, [user:account-name]';
$message_value = $token->replace($message, ['user' => $account]);

```
> 3 votes

# Answer
Your approach

```
$user = User::load($uid);
$message_value = $token->replace($message,['user' => $user]);

```

doesn't work because of user.tokens.inc:153 (as of 8.8.11):

```
  if ($type == 'current-user') {
    $account = User::load(\Drupal::currentUser()->id());
    $bubbleable_metadata->addCacheContexts(['user']);
    $replacements += $token_service->generate('user', $tokens, ['user' => $account], $options, $bubbleable_metadata);
  }

```

So, depending on where you call the `$token->replace`, you may try to tweek the `\Drupal::currentUser()->id()` by re-setting it temporary.
> 0 votes

---
Tags: 8, tokens
---


# Question
Title: Programmatically uploading and validating a user_picture
I use the following code to modify the image in the `user_picture` field of user with uid 42:

```
// Get user.
$user = \Drupal\user\Entity\User::load(42);

// Create file.
$file = file_save_data(
  file_get_contents('/tmp/image.jpg'),
  'public://pictures/image.jpg'
);

// Set file.
$user->set('user_picture', $file->id());

// Save user.
$user->save();

```

It works great, but it's very simplistic and doesn't do any of what has been configured in `/admin/config/people/accounts/fields/user.user.user_picture`, e.g:

* Validate "Allowed file extensions".
* Possibly downscale based on "Maximum image resolution".
* Save image in the "File directory" location.
* Validate "Maximum upload size".

Is there a way to somehow upload and set the file through what has been configured in the field?

# Answer
You can access the values of the image field settings with:

```
$user->getFieldDefinition('user_picture')->getSettings();

```

Which will return an array, example:

---

You then can use **file\_save\_upload**

and you can pass to it for second param, an array containing all the validation functions

> array **$validators**: (optional) An associative array of callback functions used to validate the file. The keys are function names and the values arrays of callback parameters which will be passed in after the file entity. The functions should return an array of error messages; an empty array indicates that the file passed validation. The callback functions will be called in the order specified in the array, then the hook `hook_file_validate()` will be invoked so other modules can validate the new file.
>
> <sub> source: https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file\_validate/8.9.x </sub>

Here are the validation functions you can use:

> <sub>Source: https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/8.9.x </sub>
> 1 votes

# Answer
Follow what No Sssweat said and as the documentation explains that "*The files will be added to the `file_managed` table as temporary files. Temporary files are periodically cleaned*" you'll need to set your file as permanent before to save it, else it will be erased during a cron task.

```
if ($file = file_save_upload($form_field_name, $validators, $destination, $delta, $replace)) {
  $file->setPermanent();
  $file->save();
}

```
> 1 votes

---
Tags: 8, users, files
---


# Question
Title: how can i specify in my migration not to migrate unpublished content?
in a drupal 8 migration, is there a way to specify in the .yml that i dont want to migrate any content that is unpublished . Or would that have to be done in a plugin?

# Answer
> 4 votes
You could try using the skip on value plugin.

Untested, but probably like:

```
process:
  status:
    plugin: skip_on_value
    method: row
    not_equals: true
    value: 1
    source: status

```

Should only import published content.

---
Tags: migrations
---


# Question
Title: How to use hook_field_preprocess to add a prefix/suffix to an entity reference field for different view modes?
I'm trying to move some markup from twig templates to `hook_preprocess_field()`.

I have an entity reference field (media image) that I want to add a prefix and suffix to.

I added a prefix and suffix like this:

```
function MYMODULE_preprocess_field__MYFIELD(&$variables) {
  $prefix = 'Hi... ';
  $view_mode = $variables['element']['#view_mode'];
  if ($view_mode == 'second_view_mode') {
    $prefix = 'Hello... ';
  }
  $suffix = '... there.';
  $variables['items'][0]['content']['#prefix'] = $prefix;
  $variables['items'][0]['content']['#suffix'] = $suffix;
}

```

With this code, my prefix and suffix get added, but they are cached, and the same for all view modes.

If I rebuild the cache and visit a node in `second_view_mode`, then I see `Hello...`  as the prefix for all instances of the field. But if I rebuild the cache and visit a node not in `second_view_mode`, then I see `Hi...`  for all instances of the field, even those on a node in `second_view_mode`.

I use this same approach/code for formatted text fields and I don't experience this caching problem. So I think I need to do something different for this entity reference field, but I don't know what to do.

How do I add a prefix/suffix to an entity reference field in a preprocess function for different view modes?

# Answer
If you have configured the reference field to render the referenced entities then the build array usually contains #cache keys, which result in a separate cache entry for this render array including anything you've attached to it in preprocess. This has nothing to do with the view mode of the parent entity, the cached result will also be reused when the media is displayed in a different entity.

You could split up the field content in multiple render elements so that you have the prefix/suffix outside of the cached element `content`:

```
$variables['items'][0]['content'] = [
  'prefix' => ['#markup' => $prefix],
  'content' => $variables['items'][0]['content'],
  'suffix' => ['#markup' => $suffix],
];

```
> 2 votes

---
Tags: theming, caching
---


# Question
Title: Some #states not working for custom field but do work on identical webform field
I'm working on a project where I'm programmatically cherry picking elements from a webform and then creating a custom form with all sorts of alterations and additions to the "cloned" webform fields.

```
$my_custom_field = $webform->getElement($webform_field_id, TRUE);

```

I'm then rendering a number of custom fields like the above in a custom form that extends from FormBase. The custom webform consists of fields, custom containers, attributes etc.

Everything works fine, #states included, apart from the "pattern" state and a few other states that are based on relative values e.g. "greater" / "greater\_equal" / "lower" / "lower\_equal". I'm adding these #states programmatically to the custom fields.

Example:

```
$custom_field['#states'] = [
  'visible' => [
    ':input[name="controlling_field_name"]' => [
      'value' =>
        // I've tested this pattern, it works in the webform field fine.
        'pattern' => $some_regex_pattern,
      ],
    ],
  ],
];

```

Apart from 'pattern', I've tried 'between' and 'greater', 'greater\_equal', 'lower' and 'lower\_equal' with no success.

The same exact #states (same field being dependant on same controlling field under the same exact conditions) work fine on the original webform field (when I view the webform on the admin theme for example) which makes me think that something is missing from / messing up with these #states on my custom theme.

No JS errors in the console whatsoever.

The structure of "data-drupal-states" when I render this custom field (webform field "clone") in my custom theme is exactly the same as the webform field that's rendered on the admin theme ie in its "native" webform.

Other #states work fine for the custom field ("value", "checked" etc.).

Any ideas on what's possibly messing up these specific states?

# Answer
> 1 votes
Webform form elements have additional goodies, not available in Drupal Core. But you can add those additional features with just a few lines of code:

```
<?php
public function buildForm(array $form, FormStateInterface $form_state) {
 $config = $this->config('custom_module');
 // Define the element(s).
 $form['nodes'] = [
   '#type' => 'entity_autocomplete',
   '#title' => $this->t('Select favorite articles.'),
   '#multiple' => 15,
   '#target_type' => 'node',
   '#selection_handler' => 'default:node',
   '#selection_settings' => [
     'target_bundles' => ['article' => 'article'],
     'sort' => ['field' => 'title', 'direction' => 'ASC'],
   ],
   '#default_value' => $config->get('nodes'),
 ];
 // Process the element(s).
 $this->elementManager->processElement($form['nodes']);
 // Attach behaviors. Unsaved: Warn users about unsaved changes.
 $form['#attributes']['class'][] = 'js-webform-unsaved';
 $form['#attached']['library'][] = 'webform/webform.form.unsaved';
 return parent::buildForm($form, $form_state);
}

```

Notice the `elementManager->process()` and the additional libraries. Watch the video in the linked blog post to get an idea where to get the elementManager and the libraries.

https://www.jrockowitz.com/blog/webform-apis

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


title: How do I get the taxonomy term name?

text:
# Question
Title: How do I get the taxonomy term name?
I added a taxonomy field inside a view.

>

I need to show the term name on the page in a grouped way, like this.

* taxonomy term1 name

+ title1
    + content1
    + title2
    + content2
* taxonomy term2 name

+ title1
    + content1
    + title2
    + content2

I am not sure what to put on template file to show the term name. I tried `{{term_node_tid}}`, but it doesn't show any output. On the view preview, the output is exactly what I expect.

>

How do I show it that way?

# Answer
> 0 votes
If you only have one term in each node then you can use the "All taxonomy terms" Field. There is a token for the term Name you can use in the Rewrite results section of the Field Settings:

```
Rewrite results
Override the output of this field with custom text
{{ term_node_tid__name }}

Replacement patterns

```

When you open `Rewrite results` and enable the Override option you will see the `Replacement patterns` below the text area. Open it and you will see the token list. Copy your token and paste it in the textarea above it.

If you have more than one term on any node the `All taxonomy terms` Field will group the combinations and treat them as independent output, which is probably not what you want.

In that case you need to use a more direct approach, the actual Taxonomy term Reference Field from your Content Type. This field gives you the option to show the values in different Views results rows (if it's a multivalue field).

When you disable showing all the values in the same row, and Group by that field, you will get independent terms as group headings and all their content listed below them.

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


# Question
Title: How to process single queue item using QueueWorker on cron runs?
For each cron run, I would like to be able to process only 1 item in my queue using QueueWorker. At the moment it seems to me that Drupal keep processing items until it reaches the time parameter for the queue worker. I want to change this behavior to process 1 queue item at a time regardless of the time param. This is what I have so far:

```
/**
 * Processes Tasks.
 *
 * @QueueWorker(
 *   id = "data_provider_queue",
 *   title = @Translation("task worker: data provider queue"),
 *   cron = {"time" = 60}
 * )
 */
class SomeQueueWorker extends QueueWorkerBase {
  /**
   * {@inheritdoc}
   */
  public function processItem($data) {
       // Do something with data.
       // This seems to keep getting called for more than
       // one item in the queue. How do we change that?
  }
}

```

Is this possible with QueueWorker or should I just process queue items in a cron hook manually?

# Answer
Queue workers are meant to be processed in batches, not 1-each-cron-run.

If you want to process only a single item every cron run, then use the cron-hook.
> 2 votes

# Answer
As per @Eyal's answer, process it via a cron hook like:

```
/**
 * Implements hook_cron().
 */
function example_cron() {
  $queue = \Drupal::queue('data_provider_queue');

  if ($queue_item = $queue->claimItem()) {

    /** @var \Drupal\Core\Queue\QueueWorkerInterface $queue_worker */
    $queue_worker = \Drupal::service('plugin.manager.queue_worker')
      ->createInstance('data_provider_queue');

    try {
      // Process only 1 queue item per cron run.
      $queue_worker->processItem($queue_item->data);
      $queue->deleteItem($queue_item);
    }
    catch (\Exception $e) {
      // Something went wrong...
    }
  }
}

```

And do not forget to adjust your QueueWorker and discard the cron time, so that it only processes via your cron hook:

```
/**
 * Processes Tasks.
 *
 * @QueueWorker(
 *   id = "data_provider_queue",
 *   title = @Translation("task worker: data provider queue"),
 * )
 */

```
> 1 votes

---
Tags: 8, queue
---


# Question
Title: Getting the error "No active batch." when running any batch
I am getting this error when running any batch on the site:

> No active batch.

I thought this may have been a server issue, so I tried it locally, but I got the same error. I tried deleting all the records in the batch table, but I also got the same result.

The only thing I can think of is that perhaps the web server is down. Why would that effect batches that do not connect to their servers?

# Answer
If you are using the Secure Pages module, you have apply the patches provided for that module.

As I am using the Secure Pages module, that fixed my problem.

> ### Steps to install Secure Pages 7.x-dev
> 1 votes

# Answer
I had the same issue. It was caused by the secure pages issue. So I went to secure pages settings page, and in the ignore list, I added my url (e.g. admin/structure/abc). It worked good. Hope it helps someone.
> 0 votes

# Answer
Update For Drupal 8, please, check this topic - https://www.drupal.org/project/drupal/issues/3055287#comment-13911732

removing logger.factory service from the batch fix the problem
> 0 votes

---
Tags: 7, batch-operations
---


title: How do I access profile fields?

text:
# Question
Title: How do I access profile fields?
I have installed the Profile module. I am trying to programmatically load profiles. The code works, but I am not able to access any field value.

```
class IdCardController extends ControllerBase {

  /**
   * Init id card download.
   */
  public function initDownload(User $user) {

    $user_profile = $this->entityTypeManager()->getStorage('profile')->loadByProperties([
      'uid' => $user->id(),
      'type' => 'personal_information',
    ]);
    kint($user_profile);
  }
}

```

Using `kint()`, I can see all methods are protected.

>

# Answer
> 3 votes
You could examine the Profile Entity class here profile / src / Entity / ProfileInterface.php, showing you a list of public methods including its getter methods, eg.:

```
$profile->getCreatedTime();

```

Additionally and similar as with Entities in general, you can also call data via either `$entity->get('field_name')->getValue()` or `$entity->field_name->getValue()`.

See more on that here: Get information from an entity/ Entity methods

So if you have a Profile Entity with a field machine name `address`, then you could get its data like:

```
$profile = \Drupal\profile\Entity\Profile::load(123);
$profile->get('address')->getValue();
$profile->address->getValue();

```

---
Tags: users, 9
---


# Question
Title: Cannot get the sub-theme retrieve the CSS files from libraries
I have localized Bulma theme following the instructions which were as simple as creating a new directory called 'libraries' under main directory (httpdocs) and putting the sources files in it. No problem with that.

* I have been trying to create a sub theme which I named "bulma\_sub".

bulma\_sub is located under themes' folder (where the bulma base theme is).

* there are three files in bulma\_sub folder with the following set-up.

**bulma\_sub.info.yml**

```
name: bulma_sub
description: 'subtheme based on bulma'
type: theme
base theme: bulma
core_version_requirement: ^8.8 || ^9
package: Core

regions:
  header: 'Header'
  navbar_branding: 'Branding'
  navbar_social: 'Social'
  header_search: 'Search'
  header_tabs: 'Tabs'
  primary_menu: 'Primary menu'
  secondary_menu: 'Secondary menu'
  highlighted: 'Highlighted'
  help: 'Help'
  content: 'Content'
  sidebar_first: 'Sidebar First'
  sidebar_second: 'Sidebar Second'
  tile_one: 'Tile 1'
  tile_two: 'Tile 2'
  tile_three: 'Tile 3'
  tile_four: 'Tile 4'
  tile_five: 'Tile 5'
  bottom: 'Bottom'
  footer: 'Footer'

libraries:
  - bulma_sub/global

# Information added by Drupal.org packaging script on 2020-10-27
version: '8.x-1.0-rc1'
project: 'bulma'
datestamp: 1603840308

```

**bulma\_sub.libraries.yml**

```
    global:
      css:
        theme:
          css/overrides.css: {}
          css/style.css: {}
      dependencies:
        - core/jquery
        - core/jquery.once
        - core/drupal

```

bulma\_sub.theme file (same as the source file)

```
<?php

/**
 * @file
 * The primary PHP file for the Drupal Bulma base theme.
 */

use Drupal\block\Entity\Block;
use Drupal\bulma\Bulma;
use Drupal\bulma\Bulmaswatch;
use Drupal\file\Entity\File;

/**
 * Implements template_preprocess_page().
 */
function bulma_preprocess_page(&$variables) {

  // Site slogan as separate variable.
  $site_config = \Drupal::config('system.site');
  $variables['site_slogan'] = $site_config->get('slogan');
}

/**
 * Implements template_preprocess_file_link().
 */
function bulma_preprocess_file_link(&$variables) {
  /** @var \Drupal\Core\Entity\Entity\File $file */
  $file = ($variables['file'] instanceof File) ? $variables['file'] : File::load($variables['file']->fid);

  $variables['icon'] = Bulma::getFileIcon($file);
}

/**
 * Implements hook_page_attachments_alter().
 */
function bulma_page_attachments_alter(&$page) {

  // Force IE to use Chrome Frame if installed.
  $page['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => [
        'http-equiv' => 'X-UA-Compatible',
        'content' => 'IE=edge,chrome=1',
      ],
    ],
    'chrome_frame',
  ];

  // Remove image toolbar in IE.
  $page['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => [
        'http-equiv' => 'ImageToolbar',
        'content' => 'false',
      ],
    ],
    'ie_image_toolbar',
  ];

  // Alter viewport.
  $page['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'viewport',
        'content' => 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no',
      ],
    ],
    'viewport',
  ];
}

/**
 * Implements bulma_preprocess_HOOK() for breadcrumb.
 */
function bulma_preprocess_breadcrumb(&$variables) {
  // Load Bulma class from settings.
  $classes = array_merge(['breadcrumb'], Bulma::multiSettings('breadcrumb'));
  foreach ($classes as $class) {
    $variables['attributes']['class'][] = $class;
  }
  $variables['attributes']['role'] = 'navigation';
  $variables['attributes']['aria-labelledby'] = 'system-breadcrumb';
}

/**
 * Implements theme_menu_local_tasks().
 */
function bulma_preprocess_menu_local_tasks(&$variables) {

  // Load Bulma class from settings.
  $bulma_tabs_class = Bulma::multiSettings('tabs');

  if (!empty($bulma_tabs_class)) {
    // Set variables.
    foreach ($bulma_tabs_class as $key => $class) {
      $variables[str_replace('is-', '', $key)] = $class;
    }

  }

}

/**
 * Implements hook_form_alter().
 */
function bulma_form_alter(&$form, $form_state, $form_id) {

  // Check for actions buttons, group them.
  if (isset($form['actions'])) {
    $form['actions']['#attributes']['class'][] = 'field';
    $form['actions']['#attributes']['class'][] = 'is-grouped';

    // Loop trough array to get link type.
    // Better approach maybe to use https://www.drupal.org/project/button_link.
    foreach ($form['actions'] as $key => $action) {
      if (isset($action['#type'])) {
        if ($action['#type'] == 'link') {
          $name = (string) $action['#title'];

          // Check if button should be colorized.
          $button_color = Bulma::colorizeButton($name);

          // Add button class.
          if (!empty($button_color)) {
            foreach ($button_color as $class) {
              $form['actions'][$key]['#attributes']['class'][] = $class;
            }
          }
        }

      }
    }
  }

  switch ($form_id) {
    case 'node_preview_form_select':
      $form['backlink']['#options']['attributes']['class'][] = 'button';
      break;
  }

}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function bulma_form_search_form_alter(&$form, $form_state, $form_id) {

  // Remove label.
  $form['basic']['keys']['#title_display'] = 'invisible';

  // Update the placeholder.
  $form['basic']['keys']['#placeholder'] = t('Enter your keywords');

  // Wrap class to combine form.
  $form['basic']['#attributes']['class'] = 'field has-addons';

}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function bulma_form_search_block_form_alter(&$form, $form_state, $form_id) {

  // Update the placeholder, remove title - prevent double icon.
  $form['keys']['#title'] = '';
  $form['keys']['#placeholder'] = t('Search');

}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function bulma_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if ($variables['element']['#form_id'] === 'search_block_form') {
    $suggestions[] = 'form__search_block_form';
  }
}

/**
 * Implements template_preprocess_block().
 */
function bulma_preprocess_block(&$variables) {

  // Block as panel style.
  if (Bulma::singleSetting('general.block')) {
    if ($variables['configuration']['label_display']) {
      $variables['block_panel_style'] = TRUE;
    }
  }

  // Customize the ID and classes of the main menu block.
  $main_menu = Bulma::singleSetting('general.menu');
  $plugin_id = 'system_menu_block:' . $main_menu;
  // Match blocks by plugin ID to support Bulma and any active subtheme.
  if (!empty($variables['elements']['#plugin_id']) && $variables['elements']['#plugin_id'] == $plugin_id) {
    $variables['attributes']['id'] = 'navbar-menu';
    $variables['attributes']['class'][] = 'navbar-end';
  }

  // Set a region variable for use in templates.
  if (isset($variables['elements']['#id'])) {
    $block = Block::load($variables['elements']['#id']);
    $variables['region'] = $block->getRegion();
  }
}

/**
 * Implements template_preprocess_table().
 */
function bulma_preprocess_table(&$variables) {
  // Load existing classes.
  $existing_class = [];
  if (isset($variables['attributes']['class'])) {
    $existing_class = $variables['attributes']['class'];
  }

  // Load Bulma specific table classes from theme settings.
  $bulma_table_class = Bulma::multiSettings('table');

  // Merge classes.
  if (!empty($bulma_table_class)) {
    $variables['attributes']['class'] = array_merge($existing_class, $bulma_table_class);
  }

}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function bulma_theme_suggestions_links_alter(array &$suggestions, array $variables) {
  $link_type = $variables['theme_hook_original'];

  // We want only affect node and comment links.
  $target_output = ['links__node', 'links__comment'];

  if (in_array($link_type, $target_output)) {
    $suggestions[] = 'links__bulma';
  }

}

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

  // Define defaults for exclusion for rendering as bulma input.
  $exclude_input = [
    'hidden',
    'token',
    'radio',
    'checkbox',
    'submit',
    'image_button',
  ];

  // Submit button needs have render as button element.
  if ($variables['element']['#type'] == 'submit') {
    $suggestions[] = 'input__button__bulma';
  }

  // Add theme suggestions for others input elements.
  if (!in_array($variables['element']['#type'], $exclude_input)) {

    // Default wrapped input.
    $suggestions[] = 'input__bulma';
  }

}

/**
 * Implements template_preprocess_hook().
 */
function bulma_preprocess_input__bulma(&$variables) {
  // Make sure we have data to work from.
  if (empty($variables['element']['#type']) || empty($variables['element']['#title'])) {
    return;
  }
  // Field name and type.
  $type = $variables['element']['#type'];
  $name = (string) $variables['element']['#title'];

  // Check if we use icons.
  if (Bulma::singleSetting('general.icon')) {
    $variables['icon'] = Bulma::iconMatch($name, $type);

  }

  // Size of input buttons.
  $input_size = Bulma::singleSetting('bulma_elements_input_size');

  if ($input_size != 'none') {
    $variables['attributes']['class'][] = $input_size;
  }

}

/**
 * Implements template_preprocess_hook().
 */
function bulma_preprocess_input__button__bulma(&$variables) {

  // Field name and type.
  $name = $variables['element']['#value'];
  $type = $variables['element']['#type'];

  // We need render label inside button tag.
  $variables['label'] = $variables['element']['#value'];

  // Bulma submit classes.
  $variables['bulma_button_classes'] = [];

  // Check if button should be colorized.
  $button_color = Bulma::colorizeButton($name);

  if (!empty($button_color)) {
    $variables['bulma_button_classes'] = $button_color;
  }

  // Check if we use icons.
  if (Bulma::singleSetting('general.icon')) {
    // Define default if not matched.
    $variables['icon'] = Bulma::iconMatch($name, $type);

    // Hide label for search button.
    if ($variables['icon'] == 'search') {
      $variables['label'] = FALSE;
    }
  }

}

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

  // Navbar menu.
  $bulma_nav = Bulma::singleSetting('general.menu');

  // Check if any menu is selected to be nav menu.
  if ($bulma_nav != 'none') {
    if ($variables['menu_name'] === $bulma_nav) {
      $suggestions[] = 'menu__nav_bulma';
    }
  }

}

/**
 * Implements template_preprocess_form_element().
 */
function bulma_preprocess_form_element(&$variables) {

  // Render the form element inside the label for checkbox and radio.
  if (in_array($variables['element']['#type'], ['checkbox', 'radio'])) {
    $variables['label']['#children'] = $variables['children'];
    unset($variables['children']);
  }

}

/**
 * Implements template_preprocess_form_element_label().
 */
function bulma_preprocess_form_element_label(&$variables) {

  // Check additional theme labels settings.
  $bulma_labels = Bulma::multiSettings('label');

  if (!empty($bulma_labels)) {
    foreach ($bulma_labels as $key => $value) {
      $variables[$key] = $value;
    }
  }

}

/**
 * Implements template_preprocess_page_title().
 */
function bulma_preprocess_page_title(&$variables) {
  $variables['title_attributes']['class'] = 'title';
}

/**
 * Implements template_preprocess_views_view_table().
 */
function bulma_preprocess_views_view_table(&$variables) {

  // Define defaults for variables.
  $variables['bordered'] = FALSE;
  $variables['striped'] = FALSE;
  $variables['narrow'] = FALSE;
  $variables['table'] = TRUE;

  // Load Bulma specific table classes from theme settings.
  $bulma_table_class = Bulma::multiSettings('table');

  if (!empty($bulma_table_class)) {
    foreach ($bulma_table_class as $class) {
      $variables[str_replace('is-', '', $class)] = TRUE;
    }
  }
}

/**
 * Implements hook_library_info_alter().
 */
function bulma_library_info_alter(&$libraries, $extension) {
  // Swap in Bulmaswatch theme's CSS.
  if ($extension === 'bulma' &&
    isset($libraries['global']) &&
    ($theme = theme_get_setting('cdn.bulmaswatch.theme'))
  ) {
    // If bulmaswatch is configured to use the default theme, use Bulma directly.
    $cdn_data = Bulma::getCdnData();
    $properties = [];
    if ($theme === 'default') {
      $bulma_file = '/css/bulma.css';
      if (Bulma::isLocal()) {
        $css_file = '/libraries/bulma' . $bulma_file;
      }
      else {
        $css_file = $cdn_data['api']['bulma']['file_root'] . $bulma_file;
        $properties['type'] = 'external';
      }
    }
    else {
      $properties['minified'] = TRUE;
      $themes = Bulmaswatch::getThemes();
      if (isset($themes[$theme]['local_css'])) {
        $css_file = $themes[$theme]['local_css'];
      }
      else {
        $css_file = $cdn_data['api']['bulmaswatch']['file_root'] . "/{$theme}/bulmaswatch.min.css";
        $properties['type'] = 'external';
      }
    }
    $libraries['global']['css']['base'] = [
      $css_file => $properties,
    ];
  }

}

```

**File structure**

```
libraries
|_bulma
  |_css
    |_bulma.css
  |_sass

themes
|_bulma
  |_assets
    |_bulma.style.css
    |_bulma.style.scss
    |_overrides.css
    |_overrides
|_bulma_sub
  |_css
    |_overrides.css
    |_style.css

```

The sites shows up without any css applied. And also the Home link is duplicated. Any ideas?

And I get this error

> Fatal error: Cannot redeclare bulma\_library\_info\_alter() (previously declared in C:\Users\Y430\Sites\devdesktop\drupal-8.9.1\themes\bulma\bulma.theme:416) in C:\Users\Y430\Sites\devdesktop\drupal-8.9.1\themes\bulma\_sub\bulma\_sub.theme on line 416

if I copy bulma.theme file to bulma\_sub folder. I didn't face such issue when I created a sub-theme based on bootstraps before!

# Answer
> 1 votes
You need to carefully read the creating a subtheme guide.

The fatal error is because you just cut-and-paste the bulma.theme file from the main theme to the sub theme. This means that all the functions in the main theme are included twice-- once in the main theme, and once in the subtheme (because you have an exact copy in the subtheme).

You have two options to fix this.

1. Remove all the function calls in `bulma_sub.theme`, or
2. Rename the function calls to match the subtheme.

For example,

`function bulma_preprocess_views_view_table(&$variables)` should be `function bulma_sub_preprocess_views_view_table(&$variables) {`

Normally, you would do 1 (remove all the function calls in the subtheme) because those function calls will still get called from the main theme, so you only need them in your subtheme if you actually want to do something different than the main theme.

You wrote:

> ```
> there are three files in bulma_sub folder with the following set-up.
>
> ```

You will also need to put the CSS you want to use (that you defined in `bulma_sub.libraries.yml`) in the subtheme folder.

---
Tags: theming
---


# Question
Title: How do you add a class on webform submission in the modal?
I am using webform in a modal. now I want to add a class in the confirmation pop up of the webform. How I add class in submission form in twig. I am using html.html.twig of my theme to show webform in pop up. in below code I want a class {{ webform\_submisson}} if webform get submitted in the same pop. As I am single modal for webform and confirmation

```
 <div class="modal fade ticket-system-form {{ webform_submisson}}" id="TicketSystemInformation" tabindex="-1" role="dialog" aria-labelledby="TicketSystemInformationLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
  <div class="modal-header d-block">
    <a class="ticket-system-logo" href="/" title="Home" rel="home">
      <img src="/sites/default/files/logo-header%5B1%5D.png" alt="Home">
    </a>
<h4 class='modal-heading w-100'>dfgdfgfg</h4>
    <h5 class="modal-title w-100" id="ContactInformationLabel"></h5>

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
    <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">
    {{ drupal_entity('webform', 'ticket_system') }}
  </div>
</div>

```

# Answer
I fixed the issue with js below is my code: Hope it will help to other

```
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.customPacificadvisors = {
    attach: function (context) {
      var webform = jQuery(context).closest('form.webform-submission-form');
      if (webform.hasClass("webform-submission-ticket-system-form")) {
        var form_confirmation_obj = webform.find('.webform-confirmation');
        if (form_confirmation_obj.length > 0) {
          jQuery("#TicketSystemInformation").addClass("webform-submision-class")
        }
      }
    }
  };
})(jQuery, Drupal, drupalSettings);

```
> 0 votes

---
Tags: 8, theming, webforms
---


title: Additional attribute for menu link

text:
# Question
Title: Additional attribute for menu link
How I can add `itemprop="url"` for each link (`<a>`) in main menu?

So, I need to get from

```
<a href="/node/114" data-drupal-link-system-path="node/114">Test</a>

```

to

```
<a href="/node/114" data-drupal-link-system-path="node/114" itemprop="url">Test</a>

```

Is it possible to do it in preprocess? I would like not to use any module for this.

# Answer
Try

function HOOK\_link\_alter(&$variables) or function HOOK\_preprocess\_menu(&$variables)

Or just override the menu template (`menu--main.html.twig`) and replace line

`{{ link(item.title, item.url, {'class': link_classes}) }}`

with

`{{ link(item.title, item.url, item.attributes.addClass(link_classes).setAttribute('itemprop', 'url') }}`
> 0 votes

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


title: How do I clear cache?

text:
# Question
Title: How do I clear cache?
On my new site all works fine so far, except that when I try to clear cache (e.g. class cache or table cache or just flush all caches) from the UI. I sometimes get an error about exhausted memory (64M on production, 128M on test site).

Are there any alternatives to clearing cache from the UI? Can I just delete all records from the database tables starting with "cache" and obtain the same result?

# Answer
You can manually `DELETE FROM` the cache tables, though doing this with `cache_form` can result in wonky behavior with people in the middle of form submissions.

However, I suspect the problem isn't with *clearing* the cache, rather with all of the activity involved in *rebuilding* everything that gets cached.

Long term, you would be safest to

* Disable modules you don't need
* Bump up `memory_limit` for PHP

64M is likely on the low end if you have a lot of modules enabled. You should really download the Performance module, enable **Summary Logging**, run your site for a while, and see where you land on memory stats. Also note where these go when you clear caches and perform other admin functions.
> 5 votes

# Answer
Check the new CacheFlush module:

> The fine granularity of control over cache tables and function makes this module the ultimate tool to clear the Drupal caches.
>
> It ships with a predefined set of actions, but it's biggest strength lays in it's configuration, where one can build any number of custom presets to fit almost any need on both development and production environments. It is suitable for any role, starting from developers to administrators or editors. Access to each preset can be limited by permissions.
>
> It allows mixing core and contrib cache tables and/or functions with low level custom rules to always clear just what's necessary, reducing precious development time.
> 3 votes

# Answer
You may try to use drush with the following command:

```
echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v

```

It will delete/truncate all the cache tables.

It's quicker and faster than the standard `drush cc all` method and works as far as your using SQL-based caches.

If you're using memcached, please check: What method is used to clear caches in the Drupal?
> 1 votes

# Answer
If you use the Admin Menu module on your site it has a shortcut to clear your site cache in the drop down menu when you hover over the home icon in the top right.

If you then hover over the cache clearing item there are sub-items that let you clear specific parts of the drupal cache, which means you can clear just what you want (not all individual cache tables have their own link but common ones do).

Often you only need to clear select parts so this works out well, but it also help if you want to clear all because you can clear some individually and then clear all and because you have already cleared some you will find you will probably have enough memory for the clear all.
> 0 votes

# Answer
Open **settings.php (/sites/default/settings.php)** in any plain text editor. Add this line to the end of the file and save it:

```
$settings['rebuild_access'] = TRUE;

```
> 0 votes

---
Tags: 7, caching
---


# Question
Title: How do I use the computed twig element to get the value from a custom composite element?
I have created a custom composite element by cloning the example module of Drupal 8 Webforms. It has a radio button and 4 select boxes. So when clicking 'Add" button, another row is being created, and likewise a series of 10 clicks would make the page too lengthy.

I need to list out a selected element ( Product ) in another table beneath the custom composite, and hide the filled row when the 'Add' button is clicked.

Since I am relatively new to Drupal 8, I have no idea how to achieve this. I tried using computed twig to fetch the data from products table using the syntax `{{data.products.product}}` where `products` is the key of the custom composite element & `product` is the select field inside the composite element. I didn't receive any output following the above syntax.

Could anyone help me out here ?

# Answer
> 3 votes
I suppose I can answer my own question.

It didn't work because I didn't use the `delta`. For this to work, I need to do this instead

```
{% for data.products as p %}
{{ p.product }}
{% endfor %}

```

This is because we are using a custom composite element where the products are stored like

```
$products[0]['product']
$products[1][product']
...

```

I missed the array key and hence didn't get any value to the element in the custom composite.

FYI: The answer was in the 'Help' section of the module already, but couldn't really understand it well at the time.

---
Tags: 8, webforms
---


title: Import data using ECK and feeds module

text:
# Question
Title: Import data using ECK and feeds module
Is it possible to import data from CSV file and insert all in two different entities for example I have created two different entities, cadidates and exams entities, once I import data to exam entity i would like to make candidat entity updated also referencing to some field, i have tried many solution possible but in vain

# Answer
Why not make two importers that you run on the same CSV dataset? Run it first on the first imported setup and then again on the next. Each imported can be configured to create the needed content type.
> 0 votes

---
Tags: entities, feeds
---


# Question
Title: How can I add a new field from config inside hook_update_N?
I have to add taxonomy by php code. Taxonomy has to got 2 fields. I added new function to test\_taxonomy.install, and it seems to work:

```
function taxonomy_update_8805() {

    $config_path = 'modules/feature/test_taxonomy/config/update/';
    $source = new FileStorage($config_path);

    \Drupal::entityManager()->getStorage('taxonomy_vocabulary')
        ->create($source->read('taxonomy.vocabulary.regulation'))
        ->save();
}

```

Added new vocabulary to taxonomy.

Content of file:

```
langcode: pl
status: true
dependencies:
  module:
    - test_remote_vocabulary
third_party_settings:
  test_remote_vocabulary:
    is_remote: 0
name: 'Test'
vid: regulation
description: 'Test desc'
hierarchy: 0
weight: 0

```

The problematic part is when i try to add fields to the vocabulary. I created 2 files

field.storage.taxonomy\_term.field\_regulation\_test.yml

```
langcode: pl
status: true
dependencies:
  module:
    - taxonomy
    - text
id: taxonomy_term.regulation.test
field_name: test_field
entity_type: taxonomy_term
type: text_long
settings: {  }
module: text
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

```

field.field.taxonomy\_term.field\_regulation\_test.yml

```
langcode: pl
status: true
dependencies:
  config:
    - field.storage.taxonomy_term.field_regulation_test
    - taxonomy.vocabulary.regulation
id: taxonomy_term.regulation.test
field_name: test_content
entity_type: taxonomy_term
bundle: regulation
label: TEST
description: 'Tekst test'
required: true
translatable: false
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: text_long

```

But i am not sure how can i load them in update\_xxx function.

EDIT: I tried

```
    \Drupal::entityManager()->getStorage('taxonomy_term')
        ->create($source->read('field.storage.taxonomy_term.field_regulation_abo'))
        ->save();

    \Drupal::entityManager()->getStorage('taxonomy_term')
        ->create($source->read('field.field.taxonomy_term.field_regulation_abo'))
        ->save();

```

but i'm getting *Missing bundle for entity type taxonomy\_term* while trying to update module

# Answer
> 3 votes
Yes, you can't create content before the relying config has been imported. That's a classic Drupal 8 paradox which has just recently been solved by a new hook: `hook_deploy_NAME(&$sandbox)`.

Update to the latest Drush and from now on run `drush deploy` as part of your deployment routine, which replaces the old `drush updb && drush cim` routine. Then create a new file in your module: `MYMODULE.deploy.php`. In there implement `MYMODULE_deploy_NAME(&$sandbox)` where `NAME` can be any unique name (or an incrementing number as well). And use this hook to create the terms, same as in the `hook_update_N(&$sandbox)` in your question.

`drush deploy` will ensure that this hook will be picked up at the very last in the deployment routine, after the relying config has been created from configuration import.

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


# Question
Title: Is there a plain-text equivalent to the 'html' suffix for [webform_submission:values]?
I've written a Drupal 8 webform handler plugin that sends webform submission data to another server via REST. I'm trying to send all the populated fields of the form to the third-party server so that it can be viewed in the "message" field of their UI. I've tried using the `[webform_submission:values]` token with the 'html' suffix, but it comes out as a unrendered block of html code. Is there a token suffix that will format the webform values as plain text with new line characters after each value?

Here's an example of the JSON I'm sending to the 3rd party server:

```
{
   "u_user": "[webform_submission:values:user:raw]",
   "u_service": "Foo Service",
   "assignment_group": "Bar Assignment Group",
   "u_service_provider": "Baz",
   "short_description": "[webform_submission:values:subject:raw]",
   "comments": "[webform_submission:values:html]"
}

```

I need to implement this across nine different forms, some of which have conditional logic, so hard-coding every field into every handler is impractical.

Also is there a resource on the web that lists all the suffixes and prefixes for tokens?

# Answer
> 1 votes
Thanks @leymanx for the suggestion to make my own custom token. That's what I did. I created a hook\_tokens function that borrowed code from webform.tokens.inc hook\_tokens implementation. I deleted anything that didn't relate to the one token I was after, then created a \_module\_name\_token\_get\_submission\_values function that also borrowed heavily from the corresponding function in the webform module. Finally, I wrote a function that performed a series of preg\_replace substitutions on the html code that was giving the destination server problems.

Along the way, I learned a lot about custom tokens and was able to refactor my plugin to eliminate the need for a completely separate plugin through the use of a custom token. :-)

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


# Question
Title: Alphabetically ordering vocabulary terms in a translated
I have 5 English-Italian terms in a views exposed filter:

Academic | Accademico
American Studies | Studi americani
Medieval Studies | Studi medievali
Music | Musica
Reviews | Recensioni

The English language appear in alphabetical order and, as you can probably guess, the rendering order for the Italian translation is:

Accademico
Studi americani
Studi medievali
Musica
Recensioni

The desired order is:

Accademico
Musica
Recensioni
Studi americani
Studi medievali

I sort of halfway understand what is happening here. My question is whether this is something that is best remedied by hook\_form\_alter() or whether there is some obvious translation configuration I am missing in Views?

# Answer
> 0 votes
I found an old solution for Drupal 7 and just changed it until it worked. ;)

```
function MYMODULE_form_views_exposed_form_alter(&$form, $form_state) {
  if (array_key_exists('MYEXPOSEDFILTERKEY', $form)) {
    asort($form['MYEXPOSEDFILTERKEY']['#options']);
  }
}

```

It's fairly simply and works as at that point the options are already translated. So, you just need to sort the options in the respective filter.

---
Tags: views, i18n-l10n
---


title: Release cron lock

text:
# Question
Title: Release cron lock
I ran cron and aborted the execution. Now I get this message:

> Attempting to re-run cron while it is already running.

In Drupal 7, I could delete the *cron\_semaphore* variable.

What's the way to achieve the same in Drupal 8?

# Answer
> 34 votes
It's now in the `semaphore` table with the key name "cron". This can be removed via

```
drush sqlq "DELETE FROM semaphore WHERE name = 'cron';"

```

Or, if you can execute PHP in Drupal bootstrapped environment, you can run the line:

```
\Drupal::lock()->release('cron');

```

# Answer
> 9 votes
Thanks to Shawns answer..

```
drush php-eval "\Drupal::lock()->release('cron');"

```

Seemed to help!

# Answer
> 2 votes
If you can't get it to work in Drupal 8 with the suggested steps from above - perhaps you are using something like Redis and the cron lock is stored there. In this case you can progress with:

```
drush php-eval '\Drupal::service("lock")->release("all")'

```

# Answer
> 1 votes
Drupal 7 doesn't anymore uses the *cron\_semaphore* variable, but a lock. See `drupal_cron_run()`, and in particular the following lines, part of that function.

```
// Try to acquire cron lock.
if (!lock_acquire('cron', 240.0)) {
  // Omissis
}

```

```
// Release cron lock.
lock_release('cron');

```

Porting those lines to Drupal 8 is quite straight, since Drupal 8 has a service for getting and releasing a lock.

The equivalent code is in `Cron::run()`.

```
// Try to acquire cron lock.
if (!$this->lock->acquire('cron', 900.0)) {
  // Omissis
}

```

```
// Release cron lock.
$this->lock->release('cron');

```

If you need to unlock it in a host where you cannot use Drush, as it happens to me, to achieve the same from an external script that bootstraps Drupal would require code similar to the following one.

```
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Site\Settings;

chdir('..');

$autoloader = require_once 'autoload.php';

function cron_unlock_access_allowed(Request $request) {
  $account = \Drupal::service('authentication')->authenticate($request);
  if ($account) {
    \Drupal::currentUser()->setAccount($account);
  }
  return \Drupal::currentUser()->hasPermission('administer site configuration');
}

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->prepareLegacyRequest($request);
}
catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('user');

if (cron_unlock_access_allowed($request)) {
  \Drupal::lock()->release('cron');
  $status_code = 200;
}
else {
  $status_code = 403;
}
$response = new Response('', $status_code);
$response->prepare($request)->send();

```

I adapted the code of authorize.php. I changed the user permission required to run the script, which I placed in the directory containing the authorize.php file, in the cron\_cleanup.php file.

If you can run Drush, it gets easier. (See @dman's answer.)

# Answer
> 0 votes
I got to this error when the Drupal 7 installation stuck. I fixed it by using `drush php-eval "drupal_cron_cleanup()"`.

# Answer
> 0 votes
In **Drupal 8.9.x** \- I tried the below Drush commands & manually deleted the semaphore table. But, nothing is happening.

```
drush sqlq "DELETE FROM semaphore WHERE name = 'cron';"

  drush php:eval '\Drupal::lock()->release("cron");'
  drush php-eval "\Drupal::lock()->release('cron');"
  drush php-eval '\Drupal::service("lock")->release("all")'

  DELETE FROM semaphore WHERE name = 'cron';

  drush php-eval "\Drupal::lock()->acquire('cron', 10);"
  I ran first a couple of times and then I did
  drush php-eval "\Drupal::lock()->release('cron');"

```

Finally I got the Solution. Run individual cron jobs with Drush. I ran the command one by one. then it works.

```
drush php-eval "webform_cron();"
drush php-eval "update_cron();"
drush php-eval "system_cron();"
drush php-eval "statistics_cron();"
drush php-eval "node_cron();"
drush php-eval "locale_cron();"
drush php-eval "history_cron();"
drush php-eval "file_cron();"
drush php-eval "field_cron();"
drush php-eval "dblog_cron();"
drush php-eval "comment_cron();

```

---
Tags: 8, cron
---