title: Perform math calculation in views

text:
# Question
Title: Perform math calculation in views
On Drupal 8 site, I have a exact copy of the below excel example table made with views but without the **yellow cell** yet.

The view is displaying one content type: **Client** where all the below fields are available:

* Date
* Client Name
* Client ID
* Amount ($)

Now, as you can see, the yellow cell is displaying the **total SUM** of all **amount ($)** rows. which basically is: 15+29+97+115+45+67+23+11+5+91+44 = 542$

How can i achieve this exact calculation in my view ?

I have tried to enable the **Use aggregation** option under the advanced section on my view, but it seems it doesn't do what i am asking for!

any help please ?

Note: I believe the use **Use aggregation** option doesn't add a row at the bottom of the table calculating the sum of all above rows and therefore this question Making a colums total (SUM) with Views is not a possible duplicate of this one.

**UPDATE #1**

After following the answer of @Stef Van Looveren, I am encountering a new error:

```
InvalidArgumentException: Field field_money_amount is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 587 of /home/####/public_html/#####/web/core/lib/Drupal/Core/Entity/ContentEntityBase.php)

```

Knowing that: **field\_money\_amount** is the id of the field taken from the content type being used inside the view.

**Complete code in the .module file:**

```
<?php

use Drupal\views\ViewExecutable;

function my_module_views_pre_render(ViewExecutable $view){
  if ($view->id() == "view_id" && $view->current_display == 'display_id') {
    $total = 0;
    foreach ($view->result as $value) {
      $number = $value->_entity->get('field_money_amount')->value;
      $total += $number;
    }
    $view->attachment_after = [
      '#markup' => '<table class="table cols-0"><tr><td>Total:</td><td>'.$total.'</td></tr></table>',
      '#allowed_tags' => ['table','tr','td']
    ];
  }

```

}

# Answer
> 1 votes
After further search, I have found Views Aggregator module to do exactly what I need to do.

I am willing to accept @Stef Van Looveren answer especially where i prefer not to have to add a new module to my site but for some reason isn't working for me, unless somebody can help fix the above provided code.

# Answer
> 1 votes
Interesting question and a typical use case. In a custom module, do the following:

```
use Drupal\views\ViewExecutable;

function helper_views_pre_render(ViewExecutable $view){
  if ($view->id() == "numbers" && $view->current_display == 'page_1') {
    $total = 0;
    foreach ($view->result as $value) {
      $number = $value->_entity->get('field_number')->value;
      $total += $number;
    }
    $view->attachment_after = [
      '#markup' => '<table class="table cols-0"><tr><td>Total:</td><td>'.$total.'</td></tr></table>',
      '#allowed_tags' => ['table','tr','td']
    ];
  }
}

```

Change the names according to your view name & field names. I'm sure you get the point: you add a table below with the total result.

I did a test and it gave me the following result:

---
Tags: views, 8
---


# Question
Title: How to detect the ip address of the device itself?
Using PHP and Drupal 8, I am trying to detect the ip address of the device itself and not the ip address of the router where the device is connected through the internet.

```
$DeviceIP = \Drupal::request()->getClientIp();

```

the above will return the ip address of the router where the device is connected, but what I am really trying to get is the unique ip address of the device hardware.

So say I have two mobile phones (Mobile A & Mobile B) connected to the same WiFi network, if I ran the above code on both mobiles, both will return the same IP Address... However, I am expecting Mobile A to return an IP Address which is unique and DIFFERENT from the one returned by Mobile B.

In General, what I am trying to achieve is the ability to know **if a registered user on my site is using more than one device to login to his account.**

**Update 1:**

I am not really interested to get the ip address of the mobile hardware but more interested in a method to distinguish between two different mobiles used by the same user to access his own account on my site...

Getting the Device Name or Device Serial Number or whatever information which will be unique for the device will get the job done.

How do you think this could be done ?

# Answer
I ended up using:

```
// Get all information available about the active device from the "HTTP request headers".
$currentdevicedata = $_SERVER['HTTP_USER_AGENT'];

```

I know this is not the best approach to follow but at least for now it can do the job for me.
> 1 votes

# Answer
You cannot. User routers mask IPs, see the definition of the NAT protocol that most home routers use: https://en.wikipedia.org/wiki/Network\_address\_translation

You could try to do something based on HTTP Headers (User-Agent), using cookies or the session itself, but none of them will be really reliable.
> 3 votes

---
Tags: 8, users
---


# Question
Title: Drupal 8 CKeditor behaves LTR in an RTL site
I've installed Drupal 8.0.2 in a **standard** installation process and in **English**.

I later changed The site's default language to Hebrew (Which is an RTL language) and my content type is now setted to the site's default language - Hebrew. I even determined my user's administration account, called "admin", to Hebrew (a new Drupal 8 feature that let's you pick a specific front-end language to a certain user).

After that I've organized the CKeditor full-profile edit-bar in an RTL manner at it's configuration page (and flushed all caches afterwards):

---

## You saw - I did everything by the book, and yet:

I encounter two issues that comprise my whole problem:

**1.** The CKeditor edit-bar appears the opposite from how I arranged it (as can be seen one image up).

**2.** CKeditor input area typing cursor starts in the left instead of the right (I could easily manually flip the Edit-bar but the cursor will still appear in the left).

When I installed a test site in Hebrew **from the start** (instead of installing first in English and then add Hebrew and make it default), I didn't encounter that problem, and the edit-bar was RTL. I have no clue how to explain this! Maybe you can!

# Answer
> 13 votes
The default CKEditor text language direction is LTR. To change it to RTL, you can try setting the JS config setting:

```
config.contentsLangDirection = 'rtl';

```

Reference: http://docs.cksource.com/ckeditor\_api/symbols/CKEDITOR.config.html#.contentsLangDirection

In D7, there was a config textarea that can be set:

In D8, you can set the CKEditor config settings in:

`hook_editor_js_settings_alter`

Something like:

```
/**
 * Implements hook_editor_js_settings_alter
 */
function MYMODULE_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats'][$name]['editorSettings']['contentsLangDirection'] = 'rtl';
  }
}

```

More info on creating Drupal 8 modules here: https://www.drupal.org/developing/modules/8

You can also set the config in JS, for example your theme

Something like:

```
(function ($, Drupal) {
  Drupal.behaviors.customCKEditorConfig = {
    attach: function (context, settings) {
      if (typeof CKEDITOR !== "undefined") {
        CKEDITOR.config.contentsLangDirection = 'rtl';
      }
    }
  }
})(jQuery, Drupal);

```

More info on adding theme assets here: https://www.drupal.org/theme-guide/8/assets

For your other question on the toolbar button ordering. That appears to work, just make sure you set the toolbar button order on all the "Text formats" that you want to use it with (e.g "Basic HTML", "Restricted HTML" and "Full HTML") in the CKEditor admin settings.

# Answer
> 2 votes
Also CKEditor BiDi Buttons module provides the bi directional text flow buttons, RTL and LTR.

> Integrates the CKEditor BiDi plugin with CKEditor for Drupal 8. This plugin provides the bi directional text flow buttons, RTL and LTR .
>
> The CKEditor BiDi plugin makes it possible to change the text direction for an HTML block-level elements like paragraphs and lists. This ability is essential for authoring content in languages that are written Right to Left like those with Arabic and , Hebrew writing systems.

---
Tags: 8, wysiwyg
---


# Question
Title: No install link for sub theme of sub theme
In my D8 site I have Magazine Lite, a sub theme of Classy. Magazine Lite is installed.

In web/themes/custom I have a theme installed that in its .info.yml file names Magazine Lite as its base theme.

On the Appearance tab, instead of an install link is the message:

> This theme requires the base theme Magazine Lite to operate correctly

In what way does it require the base theme beyond the base theme being present and installed?

# Answer
> 0 votes
Copied the base theme's info file and changed 'name' to 'base theme'. But the base theme entry needs to be the machine name of the theme, whereas the name is a descriptive name.

---
Tags: theming
---


# Question
Title: How can I get translated path aliases for a custom language switcher?
The Drupal 8 standard "Language switcher" dropdown does not give me what I need. What I need is to break everything apart into groups and subgroups, in a div, and have custom text for each Language, some of which are custom languages.

As ugly as my code is, I'm almost there, but I'm getting a node, instead of the actual page.

if I click on U.S. Spanish, I get: http://website.com/es-us/node/123 but I want: http://website.com/es-us/contactenos

if I click on U.S. English, I get http://website.com/en-us/node/123 but I want: http://website.com/en-us/contact-us

(note the difference in URL alias, by language)

I've found this page, and used it as my starting point: https://www.drupal.org/docs/8/multilingual/enable-language-negotiation

As I attempt to understand how I might do it, I have in my themename.theme:

```
<?php

/**
* Implements hook_preprocess_page().
*
* @param $vars
*/
function themename_preprocess_page(&$vars) {
 $current_path = \Drupal::service('path.current')->getPath();
// not used yet...
$language = $vars['language']->getId();

  $fr_ca = '';
  $en_ca = '';
  $en_us = '';
  $es_us = '';
  $en_gb = '';

  $vars['en_us'] = '/en-us' . $current_path;
  $vars['es_us'] = '/es-us' . $current_path;
  $vars['en_ca'] = '/en-ca' . $current_path;
  $vars['fr_ca'] = '/fr-ca' . $current_path;
  $vars['en_gb'] = '/en-gb' . $current_path;
 }

```

Then I was going to hardcode into the page.tpl.twig (for now, while I learn) something similar to:

```
<div class="region">
    <h1>Americas</h1>
    <div class="country">
      <h2>U.S.</h2>
      <a class="lang-switcher" href="{{ en_us }}">English</a>
      <a class="lang-switcher" href="{{ es_us }}">Español</a>
     </div>
     <div class="country">
       <h2>Canada</h2>
      <a class="lang-switcher" href="{{ en_ca }}">English</a>
      <a class="lang-switcher" href="{{ fr_ca }}">Francais</a>
     </div>
</div>

<div class="region">
   <h1>Europe</h1>
  <div class="country">
    <!-- ETCETERA -->
  </div>
</div>

```

I'm sure there are better ways to do this for a more experienced coder. But for now, I'm hoping I can get the alias in there.

I can't use **"$current\_uri = \Drupal::request()-\>getRequestUri();"**

Because that is different for each page... For example, "contactenos" in Spanish versus "contact-us" in English

# Answer
> 0 votes
Seems you can do what you want with `Url` options and a language object like following.

```
// Get all activated languages.
$languages = \Drupal::languageManager()->getLanguages();

foreach ($languages as $language) {

  // Get the current URL in each language.
  $url = \Drupal\Core\Url::fromRoute('<current>')
    ->setOption('language', $language)->toString();

  // And add it to a custom array.
  $variables['my_langswitch'][$language->getId()] = $url;
}

```

