# Question
Title: How to access fields value in views-view--[viewid]--[view-display-id].html.twig template
I'm trying to customize a View in Drupal 8 where I display a Bootstrap Carousel.
What I've managed to do so far was the right template name, by specifying the *viewid* and *view-display-id*.
The view name is `homepage-carousel` and the view display id is `block 1`, therefore the template name `views-view--homepage-carousel-block-1.html.twig` or `views-view--homepage-carousel.html.twig`.

Now I need to show the content of the fields of a specific *Content Type*. I've tried with `{{ fields.title }}`, but it doesn't work. I've also tried to change the template name in `views-view-fields--homepage-carousel-block-1.html.twig`, but the system doesn't recognize it, so it displays the default view.

Here is the code:

```
<div class="carousel-fill" style="background-image:url({{file_url(field_carousel_image.entity.fileuri)}});">
       <div class="carousel-caption">
          <h3 class="carousel-title">{{ fields.title }}</h3>

          {{ fields.field_carousel_subtitle }}
      </div>
</div>

```

How can I show the fields from this kind of view template?

**UPDATE**
I've tried to rename the template as suggested JeremyM4n, I've flushed all the cache, but it still doesn't work. The view is displayed as default, namely how it is set up in the `/admin/structure/views/view/` section.

I haven't mentioned it yet, so I specify it here: the *format* of this view is **Bootstrap Carousel**

**UDPATE 2**

I managed to find a solution by by overriding the `views-bootstrap-carousel.html.twig` template in `view_bootstrap` module. In my case, the name of the template is the following: `views-bootstrap-carousel--homepage-carousel--block-1.html.twig`

Here is the code:

```
<div id="{{ id }}" class="carousel {{ effect }}"
    data-interval="{{ interval }}"
    {% if ride %} data-ride="carousel" {% endif %}
    data-pause="{% if pause %}hover{% else %}false{% endif %}">

  {# Show indicators if set in view. #}
  {%  if indicators %}
  <ol class="carousel-indicators">
      {% for key, row in rows %}
          {% set indicator_classes = [loop.first ? 'active'] %}
          <li class="{{ indicator_classes|join(' ') }}" data-target="#{{ id }}" data-slide-to="{{ key }}"></li>
      {% endfor %}
  </ol>
  {% endif %}

  {# Carousel body. #}
  <div class="carousel-inner">
    {% for row in rows %}
      {% set row_classes = ['item', loop.first ? 'active'] %}
      <div class="{{ row_classes|join(' ') }}">
        <div class="carousel-fill">
          {{ row.image }}
          {% if row.title or row.description %}
            {%  if use_caption %}
            <div class="carousel-caption d-none d-md-block">
            {% endif %}
              {% if row.title %}
                  <h3 class="carousel-title">{{ row.title }}</h3>
              {% endif %}
              {% if row.description %}
                  <p>{{ row.description }}</p>
              {% endif %}
              <a class="btn btn-glass" href={{ row.field_carousel_button_url }}>{{ row.field_carousel_button_text }}</a>
            {%  if use_caption %}
            </div>
            {% endif %}
          {% endif %}
        </div>
      </div>
    {% endfor %}
  </div>
  {# Controls #}
  {% if navigation %}
    <a class="carousel-control-prev" href="#{{ id }}" role="button" data-slide="prev">
      <span class="carousel-control-prev-icon" aria-hidden="true"></span>
      <span class="sr-only">{{ 'Previous'|t }}</span>
    </a>
    <a class="carousel-control-next" href="#{{ id }}" role="button" data-slide="next">
      <span class="carousel-control-next-icon" aria-hidden="true"></span>
      <span class="sr-only">{{ 'Next'|t }}</span>
    </a>
  {% endif %}
</div>

```

# Answer
The template name needs double dashes between each section `views-view--homepage-carousel--block-1.html.twig.`

At the views-view level all of your data is in `rows`. You would need to loop through your rows and then get the fields. But it's much easier to just override the main structure you need to in `views-view`, and then use `views-view-fields--homepage-carousel--block-1.html.twig` to change the structure of the actual fields, in which case they are available under `fields` like your example code.
> 1 votes

---
Tags: views, 8, theming
---


# Question
Title: How do I create content during site installation?
As part of Drupal 8 site install/deploy, I want to create content so that the site is functional and ready to use.

For example, whenever I install the site, there should be a home page node created.

How do I create content during site installation?

# Answer
> 2 votes
There are few ways in Drupal 8 to manage site default content:

1. Default content module allows to export/import content via `drush` and store the content in the structure similar to config in Drupal core.
2. Umami profile in Drupal core has a custom importer which loads the content stored in CSV to be important as part of module install.
3. Migrate CSV plugin allows to important the content from CSV using Drupal core migration API.
4. Single File Components could be used to provide content with components.

---
Tags: nodes, installation
---


# Question
Title: "RuntimeException: Unable to determine class for field type found in the configuration"
I got this error while updating from Drupal 8.3.7 to Drupal 8.4.0.

> RuntimeException: Unable to determine class for field type 'webform' found in the 'field.storage.node.webform' configuration in Drupal\field\FieldStorageConfigStorage-\>mapFromStorageRecords() (line 157 of core/modules/field/src/FieldStorageConfigStorage.php).

How can I fix this error?

# Answer
One possible way is that your module is missing from the codebase or has been improperly uninstalled and you've still a field which is using that missing module.

Try the following `drush`/SQL commands to remove the broken field:

```
drush sqlq "DELETE FROM cache_config"
drush sqlq "DELETE FROM config WHERE name = 'field.storage.xxx.xxx' OR data LIKE '%field.storage.xxx.xxx%'"
drush sqlq "DELETE FROM config_snapshot  WHERE name = 'field.storage.xxx.xxx' OR data LIKE '%field.storage.xxx.xxx%'"

```

***Warning****: Don't execute above commands on master/live database. Make a backup before doing any database changes.*

Where `field.storage.xxx.xxx` is your reported field storage type (e.g. `field.storage.node.webform`).

If above won't help, check for any other references by:

```
drush sql-dump --ordered-dump | grep field.storage.xxx.xxx

```

At the end you need to rebuild your caches:

```
drush cr

```
> 52 votes

# Answer
I had a similar error with another module (address in my case). I could fix it by simply re-install the concerned module with drupal console by the following command:

```
drupal module:install address

```

And back to business :)
> 3 votes

# Answer
When I see that error my trick is to try enabling the offending module again from the command line and then clearing cache. For example:

```
lando drush cr

In FieldStorageConfigStorage.php line 174:

  Unable to determine class for field type 'simplenews_issue' found in the 'field.storage.node.simplenews_issue' configuration

In DiscoveryTrait.php line 53:

  The "simplenews_issue" plugin does not exist. Valid plugin IDs for Drupal\Core\Field\FieldTypePluginManager are: address, address_zone, address_country, comment, datetime, file_uri, file, image, link, list_float, list_string, list_integer, path, text_
  with_summary, text, text_long, integer, uri, entity_reference, uuid, float, email, timestamp, string, language, created, changed, map, string_long, password, decimal, boolean

lando drush en simplenews
 [notice] Already enabled: simplenews
lando drush cr
 [success] Cache rebuild complete.

```
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Change Image Alternative text on select box change
* Fields:

+ Image Field - field\_image
    + Selectbox Field - field\_custom\_language
* Testcase: On selecting a different value from Selectbox, Alternative text of the image field should be changed.
* Issue: Alternative text is not changed on ajax call.

```

    function custom_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
      $form['field_custom_language']['widget']['#ajax'] = [
        'callback' => 'AltChange',
        'event' => 'change',
        'wrapper' => 'custom-image-wrapper',
        'progress' => [
          'type' => 'throbber',
          'message' => t('Loading...'),
        ],
      ];
    }

    function AltChange(&$form, FormStateInterface $form_state) {
      $form['field_image']['widget'][0]['#default_value']['alt'] = $form_state->getValue('field_custom_language');
      $form['field_image']['widget'][0] = ImageWidget::process($form['field_image']['widget'][0], $form_state, $form);
      return $form['field_image'];
    }

```

# Answer
I don't think it can be done using AJAX with php, image field doesn't expose the alt as field with value to change it.
But there is a way to do it by using `custom Javascript in an AJAX callback` like the following:

```
/**
 * Implements hook_form_alter().
 */
function MODULENAME_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['field_custom_language']['widget']['#ajax'] = [
    'callback' => 'AltChange',
    'event'    => 'change',
    'wrapper'  => 'edit-field-image-wrapper',
    'progress' => [
      'type'    => 'throbber',
      'message' => t('Loading...'),
    ],
  ];
  // Add library.
  $form['#attached']['library'][] = 'MODULENAME/alter-alt-image';
}

```

and the callback function should be like:

```
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
function AltChange(array &$form, FormStateInterface $form_state) {
  // Get the language value.
  $lang_code = $form_state->getValue('field_custom_language')[0]['value'];
  $response = new AjaxResponse();
  $response->addCommand(new InvokeCommand(NULL, 'AltChange', [$lang_code]));
  return $response;
}

```

and Then create the library:
***MODULENAME.libraries.yml***

```
alter-alt-image:
  version: 1.x
  js:
    js/script.js: {}

```

and your Js script:
***MODULENAME/js/script.js***

```
(function($) {
  // Argument passed from InvokeCommand.
  $.fn.AltChange = function(argument) {
    // Set alt value to the passed arguments.
    $('input#edit-field-image-0-alt').attr('value', argument);
  };
})(jQuery);

```
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: Moving Exposed Views Filter into another region of the page
Is there any way to move the exposed filters of views into another region of the site? i.e. I want to have a Search functionality attached to the a view by exposing the "Search: Search Terms", but I want the search to reside to the right in the "Right Side Bar" region and not directly above or below the actual Views field display.

Or put another way: Is there a relatively straightforward method of replicating the Exposed Views Filter functionality of one View through another Block that resides on the same page? This way, the Block which would act as the filter "controller" would reside separately from the View on a different region of the page.

# Answer
> 8 votes
There is a module called 'Views Better expose filters' which allows you to create blocks from view exposed filters.

Project can be found at: http://drupal.org/project/better\_exposed\_filters or drush dl better\_exposed\_filters; drush en better\_exposed\_filters

There is also some excellent documentation at http://drupal.org/node/766974

# Answer
> 1 votes
You don't need any module. Edit the view \> Advanced \> Exposed form in block. Put: Yes.

