# Question
Title: How to set default form fields value from controller
How to setup default form fields value from a form created in a controller?

I tryed to set the $form\_state param but it does not work.

```
...
$form_state = new FormState();
$form_state->set('myfield_1', 'car');
$form_state->set('myfield_2', 'bus');
$form = $this->formBuilder->buildForm('Drupal\mymodule\Form\MyForm', $form_state);
return $form;

```

# Answer
> 1 votes
Add the default values to getForm():

```
return $this->formBuilder()->getForm('Drupal\mymodule\Form\MyForm', $default1, $default2);

```

And set the default values in the form class:

```
class MyForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state, $default1 = NULL, $default2 = NULL) {

    $form['field1'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Field 1'),
      '#default_value' => $default1,
    ];

    // ...

  }
}

```

# Answer
> 0 votes
The working example for add node form:

```
       <?php

        namespace Drupal\mymodule\Controller;

        use Drupal\Core\Controller\ControllerBase;

        class addController extends ControllerBase {

           public function build() {

             $entity = $this->entityTypeManager()->getStorage('node')->create(array(
               'type' => 'SomeContentType',
             ));

             $entity->set('field_link_to_item', 5);

             $form = $this->entityFormBuilder()->getForm($entity);

             return $form;
           }

        }

```

---
Tags: 8
---


# Question
Title: How to change Taxonomy admin page title?
I simply need to change the title on the (Drupal 8.8.4) administrative page which lists the existing vocabularies.

As far as I know/read, the *routing.yml* should be modified, shouldn't it? (Is only the \*defaults\_title parameter that needs to be changed?)

Inside the taxonomy.routing.yml file, I only get the form routes for taxonomy term, if I am correct.

Do I need to modify the route elsewhere?

I have tried with the *system.routing.yml* file, listing many administrative routes (I thought it was the jackpot) but there is no route for the taxonomy page.

Could someone tell me where to go and which static route to change?

### Related questions

# Answer
> 1 votes
Maybe start with https://drupal.stackexchange.com/a/232783/15055, just implement the preprocess page title hook (without the code inside for now) in a custom module or a custom theme.

Then install the Devel sub-module Kint. And put `ksm(\Drupal::routeMatch()->getRouteName());` inside this hook. Note, in the hook name replace `MYMODULE` with your custom module's or theme's machine name.

Then visit the page you want to override the page title from and flush the caches a few times. It now should tell you the name of the route.

Then use this name to build an if-request checking the route's name and replace `$variables['title']` with your new title.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {
  // ksm(\Drupal::routeMatch()->getRouteName());
  if (\Drupal::routeMatch()->getRouteName() === 'foo.bar.foobar') {
    $variables['title'] = t('My new English title');
  }
}

```

In the end you could to the same with `hook_preprocess_html` to replace the meta title by overriding `$variables['head_title']['title']` in there.

# Answer
> 1 votes
> Could someone tell me where to go and which static route to change?

It's not a static route. Like other entity collection routes, it is built with the aid of the comment annotations above the Vocabulary entity class. `VocabularyRouteProvider` also comes into play, and it sets a `_title_callback` into `TaxonomyController::vocabularyTitle` for good measure.

At any rate, this is all a bit moot because you don't want to go modifying core files, because then when you update core you will have to patch them all over again. Very tedious. Instead you could implement your own RouteSubscriberBase::alterRoutes.

---
Tags: 8, routes
---


# Question
Title: Drupal in sub directory, still not clear
My drupal project is in directory `/var/www/MY_ORGANIZATION/MY_PROJECT/current`, and apache2 is configured to point the `web` subdirectory of the above location. When I access the site, it is of course under http://www.myorganization.it/. Now I need to move it to http://www.myorganization.it/myproject, both for organization policies and to allow it to be more easily reached through a reverse proxy. I searched around and I found a couple of interesting links, like this and this and a few more. Inspired by them, I tried to move the contents of `web/` to `web/myproject`, but when I accessed http://www.myorganization.it/myproject I got blank page. The error in the logs is crystal clear:

```
Failed opening required '/var/www/MY_ORGANIZATION/MY_PROJECT/current/web/myproject/../vendor/autoload.php'

```

So I put back the installation in `web/` and renamed it to `myproject`, changed apache configuration to point `/var/www/MY_ORGANIZATION/MY_PROJECT/current`, and that worked like a charm. But I am not sure this is an advisable configuration, since, well, since all Drupal installations I saw were in a `web` directory. Also, from my research I had understood that Drupal installation can be moved to arbitrary subdirectories, but I didn't find any official documentation. It would appear that I should at least configure a path for `vendor`.

So, the concluding question is, would you recommend simply renaming `web` to `myproject`, or should I do it another way?

EDIT: a symlink from `myproject` to `web` seems an elegant solution, it works fine in apache (dev environment), while I'm getting errors with nginx+php-fpm (staging environment); still, it may be the way to go.

# Answer
Apache can handle this. You can leave the Drupal code where it is.

Have a look at the Apache documentation for Mapping URLs to Filesystem Locations. In particular, the differences between `DocumentRoot` and `Alias`.

In the absence of any other information, Apache looks for files/scripts in the document root. For a Drupal site located at `https://www.myorganization.it/`, it's enough to point `DocumentRoot` at the `web` directory. Apache will find `index.php` there.

But `myproject` isn't a directory in the filesystem. So you need to explicitly tell Apache about it, that any URL starting `/myproject` refers to the `web` directory. You can do that with the `Alias` directive:

`Alias "/myproject" "/var/www/MY_ORGANIZATION/MY_PROJECT/current/web"`

You'll also want to point `DocumentRoot` somewhere else to stop Drupal being visible at the root too (an empty directory will do).
> 1 votes

---
Tags: 8
---


# Question
Title: Views alter changes next row instead of current one
I have a view that is showing event content types. Users can apply for these events. I am using a hook to alter the 'view applicants' so I can show how many applications already excist.

The following code works and shows the values but is somehow skipping the first row and printing all the values one row later.

```
function frontview_general_preprocess_views_view_field(&$vars) {

  $view = $vars['view'];

  if(isset($vars['view']) && ($vars['view']->id() == 'evenementen') && ($vars['view']->current_display == 'accreditaties_overzicht')) {

    if($vars['field']->options['id'] ==='nothing_1') {

      // Getting the values
      $accreditaties = $vars['row']->_entity->get('field_accreditaties');
      $accreditaties = $accreditaties->getValue('list');
      $amount = count($accreditaties);

      $vars['field']->options['alter']['text'] = 'View Applicants ('. $amount .')';
    }

  }
}

```

This is my current output, the first row still shows the normal values without the hook but the first row values are printed on the second row, second row on third row, ...

This is the output that I need

I'm not sure why it's doing that, when I dd() my code it looks fine.

Thanks in advance!

\*Drupal 8

# Answer
Got it to work with the following code. I needed to output the changed value in the `$vars['output']`. This would override the url in the nothing\_1 field so I then had to create a new link and use that to alter the original value.

```
/**
 * Implements hook_preprocess_views_view_field().
 */
function frontview_general_preprocess_views_view_field(&$vars) {

  $view = $vars['view'];

  if(isset($vars['view']) && ($vars['view']->id() == 'evenementen') && ($vars['view']->current_display == 'accreditaties_overzicht')) {

    if($vars['field']->options['id'] ==='nothing_1') {
      $accreditaties = $vars['row']->_entity->get('field_accreditaties');
      $accreditaties = $accreditaties->getValue('list');
      $amount = count($accreditaties);

      // $vars['field']->options['alter']['text'] = 'View Applicants ('. $amount .')';

      $nid_value = $vars['row']->nid;
      $url = Link::fromTextAndUrl(t('View Applicants ('. $amount .')'), Url::fromRoute('view.evenementen.page_2', ['arg_0' => $nid_value]))->toString();

      $vars['output'] = $url;
    }
  }
}

```
> 1 votes

---
Tags: views, 8, hooks
---


# Question
Title: How do I load entities with Null values?
The following fails with an exception.

```
\Drupal::entityTypeManager()->getStorage('foo_module_division')->loadByProperties(['enabled'=>TRUE, 'parent_code'=> NULL]).

```

How else do I specify I want to load entities whose *parent\_code* field is `NULL`?

# Answer
The exception is the result of how `EntityStorageBase::loadByProperties()` builds the underlying `WHERE` clause; it's utilizing `::buildPropertyQuery()` which casts `NULL` to an array then uses the `IN` operator to compare; this won't work since you need a `IS NULL` query to find `NULL` entries in the DB.

Instead, you can build your own entity storage query in a similar way as `loadByProperties()`:

```
$es = \Drupal::entityTypeManager()->getStorage('foo_module_division')
$q = $es->getQuery();
$results = $q->condition('parent_code', NULL, 'IS')->condition('enabled', TRUE)->execute();
return $results ? $es->loadMultiple($results) : array();

```
> 0 votes

# Answer
The example of getting articles that has empty body:

```
  $entityStorage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $entityStorage->getQuery();
  $query->condition('type', 'article');
  $query->notExists('body');
  $nids = $query->execute();
  $nodes = $entityStorage->loadMultiple($nids);

```
> 2 votes

---
Tags: entities
---


# Question
Title: Control Visibility of Paragraph Without Fields
I'm preprocessing a paragraph to add a custom form but I'm having trouble with the visibility. I don't need any fields on this paragraph.

If I just add the form to the paragraph the whole paragraph is hidden for anonymous users.

```
function my_module_preprocess_paragraph__my_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  $form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyCustomForm');
  $variables['content']['form'] = $form;
}

```

However, if I add a title field to that paragraph everything shows up fine. Is there a way I can get the form to show without having to add fields?

# Answer
> 0 votes
Implement hook\_field\_widget\_alter

It will give control of paragraph fields.

```
function hook_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'xyz') {
    $element['subform']['field_name']['#access'] = FALSE;
  }
}

```

---
Tags: 8, forms, paragraphs
---


