# Question
Title: [user-name]@git.drupal.org: Permission denied (publickey)
I am trying to use git.drupal.org without success...

* I have uploaded my public key in the `SSH keys`tab under my profile
* I have checked that the fingerprint on Drupal match my fingerprint in `.ssh/id_rsa`
* I have Filled in the `Git access` tab under my profile=\> I got a username and I accepted the agreement

But when I run: `GIT_SSH_COMMAND="ssh -vvv -p 22 -i /home/myname/.ssh/id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" git clone my_user_name@git.drupal.org:project/a_project.git`

I got the following error: `my_user_name@git.drupal.org: Permission denied (publickey).`

Here is the output: (to anonymize the following, I replaced my Git user name by "my\_user\_name" and my computer User name by "myname")

```
OpenSSH_7.9p1 Ubuntu-10, OpenSSL 1.1.1b  26 Feb 2019
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "git.drupal.org" port 22
debug2: ssh_connect_direct
debug1: Connecting to git.drupal.org [140.211.10.58] port 22.
debug1: Connection established.
debug1: identity file /home/myname/.ssh/id_rsa type 0
debug1: identity file /home/myname/.ssh/id_rsa-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.9p1 Ubuntu-10
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4p1 Debian-10+deb9u6
debug1: match: OpenSSH_7.4p1 Debian-10+deb9u6 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to git.drupal.org:22 as 'my_user_name'
debug3: hostkeys_foreach: reading file "/dev/null"
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:FeJiekFTTnXWc1GDUfFVcRckyZkZfdmks1dSqtS6OVg
debug3: hostkeys_foreach: reading file "/dev/null"
debug3: hostkeys_foreach: reading file "/dev/null"
Warning: Permanently added 'git.drupal.org,140.211.10.58' (ECDSA) to the list of known hosts.
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug1: Skipping ssh-dss key myname@mycomputer - not in PubkeyAcceptedKeyTypes
debug1: Will attempt key: /home/myname/.ssh/id_rsa RSA SHA256:J9ZRdKhvB9rfq/uchczwpi2CyvOqzktf9q+12AIetxE explicit agent
debug2: pubkey_prepare: done
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /home/myname/.ssh/id_rsa RSA SHA256:J9ZRdKhvB9rfq/uchczwpi2CyvOqzktf9q+12AIetxE explicit agent
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
my_user_name@git.drupal.org: Permission denied (publickey).
fatal: Could not read from remote repository.

```

Any hint?

\`

# Answer
Cloning a project as maintainer of that project is done using the following command.

```
git clone git@git.drupal.org:project/a_project.git

```

The username is always *git*.

As non-maintainer, the command to clone the project is the following.

```
git clone https://git.drupalcode.org/project/a_project.git

```

When I want to clone one of the projects hosted on drupal.org for which I am maintainer, I use the following command.

```
git clone drupal:project/a_project.git

```

In the .ssh/config file, I added the following lines.

```
Host drupal
   HostName git.drupal.org
   User git
   IdentityFile ~/.ssh/id_ed25519_drupal

```

In this way, the Git command is using the correct identity file, even if I have multiple identity files (for example, one for GitHub and one for Gitlab).

The Git command I reported to clone a project, as maintainer or not, is what the *Version control* tab of every project (for example https://www.drupal.org/project/drupal/git-instructions for Drupal, where you won't see the instructions for maintainers, if you aren't one of them).
What reported in Generating SSH keys (Linux) is outdated. Git Authentication for Drupal.org Projects has the most updated information. In particular, under Changing Git Remotes, it says:

> If you are a maintainer who has an established Git remote in the format `<username>@git.drupal.org:project/<yourproject>.git`, the format should be changed to `git@git.drupal.org:project/<yourproject>.git`.
> 7 votes

---
Tags: version-control, community-official-site
---


# Question
Title: What does the rule event mean "Drupal is initializing"
What does "Drupal is initializing" mean as a rule event?

# Answer
> 1 votes
In Drupal 7, the rule will run when `hook_init()` is called. As explained on the Drupal documentation page for `hook_init()`:

> This hook is run at the beginning of the page request. It is typically used to set up global parameters that are needed later in the request. When this hook is called, the theme and all modules are already loaded in memory.
>
> This hook is not run on cached pages.
>
> To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.

# Answer
> 0 votes
To redirect anonymous users to login page using Rule module.

Please check the LINK. Through this I think you will achieve what you want.

# Answer
> 0 votes
An important fact to realize is that Drupal needs to be "initialized" on each and every page request. Drupal isn't constantly running on the server, it is only executed when needed. That is, when a request for a Drupal page comes in, your server needs to start up Drupal and "ask" Drupal to respond to the page request. Drupal will use the URL requested plus any data passed and return a rendered page in response. Then Drupal will stop running.

So in practice, the "Drupal is initializing" event occurs on each and every page request, and the event happens at the beginning of this process.

Specifically, in Drupal 8, the Rules event "Drupal is initializing" occurs when the Symfony kernel.request event is generated. This is at the very beginning of a page request, before the response has been generated. See also the Drupal KernelRequest class.

---
Tags: rules
---


# Question
Title: How to find the viewid and view-display-id?
I'm trying to customize a view displayed in the homepage. Specifically, I'm trying to build slideshow with Bootstrap Carousel.

I've checked this page, but I don't understand how to find *viewid* or *view-display-id*. Instead of the *viewid* I've tried to use the view name, but it doesn't seem to work.
Anyhow, I've created a new folder inside the `templates` folder called `views`, in which I've created a new file with the following name: `views-view-fields--homepage-carousel--block.html.twig`

Here is the code:

```
<div class="carousel-fill" style="background-image:url({{file_url(node.field_carousel_image.entity.fileuri))}};">
    {% if ((title is not empty) or (description is not empty)) %}
       <div class="carousel-caption">
        {% if (title is not empty) %}
          <h3 class="carousel-title"> {{ title }}</h3>
        {% endif %}

        {% if (description is not empty) %}
          {{ description }}
        {% endif %}
      </div>
    {% endif %}
</div>

```

Which naming should I use to override a view displayed only in the homepage?
Thank you!

**UPDATE**

I've managed to correct the information thanks to user No Sssweat. Now, I'm able to customize my view. Here is the file name: **views-view--homepage-carousel--block-1.html.twig**, where **homepage-carousel** is the *viewid* and **block-1** is the *view-display-id*

# Answer
> 2 votes
> Anyhow, I've created a new folder inside the theme root called views

This might not work if it's not inside the /templates folder. You should create a /templates folder if there isn't one already and then create a /views folder inside there.

So should be mytheme/templates/views and then you put all your Views' template files here.

> I don't understand how to find viewid or view-display-id

You can find the view name at the top left. Although if your view name were to have an empty space you would have to add a dash. Ex: If it was named "Front Page" then the view-id would be `front-page`

You can find the Display ID under Advanced, machine name.

---

Another way would be to right mouse click and inspect element with your browser

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


title: Delete any path alias by language

text:
# Question
Title: Delete any path alias by language
We are running Drupal 8.8.5. I can see duplicate aliases when I look at /admin/config/search/path.

Unfortunately, there are many duplicate aliases on our website with 6000 URLs. The /node/1 node has three translations: en, es, and zh-hans. /node/1 also has a second entry for *es* containing a duplicate path alias which I would like to delete.

I need to find a way to programmatically delete path aliases. If I have Create, Read, Update and Delete (CRUD) operations on the path/alias/langcode, I can create a solution to eliminate the duplicates.

The following code obtains the alias data associated with the node whose ID is equal to 1 and dumps the Path, Alias and LangCode.

```
$alias = \Drupal::entityTypeManager()->getStorage('path_alias')->load('1');
var_dump($alias->getPath());
var_dump($alias->getAlias());
var_dump($alias->language()->getId());

```

The base language of the website is English, and the last `var_dump()` yields *en*. So far so good.

How can I gain access to the alias data for these two languages? I know the following works.

```
$alias_es = \Drupal::service('path_alias.manager')->getAliasByPath('/node/1','es');

```

I need to delete the duplicate Spanish path alias to accomplish my goal, so I need to figure out how to use entities which have a `delete()` method. You might think the following code should work.

```
$alias_es = $alias->getTranslation('es');

```

It returns:

> InvalidArgumentException: Invalid translation language (es) specified.

I also tried `$alias->getTranslationLanguages()`, which returns an array with only one element (`['en'] => object(Drupal\Core\Language\Language)`).

It appears that our original `$alias = \Drupal::entityTypeManager()->getStorage('path_alias')->load('1');` only has one language translation which is English.

How can I gain access to the path aliases for *es* and *zh-hans*?

# Answer
> 0 votes
Thank you @berramou!

There were two cases to deal with in my situation: (1) an alias that does not match the current alias for a language and (2) a duplicate alias for the same language that matches the current alias. The following code identifies both of these case. The code does not delete the offending alias objects. Please look at your case first and see if the code works for you before removing the commented alias object delete.

```
$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');

$nids = \Drupal::entityQuery('node')
  ->execute();

$n = 0;
foreach($nids as $nid) {

  $alias_objects = $path_alias_manager->loadByProperties([
    'path' => "/node/$nid",
  ]);

  foreach(['en','es','zh-hans'] as $lang)
    $current_alias[$lang] = \Drupal::service('path_alias.manager')->getAliasByPath("/node/$nid",$lang);

  $aliases = [];
  foreach($alias_objects as $ao) {
    $lang = $ao->language()->getId();
    $alias = $ao->getAlias();
    $path = $ao->getpath();
    if($current_alias[$lang] != $alias) {
      delete_ao($ao,$alias_objects,$current_alias[$lang],'not current');
    } else {
      if( isset($aliases[$lang]) ) {
        delete_ao($ao,$alias_objects,$current_alias[$lang],'duplicate');
      } else {
        $aliases[$lang] = $alias;
      }
    }
  }
  if($n++ == 100)exit;
}