But as I already said in the comments to your question, this should actually be put in a custom block. And since it's all just about a little bit of changing markup I'd even go for JavaScript here and stick to the built-in language switcher. Also as I'm not sure how above works with caching enabled.

---

If you prefer getting the paths one-by-one, get a language object first and then use that to get the path alias.

```
// Get Swedish language
if ($sv_language = \Drupal::languageManager()->getLanguage('sv')) {

  // Get Swedish URL.
  $sv_url = \Drupal\Core\Url::fromRoute('<current>')
    ->setOption('language', $sv_language)->toString();

  // Add it as custom variable.
  $variables['sv_url'] = $sv_url;
}

```

---
Tags: 8, i18n-l10n, path-aliases
---


title: Entity without translation

text:
# Question
Title: Entity without translation
I want to make entity in Drupal 8 called `cash` that store only numeric value (integer or float). I think, that entity not need translation. Is it possible for us to create custom entity without language/translation?

# Answer
> 0 votes
@IgorTengab An entity in Drupal 8 needs translation to be enabled to be translatable

For example by going to `/admin/structure/types/manage/ENTITYNAME` \> language settings \> enable translation

For more info look here

But for your purpose perhaps a light-weight alternative would be to create a custom entity https://www.drupal.org/docs/8/api/entity-api/create-a-custom-content-entity

---
Tags: entities, i18n-l10n
---


# Question
Title: Create a view to list all contents that uses media through any entity reference field
I know it is possible to create view to list all content that is using media through a **particular** entity reference field.

Is it possible to create a view to to list all content that is using media thought **any** entity reference field?

# Answer
> 0 votes
Mostly yes, by adding relationships to a view. The drawback is that is not done automatically: you manually have to add all entities/fields that possibly can refenrence a media entity. Create a view showing media entities. Then add the related tables and filter criterias *"related/foreign field referencing media -- is not empty"*

I'd not recommend the *"File usage"* relation and its *"Use count"* field. It doesn't seem to count correctly in my projects.

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


title: Difference between $bundle and bundle()

text:
# Question
Title: Difference between $bundle and bundle()
Background information: I'm trying to manipulate the available options of a list type text field, depending on the host bundle:

```
function wtbase_options_list_alter(array &$options, array $context) {
  $fieldDefinition = $context['fieldDefinition'];
  if ($fieldDefinition->getName() == 'field_aos_cell' && $fieldDefinition->bundle() != 'link') {
    foreach ($options as $key => $value) {
      if ($key == 'link-horizontally-opposing') {
        unset($options[$key]);
      }
    }
  }
}

```

The `$fieldDefinition->bundle` part is really confusing. There seems to be a variable `$fieldDefinition->bundle` (containing the expected bundle name `link`) and a function `$fieldDefinition->bundle()` (containing `field_config`). But I can't access the variable `bundle`, because this crashed with `Cannot access protected property Drupal\field\Entity\FieldConfig::$bundle`.

After some digging I found FieldConfigBase::getTargetBundle(), which did return the expected result and did not crash (yet).

So this leads to two questions:

What is the difference between `$bundle`, `bundle()` and `getTargetBundle()` and which one I'm supposed to use? I'd prefer using variables, because they are visible in Xdebug, while functions are not.

And in a more general point of view, are there some guidelines when to use functions and when to use variables? In the same example as above Xdebug printed the same weird results for e.g. `entity_type` vs `entityTypeId` vs `getEntityType()` vs `getEntityTypeId()`.

--

Update, clarification for question 1:

I know the technical difference between a member property and a member function. But I'm deeply confused that a property `$bundle` and a function `bundle()` of the exact same name are returning values from a completely different entities/context. In my example `$fieldDefinition->bundle` returns a Paragraph bundle name `link`, while `$fieldDefinition->bundle()` seems to return the bundle name from FieldConfig. I know this is technically possible... but why would anyone write code like this? I've not yet experienced this behavior anywhere else in Drupal core, usually `$entity->bundle` and `$entity->bundle()` return the same result.

# Answer
> 3 votes
`bundle` is the property on the object. It's where the value is stored. Properties can be assigned one of three ways:

* `public`: these properties can be directly set or read on the object. Example:

```
$object->key = 'value';
$value = $object->key;

```
* `private`: These can only be accessed by methods (functions) of the class itself. Nothing else can access it. For example, this will throw an error:

```
$value = $object->key;

```

Whereas this would be allowed:

```
class Example {
  private $key;

  function getPrivateValue() {
    return $this->key;
  }
}

$value = $object->getPrivateValue();

```

`$key` cannot be accessed outside of the class, since it is private. This can be used to enforce rules on the types of data to be stored in the property. Checks can be run to ensure it's an allowed data type.
* `protected`: These are like private properties, however if a class extends the class, the extended class can access the property. If the property is private, extended classes cannot access it.

One thing for you to understand is that `$node->bundle` and `$node->bundle()` are not the same things. The first is a property, the other is a method. This should help understand, as a (non-real) example:

```
class Node {
  protected $bundle;

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

```

The above class has the property `$bundle`, and the method (function) `bundle()`. The method returns the value stored in the property.

Look at the error you are seeing: `Cannot access protected property Drupal\field\Entity\FieldConfig::$bundle`. This is because you are trying to access the `$bundle` property, but it is protected, meaning you cannot access it from outside the class.

To get the bundle of a node, you need to call the `bundle()` method on it, which will give you the bundle type. This is the answer to your question about which to use.

> And in a more general point of view, are there some guidelines when to use functions and when to use variables?

It's generally thought to be a best practice to not provide direct access to properties on objects, and instead create setter and getter methods (functions) on objects to set and retrieve the property values. That way you can say, enforce a pattern:

```
class Example {

  protected $username

  public function setUsername($username) {
    if (!is_string($username)) {
      throw new \Exception('Username must be a string');
    }
    elseif (!preg_match('/^[a-zA-Z0-9_-]{3,12}$/', $username)) {
      throw new \Exception('Username must be between 3 and 12 characters, and may contain only alphanumerics, underscores or hyphens');
    }

    $this->username = $username;
  }

  public function getUsername() {
    return $this->username;
  }
}

```

The above enforces that username is both a string, and is the right length and only contains allowed characters.

Edit: Additional comment from Leigh:

another reason to avoid accessing the property directly is when you have multiple values. e.g. if you have a field "my\_field" on a node which has multiple values if you use $node-\>my\_field-\>value you'll only get 1 value returned

---
Tags: entities, debugging
---


# Question
Title: Sorting view results using contextual filters on Drupal 8
I created a views that filter nodes according taxonomy terms passed through contextual filters.

* Node 1: term1, term2, term3
* Node 2: term1, term6
* Node 3: term1, term7

Everything is working good, expect i would like to display the number of term tid found in the node.

When i use the parameters term1+term7 (in contextual filters), i would like a result like this :

* Node title 1: match 1
* Node title 2: match 1
* Node title 3: match 2

and then sort results by the matching terms.

How can i make it work with Views 3 in Drupal 8?

Many thanks.

# Answer
There are two parts to this question: getting the Contextual filtering to reduce the results to only the term IDs you specify in the URL, and using Aggregation for counting and sorting the results according to that count.

## Contextual filter for Taxonomy term ID

1. Create your Views list of nodes with the Taxonomy reference field showing the tags, and configure that field to show all values in the same row
2. Add the Contextual filter for your Taxonomy term field or for the Field `Has taxonomy term ID` and configure it:
`When the filter value is NOT available`
**Provide default value**
**Taxonomy term ID from URL**
**Load default filter from node page, that's good for related taxonomy blocks**
**Filter to items that share any term**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term ID**
**\[your vocabulary\]**
**One or more IDs separated by , or +**
`More`
**Allow multiple values**

Test this by entering the term ID (number) into the Views Preview field. You should see the results reduce to show nodes tagged with that term. Also test for more than one term, enter, for example, `3+5` to show nodes that are tagged with *either* terms 3 *or* 5, or `3,5` to show nodes tagged with *both* terms 3 *and* 5.

If you want to use term names instead of term ID numbers, then instead of using the taxonomy term reference field as the Contextual filter, you'll have to first add a Relationship for that field, then you will have the Taxonomy `Name` Contextual filter available. You configure it similarly as above, be careful about case options. You test it by entering the term names into Preview: `firstTerm,secondTerm`.

## Count with Aggregation

1. Turn Aggregation on in the third column of Views settings
2. Click on Aggregation settings for the Taxonomy field (from step 1. above) and change the Aggregation type to Count DISTINCT.

This field will now show the count how many terms are shared.
3. Add the Sort criteria for your Taxonomy terms field, and set its Aggregation to `Count DISTINCT` and you'll probably want to sort descending. You should have no other sorting added except this. You will see the nodes sorted by the number of tags shared with the contextual filter.

Test this the same way as above, entering term IDs, or term names if that's what you're using.

In the end you'll have to test in a real page to check that the Contextual filter has been configured properly. Build and test in steps, don't first build everything and only test because if there's something wrong it will be more difficult to figure out what and you'll have to start from scratch step by step anyway.
> 1 votes

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


# Question
Title: Cannot get role information in twig file
I cannot seem to get the role of the current user in my twig template. I have tried the following:

```
{{ user.getRoles }}

{{ user.hasRole('content_administrator') }}

```

and neither return anything.

Notes:

* I use a subtheme of radix.
* I want to include stuff in the theme if the user has a certain role. Specifically, I have regular viewers and a content admin, and the content admin shall see extra things. I created a view called /revisionhistory which has a contextual link, and shows revisions. The theme should generate a link to /revisionhistory/{{node.id}} if the user has the administer\_content role.

# Answer
> 2 votes
Displaying content if the user has a certain role:

```
{% if 'content_administrator' in user.getroles %}
  <p>Only displayed for the role Content Administrator</p>
{% endif %}

```

More info: Restrict content to a user role in a template file

# Answer
> 1 votes
The best practice for security in Drupal development is not to use roles to determine access but to use permissions. So instead of user.hasRole(). You should use `{{ user.hasPermission(permission) }}`. This means the code does not have to be modified as roles are added / changed.

As in the comments, the core permission name for managing nodes is not administer\_content but is 'administer nodes'. You need to make sure you are using the correct permission 'label'. However, finding permission names in Drupal is harder than it should be IMHO.

A couple of ways to do this are:

Use the `drush role-list` command. This lists all roles and their permission labels. You can specify a specific role to just list that one.

Alternatively, you can inspect the checkboxes in the permissions page. The permission label is buried in the name attribute in the format role\[permission\], e.g. anonymous\[administer nodes\].

Note that this will work with all permissions core and (custom) module added.

---
Tags: theming
---