You can now add the filter in Structure as a block.

---
Tags: 7, views, theming
---


# Question
Title: How can I hide nodes from view, but open access to JSON:API at the same time?
I would like to use Drupal as a decoupled system, sourcing its content by using Gatsby. Having set it all up, I would like my Drupal nodes not to be accessed by random unauthenticated users so I removed the permission from 'View Content'.

Having done that now I can't access the content by my Front end service which uses JSON API (unauthenticated of course).

What's the method to remove the node pages from the site and leave only the admin backend, while allowing to access the content using JSON API ?

# Answer
> 2 votes
If you're working with unauthenticated consumers, the Rabbit Hole module has the means to disable `node/*` routes without using the user role/permission system.

The Rabbit Hole module has a sub-module *Rabbit Hole nodes* that, when enabled, will let you disable `node/*` routes. This should leave open your `jsonapi/*` endpoints to anonymous consumers.

# Answer
> 1 votes
Another solution I found was to remove the 'view published content' permission for anonymous users, and activate the Basic Authorisation module to use for JSON API requests.

---
Tags: nodes, 8
---


title: What is the URL for the login form?

text:
# Question
Title: What is the URL for the login form?
I am trying to log in on a Drupal site, but the site doesn't have the login block enabled.

How can I find the URL for the login form?

# Answer
Drupal default login URL format,

**example.com/user**
> 4 votes

# Answer
You can also check http://example.com/?q=user/login if the clean url is not enabled.
> 2 votes

# Answer
If nothing is working, then there is a possibility that the user has overridden the `user.tpl.php` for that you can use

# http://example.com/user/login

same way for directly resetting the password you can access `user/password` and for getting logged out directly from a Drupal site if you're unable to find any option then you can use `user/logout`

Cheers!
> 1 votes

# Answer
With Drupal, if the login block isn't shown in any page, you can see the login form visiting the user/login path. If you are already logged in, Drupal will return a 403 error, since only users who still have to log in can access that page.
If you visit http://example.com/user (replace example.com with the domain of your site), you will see your user profile page, if you are logged in, or you will be redirected to the login form, if you aren't logged in.

If clean URLs aren't enabled, the login form will be visible on http://example.com/?q=user/login, while the user profile page will be visible on http://example.com/?q=user. (Replace example.com with the domain of the Drupal site.)
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: How to check if current page is a group entity?
Im using drupal 7 and group module

I am trying to run some code only if the current page is a group.

here is my code

```
<?php
$arg = arg(0);
$arg1 = arg(1);
global $user;
if($arg ='group' && is_numeric($arg1)) {
    $group = group_load($arg1);
    if($group->getMember($user->uid)) {
       print ('user is member');
    };
};
?>

```

If this is placed on a group page it will print user is member if the current user is a member. If the current user isn't a member it will not show anything. Which is what it is supposed to do.

If I navigate to a none group page I get an error 'Error: Call to a member function getMember()', but the if statement should prevent this?

How do I check if the current page is a group entity?

Thanks

Edit

I wanted to return true if a group page and user is a member of the group. Using menu\_get\_object by Jaypan I used the code below to show. Im checking if page is group if so loading the group then checking if the user is a member of the group.

```
if (!empty(menu_get_object('group')))
   {
   $group = group_load(arg(1));
   if($group->getMember($user->uid)) {
       return TRUE;
    }
}

```

# Answer
You can get the object for the current page in Drupal 7 using menu\_get\_object().

```
if ($group == menu_get_object('group')) {
  // do something with $group
}

```
> 0 votes

# Answer
checking if page is group if so loading the group then checking if the user is a member of the group.

```
if (!empty(menu_get_object('group')))
   {
   $group = group_load(arg(1));
   if($group->getMember($user->uid)) {
       return TRUE;
    }
}

```
> 0 votes

---
Tags: 7, group
---


# Question
Title: Provide unique values from a user profile field in a content type field (How to use DISTINCT in ER View)?
My users profiles contain a field with department name.

**How can I make the unique values from department available in a select list within a content type field?** i.e. Sales, Marketing, IT, etc. (to avoid duplicates).

UPDATE:

I created **Entity Reference** \> Select List \> User (target type) + a view with ER that contains the user profile field department, but **Query settings DISTINCT** still doesn't get rid of the duplicates.

I even tried views\_distinct module with Filter Repeats.

# Answer
> 0 votes
Try using aggregation. Set this value in your View under Advanced \> Use aggregation. The **Group Results Together** aggregation type should be the default and should provide the behavior you're looking for.

If this isn't quite what you're looking for, please export a copy of your view configuration, from Configuration \> Development \> Configuration synchonization \> Export, then select Single and find your view under the Views dropdown and update your question with this export.

---
Tags: views, entities
---


title: Help with hook_form_alter

text:
# Question
Title: Help with hook_form_alter
So I've got a custom module that builds a page (/simple-ajax-form) and has a form on it with the ID "payment\_form" and other fields with IDs like "number\_1". My module name is "Drupalup Simple Custom Form" for reference.

The problem I can't figure out (as I'm new to hook\_form\_alter) is that on the form ID instead of it being "payment\_form" the ID gets rendered as "payment-form" and then on the input fields instead of it being "number\_1" the ID get rendered as "edit-number-1".

What code do I need to make the form render as "payment\_form" and inputs without "edit" and to also have underscores? And where does this code go - in my custom module?

# Answer
Figured it out - put it the ID request in to an array:

`$form['#attributes'] = array('id' => array('payment_form'));`

Instead of

`public function getFormId() { return 'payment_form'; }`
> -1 votes

---
Tags: forms
---


# Question
Title: Is the path_alias table queried for all URLs?
I'm trying to generate SEO-friendly URLs for a set of exposed filters. For e.g.:

`/analyst-relations/firm?related_firm=5072` would look like

`/analyst-relations/firm/forrester`

one way I imagined doing it was by adding/updating/deleting this path programmatically to the path\_alias table upon creation/modification/deletion of the relevant term or entity. However I seem to have misunderstood how path\_alias works. I was able to successfully add the path `/analyst-relations/firm?related_firm=5072` and the alias `/analyst-relations/firm/forrester`, but the exposed filter links still load like the former. Is the path\_alias table not queried for all URLs? If not, is it possible to somehow 'attach' this path and alias to an entity?

EDIT: I'm using Better Exposed Filters to exposed the filters as links, so afaik there is no form submission