function delete_ao($ao,$alias_objects,$current,$why) {
  $lang = $ao->language()->getId();
  print_aos($alias_objects);
  print ">> delete as $why: ";
  print_ao($ao);
  if($why == 'not current')
    print ">> current_alias for $lang: $current\n";
  print "\n";
  // $ao->delete();
}

function print_ao($ao) {
  print $ao->getPath() . ', ' .
        $ao->getAlias() . ', ' .
        $ao->language()->getId() . "\n";
}
function print_aos($alias_objects) {
  foreach($alias_objects as $ao)
    print_ao($ao);
}

```

# Answer
> 3 votes
> How can I gain access to the path aliases for es and zh-hans?

To get all path alias by language for instance es:

```
$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');
// Load all path alias for this node for es language.
$alias_objects = $path_alias_manager->loadByProperties([
  'path' => '/node/' . $nid,
  'langcode' => 'en'
]);

```

> I need to delete the duplicate Spanish path alias

```
$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');
// Load all path alias for this node for es language.
$alias_objects = $path_alias_manager->loadByProperties([
  'path'     => '/node/' . $nid,
  'langcode' => 'es',
]);

// Get the actual associated spanish path alias to your node.
$spanish_associated_alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid, 'es');
foreach ($alias_objects as $alias_object) {
  // If its not the actual alias delete it.
  if ($alias_object->get('alias')->value !== $spanish_associated_alias ){
    $alias_object->delete();
  }
}

```

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


title: Check for last row

text:
# Question
Title: Check for last row
Is there any way to find the last row from view itself.I have to add some extra html for the last item. I know we can do this using view's twig template, but I want to know is there any option in the view itself to check the last item.

# Answer
> 0 votes
It is better to use hook to achieve this. You can use template\_preprocess\_views\_view\_unformatted hook function and implement code as below *(it already does what you need it to do)*. Add this hook to your **themename.theme** file and don't forget to clear cache.

```
function THEMENAME_preprocess_views_view_unformatted($variables) {
  $view = $variables['view'];

  // Select view by machine name `blog` and display machine name `block_2`
  if ($view->id() === 'blog' && $view->current_display === 'block_2') {
   $rows = $variables['rows'];

   // Get number of rows
   $rows_size = count($rows) - 1;

   // Add custom CSS class ONLY to last row
   // This is what you want to achieve
   $variables['rows'][$rows_size]['attributes']->addClass('my-super-class');

   // OR Iterate over each row and do something
   // This is in case you want to alter each view's row result
   foreach($rows as $id => $row) {
     $variables['rows'][$id]['content']['my_custom_field'] = 'my custom value';
   }
  }
}

```

---
Tags: views, 8
---


title: Form field default value not working

text:
# Question
Title: Form field default value not working
I have an inherited project to which I need to add small form api changes. The changes are to two form fields shown below:

```
$form['start'] = [
    '#type' => 'number',
    '#title' => t('Between:'),
    '#required' => TRUE,
    '#default_value' => 1988,
    '#min' => 1900,
    '#max' => date('Y'),
    '#value' => 1988,
];
$form['test'] = [
    '#type' => 'number',
    '#title' => t('TEST:'),
    '#required' => TRUE,
    '#default_value' => 1988,
    '#max' => date('Y'),
    '#min' => 1900,
    '#value' => 1995,
];
$form['end'] = [
    '#type' => 'number',
    '#title' => t('and'),
    '#required' => TRUE,
    '#min' => 1900,
    '#max' => date('Y'),
    '#default_value' => 1999,
    '#value' => 1999,
];

```

This is a bizarre problem as my attempts to set the **#value** and **#default\_value** for both the *start* and *end* fields are not working.

However, I created the **test** field and it successfully adds to the form and sets my configured value and default\_value.

So, for the start field, I expect to see **1988** as the displayed value but instead that form field displays 1900. The **test** field I create meanwhile displays and behaves properly ... go figure.

As it is an inherited project, **I wonder if there are other means of configuring a form which I am unaware of ?**

UPDATE: Thanks to Leymannx for contributing and attempting to help. As per your suggestions, I tried the following but **without success**:

```
$form['start'] = [
    '#type' => 'number',
    '#title' => t('Between:'),
    '#required' => TRUE,
    '#min' => 1900,
    '#max' => idate('Y'),
    '#default_value' => 1988,
];

```

**Note:** The problem is that both the start and end fields refuse all my efforts to configure the value and default\_value. So, for the start field, I expect to see 1988 but instead that form field displays 1900.

# Answer
> -1 votes
I removed all `'#value'` keys and replaced `date('Y')` with `idate('Y')` and for me it's working without any problem. **Flush cache!**

```
$form['start'] = [
  '#type' => 'number',
  '#title' => t('Between') . ':',
  '#required' => TRUE,
  '#default_value' => 1988,
  '#min' => 1900,
  '#max' => idate('Y'),
];
$form['test'] = [
  '#type' => 'number',
  '#title' => t('TEST') . ':',
  '#required' => TRUE,
  '#default_value' => 1988,
  '#max' => idate('Y'),
  '#min' => 1900,
];
$form['end'] = [
  '#type' => 'number',
  '#title' => t('and'),
  '#required' => TRUE,
  '#min' => 1900,
  '#max' => idate('Y'),
  '#default_value' => 1999,
];