# Question
Title: Views filter criteria date field is greater than current date
I have a overview page with different events. Now it shows all events which were created. But I will that it just shows all the future events.

The content type has a datefield for the eventdate. I selected the field\_date\_event by the filter criteria but there I can not enter the token \[current-date\] or a dateformat like d.m.y.

How can I solve this problem?

# Answer
You should be able to choose the `Operator` **Is greater than or equal to**, and the `Value type` set to offset with value **Today**:

This will include events happening today. If you want strictly from tomorrow you can choose **Is greater than** as the Operator.
> 8 votes

# Answer
Add filter:

Operator "Is less than" value "today +24 hours" to remove future dated content if needed.

See: Filter nodes by today's date
> 3 votes

---
Tags: views, 8, datetime
---


# Question
Title: How do I remove <div class="views-element-container form-group"> from output?
I'm trying to theme the output of a Drupal 8 view to use via a token for email recipients of a YAML form. I'm on the latest Drupal 8 core release and using a Bootstrap subtheme.

I have successfully removed all of the other views markup with the following TWIG theme override templates:

views-view-fields--ts--page\_1.html

views-view--ts--page\_1.html

views-view-unformatted--ts--page\_1.html

For some reason, I keep getting the following markup added:

```
<div class="views-element-container form-group">

```

I have tried using the views UI options to strip HTML and/or customize the markup output and this does nothing. I've also tried using the TWIG filters like striptags, but this either removes the entire views output (a comma separated list of email addresses) or doesn't work at all.

How do I remove `<div class="views-element-container form-group">`?

# Answer
Okay, I figured it out. After setting the services.yml file debug to "true" and enabling comments in my Firefox console, I was able to get the theme output for the particular set of divs that was adding the unwanted markup (I tried this earlier, but I think I forgot to rename default.services.yml to services.yml).

Anyway, I found that the markup was coming from Bootstrap's container.html.TWIG template. Of course, this is one of the templates that doesn't come with override suggestions, just the hook theme\_container() theme function. So I copied the default function into my \[subtheme name\].theme file at the top of my subtheme's directory and modified it thus to suit my needs:

```
<?php
// Implements hook_container().
use Drupal\Core\Template\Attribute;

function vatheme_container($variables) {

  $request = \Drupal::request();

  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  }

// Special handling for form elements.
$element = $variables['element'];
 // Ensure #attributes is set.
$element += array('#attributes' => array());

        if (isset($element['#array_parents'])) {
            // Assign an html ID.

            if (!isset($element['#attributes']['id'])) {
                $element['#attributes']['id'] = $element['#id'];
            }

            // Add the 'form-wrapper' class.
            $element['#attributes']['class'][] = 'form-wrapper';
        }

        if($title == 'Contact Tech Support'){
            return $element['#children'];
        }
        else{
            return '<div' . new Attribute($element['#attributes']) . '>' . $element['#children'] . '</div>';
        }
}

```

So, that seems to do the trick. This was my first stab at doing theme work in Drupal 8 and there are a lot of not insignificant changes from Drupal 7 here, so I thought I'd go through the details of my solution. Hopefully this helps someone else out there.
> 3 votes

# Answer
The following approach is a large improvement over Sky Tonnessen's answer and was originally written up in this gist by idiazroncero as it will not negatively affect the javascript wrapper classes functionality

Copy the following into YOURTHEME/templates/form/container.html.twig

```
{%
  set classes = [
    has_parent ? 'js-form-wrapper',
    has_parent ? 'form-wrapper',
  ]
%}

{# Remove unnecessary <div class="views-element-container"> wrapper #}
{% if attributes.hasClass('views-element-container') %}
  {{ children }}
{% else %}
  <div{{ attributes.addClass(classes) }}></div>{{ children }}</div>
{% endif %}

```

This is the only known workaround at the theme layer, since these classes are added via a preRender function. For a more sustainable approach, follow and help on #2721899: Move views-element-container to Twig template
> 0 votes

# Answer
If anyone stumbles here, I found this worked for me. You can override the twig in your theme.

Create this twig here: YOUR\_THEME/templates/form/container.html.twig In the twig file just put:

{{ children }}
> -1 votes

---
Tags: views, theming
---


# Question
Title: How to limit form submission per user per day and week?
The goal is very straightforward. I need a form to limit each user to 1 submission per day and 3 per week.

## What I found:

**Webform:** The "Form settings" in webform has the "Per user submission limit" setting. It does not allow me to make more than 1 validation. I'm not able to have both per day and per week in the same form.

**Entityform:** I found people use hook function on node limit on Drupal 8. This may work on Drupal 7 Entityform but I don't know how to write that syntax.

**Rule:** It may possible to use Rule module but I don't see any connection with period of time validation.

////// **PS: My question is about the limit on Webform(or Entityform) submission for authenticated users.**

# Answer
> 1 votes
Make a custom module to implement hook\_node\_access, i will post some code based on a user date field that compares 'today' with this user-date-field and return access deny if dates comparison goes beyond 'today', and another with today+7 days, you will have to adapt this code to your needs; please add in user profile a date field, this field it has to be updated by rules every time a user adds content of your 'special content-type', maybe you will need 2 user-date-fiels, one for each 'special-contentype' if you need help with this last comment please ask.

```
// replace HOOK with yourmodulename and field machine names
function HOOK_node_access($node, $op, $account) {

  $type = is_string($node) ? $node : $node->type;

  global $user;

  // check if not anonymous
  if($user->uid!=0){

    //check if not administrator role, admin will have allways access
    $user_role = '';
    if (in_array('administrator', $user->roles)) {
      // do fancy stuff
      $user_role = 'administrator';
    }

    if (!$user_role == 'administrator') {

      $user_logged = user_load($user->uid);
      $user_date_field = $user_logged->YOUR_USER_DATE_FIELD[LANGUAGE_NONE][0]['value'];

      // today date in UNIX date stamp
      $today_int = date('U');

      // your user_date_field in UNIX time stamp
      $date_int = (int)strtotime($user_date_field);

      // check if 'today' is > than user_date_field
      $diff = $date_int - $today_int;
      $diff = round($diff/86400); // diff in days betwen 2 dates

      // today comparison
      if ($diff >= 0 ) {
        // code... user do have access to add/edit content

      } else {
        // code... retunr access deny 'today' add/edit
        if ($type == 'YOUR_CONTENT_TYPE_MACHINE_NAME') {
          // if options are update ore cerate content, return access deny
          if ($op == 'update' OR $op == 'create') {
            return NODE_ACCESS_DENY;

          }
        }
      }

      //  1 week comparison
      $diff7 = $diff + 7;

      if ($diff7 >= 0 ) {
        // code... user do have access to add/edit content

      } else {
        // code... retunr access deny 'today +7 days' add/edit
        if ($type == 'YOUR_CONTENT_TYPE_MACHINE_NAME_7') {
          // if options are update ore cerate content, return access deny
          if ($op == 'update' OR $op == 'create') {
            return NODE_ACCESS_DENY;

          }
        }
      }
    }
 }
}

```

NOTE, if you do not want to add fields to user profile form, it could be done by adding variables to logged-user by HOOK\_entity\_property\_info\_alter(&$info), if this is needed please ask.

EDIT:

please specyfy in your question that is about webforms, so, above code do not apply, i'll leave it, could be usefull for someone else.

what you can do is still keep 'user\_date\_field', install the following mudules: flags, rules and panels.

I will explain only ‘today’ settings, same thing for ‘1 week settings’, only in this last case you will need another field (or user-variable) to store how many webforms has submitted this user in current week.

Steps:

```
• enable rules, rules scheduler, flag & panels modules.

• make a user flag ‘user-posted-a-webform’

• in rules:

• make a component, unflag current user (it will be invoked later).

• make a rule, flag user when submit a webform, update 'user_date_field' with site-current-date

• in panels make a page and add your webform, add a rule (inside panles content section) make it visible only if user is NOT flagged.

• Return to your rule, add an action “schedule component evaluation”, choose your component, inside action setting, on ‘scheduled evaluation date’ enter ‘+1 day’.

• Done

```

COMPONENT unflag-user

---
Tags: 7, forms, datetime
---


# Question
Title: How to wrap node output with a link using Display Suite?
how would I best wrap my entire node in an tag linking to the full node? My nodes are display using Display Suite and a custom view mode.

I'm guessing creating a php template and manually writing the link somehow would work?