# Answer
While @Clive's comment is in most cases correct, from a SEO perspective it can make sense to expose certain filters as links and make them searchable through Google. Path aliases are implemented in AliasPathProcessor. Since the core alias lookup system can't handle query parameters and you can alias without a lookup table by querying the entity data directly, you could add your own path processor. Inbound you have to change the path to the internal path and add the query parameter to the request, outbound vice versa (but use $options to remove the query parameters because this is for all outgoing links, don't use the request).
> 2 votes

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


# Question
Title: How to return a user's group access permissions?
I am trying to block a user from accessing certain content/blocks if they do not have permission to view content of a certain type within a group.

I have the user ID and the group ID, but how do I check the user's permissions for that group? I can't find any documentation.

To start, how would I print all the permissions for a given user and group?

# Answer
> 0 votes
The Group class has a userHasPermission() method you can use. So something like this:

```
if ($group->userHasPermission($user->uid, 'some permission')) {
  // do something.
}

```

# Answer
> 0 votes
Assuming that `$gid` contains the group ID and `$uid` contains the user ID, you can get the list of the permission names that user has on the group using the following code.

```
$group = entity_object_load($gid, 'group');
$permissions = $group->userPermissions($uid);

```

`$permissions` will contain an array with all the permission names.

---
Tags: 7, group
---


# Question
Title: Constraint doesn't attach from BundleFieldDefinition, but does from entity_bundle_field_info_alter()
I'm adding a trait to Commerce Product Variations, which applies the following

```
  public function buildFieldDefinitions() {
    // Builds the field definitions.
    $fields = [];
    $fields['plan_code'] = BundleFieldDefinition::create('string')
      ->setLabel(t('Recurly Plan Code'))
      ->setDescription(t('The Plan Code of the related Recurly plan.'))
      ->setCardinality(1)
      ->setRequired(TRUE)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', FALSE)
      ->addConstraint('RecurlyPlanCodeExists', []);
    return $fields;
  }

```

The `plan_code` field appears on product variations as expected when the trait is enabled, but the field is not validated against `RecurlyPlanCodeExists` when the entity is saved. However, if I add the constraint via hook, as in the following, the constraint is attached and validation runs as expected.

```
/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function commerce_recurly_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
    if ($bundle === 'recurly_plan_variation') {
      if (isset($fields['plan_code'])) {
        $fields['plan_code']->addConstraint('RecurlyPlanCodeExists', []);
      }
    }
}

```

Inspecting `$fields['plan_code']` in the above hook confirms no constraints exist on the field prior to adding `$fields['plan_code']->addConstraint('RecurlyPlanCodeExists', []);`. Interestingly, `$fields['plan_code']['description']` is also an empty string despite being defined in the `BundleFieldDefinition`. I'd assume that these are related. Any idea what the cause might be?

I've already tried deleting all existing variations and disabling/re-enabling the trait and it's had no effect.

EDIT: I just realized that the docs refer to adding constraints to `BaseFieldDefinition`, while I'm using `BundleFieldDefinition`. Maybe this is the reason?

# Answer
Yes, both are different. In core the system to define bundle fields in code is broken from the beginning. Commerce did implement their own system (entity traits), but although it looks like the fields are defined in code, in reality they are not. Commerce adds them to config and doesn't transfer constraints in this process.
> 2 votes

---
Tags: 8, commerce
---


# Question
Title: How can I pass display exposed filter in views-view-unformatted.html.twig?
I would like to display an exposed filter inside views-view-unformatted.html.twig rather than views-view.html.twig due to specific UI design?

# Answer
Try using Views Exposed Filter Blocks.

* Use the Twig Tweak module and embed the exposed filter block in your template with code like this: `{{ drupal_block('views_exposed_filter_block:my_view_id-my_views_block_id', wrapper=false) }}`.
* You can also just place the exposed filter block in any region.
> 4 votes

---
Tags: views
---


title: Using entityQuery on node templates

text:
# Question
Title: Using entityQuery on node templates
I've been working with entityQuery in preprocess\_node hook in theme file. On a view page I can run the below query and it will return the latest 3 created articles(nodes) from a specific content type. On each specific article(node template) page I would like to use a similar query that will return the latest 3 articles within each. Is there a difference between using this on pages (page.html.twig) as opposed to (node.html.twig)? I basically created a variable to add to the template that returns 3 nodes.

```
  $query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'article')
    ->pager(3)
    ->range(0, 2)
    ->sort('created', 'DESC');

  $nids = $query->execute();
  $nids = $nids;
  $view_mode = 'teaser';

  if (!empty($nids)) {
    $nodes = Node::loadMultiple($nids);
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder(reset($nodes)->getEntityTypeId());
    $nodes_views = $view_builder->viewMultiple($nodes, 'teaser');
  }
  $variables['article'] = $nodes_views;

```

# Answer
Drupal 8 ships with a view called **Recent content** that displays the most recent Node content on your site. You can edit or clone this view for your purposes. I recommend cloning the view.

I think you would also benefit from a tutorial on using contextual filters. Here's one to get you started: https://redcrackle.com/blog/adding-contextual-filter-view-drupal-8
> 0 votes

---
Tags: 8
---


# Question
Title: I am getting an error "Notice: Undefined index: distribution_name in drupal_install_profile_distribution_name() ". How do I fix this?
I am using Drupal 7.69. I log in and go to my modules page and get the following error:

> Notice: Undefined index: distribution\_name in drupal\_install\_profile\_distribution\_name() (line 207 of /var/www/html/includes/install.inc).

According to this page: https://www.drupal.org/project/drupal/issues/1170362, you're supposed to run the following update SQL statement to set the correct status: `UPDATE system SET status=1 WHERE name='standard';`

My problem is in my system table I don't have any record with name equal to "standard". How do I add it?

# Answer
> 0 votes
After seeing the results of drupal\_get\_profile() and querying for that value in the system table, the result of the query showed that the profile's files were (supposed to be) in:

```
/var/www/html/profiles/[profile name]/

```

However, that folder path did not exist. Since Drupal could not find the profile's files in that folder path, it could not set a distribution\_name.

I found the correct profile files in my original download from way back in the day, re-uploaded them to the correct directory on my server and cleared the cache. The message disappeared.

---
Tags: 7
---


# Question
Title: Contextual filter doesn't work with the name of the entity reference, it only works with its ID
why is the contextual filter below only working the the id of the entity reference ID? I would to search by name like by "Oceanography" or "Ecology and Evolution", but i'm not sure how. If i add a relationship the contextual filter doesn't even work with the ID number. Please help. Thanks in advace.

# Answer
Like Drupal 7 this configuration should work for you :  But for some reason it doesn't work, so your alternative is Views Taxonomy Term Name Depth module if you are working with **Drupal 8.6 or higher version**:\`\`

1. Install and enable the module.
2. Add contextual filter **Content: Has taxonomy term name with Depth**
3. Save your changes.
> 0 votes

---
Tags: views, 8
---


# Question
Title: entity:file:undefined" plugin does not exist upload using curl to jsonapi
I'm using php\_curl to POST a binary image to my local D8.8 app but it keeps returning a 500 error:

> The "entity:file:undefined" plugin does not exist. Valid plugin IDs for Drupal\Core\TypedData\TypedDataManager are: helpful list of D8 entities.

Using the example "Flow 1" from this doc page, I started out with this:

```
     $binary = file_get_contents('Wilson.jpeg');
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,'http://localhost/jsonapi/node/doctor/field_photo');
      curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
      curl_setopt($ch, CURLOPT_USERPWD, "admin:mypwd");
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_VERBOSE, 1);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $binary);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/octet-stream',
        'Accept: application/vnd.api+json',
        'Content-Disposition: file; filename="Wilson.jpeg"',
        ));
      curl_setopt($ch, CURLOPT_POSTFIELDS, $binary);
      $result = curl_exec($ch);

```

Searching I read that D8 is more strict about entity bundles, I can report that my field\_photo for the doctor content type is instantiated as an image. Examining my app's /admin/structure/file-types/manage/image/edit I can see in the Known Mime Types section that application/octet-stream and image/jpeg exists and standing by. Rereading the error Drupal seems to perceive that this is a file but isn't clear what kind it is. I thought I was being clever and changed the Content Disposition from 'file' to 'image' but no such luck. Exact same error returned. Swapping it out to one of the suggested to 'entity:file:image' did not change the error message. It suggests to me that I need to do something in this curl header to prompt Drupal to understand that this is a file that has a plugin established for it.

Digging into the stacktrace I see that it's generating "entity:file:undefined" because the Bundle property for this entity is "undefined". Working backwards, in context of the doctor node definition, the field passes through the MimeTypeGuesser class has figured out that it is a jpeg and its attributes. But this gets lost when passed to the TemporaryJsonapiFileFieldUploader where it attempts to validate the File.

I've attempted adding "application/octet-stream" as a second entry underneath the "image/\*" on the /admin/structure/file-types/manage/image/edit page but nothing changes. How should I associate its bundle to "image" so that I end up with "entity:file:image" and I can move on?

One thing that bothers me is that file uploading was added to the 8x-2.x branch and I'm reading that it is part of core. I'm on 8.8.5 and am assuming I have the latest after running composer update. I've checked some of the file diffs on jttps://git.drupalcode.org/project/jsonapi/ and it appears the files I'm working on are current, but it bothers me that I haven't resolved this. The json output from this module returns "jsonapi":{"version":"1.0" which is an indicator of the external jsonapi specification, not the drupal module.

# Answer
> 0 votes
The usual troubleshooting step when it seems to work for others is to spin up a minimal D8 app and see if it occurs there. The minimal app worked as expected, which points to a module conflict. For me, the contrib module file\_entity was causing this trouble. It took several efforts to get it uninstalled, and only by following the #8 comment on https://www.drupal.org/project/file\_entity/issues/3060204 where I try to install it would I be able to finally uninstall it.

---
Tags: 8, entities
---


# Question
Title: Confirmation message not getting rendered when printing the elements seprately in twig and ajax is enabled
Iam using the following twig code in webform-submission-form--newsletter-signup.html.twig

```
                        <div class="col-12 col-sm-12 col-md-6">
                            {{ form.elements.url }}
                        </div>
                        <div class="col-12 col-sm-12 col-md-6">
                                {{ form.elements.email }}
                        </div>
                        <div class="col-12 col-sm-12 col-md-12 mt-3 text-center">
                         {{ form.elements.actions }}
                        </div>

                    {{ form.form_build_id }}
      {{ form.form_token }}
      {{ form.form_id }}

```

and Iam using the following code in webform--newsletter-signup.html.twig

```
 <form{{ attributes.addClass('subscribe-form') }}>
  <div class="row">

  {{ title_prefix }}
  {{ children }}
  {{ title_suffix }}
  </div>

</form>

```

When I try to use the default webform templates the message gets displayed after ajax request infact the message is returned as part of the data in response but when I use these templates the message is not present in ajax response what am I doing wrong here please help

# Answer
> 0 votes
You need to still include `{{ title_prefix }}` and `{{ title_suffix }}` in your template

In the comments in the default webform.html.twig it gives a short description of the default variables "Additional output populated by modules" which includes essentially anything else apart from the form elements themselves

---
Tags: 8, ajax, webforms
---


# Question
Title: HTML tags being removed after theme_preprocess_node
I am using theme\_preprocess\_node to modify an HTML tag, but the tag is being stripped somewhere in the theme layer.

mytemplate.twig

```
{% if node.field_embedded_media.value %}
  {{ content }}

```

mytheme.theme

```
    function mytheme_preprocess_node(&$variables) {
      if ($variables['view_mode'] == 'ebook_export') {
        $contentBody = $variables['node']->get('body')->value;

        $pattern = '/<drupal-media/';
        $replace = '<drupal-media data-view-mode="markdown_link"';
        $contentBody = preg_replace($pattern, $replace, $contentBody);

        $variables['content']['body'] = array(
            '#markup' => $contentBody
          );
        }
     }

```

Original input (node body value):

```
<drupal-media data-align="center" data-entity-type="media" data-entity-uuid="269d4491-9866-403c-90e3-c1298e9857de"></drupal-media>

This is some text.

<drupal-media data-align="center" data-entity-type="media" data-entity-uuid="269d4491-9866-403c-90e3-c1298e9857de"></drupal-media><pre>

This is some more text.

```

dpm($contentBody) in mytheme\_preprocess\_node (this is what I want to output, and it's correct here)

```
<drupal-media data-view-mode="markdown_link" data-align="center" data-entity-type="media" data-entity-uuid="269d4491-9866-403c-90e3-c1298e9857de"></drupal-media>

This is some text.

<drupal-media data-view-mode="markdown_link" data-align="center" data-entity-type="media" data-entity-uuid="269d4491-9866-403c-90e3-c1298e9857de"></drupal-media>

This is some more text.

```

Actual HTML output on page render (this is what I get, and the `<drupal-media>` tags are gone)

```
This is some text.

This is some more text.

```

The `<drupal-media>` tags got stripped. How do I prevent them from being stripped? I don't understand enough about the theme layer to determine where this is happening.

# Answer
> 3 votes
As described in Render API overview, the value passed in `#markup` is sanitized via `\Drupal\Component\Utility\Xss::filterAdmin()`. You can eventually pass the tags not to filter via the `#allowed_tags` properties, but the tag attributes could still be sanited.

To have full control on what it is sanitized, you should use `#theme` or `#type` instead of `#markup`. (The first is my choice when the markup is rendered only in a single place/page. Alternatively, you could also use `#inline_template` as in the following example code taken from the documentation page.

```
$build['hello'] = [
  '#type' => 'inline_template',
  '#template' => "{% trans %} Hello {% endtrans %} <strong>{{name}}</strong>",
  '#context' => [
    'name' => $name,
  ],
];

```

It allows to use any Twig filter Drupal core can use and to have full control over the rendered tags.
It's the easier alternative to `#theme` which doesn't require to implement `hook_theme()` nor putting the template content in a separated file. (If you need to reuse the same inline template in different pages, or the template content is rather complex, using `#theme` is still preferable.)

---
Tags: 8, theming
---


# Question
Title: How to make private (hidden) node path aliases?
The site (Drupal 7) has regular nodes that are publicly visible via standard node alias (`node/<nid>`). I need to be able to create hidden (private) node aliases that are random (e.g., `node/9s8d0a8z9d`) which will allow the person who has the URL to access the node.

User who accesses the node via random node alias should not be able to see the node id in URL hence the required feature. The main purpose of private URL is to make them expirable. It's ok if user gets to know the node id by digging the site once it gets there, I need to make the node alias obscure just in the URL itself.

I can create multiple node aliases with path and pathauto modules but one of random aliases will eventually be set as default alias which will be visible as node URLs in views or in Content page which is not desired.

Are there Drupal modules that can provide this functionality?

# Answer
> 0 votes
There is different solutions

---
Tags: path-aliases
---


title: Render Image on Controller

text:
# Question
Title: Render Image on Controller
I have a controller that renders page elements. I have a php variable of type png image. What is the proper way to render it?

My code:

```
public function buildPage() {

    $page = [];

    $block_manager = \Drupal::service('plugin.manager.block');
    $config = [];
    $plugin_block = $block_manager->createInstance('my_custom_block', $config);

    $page['element_one'] = $plugin_block->build();

    $page['element_two'] = array(
      '#type' => 'markup',
      '#markup' => $this->t('This is the second page element'),
    );

    //How to render this on a third page element?
    $image = 'test.png'

    return $page;
  }

```

Thank you

# Answer
You can add the element using the image theme hook:

```
$page['element_three'] = [
  '#theme' => 'image',
  '#uri' => $image_path,
  '#alt' => $title,
  '#title' => $title,
  '#width' => $width,
  '#height' => $height,
];

```
> 0 votes

---
Tags: 8
---


title: Forgot password REST services_token

text:
# Question
Title: Forgot password REST services_token
I have picked up some work on a headless Drupal 7 site, using services, and service\_token.

Where the "normal" service login, as I understand it, uses a cookie to authenticate, Services Token allows authentication by passing a token as the username in a basic auth header.

All appears to work well. But I have been asked to implement "Forgot password", and I am struggling to understand how that flow fits with Services Token.

Any guidance most appreciated.

# Answer
> 2 votes
In Drupal 8 you can reset it by

```
curl  POST 'http://YOUR_SITE.URL/user/password?_format=json' \
--header 'Content-Type: application/json' \
--header 'Content-Type: application/json' \
--data-raw '{
    "mail": "USER_EMAIL"
}'

```

# Answer
> 1 votes
It's already built into the Services module, just enable its corresponding resource then do a **POST** `?q=[my-endpoint]/user/request_new_password.json` and send along a name, e.g.: `name=john` or an e-mail address: `name=john@example.com`

# Answer
> 0 votes
The solutions, a custom endpoint that takes the token as a password.

The problem we had was that the standard `services` authentication flow relies on cookies and that is a problem/pain when working with AngularJS (apparently).

Hence the use of `service_token`. An update to the two modules allowed for most of the login and forgot password flow. `service_token` for auth, and `services` for forgot password.

To handle the reset (noting that this was not a production site and this was not the most robust of solutions), we added a custom endpoint that took the `service_token` token as the "current password"

Hope that is of help to others.

---
Tags: 7, services
---


title: Modifying CKEditor toolbar at runtime

text:
# Question
Title: Modifying CKEditor toolbar at runtime
We have a requirement that our standard CKEditor toolbar omit a specific button on only one content type. It seems silly to create a brand new text format just for this. I'm able to modify the toolbar via a hook, but the modification gets saved and applied everywhere.

How can I programmatically modify the toolbar for just that content type?

# Answer
I think you will have to do this at the CKEditor level. See:

https://ckeditor.com/docs/ckeditor4/latest/guide/dev\_configuration.html#defining-configuration-in-page

On the Drupal side, this JS could be added by altering the content type edit form to add the JS.
> 0 votes

---
Tags: javascript
---


# Question
Title: How can I retrieve a user name and password?
Someone installed the drupal 8 site and did not share the password. I do not know what email he has used to install the site either. I do not have the password. In phpmyadmin, I clicked the database name. I ran the sql

```
UPDATE users SET pass = MD5( 'NewPassword' ) WHERE uid = 1;
Select * from users.

```

> # 1146 - Table 'xxx.users' doesn't exist

How can I retrieve the drupal 8 website password?

# Answer
Drupal does not store passwords, but rather password hashes. There is no way to recover the password. You can use Drush to either set a new password or generate a one-time log-in link:

* Reset PW: `drush upwd <username> --password="<password>"`
* One-time login-in link: `drush uli <username>`
> 1 votes

# Answer
Since you have access to the database, you can change the email for the superuser (uid: 1) to your email, in table users\_field\_data. Then follow the normal reset password link (user/password).

```
UPDATE `users_field_data` SET `mail` = 'user@example.com' WHERE `uid` = 1;

```

If you're getting an error that the users table doesn't exist, then you may have run the statement on the wrong database, or your tables may be prefixed, like `xyz_users_field_data`.
> 1 votes

---
Tags: 8, users, database
---


# Question
Title: The view is not filtering the duplicate nodes
i have a view which is not filtering the duplicated nodes and i tried couple of solutions but it looks like they are not working.

The code I am using is the following.

```
function mymodule_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'basicnews') {
    $unique_nids = $new_results = array();

    // Loop through results and filter out duplicate results.
    foreach ($view->result as $index => $result) {
      if (!in_array($result->nid, $unique_nids)) {
        $unique_nids[] = $result->nid;
        $new_results[] = $result;
      }

      // Replace $view->result with new array. Apparently views requires sequentially keyed
      // array of results instead of skipping keys (e.g. 0, 2, 4, etc), so we can't just
      // unset the duplicates.
      $view->result = $new_results;
    }
  }
}

```

Is there any patch or work-around for this issue?

# Answer
> 0 votes
You can handle most duplicate node issues using Views Aggregation options.

Go to advanced in the view and select "Use Aggregation"

Then in the fields area, set the aggregation settings. Generally, you just want the group together option with Entity ID as the group column. Sometimes you have to play around with other settings as well.

---
Tags: views
---


# Question
Title: Webform Module or hook_form_alter() - What is right for me?
I'm delving into my first custom Content Node Submission Form creation and looking at my first ever `hook_form_alter()` attempted efforts.
However, I'm confused over whether the WebForm module will do the job for me to allow user submission of new Node Content as I need to change the display of the said Node fields displayed. The way I read the WebForm documentation it's for emailed webforms and questionnaires, not really what I want but to submit new Node Content to the database, but others online say it can be used otherwise.

Would someone care to clarify before I waste another 2 hours effort?

Thanks in advance.

# Answer
Webforms generally are best as contact/survey forms or some variant of them.

For an application like this, in my opinion it is just easier to implement your own form and do your own validation and submission. The validate handler could evaluate if the data is valid, and then the submit handler could create a new Node, set values, and save it.

Technically, you could do that submit Node creation handler with Webform, but it isn't as practical to me. Plus, if you haven't learned the Form API, this is a good opportunity to do so!

If this is Drupal 7, you could also take a look at Entity Forms and Rules, but again in my experience, getting to the goal is just faster with your own form or two and coding in what you want.
> 0 votes

# Answer
It depends what your preferences are, and maybe also what you're most comfortable with.

If it was my choice, I'd go for an approach as described in the question "How to create a node from a Webform using rules?". All you'd need is the Webform Rules module (and a custom rule that fits your specs).
> 0 votes

# Answer
Little late to the game here,but in case anyone is still looking for answers, there is the Webform Content Creator module which will create a designated content type from a Webform. It can also link the webform submission to the node in terms of keeping the content of both of them synchronized if desired.
> 0 votes

---
Tags: forms, webforms
---


# Question
Title: Bypassing internal cache via query parameter
I'm attempting to bypass drupal's internal page cache and dynamic cache when a given url parameter is in a URL (as an anonymous user). The page in question is a view, and occasionally, when a user clicks a link to load that view, the URL has the associated query param. I've tried a number of different ways to add the cache context like below:

`$vars['#cache']['contexts'][] = 'url.query_args:dynamic_trials';`

I've added this in a `hook_preprocess_node`, I've added it in a `preprocess` on the view itself I've added it in a `function tibco_views_utils_views_pre_view` with a call to

`view->element['#cache']['contexts'][] = 'url.query_args:dynamic_trials';`

None of these have worked. I noticed this on one of the drupal docs pages:

`Note the Internal Page Cache assumes that all pages served to anonymous users will be identical, regardless of the implementation of cache contexts. If you want to use cache contexts to vary the content served to anonymous users, this module must be disabled, and the performance impact that entails incurred`

Is this true? There's no way to do what I'm trying to do above without disabling the internal page cache entirely?

# Answer
The Internal Page Cache is designed to serve database content requested by a URL (the entire URL including query string). It works as long as you don't have any dynamic component, for example time based, or client request data not included in URL or session cookie, like request headers or custom cookies.

The Dynamic Page cache works on a different level. It doesn't depend on the URL directly but on the matched route. Any code using contextual data from the request or the matched route has to declare these dependencies as cache metadata.

Your problem is custom code in a Views hook. The old style Views hooks have a very narrow scope while at the same time you can access the entire View. So not all code snippets you find are good practice. Better use the Views plugin system for custom code.

For the caching part the easiest way would be to use the code of the Views caching plugins already in core which you control through the advanced settings of the View. If you only have anonymous traffic already cached by the Internal Page Cache you could disable caching of the View without impacting performance. Either through the none caching plugin or the time-based plugin which gives you finer control.
> 1 votes

---
Tags: 8, caching
---


# Question
Title: Want to display the validation error message above the webform
I have a webform created in Drupal 8 using the webform module I have to submit the data to 2 different 3rd party API.

The scenario is I have to submit the data to the 1st API if there is no error response found then submit the data to 2nd API so now I have created a submit handler and attached the handler to the webform. Now the issue is when I got an error response message while submitting the data to 1st API and showing the message using `drupal_set_message()` function everything is working fine but the form validation js not loading at this point.

**The used code is like the below:**

```
drupal_set_message(t($msg), 'error');
$form_state->setRebuild(true);

```

can anybody help me with this?

# Answer
For form validation error messages you do not use the drupal\_set\_message() which by the way, it's deprecated.

> Deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead.

Back to my point, in forms you don't use the Drupal messager, instead you use the FormState::setErrorByName

```
$form_state->setErrorByName('field_name', t('Error Message'));

```
> 3 votes

# Answer
**you can put the validation messages above the webform by -**

---

1.put the generic element above the form

```
messages:
  '#type': status_messages

```

2.make sure the webform's status messages purge all messages using the below hook in a CUSTOM\_MODULE

```
function CUSTOM_MODULE_webform_element_alter(array &$element, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  if (isset($element['#type']) && $element['#type'] === 'status_messages') {
    $element['#pre_render'][] = 'CUSTOM_MODULE_webform_element_status_messages_pre_render';
  }
}

/**
 * Pre render callback to display status messages element.
 */
function CUSTOM_MODULE_webform_element_status_messages_pre_render($element) {
  // Replace the status messages placeholder with the rendered messages.
  // Calling drupal_get_messages(NULL, TRUE) will purge all messages, which
  // prevent the messages block from being displayed.
  // @see \Drupal\Core\Render\Element\StatusMessages
  // @see drupal_get_messages()
  $element = [
    '#theme' => 'status_messages',
    '#message_list' => drupal_get_messages(NULL, TRUE),
    '#status_headings' => [
      'status' => t('Status message'),
      'error' => t('Error message'),
      'warning' => t('Warning message'),
    ],
  ];
  return $element;
}

```
> 1 votes

# Answer
Drupal 8/9 version. Updated version of Wasim Khan solution.

1.Put the generic element above the form. https://SITEURL/en/admin/structure/webform/manage/WEBFORM\_ID/source

```
`messages:
  '#type': status_messages`

```

2.Make sure the webform's status messages purge all messages using the below hook in a CUSTOM\_MODULE

```
function CUSTOM_MODULE_webform_element_alter(array &$element, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  if (isset($element['#type']) && $element['#type'] === 'status_messages') {
    $element['#pre_render'][] = 'CUSTOM_MODULE_webform_element_status_messages_pre_render';
  }
}

/**
 * Pre render callback to display status messages element.
 */
function CUSTOM_MODULE_webform_element_status_messages_pre_render($element) {
  // Replace the status messages placeholder with the rendered messages.

  $messages = \Drupal::messenger()->all();

  $element = [
    '#theme' => 'status_messages',
    '#message_list' => $messages,
    '#status_headings' => [
      'status' => t('Status message'),
      'error' => t('Error message'),
      'warning' => t('Warning message'),
    ],
  ];
  return $element;
}

```

3.Also check your twig template, if you have it.
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: Change CSS class based on number (length) of entity reference items, in a paragraph entity
In my paragraph twig file `paragraph--call-to-actions.html.twig`, I want to render and build up the entity reference items (the child items from a certain Paragraph type).

There could be 3 or 4 items. Based on the `length` of the items (3 or 4) I want to change the markup/change a CSS class so I could have 3 or 4 columns.

In `paragraph--call-to-actions.html.twig` I could do something like:

```
{% if content.field_call_to_actions|length == 3 %}
  {# Build 3 column item markup here #}
{% elseif content.field_call_to_actions|length == 4 %}
  {# Build 4 column item markup here #}

```

But how do I loop through my entity reference items (Paragraph type items) so I can print all of the fields of my paragraph type?

Or is there a cleaner approach?

**Update:** I found a solution by extending `field.html.twig` to `field--paragraph--call-to-actions.html.twig` and in there:

```
{% for item in items %}

  <div class="card mx-6 md:mx-4 mb-6 md:mb-0
  {% if items|length == 3 %}
    md:w-1/3
  {% elseif items|length == 4 %}
    md:w-1/2 lg:w-1/4
  {% endif %}
  ">
    {{ item.content }}
  </div>

{% endfor %}

```

I can't use `loop.lenght` here because of the different breakpoints.

Can I write this more cleaner without duplicate classes (DRY)?

# Answer
I found a solution by extending field.html.twig to field--paragraph--call-to-actions.html.twig and in there:

```
{% for item in items %}

  <div class="card mx-6 md:mx-4 mb-6 md:mb-0
  {% if items|length == 3 %}
    md:w-1/3
  {% elseif items|length == 4 %}
    md:w-1/2 lg:w-1/4
  {% endif %}
  ">
    {{ item.content }}
  </div>

{% endfor %}

```
> 0 votes

# Answer
```
{% for action in paragraph.field_call_to_actions %}
    {{ paragraph.action.value }}
{% endfor %}

```
> 0 votes

# Answer
My suggestion is to use the Twig Field Value module.

```
{% for action in paragraph.field_call_to_actions %}
    {{ paragraph.action|field_value }}
{% endfor %}

```

or

```
{% for action in paragraph.field_call_to_actions %}
    {{ paragraph.action|field_value|render }}
{% endfor %}

```
> 0 votes

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


title: How to render a facet block?

text:
# Question
Title: How to render a facet block?
I've created a facet block according to this example Programatically render a block in a twig template

I've created the facet block as follows:

```
$variables['block_output'] = Drupal::service('plugin.manager.block')->createInstance("facet_block:topic")->build();

```

That works great, but I'm missing the block template itself on my page (the block around the facet links output). I need a custom suggestion for this block to format it. Unfortunately, the hook\_theme\_suggestions\_alter() doesn't detect this block. How can I add a file name suggestion?

Thank you!

# Answer
I'm using the module **Twig Tweak**, so you don't have to create a block, but you can add in in your twig file.

In my `views-view--view-id--page.html.twig` file I use it like this:

```
<div>
 {{ drupal_block('facet_block:facet_id') }}
</div>

```

Where the facet\_id is the machine name of my facet.
> 4 votes

---
Tags: 8, blocks, search
---


# Question
Title: How to install another module when a module is being installed
I have created a module (*travel\_list*) that uses the Field Group module. I want the *Field group* module to be automatically downloaded and installed whenever the *travel\_list* module is installed.

How can I achieve this?

# Answer
> 1 votes
With Drupal, a module doesn't download and install the modules from which it depends. Doing that would fail, as the system account used to run PHP should not have write access to the directory containing the modules. Letting PHP write files in the directory containing the modules, especially if those files contain PHP code, is considered a security issue.

Instead, modules declare their dependencies from other modules in their .info.yml file. In your case, the *travel\_list.info.yml* file would contain the following lines.

```
dependencies:
  - field_group:field_group

```

It should also declare its dependencies from Drupal core modules. For example, in the case it also depends from the *Search* module, it should contain the following lines.

```
dependencies:
  - drupal:search
  - field_group:field_group

```

# Answer
> 3 votes
If a module depends on another module, you have to declare it as a dependency. The way Drupal handles this, is through the \*.info.yml files, which define the basic module attributes.

In 'travel\_list.info.yml' add this key:

```
dependencies:
  - field_group:field_group

```

Doing that, whenever you install the module 'travel\_list' it will enforce you to install 'field\_group'; this means that if you try to install 'travel\_list' module and 'field\_group' is not installed, the installation will abort reporting that 'field\_group' module is needed.

Developing an script that downloads and triggers the module installation is far away from good practices and can lead to a number of unpredicted situations, starting by the fact that the required modules of your Drupal are defined in the composer.json.

---
Tags: installation
---


title: 403 on creating a node via rest api

text:
# Question
Title: 403 on creating a node via rest api
I have an issue with creating a node via rest API. I have the correct permissions setup but it seems like a glitch somewhere in the permissions. An admin can create a content but no other role can.

`{content_type}: Can create new content` permission is checked.

Getting access denied error along with the username in the logs.

Config:

Client:

```
return api({
    method: 'post',
    url: 'node?_format=hal_json',
    data: JSON.stringify(_node),
    headers: {
        'Content-Type': 'application/hal+json',
        'X-CSRF-Token': _xscrf_token,
    },
});

```

# Answer
Url should be `/entity/node?_format=hal_json`
> 0 votes

# Answer
Make sure you check the correct permissions for the roles you want in the "RESTful Web Services" section on the /admin/people/permissions page.
> -1 votes

---
Tags: nodes, 8
---


# Question
Title: Where do I find the vocabulary ID ($vid)?
In Drupal 6 I would go to the taxonomy section of my /admin and I'd be able to find the $vid (numerical) in the URL.

In Drupal 7 (no doubt due to the introduction of terms as entities) the URL is no longer as verbose (and some would say cleaner) as it now shows the machine name (bundle name?) of the vocabulary as it can be seen in `admin/structure/taxonomy/my_vocabulary/edit`.

My end-game is to use taxonomy\_get\_tree($vid, $parent, $max\_depth, $load\_entities) to load my vocabulary, and work with it in glorious and plentiful ways, but alas this function does not accept a machine\_name but presumably prefers the numerical `$vid`.

I'll accept alternatives to load a full vocab tree (i.e. all terms and their relationships to each other), but I do think that this question should be answered directly for future generations to google.

# Answer
Actually you can use:

```
$vocab = taxonomy_vocabulary_machine_name_load('my_vocabulary');
$vid = $vocab->vid;

```
> 32 votes

# Answer
Following Manu, if you have command line Drush access, you could do:

```
drush php-eval '$tax=taxonomy_vocabulary_machine_name_load("main_site_structure");echo $tax->vid;'
```
> 10 votes

# Answer
I am using entity\_load() to load my vocab object, and recieve it's $vid.

The trick is to pass in `false` for the 2nd parameters (which is `$ids`) and then reference the `taxonomy_vocabulary` table in your mysql database to see what you can pass in as conditions. I chose to use the `machine_name` as you can see below:

```
$ids = false;
$conditions = array('machine_name' => 'my_vocabulary');
$vocab = entity_load('taxonomy_vocabulary', $ids, $conditions);

```

*If you know of a quicker/lighter way then please offer it here :)*
> 1 votes

# Answer
You can use manually examine the `{taxonomy_vocabulary}` table in the database, and then check the `vid` column.
> 1 votes

# Answer
**In D7**

If all you need is the vocabulary ID (vid) and you know the machine name, you can use:

```
$query = db_select('taxonomy_vocabulary', 'tv');
$query->fields('tv', array('vid'));
$query->condition('tv.machine_name', __VOCAB_MACHINE_NAME, '=');
$result = $query->execute();
$data = $result->fetchAssoc();
$vid = $data['vid'];

```

Small performance increase: ~0.0036489963531494 seconds to ~0.00030779838562012 seconds.

This, of course, could be tailored as needed. Just change the condition to what information you have.
> 1 votes

# Answer
If you inspect the "Edit Vocabulary" link the vid is in the ID attribute e.g. "edit-12-edit".
> 1 votes

# Answer
This is to load using entity field query as bojan mention:

```
$query = new entityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'taxonomy_vocabulary')
  ->propertyCondition('machine_name', 'my_vocabulary')
  ->execute();

if (empty($result['taxonomy_vocabulary'])) {
  return;
}

$vocabularies = taxonomy_vocabulary_load_multiple(array_keys($result['taxonomy_vocabulary']));
dpm($vocabularies);

```
> 0 votes

# Answer
This was the fastest way for me to see a list of all the vocabulary IDs via Drush:

1. Connect to your database with the Drush command
```
drush sqlc
```
2. At the mysql prompt, type
```
select * from taxonomy_vocabulary;
```
> 0 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: How do I fetch the user ID from the shipping profile?
I'm trying to get the User ID from Shipping Profile in Drupal Commerce using the following code, but eventually, $entity-\>getOwnerId() is returning me NULL in any case, if it's an authenticated user or admin it's giving me `0` as the UID.

```
function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'profile') {
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($entity->getOwnerId());
    }
}

```

# Answer
Shipping and billing profiles don't have a user ID, they are always anonymous because they belong to the parent entity (order/shipment), not the user.

Only address book profiles have user IDs.
> 2 votes

# Answer
Thanks for the heads-up @bojanz. Considering your response, I've found 2 possible solutions:

```
function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'profile') {
        $entity->setData('copy_to_address_book', TRUE);
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($entity->getOwnerId());
    }
}

```

More reasonable one:

```
function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'commerce_order') {
        $uid = $entity->get('uid')->target_id;
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($uid);
    }
}

```
> 0 votes

---
Tags: 8, users, commerce
---


# Question
Title: Updating 7 to 8, how to remove .less / scss files
I am updating a website from Drupal 7 to Drupal 8 and suddenly I see all these .less files influencing the style of the page. I found them in the theme's /srss directory (mytheme/srss/bootstrap/)

When I look at the current Drupal 7 version of the site, the navbar.less and navs.less files are not referenced.

On the Drupal 8 version of the site, I see navbar.less and navs.less styling the menu links. Turning off their attributes (in the browser only), specifically padding and margins, puts things back closer to where they are supposed to be.

Deleting or moving the \_navbar.less and \_navs.less files does nothing. Even after clearing the cache.

**How do I remove or neutralize these \*.less files from my site?**

# Answer
Seems the issue is completely different. The theme is based on bootstrap and In Drupal 7 the theme did not have a CDN provider option but in Drupal 8 it is defaulted to jsDelivr. The navbar.less and navs.less references came from the CDN stylesheet link. Changing the theme's CDN Provider to "None" removed the reference and these LESS file references are gone (as well as their styling). So it was a change in Bootstrap from Drupal 7 to Drupal 8 issue introducing the CDN (and about 20+ /core stylesheets).
> 0 votes

---
Tags: theming
---


# Question
Title: Using a Paragraph field value as a View filter
I am attempting to create a view and paragraph combination that allows for site authors to customize the content that they want to display.

**What is currently working:**

* Within my site is the content type of Article
* I have a view, called News, that is set up to display the published Articles.
* I created a Paragraph called Article Scroller (article\_scroller) that uses a Views reference field (field\_view\_ref\_news) to display the above view.

The above setup allows authors to add the News view to any page, such as a Basic Page or another custom content type. This is all working great.

**Where I'm stuck:**

I want to take this a step further and allow for the content author to define a filter for the view, such as a location. To do this, I added an Entity Reference field to my Article content type called "Location" (field\_location). This is populated with a value from a taxonomy list of states (e.g. Texas).

I then added this same field (field\_location) to my article\_scroller paragraph.

The idea is that an author would add Texas to an article, and then if they wanted to customize the view to show Texas articles only, they would also define this term within the paragraph.

From there, I'm not sure how to proceed. I'm pretty sure I need to add some kind of relationship and contextual filter here, but am struggling because the term/tid is not going to appear within the URL, and the options under "Provide default value" don't seem to be relating to what I want to do (at least, nothing I've tried from other posts and research has seemed to apply).

Another confusing thing is that I only have my one "field\_location" field, but within the view, it appears as two different fields - one under the "Content" category and the other under the "Paragraph" category, which makes sense, but seems to complicate the contextual filters even more as I have to choose between "Content: Location" and "Paragraph: Location".

I know that one alternative method would be to create a view page/block for each location, Texas, California, New York, etc. I am just hoping I can do something a bit more dynamic.

# Answer
Have you seen these Modules, i have not used them but they look like they do the job.

Otherwise you could preprocess your paragraph and render the view

```
function renderView($viewId, $displayId, $arguments)
{
    $result = false;
    $view = Views::getView($viewId);

    if (is_object($view)) {
        $view->setDisplay($displayId);
        $view->setArguments($arguments);
        $view->execute();

        $result = \Drupal::service('renderer')->render($view->render());
    }

    return $result;
}

```
> 0 votes

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


# Question
Title: How do I add CSS body classes for logged-in and logged-out users?
In Drupal 7 I would add a theme process function to add the body classes needed.

```
function template_preprocess_html(&$variables) {
  $variables['classes_array'][] = $variables['is_front'] ? 'front' : 'not-front';
  // Add a class that tells us whether the page is viewed by an authenticated user or not.
  $variables['classes_array'][] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';
}

```

In D8 this theme function exists but they don't have all the variables need for users.

# Answer
> 4 votes
Ok I think I figured this out as in Drupal 8 it uses TWIG to print the body classes for content types or users we need.

In the html.html.twig

```
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    user.hasPermission('administer')  ? 'isAdmin',
    user.getRoles()|join(' role_')
  ]
%}

```

Then make sure this line is added to the body classes

```
   <body{{ attributes.addClass(body_classes) }}>

```

So if the user is logged out we can use the role class to identify them.

```
   .anonymous { }

```

Or we can use the :not Css selector :not

```
   :not.user-logged-in {}

```

# Answer
> 2 votes
In html.html.twig and page.html.twig we have various variable available like `logged_in`, `is_front`, `is_admin` by default. Using these variables as condition we can add class to body tag. Some classes like `path-frontpage`, `page-node-type-*` are by default present in node and they is no need to add them explicitly.

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


# Question
Title: Does requiring core/drupal load jQuery in custom script files?
I am trying to understand a bit more about where and how jQuery is loaded in Drupal 8.

If I write a custom script file that will include some translation strings using `Drupal.t()`, I need to add `core/drupal` as a dependency.

I know we have a call for jQuery: `core/jquery`, but hoping to have a clear understanding.

Drupal core in places uses jQuery, does calling `core/drupal` include jQuery? When using `Drupal.t()`?

Is there a difference when doing so inside a custom behaviors wrapper?

The premise is if I write my scripts in vanilla js, will using `core/drupal` and/or behaviors still call any jQuery?

# Answer
No, core/drupal depends only from core/drupalSettings; using it will not load core/jquery. The definition of those libraries is contained in core.libraries.yml, where you can see their dependencies.

```
drupal:
  version: VERSION
  js:
    misc/drupal.js: { weight: -18 }
    misc/drupal.init.js: { weight: -17 }
  dependencies:
    - core/drupalSettings
  drupalSettings:
    suppressDeprecationErrors: true

drupalSettings:
  version: VERSION
  js:
    # Need to specify a negative weight like drupal.js until
    # https://www.drupal.org/node/1945262 is resolved.
    misc/drupalSettingsLoader.js: { weight: -18 }
  drupalSettings:
    # These placeholder values will be set by system_js_settings_alter().
    path:
      baseUrl: null
      scriptPath: null
      pathPrefix: null
      currentPath: null
      currentPathIsAdmin: null
      isFront: null
      currentLanguage: null
    pluralDelimiter: null

```
> 1 votes

---
Tags: 8, javascript
---


# Question
Title: How do I strip spaces from a Twig variable?
Example code I'm working with:

```
<a{{ attributes.addClass(classes, 'field__item') }} name="{{ item.content }}">{{ item.content }}</a>

```

In this example, I have created a Brick with a field called anchor\_id. The idea is that content creators can name an anchor whatever they want, and then add that brick to a page.

I can get the field to show up fine. But, I'd like to strip out spaces so if they enter "my awesome tag" it instead gets rendered as `name="myawesometag`.

I've tried a few methods, but can't seem to figure it out. Seems like it would be some simple filter, but if it is I'm not seeing it.

Thanks in advance!

# Answer
> 4 votes
You can use "replace" - much like you would in PHP - and replace the space with no space

```
{{ anchor_id|replace({' ': ''})

```

More info: https://twig.symfony.com/doc/3.x/filters/replace.html

---
Tags: theming
---


title: hook_user_insert not being called

text:
# Question
Title: hook_user_insert not being called
I've got a custom module `weekly_digest` and I want to make it so each new user is added to a table with info on their subscription preferences.

I've been using the admin UI to add the users to test, unsure if that effects things but I don't see why it would.

As some context, in my .module I currently have `weekly_digest_node_insert` and that works just fine.

And here is the function which does not get executed and I can't get Xdebug to catch it either:

```
function weekly_digest_user_insert(UserInterface $entity) {

  $query = Drupal::database()->insert('weekly_digest_user_preferences');
  $query->fields([
    'uid',
  ])->useDefaults([
    'new_posts',
    'digests',
  ])->values([
    $entity->id(),
  ])->execute();

}

```

Most search results returned "Can't in theme" or "Drupal 7" so I was unable to figure this out.

# Answer
> 2 votes
It could be that you are using the incorrect argument. `hook_ENTITY_TYPE_insert` is a generic hook, it's not opinionated about what entity you are "inserting" (E.g. it could be a node, taxonomy, user...)

Try:

```
function weekly_digest_user_insert(\Drupal\Core\Entity\EntityInterface $entity) {
  // Do stuff.
}

```

---
Tags: 8, users, hooks
---


# Question
Title: How can I programmatically copy all blocks of a given theme into the same regions of a new theme?
I would like to switch admin themes from a core theme (seven) to a custom sub-theme so I can add some customization without hacking core.

When I install the new sub-theme it creates all the block placement settings and leaves them header or content. I haven't changed any regions between the two themes, and just want to copy all the blocks from the seven theme to the current theme. I know I can check block settings with block plugin manager (`plugin.manager.block`) but I don't know what blocks to edit. I would like to know how to get a list of all the blocks from the old theme and copy all the placement to new theme programmatically.

# Answer
You can entity query your relevant block config then create a cloned entity object via `Block::createDuplicateBlock()` then modify the sub-theme clones before saving the new block config into sub-theme region.

For example:

```
$block_ids = \Drupal::entityQuery('block')->condition('theme', 'my_base_theme')->condition('region','my_region')->execute();
foreach ($block_ids as $block_id) {
  $parent_block = \Drupal\block\Entity\Block::load($block_id);

  $new_id = str_replace('my_base_theme', 'my_sub_theme', $parent_block->get('id'));
  $child_block = $parent_block->createDuplicateBlock($new_id, 'my_sub_theme');
  // @TODO: set other properties that might need to be unique to this new theme's block

  $child_block->save();
}

```
> 2 votes

# Answer
I have done this before but it's been a while. First, make sure the regions match between your two themes. I think this is what I did:

* Export configs:

```
$ drush cex

```
* Use text editor to locate all of the config files that start with `block.block...`.
* Run a bulk find `theme: seven` and replace with `theme: subtheme`.
* Delete the `uuid: ...` line from each of the updated config files.
* Import configs:

```
drush cim

```
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: How can I have editors select which blocks to be displayed in what order per page?
I have taken on a site that has hard coded page urls in it's page.html.twig for loading specific sidebar blocks based on the url for related content. eg:

```
  {% if 'frozen' in url|render|render %}
              {# shows these blocks and in this order #}
              <aside id="sidebar">
                  {{ block_chooserecipes }}
                  {{ block_healthbenefits }}
              </aside>

```

Is there a way to create a content type field that will load the sidebar blocks that the editor wishes to include with their main content?

# Answer
> 1 votes
You can have a checkbox field for sidebar block in your content type. Once user selects a set of block to be visible, check those checkbox values in your page.html.twig. Print only those blocks which are checked by user.

# Answer
> 0 votes
First you can create an entity reference field node -\>\> blocks. Then, create a custom Block visibility condition, like for example web/core/modules/language/src/Plugin/Condition/Language.php Where you can check if the block belongs to the node you are in at the moment.

---
Tags: 8, theming, blocks
---


# Question
Title: In hook_form_alter how can I attach libraries on frontend only?
I'm trying to attach a js file to a form using hook\_form\_alter() but I don't want to js to be loaded on the administration template.

How can I achieve something like this? With what do I need to replace the `THEME != ADMINTHEME` part in the following code snippet?

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (($form_id == 'node_CUSTOM_edit_form' || $form_id == 'node_CUSTOM_form') && THEME !== ADMINTHEME) {
    $form['#attached']['library'][] = 'MYMODULE/myLib';
  }
}