```

---
Tags: 8, forms
---


# Question
Title: Can PhpStorm autocomplete methods in Drupal::service?
Are there anyway to get phpStorm to autocomplete **\Drupal::service("xxxx")-\>..**

\[https://api.drupal.org/api/drupal/core!core.services.yml/8 For complete reference of Drupal8 service

For example Typing .. \Drupal::service("config\_factory")-\>g should show "get" in autocomplete popup list

This would be very handy for services from third-party developer also.

# Answer
> 6 votes
The auto-complete suggestions are based on the type of return value documented in the `\Drupal::service()` doxygen comment. Since the method may return service of any kind the type of return value is *mixed*.

That means auto-complete is not possible unless you explicitly specify type of the service.

```
/** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
$config_factory = \Drupal::service('config.factory');

```

For some particular services you can use dedicated methods like `\Drupal::configFactory()` or `\Drupal::config()` which have properly documented return value.

Notice that generally dependency injection is more preferable method for accessing services.

# Answer
> 3 votes
There is PHPStorm metadata now.

Install it, run `$ drush phpstorm-metadata:generate` and it will generate a `.phpstorm.meta.php` file in your web root for PhpStorm to match services to their corresponding classes and now autocompletion works. What a bliss!

> This module allows to export PHPStorm Advanced Metadata in order to get autocomplete functionality and return type information for next calls:
>
> * `Drupal::service()`
> * `ContainerInterface::get()`
> * `EntityTypeManager::getStorage()`

---
Tags: 8
---


# Question
Title: How should I validate field values against an external service?
I am looking at how to update a module that validates field values against an external service. Currently, it uses `hook_form_alter()`.

I assumed I should:

1. Write a service that handles external communications and returns a Boolean value
2. Write a Constraint and a ConstraintValidator class that uses the service
3. Attach the ConstraintValidator object in `hook_form_alter()`

I assumed I would find a similar implementations in the code of the ReCaptcha or ReCaptcha V3 module. Neither of them uses that approach. I found the Field Validator module that is using constraints.

Is using a constraint validator the correct way, or are there other approaches?

# Answer
> 1 votes
As you want the field value to be validated, I would use a constraint, This ensures that the value is validated regardless of how the field value is saved - whether through a Form, an API (REST/JSON etc) or programatically.

As you didn't create the entities and fields yourself (I'm assuming you mean they're provided by a module or core, and not just that a former developer created them), you'll have to attach your constraint in hook\_entity\_bundle\_field\_info\_alter() as explained in this post: How do I add a custom validation handler to an existing form/field?

Note however that this will mean anytime your entity has saved, and this field value has changed, your remote API will be called. If this is going to happen regularly, you may want to create some kind of caching system that caches the responses from the remote API.

---
Tags: 8, entities
---


# Question
Title: How do I get a field value in another field's template on a paragraph?
I have a Paragraphs bundle that has 2 fields. I want to have the value of the first field in the second field's template so I can combine it with `{{ loop.index }}` to make unique classes for a grid layout.

Is this possible using a preprocess function and a theme template?

# Answer
For non-paragraph fields, there is a node object available in the variables of the field template, so you can put this in a field.html.twig file:

```
{{ element['#object'].machine_name_of_other_field.value }}

```
> 8 votes

# Answer
Here is a solution that I came up with to solve this in the Paragraph template (`paragraph--PARAGRAPH-NAME.html.twig`), but I still think there is a better way using a preprocess.

```
{# Renders Grid Style field. #}
{% if content.field_grid_style|render %}
  {% set grid_style = content.field_grid_style['#items'].getString() %}
{% endif %}

{#
  Loops through the Column field here instead of the field template so we can
  set the grid_style class and add the loop index (key + 1)
#}
{% for key, item in content.field_column_content if key|first != '#' %}
  <div class="{{ grid_style }}--{{ key + 1 }}">{{ item }}</div>
{% endfor %}

```
> 2 votes

# Answer
Here is the solution for rendering one field inside second's field template.

> Get the first field value from hook\_preprocess\_field.

```
function teachervision_preprocess_file_field(&$variables) {
  if ($variables['field_name'] == 'second_field_machine_name') {
    $node = \Drupal::routeMatch()->getParameter('node');
    $variables['first_field'] = '';
    if ($node && isset($node->first_field_machine_name->value)) {
      $variables['first_field'] = $node->first_field_machine_name->value;
    }
  }
}

```

> Inside field template of second field, you can get this variable 'first\_field' and do something like that

```
{% for item in items %}
  <div{{ attributes.addClass(classes, 'field__first_item') }}>{{ first_field }}</div>
  <div{{ attributes.addClass(classes, 'field__second_item') }}>{{ item.content }}</div>
{% endfor %}

```

Hope, it makes sense to you.
> 0 votes

# Answer
Another option that worked for me. Enable `view()` in twig templates. See this Drupal 8 tutorial:

* Whitelist `view` in your settings.php file.
* `{{ element['#object'].machine_name_of_other_field.view }}`
> 0 votes

# Answer
This worked for me within my field.twig where field\_column\_classes is my custom field name.

```
{% set paragraph_parent = paragraph.getParentEntity() %}
{% set column_classes = paragraph_parent.field_column_classes.value %}
{{ element['#object'].field_column_classes.value }}

```
> 0 votes

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


# Question
Title: Add bootstrap row class on every n views rows
I am using Drupal Bootstrap and to get the correct positioning I am using bootstrap rows and columns classes.

How do I render a bootstrap row class on every let's say 3 view rows (bootstrap columns)? The structure must be like this

```
<div class="row">
  <div class="views-row col-md-4"></div>
  <div class="views-row col-md-4"></div>
  <div class="views-row col-md-4"></div>
</div>
<div class="row">
  <div class="views-row col-md-4"></div>
  <div class="views-row col-md-4"></div>
  <div class="views-row col-md-4"></div>
</div>

```

# Answer
Use views bootstrap module, in views format style chose Bootstrap Grid it will solve your problem.
> 1 votes

# Answer
You add class in Unformatted list formate .

and your class show like this
> -1 votes

# Answer
You can use this. Set number of columns 3 and apply custom row and column class
> -1 votes

---
Tags: 7, views
---


# Question
Title: How to solve "Query failed" error in drush sql-sync output?
This is a follow-on to my earlier question on this site. I hope posting it as a new question is appropriate. I'm trying to clone an existing drupal installation into a place on my mac with the commands:

```
echo "Pushing private files"
/usr/local/bin/drush core-rsync @hpc.dev:%private @hpc.local:%private
echo "Pushing webroot files"
/usr/local/bin/drush -y core-rsync @hpc.dev @hpc.local
echo "Pushing database"
/usr/local/bin/drush -y sql-sync --no-cache @hpc.dev @hpc.local
echo "Clearing Drupal cache"
/usr/local/bin/drush -y @hpc.local cc all

```

The sql-sync bit is failing with the following error:

```
Copying dump file from Source to Destination.                                      [ok]
Starting to import dump file onto Destination database.                            [ok]
/usr/bin/php /usr/local/drush-master/drush.php --php=/usr/bin/php  --backend=2        [notice]
--verbose --yes --strict=0 --root=/Users/cook47/Sites/drupal-test/html
--uri='http://localhost/~cook47/drupal-test'  sql-query
--file=/tmp/hpc-drupal-dev_20160302_175129.sql.gz --file-delete 2>&1
Executing: gzip -d /tmp/hpc-drupal-dev_20160302_175129.sql.gz
Executing: mysql --defaults-extra-file=/private/tmp/drush_wKQDuq --database=hpc-drupal-dev --host=localhost --silent  < /tmp/hpc-drupal-dev_20160302_175129.sql
Query failed.                                                                      [error]
Command dispatch complete                                                             [notice]
Command dispatch complete                                                             [notice]

```

The sql file does exist. I think the problems is that --defaults-extra-file part, because when I run that last command by hand, I get this:

```
cook47@rcmac (Downloads ):  mysql --defaults-extra-file=/private/tmp/drush_wKQDuq --database=hpc-drupal-dev --host=localhost --silent  < /tmp/hpc-drupal-dev_20160302_175129.sql
mysql: [ERROR] Could not open required defaults file: /private/tmp/drush_wKQDuq
mysql: [ERROR] Fatal error in defaults handling. Program aborted!

```

I have no idea where that --defaults-extra-file=/private/tmp/drush\_wKQDuq comes from. It's nowhere earlier in the output. The directory /private/tmp/ exists and I can write to it. Here is the 'local' array alias in my hpc.aliases.drushrc.php file:

```
$aliases['local'] = array (
  'root' => '/Users/cook47/Sites/drupal-test/html', //CHANGEME
  'uri' => 'http://localhost/~cook47/drupal-test', //CHANGEME
  //'remote-host' => "localhost",
  //'remote-user' => 'cook47',
  'path-aliases' => array (
    '%drush' => '/usr/local/bin/drush', //CHANGEME
    '%site' => 'sites/default/',
    '%files' => 'sites/default/files',
    '%private' => '../private',
    '%dump' => '/Users/cook47/Sites/drupal-test/drush-dump.sql',//CHANGEME
  ),
  'target-command-specific' => array(
    'sql-sync' => array(//CHANGEME
      'enable' => array(),
      'disable' => array(
      ),
    ),
  ),
  'command-specific' => array(
    'rsync' => array(
      'mode' => 'vrlzOk',
      'exclude-conf' => 1,
    ),
  ),
);

```

Anyone able to resolve this or point me to how to resolve it?

# Answer
The reason you get a 'file not found' error when you run the import by hand is that Drush automatically deletes its temporary files when the command completes. So, the error you are seeing there is different than the 'Query failed' error you are getting from Drush. Also, note that the --defaults-extra-file contains the credentials for your mysql connection, whereas the file shown at the end of the line is the actual sql dump.

If you'd like Drush to keep the sql file around, you can specify your own location for it; in this instance, Drush will not delete the file when it exits. Use the option `--target-dump=/path/to/mydump.sql`. It is unclear to me from your pasted output above whether or not your %dump option is being respected (since the path used is different than the one shown in your site alias). If %dump is not working, you could try moving this to your target-command-specific options, although if you do this, the key should be simply `dump`, not `%dump`. If your sql dump file is not being deleted, then disregard this advice.

If you want to try to re-import your local dump file, you could do this:

`$(drush @hpc.local sql-connect) < /tmp/hpc-drupal-dev_20160302_175129.sql`

If you do this, you should get the same 'Query failed' message. `$(drush @hpc.local sql-connect -d)` might give you more information.

The cause of the 'Query failed' message could be a number of things, but it's most likely a mismatch in the mysql version on your host vs. your local system, or (less likely) an encoding mismatch (e.g. if your dump is in utf-8, and that encoding is not available on your local system).
> 2 votes

# Answer
I had the same error "Query failed" using drush sql-sync. Finally I found a solution.

Make sure your database user privileges include `LOCK TABLES` and `CREATE TEMPORARY TABLES`.

(In addition to SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, DROP)
> 1 votes

---
Tags: drush, database
---


# Question
Title: Where can I set the following HTML attribute to my custom field?
I'm developing a custom module with an image field.

Where can I set the following HTML attribute to my custom field?

```
<input type=file
       accept="image/*"
       capture=environment>

```

I have created the image field and i'm able to process some OCR with an external library uploading the image but I need to use webcam instead and I can't find the way to set the "capture=enviroment" tag to my input form in the field widget file.

Thank you

# Answer
> 2 votes
Solved with formElement, at least form mobile devices. Just was I was looking for.

```
  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element['#accept'] = 'image/*;capture=camera';

    return $element;
  }

```

Thank you!

---
Tags: 8, files
---


# Question
Title: Why are new users having their role deleted on signup?
Today my client added some new users & gave them a role, and checked 'Notify user of new account'. The users clicked the email link, entered their password and all was well - except that the role they had been given had been removed, so they had no useful access. I've never seen this before, and in replicating it I can see that the role is removed at the point where the new user clicks save on their new password. I'm so puzzled by this, as we're at Drupal 7.69 which hasn't changed for a while and I can't see that anythig else has changed.

# Answer
> 1 votes
The problem was caused by the module 'Civigroup Roles Sync'. Adding the new user with a role that was synced to CiviCRM caused the user's role to be dropped because in CiviCRM they weren't in that group.

---
Tags: users, civicrm
---


# Question
Title: How can I find out if the present theme version would work
In the last years I've used pixture reloaded, a subtheme to adaptive theme, on some drupal sites and I was wondering whether this will work on Drupal 9. I've seen that the Adaptive theme homepage has not been reachable for some weeks and that the last update of Adaptive themes was 3 years ago. So I don't expect them to further develop the theme. How can I find out if the present version would work in Drupal 9?

# Answer
> 0 votes
Install the Upgrade Status module and then visit /admin/reports/upgrade-status and scan the Adaptive Theme and your sub-theme and get a report on all problems regarding Drupal 9 compatibility.

> This module scans the code of the contributed and custom projects you have installed, and reports on any deprecated code that must be replaced before the next major version. Available project updates are also suggested to keep your site up to date as project will resolve deprecation errors over time.
>
> Due to third party PHP library dependencies, the module needs to be installed with Composer.

---
Tags: 9
---


# Question
Title: Updating custom field with module upgrade gives a "Page not found"
I have been working for quite some time on a custom module. So far I have always been able to reinstall everything from scratch, but now I need an update to a custom field. Following the indications in Manually Downloading Module or Theme Files and in Updating a Module I created a mymodule.install file with a content like this:

```
use Drupal\Core\Database\Database ;

function mymodule_update_8101(&$sandbox) {
    $spec = [
      'type' => 'varchar',
      'length' => 32,
    ) ;

    $schema = Database::getConnection()->schema();
    $schema->addField('node__field_newfield', 'column_name', $spec);
}

```

Then I put the site in maintenance mode, replaced my module directory with the new one, and then went to http://myserver:myport/update.php, which showed me the small update file as a message. I clicked on Continue, and I got a Page not found.

I am sure I am missing something trivial, but I can't understand what :(

# Answer
> 1 votes
There's not a lot of information, but you do have an error in your code,

```
use Drupal\Core\Database\Database ;

function mymodule_update_8101(&$sandbox) {
    $spec = [
      'type' => 'varchar',
      'length' => 32,
    ];
//    ) ;

    $schema = Database::getConnection()->schema();
    $schema->addField('node__field_newfield', 'column_name', $spec);
}

```

---
Tags: 8, updating
---


# Question
Title: How to get current language of node in twig?
I have a tranlatable node, and I need to get its translation language. You know, I must to know is current node is in Polish or English. So... below there are my devel dumps from a node in Polish and a node in English. I see that there is a difference in `#activeLangcode` (x-default and en). But how to get that value? Or is there any better way to check current language of node in twig? Please help.

# Answer
A more elegant Drupal way without typing code:

1. Go to the Manage display of the content type of your node (/admin/structure/types/manage/YOUR\_CONTENT\_TYPE/display/full). Select your display mode (or use the default). You will notice the field 'Language', move it to the upper side so it gets out of 'Disabled'.
2. Once you have done that, the language of the node is available in Twig. You can access the id this way `{{ node.langcode.langcode }}`; or you can access the whole Object to get other data like the name `{{ drupal_dump(node.langcode) }}`
> 6 votes

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


title: Automatically rotate image on upload

text:
# Question
Title: Automatically rotate image on upload
I did a Drupal site with a field gallery using nodes as albums containing multiple images.. i am using MultiUpload module to upload whole folders at one time instead of 1 image at the time like the standard image module provides. Most pictures are 1024x768 , but the photographer has also some vertical pictures 768x1024 , and when they are uploaded Drupal automatically takes the tall 768x1024 and rotates them to 1024x768 .. i just want them to be shown tall if they are tall ..

Thank you

# Answer
If you want to autorotate images based on their EXIF information, you can use the Autorotate submodule provided by Imagecache Actions.

Enable the Autorotate submodule and then add an *Autorotate image* action to each of your image styles. This will automatically rotate the images and hopefully give you the results that you expect.

Note that this submodule requires the **Exif PHP extension** to be enabled.
> 9 votes

# Answer
It happened to me too. Are you sure images are really vertical? Probably they are all horizontal, just with orientation saved in EXIF tag. Some software (like windows photo viewer and most mobile devices) recognizes this tag. Web server's GD library does not.

If that's the case, ask photographer for really vertical photos, or try EXIF module to test for that parameter and execute rotation if needed.
> 3 votes

# Answer
This is an issue that happens with iOS phones, take a look at the EXIF Orientation module to fix it.

> This module reads EXIF data to rotate images that have an Orientation key set. This module solves the issue where iOS devices take images in one position but set an EXIF Orientation value, leaving applications viewing the image responsible for rotating the image.
> 3 votes

# Answer
Save the images in another format, for example PNG. This will remove the existing EXIF information attached to the image which makes Drupal rotate the images.
> 0 votes

---
Tags: media
---


# Question
Title: How do I configure meta tags for a panel page?
How do I configure meta tags for a panel page? I want to change title, keywords and description.

Ideally I want to use Yoast.

# Answer
> 2 votes
I have the same requirement and one of the patches attached in the issue titled "Panels / Page Manager integration" worked for me. This patch basically adds a module of panel pages which when enabled, provides interface to configure meta tags for each panel pages under `/admin/config/search/metatag`.

# Answer
> 0 votes
If it might help someone, specific panel pages meta descriptions are available under `/admin/structure/pages`, find your page and edit the tab Meta tags.

---
Tags: 8, panels, meta-tags
---


# Question
Title: Why is library not being attached to my email twig template?
I am overriding the commerce-order-receipt.html.twig by adding that file to mytheme/templates/commerce. I then add these lines to mytheme.libraries.yml

```
email:
  css:
    base:
      assets/css/email.css: {}

```

in mytheme.info.yml i add:

```
libraries:
  - mytheme/email

```

and then at the top of my twig tpl i add this:

```
{{ attach_library('mytheme/email') }}

```

but email that is sent does not have email.css attached.

Am i still missing something?

# Answer
I guess you need to add the placeholders in your twig template too:

```
<css-placeholder token="{{ placeholder_token|raw }}">
<js-placeholder token="{{ placeholder_token|raw }}">

```

See here for the placeholder tokens: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template\_preprocess\_html/8.2.x

Be aware that this will load all libraries for the request and bloat up your email with a lot of (unwanted) css and js.

> I strongly recommend to use inline CSS for you email template.
> -1 votes

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


# Question
Title: How to boost relevance of Search API solr with creation date?
We have replaced Drupal's core search with SolR but we have noticed a recursiveness issue regarding the search results, for ex. when searching “executive committee”, documents created in 2006 and 2007 are listed before newer documents created in 2010. (http://www.etuc.org/search-page)

What we would like to do is to **sort** the articles **by date and by relevance**.

We have tried to alter this at the View level (date + Search:relevance) but it short circuits SolR.

We have looked at the search api settings and it seems that one cannot boost date field. Only fulltext fields are ‘boostable’ (?)

We have also found a few articles related to the subject:

but they weren’t much help.

We are using Drupal 7, SolR 3 and the following modules

* Search API 7.x-1.11
* Search API autocomplete 7.x-1.0
* Search facets 7.x-1.11
* Search views 7.x-1.11
* SolR search 7.x-1.4

Does anybody has an idea how to fix this issue? Thank you very much in advance.

# Answer
> 1 votes
To do this (Drupal 7), one needs to implement the below hook:

```
hook_search_api_solr_query_alter(&$call_args, SearchApiQueryInterface $query)

```

This hook can go in the theme or module layer.

Example code could be:

```
/**
 * Implements hook_search_api_solr_query_alter().
 *
 * @see https://www.drupal.org/node/2009760#find-out-field-id
 * @see https://www.drupal.org/project/search_api_solr/issues/2194055
 * @see https://www.metaltoad.com/blog/date-boosting-solr-drupal-search-results
 * @see https://www.drupal.org/forum/support/module-development-and-code-questions/2014-12-18/extending-search-api-solr-search-with
 * @see https://www.drupal.org/project/search_api_solr/issues/2392499
 * @see https://www.drupal.org/project/search_api/issues/1694698
 * @see https://books.google.com.au/books?id=othpBgAAQBAJ&pg=PA157&lpg=PA157&dq=3.16e-11+solr
 */