# Question
Title: Embed a single field from an existing content in ckeditor
I managed to embed the full content or teaser using Entity Embed module in Drupal 8 but, is it possible to embed a single field which contains text or html without coding

# Answer
> 1 votes
You can accomplish this using tokens. The exact token used will vary based on your configuration, but if you wanted to embed a the current user's first name, you could use something like \[current-user:field\_first\_name\]. Here's one article about them. https://www.ostraining.com/blog/drupal/tokens-in-drupal-fields/

---
Tags: 8
---


# Question
Title: Batch API error: ResponseText: {"errors":[{"message":"Not acceptable format: json"}]}
When running a batch process on Drupal 8, the following error is returned:

```
ResponseText: {"errors":[{"message":"Not acceptable format: json"}]}

```

The HTTP response is HTTP POST / 406

I can see the route is defined ok for the batch callback with the JSON support there:

```
select * from router where name like '%system.batch_page%' \G;
*************************** 1. row ***************************
           name: system.batch_page.html
           path: /batch
pattern_outline: /batch
            fit: 1
          route: C:31:"Symfony\Component\Routing\Route":970:{a:9:{s:4:"path";s:6:"/batch";s:4:"host";s:0:"";s:8:"defaults";a:2:{s:11:"_controller";s:52:"\Drupal\system\Controller\BatchController::batchPage";s:15:"_title_callback";s:57:"\Drupal\system\Controller\BatchController::batchPageTitle";}s:12:"requirements";a:2:{s:7:"_access";s:4:"TRUE";s:7:"_format";s:4:"html";}s:7:"options";a:4:{s:14:"compiler_class";s:34:"\Drupal\Core\Routing\RouteCompiler";s:12:"_admin_route";b:1;s:12:"_no_big_pipe";b:1;s:14:"_access_checks";a:1:{i:0;s:20:"access_check.default";}}s:7:"schemes";a:0:{}s:7:"methods";a:2:{i:0;s:3:"GET";i:1;s:4:"POST";}s:9:"condition";s:0:"";s:8:"compiled";C:33:"Drupal\Core\Routing\CompiledRoute":312:{a:11:{s:4:"vars";a:0:{}s:11:"path_prefix";s:0:"";s:10:"path_regex";s:12:"#^/batch$#sD";s:11:"path_tokens";a:1:{i:0;a:2:{i:0;s:4:"text";i:1;s:6:"/batch";}}s:9:"path_vars";a:0:{}s:10:"host_regex";N;s:11:"host_tokens";a:0:{}s:9:"host_vars";a:0:{}s:3:"fit";i:1;s:14:"patternOutline";s:6:"/batch";s:8:"numParts";i:1;}}}}
   number_parts: 1
*************************** 2. row ***************************
           name: system.batch_page.json
           path: /batch
pattern_outline: /batch
            fit: 1
          route: C:31:"Symfony\Component\Routing\Route":858:{a:9:{s:4:"path";s:6:"/batch";s:4:"host";s:0:"";s:8:"defaults";a:1:{s:11:"_controller";s:52:"\Drupal\system\Controller\BatchController::batchPage";}s:12:"requirements";a:2:{s:7:"_access";s:4:"TRUE";s:7:"_format";s:4:"json";}s:7:"options";a:3:{s:14:"compiler_class";s:34:"\Drupal\Core\Routing\RouteCompiler";s:12:"_admin_route";b:1;s:14:"_access_checks";a:1:{i:0;s:20:"access_check.default";}}s:7:"schemes";a:0:{}s:7:"methods";a:2:{i:0;s:3:"GET";i:1;s:4:"POST";}s:9:"condition";s:0:"";s:8:"compiled";C:33:"Drupal\Core\Routing\CompiledRoute":312:{a:11:{s:4:"vars";a:0:{}s:11:"path_prefix";s:0:"";s:10:"path_regex";s:12:"#^/batch$#sD";s:11:"path_tokens";a:1:{i:0;a:2:{i:0;s:4:"text";i:1;s:6:"/batch";}}s:9:"path_vars";a:0:{}s:10:"host_regex";N;s:11:"host_tokens";a:0:{}s:9:"host_vars";a:0:{}s:3:"fit";i:1;s:14:"patternOutline";s:6:"/batch";s:8:"numParts";i:1;}}}}
   number_parts: 1
2 rows in set (0.00 sec)

```

Just wondering if anyone else has encountered this error for the Batch API processing and may have some suggestions on it.

# Answer
In our case, we had to turn off Cloudflare's `Query String Sort` option. See here --\> https://support.acquia.com/hc/en-us/articles/360022037774-Resolving-Not-acceptable-format-json-error-HTTP-code-406-in-batch-operations

Here is the drupal issue too --\> https://www.drupal.org/project/drupal/issues/2879023
> 2 votes

---
Tags: 8, batch-operations
---


# Question
Title: hook_update_N() for more than 100 updates or 10 major releases
The documentation for hook\_update\_N() says the following:

> Implementations of hook\_update\_N() are named (module name)*update*(number). The numbers are composed of three parts:
>
> * 1 digit for Drupal core compatibility.
> * 1 digit for your module's major release version (e.g., is this the 7.x-1.\* (1) or 7.x-2.\* (2) series of your module?). This digit should be 0 for initial porting of your module to a new Drupal core API.
> * 2 digits for sequential counting, starting with 00.

These are hypothetical questions:

What happens if you get to something like 7299? Are you required to release a major version update next even if you don't implement the hook, or if you do?

What happens if you have a lot of branches or major releases and get to something like 8900 and want to release a new one for that version of Drupal... 8(10)00? I know some modules go from 7.x-3.x to 8.x-4.x, so this could potentially happen if they continue in that way.

# Answer
> 0 votes
The one time I dealt with this, I just kept on going. After 7199, I moved to 71100, then 71101 etc. It wasn't a problem (Drupal 7).

---
Tags: hooks
---


# Question
Title: For each image uploaded in a node: get the url
I'm begining with Drupal 8 and I want to get the url of the photos in the content I create to display them.
The context is : a photograph upload pictures for a customer. This customer can see it on a page. To get this data in common I created a content for my shooting with an id.
What i did is :

```
$photos = $shooting->field_shooting_photos->target_id;

```

This allow me to get the id of every pictures uploaded. Now I want to do a foreach on $photos in my .module that will return every url in an array.
Then I will use this array in my Twig and do a foreach on it too to return every photos.
I just can't figure out how to do, I think I will have to use something like that

```
$path = $photo_id->getFileUri();

```

but I can't figure out the syntax to get it into an array.
Thank you for your help!
**Solution :**
Here is what I did in case it can help someone :

```
$photosTest = $shooting->field_shooting_photos->referencedEntities();

$photoUrls = [];

foreach($photosTest as $media) {
  $photoUrls[] =
  $photoUrls[] = [
      'render' => [
         '#theme' => 'image_style',
         '#style_name' => 'medium',
         '#uri' => $media->field_media_image->entity->getFileUri()
       ],
       'href' => $media->field_media_image->entity->getFileUri(),
     ];
}

```

In my Twig file I render the array :

```
<div>
 {% for photo in photos %}
    <a href="{{ file_url(photo.href) }}">{{ photo.render }}</a>
 {% endfor %}
</div>

```

# Answer
Giving field\_shooting\_photos is a multi valued field of Files, this is how to generate your array of URI :

```
$photoUrls = [];
foreach($shooting->field_shooting_photos->referencedEntities() as $image) {
    $photoUrls[] = $image->getFileUri();
}

```

For media image :

```
$photoUrls = [];
foreach($shooting->field_shooting_photos->referencedEntities() as $media) {
    $photoUrls[] = $media->field_media_image->entity->getFileUri();
}

```

Note this will give you the File\_id of the first image in the entite file reference list :

```
$shooting->field_shooting_photos->target_id;

```

NB : Best way is probably to generate render array or use built-in drupal themes, is none fit your needs, your may also generate a custom field formatter.
> 1 votes

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


# Question
Title: Migration with unique index across multiple fields
It is the first time I'm using the migrate module and I want to import some nodes from a JSON file and to specify a unique key that has two distinct fields. I.e so that the row is not imported or it's updated when the combination of those two fields values already exists in the database

```
id: import_json_entities
label: "JSON Entities"
migration_group: import_json_group

destination:
  plugin: entity:node

migration_dependencies: { }

dependencies:
  enforced:
    module:
      - my_module

source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json

  urls:
    - 'public://entitities.json'

  item_selector: Schema

  ids:
    - name
    - version

  fields:
    -
      name: name
      label: 'Name'
      selector: Name
    -
      name: version
      label: 'Version'
      selector: Version

process:
  type:
    plugin: default_value
    default_value: service

  title: name
  uid:
    plugin: default_value
    default_value: 1

  field_version: version

```

It works if I only leave "name" in the list of ids, but it does not import anything if I specify both "name" and "version" as id.

What I want is something similar with what you achieve in MySQL with:

```
ALTER TABLE `entities` ADD UNIQUE `unique_index`(`name`, `version`);

```

# Answer
> 1 votes
This is what I'm using in one of my imports:

```
source:
  ids:
    event_id:
      type: integer
    date_iso:
      type: string

```

I'm explicitly specifying the ID column type using `type: integer` or `type: string`.