# Answer
> 1 votes
When you go `/admin/structure/types/manage/blog/display/teaser` (or whatever content type you're going for) at the bottom is a list of possible template names. In my example `ds-2col-stacked-fluid--node.tpl.php` was what I needed.

In the template file I ended up wrapping my content variables with the following:

```
<a href="<?php echo url('node/' . $nid); ?>"> normal node here </a>

```

One thing to note is that you need to make sure there are no nested links around fields like image, author or title.

# Answer
> 7 votes
A good option for this is Field Group Link.

For your case, basically you need to create a field group wrapping the whole node, and set the group type to 'Link'.

# Answer
> 0 votes
You can do this with a display suite custom wrapper.

Make sure you are using a display suite layout for the teaser view mode, and then select custom wrappers from the bottom left hand menu. Choose "link to content" from the "add link" drop down.

---
Tags: theming, display-suite
---


# Question
Title: How to map Address field module sub fields (City, State, etc.) to specific (individual) fields in Salesforce?
Address module: https://www.drupal.org/project/address Usually Salesforce mapping doesn't allow to add Address module subfields in the mapping.

# Answer
We can resolve this by using typed\_data module. https://www.drupal.org/project/typed\_data This is a required module for Salesforce Suite installation.

In the Field Type select Properties,Extended then select the name of the field associated the Address field Module corresponding to the Salesforce field.
> 0 votes

---
Tags: 8
---


# Question
Title: How do I execute code when a module is installed or uninstalled?
Currently, I manually have to add terms one by one every time a module gets installed, and that's not efficient. I'm writing a simple module that needs to automatically install 2 terms every time the module gets installed, and remove them every time the module gets uninstalled.

From Create taxonomy term programmatically on Drupal 8, I learned how to add terms. However, I simply don't know where to put the code. What must I do to achieve it?

# Answer
> 3 votes
Needs to go inside of **mymodule.install** file

```
<?php

/*
 * Implements hook_install()
 */
function mymodule_install() {

  // code that creates terms

}

/*
 * Implements hook_uninstall()
 */
function mymodule_uninstall() {

  // code that deletes terms

}

```

---
Tags: 8
---


# Question
Title: Modal Dialog not Opening when not authenticated or in incognito mode
Hi i am using Drupal 8 to render a modal popup on clicking a link. However when i am connected as admin the popup render well but as soon as i logout or choose to be incognito mode of the browser the popup does not appear and the page is redirected to link set in the href tag. Here is my link :

```
<a href="/mysite.com/contact/download_file_advance?nid=371" class="use-ajax" data-dialog-type="modal" data-accepts="application/vnd.drupal-modal" data-filename="Livre Blanc">SOME TEXT IN MODAL</a>

```

Can anyone explain to me why this is so? I can't figure out why when i am connected the modal render well but when not connected it redirect me to the node.

# Answer
Ajay is correct, the javascript dependencies wont load by default for anonymous users. Here's what I added to my `theme.libraries.yml` to get it working:

```
dependencies:
  - core/jquery
  - core/drupal.dialog.ajax

```
> 9 votes

# Answer
For me the only thing that helped beside of hacking PHP code, which in my opinion would be an overkill, was to add the following to the `MY_THEME.info.yml` under the section `libraries`:

```
- 'core/drupal.dialog.ajax'

```

In my case, using a bootstrap based theme, the whole section looked like this:

```
libraries:
  - 'bootstrap_freigeist/global-styling'
  - 'bootstrap_freigeist/bootstrap-scripts'
  - 'core/drupal.dialog.ajax'

```

Be aware that adding the script to the `MY_THEME.libraries.yml` didn't do the trick for me.
> 4 votes

# Answer
For me adding dependencies in libraries.yml did not worked, I am using drupal 8.x version. Below is working solution for me

In your theme file, say your theme name is "abc" then you will have a file "abc.theme", add following code in file. assuming your page alias path is "abcde" where you want to add the dialog box

```
function abc_page_attachments_alter(&$page){
        $current_path = \Drupal::service('path.current')->getPath();
        $path = $current_path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
        if($path == '/abcde') {
            $page['#attached']['library'][] = 'core/drupal.ajax';
        }
    }

```

if you want to load library in all pages then replace above function with

```
  function abc_page_attachments_alter(&$page){
                $page['#attached']['library'][] = 'core/drupal.ajax';
        }

```

clear cache and hard refresh your page. dialog box should be working now
> 2 votes

# Answer
The answers posted here are right, also you can include jQuery libraries and the Ajax libraries using *hook\_page\_attachments*, just implement this function in your ***yourmodule****.module* file, replacing the name of your module accordingly, of course:

```
function yourmodule_page_attachments(array &$attachments) {
    $attachments['#attached']['library'][] = 'core/jquery';
    $attachments['#attached']['library'][] = 'core/drupal.dialog.ajax';
}

```

This snippet will add jQuery and Ajax required libraries to all your pages, then you can write your own logic in it if you want to restrict this libraries to only certain pages.

Good luck!
> 1 votes

# Answer
You need to add code dependencies in your theme for ajax and jQuery in your `theme.libraries.yml` file.

Drupal by default does not load ajax for anonymous users.
> 0 votes

---
Tags: 8
---


title: Install Drupal using composer

text:
# Question
Title: Install Drupal using composer
I'am trying to install Drupal 7 using composer. Before that I tried to install drupal 8 using composer and it works perfectly.

Now when I try to install D7 using same method it is still installing D8 instead of D7. I set up package repository as mentioned here but still installing D8 only. I tried `$ composer clearcache` also but no difference. Please help.

# Answer
> 7 votes
Checking https://packagist.org/packages/drupal/drupal for the versions available there is NO 7.x version. Drupal 7 has no **composer.json** for this to command to work.

You can use one of the other 2 methods mentioned on https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

Using https://github.com/drupal-composer/drupal-project you need to tell the version

```
composer create-project drupal-composer/drupal-project:7.x-dev \
  test-3 --stability dev --no-interaction

```

Using https://github.com/hussainweb/drupal-composer-init you can do

```
composer drupal-init --drupal-7

```

Please note:

# Answer
> 1 votes
```
$ composer create-project drupal-composer/drupal-project:7.x-dev \
example --stability dev --no-interaction

```

This will copy the drupal-project to the example directory, and download Drupal core and some handy packages. This is a good point to cd into the example directory, run git init , and to then create your initial commit for your project.

# Answer
> 0 votes
Encountering this issue, in the process of upgrading a D7 site to D8, it took me a while to realize that there might be a slightly different question that often is more relevant:

**How would one install D7 with modules, similarly to how one would install D8 with composer?**

By using `drush make` was the answer for me. Unless I'm mistaken, that tool was contemporary with D7 to a much higher degree than composer was.

An easy way to get started is to install drush 8 (make is removed in newer versions) using composer, and then adapt `drush/drush/examples/example.make.yml` to your needs. For more details please see the documentation.

Clearly this is a bad idea for production systems, but that goes for creating new D7 instances today too.

---
Tags: 7, installation, composer
---


# Question
Title: Hiding view filter option based on another filter selection
I have a view with search criteria and the search criteria looks like below:

Age group(options: new born, toddler, pre-school) Classroom (options: NA, potty-trained, transition, not-trained) All these filter fields are check boxes.

When I select 'new born' as age-group, all of the classroom options should be hidden/disabled except NA option When I select 'toddler/pre-school' all of the classroom options should show up again except NA option

I am using the below code for doing this:

```
$('#edit-field-agegroup-value-1').click(function() {
    if( $(this).is(':checked')) {
        $("#edit-field-classroom-value-3").prop('disabled', true);
     } else {
        $("#edit-field-classroom-value-3").prop('disabled', false);
     }
    });

```

This code is working fine. However, when I submit the refresh button the page refreshes and the disabled fields show enabled again. Any help on how this can be fixed?

# Answer
> 1 votes
Run the check on page page load, not just on click:

```
 ... wrapped in the usual Drupal boilerplate

disableFilter($('#edit-field-agegroup-value-1'));

$('#edit-field-agegroup-value-1').click(function() {
    disableFilter($(this));
});

function disableFilter(element) {
    if( element.is(':checked')) {
        $("#edit-field-classroom-value-3").prop('disabled', true);
     } else {
        $("#edit-field-classroom-value-3").prop('disabled', false);
     }
}

```

---
Tags: views, javascript
---


title: AJAX error on form alter

text:
# Question
Title: AJAX error on form alter
I have a form alter function, it seems working fine, but, i am getting this strange error, i am not able to figure this out. Please help me out. I have a dependent dropdown. I am pulling 1st level vacabulory in 1st dropdown. 2nd dropdown is basically the childrens of the parent chosen from the 1st dropdown. The code works, but give me error.

```
function teacher_form_alter(&$form, &$form_state, $form_id){

  if($form_id == "teacher_profile_node_form"){

        $form['field_teacher_city'] = array (
           '#title'   => 'City',
           '#type'    => 'select',
           '#options' => _teacher_city_options_list_taxonomy(),
           '#ajax'    => array(
                'event'=>'change',
                'callback' =>'_teacher_location_list_dropdown',
                'wrapper' => 'edit-field-city',
                'method' => 'replace',
                )
          );

      $form['field_teacher_locations'] = array(
           '#title'   => 'Location',
           '#type'   => 'select',
           '#options' => get_dropdown_list(),
           '#prefix' => '<div id="edit-field-city">',
           '#suffix' => '</div>',

       );
     }

    return $form;
}

function get_dropdown_list() {

      $options2 = array(
        0 => t('Zero'),
        1 => t('One'),
        2 => t('Two'),
        3 => t('Three'),
           );

return $options2;
}

function _teacher_location_list_dropdown($form, $form_state)  {
  // use this method to populate the demo list from the list of courses
  $vocab = taxonomy_vocabulary_machine_name_load('locations');

  $vid = $vocab->vid;

  $sel = $form_state['values']['field_teacher_city'];
  drupal_set_message($sel);

  if (!isset($sel)) {

      $options = array(
        0 => t('four'),
        1 => t('five'),
        2 => t('six'),
        3 => t('seven'),
           );

  }
  else {
      $terms = taxonomy_get_tree($vid,$sel,1,FALSE);

      $options = array();
      foreach ($terms as $term)  {
    $options[$term->tid] = $term->name;
      }
  }

  $form['field_teacher_locations']['#options'] = $options;

  return   $form['field_teacher_locations'];
;
}

```

Error is below

```
Warning: array_values() expects parameter 1 to be array, string given in _field_filter_items() (line 515 of C:\wamp\www\drupal-7.19\modules\field\field.module).
Warning: Invalid argument supplied for foreach() in list_field_validate() (line 392 of C:\wamp\www\drupal-7.19\modules\field\modules\list\list.module).

```

# Answer
> 0 votes
You're not supposed to change the `$form` element in the AJAX callback, only in the form\_alter function. Otherwise,

> when the form is submitted (ajax or not), the submitted form does not match the cached form, which causes Drupal to fail

---
Tags: ajax, forms
---


# Question
Title: How to unfocus button after ajax form was rebuilt?
I have a form that is completely ajaxified and when I submit the form the submit button stays focused.

I have styling in place and it results in bad UX. How should I unfocus the button? Do I have to implement ajax response and some custom JS for this? Seems like a hacky solution :(

# Answer
You can solve this by setting focus to another element on rebuild.

I don't know how to do it in Drupal 8, but here's Drupal 7 code to focus an element:

**In the form\_alter:**

```
  // Focus the first element on rebuild.
  if ($form_state['rebuild']) {
    $first_element = array_keys($form['entry_fieldset']['entry_ids'])[0];
    $form_state['focus_id'] = $first_element;
  }

  // Allow a form element to be focused.
  if (isset($form_state['focus_id'])) {
    // Pass the element ID as a variable to the JS.
    $settings = array('focus_id' => $form_state['focus_id']);
    $form['#attached']['js'][] = array(
      'data' => array('example' => $settings),
      'type' => 'setting',
    );
  }

```

**JS:**

```
  /**
   * Focus a form element.
   */
  Drupal.behaviors.exampleFocusElement = {
    attach: function(context, settings) {
      if (settings.example && settings.example.focus_id) {
        // Focus the element having the ID passed in.
        $('#' + settings.example.focus_id, context).focus();
      }
    }
  };

```
> 0 votes

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


# Question
Title: How can I fetch the complete main navigation menu via JSON:API?
How can I fetch the complete main navigation menu via jsonapi?

I've tried:

```
curl --header 'Accept: application/vnd.api+json' https://cms.example.com/jsonapi/menu/menu/

```

and

```
 curl --header 'Accept: application/vnd.api+json' https://cms.example.com/jsonapi/menu/menu/232fc942-51f3-4478-8535-e5dc482a166e

```

where `232fc942-51f3-4478-8535-e5dc482a166e` is the `id` of the main-navigation menu BUT only the first level nodes are returned:

```
{
  "data": {
    "type": "menu--menu",
    "id": "232fc942-51f3-4478-8535-e5dc482a166e",
    "attributes": {
      "label": "Main navigation"
    },
    "links": {
      "self": {
    "href": "https://cms.garanteasy.com/jsonapi/menu/menu/232fc942-51f3-4478-8535-e5dc482a166e"
      }
    }
  },
  "jsonapi": {
    "version": "1.0",
    "meta": {
      "links": {
    "self": {
      "href": "http://jsonapi.org/format/1.0/"
    }
      }
    }
  },
  "links": {
    "self": {
      "href": "https://cms.garanteasy.com/jsonapi/menu/menu/232fc942-51f3-4478-8535-e5dc482a166e"
    }
  }
}

```

# Answer
I did not get it to run with JSON:API, there are several long-standing issues...

*However* you can get it to run if you additionally install the REST Menu Tree module.

Be aware that this has several direct and indirect dependencies:

It has a direct dependency on Menu Normalizer and according to this issue you need to then activate that endpoint for example with the REST UI module - which in turn will activate the core REST module.

Then in your site activate the endpoint via the Rest UI in `/admin/config/services/rest`.

Afterwards you might also want to allow everyone to GET this endpoint via `/admin/people/permissions#module-rest`

And finally you get a JSON array in `/entity/menu/main/tree`. Or query a different menu via `/entity/menu/{internal_menu_name}/tree`.
> 2 votes

# Answer
It is possible to pull all the menu items using the JSON:API exclusively. The main "long standing issue" is that the links are not available to non admin users, which probably defeats the purpose for most users. There are a couple patches, however, that allow this:

https://www.drupal.org/project/drupal/issues/2915792

And to add the url property:

https://www.drupal.org/project/drupal/issues/3066751

This allows you to hit this endpoint:

`/jsonapi/menu_link_content/your-menu-machine-name`

And get a standard JSON:API result.

> Key takeaway: The state of Drupal's headless menu fetching is abysmal.
> 2 votes

# Answer
There is also the rest\_menu\_items module. This doesn't have any dependencies, the only thing you need to do is enable the endpoint. This also enables you to specify which values you want, and specify the depth of the tree.
> 0 votes

---
Tags: 8
---


# Question
Title: How do I prevent the HTML markup in an item list from being escaped?
As you can see in the code below, I try various ways to prevent Drupal from escaping the HTML and passing the link tags to the output, including the use of '#allowed\_tags' and the `Markup` class. None of these approaches are working.

```
$text = t('Administer books');

$markup = new Markup();
$link = $markup->create(Link::fromTextAndUrl($text, $url)->toString());

$items[] = $link . ': ' . t('Browse books and edit fields') . '.';

$text = t('Import books');
$url = new Url('mei_marc.import');

$items[] = Link::fromTextAndUrl($text, $url)->toString() . ': ' . t('Visit this page to import a book') . '.';

$array['mei_marc_list'] = array(
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#title' => '',
  '#items' => $items,
  '#allowed_tags' => ['a'],
);

$txt = drupal_render($array);

$markup = new Markup();

$list = $markup->create($txt);

return ['#markup' => $list];

```

The output is the following.

```
<div class="item-list">
<ul><li><a href="/mei_marc/list">Administer books</a>: Browse books and edit fields.</li>
<li><a href="/admin/mei_library/import">Import books</a>: Visit this page to import a book.</li>
</ul>
</div>

```

# Answer
```
$items[] = [
  '#markup' => Link::fromTextAndUrl($text, $url)->toString() . ': ' . t('Visit this page to import a book') . '.',
];

$form['mei_marc_list'] = [
  '#theme' => 'item_list',
  '#items' => $items,
];

return $form;

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to get replacement pattern for Search API's fulltext search in global text area header
In Drupal 7, I'm currently using the default core search, and a view for node search results. I have a global text to pull in the replacement pattern for the term that were searched for. I get the token by adding the contextual filter `Search: Search Terms` I am using the replacement pattern `%1` as seen in the picture:

Then I put `<span class="MY-CLASS">You searched for:</span> <b> %1 </b>` in my `global text` to display the keywords that were searched for:

This all works great for Drupal core search, but I am not finding a way to do this with the view in Search API? I am using Database Service, and a view built from the database index I created. I have tried to find a field such as keywords for the full text search, but since the view is based off of indexed content, I am not able to get those type of fields added, to make them available for tokens, even via relationships. Maybe there is a better way to build the view?

# Answer
> 0 votes
The problem I was having here is my view that I was trying to build for search API was using a full text search **exposed filter** rather than a **contextual filter**. The contextual filter provides the `search term title` and `search term input` tokens that are pictured above. The exposed filter will not produce them. Live and learn.

EDIT: There is a bit of a workaround I found but it was an implementation I would not recommend. I was using Drupal core search blocks with Search API view's contextual filters together. I was able to add the contextual filter, get the token, then remove the contextual filter. That somehow allowed the token to work in that context.

---
Tags: views, search, tokens
---


# Question
Title: Programmatically creating a custom block
I followed the steps from https://www.webwash.net/programmatically-create-block-drupal-8/. I have a view already created and I want to render this view in this block. I can't find a good documentation for *build()* function.

The reason is that I want to hide the view for a role implicitly included by authenticated role.

How can I display the existing view inside the custom block I've created?

# Answer
I didn't find a way to display the view and restrict for certain roles.

But I've managed to solve the problem in another way.

I created a script in *Admin \> Structure \> Block \> My\_Block \> Configure \> Visibility PHP*:

```
<?php
$match = TRUE;
$heh = \Drupal::currentUser()->getAccount()->getRoles(TRUE);
$hide_from_roles = array('administrator', 'sefii', 'membership');
 if (count(array_intersect($heh, $hide_from_roles)) > 0) {
    $match = FALSE;
}
return $match;
?>

```
> -2 votes

---
Tags: views, blocks
---


title: Custom Condition on Query

text:
# Question
Title: Custom Condition on Query
I'm trying to add a custom condition in a query:

```
 $today = new DrupalDateTime();
 $today = $today->format("m-d");
 $ids = Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition("date_format('field_birthday','%m - %d')", $today, '=')
  ->execute();

```

Error:

> PHP message: Uncaught PHP Exception Drupal\Core\Entity\Query\QueryException: "'date\_format('field\_birthday','%m-%d')

**Version Drupal 8.8.4**

What is the best way to solve this?

# Answer
> 0 votes
You can try use hook\_query\_TAG\_alter

```
...
->addTag('my_module_birtday')

/**
 * Implements hook_query_TAG_alter().
 */
function my_module_query_my_module_birtday_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $today = new DrupalDateTime();
  $today = $today->format("m-d");
  $query->addJoin('LEFT', 'user__field_birthday', 'field_birthday', 'field_birthday.entity_id = base_table.uid');
  $expression = "DATE_FORMAT(field_birthday.field_birthday_value,'%m-%d')";
  $args = [
    ':birthday'=>$today
  ];
  $query->where($expression . '=:birthday', $args);

}

```

---
Tags: entities
---


# Question
Title: Programatically change exposed filter value based on another exposed filter
I have 2 exposed filters in my Drupal 8 view - both are select dropdowns. I want the value of the 2nd filter to change based on selection of first filter Here are the filters `$filters = $view->display_handler->getOption('filters');`

`$filters['country']` and `$filters['states']`.

Problem is that I always get an empty value when I try to access country filter in my views\_pre\_view hook.

`dpm($filters['country']['value'])` always prints empty.

How do I solve this please?

# Answer
You don't have access to your filter options inside `hook_views_pre_view`.

```
$filters = $view->display_handler->getOption('filters');

```

give only informations about the filter something like:

```
 "field_country_target_id" => array:20 [▼
    "id" => "field_country_target_id"
    "table" => "node__field_country"
    "field" => "field_country_target_id"
    "relationship" => "none"
    "group_type" => "group"
    "admin_label" => ""
    "operator" => "or"
    "value" => []
    "group" => 1
    "exposed" => true
    "expose" => array:13 [▶]
    "is_grouped" => false
    "group_info" => array:10 [▶]
    "reduce_duplicates" => false
    "type" => "select"
    "limit" => true
    "vid" => "countries"
    "hierarchy" => false
    "error_message" => true
    "plugin_id" => "taxonomy_index_tid"
  ]

```

To get the selected filter values with:

```
$filters_selected = $view->getExposedInput();

```

Even you get the filter options you can't alter it because exposed filters are form inputs.
So i thing the best way to achieve this is by using `hook_form_FORM_ID_alter` like the following.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODUOLE_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Here is options of your country filter
  // Note that they key is FIELD_NAME_target_id
  // Change the FIELD_NAME with you field name
  $countries = $form['field_country_target_id']['#options'];
  // Get the city options the same way .
  /**
   * TODO: To alter options array change $form['field_country_target_id']['#options'] not the $countries
   */
}

```
> 0 votes

---
Tags: views
---


title: Get domain from a URL field

text:
# Question
Title: Get domain from a URL field
I have a link field in a content type, *field\_source*. I created a computed field (*field\_source\_domain*) in the same content type, which should contain the domain for the link in *field\_source*.

I tried with `$value = parse_url('https://subdomain.example.com/foo/bar', PHP_URL_HOST);` and it works, but when I tried `$value = parse_url('$entity->field_source->value', PHP_URL_HOST);` or `$value = parse_url('$fields['field_source']', PHP_URL_HOST);`, I didn't get anything.

How do I get the domain name using a computed field?

# Answer
I found the solution to my problem:

```
$field_source = $entity->get('field_source')->getValue();
$url_link = $field_source[0]['uri'];
$parse = parse_url($url_link);
$value = $parse['host'];

```
> 0 votes

---
Tags: 8
---


# Question
Title: Installing drupal/recommended-project fails at installing coder
running composer install with the Drupal 8 recommended setup fails when installing coder with authentication message or similar. Does somebody else have this behavior?

Workaround was to run `composer install --no-dev` and running `composer install` afterwards, but this doesn't install Coder. Colleagues told me they have similar problems with different libraries.

Here is my composer.json

```
{
    "name": "drupal/recommended-project",
    "description": "Project template for Drupal 8 projects with a relocated document root",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "homepage": "https://www.drupal.org/project/drupal",
    "support": {
        "docs": "https://www.drupal.org/docs/user_guide/en/index.html",
        "chat": "https://www.drupal.org/node/314178"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "composer/installers": "^1.2",
        "drupal/core-composer-scaffold": "^8.8",
        "drupal/core-project-message": "^8.8",
        "drupal/core-recommended": "^8.8"
    },
    "require-dev": {
        "drupal/core-dev": "^8.8"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "extra": {
        "drupal-scaffold": {
            "locations": {
                "web-root": "web/"
            }
        },
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/Commands/contrib/{$name}": ["type:drupal-drush"],
            "web/modules/custom/{$name}": ["type:drupal-custom-module"],
            "web/themes/custom/{$name}": ["type:drupal-custom-theme"]
        },
        "drupal-core-project-message": {
            "include-keys": ["homepage", "support"],
            "post-create-project-cmd-message": [
                "<bg=blue;fg=white>                                                         </>",
                "<bg=blue;fg=white>  Congratulations, you’ve installed the Drupal codebase  </>",
                "<bg=blue;fg=white>  from the drupal/recommended-project template!          </>",
                "<bg=blue;fg=white>                                                         </>",
                "",
                "<bg=yellow;fg=black>Next steps</>:",

                "  * Install the site: https://www.drupal.org/docs/8/install",
                "  * Read the user guide: https://www.drupal.org/docs/user_guide/en/index.html",
                "  * Get support: https://www.drupal.org/support",
                "  * Get involved with the Drupal community:",
                "      https://www.drupal.org/getting-involved",
                "  * Remove the plugin that prints this message:",
                "      composer remove drupal/core-project-message"
            ]
        }
    }
}

```

Here the Error-Message while running composer install inside the container

```
:/var/www/html/web$ composer install
No composer.json in current directory, do you want to use the one at /var/www/html? [Y,n]? y
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 9 installs, 0 updates, 0 removals
  - Installing drupal/coder (8.3.6): Cloning 4337ddf58d from cache
    4337ddf58d28dbdee4e1367bf71ee13393ab9820 is gone (history was rewritten?)

  [RuntimeException]
  Failed to execute git checkout '4337ddf58d28dbdee4e1367bf71ee13393ab9820' -- && git reset --hard '4337ddf58d28dbdee4e1367bf71ee13393ab9820' --

  fatal: failed to read object 4337ddf58d28dbdee4e1367bf71ee13393ab9820: Operation not permitted

install [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [--no-suggest] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--i
gnore-platform-reqs] [--] [<packages>]...

```

And here when running composer install locally inside the source dir:

```
λ composer install
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 9 installs, 0 updates, 0 removals
  - Installing drupal/coder (8.3.6):     Authentication required (git.drupalcode.org):
      Username:

```

I started by installing D8 like described here https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies This initially worked and we commited the codebase (mostly composer.json & composer.lock) into our git-lab, but after checkout to a different folder and runing composer install with the composer.json & composer.lock fails as described above.

# Answer
> 0 votes
I am not sure yet why, but running composer install --no-cache fixes that issue for me. Maybe someone could shine some more light on whats going on there.

```
uid1000@drupal-web:/var/www/html/web$ composer install --no-cache
No composer.json in current directory, do you want to use the one at /var/www/html? [Y,n]? y
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 9 installs, 0 updates, 0 removals
  - Installing drupal/coder (8.3.6): Cloning 4337ddf58d
  - Installing seld/phar-utils (1.0.1): Downloading (100%)
  - Installing seld/jsonlint (1.7.1): Downloading (100%)
  - Installing composer/composer (1.9.1): Downloading (100%)

```

---
Tags: installation, composer
---


# Question
Title: How can I add a field in Entityform / hook_form_alter
I'm trying to add a field to the form in hook\_form\_alter. What's the proper way of adding fields in this hook in case of entityform?

I tried to add it this way:

```
$form['leadname'] = array(
    '#type' => 'hidden',
    '#value' => 'abc'
);

```

but I have the impression that this is not the way it should be done...

# Answer
That is the way it should be done.

For example using

```
MODULE_form_ENTITYFORM_MACHINE_NAME_entityform_edit_form_alter(&$form, &$form_state) {}

```
> 0 votes

# Answer
You have to use the following API's

Reference
> -1 votes

---
Tags: 7, forms
---


title: Migrating into Double field

text:
# Question
Title: Migrating into Double field
I am migrating a CSV into D8 node type which has a double field. The CSV has the following structure:

I am trying to migrate the **year**, from the header, into the first double-field subfield (as a label) and the **population** data for each country (Afganistan, in the example above) into the second double-field subfield.

The double-field has the following interface (the data in this example was entered manually):

And, this is how the data is represented in the node as seen via Devel:

I have tried a variety of things in my migration yaml code but I have not been able to migrate either the year nor population data. My code is below:

```
.
.
.
process:
  type:
    plugin: default_value
    default_value: census
  title: 'Country Name'
  field_country_code: 'Country Code'
  field_count_first:
    0:
      plugin: get
      source:
        - 1960
.
.
.
------- also - tried -----------
.
.
.
process:
  type:
    plugin: default_value
    default_value: census
  title: 'Country Name'
  field_country_code: 'Country Code'
  field_count:
    first:
      0:
        plugin: get
        source:
          - 1960
.
.
.

```

I would appreciate some help.

# Answer
Ran into exactly the same issue, here is my solution. In my case for field 'first' I have a select list of contact types in field 'second' it is a plain text field. For one of the source fields I am converting a taxonomy term to a plain text so there is a service injected to do a lookup up from the source database. The migration config looks like this for the fields I want to convert:

```
  field_phoned:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: num_office
      source: field_phoned
  field_mobile_number:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: num_mobile
      source: field_mobile_number
  field_skype_contact:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: skype
      source: field_skype_contact
  field_whatsapp_number:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: whatsapp
      source: field_whatsapp_number
  field_location_taxonomy:
    -
      plugin: add_contact_info_field
      target_field: field_contact_info
      target_label: location
      source: field_location_taxonomy

```

The process plugin 'add\_contact\_info\_field':

```
<?php

namespace Drupal\custom_migrate_tools\Plugin\migrate\process;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\custom_migrate_tools\TermLookupInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a 'AddParagraphBody' migrate process plugin.
 *
 * @MigrateProcessPlugin(
 *  id = "add_contact_info_field"
 * )
 */
class AddContactInfoField extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  /**
   * Lookup source term service.
   *
   * @var \Drupal\custom_migrate_tools\TermLookupInterface
   */
  protected $termLookup;

  /**
   * The migration.
   *
   * @var \Drupal\migrate\Plugin\MigrationInterface
   */
  protected $migration;

  /**
   * TaxonomyLookup constructor.
   *
   * @param array $configuration
   * @param $pluginId
   * @param $pluginDefinition
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   * @param \Drupal\custom_migrate_tools\TermLookupInterface $termLookup
   */
  public function __construct(array $configuration,
                              $pluginId, $pluginDefinition,
                              MigrationInterface $migration,
                              TermLookupInterface $termLookup) {
    parent::__construct($configuration, $pluginId, $pluginDefinition);
    $this->migration = $migration;
    $this->termLookup = $termLookup;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $pluginId,
      $pluginDefinition,
      $migration,
      $container->get('custom_migrate_tools.term_lookup')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $contact_info = [];
    if ($label = $this->configuration['target_label']) {
      $contact_info[0]['first'] = $label;
    }
    else {
      $contact_info[0]['first'] = $label;
    }

    if ($destination_property == 'field_location_taxonomy') {
      $contact_info[0]['second'] = $this->termLookup->getTermName($value['target_id'])->name;
    }
    else {
      $contact_info[0]['second'] = $value['value'];
    }

    if ($targetField = $this->configuration['target_field']) {
      if ($field_contact_info = $row->getDestinationProperty($targetField)) {
        array_push($field_contact_info, reset($contact_info));
      }
      else {
        $field_contact_info = $contact_info;
      }
      $row->setDestinationProperty($targetField, $field_contact_info);
    }
    return $value;
  }

}

```
> 0 votes

---
Tags: 8, nodes, migrations
---


# Question
Title: Unable to retrieve checkbox values from a template file
I have created a checkbox option for a field.

* Category

+ One
    + Two
    + Three
    + Four

This is the code I am using.

```
    {% for key, item in content.field_room_category if key|first != '#' %}
         <li>{{ item }}</li>
    {% endfor %}

```

In the `<li>` tag, I get all the checked values, but I also need to check which values have been selected.

For this, I tried `{{ item.value }}`, `{{ item.content }}`, and `{{ item['#title'] }}`. None of them worked.

Is there any way to get all the checkbox items with their values?

>

I want to achieve something similar to the image above. If the item is checked, I show an icon; if the item is unchecked, another icon will be shown.

# Answer
Checkbox values are preprocessed so only checked ones you can get in your twig:
I think you need to preprocess your field by implementing `hook_preprocess_HOOK` to add unchecked ones to your variables something like:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MY_MODULE_preprocess_field(&$variables) {
  $element = $variables['element'];
  if ($element['#field_name'] == "field_room_category") {
    // Node object.
    $node = $element['#object'];
    // All allowed values in the field.
    $allowed_values = $node->field_room_category->getFieldDefinition()
      ->getSetting('allowed_values');

    // Checked values.
    $checked_values = array_filter($element, function ($key) {
      return is_int($key);
    }, ARRAY_FILTER_USE_KEY);

    for ($i = 0; $i < count($allowed_values); $i++) {
      // If the checkbox already checked add is_selected as true.
      if (isset($checked_values[$i])) {
        $variables['element'][$i]['is_selected'] = TRUE;
      }
      else {
        // If the checkbox not checked add the item with is_selected as false.
        $variables['element'][$i] = [
          '#markup'       => current(array_slice($allowed_values, $i-1, 1, FALSE)),
          '#allowed_tags' => [],
          'is_selected'   => FALSE,
        ];
      }
    }
  }
}

```

now in your twig you can do something like:

```
  {% for key, item in element if key|first != '#' %}
     <li>
       {% if item.is_selected %}
         <span style="color: green;">  {{ item }} </span>
       {% else %}
         <span style="color: red;">  {{ item }} </span>
       {% endif %}
     </li>
   {% endfor %}

```
> 1 votes

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


title: Create cookie after download file

text:
# Question
Title: Create cookie after download file
I want to create a **cookie after a file download**.

This is an extension on the existing module: https://www.drupal.org/project/file\_utility

Each time you click on a download, a popup opens. For me it is fine to have the visitors e-mail address once. Then direct download is possible without showing the popup again on other download pages.

This part of code is not generating a cookie .. why?

**EDIT: $c\_response-\>send(); was missing here.**

```
    $c_response = new \Symfony\Component\HttpFoundation\Response();
    $c_response->headers->setCookie(new \Symfony\Component\HttpFoundation\Cookie('foo', 'bar'));
    $c_response->send();

    // Get cookie value
    $c_request  = new \Symfony\Component\HttpFoundation\Request();
    $c_value = $c_request->cookies->get('foo');

    if($c_value) {
        \Drupal::logger('file_utility')->notice($c_value);
    } else {
        \Drupal::logger('file_utility')->notice("cookie foo is empty");
    }

```

This is the function where the download logic happens: In this function, first I need to check if the cookie exists. If so, direct download can start. If not, popup must be initiated. The first time, the cookie will be empty.

```
    public function downloadAction() {
        // Get cookie value
        $c_request = new \Symfony\Component\HttpFoundation\Request();
        $c_value = $c_request->cookies->get('foo');
        \Drupal::logger('file_utility')->notice("cookie: " . $c_value);
        if ($c_value) {
            \Drupal::logger('file_utility')->notice($c_value);
        } else {
            \Drupal::logger('file_utility')->notice("cookie foo is empty");
        }

        /** set cookie if $c_value is empty **/
        $c_response = new \Symfony\Component\HttpFoundation\Response();
        $c_response->headers->setCookie(new \Symfony\Component\HttpFoundation\Cookie('foo2', 'bar2'));
        $c_response->send();
        /** end set cookie **/

        if (!isset($_GET['f_path'])) {
            return;
        }
        // Process download.
        $f_path_encoded = \Drupal::request()->query->get('f_path');
        $full_path = base64_decode(urldecode($f_path_encoded));
        $force_download = \Drupal::request()->query->get('force_download');
        $response['file_name'] = basename($full_path);
        $uid = \Drupal::currentUser()->id();
        $user = User::load($uid);
        if ($user->hasPermission('file download access') && $force_download == '1') {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($response['file_name']) . '"');
            header('Expires: 0');
            header('Content-Transfer-Encoding: binary');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            // Flush system output buffer.
            flush();
        } elseif ($user->hasPermission('file download access') && $force_download == '0') {
            $response = new RedirectResponse($full_path);
            $response->send();
            die;
        } else {
            $url = $full_path;
            if (strpos($full_path, 'sites/default') !== FALSE) {
                throw new AccessDeniedHttpException();
            } else {
                $response = new RedirectResponse($url);
                $response->send();
                die;
            }
        }

    }