function mytheme_search_api_solr_query_alter(&$call_args, SearchApiQueryInterface $query) {
  // Boost more recently created content. This is taken directly from an
  // apachesolr query with +1 boost (+1 for every 100).
  $fields_names = $query->getIndex()->server()->getFieldNames($query->getIndex());
  if (isset($fields_names['created'])) {
    // If using node property 'created', get solr name of it  e.g. 'dm_created'.
    $created_field_name = $fields_names['created'];
    // @codingStandardsIgnoreStart
    // Field name version.
    // $created_field_name = $fields_names['field_date'];
    // @codingStandardsIgnoreEnd
    // Ensure '$call_args['params']['bf']' exists.
    if (!isset($call_args['params']['bf'])) {
      $call_args['params']['bf'] = [];
    }
    $call_args['params']['bf'][] = "recip(ms(NOW,{$created_field_name}),3.16e-11,0.5,0.5)^100.0";
  }
}

```

# Answer
> 0 votes
I'm not 100% sure this will work, but definitely worth a try.

Go to /admin/config/search/search-api/index/your\_index/edit

And then under this heading: `CONFIGURE THE DEFAULT TRACKER` There are two options to set the "**Default index tracker which uses a simple database table for tracking items.**"

Select "most recent items first". You will need to reindex the site after saving the settings for the change to take effect.

 Index items in the same order in which they were saved
 Index the most recent items first```

---
Tags: search
---


# Question
Title: One contextual filter based on two entity reference fields
I have two content types.

1. Doctor
2. Location

Doctor has two entity reference fields. *Both* reference Location nodes.

1. Primary Location
2. Secondary Location

I need to create a view that appears on a Location node and shows all Doctors that reference the Location node via the Primary Location or Secondary Location fields.

This has turned out to be incredibly difficult.

I've create a contextual filter for Content: Primary Location and set Provide default value to Content ID from URL. This successfully filters the view to Doctors that reference the Location via the Primary Location field.

I now create a contextual filter for Content: Secondary Location and set Provide default value to Content ID from URL. I now have no results.

I can then delete the Content: Primary Location contextual filter and this successfully filters the view to Doctors that reference the Location via the Secondary Location field.

It appears I can't have both at the same time. Thanks for any help!

# Answer
> 0 votes
Of course I solve this immediately after I post it after hours of trying. If you're in the same situation, it appears the only solution is to use https://www.drupal.org/project/views\_contextual\_filters\_or .

Configure the view as described above. Then additionally, under Query settings, check Contextual filter OR.

The UI of this module leaves something to be desired but it works so long as all your contextual filters should relate to each other as OR.

The second missing piece was that I was testing this in the view UI using the preview. I was passing the NID of the Location as an argument. What I missed is that because I have two contextual filters I actually need to pass the NID twice like this: "2173/2173". When the view is actually used on the page, the NID is retrieved from the URL and the fact that there are two contextual filters becomes irrelevant.

---
Tags: views
---


# Question
Title: Block form: radio buttons selection not saved
I have a block form with 1 radio button and one text field. The problem is the selection for the radio button is not saved: in blockSubmit $values\['colour\_select'\] is empty. The value of the text box is saved and working fine. What is missing for the radio button?

Thank you

```
class UnitSiteIdentityBlock extends BlockBase implements BlockPluginInterface{
  public function build() {
    $config = $this->getConfiguration();
    $colour_select = $config['colour_select'];
    $custom_colour = $config['custom_colour'];
    return [
     '#theme' => 'folwell_unit_identity_block',
     '#colour_select' => $colour_select,
     '#custom_colour' => $custom_colour,
    ];
  }
  public function blockForm($form, FormStateInterface $form_state) {
    //$form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();
    $form['colour_select'] = [
      '#type' => 'radios',
      '#title' => $this->t('Pick a colour'),
      '#options' => [
        'white' => $this->t('White'),
        'black' => $this->t('Black'),
        'other' => $this->t('Other'),
      ],
      '#attributes' => [
        'name' => 'field_select_colour',
      ],
      '#default_value' => $config['colour_select'],
    ];
    $form['custom_colour'] = [
      '#type' => 'textfield',
      '#size' => '60',
      '#placeholder' => 'Enter favourite colour',
      '#attributes' => [
        'id' => 'custom-colour',
      ],
      '#default_value' => $config['custom_colour'],
    ];
    return $form;
  }
  public function blockSubmit($form, FormStateInterface $form_state) {
    //parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    foreach ($values as $key => $value) {
      \Drupal::messenger()->addMessage($key . ': ' . $value);
    }
    $this->configuration['colour_select'] = $values['colour_select'];
    $this->configuration['custom_colour'] = $values['custom_colour'];
  }
}

```