```

# Answer
> 0 votes
To answer your question, you can get the active theme name using below code in module file.

`$activeTheme = \Drupal::service('theme.manager')->getActiveTheme()->getName()`

and check if `$activeTheme !== 'Your admin theme'`.

**Recommended way:**

In your case as you want to add library specific to theme, it should be added in theme file and not module file.

---
Tags: 8, theming
---


title: My custom CSS is not taken into account

text:
# Question
Title: My custom CSS is not taken into account
I add a CSS file (mymovies.css) to a custom form (SeenMovies) in a custom module (eric) with this code I inserted at the end of `buildForm`

```
$form['#attached']['library'][] = 'eric/mymovies';

```

and this code in `eric.libraries.yml`

```
mymovies:
  version: 1.x
  css:
    theme:
      css/mymovies.css: {}

```

But my css doesn't override `bootstrap.min.css` as you can see in Firefox inspector:

How can I fix that?

# Answer
Finally, I used the advice from @leymannx and changed my css to

```
#seen-movies hr{
  margin-top: 0px;
  margin-bottom: 0px;
  border-top: 1px #808080 solid;
}

```

where 'seen-movies' is my form id.
> 1 votes

# Answer
This question has nothing to do with Drupal but with CSS order of precedence. If more than one identical CSS rules are found, the last one takes precedence.

As @leymannx pointed in their comment, your page is loading first your CSS file, then Bootstrap. Just move your Bootstrap into a new library as you just did with 'mymovies', then add a dependency to 'mymovies'. Declaring it as a dependency, it will load first the need libraries, then the library being called.

**Edit - after saying you are using OnePage Zymphonies theme:**

If you check 'onepage\_zymphonies\_theme.libraries.yml' you will see that the Bootstrap library is defined. Following my answer:

```
mymovies:
  version: 1.x
  css:
    theme:
      css/mymovies.css: {}
  dependencies:
      - onepage_zymphonies_theme/bootstrap