# Answer
> 1 votes
Ok, it seems that the problem was not with the syntax, but with the fact that the table created in the database for my migration was corrupted (it had the wrong unique index). I had to manually delete migrate\_map\_import\_json\_entities and then reinstall the module (for some reason, uninstalling it didn't automatically deleted the table). Now it seems to work.

---
Tags: 8, migrations
---


# Question
Title: Render array only working with numeric keys
I have a FieldFormatter that outputs a DIV, a table and attaches a JS library.

Normally in Drupal (e.g. Form API) it's possible to label the render array keys however you like? Weirdly in this case, only numbering them seems to work.

If it's a typo, I'm not spotting it, and there are no errors in the log.

Are there differences in how FieldFormatter rendering works?

**Working numeric keys:**

```
  public function viewElements(FieldItemListInterface $items, $langcode) {

    // various logic ...

    $build = [];

    $build[0] = [
      // placeholder div for the YouTube player
      '#type' => 'container',
      '#attributes' => [
        'id' => ['youtube-timecode-player'],
      ],
    ];

    // various logic ...

    // attach our timecode.js javascript make the video ID available
    $build[0]['#attached']['library'][] = 'mymodule/youtube_timecode';
    $build[0]['#attached']['drupalSettings']['mymodule']['video_id'] = $video_id;

    $build[1] = [
      '#type' => 'table',
      '#caption' => $this->t('Questions'),
      '#header' => [$this->t('Time'), $this->t('Question')],
      '#rows' => $timecodes
    ];

    return $build;
  }

```

**Non-working text keys (no output and no errors):**

(I've changed `0` to `video` and `1` to `timecode_list`)

```
public function viewElements(FieldItemListInterface $items, $langcode) {

    // various logic ...

    $build = [];

    $build['video'] = [
        // placeholder div for the YouTube player
        '#type' => 'container',
        '#attributes' => [
            'id' => ['youtube-timecode-player'],
        ],
    ];

    // various logic ...

    // attach our timecode.js javascript make the video ID available
    $build['video']['#attached']['library'][] = 'mymodule/youtube_timecode';
    $build['video']['#attached']['drupalSettings']['mymodule']['video_id'] = $video_id;

    $build['timecode_list'] = [
        '#type' => 'table',
        '#caption' => $this->t('Questions'),
        '#header' => [$this->t('Time'), $this->t('Question')],
        '#rows' => $timecodes
    ];

    return $build;

}

```

# Answer
> 3 votes
The return value of FormatterInterface::viewElements is defined as:

> **Return value**
>
> *array* A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

The theming layer can't handle other arrays for field values, see How to print all values of a multi-value field, except the first?

---
Tags: 8
---


# Question
Title: How to update custom paragaph which is added to User Profile?
I have a requirement to create/update a paragraph which is added as a custom field in USER profile. After surfing here, i got how to update a paragraph which is connected to node. But I am not able figure out for User profile. Any help will be appreciated. I used below code for saving the paragraph, but how it will linked to `$user->save();` ?

```
$paragraph = Paragraph::create([
      'type' => 'mmodule_paragraph',
      'field_employee_id' => 'Field value',
      'field_location' => 'Field value',
      'field_name' => 'Field value',
      'field_segment' => 'Field value',
    ]);
    $paragraph->save();

```

# Answer
Don't save the paragraph, add it to the user field and then save it together with the user:

```
$paragraph = Paragraph::create([
  'type' => 'mmodule_paragraph',
  'field_employee_id' => 'Field value',
  'field_location' => 'Field value',
  'field_name' => 'Field value',
  'field_segment' => 'Field value',
]);
$user->field_paragraph[] = $paragraph;
$user->save();

```

In case you want to replace the field content overwrite the entire field array:

```
$user->field_paragraph = [['entity' => $paragraph]];

```
> 4 votes

---
Tags: 8, users, updating, paragraphs
---


title: How to remove the size of an input?

text:
# Question
Title: How to remove the size of an input?
I create a very simple theme with "stable" parent theme.

So far so good.

The size of input is indicated in HTML, and it bothers me a lot for the layout of my forms.

This is an example.

```
<input (...) value="" size="60" maxlength="128">

```

I have of course looked in the stable theme, but in the template input.html.twig, it is only indicated `<input{{ attributes }} />{{ children }}`.

I would like to remove the size indication to fully manage my layout in CSS.

How can I achieve this?

# Answer
This question is quite old but here a solution

```
/**
 * Implements template_preprocess_form_element().
 */
function mytheme_preprocess_input(&$variables) {
  // remove size
  unset($variables['element']['#size'], $variables['element']['#attributes']['size'], $variables['attributes']['size']);
}

```
> 3 votes

# Answer
You can change or remove size of field by changing `$form['field_name']['widget'][0]['value']['#size']`

For example you can set the size of the title field to `120` using:

```
$form['title']['widget'][0]['value']['#size'] = 120;

```

Use Devel to print the `$form` to get the exacte location of the `#size`.

**UPDATE**
To remove the size set it to `NULL` try with

```
$form['title']['widget'][0]['value']['#size'] = NULL;

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to remove blocks as a Context reaction?
I must be missing something here, I hope someone can shed some light on this, but I can't see how to remove blocks when using the Context Reaction - Blocks on the context configuration screen.

I can add blocks using the checkboxes and the add buttons, and I can remove them once added but how do you remove blocks that are already being rendered?

thanks

Jack

# Answer
> 2 votes
@jack, you can't remove blocks that are already being rendered, but you can show them only on specific pages, which will effectively do what you need.

For example, I had a footer contact form which I want to show on all pages on the site except on the contact page. I used the following steps:

1. Added a new context called "except\_contact".
2. On the new context editing screen, added a path condition with the path negation operator, "~" (which is specific to contexts): "~contact/info" will activate the context in all paths except contact/info.
3. Added the global contact block to the footer region.

This does what you need - show the block in all pages except the designated page where the block is effectively removed.

# Answer
> 1 votes
If Blocks are being rendered, it's probably because they were enabled in

```
example.com/admin/structure/block
```

I usually disable all blocks there which only leaves me with the Main Content. If you need certain blocks across your website, you can create a site wide Context.

# Answer
> 0 votes
There's a little X on the right side of the block-item in the regions list of context.

Oh, maybe you mean something different. What do you mean exactly with:

> how do you remove blocks that are already being rendered?

Do you think about an "reaction" to remove blocks? In this case you'd have to create another condition and just do not add the particular block.

# Answer
> 0 votes
Create a custom module and use this code. Make sure to comment out kpr() functions ... they are only here to help inspect what blocks appear and conditions in the current node.

```
function mymodule_block_list_alter(&$blocks) {
  foreach($blocks as $bid){
    kpr($bid); // Enable module Devel - identify the block you want to remove
    switch ($bid->delta) {
      case 'block_to_remove': // this is the specific block's delta
        $thisbid = $bid->bid;
        $node = menu_get_object();
        kpr($node);  // Enable module Devel and view what node condition you wish to test for
        // test for the node condition
        $node->field_condition['und'][0]['value']) === "contextual condition" ? $condition = TRUE : $condition = FALSE ;
        // remove block from list if condition is true
        if(!$condition){ unset($blocks[$thisbid]); }
      break;
    }
  }
}

```

---
Tags: blocks, 7
---


title: Change path of uploaded files in zip

text:
# Question
Title: Change path of uploaded files in zip
I've a form that allow the customer to download every photos that a photograph uploaded before. Here is my submit form :

```
 public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $parameters = \Drupal::routeMatch()->getParameters();
    $shooting = Node::load($parameters->get('shooting_id'));

    $destination = \Drupal::service('file_system')->realpath('temporary://');

    $zipname = $destination . '/vos_photos_'.$shooting->id().'.zip';

    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: ' . filesize($zipname));

    $zip = new \ZipArchive();

    $zip->open($zipname, constant("ZipArchive::CREATE"));

    foreach ($shooting->field_shooting_photos as $media) {

      $uri = $media->entity->field_media_image->entity->uri->value;
      $file_path = \Drupal::service('file_system')->realpath($uri);

      // Ajout de chaque fichier dans le zip //
      $zip->addFile($file_path, $media->entity->field_media_image->entity->name);

    }

    $zip->close();

    readfile($zipname);
    exit;

  }

```

This works great.
The only problem is when I unzip it, I get var/www/drupalvm/web/sites/defaults/files/{My content}
I would like to just have a simple folder files/{my content} without the long path before, or if it's not possible, simply {my content} when you extract the zip. Thank you
I'm pretty the problem can be solved in the addFile by giving a localname, I just can't figure out how to

# Answer
I finally found the solution, instead of

```
$zip->addFile($file_path, $media->entity->field_media_image->entity->name);

```

I simply put

```
$zip->addFile($file_path, basename($file_path));

```

and it does the job.
> 0 votes

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


# Question
Title: Patch Status for 'cweagans/composer-patches'?
It seems that 'Drush Patch File' (https://bitbucket.org/davereid/drush-patchfile/src/master/) isn't compatible with Drush 9. It, however, has one important function - Patch Status - which enables developers to check that all the required patches were successfully applied.

I was unable to find any way how to do this via the actually recommended Composer patch management (cweagans/composer-patches)... Is there any way how to (via Composer or Drush command) check the status of the patches? Or is there a clone of 'Drush Patch File' working with Drush 9?

Any help highly appreciated!

# Answer
> 1 votes
https://gitlab.com/davereid/drush-patch is now available which is the Drupal 8 + composer-patches port of my exising drush-patchfile.

# Answer
> 1 votes
I found no available solution, so I've created a new Drush Command for this: https://github.com/SeoGow/patch\_overview/tree/master.

I hope this helps somebody.

---
Tags: drush, composer
---


# Question
Title: How come my view block is not loading using ajax?
We have a view, `myview`, that has an exposed filter `title` (text input). The view has `Exposed form in block:Yes` and so we load it onto the page under `admin/structure/block`. The block has a machine name of `exposedform_myview_title`.

We want to remove it from display and only load the view block on click of an icon. How come my view block is not loading when using ajax?

View Setup:

* view\_name = 'myview\`
* when creating view, view page setting -\> "create a page" was set to true
* view machine name = `mypage`
* view `use ajax` = Yes
* view block (displayed using admin/structure/block) machine name `exposedform_myview`

**Error message**

> https://somesite/path/views/ajax?view\_name=myview&view\_block\_id=mypage 404 (not found)

**myjs.js**

This will load the view itself and not the `exposedform_myview_title` block. We want the `exposedform_myview_title` to be displayed.

```
(function($) {
  'use strict';

  Drupal.behaviors.iconClick = {
    attach: function(context, setting) {
      $('#someid', context).once().each(function () {
        $(this).on('click', function(clickEvent) {
          // Use Ajax to load form.
          $.ajax({
            url: drupalSettings.path.baseUrl + 'views/ajax',
            type: 'GET', // type: 'POST' not succesfull
            dataType: 'json',
            data: 'view_name=myview&view_display_id=mypage',
            //not successfull --> data: 'view_name=myview&view_block_id=exposedform_myview',
            success: function(response) {
              var output = response[1].data;
              $('.some-element').html(output);
            },
            error: function(data) {
              alert('error');
              console.log(data);
            }
          });
        });
      });
    }
  };

})(jQuery);

```

**page.html.twig**

```
...
<div id="someid">my icon goes here</div>
<div class="some-element"> view block exposed form should go here </div>
...

```

we also tried to use `Drupal.ajax`, but that did not load the View into the required `<div class="some-element">`

```
(function($) {
  'use strict';

  Drupal.behaviors.iconClick = {
    attach: function(context, setting) {
      $('#someid', context).once().each(function () {
        $(this).on('click', function(clickEvent) {
          // Use Ajax to load form.
          var ajaxPath = '/views/ajax';
          var view_info = {
            view_name: 'myview',
            view_display_id: 'page'
          };

          var ajax_settings = {
            submit: view_info,
            url: ajaxPath,
            event: 'click'
          };

          Drupal.ajax(ajax_settings);
        });
      });
    }
  };

})(jQuery);

```

# Answer
> 0 votes
I got this working:

gotchas: 1. Had to load ajax\_view.js, added this code snippet to theme file, check your view source to make sure ajax\_view.js is loaded.

```
use \Drupal\views\ViewExecutable;
function customthemename_views_pre_render(ViewExecutable $view) {
  if (isset($view) && ($view->storage->id() == 'community_plan_update_news_feed')) {
    $view->element['#attached']['library'][] = 'pager-view';
  }
}