# Answer
I found the problem with this: it was the name attribute. As soon as I removed it, $values\['colour\_select'\] stored the selected color.
> 0 votes

---
Tags: forms
---


# Question
Title: How do I add the "- Any -" option for the published status on exposed filters?
I need to add the *\- Any -* option for the published status, on exposed filters.

I can't use it, as when I try to add it, I get the following error.

> You must select a value unless this is an non-required exposed filter.

>

How can I add *\- Any -* as option?

# Answer
As the screenshot shows, the filter is set as *Required*. This means the users need to select a value for that filter that, being a filter for the published status, can only get *Yes* and *No* as values.

If you want to allow users to select *\- Any -* as value for that filter (which isn't really a value for the published status, but a value that tells the view not to filter the nodes basing on their published status), you need to deselect the checkbox that is shown to the left of *Required*.

>
> 2 votes

---
Tags: views, 8
---


title: Clearing Twig cache only?

text:
# Question
Title: Clearing Twig cache only?
We have this large website where we would have to deploy html changes in Twig quite often. I'm looking for a solution to clear the Twig cache ONLY. So we do not have to do a general cache rebuild, which consumes a lot of CPU each time. `drush cc render` does not work, twig html still cached. Any suggestions?

# Answer
> 5 votes
Invalidate the twig cache first, like this:

```
drush php-eval "\Drupal::service('twig')->invalidate();"
drush cc render

```

---
Tags: 8, caching
---


# Question
Title: Override user register default URL to set up password
in order to create a sign in/sign up workflow on a decoupled Drupal(React on front). I've used the core provided rest resource `/user/register` with Rest ui, and after giving the permission Access POST on User registration resource to anonymous users , i was able to register users via the resouce `/user/register?_format=hal_json` without any authentication

**I wonder if there is a way to override the link that is by default sent to the newly users via mail to setup his password ?**

I don't want the users to setup their passwords on a Drupal page with a Drupal form.

# Answer
> I think no need to override the default register url.

To prevent Anonymous from register users, Just go ***Administration \>\> Configuration People*** http://example.com/admin/config/people/accounts.
and check **Administrators only** in **REGISTRATION AND CANCELLATION** fieldset like the following:

If you have another raison to change the default url follow this tutorial just change route name from `user.login` to `user.register`.
> 1 votes

---
Tags: users
---


# Question
Title: How do I load a form with a specific form display (form mode)?
On a custom page I'm trying to load an user edit form with a specific form display. I'm able to load the form however I can't figure out how to load the form with the specific display.

This is what I have now:

```
public function content($substep) {

    $user = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->load(1); // loading user 1 for test purpose

    $form_state = new FormState();

    $form = \Drupal::entityTypeManager()
      ->getFormObject('user', 'default')
      ->setEntity($user);

    return \Drupal::formBuilder()->getForm($form);
}

```

Anyone has an idea?

# Answer
> 15 votes
In D8 you can add display modes for forms in UI. But these form modes can't be used right away like view modes.

If you want to use a form mode in code you have to set a form operation with the same name in the handlers section of the entity type. The form class you use for this handler is the same as in the default handler, because you want to control which fields are displayed in the form mode, not in a different form class.

For example to use a form mode `profile2`, which you have configured in UI, you have to add a form operation `profile2` to the user entity type definition in a hook\_entity\_type\_build:

*mymodule.module*

```
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('profile2', 'Drupal\user\ProfileForm');
}

```

Then you can use the new form operation (form mode) in the code example from the question:

```
public function content($substep) {

  $user = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->load(1); // loading user 1 for test purpose

  $form = \Drupal::entityTypeManager()
    ->getFormObject('user', 'profile2')
    ->setEntity($user);

  return \Drupal::formBuilder()->getForm($form);
}

```

# Answer
> 4 votes
Found this answer really helpful,

```
function my_module_entity_form_display_alter(&$form_display, $context) {
  if($context['entity_type'] == 'user' && $context['bundle'] == 'user'){
    $user = \Drupal::currentUser();
    if(!in_array('administrator', $user->getRoles())){
      $storage = \Drupal::service('entity_type.manager')->getStorage('entity_form_display');
      $form_display = $storage->load('user.user.restricted');
    }
  }
}

```

Via drupal.org. Also, form\_mode\_manager seems like a contrib way to fix this problem via the UI.

# Answer
> 4 votes
In Addition to @powpow12 answer, you could use the route name to edit the display mode on a form only for embed forms, like the entity browser "edit entity" option.

```
/**
 * Implements hook_entity_form_display_alter().
 */
function mr_media_entity_form_display_alter(&$form_display, $context) {
  $route_service = \Drupal::service('current_route_match');
  $route_name = $route_service->getRouteName();

  if ($route_name == 'entity_browser.edit_form' && $context['entity_type'] == 'media' && $context['bundle'] == 'image) {
    $storage = \Drupal::service('entity_type.manager')->getStorage('entity_form_display');
    $form_display = $storage->load('media.image.edit_for_entity_browsers');
  }
}

```

---
Tags: 8, forms, entities
---


# Question
Title: How to access a field value in hook_preprocess_eck_entity
How can I access a field value in hook\_preprocess\_entity(&$vars)?

I am able to do the following, but it does not seem like the best approach. What is a better approach?

```
function mymodule_preprocess_eck_entity(&$vars) {
  $myvalue = $vars['content']['field_myfield'][0]['#context']['value'];
}

```

# Answer
I found I can get the value with:

```
  $myvalue = $vars['eck_entity']->get('field_myfield')->getString();

```
> 0 votes

---
Tags: 8
---


# Question
Title: How can I share cache with multiple users and roles?
In my custom module, I define a custom block that performs an expensive operation:

```
/**
 * {@inheritdoc}
 */
public function build() {
  $data = get_expensive_data();
  $agent_number = get_agent_number_from_context();
  return [
    '#theme' => 'my_custom_module',
    '#cache' => [
      'keys' => ['my_block', 'full_version', $agent_number],
      'tags' => ['my_custom_module'],
      'max-age' => 86400,
    ],
  ];
}

```

The caching works except when another user views the block or a user with a different role view the page; it creates a new cache item. Is it possible to have cache only one time for multiple users/roles?

**Edit**

I tried the following (ended up using `route` context just to not add another variable to my problem):

```
/**
 * {@inheritdoc}
 */
public function build() {
  $data = get_expensive_data();
  return [
    '#theme' => 'my_custom_module',
    '#data' => $data,
    '#cache' => [
      'contexts' => ['route'],
      'tags' => ['my_module'],
      'max-age' => 86400,
    ],
  ];
}

```

Noticed when I had the block using Layout Builder via Page Manager, no item got added to the `cache_render` table (that might be a separate issue). When I added the block on default Drupal Block Layout I noticed that it still created a new cache record for every user. For example:

User 1 navigated to: /my-account/A123 and the following record got added to the `cache_render` table:

**cid**

```
entity_view:block:mycustomblock:[languages:language_interface]=en:[route]=entity.node.canonical7ccb4f15749b8c9e759f0016bfc863bd5e6bef88ea0a9dfe7b1cbe2687d30b32:[theme]=my_theme:[url.site]=http://mysite.test:[user]=1

```

**tags**

```
block_view config:block.block.mycustomblock config:user.role.administrator config:user.role.authenticated my_module rendered user:1

```

User 72 navigated to: /my-account/A123 and the following record got added to the `cache_render` table:

**cid**

```
entity_view:block:mycustomblock:[languages:language_interface]=en:[route]=entity.node.canonical7ccb4f15749b8c9e759f0016bfc863bd5e6bef88ea0a9dfe7b1cbe2687d30b32:[theme]=my_theme:[url.site]=http://mysite.test:[user]=79

```

**tags**

```
block_view config:block.block.mycustomblock config:user.role.agent config:user.role.authenticated my_module rendered user:79

```

With using contexts, I am still seeing it create a new record for every user.

**Edit 3**

I think my test form Edit 2 is invalid because I was trying to make the block work outside of page manager but I needed the context from page manager so it was using the logged-in users. Long story short, I need to figure out why context caching isn't working (although key caching is working) when using Page Manager or Layout Manager.

# Answer
Caching is shared with multiple users or roles by default, unless you add a cache context like `user` or `user.roles`.

Otherwise it's hard to tell what the code in the question wants to achieve.

1. If it wants to set block cache keys, then you can't do it from here and you don't need to. They're set automatically. `get_agent_number_from_context()` should probably be a custom `cache_context.agent_number` which you then could add to the block build array to vary the cached block by this variable:

```
/**
 * {@inheritdoc}
 */
public function build() {
  $data = get_expensive_data();
  return [
    '#theme' => 'my_custom_module',
    '#data' => $data,
    '#cache' => [
      'contexts' => ['agent_number'],
      'max-age' => 86400,
    ],
  ];
}

```

How to create a custom cache context: https://www.drupal.org/docs/8/api/cache-api/cache-contexts#recognize-discover-create
2. If it wants to cache the expensive data on its own (which makes sense if you want to reuse the rendered result in other places not necessarily blocks), then you need to execute `get_expensive_data()` in a `#pre_render` callback to avoid that it gets executed in case of a cache hit. See https://dev.acquia.com/blog/drupal-8-performance-render-caching

Edit 1: The cids you have added to the question contain a cache context for the user. I can't tell by the code shown so far how it ends up in your block. But there is also a cache tag of the user, so there has to be some code retrieving and rendering the current user.

Edit 2: Assuming the theme is the same there is also a default `user.permissions` cache context for all render caching which probably kicks in now that `user` is removed. See https://www.drupal.org/project/drupal/issues/2493033
> 5 votes

---
Tags: 8, users, caching
---


title: Upgrade with third-party modules

text:
# Question
Title: Upgrade with third-party modules
I'm trying to migrate a Drupal 7 website to Drupal 8. I have installed on the same server those two websites. Drupal8 version is empty. On the Drupal 7 website, more than twenty contrib modules are installed, like LinkIt, PathAuto, Token... I downloaded with Composer the D8 version of those modules. I installed them without any configuration. I followed the upgrading process on my D8 website, but the process cannot see installed modules on D8 version and told me that LinkIt or PathAuto won't be upgraded.

How can I fix it? Is there a solution to migrate configuration datas for these modules?

# Answer
> 0 votes
Pathauto has migrations for settings & patterns built into the D8 module. Linkit doesn't have built-in support migrations.

---
Tags: upgrading
---


# Question
Title: get user id from username or email without logging in
I want to get the user id and role before the user is logged in. If i have the email or username, what function can I use with D8 to get the user id ?

# Answer
You can load the user with `loadByProperties()`:

```
$users = \Drupal::entityTypeManager()->getStorage('user')
  ->loadByProperties(['mail' => $mail]);
$user = reset($users);
if ($user) {
  $uid = $user->id();
  $rids = $user->getRoles();
}

```
> 14 votes

# Answer
Drupal 8 now also has these specific functions:

**user\_load\_by\_name()**

```
$user = user_load_by_name('some user');
$uid = $user->id();

```

https://api.drupal.org/api/drupal/core!modules!user!user.module/function/user\_load\_by\_name/8.9.x

**user\_load\_by\_mail()**

```
$user = user_load_by_mail('email@example.com');
$uid = $user->id();

```

https://api.drupal.org/api/drupal/core!modules!user!user.module/function/user\_load\_by\_mail/8.9.x
> 5 votes

---
Tags: users, 8
---


title: Adding JS script, how to format JS

text:
# Question
Title: Adding JS script, how to format JS
I am trying to add this simple script to my block

```
<script>
    const config = {
      sourceAssetAddress: null,
      sourceAmountDecimal: null,
      destinationAssetAddress: null,
      destinationAmountDecimal: null,
      apiKey: null,
      partnerContractAddress: null,
    };
    const nodeId = "totle-widget";
    !function(){const t=document.createElement("script");t.type="text/javascript";const e=()=>{TotleWidget.default.run(config,document.getElementById(nodeId))};t.readyState?t.onreadystatechange=function(){"loaded"!=t.readyState&&"complete"!=t.readyState||(t.onreadystatechange=null,e())}:t.onload=function(){e()},t.src="https://widget.totle.com/latest/dist.js",document.getElementsByTagName("head")[0].appendChild(t)}();
</script>

```

Problem I have is that I tried to add it as library like this

```
(function ($) {

    'use strict';

    /**
     * Attaches the behavior to bootstrap carousel view.
     */
    Drupal.behaviors.totle_widget = {
      attach: function (context, settings) {

        const config = {
            sourceAssetAddress: null,
            sourceAmountDecimal: null,
            destinationAssetAddress: null,
            destinationAmountDecimal: null,
            apiKey: null,
            partnerContractAddress: null,
          };
          const nodeId = 'totle-widget';
          !function(){const t=document.createElement("script");t.type="text/javascript";const e=()=>{TotleWidget.default.run(config,document.getElementById(nodeId))};t.readyState?t.onreadystatechange=function(){"loaded"!=t.readyState&&"complete"!=t.readyState||(t.onreadystatechange=null,e())}:t.onload=function(){e()},t.src="https://widget.totle.com/latest/dist.js",document.getElementsByTagName("head")[0].appendChild(t)}();
}}}(jQuery));

```

and somehow script goes beserk after this, loads many times and finaly breaks. It is attached to block in build and should be fine.

```
$build['#attached'] = array('library' => array('exch/totle'));

```

So I am not really sure what is wrong here. All I want to is to add this script somewhere in body of my html. Like when I add it directly into html.html.twig template of my theme and it works, but ofcourse I want to do it more in drupal way. What is wrong, how should I add this script to my library?

# Answer
Using once with proper definition helped.

```
(function ($) {

    'use strict';

    Drupal.behaviors.totle_widget = {
        attach: function (context, settings) {

          // Using once() so script is loaded only once
          $('#totle-widget', context).once('totle_widget').each(function () {

            const config = {
                sourceAssetAddress: null,
                sourceAmountDecimal: null,
                destinationAssetAddress: null,
                destinationAmountDecimal: null,
                apiKey: null,
                partnerContractAddress: null,
              };
              const nodeId = 'totle-widget';
              !function(){const t=document.createElement("script");t.type="text/javascript";const e=()=>{TotleWidget.default.run(config,document.getElementById(nodeId))};t.readyState?t.onreadystatechange=function(){"loaded"!=t.readyState&&"complete"!=t.readyState||(t.onreadystatechange=null,e())}:t.onload=function(){e()},t.src="https://widget.totle.com/latest/dist.js",document.getElementsByTagName("head")[0].appendChild(t)}();

          });
        }
      };

  }(jQuery));

```
> 1 votes

---
Tags: javascript, 8
---


# Question
Title: How to confirm that drush-based cron is being called from crontab?
I don’t know whether this is a docksal-specific question or a general cron one, but likely the latter.

I’ve set up a crontab for docksal (see https://blog.docksal.io/running-scheduled-events-with-docksal-43fc69d7b29b):

`0 */3 * * * drush --root="/var/www/docroot" core-cron`

My question is how tell if it’s actually working. I don’t see anything logged in at `/admin/reports/dblog`. I also tried enabling the syslog module, but I’m not seeing a syslog file at `/var/log` as described, using `fin bash` and `cd`ing to that directory.

I don't whether I should expect to see something, but would prefer I did. Otherwise it's like trying to check if the refrigerator light has gone off when you've closed the door.

# Answer
It sounds like you've answered your own question. Viewing the admin DB log reports or running something like `fin drush wd-show --type=cron` should show cron execution entries. If you're ***not seeing*** those logs, it most likely means the crontab config isn't working.

You should check `drush --root="/var/www/docroot" core-cron` works correctly when manually executed in the container where crontab is configured (e.g. perhaps the crontab user doesn't have `drush` available in its path or drush can't find the DB config) & the `/var/log/` dir (it will depend on the Linux distro the Docksal image is based on) for cron logs to confirm that its firing.
> 1 votes

---
Tags: 8, drush, cron
---


title: Using Views in Complex Pages

text:
# Question
Title: Using Views in Complex Pages
I would like to use Views to create content for custom content type pages. This seems to be consistent with the use of Views in the Admin pages of Drupal 8. I'm running into problems integrating Views (the page content) with the page layout of the page. This should be simple -- but it does not seem to be. In all of this I would like to use the base features of Drupal 8 without custom or contributed modules.

The key functions that I am working to implement is being able to embed a View anywhere I would like in a page. Said another away, I would like to embed several Views (page content) into specific portions of a complex page structure (page layout).

* In Drupal 6 we have a content type and associated template file. Embedding a View in the template is straight-forward -- we use PHP code.
* I tried creating Views as Blocks and placing them in different Block layout areas. This became complicated quickly -- to much so. The problem is the page layout must become part of the Views. There may be a solution involving the creation of custom Block layout regions and make the Views part of these new region. The page design has several layers of content for mobile devices. We would need Block layout regions for "Layer 1", "Layer 2" and "Layer 3" which are all part of the page Body. I don't know if this will work.
* I created a custom module that creates a Block for the page. I can render whatever I want including layout elements and embedded Views content. The problem is I am quickly generating a lot of custom code -- one of my goals is to avoid this.
* I'm starting to look at Page Manager and Panels for a solution. Bringing these modules into the design for a seemingly simple problem does not seem like the correct answer.
* It seems there should be a simple way to embed a View into a Twig file associated with a content type. This is where we started -- the Drupal 6 approach. This simple solution has been difficult for me to achieve.

Any ideas?

---

The content we want to create has four parts. All four portions of content is a part of the "content" region of the page -- the top and three overlays. Here is a rough prototype: `raystedman.org/d8/landing`

# Answer
It seems like you have a content type, and there are many different content items of that type, each content item being its own "page".

Each content item has fields containing content unique to that content item. But on the page for each content item, you would also like to show multiple views listing other content (of the same or different content types). The content of these views is not the same for every page, but is filtered or tailored in some way to fit the current content item.

These views and fields appear in various regions of the page, which will be rendered in various ways depending on device, including as tabs.

If all this is true, then your problem is all about how to generate views tailored to the current content items. This is a very common problem, and there are many different solutions.

* You could write the whole thing in custom code, slipping in the view at a number of possible points in the rendering process.
* You could take use the power of views to take on the task of rendering of the content type, and the views\_field\_view to embed your child views inside the main view. Views provides tabbed pages which might suit you.
* In D7, you would reach for the Entity Views Attachment (EVA) module (with 50k installs). This module does one thing and does it simply: it enables you to add a view as a field on a content item and pass that item as an argument to the view. Sadly, it has no D8 port.
* In D7, you could use Panelizer, Panels and Ctools. Together these allow you to take over the page rendering for a content type, defining regions on the page, allocating regular fields and/or "views content panes" to regions, and passing the current content item as context arguments to the view. The Panels approach is mature, beloved of many Drupal professionals, powerful and flexible. The Panels family is in heavy development for D8 are expected to become useable in the next few months.
* Display Suite allows you to add extra display fields to a content item, and these can include views. By setting the views to use contextual filters, they can get the identity of the current content item from its URL and filter themselves based on that. The only disadvantage of this route is that because of this URL dependence you don't get the contextual filter of the view working properly if the view is embedded in another view, it only works on the content item's page. DS is a major Drupal module, and has a relatively mature D8 release.
* Views\_field\_view already has a working D8 port. It works similarly to EVA. The only catch is that it's more sophisticated, in that it allows editors to specify view arguments for each content item. If you don't want this, you can set the current content item as the "default" and choose to "force the default".
* Display fields is a new D8 module. It gives EVA-like functionality, alongside other useful things. See https://www.drupal.org/node/2639296 for notes on how to use it for views.
* 'Views field formatter' is yet another module in the same space. It's D8 version is almost but not quite ready.

Which of these options you choose may depend in part on how you want to handle the tabs, whether these are Drupal-managed navigation leading to separate URLS, or whether they are just part of the theme-managed HTML page controlled by CSS or Javascript.
> 2 votes

# Answer
You can still embed views in templates, just prepare them in `yourtheme_preprocess_TEMPLATE(&$variables)`, put them in `$variables['some_key']` and then display in your template as `{{ some_key }}`.

> I'm starting to look at Page Manager and Panels for a solution. Bringing these modules into the design for a seemingly simple problem does not seem like the correct answer.

I don't see why it wouldn't be. It's possible to do a lot more with just Drupal 8 core than before, but not everything. Using contrib modules is perfectly fine, as long as you try to not add every single module out there to your site.

The only problem is that it is a bit early for many contrib modules unless you know what you're doing and can dig into the code in case you run into issues.
> 4 votes

# Answer
I had exactly same problem. I had set "access" to certain "roles" I had defined. I had not checked "Authenticated User", since I did not want all roles to have access. So I made checked "Authenticated User" and it worked fine. I then went back and unchecked "Authenticated User" and low and behold, it still worked... only Drupal knows why!
> 0 votes

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


title: Font Awesome icons in link field

text:
# Question
Title: Font Awesome icons in link field
I would like to have a font awesome icon in my link text.

```
<i class="fa fa-pencil"></i>Blogs

```

Since link fields are generated in LinkGenerator.php, they get escaped.

```
if (!SafeMarkup::isSafe($variables['text'])) {
  $variables['text'] = Html::escape($variables['text']);
}

```

There doesn't seem to be any way to bypass this by setting a HTML option to `TRUE`.

Is there any way to achieve this?

# Answer
You can define your own template.

For example as inline:

```
$link = array(
    '#type' => 'inline_template',
    '#template' => '<a href="{{ url }}"><i class="fa {{ fa_icon }}"></i>{{ title }}</a>',
    '#context' => array(
        'url' => $url,
        'title' => $title,
        'fa_icon => 'fa-pencil',
    ),
  );

```

If you are working on a theme or module you should define a template with its own name like `link_fa`, so that it can be overridden by other modules or themes.
> 5 votes

# Answer
As you want to let the user chose an icon, maybe the Link Icon module fits your needs.

> The Link icon module is a simple link field formatter to create icon classes based on a predefined set of link titles.
>
> Link icon is an icon-agnostic formatter, meaning it doesn't care for whatever icon you use. Any icon will simply work. It doesn't hard-code icon names, nor includes icons.
>
> Drupal supports unlimited values, the limitation is your available icon fonts.

Or if it doesn't fit, you can have a look at the modules code, to see how they have implemented the *field widget* and the *field formatter* as a starting point.
> 1 votes

# Answer
Every font awesome icon also has a unicode associated with it, see the cheatsheet. These unicodes look like ``. This means that you do not need to use the class, but can use this as a character instead.

There is however one big BUT. Just adding the unicode does not work, you also have to apply the font-awesome font to the HTML selector.

So in order to make `<i class="fa fa-pencil"></i>Blogs` display a pencil, you could also use `<i></i>Blogs` and add `font-family: FontAwesome` to the CSS of `<i>`:

```
i {
  font-family: FontAwesome;
  font-style: normal;
}

```

Also read this Stack overflow question.

UPDATE:

I misread the question, I thought the class got stripped from the tags, but it seems the entire tag is removed. In that case this is less helpful...
> 0 votes

# Answer
In the view, you can rewrite the results. For example, In view select the font awesome field and click on rewrite results and then tick the "Output this field as a custom link" checkbox. There you can give the link
> 0 votes

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


title: Database updates failing

text:
# Question
Title: Database updates failing
I sort of inherited a Drupal 8 site which has lately generated a problem causing 500 error when e.g. trying to modify menus. I haven't myself updated the Drupal (just got it, it is currently on version 8.7.5).

I checked what is the status of database and found out there's about two dozens updates needed. So, I though, maybe drush updb would cure the problem. Well, it still might, except that the first update fails and so the others never ever get even tried. The significant lines are as below

> \[notice\] Update started: feeds\_update\_8001
>
> \[error\] Missing bundle entity, entity type node\_type, entity id migrate\_example\_beer.
>
> \[error\] Update failed: feeds\_update\_8001
>
> \[error\] Update aborted by: feeds\_update\_8001
>
> \[error\] Finished performing updates.

How to overcome that? There is no table named migrate\_example\_beer (though a few others including that part do).

Is it possible somehow to skip the first update, or anyone has any ideas how to cure that one error?

# Answer
> 0 votes
I finally got through this. In config table in the database there was (probably just from some test long ago) a reference to that example.

Deleting that line made the updates to go through.

Now checking if it solved my actual problem...

Thanks for the help

hank

---
Tags: 8, updating
---


# Question
Title: How do I update configuration/database after a core update?
This may seem like a dumb question to some of you, I'm sure. After having worked with Drupal from version 6, I'm now for the first time using Drupal 8 and -- after some initial difficulties -- have actually come to enjoy the new development process (using Composer and Configuration Management etc.). However, I'm still failing to understand the indended workflow, after having completed a core update in my local installation. Here's my understanding, so far:

1. In case of simpler modifications -- like, say, having created a new content type -- I usually call `drush cex` on my local Drupal site, then transfer the contents of the sync directory to my staging (or production, if I'm feeling venturous) site (using FTP) and go to `Configuration > Development > Configuration Synchronization` to apply the changes. (Note that I can't call `drush cim` at this point, as I'm not able to use the terminal in my staging/production site.)
2. If any content has been created for that new content type in my local site, I transfer that content to staging using the `Deploy` module.

So far, that's working pretty well. However, how am I supposed to proceed, after having completed a bigger update that involves non-trivial modifications to the database?

1. Say, I'm performing a core update: `composer update drupal/core --with-dependencies`
2. I will then perform the necessary database updates locally, either by calling `drush updatedb` or by visiting `update.php` in a browser.

But then what?

Say, I'll upload all the new files via FTP to the staging site. Clearly, I cannot also copy the local database to the staging site, because the contents would be overwritten. So, I need to import the new configuration to the staging site... but accessing `Configuration > Development > Configuration Synchronization` to update the database will probably result in an error, exactly because the database has not been updated, yet.

This is where I'm stuck. I suspect, there's a piece to the puzzle that I'm missing, but what is it?

# Answer
> 2 votes
Updating Drupal 8 roughly goes like this. First in a **local** instance of your site:

* Run `composer update drupal/core --with-dependencies` to update core. (Updating all dependencies including contrib would be `composer update --with-dependencies`.)
* Now apply database updates by either `drush -y updb` or by visiting /update.php in your browser.
* Next export the config that may have changed now by either `drush -y cex` or from your Drupal back-end in the browser.
* Git commit and push the updated composer.lock file and the updated config files.

Next on your **live** site you roughly do the same, but now import the config at the end.

* Git pull the updated composer.lock and config.
* Run `composer install --no-dev` to update the files.
* Run `drush -y updb` or visit /update.php to apply the database updates.
* Run `drush -y cim` or visit your admin settings to import the updated config that now should match the one you exported locally earlier.

For a more advanced deployment flow, for example flushing cache and activating the maintenance mode, see my other answer on Order of drush commands for automated deployment?

---
Tags: 8, updating
---


# Question
Title: Search results only for the current language
I have a site with 4 languages and am using the builtin search to look for content on the site. How is it possible to restrict the search results only to the currently selected language?

I tried looking into Configuration \> Search Pages, but do not see any way how to do that there.

# Answer
The "Advanced" core search has this built in. If you prefer to do this from a theme - you could do it with form\_alter. This basically hides the advanced search settings and sets current language as the only language to get results from, in the search block and search page.

Alternately you can just allow users to control which language they want to get results from and simply allow them to use advanced search.

Code for theme:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_form_alter(&$form, &$form_state) {
  $form['help_link']['#access'] = FALSE;
  $form['advanced']['#access'] = FALSE;
  $form['basic']['keys']['#title'] = '';
  $manager = \Drupal::languageManager();
  $form['advanced']['lang-fieldset']['language']['#default_value'] = [$manager->getCurrentLanguage()->getId()];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_block_form_alter(&$form, &$form_state) {
  $manager = \Drupal::languageManager();

  $form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
  ];
  $form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . $manager->getCurrentLanguage()->getId(),
  ];
}

```
> 7 votes

# Answer
You can use simple way `hook_query_TAG_alter`. Example return node for current language.

```
<?php

use Drupal\Core\Database\Query\AlterableInterface;

/**
 * Implements hook_query_TAG_alter(): tag search_$type with $type node_search.
 */
function MYMODULE_query_search_node_search_alter(AlterableInterface $query) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $query->condition('n.langcode', $language, '=');
}

```
> 6 votes

# Answer
```
/**
 * Implements hook_query_TAG_alter()
 */
function hook_query_search_node_search_alter(&$query) {
      $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
      $query->condition('i.langcode', [$language, 'und', 'zxx'], 'IN');
}

```
> -1 votes

---
Tags: 8, search
---


# Question
Title: Reference three types of entities and render them in one list
I have this requirement, where a Node needs to reference instances of three different types of entities (a Node, a custom entity, and a webform). These three entities will then be rendered as one list of "related content".

Currently, I have them as three separate entity reference fields. But I could not figure out how to render them as a single list (it ends up being three lists of entities). Also tried the Dynamic Entity Reference module, but that one doesn't reference Config Entities (webform).

Am I missing an obvious way to achieve this?

# Answer
If I understand your question correctly, you currently have three different reference fields (one for each entity type to reference to) that each can have multiple values. And you want to combine the value of these three fields in groups, so the first values are displayed as a set, the second values are displayed as a set, etc.

I think the Paragraphs module is what you are looking for. You can create a paragraph that contains the three reference fields, in your case allowing only one value per field. And on your node (type) you add a multi-value paragraphs field, allowing your editor to provide groups of references which are rendered together.
> 2 votes

---
Tags: views, 8
---


# Question
Title: How do I filter a view by the results of hook_node_access?
I have been trying to wrap my head around a specific problem for a few days now and have been unable to find a solution. Here's my problem:

In my LMS I'm performing pretty complex access checks. (In particular, I need to check permissions over references: A *lesson* should be accessible, if it's part of some *course* that's marked accessible for that specific user.) I have already written a module implementing `hook_node_access` and, so far, everything is working fine. Here's part of the code:

```
function mymodule_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account){
  $type = $node->bundle();
  $user = $account->getAccount();
  $uid = $user->id();

  // only handle the lesson content type
  if ($type === 'lesson') {

    if ($account->id() !== 1) {

      // first, check the user's access to the lesson itself
      $lessonaccess = ...

      // then, check the user's access to the referring courses
      $courseaccess = FALSE;
      if ($node->hasField('reverse_entity_reference')) {
        $parentcourses = $node->get('reverse_entity_reference')->getValue();

        foreach ($parentcourses as $course) {
          $coursenode = \Drupal\node\Entity\Node::load($course['target_id']);
          // perform access checks for the referring course
          $courseaccess = $courseaccess || ...
        }
      }

      // combine the results; teasers should always be accessible
      if ($lessonisteaser || ($lessonaccess && $courseaccess)) {
        return AccessResult::allowed();
      } else {
        return AccessResult::forbidden();
      }
    }
  }

  else {
    return AccessResult::neutral();
  }
}