```
> 1 votes

# Answer
Instead of adding an additional selector for all the css in future to override the bootstrap css you can try using the weight flag of libraries like this:

```
mymovies:
  version: 1.x
  css:
    theme:
      css/mymovies.css: { weight: N }

```

Just determine the weight of bootstrap library and replace `N` with the number greater than that.

In this way your mymovies.css will load after bootstrap css and you will no longer need to write that extra selector
> -1 votes

---
Tags: 8, theming
---


title: Webform new line after the field name

text:
# Question
Title: Webform new line after the field name
I have created my first webform in drupal 8. However, I found that some of the fields such as "Telephone", "Email" are showing the field name and the textfield on the same line. However, for the text field such as "Name" and "Subject" (Also a textfield), the field name and textfield are showing on different line.

I haven't done any setting on those 4 fields. I would like to ask if I could do some settings such that the textfield is always under the field name?

Thank you for your help.

# Answer
Telephone and Email are field which looks like textfield but actually are not of type textfield. Instead, they are of field type `telephone` and `email` respectively, which was introduced when Drupal 8 was released.

In order to show field title and field input in same line use below steps,

1. Edit the individual field.
2. Go to form display setting and open the title display dropdown.
3. Select `Inline` option.
> 0 votes

---
Tags: webforms
---


# Question
Title: How can we check the emptiness of field value without increasing the Cyclomatic and NPath complexity?
I am working on Rest api end points for different content types. I am using normalizers for the same, but when i'm trying to make use of same normalizer for all content type, conditions in the functions are increasing. How can we reduce the Cyclomatic and NPath complexities. Below is example code snippet:

```
  $appealData['description'] = !empty($entity->body->getValue()[0]['value']) ? $entity->body->getValue()[0]['value'] : '';
    $appealData['image'] = !empty($imageFile) ? $imageFile->url() : '';
    $appealData['pulloutQuote']['text'] = !empty($entity->field_quote_content->getValue()[0]['value']) ? $entity->field_quote_content->getValue()[0]['value'] : '';
    $appealData['pulloutQuote']['author'] = !empty($entity->field_quote_citation->getValue()[0]['value']) ? $entity->field_quote_citation->getValue()[0]['value'] : '';