```
2. Had to write my own jquery once function in Drupal Behaviors file:

```
(function($, Drupal, drupalSettings) {
    'use strict';
    // turn off scrolltoTop
    if (Drupal.AjaxCommands) {
        Drupal.AjaxCommands.prototype.viewsScrollTop = null;
    }
    // Write your own jquery once function
    $.fn.once = function(processed_class) {
        if (typeof processed_class == 'undefined') {
            processed_class = 'processed';
        }
        return $(this).not('.' + processed_class).addClass(processed_class);
    };

    Drupal.behaviors.pagerFragments = {
        attach: function(context, settings) {
            var pager_links = $('.tab-content .pager__items li a').addClass("use-ajax");
        }
    };

    Drupal.behaviors.linkClick = {
        attach: function(context, settings) {
            $(".pager__items li a", context).on('click', function() {

                var ajaxObject = Drupal.ajax({
                    success: function(response) {
                        var viewHtml = response[1].data;
                        Drupal.settings.views = response[0].settings.views;
                        Drupal.attachBehaviors();
                        if (response[1].data !== undefined) {
                            $('.tab-content').html(viewHtml);
                        }
                        var ajaxPath = 'views/ajax';
                        var view_info = {
                            view_name: 'community_plan_update_news_feed',
                            view_display_id: 'general_plan_news',
                        };
                        var ajax_settings = {
                            submit: view_info,
                            url: ajaxPath,
                            cache: true,
                            event: 'click',
                            async: true,
                        };

                        Drupal.ajax(ajax_settings);
                        ajaxObject.success(response, "success");
                    },

                });
            });
            // reload sharethis icons
            if (__sharethis__ && __sharethis__.config) {
                __sharethis__.init(__sharethis__.config);
            }
            Drupal.behaviors.animate = {
                attach: function(context, settings) {
                    $(document).ajaxStart(function() {
                        $('.tab-content').fadeTo(200, 0);
                    });
                    $(document).ajaxSuccess(function() {
                        $('.tab-content').fadeTo(200, 1.0);
                    });
                }
            };
        }
    }
})(jQuery, Drupal, drupalSettings);

```

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


# Question
Title: How to create a Content Type field that will be only set by query parameters?
I'm using Drupal 7. I want to create an Entity Reference field in my Order content type that will be set based on whatever the query parameter node ID is for my parent node. In other words, the user is viewing a table list of parent nodes. The right-most column is a link to "File Order" (as in, create a child node relating to that particular parent node). So the URL that it links to is **/node/add/order?nid=\[nid of parent\]**.

On the Order node add screen, the "Related Node ID" Entity Reference field should auto-populate based on whatever the nid query parameter is. So the user should not have to worry at all about setting that value ever. How do I do this?

# Answer
The Prepopulate module appears to be what you're looking for.
> 2 votes

---
Tags: hooks
---


# Question
Title: After implementing hook_node_access, how to stop node from appearing in view?
In Drupal 8, I implemented a `hook_node_access` function in my module to control access for a certain role under certain conditions and it works fine.

However, all of that content type are still shown on a view when the user views it. This is expected behavior according to the documentation:

> In node listings (lists of nodes generated from a select query, such as the default home page at path 'node', an RSS feed, a recent content block, etc.), ... hook\_node\_access() is not called on each node for performance reasons and for proper functioning of the pager system. When adding a node listing to your module, be sure to use an entity query, which will add a tag of "node\_access". This will allow modules dealing with node access to ensure only nodes to which the user has access are retrieved, through the use of hook\_query\_TAG\_alter(). See the Entity API topic for more information on entity queries.

(Link)

I understand why the view does not check each individual content, but I do not understand what this documentation is asking me to do to fix that. The documentation for `hook_query_TAG_alter` and on entity queries is not very helpful either.

How do I ensure that only items of this content type that the current user has view access to are shown in a view?

# Answer
having run into the same problem as you I hope I can save you a headache. Depending on the amount of results you have I can provide 2 ways to tackle this:

**1. Works when you don't need pagination**

HOOK\_views\_post\_execute. This will have the rows in the variable. In here you can check the access and unset() the rows not allowed.

**2. Works when you need pagination**

HOOK\_views\_query\_alter. I've used this solution for a view I needed myself with around 10000 results. I do a custom permissions check based on the user and the groups they are part of. Baed on this I generate a list of ID's of nodes they user is allowed to see. I add these ID's as an "IN" query to the view:

```
$cond["field"] = "media_field_data.mid";
$cond["operator"] = "IN";
$query->addWhere('1', $cond["field"], $mids, $cond["operator"]);

```

Where **$mids** has all the allowed Mids in there. Hope this helps you get along!
> 1 votes

# Answer
I had the same issue when using a custom hook\_ENTITY\_TYPE\_access

... just putting an example here to save people time:

```
/**
 * Implements hook_views_post_execute().
*/
function MODULE_views_post_execute(ViewExecutable $view) {
  if ($view->id() == 'view_name') {
   $result = $view->result;
   $account = $view->getUser();
   $user = \Drupal::entityTypeManager()->getStorage('user')->load($account->id());
   $filter_results = [];
   foreach ($result as $key => $value) {
     $entity = $value->_entity;
       /// opp can be create, view, delete, update.
       if ($entity->access('view', $user) == TRUE) {
        $filter_results[$key] = $value;
     }
   }
   $view->result = $filter_results;
  }
 }

```
> 1 votes

---
Tags: views, 8
---


title: Add and edit nodes using the main theme

text:
# Question
Title: Add and edit nodes using the main theme
In Drupal 7, I could use hook\_admin\_paths to decide if a page used the main or admin theme. This has changed in Drupal 8. This option is now set in a route definition. Existing routes, like *node.add*, can be altered. However, looking in *node.routing.yml*, under *node.add*, I do not see `_admin_route: TRUE`, which I intended to alter to `FALSE`.

What do I need to alter, and how, so that adding and editing nodes is done using the main theme?

# Answer
> 3 votes
You can configure this in UI, see the checkbox at the end of the theme list in */admin/appearance*:

> \[x\] Use the administration theme when editing or creating content

This config option is then used to alter the route in the following code example, which would also answer how to alter the route in a route subscriber:

**NodeAdminRouteSubscriber::alterRoutes()**

```
  protected function alterRoutes(RouteCollection $collection) {
    if ($this->configFactory->get('node.settings')->get('use_admin_theme')) {
      foreach ($collection->all() as $route) {
        if ($route->hasOption('_node_operation_route')) {
          $route->setOption('_admin_route', TRUE);
        }
      }
    }
  }

```

More info https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones

# Answer
> 1 votes
Other alternative could be to use the Context module: there is an available Reaction called 'theme' that allows to set the theme depending on any available Condition (system path, content type, etc...)

---
Tags: 8
---


# Question
Title: Drush or Drupal console command to list modules with security updates?
Is there a command for Drupal 8.x that shows available updates?

I added forms\_steps 1.1 that has an SA and a security update required in the Web UI, which is saying to update to 1.2

I tried `drush pm:security` but it reports that there is no outstanding security.

```
root@d568732a8640:/app# drush pm:security
 [success] There are no outstanding security updates for Drupal projects.

```

I might have overestimated the capability of this command so I'm looking for alternatives to get both update and security update in the console. My goal with this is to add a schedule job in our CI that will report on those.

# Answer
`drush pm:security` should be fine in listing Drupal modules with security updates.

There was a bug from the drupal-composer/drupal-security-advisories project that resulted in not listing the forms\_steps module and some other modules. It was promptly fixed and now it works!
> 3 votes

---
Tags: 8, drush, security, console
---


# Question
Title: How can I change add to cart to some other option when stock drops to zero?
Does it have some inbuilt functionality already, or should I work with hooks or even subscriber to achieve this?

# Answer
I solved this issue by using commerce stock module

You also need to select enforce option so that "add to cart" will automatically be disabled when stock drops to 0. Then you can use hook to hide the cart and show your own option.
> 0 votes

---
Tags: commerce
---


# Question
Title: BlockContent::load for addtoany_block returns null
I am trying to load the "AddToAny Buttons" block of AddToAny module inside a controller. My idea is to render the block content as a part of the page. I have verified the block id of "AddToAny Buttons" block in the Addtoany module's block plugin file which is 'addtoany\_block'. But BlockContent::load('addtoany\_block') returns null. Could somebody help me identify where I'm going wrong? Here is the code snippet

```
$block = \Drupal\block_content\Entity\BlockContent::load('addtoany_block');
$render = \Drupal::entityTypeManager()->
getViewBuilder('block_content')->view($block);

```

# Answer
The `addtoany_block` is not a block content, but it's a plugin block.
So if you want to get the its build programmatically you should:
1. Get the block configuration (addtoany\_block settings).
2. Create an instance of the block.
3. Get the build.

Try the following:

```
// Block manager.
$block_manager = \Drupal::service('plugin.manager.block');
// Load Block settings / Settings.
$addtoany_config = \Drupal::config('addtoany.settings')->getRawData();
/** @var \Drupal\addtoany\Plugin\Block\AddToAnyBlock $plugin_block */
$addtoany_block = $block_manager->createInstance('addtoany_block', $addtoany_config);
// Get Block build.
$build = $addtoany_block->build();

```
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: How to remove Home title from the home page?
There are several posts on a similar question. Despite that, I couldn't find the best way to resolve it. Display Suite is installed but don't see option to turn off page title. Our home page content type is Slider. I can see the html code using Inspect Element on Firefox. Don't know where the page is to remove it.

# Answer
> 0 votes
I think there is no way to remove it from the BO:
You can use code to remove it something like:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function myTheme_preprocess_page(&$variables) {
  if($variables['is_front']){
    drupal_set_title('');
  }
}

```

---
Tags: 7, theming, nodes
---


title: Image Style Clarification

text:
# Question
Title: Image Style Clarification
Can I get some clarification as to why images aren't being generated for a certain image style in a view?

Here's my setup; I have an `Article` content type which allows for a main image to be uploaded. An `Article Images` image style is applied which crops to the focal point (Module that's installed) and generates the image for the Article node.

I also have a view block that I use on my homepage that displays the 2 most recent articles. What this does is display the title of the article, date and tag over the main image.

In my view settings for this block, I have the Image Style set to `Article Homepage - 1075x400` with the Formatter set to `URL to image`. With a custom template, the block is displayed and what it's supposed to do is set the main image as the background image. If I leave the Image Style set to `Article Images` in the view, this works perfectly, however, changing it to the above mentioned `Article Homepage - 1075x400` ends up generating an error as it says the image doesn't exist.