```

**Extra: Can I set the cookie after the formsubmit?** I found that you can add a response to a form\_state but that is also not setting the cookie. I have added the first 3 lines in below function, but that is not working at the moment.

```
     /**
     * AJAX callback handler that displays any errors or a success message.
     */
    public function submitUserInfoFormAjax(array $form, FormStateInterface $form_state) {
        $c_response = new \Symfony\Component\HttpFoundation\Response();
        $c_response->headers->setCookie(new \Symfony\Component\HttpFoundation\Cookie('john', 'do'));
        $form_state->setResponse($c_response);

        $response = new AjaxResponse();
        $value = $form_state->getValues();
        //$name = $value['name'];
        $email = $value['email'];
        $user_ip = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : \Drupal::request()->getHost();
        $f_path_encoded = \Drupal::request()->query->get('f_path');
        $f_path = base64_decode(urldecode($f_path_encoded));
        $force_download = \Drupal::request()->query->get('force_download');
        // If there are any form errors, re-display the form.
        if ($form_state->hasAnyErrors()) {
            $response->addCommand(new ReplaceCommand('#status_message_div', $form));
        } else {
            $status = parent::save($form, $form_state);

            $entity = $this->entity;
            $response->addCommand(new RedirectCommand('/filedownload?f_path=' . $f_path_encoded . '&force_download=' . $force_download));
            $response->addCommand(new CloseModalDialogCommand());
        }

        return $response;
    }