```

The problem is that I would now like to create a view listing all lessons that are accessible to the current user. So, simply filtering by node access -- as is straightforward to achieve in Views -- is not sufficient, as I need to **filter by what is returned from the access checks** in `hook_node_access`.

Can anybody think of a way to make that possible? Maybe storing the result somewhere?

# Answer
The problem here is that hook\_node\_access is a PHP function that has nodes passed through it, but Views is doing a database query for the relevant nodes. These two are incompatible, as Views would have to fetch every node in the system from the DB, then pass them all through that function, which would add major overhead.

Drupal's solution to this is the node grants system, which writes a set of grants to the {node\_access} table, which can then be used in querying nodes.

To implement a grants system, you'll need to implement hook\_node\_access\_records(), which is called when each node is saved, and sets up a number of rules by which the node being save is allowed to be accessed. Then you implement hook\_node\_grants(), which generates a set of potential grants for the current user, and tries to match them with the grants created in hook\_node\_access\_records(). When there is a match, the user is granted permission to access, and this will work with DB queries.
> 3 votes

---
Tags: views
---


title: Add JavaScript at the bottom of a page

text:
# Question
Title: Add JavaScript at the bottom of a page
How can I add JavaScript scripts to bottom of a page, in my template?

# Answer
I think you can do it with drupal\_add\_js(); it seems that the scope key option is your friend!
> 19 votes

# Answer
In your theme's `html.tpl.php` there is a line `<?php print $scripts; ?>`.

That's the line that prints out the javascript in your page.

You can move it around anywhere you like, for example, place it after everything else, just before the closing `body` tag to have all your scripts load at the bottom.
> 6 votes

# Answer
You can try adding the file like this:

```
drupal_add_js('sites/all/themes/themname/js/skrollr.js', array('scope'=>'footer'));