In one way, this makes sense to me since when I uploaded that image to the article node, it was uploaded only in that certain style so it wouldn't make it available in any other style, would it? Or maybe I'm not seeing this the right way or something in my template is wrong.

Any clarification as to why changing the style for my homepage view ends up displaying nothing would be great.

Below is the template for that homepage block in case my issue is coming from this. *Maybe there's something I need to put in here so that any style can take effect?*

```
  {% set bg_url = fields.field_image.content|render|striptags|trim %}
  {% if bg_url %}
  <div class="news-home-item--image d-flex align-items-center justify-content-center" style="background-image: url({{ bg_url }})">
  {% else %}
  <div class="news-home-item--image d-flex align-items-center justify-content-center">
  {% endif %}
  </div>
  <div class="news-home-item--info">
    <h5>{{ fields.title.content }}</h5>
    <div class="news-home-item--info__meta">
      <div class="news-home-item--info__meta-date float-lg-left">{{ fields.created.content }}</div>
      {% if fields.field_tags.content|render %}
      <div class="news-home-item--info__meta-tags float-lg-right">{{ fields.field_tags.content}}</div>
      {% endif %}
    </div>
  </div>

```

**Update 1:**

So, I think I might be onto what's happening here. I think it comes down to me using the twig filters in my theme file. If I remove `|striptags|trim` it generates the image style, however, it won't actually show up in my dev site, in which I'm developing all this, due to the fact that without those other two filters, this is what ends up printing out in the style class:

```
style="background-image: url(
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_field' -->
<!-- BEGIN OUTPUT from 'themes/custom/scc/templates/views/views-view-field.html.twig' -->
/sites/default/files/styles/articles_homepage_1075x400/public/articles/2019-05/image.jpg?h=287a81f3&itok=aMmcvNDO
<!-- END OUTPUT from 'themes/custom/scc/templates/views/views-view-field.html.twig' -->
)"

```

After removing those filters in the file, letting it generate the style, then putting the other two filters back, the image does show up. I'm assuming those filters are hindering the creation for some reason. It may end up not being a problem if I leave those filters out. Sure it won't show up properly on my dev site but I'm going to assume it'll work properly on dev.

**Update 2:**

Removing `|render|striptags|trim` from my `field_image` ended up making this work as intended on my production website. It still remains broken on my dev site though due to it spitting out that extra code.

# Answer
> 0 votes
Are you sure that image style still exists? Views doesn't like when you delete/change image styles that it is already using. A remedy might be to delete that field from your view, and reset it (with the confirmed good image style?)

Maybe your image style was formed improperly?

(Are your view blocks restricted to not show on the home page (block admin?)

---
Tags: views, 8, media
---


# Question
Title: hook_ENTITY_TYPE_insert never gets called
Can anyone help me on the below functions. I am trying to alter user registration form and add my user form fields to default registration form. I am successfully retrieving data till validation, but I am not sure where I am going wrong in `hook_user_insert`. I am not able to retrieve the field value of my custom fields in hook\_user\_insert function.

Early support will be helpful in completion of the module.

```
function security_questions_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Hide the questions form when the user is being registered by an admin.
  if (!\Drupal::currentUser()->hasPermission('administer users')) {
    // Merge in our user form.
    $form += SecurityQuestionsUserForm::buildForm($form, $form_state);
    array_unshift($form['#validate'], 'security_questions_form_user_register_form_validate');
    // We can't add our submit handler here, because the user account doesn't
    // exist yet. Instead, we will get the info during hook_user_insert().
  }
}

/**
 * Validation handler for security_questions_form_user_register_form_alter().
 */
function security_questions_form_user_register_form_validate(array &$form, FormStateInterface $form_state) {
  //module_load_include('inc', 'security_questions', 'security_questions.pages');
  SecurityQuestionsUserForm::validateForm($form, $form_state);
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function security_questions_user_insert(\Drupal\user\UserInterface $account) {
  // During registration, save the user's answers.
  print_r($account->questions);
  die;
  if (!empty($account->questions)) {
    security_questions_user_answers_save($account, $account->questions);
  }
}

```

# Answer
> 0 votes
You probably need to add a field to the user entity, which matches your form field key. Or, save the data in the session ..

---
Tags: 8
---


# Question
Title: How do I show the number of nodes using a taxonomy term?
Somebody asked Views and node count for taxonomy terms. I am trying to do the same, but with Drupal 8.

I follow the steps reported in that question, and I get a count of the taxonomy term (say "fruit"), but when I click on it there is a page that lists "fruit" multiple times, instead of listing the pages themselves.

If I do not do a count. then when I click on the taxonomy term I get the correct listing page (e.g. *apple*, *orange*, *pear*).

Can anyone help me with this?

# Answer
> 13 votes
The following worked for me in Drupal-8.0.6.

Note that for some reason 'Content NID' is not offered as a field for the 'Content with term' relationship, so I used UUID instead and it worked.

1. Create a Taxonomy Term view (with a field `Taxonomy term: name`, usually linked to the term page)
2. Relationship \> Taxonomy term: Content with term (will be called `node`).
3. Advanced: Use aggregation: Yes
4. Add Field \> `Content: UUID` with relationship `node`
5. Aggregation type for UUID = Count

You may have to play with `COUNT` vs `COUNT distinct`

If you want tbe count to appear in brackets like this:

```
linked_term (count)

```

On UUID field use **Rewrite results**:

```
({{ uuid }})

```

Note that it is using the new Twig template language notation.

# Answer
> 3 votes
Differently from what stated in the other answer for Drupal 8.0.6, there is a field for the node ID, in Drupal 8.1.3.

With Drupal 8.1.3, I followed these steps:

* I created a view of taxonomy terms, limiting them to the ones of just a vocabulary (in my case *Blog categories*)
* As relationship, I added *Content using field\_blog\_category*, where *field\_blog\_category* is the field I added to a content type I created
* I checked *Use aggregration*
* I added *ID* (listed under the *Content* category) as new field
* I set *Aggregration type* to *Count* for the new field (by clicking on *Aggregration settings* for that field)

What I got was the following one (as seen from the preview).

>

Following the steps I listed, but using *UUID* as new field (still listed under the *Content* category), I would have obtained the same result.

As expected, also the resulting query didn't change much, using the node ID or its UUID.

### Using the node ID

```
SELECT taxonomy_term_field_data.name AS taxonomy_term_field_data_name, COUNT(field_blog_category_taxonomy_term_field_data.nid) AS field_blog_category_taxonomy_term_field_data_nid, MIN(taxonomy_term_field_data.tid) AS tid, MIN(field_blog_category_taxonomy_term_field_data.nid) AS field_blog_category_taxonomy_term_field_data_nid_1
FROM
{taxonomy_term_field_data} taxonomy_term_field_data
LEFT JOIN {node__field_blog_category} node__field_blog_category ON taxonomy_term_field_data.tid = node__field_blog_category.field_blog_category_target_id AND node__field_blog_category.deleted = '0'
LEFT JOIN {node_field_data} field_blog_category_taxonomy_term_field_data ON node__field_blog_category.entity_id = field_blog_category_taxonomy_term_field_data.nid
WHERE (( (taxonomy_term_field_data.vid IN  ('blog_categories')) ))
GROUP BY taxonomy_term_field_data_name
LIMIT 21 OFFSET 0

```

### Using the node UUID

```
SELECT taxonomy_term_field_data.name AS taxonomy_term_field_data_name, COUNT(field_blog_category_taxonomy_term_field_data__node.uuid) AS field_blog_category_taxonomy_term_field_data__node_uuid, MIN(taxonomy_term_field_data.tid) AS tid, MIN(field_blog_category_taxonomy_term_field_data.nid) AS field_blog_category_taxonomy_term_field_data_nid
FROM
{taxonomy_term_field_data} taxonomy_term_field_data
LEFT JOIN {node__field_blog_category} node__field_blog_category ON taxonomy_term_field_data.tid = node__field_blog_category.field_blog_category_target_id AND node__field_blog_category.deleted = '0'
LEFT JOIN {node_field_data} field_blog_category_taxonomy_term_field_data ON node__field_blog_category.entity_id = field_blog_category_taxonomy_term_field_data.nid
INNER JOIN {node} field_blog_category_taxonomy_term_field_data__node ON field_blog_category_taxonomy_term_field_data.nid = field_blog_category_taxonomy_term_field_data__node.nid
WHERE (( (taxonomy_term_field_data.vid IN  ('blog_categories')) ))
GROUP BY taxonomy_term_field_data_name
LIMIT 21 OFFSET 0

```

# Answer
> 0 votes
Ran into a Drupal core bug with the taxonomy Content with term relationship. Patch in https://www.drupal.org/project/drupal/issues/2674832#comment-10890660 Let me use other content fields to filter (content type, not just UUID) to get a count.

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


# Question
Title: Custom Entity's Custom Fields doesn't show in when trying to Add Field in Views
I've created a custom entity and allowed administrators to add custom fields to this entity using the "Manage Fields" Form; however, the custom fields I add to the entity does not appear in the list that pops up when trying to "Add Fields" in a view.

How does one go about making custom fields appear in the Views?

# Answer
> 3 votes
I ran into this just today. Turns out you shouldn't set **data\_table** in the entity type annotation if **translatable** is FALSE. Otherwise views associates all of the fields with the **data\_table**, but **data\_table** is never associated with **base\_table** due to translations being disabled.

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


# Question
Title: Field formatter module throws cannot declare class error
I am trying to write a custom module, which defines a field formatter plugin, but when I visit the Manage display page, I get this error:

> Fatal error: Cannot declare class Drupal\my\_formatter\Plugin\Field\FieldFormatter\MyFormatter, because the name is already in use in /var/www/sites/drupalroot/web/modules/custom/my\_formatter/src/Plugin/Field/FieldFormatter/MyFormatter.php on line 0

I've compared my module to several other working field formatter plugins and can't seem to figure out what I'm missing.

My module directory is laid out like this:

```
web/modules/custom/my_formatter/
├── my_formatter.info.yml
├── my_formatter.module
├── src
│   └── Plugin
│       └── Field
│           └── FieldFormatter
│               └── MyFormatter.php
└── templates
    └── my-formatter.html.twig

```

My info file:

```
name: My Formatter
type: module
description: 'Do some fun stuff.'
package: Field types
core: 8.x
dependencies:
  - field
  - file

```

And my `MyFormatter.php` file:

```
<?php
/**
 * @file
 * Contains \Drupal\my_formatter\Plugin\Field\FieldFormatter\MyFormatter.
 */

namespace Drupal\my_formatter\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase;

/**
 * Plugin implementation of the 'my' formatter.
 *
 * @FieldFormatter(
 *   id = "my",
 *   label = @Translation("My Formatter"),
 *   field_types = {
 *     "file"
 *   }
 * )
 */
class MyFormatter extends FileFormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#theme' => 'my_formatter',
        '#my_var' => 'Hello',
      ];
    }
    return $elements;
  }

}

```

Any help would be greatly appreciated.

# Answer
Here are some pointers that might help:

* Run `drush cr` to clear cache and see if the error persists.
* Enable error backtraces from the `Config > Development > Logging & Errors` page to see if you get more info in the error message about where the class is being redeclared.
* Search your project for the name `MyFormatter` and see if you find anything besides the `MyFormatter.php` file you've mentioned.
* File, directory and class names are case-sensitive – in what you've shared, they seem to be correctly named.
* Make sure you're not manually using `require` or `include` anywhere to include this file.
    + Probably, not applicable in your case.
> 3 votes

# Answer
This error is often caused by a "stale" autoloader file. The first and most effective step would be to call

`composer dump-autoload`

from inside your drupal installation folder (presumably `/var/www/sites/drupalroot/`) in order to force an updating of the autoloader file in your vendor folder. Try clearing the composer caches as well in combination with this command:

`composer clear-cache`

Good luck!

P.S.: @see dump-autoload-dumpautoload for more information
> 3 votes

---
Tags: 8, files, plugins
---


title: Display content assigned to a group

text:
# Question
Title: Display content assigned to a group
I am relatively new to Drupal, so I apologize in advanced if my question is confusing.

I am building a school website that will have a parent district site and then school websites within the district. I want to have give the teachers permission to only edit their own respective sites as well.

I feel like I could do this easier with D7 but I want to be future proof so I am attempting this with D8.

Are there any methods I could try to achieve this?

# Answer
It seems that all you'd need to do, is to use the Group module.

Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

# Resources
> 0 votes

---
Tags: 8, multi-sites
---


# Question
Title: Unknown option `--tail` when running `drush ws --tail`
I am using Drush version 9.0-dev-dev.

When I run `drush ws --tail`, I get the following error:

```
[error]  Unknown option: --tail.  See `drush help watchdog-show` for available options. To suppress this error, add the option --strict=0.

```

I've used this with all other versions of drush with no issues.

# Answer
> 2 votes
It's all in the linked issue.

> Some existing Drush commands were simplified in Drush 9. I think that --tail would still be a welcome addition, if someone wanted to submit a PR.

But as of today the pull request is still unmerged. Maybe you can reanimate it and provide some help.

---
Tags: 8, drush
---


# Question
Title: Hide a list of blocks from Panelizer in-place editor (IPE)
I have a list of blocks that shouldn't be added via panelizer IPE popup under manage content. Is there any way to remove them from the list?

# Answer
> 1 votes
One of the options is to extend the IPE controller to remove the unwanted blocks from display. Here are the code changes:

1. Route subscriber:

```
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: 'event_subscriber' }

```
2. Update the IPE controller:

```
<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\mymodule\Controller\MymoduleIPEPageController;
use Symfony\Component\Routing\RouteCollection;

/**
 * Subscriber to update IPE controller.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    /* \Symfony\Component\Routing\Route $route */
    if ($route = $collection->get('panels_ipe.block_content_types')) {
      $route->setDefault('_controller', MymoduleIPEPageController::class . '::getBlockContentTypes');
    }
  }

}

```
3. Controller:

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\panels_ipe\Controller\PanelsIPEPageController;

/**
 * Extends IPE controller for site specific customization.
 */
class MymoduleIPEPageController extends PanelsIPEPageController {

 /**
   * {@inheritdoc}
   */
  public function getBlockContentTypesData($panels_storage_type, $panels_storage_id) {
    // Assemble our relevant data.
    $types = $this->entityTypeManager()
      ->getStorage('block_content_type')
      ->loadMultiple();
    $data = [];
    $blocks_blacklist = $this->getHiddenBlockList();
    /** @var \Drupal\block_content\BlockContentTypeInterface $definition */
    foreach ($types as $id => $definition) {
      if (in_array($id, $blocks_blacklist)) {
        continue;
      }
      $data[] = [
        'id' => $definition->id(),
        'revision' => $definition->shouldCreateNewRevision(),
        'label' => $definition->label(),
        'description' => $definition->getDescription(),
      ];
    }

    return $data;
  }

 /**
   * List of blocks not available to add via PIE.
   *
   * @return array
   *   An array of block IDs.
   */
  protected function getHiddenBlockList() {
    // Remove UUID and title fields from the list.
    return [
      'entity_field:node:uuid',
      'entity_field:node:title',
    ];
  }

}

```

# Answer
> 1 votes
Another simpler option is to use the `hook_panels_ipe_blocks_alter()` hook in a custom module of yours and apply the necessary logic. An example is documented in panels\_ipe.api.php:

```
function hook_panels_ipe_blocks_alter(array &$blocks, PanelsDisplayVariant $panels_display) {
  // Only show blocks that were provided by the 'mymodule' module.
  foreach ($blocks as $key => $block) {
    if ($block['provider'] !== 'mymodule') {
      unset($blocks[$key]);
    }
  }
}

```

---
Tags: 8, blocks, panels
---


# Question
Title: Overwrite an empty field value on node / rendered entity
I have a text field in a media image type (for a photo caption) - I'd like to *output* a default value whenever it's empty.

I tried using *HOOK\_preprocess\_field*, but that hook isn't reached if the field of the node is blank.

It's being inserted in a View, but it's more than one field (a display mode of a Rendered Entity showing a photo thumbnail and the caption) and therefore as the photo is present when the caption isn't, I can't use the *No results behaviour*.

I also tried *HOOK\_preprocess\_node* and *HOOK\_preproces\_content\_field*, neither of those seem to be called *at all* in the view.

Is there anywhere else I can edit it?

# Answer
You might consider overriding an appropriate Twig template, something along the lines of `{% if content.field_caption %} {{ content.field_caption }} {% else %}} default text {% endif %}`
> 1 votes

# Answer
You can use the hook `theme_preprocess_media` check on media if it's an image and than get the default value of your field to compare it with the actual value.
Try the following.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function myTheme_preprocess_media(&$variables) {
  /** @var \Drupal\media\MediaInterface $media */
  $media = $variables['media'];
  if ($media->getSource()->getPluginId() === 'image') {
    $elements = $variables['elements'];
    if ($media->hasField('field_caption') && isset($elements['field_caption'])) {
      // Get the default value of field_caption field.
      // To compare it with the the actual value.
      $caption_default_value = $elements['field_caption']['#items']->first()
        ->getFieldDefinition()
        ->getDefaultValue($media)[0]['value'];
      // Get the actual value.
      $caption_actual_value = $media->field_caption->getValue()[0]['value'];

      // Check if the value hasn't change so its has the default value.
     if ($caption_default_value === $caption_actual_value){
       // Change the value of caption  field.
       $variables['content']['field_caption'][0]['#context']['value'] = t('This is new value of caption');
     }
    }
  }
}

```
> 1 votes