```

**Important notice for making the cookie available for javascript:**

httponly must be set to false in the constructor.

```
$response->headers->setCookie(new \Symfony\Component\HttpFoundation\Cookie('_john', 'do', time() + 3600, '/', '.yourdomain.com', false, false));

```

# Answer
> 1 votes
I think the problem in your current code is that you're overwriting the response. You should add the cookie to the default AjaxResponse instead:

```
public function submitUserInfoFormAjax(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    $response->headers->setCookie(new \Symfony\Component\HttpFoundation\Cookie('john', 'do'));

    $value = $form_state->getValues();
    //$name = $value['name'];
    $email = $value['email'];
    $user_ip = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : \Drupal::request()->getHost();
    $f_path_encoded = \Drupal::request()->query->get('f_path');
    $f_path = base64_decode(urldecode($f_path_encoded));
    $force_download = \Drupal::request()->query->get('force_download');
    // If there are any form errors, re-display the form.
    if ($form_state->hasAnyErrors()) {
        $response->addCommand(new ReplaceCommand('#status_message_div', $form));
    } else {
        $status = parent::save($form, $form_state);

        $entity = $this->entity;
        $response->addCommand(new RedirectCommand('/filedownload?f_path=' . $f_path_encoded . '&force_download=' . $force_download));
        $response->addCommand(new CloseModalDialogCommand());
    }

    return $response;
}