```
> 5 votes

# Answer
It's worth looking at using this module here to manage that for you https://drupal.org/project/advagg
> 2 votes

# Answer
I enabled AdvAgg Modifier and Advanced CSS/JS Aggregation. Then I visited settings page `/admin/config/development/performance/advagg/mod` where I checked options:

* Enable preprocess on all JS
* Move all inline scripts to the bottom of the execution order
* Move all browser conditional JavaScript to the bottom of the group
* Move JS to the footer - All

And now I have all JS on the bottom (as Google recommends), without the need to change `html.tpl.php`.
> 0 votes

---
Tags: 7, javascript
---


title: query condition comparing two fields

text:
# Question
Title: query condition comparing two fields
i am having this query :

```
   $db = \Drupal::database();

  $exist_query= $db->select('user__roles', 'ur');
  $exist_query->fields('ur', ['entity_id']);
  $exist_query->condition('ur.entity_id','u.uid', '=');
  $exist_query->condition('ur.roles_target_id', $included_user_roles, 'IN');

  $not_exist_query= $db->select('user__roles', 'ur');
  $not_exist_query->fields('ur', ['entity_id']);
  $not_exist_query->condition('ur.entity_id','u.uid', '=');
  $not_exist_query->condition('ur.roles_target_id', $excluded_user_roles, 'IN');

  $query = $db->select('users_field_data', 'u');
  $query->fields('u', ['uid']);
  $query->condition('u.uid', 1, '>');
  if (!empty($param['login_value'])) {
    $query->condition('u.login', $logindate, '<');
    $query->condition('u.login', 0, '!=');
  }
  $query->exists($exist_query);
  $query->notExists($not_exist_query);
  dpq($query);