```

Any alternative to check emptiness of field value? I am just trying to replace `NULL` with `''`. Please help me in this regard.

# Answer
> 0 votes
When you are trying to replace `NULL` with `''`, don't use `empty()`, because empty does a boolean evaluation and would also replace `0` with `''`

The shortest null-detecting PHP7 code for single-value fields with a primitive data value (text, number,...) is the null-coalescing operator `??`

```
$foo = $entity->field_foo->value ?? '';

```

# Answer
> -1 votes
Some unwanted code can be removed and can be optimised as below:

```
$appealData['description'] = $entity->body->value ? $entity->body->processed : '';
$appealData['image'] = !empty($imageFile) ? $imageFile->url() : '';
$appealData['pulloutQuote']['text'] = $entity->field_quote_content->value ? $entity->field_quote_content->value : '';
$appealData['pulloutQuote']['author'] = $entity->field_quote_citation->value ? $entity->field_quote_citation->value : '';

```

---
Tags: 8
---


# Question
Title: How can I write into a Flag's custom field programmatically?
I successfully managed to save a flag programmatically in Drupal 8 thanks to this help but I cannot manage to save data into a custom field I added to the flag entity.

The following code saves the flag but the field stay empty.

```
$entity = \Drupal::entityTypeManager()->getStorage('node')->load($entity_id);
$flag_id = 'bookmark';
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);