```

---
Tags: 8, cookies
---


# Question
Title: Possible to use EntityStorageBase::loadByProperties() to specify that field is or is not empty?
Is there a way to use `EntityStorageBase::loadByProperties()` to specify that a field is either empty or not empty? I just want to check whether or not a `field_date_completed`has a value set one it.

Looking to do something like `$this->myEntityStorage->loadByProperties(['field_date_completed'=> notEmpty])` or `$this->myEntityStorage->loadByProperties(['field_date_completed'=> isEmpty])`

EDIT: Sorted out a solution using the accepted answer. Per How get empty record on date field with entityQuery?, we can do something like

```
$query = $this->myEntityStorage
  ->getQuery()
  ->notExists('field_data_completed');

$entity_ids = $query->execute();

```

# Answer
> 1 votes
Only in a narrow scope where "empty" for the field means the empty string (`''`) and it's stored as such in the DB.

`EntityStorageBase::loadByProperties()` uses a helper method, `::buildPropertyQuery()`, that chains comparisons using the `IN` operator. As such, you can't use negation or special comparison cases (e.g. `IS NULL` if "empty" means `NULL` in the DB).

Unless you have simple string comparisons for your field, you're better off skipping `::loadByProperties()` and using `EntityStorageBase::getQuery()` to retrieve a query object that you can customize to fit a "empty" / "not empty" query.

---
Tags: 8, entities
---


title: Unable to apply patch

text:
# Question
Title: Unable to apply patch
I am unable to apply patch using composer in Drupal core 8.6.4. Can anyone help me to apply patch using composer? Here is the process what I am doing :

```
{
"name": "drupal/drupal",
"description": "Drupal is an open source content management platform powering millions of websites and applications.",
"type": "project",
"license": "GPL-2.0-or-later",
"require": {
    "composer/installers": "^1.0.24",
    "wikimedia/composer-merge-plugin": "^1.4",
    "drupal/admin_toolbar": " ^1.25",
    "drupal/config_ignore": "^2.1",
    "drupal/config_split": "^1.4",
    "drupal/devel": "^1.2",
    "drupal/paragraphs": "^1.5",
    "drupal/pathauto": "^1.3",
    "drupal/s3fs": "^3.0-alpha13",
    "drupal/field_group": "^3.0-beta1",
    "drush/drush": "^9.4",
    "drupal/backup_migrate": "^4.0",
    "drupal/restui": "^1.16",
    "drupal/conditional_fields": "^1.0-alpha4",
    "drupal/ckeditor_font": "^1.0",
    "drupal/colorbutton": "^1.1",
    "library-ckeditor/panelbutton": "^4.11",
    "library-ckeditor/colorbutton": "4.11.1",
    "drupal/migrate_plus": "^4.1",
    "drupal/migrate_tools": "^4.1",
    "drupal/migrate_source_csv": "^2.2",
    "drupal/migrate_file": "^1.1",
    "drupal/taxonomy_import": "^1.0",
    "drupal/metatag": "^1.7",
    "predis/predis" : "^1.1.1",
    "drupal/rabbitmq": "^1.1",
    "php-amqplib/rabbitmq-bundle": "^1.14",
    "drupal/ultimate_cron":"^2.0-alpha4",
    "cweagans/composer-patches": "~1.0"
},
"require-dev": {
    "asm89/twig-lint": "^1.0",
    "dealerdirect/phpcodesniffer-composer-installer": "^0.5.0",
    "drupal/coder": "^8.2.12"
},
"replace": {
    "drupal/core": "^8.6"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
    "preferred-install": "dist",
    "autoloader-suffix": "Drupal8"
},
"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php.",
        "This file specifies the packages.drupal.org repository.",
        "You can read more about this composer repository at:",
        "https://www.drupal.c/node/2718229"
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json"
        ],
        "recurse": true,
        "replace": false,
        "merge-extra": false
    },
    "installer-paths": {
        "core": ["type:drupal-core"],
        "modules/contrib/{$name}": ["type:drupal-module"],
        "profiles/contrib/{$name}": ["type:drupal-profile"],
        "themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"],
        "modules/custom/{$name}": ["type:drupal-custom-module"],
        "themes/custom/{$name}": ["type:drupal-custom-theme"]
    },
    "enable-patching": true,
    "patches": {
        "drupal/core": {
            "Search autocomplete from views result": "https://www.drupal.org/files/issues/2019-01-10/2174633-238.patch"
        }
    }
},
"autoload": {
    "psr-4": {
        "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
    }
},
"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "drupal-phpunit-upgrade-check": "Drupal\\Core\\Composer\\Composer::upgradePHPUnit",
    "drupal-phpunit-upgrade": "@composer update phpunit/phpunit phpspec/prophecy symfony/yaml --with-dependencies --no-progress",
    "phpcs": "phpcs --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --",
    "phpcbf": "phpcbf --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --"
},
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    },
    {
        "type": "package",
        "package": {
            "name": "library-ckeditor/panelbutton",
            "version": "4.11.1",
            "type": "drupal-library",
            "dist": {
                "url": "https://download.ckeditor.com/panelbutton/releases/panelbutton_4.11.1.zip",
                "type": "zip"
            }
        }
    },
    {
        "type": "package",
        "package": {
            "name": "library-ckeditor/colorbutton",
            "version": "4.11.1",
            "type": "drupal-library",
            "dist": {
                "url": "https://download.ckeditor.com/colorbutton/releases/colorbutton_4.11.1.zip",
                "type": "zip"
            }
        }
    }
]