```

the problem i am having is here

```
  $exist_query->condition('ur.entity_id','u.uid', '=');

```

it generates :

```
WHERE (ur.entity_id = 'u.uid')

```

when it should

```
WHERE (ur.entity_id = u.uid)

```

How can i solve this ?

The working request i am trying to achieve

```
SELECT u.uid AS uid
FROM
users_field_data u
WHERE (u.uid > '1') AND (u.login < '1586705658') AND (u.login != '0') AND (EXISTS (SELECT ur.entity_id AS entity_id
FROM
user__roles ur
WHERE (ur.entity_id = u.uid) AND (ur.roles_target_id IN ('admin_site')))) AND (NOT EXISTS (SELECT ur.entity_id AS entity_id
FROM
user__roles ur
WHERE (ur.entity_id = u.uid) AND (ur.roles_target_id IN ('membre_du_site'))))

```

# Answer
> 2 votes
You can add such a clause manually:

```
$not_exist_query->where('ur.entity_id = u.uid');

```

---
Tags: 8, database
---


# Question
Title: How can I programmatically restrict node access?
I'm using Drupal 8 with the nodeaccess module.

I'm able to set the node grants with the form.

I also have a custom module which imports new nodes. These new nodes should be shown only to certain users.

I know I can insert the corresponding lines into the database tables nodeaccess and node\_access. But this might be not consistent.

Is there a way to set the nodeaccess programmatically?

# Answer
I use a function to build the database rows in node\_access and nodeaccess:

```
  private function set_node_access($nid, $id, $realm='nodeaccess_uid', $view=1, $update=0, $delete=0)
  {
    // ksm("nid: $nid uid: $uid");
    $connection = \Drupal::database();
    $sql = "INSERT INTO nodeaccess (nid, gid, realm, grant_view, grant_update, grant_delete)
            VALUES($nid,$id,'$realm',$view,$update,$delete)
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete)";
    $connection->query($sql);
    $sql = "INSERT INTO node_access(nid, langcode, fallback, gid, realm, grant_view, grant_update, grant_delete)
            VALUES($nid,'de', 1, $id,'$realm',$view,$update,$delete)
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete);";
    $connection->query($sql);
  }

```

That's not the nice way, but it works for me.
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: Memory leak in hook_entity_type_alter with php7.2 or higher
So i upgraded PHP7.0 to PHP7.4 due to a requirement from a module. Now when enabling/disabling modules, clearing cache, importing config i get the memory exhausted error. After some debugging with a new installation i found out that one of my custom modules with hook\_entity\_type\_alter causes this errors. In this hook i'm trying to add my custon viewmodes depending on the role for the profile edit form. Using the following piece of code:

```
function custom_module_entity_type_alter(array &$entity_types) {
  $current_user = \Drupal::currentUser();

  $roles = $current_user->getRoles();

  $node_type = $entity_types['user'];
  $default_handler_class = $node_type->getHandlerClasses()['form']['default'];
  $node_type->setFormClass('profile_edit',  $default_handler_class);
  if(in_array('organization', $roles)) {
    $node_type->setFormClass('organization_edit',  $default_handler_class);
  } else {
    $node_type->setFormClass('profile_edit',  $default_handler_class);
  }
}

```

I had to remove all code in this hook to make the site work again, even:

```
function custom_module_blocks_entity_type_alter(array &$entity_types) {
  $current_user = \Drupal::currentUser();
  kint($current_user);
}

```

Gives me this error, without kint it works. But any more code in this hook will give me the memory error. I already tried putting memory\_limit on 500M and even -1 where my PC completely froze due to this memory leek.

# Answer
I fixed it by using a different hook

```
function custom_module_entity_form_display_alter(&$form_display, $context) {
  if($context['entity_type'] == 'user' && $context['bundle'] == 'user'){
    $user = \Drupal::currentUser();
    if(in_array('organization', $user->getRoles())){
      $storage = \Drupal::service('entity_type.manager')->getStorage('entity_form_display');
      $form_display = $storage->load('user.user.organization_edit');
    } else {
      $storage = \Drupal::service('entity_type.manager')->getStorage('entity_form_display');
      $form_display = $storage->load('user.user.profile_edit');
    }
  }
}

```
> 0 votes

---
Tags: 8
---