/* Here is where I'm trying to set my custom field value */
$flag->set('field_my_custom_field', $link_name);

$flag_service->flag($flag, $entity);

```

I cannot find any info into the documentation. Any help will be much appreciated.

# Answer
I fix it with this code. You should save the output of the function

```
$flag_service->flag($flag, $entity);   //Wrong method

```

in a variable like it

```
$id_flagged_entity = $flag_service->getFlagging($flag, $entity);

```

and set the title at this entity

```
$id_flagged_entity->set("field_my_custom_field", $link_name);
$id_flagged_entity->save();

```
> 5 votes

---
Tags: 8, flags
---


# Question
Title: Programmatically set the value of a multi-value field from multiple arrays
I have 3 taxonomy vocabularies:

1. Fruits
2. Vegetables
3. Drinks

On the `Article` content type, I have set a multi-value entity reference field `field_article_all_items` referencing all of `Fruits`, `Vegetables` and `Drinks` taxonomy vocabularies.

Using the Webform module, I have created a webform with 3 elements:

* `fruits_category` which is a **non-required**, **multi-value** Entity Checkboxes element referencing the `Fruits` Taxonomy Vocabulary
* `vegetables_category` which is a **non-required**, **multi-value** Entity Checkboxes element referencing the `Vegetables` Taxonomy Vocabulary
* `drinks_category` which is a **non-required**, **multi-value** Entity Checkboxes element referencing the `Drinks` Taxonomy Vocabulary

Now on webform submit, I want to:

1. Create a new node of type `article`.
2. Set the values of `field_article_all_items` equal to all selected values from `fruits_category`, `vegetable_category` and `drinks_category`.

**In my customhandler.php file, I have tried:**

```
// Get an array of the values from the submission.
    $values = $webform_submission->getData();

// Get 'Fruits Category' Value.
    $FruitsCategory = $values['fruits_category']; // Multi-value tid

// Get 'Vegetables Category' Value.
    $VegetablesCategory = $values['vegetable_category']; // Multi-value tid

// Get 'Drinks Category' Value.
    $DrinksCategory = $values['drinks_category']; // Multi-value tid

// Put all values in an array().
    $AllItems = array($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        'field_article_all_items' => $AllItems,
        ]);
// Save the created node.
    $article->save();

```

the above code created a new node but with `field_article_all_items` field empty.

**Also I have tried:**

```
// Get an array of the values from the submission.
    $values = $webform_submission->getData();

// Get 'Fruits Category' Value.
    $FruitsCategory = $values['fruits_category']; // Multi-value tid

// Get 'Vegetables Category' Value.
    $VegetablesCategory = $values['vegetable_category']; // Multi-value tid