```

}

Command: composer install - but nothing happens.

# Answer
> 1 votes
You need 'composer require cweagans/composer-patches' in order to apply patches.

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


# Question
Title: Which event should we subscribe to if we want code to be triggered when a new user registers?
I noticed that *account.set* is the event invoked for a user account.

I want to create an event subscriber which adds a callback invoked when a new user registers on the site. I am not sure whether *account.set* is the correct event.

Are there other better events for this?

# Answer
> 3 votes
`AccountEvents::SET_USER` isn't the event for user registration. Per the docs:

> This event allows modules to perform an action whenever the current user is set. The event listener receives an \Drupal\Core\Session\AccountSetEvent instance.

The event is fired when Drupal initializes the user object for the current request, not when new users are created.

For responding to new user creation, you can still use `hook_user_insert()`.

# Answer
> 3 votes
> Aww. I was hoping to write an event subscriber and use Drupal 8's new methods to get the job done. What a pity ;-)

**You could using the Hook Event Dispatcher module**, see README.md file on how to use.

> This module dispatches events for several Drupal core hooks. This allows you to use the D8 Event Subscriber system, instead of the outdated hook system, to react on certain events.

---
Tags: 8, event-subscribers
---


# Question
Title: is it possible to populate subclass of FieldItemList from code?
The context first:

I'm migrating a website from D7 to D8 and one of the modules has no update on D8. I found an alternate module with the same functionality.

For the FieldType of the alternate module, it consists in a subclassOf FieldItemList, lets say MyFieldItemList and a subclass of FieldItemBase, lets say MyFieldItemBase.

I'm quite stuck on this:

1. I exported the data from D7 using views and a csv generation export
2. I'm creating a micro Drupal 8 module to upload csv file and populate existing nodes with csv data
3. I can get the subclass of FieldItemList from my node and saw the "append(...)" method in documentation.
4. I can't manage to find how to create a new item of type MyFieldItemBase

I can't find any examples in existing modules and over the web, is there a flaw in the import process I wanted to follow?

# Answer
So I found out what I was trying to do in a complicated way could be done by simply setting the field values on the node, like this:

```
            $node->set($field_name, $field_values);
            $node->save();

```
> 0 votes

---
Tags: 8, entities, migrations
---


# Question
Title: How to show reset button in a view only when filter is applied?
I have created a view with four exposed filters. In exposed form settings, I added a reset link and used auto submit option. Filter and reset works fine without error, but I want to show the reset button only when the filter is applied. If no filter is applied, there should not be reset button.

I have searched, but I didn't find any solution.

How can I achieve this?

# Answer
> 1 votes
`hook_form_alter()` can also do this

```
function module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'Your_form_id") {
    if (!$form_state['view']->exposed_input) {
      unset($form['reset']);
    }
  }
}

```

You will have some other value for \['view'\]-\>exposed\_input. Use dpm(0 to get the exposed\_input value. \['view'\]-\>exposed\_input returns nothing if filter is not applied. Hope it works.

# Answer
> 0 votes
You can achieve this either using custom module\[hook\] or jQuery.

**Using jQuery**

1. Hide **Reset** button using CSS `display:none`.
2. Now in jQuery, on page load, check for URL containing **Query String.**

> **Example:** \[view-URL\]/?type=page.

3. If URL contains any **Query String**, then make **Reset** button visible.

# Answer
> 0 votes
Thanks, Vamsi! I a bit fix your code.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  // Show reset button in a view only when filter is applied.
  if (isset($form['reset']) && empty($form_state['view']->exposed_input)) {
    unset($form['reset']);
  }
}

```

---
Tags: 7, views
---


# Question
Title: How do I save uploaded file permanently in file_manged table?
How do I save a uploaded file with status equal to 1 in the file\_managed table, in Drupal 8?

Whenever I upload a file, it is stored in the file\_managed table with status value 0.
I have used `File::load( $form_state->getValue('image'))` to load the file. What do I need to do next?

In Drupal 7, I would use `$file->status = FILE_STATUS_PERMANENT`. What is the equivalent code for Drupal 8?

```
class AddBannerForm extends FormBase {

  public function getFormId() {
    return 'add_banner_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['image'] = [
      '#type' => 'managed_file',
      '#title' => t('Choose Image File'),
      '#upload_location' => 'public://images/',
      '#default_value' => '',
      '#description' => t('Specify an image(s) to display.'),
      '#states' => [
        'visible' => [
          ':input[name="image_type"]' => ['value' => t('Upload New Image(s)')],
        ],
      ],
    ];

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

    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    File::load($form_state->getValue('image'));
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {

  }
}

```

# Answer
> 20 votes
Thank you **@Clive** & **@kiamlaluno**

```
/* Fetch the array of the file stored temporarily in database */
   $image = $form_state->getValue('image');

/* Load the object of the file by it's fid */
   $file = File::load( $image[0] );

/* Set the status flag permanent of the file object */
   $file->setPermanent();

/* Save the file in database */
   $file->save();

```

# Answer
> 6 votes
Use this code to save the image permanently in the configuration form, if you are using Drupal 8.

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);
  $image = $form_state->getValue('welcome_image');
  // Load the object of the file by its fid.
  $file = File::load($image[0]);
  // Set the status flag permanent of the file object.
  if (!empty($file)) {
    $file->setPermanent();
    // Save the file in the database.
    $file->save();
    $file_usage = \Drupal::service('file.usage');
    $file_usage->add($file, 'welcome', 'welcome', \Drupal::currentUser()->id());
  }
  $config = $this->config('welcome.settings');
  $config->set('welcome_text', $form_state->getValue('welcome_text'))
    ->set('welcome_image', $form_state->getValue('welcome_image'))
    ->save();
}

```

# Answer
> -1 votes
You might also need to disable cache in your buildForm function

```
$form_state->disableCache();

```

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


# Question
Title: Source entity type and id in webform node
Im looking for a way to set the source entity type and id to a webform that is inside a webform content type (webform\_node)

I followed the modal convention: the address of the webform is `/webform/14?source_entity_type=node&source_entity_id=15` Now i would like this to work.

in `QueryStringWebformSourceEntity` class i see the notice

```
 // Note: We deliberately discard $ignored_types because through query string
 // any arbitrary entity can be injected as a source.

```

which makes sense. what are my options then to add my source identity to the webform submission?

thank you!

# Answer
> 0 votes
a naive solution:

```
function THEME_preprocess_node(&$variables){
  //adding query source entity and type to a webform node
 if($variables['node']->getType()=='webform'){
   if (\Drupal::request()->get('source_entity_type') && \Drupal::request()->get('source_entity_id')){
     $variables['content']['webform'][0]['#entity_type'] = \Drupal::request()->get('source_entity_type');
     $variables['content']['webform'][0]['#entity_id'] = \Drupal::request()->get('source_entity_id');
  }
 }
}

```

---
Tags: 8, webforms
---


# Question
Title: is there any possible conflict for fields with the same machine name?
i am trying to debug a paragraph not displaying fields and i am having

> /admin/reports/fields

a same machine name for a field in 3 different paragraphs

```
field_call_to_action_ref    paragraph   Entity reference revisions (module : entity_reference_revisions)

    Bloc compositeParagraphe standardElement d'accordéon