---
Tags: 8
---


title: Place a custom block inside admin area

text:
# Question
Title: Place a custom block inside admin area
How is it possible to place a custom block inside the admin area? (e.g. in a node edit form)? I tried with page restriction but with no success. How can I see the block regions of the admin theme (seven)?

# Answer
> 1 votes
You can just go to "Structure \> block layout" from the admin bar. This will default to your current default theme but along the top of that page it will list out all other active themes and "Seven" will be one of them

Click that and the block listing will now be for the Seven theme and you can add/remove blocks like you can normally except it will now be for the Seven theme

You wouldn't be able to place a block midway through the form but you could add a block above/below the form

---
Tags: blocks, theming
---


# Question
Title: How can I remove the default value _none in a select list?
1. Created a content type and added a field "list(text)".
2. Under field settings marked the field as required.( Please make a note of an option for default value where the value is set to None by default).
3. Started creating content and given all the mandatory fields and left the value of the select-list field to default like 'select a default value' and try to submit the content.
4. The form gets submitted without HTML5 validation(i.e it is not showing a popup that the field is required to the user while filling the form.) but server side validation is in place so one can observe form error after submitting the form that field list is required.

Noticed the reason behind the HTML5 validation not working is the value for the option is a string '\_none'.

How to remove the default value "\_none" from select-list.

# Answer
> 3 votes
First unset the value like below.

```
unset($form['field_registration_type']['widget']['#options']['_none']);

```

Then set your drop down value to null, like below.

```
$form['field_registration_type']['widget']['#options'] = ['' => 'Select'] + $form['field_registration_type']['widget']['#options'];

```

Now your drop down value is null and your validation will work as expected.

# Answer
> 0 votes
istead :

```
$form['field_registration_type']['widget']['#options'] = ['' => 'Select'] +$form['field_registration_type']['widget']['#options'];

```

i would use:

```
$form['field_name']['widget']['#empty_option'] = "- Select - ";
$form['field_name']['widget']["#empty_value"] = "";

```

i think this is more clear and you don't need to change all options, but one

happy coding, Adam

---
Tags: 8, forms
---


title: Using SweetAlert with preventDefault()

text:
# Question
Title: Using SweetAlert with preventDefault()
I have an event on a form submit.

I set `preventDefault()` to stop the form submitting then pop SweetAlert with a confirmation callback. If they decide to go ahead, it POSTs the form to Drupal.

It doesn't hit the form submission method, but it redirects to the same page with a GET request. If I simply return `true` from the jQuery submission event, it works.

When they confirm, `form.off('submit').submit()` is executed, but it doesn't work.

Can anybody help me?

# Answer
> 0 votes
I solved this.

Drupal uses the `$op` variable, which contains the label of the used submission button. When `preventDefault()` is used, that value is removed.

The solution is adding this to the SweetAlert callback function when a form is submitted.

```
formE.off('submit');
var input = $("<input>").attr("type", "hidden").attr("name", "op").val("Update");
formE.append(input);
formE.submit();

```

---
Tags: 7, javascript
---


title: Permission for anonymous user

text:
# Question
Title: Permission for anonymous user
I got custom registration form under `/user/register` URL but anonymous user gets `denied access` what type of permissions should I set.
I tried:

```
 requirements:
   _permission: 'access content'

```

and

```
requirements:
   _permission: 'none'

```

or I deleted it completly but it didn't help.

# Answer
'access content' should be good in general, check it under "people/permissions" to seem if also anonymous users have right to "access content". You can also declare:

```
_access: 'TRUE'

```

In this case you don't need the permission part, this one should definitely work!
> 11 votes

# Answer
The above answer did not work until I added the quote marks around TRUE. See the following YAML example placed in my\_module.routing.yml

```
my.module:
    path: '/my-module'
    defaults:
      _controller: '\Drupal\my_module\Controller\MyModuleController::connection'
    requirements:
      _access: 'TRUE'

```
> 3 votes

# Answer
The most correct way is use the \_persmission as following:

```
custom_module.add:
  path: '/tools/add'
  defaults:
    _title: 'Add new tools'
    _controller: '\Drupal\custom_module\Controller\ToolsInputPage::render'
  requirements:
    _permission: 'access content'

```
> 1 votes

# Answer
Try this.

```
  requirements:
    _role: 'authenticated'

```

or use the User service.

```
  requirements:
    _user_is_logged_in: 'TRUE'

```
> -2 votes

---
Tags: 8, users
---


# Question
Title: How to exclude views fields from display when a node is flagged
We use the flag module to mark items that will have delays in shipping so that the customer knows that those items will be delayed before adding them to cart. In drupal 7, we excluded our "add to cart" button and "more info" button from display and used a global custom text to rewrite them with the following text displaying them inside a btn-bar div class.

`<div class="btn-bar [flagged_1]">[flagged]<span class="atc">[add_to_cart_form]</span> <span class="moreinfo"><a href="[path]">More info</a></span></div>`

We then use the following css to hide the add to cart, and more info elements when the flag is present in the button bar.

```
.btn-bar.pre-order .atc,
.btn-bar.pre-order .moreinfo{
  display: none;
}

```

In Drupal 8, the functionality of this still works correctly (updating the replacement patterns of course), but there is apparently a security issue with rewriting forms, so the add to cart button won't render properly when being rewritten in a global custom text.

So my question is what is the "simplest" way to hide those 2 fields when that particular node is flagged? Can this be accomplished by adding some code to my custom theme for the view in question?

# Answer
> 0 votes
General approach:

Use the Rules module (which does not yet have a stable release for Drupal 8, but does have the capability in its current state to implement the recipe below) to detect the content is flagged, then do a Rules action which will result in those fields being hidden.

**Here is one specific example**, but there are many ways, and likely simpler ways to do it than my recipe. I wanted to give you an example that doesn't require coding or extra modules besides the Rules module:

Drupal automatically includes a body class with the content type of the node. So make a rule that will evaluate that a node has been flagged, and if it is, change that node's content-type via the action "Data =\> set a data value." Now you can easily create the css to hide the fields that you want hidden by using the body class for the content type assigned flagged nodes.

Make sure the two content types use the same fields and have all the same settings for those fields.

Also make sure to set up a second rule which does the opposite so that the content type is returned to the original when the flag is removed.

---
Tags: views, 8, flags
---


# Question
Title: Newly (created by Drupal) dir not writable after first upload?
I'm working on Mac (Mojave) and using Vagrant for local dev. server. "nfs" is set to true if that maters. On Vagrant box I run Ubuntu 18.04. Drupal version is 8.7.2.

I add some new image field to some existing content type. For that field I set directory name, where files should be stored, i.e. "people" so dir is created in `sites/default/file`.

Then when I edit some node in that type and upload image for the first time it works fine. But when I edit another one I can not upload image - this directory becomes write protected?! And then when I manually allow writing (change dir permissions) I can upload image again and it works well after that for all other nodes.

So it's like after first upload Drupal makes directory write protected for some reason?! Or is that done by virtual box?

Any idea why is that happening?

# Answer
It's the server software that controls the file permissions, you need to have that set up correctly first. Drupal is then granted access to the dedicated folder for site uploads and other generated files necessary for the site activity.

It's very important for your site security to have the files' and folders' owners, groups, and permissions correctly set up, and this is a part of any Drupal installation.

This is a long but detailed resource on this: Securing file permissions and ownership

Usually you need to make the `www-data` user the owner of the files/ folder, this is the Apache server user on a lot of installations but YMMW, it can be called something different. And it's important to give all the necessary permissions for that user and the group too, but not more than necessary to keep it perfectly secure.

Doing this step during Drupal installation usually ensures you don't stumble upon file-upload-permission related issues.

Also check your Status Report for any messages related to file uploads. You will also have entries in the Latest log entries if the system encounters something worth throwing an error for. And check the File system related admin pages (under Configuration), try saving the form there and see if you get any errors and get more info about your case.

Did you use some special Drupal Vagrant setup?
> 0 votes

---
Tags: 8
---


title: Recover a deleted user's content

text:
# Question
Title: Recover a deleted user's content
A few weeks ago a site admin canceled a user account on one of my Drupal 7 sites and clicked on "Delete the account and its content." That user had created about half the content on the site in different content types and uploaded files.

So we lost about half our content.

I have backup (a mysql dump) of the site from before account was removed and all the uploaded files, and I'm sure the user wasn't active in the time between the backup and the removal.

Is there an easy way to recover the content from that one user? I cannot just restore the database from the dump, since that will wash away any changes since then.

# Answer
> 2 votes
It depends on how complicated your content/site structure is, authored by the user account that got deleted, but it can be fairly easy if it's just nodes and sum such content.

Use which ever migration method you're most comfortable with. Migrate module is popular, but Feeds may be more user-friendly? Don't hang on module reviews here ;)

One way to go about it is to create a separate dev instance of your site by copying the live Drupal folder, and restoring the database backup that contains your deleted user and content. Like a time machine viewing your site at a moment in the past :)

You can use Views to list all content from that user, export it as CSV, or some other parsing case. Views gives you a nice overview of what's there so you can check you got everything. You can output post times, statuses, references to other entities...

Then build Feeds importer for what you exported. Test the import on yet another dev instance of your site, the copy of the current db. TEST everything thoroughly before importing to a site that matters, this should be obvious. Migrations are notoriously tricky and long affairs.

You could go as far as to restate the user with account history etc with some more magic, but it seems you only need the content so it will probably easier to just assign authorship to another user or anonymous if it doesn't clash with permissions, or create a completely new user, you can name it the same as the old one but the ID will be different.

---
Tags: users, backups
---


title: Strange views issue on upgrade

text:
# Question
Title: Strange views issue on upgrade
I'm upgrading a site from 8.4.8 to 8.7.7 via Composer. After a few rounds, things seem pretty good, but I'm stuck on a tricky bit: on `drush updatedb` the process throws an error on Views post-update. Here's the output

> views module :
> Update dependencies for moved bulk field plugin.
> Add additional settings to the entity link field and convert node\_path usage to entity\_link.
> Update exposed filter blocks label display to be disabled.
> Add placeholder settings to string or numeric filters.
> Rebuild cache to allow placeholder texts to be translatable.
> Fix cache max age for table displays.
> Include views data table provider in views dependencies.
>
> Do you wish to run all pending updates? (y/n): y
> Malformed backend packet \[error\]
> Post updating views \[ok\]
> Failed: Exception: No entity type for field field\_title on view image\_paragraph\_default in Drupal\views\Plugin\views\HandlerBase-\>getEntityType() (line 713 of .../docroot/core/modules/views/src/Plugin/views/HandlerBase.php). \[error\]
> The command could not be executed successfully (returned: DRUSH\_BACKEND\_OUTPUT\_START - DRUSH\_BACKEND\_OUTPUT\_END, code: 1) \[error\]
> Cache rebuild complete. \[ok\]
> Finished performing updates.

So, first of all, am I just missing something obvious? The view is broken in the 8.4 site, too, but I can't figure out how to modify the field *or* remove the view, since all attempts throw the same error! Is there a way around that?

Thanks.

# Answer
> 0 votes
Bah, nevermind -- I realized that I can just remove the view from the config table in the db. Then all updates are free to proceed. Thanks!

---
Tags: views, 8, updating
---


title: How is $form['#action'] encoded?

text:
# Question
Title: How is $form['#action'] encoded?
I have the following set up:

* Webform "my\_webform"
* Entity type "activity"
* The "activity" entity type includes a webform reference field
* Activity ID 14 has some content and a reference to "my\_webform"
* Activity ID 14 has the path "/activity/14"

In a custom module I have a `hook_form_alter()` to perform some changes based on certain conditions. I'm using the devel module and `kint()` to debug the structure.

```
function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'my_form) {
    kint($form['#action']);
  }
}

```

Here's the first bit of strangeness:

`kint()` states the length of the string as being 55 characters. To work out what the characters are, I used the following:

```
function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'my_webform) {
    $array = [];
    for ($i=0; $i<strlen($form['#action']); $i++) {
      $array[$i] = $form['#action'][$i];
    }
    kint($array);
    print implode(' ',$array);
  }
}

```

This produced the following:

`f o r m _ a c t i o n _ p _ p v d e G s V G 5 z N F _ X L G P T v Y S K C f 4 3 t 8 q Z Y S w c f Z l 2 u z M`

To get a proper look, I tried to remove this spaces:

```
print str_replace(" ", "", 'f o r m _ a c t i o n _ p _ p v d e G s V G 5 z N F _ X L G P T v Y S K C f 4 3 t 8 q Z Y S w c f Z l 2 u z M');

```

The result: `/activity/14`

The full `hook_form_alter()`:

```
function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'my_webform) {
    $array = [];
    for ($i=0; $i<strlen($form['#action']); $i++) {
      $array[$i] = $form['#action'][$i];
    }
    kint($array);
    print implode(' ',$array);
    print str_replace(" ", "", 'f o r m _ a c t i o n _ p _ p v d e G s V G 5 z N F _ X L G P T v Y S K C f 4 3 t 8 q Z Y S w c f Z l 2 u z M');

    // exit;
  }
}

```

Uncommenting the `exit;` results in the full 55 character string so something's happening after this `hook_form_alter()` is invoked. Where and how this is happening? How does it alter what `print` displays after the fact?

I've hardcoded the string in `str_replace()` for testing but this can be replaced with `print implode('',$array);`

# Answer
The form action url is placeholdered to make the form cacheable when used on different pages:

*Drupal\Core\Form\FormBuilder::prepareForm*

```
  public function prepareForm($form_id, &$form, FormStateInterface &$form_state) {
    $user = $this->currentUser();

    $form['#type'] = 'form';

    // Only update the action if it is not already set.
    if (!isset($form['#action'])) {
      // Instead of setting an actual action URL, we set the placeholder, which
      // will be replaced at the very last moment. This ensures forms with
      // dynamically generated action URLs don't have poor cacheability.
      // Use the proper API to generate the placeholder, when we have one. See
      // https://www.drupal.org/node/2562341. The placeholder uses a fixed string
      // that is Crypt::hashBase64('Drupal\Core\Form\FormBuilder::prepareForm');
      $placeholder = 'form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM';

      $form['#attached']['placeholders'][$placeholder] = [
        '#lazy_builder' => ['form_builder:renderPlaceholderFormAction', []],
      ];
      $form['#action'] = $placeholder;
    }

```

The placeholder is replaced before the cached page is delivered to the client. See FormBuilder::renderPlaceholderFormAction and FormBuilder::buildFormAction

The confusion in your debugging attempts is caused by placeholders being replaced not only in rendered forms, but also in debug output you put on the page via kint() or print.
> 2 votes

---
Tags: 8, webforms
---