// Get 'Drinks Category' Value.
    $DrinksCategory = $values['drinks_category']; // Multi-value tid

// Put all values in an array().
    $AllItems = array($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        //'field_article_all_items' => $AllItems,
        ]);
// Save the created node.
    $article->save();

foreach ($AllItems as $Item) {
  $article->field_article_all_items[] = $Item;
}

// Save the created node again.
    $article->save();

// Also I have tried the below method.
//   $article->field_article_all_items[] = ['target_id' => $AllItems]

  //Save the created node again.
//   $article->save();

```

But also this code created a new node but with `field_article_all_items` field empty.

How to set the values of `field_article_all_items` equal to `fruits_category` \+ `vegetable_category` \+ `drinks_category` ?

# Answer
> 2 votes
Educated guess: (The key was to merge the arrays by using `array_merge()`)

```
// Put all values in an array().
$AllItems = array_merge($FruitsCategory, $DrinksCategory, $DrinksCategory); // use array_merge

foreach ($AllItems as $Item) {
  $article->field_article_all_items[] = ['target_id' => $Item];
}

$article->save();

```

Also it can be used within the node creation:

```
// Put all values in an array().
    $AllItems = array_merge($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        'field_article_all_items' => $AllItems,  // use array_merge
        ]);
// Save the created node.
    $article->save();

```

---
Tags: 8, webforms
---


# Question
Title: Download a module for a different core version?
I'm using Drush 10, and I can't use `dl` to download a module, since the command was removed to push Composer use.

Is there a way to download a Drupal 7 module into a Drupal 8 site using Composer, so that I can use the Drupal 7 to 8/9 Module Upgrader script on it?

The project I want to download doesn't have a Drupal 8 version yet, and it has no composer.json.

# Answer
If I were you, I would just use `wget`.

Copy the Zip file url, ex:

```
sudo wget https://ftp.drupal.org/files/projects/views-7.x-3.24.zip

```

and then

```
sudo unzip views-7.x-3.24.zip

```
> 1 votes

---
Tags: 8, composer
---


title: Get parent of an entity reference

text:
# Question
Title: Get parent of an entity reference
I have an entity reference inside node. How can I retrieve the parent node?

I tried with the following code, where `$node` is my entity reference, but it doesn't work.

```
$entity_ids = $query
    ->condition('type', 'user')
    ->condition('status', 1)
    ->condition('field_product_document', $node->getTitle(),'CONTAINS');

```

What is wrong in the code? What code should I use?

# Answer
An entity reference field is implemented from the `\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem` class. If you look at the code for `EntityReferenceItem::preSave()`, you will notice it is setting its *target\_id* property to `$this->entity->id()`.

```
public function preSave() {
  if ($this->hasNewEntity()) {
    // Save the entity if it has not already been saved by some other code.
    if ($this->entity->isNew()) {
      $this->entity->save();
    }
    // Make sure the parent knows we are updating this property so it can
    // react properly.
    $this->target_id = $this->entity->id();
  }
  if (!$this->isEmpty() && $this->target_id === NULL) {
    $this->target_id = $this->entity->id();
  }
}

```

I take your code should be changed to the following one.

```
$entity_ids = $query
    ->condition('type', 'user')
    ->condition('status', 1)
    ->condition('field_product_document', $node->id());

```

The change makes also sense: A node title cannot be used to uniquely identify a node, since there could be more nodes with the same title; the node ID uniquely identify a node on a Drupal site.
> 3 votes

# Answer
Here is how to do it with entityTypeManager:

```
$parent_node_results = \Drupal::entityTypeManager()
  ->getListBuilder('node')
  ->getStorage()
  ->loadByProperties([
    'type' => $bundle,
    'status' => 1,
    'field_child_nodes' => $node->id(), //the reference field on the parent
   ]
);

if($parent_node_results) {
  // $parent_node_results is an associative array of parent_id=>parent_entity.
  $parent_node_id = key($parent_node_results);
  $parent_node = $parent_node_results[$parent_node_id];
}

```
> 2 votes

# Answer
You should be able to get the referenced entity using

```
$parent = $node->field_product_document->entity;

```
> -1 votes

---
Tags: 8, entities
---


# Question
Title: How do I use Taxonomy reference field tokens in a path alias?
I have a content type with two taxonomy entity reference fields. Both are required fields that only allow one value. I have path\_auto and token enabled. I would like to use them to set the path of the node type.

This is the path pattern that is a problem:

`[node:field_main_site_section:entity:name]/[node:field_content_category:entity:name]/[node:title]`

It looks close to the answer given in another questionn here.

**Result:** The only thing showing up in the path is the title.

Versions: Drupal 8.8.5, pathauto 1.8, token 1.7

**What have I tried?**

I tried running the code through the debugger and found out that the action is in the functions `PathautoGenerator::createEntityAlias()` and `Token::generate()`. I see that the three tokens are found and that a Node data is passed to Token generate. Then the `generate` function runs `$replacements = $this->moduleHandler->invokeAll('tokens', [$type, $tokens, $data, $options, $bubbleable_metadata])`. There were 9 modules found that implement hook\_tokens but the only one returning any data is node\_tokens. Looking at that code I don't see any attempt to return fields.

I also found an issue on the token module that indicated that I might be missing Token view modes. I was indeed missing a token view mode for my two taxonomy vocabularies so I created them. I added each field in the vocabulary including "name" in plain text.

I also tried to guess that the node needed to be converted to an entity to grab it's fields:

`[node:entity:field_main_site_section:entity:name]/[node:entity:field_content_category:entity:name]/[node:title]`

That was an invalid pattern.

**Question:** What is the correct pattern or what else do I need to configure?

# Answer
> 0 votes
Solved by two changes:

* Apply the patch from this Token issue, "Inconsistent loading of third party hook implementations"
* Make sure Token display mode exists for each taxonomy vocabulary

I tested and confirmed that both the patch and the display mode config changes were needed.

---
Tags: path-aliases, tokens
---


title: E-mail validation form api

text:
# Question
Title: E-mail validation form api
What is the best way to handle server side e-mail validation in the form API?
Can it be implemented somewhere inside part of the form described below or are there other options?

```
 $form['address']['mail'] = array(
   '#type' => 'textfield',
   '#title' => t('E-mail'),
   '#required' => TRUE,
   '#default_value' => $subscription->mail,
   '#maxlength' => 255,
 );

 $form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Versturen'),
 );

 return $form;
}

```

# Answer
> 5 votes
Create a validation function for your form. Here is an example using your form. For instance, say your form code is in a function called `my_email`:

```
<?php
function my_email() {
  $form = array();

  $form['address']['mail'] = array(
   '#type' => 'textfield',
   '#title' => t('E-mail'),
   '#required' => TRUE,
   '#default_value' => $subscription->mail,
   '#maxlength' => 255,
  );

  $form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Versturen'),
  );

  return $form;
}

function my_email_validate($form, &$form_state) {
  // YOUR CUSTOM VALIDATION CODE GOES HERE
 if (!valid_email_address($mail)) {
   form_set_error('submitted][email_address', t('The email address appears to be invalid.'));
   }
}

function my_email_submit($form, &$form_state) {
  // YOUR CUSTOM SUBMIT CODE GOES HERE
}
?>

```

This function will allow you to write custom code to determine if the values entered in your fields are valid or not. You can also add a custom submit function for your form to execute custom code while the form is being submitted.

Read more about validating forms at Validating Forms, submitting forms at Submitting Forms or read the whole article for a better understanding of the Forms API: Form API Quickstart Guide

# Answer
> 5 votes
Instead of adding a form validation handler to the form, you can add a validation handler to the form element that needs to be validated: Use #element\_validate, which accepts an array of validation handlers that will be applied to the form element.

```
$form['email'] = array(
  '#type' => 'textfield',
  '#title' => 'Email',
  '#required' => TRUE,
  '#element_validate' => array('myelement_email_validate')
);

```

The validation handler receives three arguments: The form element being validated, the `$form_state` and the `$form` array for the form containing the form element. The validation handler should call form\_error() or form\_set\_error() to report any validation error.

```
function myelement_email_validate($element, &$form_state, $form) {
  $value = $element['#value'];
  if (!valid_email_address($value)) {
    form_error($element, t('Please enter a valid email address.'));
  }
}

```

# Answer
> 3 votes
Explained here: http://drupal.org/node/279127

```
<?php
$mail = $form_values['submitted_tree']['email_address'];
if (!valid_email_address($mail)) {
  form_set_error('submitted][email_address', t('The email address appears to be invalid.'));
}
?>

```

# Answer
> 1 votes
In Drupal 8 It can be validated by the following code.

```
/**
 * {@inheritdoc}
 */
public function validateForm(array &$form, FormStateInterface $form_state) {
  // Validate email
  if (!\Drupal::service('email.validator')->isValid($form_state->getValues()['email'])) {
     $form_state->setErrorByName('Email', $this->t('Email address is not a valid one.'));
  }
}

```

There's interface for that since 8.7 https://www.drupal.org/node/2997196

Reference : https://www.drupal.org/node/2912661

# Answer
> 0 votes
You can just use the Elements module and just use the 'emailfield' in the #type property of form element, just like this:

```
 $form['YOUR_FIELD_KEY'] = array(
    '#type' => 'emailfield',
    '#title' => t('Email'),
    '#size' => 20,
    '#maxlength' => 20,
    '#description' => t('Enter a valid email'),
    '#required' => TRUE,
  );

```

Just that easy with elements module, make custom validation for a simple email field does not have sense, you do not have to reinvent the wheel...

# Answer
> 0 votes
Install Email Field module and patch it with the patch on comment 16. Then use the code in the linked issue description to define your email field with built-in validation:

```
$form['email'] = array(
    '#type' => 'email',
    '#title' => t('Email'),
    '#required' => TRUE,
    '#default_value' => "",
    '#description' => "Please enter your email.",
    '#size' => 20,
    '#maxlength' => 20,
  );

```

# Answer
> -1 votes
Email address can be validated with your form validate handler

If function `your_form` defines your form then default validate handler would be `your_form_validate` or otherwise you can also set it manually

```
 $form['#validate'] = array('callback_to_validate');

 function your_form_validate($form, $form_state){
   if(!filter_var($form_state['values']['mail'], FILTER_VALIDATE_EMAIL))
     form_set_error('email', t('Invalid Email Address'))
 }

```

---
Tags: forms
---