```

# Answer
Machine names for fields must be unique per entity type.

The means that with nodes, fields must be unique across all content types. So you can't create two fields with the same machine name on different content types, as both content types are nodes, and machine names must be unique for the entity type. (Edit - you can however re-use the same field on multiple content types, but it will be the same field, not two fields with the same machine name).

You can have a `field_image` on a node, and `field_image` on a taxonomy term. Here, the machine name is the same, but unique to each entity type, so there is no problem.
> 3 votes

---
Tags: paragraphs, entities
---


# Question
Title: Can I somehow edit libraries.yml files from the backend using the admin panel?
In my Drupal project, we load custom CSS for some of our specific pages. Right now I do all of these modifications programmatically.

But what our manager wants is to create it manually in the admin panel. Uploading the CSS file in the new content type I'll create.

I'm a bit worried because I add these custom CSS we had in the libraries.yml like this:

Is there anyway they can edit this yml file in the admin panel? Or is there any better ideas I can do when adding custom CSS?

EDIT: I need to setup an advanced rule. In our project, each of our articles contain categories. And we apply different CSS files in some special categories. So basically what I'm doing is I query the categories of the article and inject the custom CSS. I attach the CSS like this in the page\_attachment.inc:

# Answer
To directly answer your question, yes, you can edit config with the devel module. Install it, then configure it to display the Config Editor.

To answer your question pragmatically, I need to point out that making direct edits to configuration on a regular basis is a recipe for disaster. I think you would be better served using the Asset Injector module, which will allow you to add CSS and JS on the fly, without tinkering with configuration files.

If it is an absolute necessity to modify the library definition, then I think that hook\_library\_info\_alter() is what you need. However, as leymannx points out, libraries aren't intended to be constantly manipulated on the fly. This brings me back to using the Asset Injector. The CSS injector portion is pretty much perfectly suited to your use case; it allows for adding and editing CSS through the admin interface. The CSS injector allows for multiple rules, and these can each be targeted based on path and/or theme.

If you combine this with custom classes attached to the page, then you can use those classes in your CSS rules. You can implement hook\_preprocess\_page() to do this:

```
myproject_preprocess_page(&$variables) {
  $node = $variables['node'];
  if ($node) {
    // Assume that the Taxonomy Vocabulary machine name is "category".
    /** @var \Drupal\taxonomy\Entity\Term[] $terms */
    $terms = \Drupal::entityTypeManager()
      ->getStorage("taxonomy_term")
      ->loadByProperties(["vid" => "category"]);
    // Get all categories present on the current node.
    $categories = $node->get('field_category')->getValue();
    // Get just the TIDs as a simplified array.
    $categories = array_column($categories, 'target_id');
    // Ensure that there is a class array.
    $variables['attributes']['class'] = $variables['attributes']['class'] ?? [];
    foreach($categories as $category) {
      // Craft a HTML-compliant class name based on the label.
      $variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($terms[$category]->label());
    }
  }
}

```
> 1 votes

# Answer
I assume, you can use next modules for your manager (without editing yml files, so no skills required for editing this important one file):

CSS Editor This module allows site builders to customize a theme's CSS through the browser, using a rich text editor with syntax highlighting and live preview.

Asset injector This module is definitely not a replacement for full-fledged theming, but it provides site administrators with a quick and easy way of tweaking things without diving into full-fledged theme hacking.
> 0 votes

---
Tags: 8, theming
---


title: Render TableField

text:
# Question
Title: Render TableField
I am using the `TableField` module and trying to render a field of this type in a custom block. I have tried many different approaches but I am not able to get any output. For instance:

```
{{ product.entity.field_table.value }}
{{ product.entity.field_table.0.value }}
{{ product.entity.field_table.entity.field_table }}

```

Can anyone tell me what I am doing wrong here?

I manage to output the table using the following code, but it does not seem to be the best solution:

```
{% for row in product.entity.field_table.entity.field_table.getValue().0.value %}
<tr>
  <td>{{ row.0 }}</td>
  <td>{{ row.1 }}</td>
</tr>
{% endfor%}

```

# Answer
This may not be the most elegant solution, but based upon your preliminary solution and using the output from `{{ dump(tableItem }}` (the dump is just commented out in the code below; also see code for meaning of `tableItem`), I was able to extend getting the necessary values in a generic way to output all the values of a given table. Also, after the table, the following code will output the caption of the tablefield widget. The `field_data_tables` is the machine name of the tablefield widget for this node. In reference to the original poster, the `node` in this code would correspond to the `product` in the OP.

Note that the code also uses row and col counters because the last col and last row contain non-table values, so we have to exclude those in the `{% for ... %}` loops.

```
{# The tableItem is the array of table values in the tablefield widget #}
{# Last row & col contain non-table values so use counters to exclude last row & col #}

{% for tableItem in node.field_data_tables.getValue() %}

        {# dump(tableItem) #}

        {% set rowCount = tableItem['value'] | length %}

        <table border="1">
          {% set rowCounter = 1 %}

          {% for rows in tableItem['value'] if rowCounter < rowCount %}

            {%  set colCount = rows | length %}

            <tr>
              {% for i in 0..colCount-1 %}
                <td> {{ rows[i] }} </td>
              {% endfor %}
            </tr>

            {% set rowCounter = rowCounter + 1 %}
          {% endfor %}

        </table>

        {{ tableItem.caption }} <br>

      {% endfor %}

```
> 0 votes

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


# Question
Title: How to get username of two different ids
I have created a block inside a module and in that, I just need to get usernames of two different Ids

```
$account = \Drupal\user\Entity\User::load($id_1);
$account_2 = \Drupal\user\Entity\User::load($id_2);
$tenant_name = $account_2->getUsername();
$owner_name = $account->getUsername();

```

I have used this code.

# Answer
> 0 votes
The function `getUsername()` is deprecated and returns the below error

> \Drupal\Core\Session\AccountInterface::getUsername() is deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0. Use \Drupal\Core\Session\AccountInterface::getAccountName() or \Drupal\user\UserInterface::getDisplayName() instead. See https://www.drupal.org/node/2572493

The correct way to get user/account name from user object is to call its `getAccountName()` function.

**Example:**

```
use Drupal\user\Entity\User;

$account = User::load($user_id);
$name = $account->getAccountName();

```

---
Tags: entities
---


title: Fixing Class Not Found error

text:
# Question
Title: Fixing Class Not Found error
I recently moved a module from one location to another location and I am getting a `ClassNotFoundException`. Is there something similar to Registry Rebuild Module that can help rebuild the registry?

# Answer
> 25 votes
In addition to the usual cache rebuild, the additional need to restart the web server is due to a decision in Drupal 8 to be 'fast by default' use the APC Classloader if it is available. It is faster, but it doesn't necessarily catch changes as you make them. To not have to restart your web server during development, you can set your local environment to *not* try to use a better-for-production class loader.

For instance, in **local.settings.php** add:

```
$settings['class_loader_auto_detect'] = FALSE;

```

Via, and more background information at, what to do when developing a Drupal 8 module and a class file just isn't being loaded even though it is definitely there.

# Answer
> 5 votes
In Drupal 8 the equivalent of Registry Rebuild is built in to Cache Rebuild. If your site is not accessible you will need to use Drush. Its an indispensable tool in D8 for just this reason.

`drush cr`

# Answer
> 4 votes
"drush cr" may not always work. You may have to restart your Web server to pick up new file locations. This is due to some caching at that level.

# Answer
> 3 votes
I recently got this issue of "class not found" with a custom module. The strange thing is that this problem occurred in a **multi-sites** installation after installation of new site on server. But the issue never pop-up before with other sites with same modules and configuration. Thus it is very strange. I tried all sort of cache clearing, composer updates, restarts and so on. Also tried to replicate the installation on local computer and it worked fine in this case.

I really can't figure out what could be the explanation and why it happens specifically on a "sub" site and not on the others.

The only solution I could implement is for this particular setting is

```
$settings['class_loader_auto_detect'] = FALSE;

```

which is working but does not bring any clue on the issue.

Any idea on the direction to look for is welcome. Thanks

# Answer
> 1 votes
The easiest solution could be visiting `www.yoursite.com/core/install.php` location on your website.

If that doesn't solve your problem take a look at https://www.drupal.org/documentation/rebuild for further debugging which gives an exhaustive list of what could have gone wrong in your installation.

# Answer
> -1 votes
You can also call following path /core/rebuild.php like: mydrupalsite.test/core/rebuild.php

---
Tags: 8
---


# Question
Title: Adding Vue.js to my theme with Webpack not working
I am trying adding Vue.js into my Drupal 8 theme with my Webpack setup (which I had already working).

It's all compiling fine with Webpack, without errors after my npm script `npm run build`.

---

In my `index.js` I have:

```
import './styles.css';
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

```

---

In my `App.vue` I have:

```
<template>
  <div id="app">
    <HelloWorld msg="Coming Soon: Near-Earth Objects"/>
  </div>
</template>

<script>
  import HelloWorld from './components/HelloWorld.vue'

  export default {
    name: 'app',
    components: {
      HelloWorld
    }
  }
</script>

<style>

</style>

```

---

In my `./components` folder I have `HelloWorld.vue`

First I am trying now to render my Vue component inside `header.html.twig` like

```
<hello-world></hello-world>

```

My thoughts are, by the element in page.html.twig I can show, arrange and position all my Vue.js components where I want. Is that correct?

But why is my component not showing up?

**Update:**

I figured out. My webpack.config.js is splitting Vue into `/themes/custom/my_theme/dist/vendors~main.bundle.js`. By this setting:

```
config.optimization = {
      splitChunks: {
        chunks: "all"
      },

```

What is the purpose of this? Isn't it better to compile it all into the same file `main.bundle.js`?

# Answer
I recommend looking into the Decoupled Pages module which can make integrating Vue.js simpler.
> -1 votes

---
Tags: 8, javascript
---