# Question
Title: Drush error when attempting Drupal update: unable to copy/move
I have a Drupal site running on localhost (Windows) that I'm trying to update from 8.6.7 to 8.6.15.

When using Drush to perform the update (`drush up drupal -y`), I encounter the following error:

```
Unable to copy C:\Users\USERNA~2\AppData\Local\Temp/drush_tmp_1556533742_5cc6d1ee1cacf/drupal-8.6.15 to
W:\htdocs\site-name\www/drupal-8.6.15.
Unable to move C:\Users\USERNA~2\AppData\Local\Temp/drush_tmp_1556533742_5cc6d1ee1cacf/drupal-8.6.15 to
W:\htdocs\site-name\www/drupal-8.6.15.
Updating project drupal failed. Attempting to roll back to previously installed version.
Backups were restored successfully.

```

I've tried:

* clearing Drush's cache (`drush cc drush`)
* updating Drush (via composer) (now running Drush 8.2.3)
* clearing Drupal's caches

But the problem remains.

This problem does NOT occur when updating modules. Only Drupal itself.

I checked the `C:\Users\USERNA~2\AppData\Local\Temp` folder while drush was working, and I was able to confirm that the `drush_tmp_1556533742_5cc6d1ee1cacf` subfolder was indeed present for a time (containing the Drupal .tar.gz and its upacked folder). So there's no issue in writing in this folder.

Any idea what causes this and how to solve it?

Thanks in advance.

# Answer
We can only guess at an answer. A likely scenario might be disk space, permissions, or some other conflict with Drush & filesystem, but that's speculation.

Run the same command with the `--debug` flag (`drush up drupal -y --debug`) to see a verbose dump of what Drush is doing and look for errors/warnings that occur as Drush is attempting a core update. Once you know the underlying filesystem issue you'll be able to resolve it.
> 1 votes

# Answer
Please upgrade to Drush 9 and try again. See Drush's Drupal Compatibility.

And then maybe use `grasmash/composerize-drupal` to composerize your Drupal installation because:
> 0 votes

---
Tags: 8, drush
---


# Question
Title: How to build render array with node title linked to node for a list of nodes
I have a paragraph type to output a list of content. The editor can set different options, one of them is to show the list as teasers or just node titles linked to node. The corresponding part in code looks like:

```
    if ($teaser_display) {
      $value = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
    }
    else {
      $value = \Drupal::entityTypeManager()->getViewBuilder('node')->viewField($node->get('title'), ['link' => true, 'type' => 'entity_reference_label']);
    }

```

Is there a way to build the render array for titel field linked to the node without creating a dedicated view mode and without rendering the markup directly? I thought it should somehow work to use the method viewField() as $display\_options can either be a view mode or an array with display options.

# Answer
> 2 votes
As pointed out by @4k4 I used the entity reference field formatter, which does not apply here. Theming as link, as answered in How do I theme a link? does the job:

```
if ($teaser_display) {
  $value = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
}
else {
  $value = [
    '#type' => 'link',
    '#title' => $node->label(),
    '#url' => $node->toUrl(),
    '#cache' => ['tags' => $node->getCacheTags()],
  ];
}

```

---
Tags: 8
---


# Question
Title: Extract content only from Drupal 8 site?
Is there a way to extract only the content (data) that content authors have added to a Production Drupal instance?

Basically, I'm trying to figure out which tables in MySQL are responsible for holding the content data (nothing configuration related), export the data from those content tables, and then import (the diff) into my local MySQL database.

Thanks you.

# Answer
> 1 votes
Not sure about a good solution for this, but this is likely a pretty hard problem to solve, keep in mind that it's not just about new content, but also updates and deletions.. how are you going to track that?

The thing is that almost every table in Drupal holds content. Configuration is limited to config, key\_value and a few others, almost everything else is content in one way or another. And key value is also not something you can exclude and transport in a different way, so the only thing you could exclude really is the config table.. but that's tiny, compared to the others and actually not really worth excluding, except when you want to explicitly avoid removing configuration.

# Answer
> 1 votes
I had some good results using this module: https://www.drupal.org/project/content\_sync You have to ensure the module is installed on both your local and remote destinations and then use the import/export feature that it introduces into the system to export content from 1 site and import it to the other. This requires no database manipulation and doesn't interfere with config or code. I did have an issue where some images would not import but all other fields did. I was able to easily correct this though and the Issues listed on the module page appear to have found a solution for that too.

---
Tags: 8, database
---


# Question
Title: How to include exposed filter name in views data feed export CSV title?
Trying to get views data export to save file with selected token from exposed filter

In the settings I can see this explanation:

%exposed == effective exposed filters, like filter1\_foo-filter2\_bar

So I tried this:

```
%[field_industry_type].csv
%field_industry_type.csv
%field_industry_type_tid.csv

```

But can't get nothing to work, what I'm trying to do is use a field filter as .csv name, one of the filter types is industry, so if industry is "relocation" I would like the file to save like this:

relocation.csv

Maybe my token syntax is wrong?

# Answer
%exposed itself combination of the number of exposed filters you have on your view. When you save file name only with %exposed.csv it should generate file name as per your request would be like "industry\_relocation.csv".

So, %exposed will generate based on "FIELDIDENTIFIERNAME\_VALUE-ANOTHERFIELD\_VALUE".

To generate a custom file name you should use hook\_views\_pre\_build() function. You can find examples here: https://www.drupal.org/project/views\_data\_export/issues/1288612
> 0 votes

---
Tags: views, tokens
---


# Question
Title: Convert current time from Unix timestamp to date format (d/m/y)
In my custom module (.module) file, I am using:

```
$current_time = \Drupal::time()->getCurrentTime();
date_default_timezone_set('GMT');

```

to get the current date... However, the date value is returned in int A Unix timestamp like: `1556582116`

I have tried so far something like:

```
$current_time = \Drupal::time()->getCurrentTime();
$timenow = $current_time->format('Y-m-d H:i:s');

```

or

```
$current_time = \Drupal::time()->getCurrentTime('d');

```

to get only the day value... but with no success

How can I return the date value in the format of: D/M/Y like: `30/04/2019` or `30/Apr/19`

# Answer
> 5 votes
You can do that with simple PHP function. Is there any specific reason you want a drupal function ? If not then you can use PHP's `date()` function.

```
$current_time = \Drupal::time()->getCurrentTime();

//To return 30/04/2019
$date_output = date('d/m/Y', $current_time);

//To return 30/Apr/19
$date_output = date('d/M/y', $current_time);

```

# Answer
> 12 votes
You can format the current date using the below solutions.

**Drupal 8**:

```
//format date in 30/04/2019
$current_time = \Drupal::time()->getCurrentTime('d');
$date_today = format_date($current_time, 'custom', 'd/m/Y');

//format date in 30/Apr/2019
$current_timestamp = \Drupal::time()->getCurrentTime();
$todays_date = format_date($current_timestamp, 'custom', 'd/M/Y');

```

**Drupal 9**:

```
//format date in 30/04/2019
$current_time = \Drupal::time()->getCurrentTime('d');
$date_today = \Drupal::service('date.formatter')->format($current_time, 'custom', 'd/m/Y');

//format date in 30/Apr/2019
$current_timestamp = \Drupal::time()->getCurrentTime();
$todays_date = \Drupal::service('date.formatter')->format($current_timestamp, 'custom', 'd/M/Y');

```

---
Tags: 8, datetime
---


# Question
Title: Wizard or Form to create 5 nodes of 3 content types
I'm building a genealogy site. One of the most important use cases is to create an individual. I want to use a single form to capture information that will be used to create up to five nodes after clicking submit. I've done a bunch of research, and found lots of stuff partially represented by the links below, but I haven't found anything that will do this. Can you point me to any modules to that do this? Or will I need to write my own module for this?

New Individual form captures the following fields:

* Birth Given & Surnames
* Current checkbox (checked if it's still individual's current name)
* End date, if not current name
* Current Given & Surnames - if different from birth
* Start Date - if applicable
* Date of Birth
* Place of Birth
* Date of Death
* Place of Death

The form then creates the following five nodes:

1. Individual node - with Title
2. Name node for birth name
3. Name node for current name (if different from birth name)
4. Event node for birth
5. Event node for death

Nodes 2-5 would have ER field\_individual, to link back to the individual to which they are related.

Below are links to some of the resources I have found which are similar, but do not actually do what I'm looking to do:

# Answer
> 1 votes
I think you will need a custom module to do that

An outline of what your module should be doing

---
Tags: forms
---


title: Drush 9 on Windows 7 problem

text:
# Question
Title: Drush 9 on Windows 7 problem
I installed drush 9 and now I'm getting the following error whenever I run a drush command:

```
/usr/bin/sh: /cygdrive/c/mysite/vendor/drush/drush/drush.launcher: No such file or directory

```

Details:

* I have installed drush 9 on Windows 7 using `composer`. This was an update to my previous drush 8.
* The drush files are installed in my local site's `vendor` directory.
* The `drush.launcher` file is in the directory indicated in the above error message.
* To run a drush command, I go to my site's root directory using `MINGW64` and run the command using `vendor/bin/drush`. for example:

```
vendor/bin/drush drusn --version

```
* I have `C:\mysite\vendor\bin` in my `path` environment variable.
* I don't want to use `drush.launcher` at this time but not sure why it gets invoked and yet not found.

Thank you in advance for your help.

# Answer
> 0 votes
Drush 9 doesn't come with `drush.launcher` so something is wrong with your Drush installation / update. You should try to fix that by updating or reinstalling Drush. However, in the meantime just delete `drush.launcher`.

PS! It's recommended to install Drush Launcher in addition to the site-local Drush.

---
Tags: drush
---


title: "Cannot use string offset as an array"

text:
# Question
Title: "Cannot use string offset as an array"
I am theming a node for a specific content type and split the theme into whether the node is being displayed as a teaser or full. This error only comes up when you view the full node.

> Error: Cannot use string offset as an array in XXXXXX/node--event.tpl.php on line 100

The node displays fine as a teaser, which makes this error even more confusing as the problematic line is used during teaser display. The code below is the one for the teaser part of the template.

```
  <?php if ($teaser): ?>
  <div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

        <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?> -

        <span class="eventdate"><?php print(substr($node->field_date[und][0][value], 0, -9));?></span>
        </a></h2>
  <div class="content clearfix"<?php print $content_attributes; ?>>
     <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      //*********LINE100**************
print($node->body[und][0][safe_value]);
    ?>
  </div>

    <div class="link-wrapper">
      <?php print $links; ?>
    </div>
    </div>
  <?php endif; ?>

```

# Answer
> 1 votes
If you get that error, it means that `$node->body` is not an array, but a string. In that case, PHP would take `$node->body[und]` as a string offset, and you could not use `$node->body[und][0][safe_value]`.

To notice that both `und`, and `safe_value` are considered from PHP two constants, but Drupal doesn't define those constants. In that case, PHP would use as value of the constants `und`, and `safe_value`, the values of the strings `'und'`, and `'safe_value'`, but you should not rely on that.

# Answer
> 0 votes
In Drupal 7, you should be utilizing the render() function rather than directly printing a node field's value. So, line 100 of your node.tpl.php file should read:

```
print render($content['body']);

```

If you need to make changes to the data in the $content\['body'\] variable for teaser views, that sort of processing should be done in an implementation of template\_preprocess\_node(), not in the node template.

More information about your motivation behind the code on line 100 and your desired result would help me to provide a solution more specific to your situation.

# Answer
> 0 votes
I don't know if this helps, but I encountered this error because I declared an array as a string earlier in my own code.

https://php.net/manual/en/migration71.incompatible.php#migration71.incompatible.empty-string-index-operator (in PHP 7.0 this is allowed, but PHP 7.1+ will not covert stings to arrays)

I can't see enough of your code to inspect the issue, but it's possible something similar maybe happening.

https://stackoverflow.com/questions/1873970/cannot-use-string-offset-as-an-array-in-php

---
Tags: theming, nodes
---


# Question
Title: How do I set an empty link title in a menu item?
I'm using a fontawesome icon in a menu (with the tbmegamenu module) and I want to remove the text. Drupal forces me to enter something, ` ` doesn't work so as a temporary solution I put at dot `.` How can I remove the dot without resorting to very dirty CSS tricks?

See also the actual HTML at the website.

Entering an empty string in the menu title would be the cleanest way to get to a solution now. Maybe it's possible with a hook that lets me put `<none>` in the menu title?

# Answer
> 1 votes
If you use Icon API and Icon API:Menu submodule, You can just put `<none>` in the text field of the menu item. fontawesome icons are available in the menu item properties with this module.

# Answer
> 2 votes
No need to resort to "dirty CSS tricks", you can just use clean CSS:

```
a.class {
  display: inline-block; // Or block if it makes more sense for your layout.
  text-indent: -9999em;
}

```

This is the correct way to handle it, as you can include proper text as your link (e.g. "Home"), so you're not alienating users with screen readers, etc.

# Answer
> 2 votes
What about

```
<a href="/" class="">
  <i class="icon-home" style="text-indent: -1000px;">
    This is the homepage
  </i>
</a>

```

# Answer
> 0 votes
You can use FontAwesome menu icons module in Drupal 8.

After enable it, you get new options in each menu-item edit page:

* A field for setting a fontawesome icon writting the code (fa-user, fa-sign-out,...)
* Another field ("FontAwesome Icon - Appearance") where you can select "Without text" for an empty title.

---
Tags: navigation
---


# Question
Title: Mink failing to run JavascriptTestBase tests
I suspect this is more a config issue than anything but struggling to run JavascriptTestBase tests. The error I'm getting is as below:

> wodby@php.container:/var/www/html $ ./bin/phpunit -v -c ./web/core ./web/core/tests/Drupal/FunctionalJavascriptTests/Tests/JSWebWithWebDriverAssertTest.php PHPUnit 6.5.8 by Sebastian Bergmann and contributors.
>
> Runtime: PHP 7.1.17 Configuration: /var/www/html/web/core/phpunit.xml
>
> Testing Drupal\FunctionalJavascriptTests\Tests\JSWebWithWebDriverAssertTest S 1 / 1 (100%)
>
> Time: 21.2 seconds, Memory: 6.00MB
>
> There was 1 skipped test:
>
> 1) Drupal\FunctionalJavascriptTests\Tests\JSWebWithWebDriverAssertTest::testJsWebAssert An unexpected error occurred while starting Mink: Could not open connection: Error forwarding the new session cannot find : Capabilities {browser: firefox, browserName: chrome, browserVersion: 9, deviceOrientation: portrait, deviceType: tablet, name: Behat Test, selenium-version: 2.31.0, version: 9}
>
> /var/www/html/web/core/tests/Drupal/FunctionalJavascriptTests/JavascriptTestBase.php:50 /var/www/html/web/core/tests/Drupal/Tests/BrowserTestBase.php:484
>
> OK, but incomplete, skipped, or risky tests! Tests: 1, Assertions: 1, Skipped: 1.

I'm running this directly within a docker container. Selenium is also running in a docker container and I know I can connect from my PHP/Apache container to the Selenium container as running

```
wget http://selenium:4444/grid/console

```

Returns the selenium Grid Console homepage.

My phpunit.xml file looks as follows:

```
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true">
  <php>
    <ini name="error_reporting" value="32767"/>
    <ini name="memory_limit" value="-1"/>
    <env name="SIMPLETEST_BASE_URL" value="http://apache"/>
    <env name="SIMPLETEST_DB" value="mysql://drupal:drupal@mariadb/drupal"/>
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value=""/>
    <env name="SYMFONY_DEPRECATIONS_HELPER" value="weak_vendors"/>
    <env name="MINK_DRIVER_ARGS_WEBDRIVER" value='["chrome", null, "http://selenium:4444/wd/hub"]'/>
  </php>
  <testsuites>
    <testsuite name="unit">
      <file>./tests/TestSuites/UnitTestSuite.php</file>
    </testsuite>
    <testsuite name="kernel">
      <file>./tests/TestSuites/KernelTestSuite.php</file>
    </testsuite>
    <testsuite name="functional">
      <file>./tests/TestSuites/FunctionalTestSuite.php</file>
    </testsuite>
    <testsuite name="functional-javascript">
      <file>./tests/TestSuites/FunctionalJavascriptTestSuite.php</file>
    </testsuite>
  </testsuites>
  <listeners>
    <listener class="\Drupal\Tests\Listeners\DrupalListener">
    </listener>
    <listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener">
    </listener>
  </listeners>
  <filter>
    <whitelist>
      <directory>./includes</directory>
      <directory>./lib</directory>
      <directory>./modules</directory>
      <directory>../modules</directory>
      <directory>../sites</directory>
      <exclude>
        <directory suffix="Test.php">./</directory>
        <directory suffix="TestBase.php">./</directory>
      </exclude>
     </whitelist>
  </filter>
</phpunit>

```

Could anyone give me any pointers in the right direction?

# Answer
There's an annoying bug with the `Selenium2Driver` code with regards to specifying the correct browser. If no capabilities are specified, it uses the defaults:

```
    public function setDesiredCapabilities($desiredCapabilities = null)
    {
        if (null === $desiredCapabilities) {
            $desiredCapabilities = self::getDefaultCapabilities();
        }

```

Note in the error it hase `browser` defaulted to `firefox` while the `browserName` is correctly set to `chrome`:

```
Capabilities {browser: firefox, browserName: chrome,

```

In order to workaround this issue, change your capabilities to also specify `browser`:

```
<env name="MINK_DRIVER_ARGS_WEBDRIVER" value='["chrome", {"browser": "chrome"}, "http://selenium:4444/wd/hub"]'/>

```
> 1 votes

---
Tags: 8, testing
---


# Question
Title: Running functional tests on a non-English site
When creating functional tests (extending BrowserTestBase) for a D8 site, how would I go about changing the default language of the site being temporarily created by BrowserTestBase?

I'm trying to run tests on a site in a non-English language, and I'd like to avoid confusion by using English terms etc. in test cases.

As far as I see, Drupal/Core/Test/FunctionalTestSetupTrait.php sets the default langcode to be 'en' (in the installParameters method) and there's no option to specify custom installation parameters. Besides hacking this manually, is there a more elegant, "proper" way of changing this behavior?

If that's not possible, then would it be possible to change the site's language after it's created, maybe in the setUp method of the test class?

# Answer
> 0 votes
I think there are a few ways. The simplest might be to override the `installParameters()` method to specify your desired language:

```
protected function installParameters() {
  // This will come back with the langcode set to `en`.
  $parameters = parent::installParameters();

  // Update to desired langcode:
  $parameters['parameters']['langcode'] = 'es';

  return $parameters;
}

```

I didn't find any tests in core that did it this way, but there are a few that change it during setup via the UI. (This example from `LanguagePathMonolingualTest`)

```
// Make French the default language.
$edit = [
  'site_default_language' => 'fr',
];
$this->drupalPostForm('admin/config/regional/language', $edit, t('Save configuration'));

```

---
Tags: 8, i18n-l10n, testing
---


title: Unit test a plugin

text:
# Question
Title: Unit test a plugin
I want to add a small unit test to a migrate plugin for a migration I am building. I looked for some examples but did not find much for unit tests of a plugin.

I want to run some assertions when the plugin is instantiated and check its values in a unit test. Is `PluginTestBase` the class to use? Can I not simply run a test without bootstrapping Drupal?

```
class EndpointTest extends PluginTestBase {
  // not sure what to do here
}

```

# Answer
> 2 votes
The test class `PluginTestBase` is a kernel test (which bootstraps Drupal, has a db, and limited schemas/configs installed). This can be valuable as they are faster than full functional tests, and require less service mocking than unit tests do for plugins that rely heavily on (for instance) the database or entity API.

That being said, you can write traditional unit tests for plugins depending on how they are written. Here's a few examples I am aware of:

---
Tags: 8, testing, plugins
---


# Question
Title: Output Paragraph values instead of the Paragraph IDs in a View REST export?
I have a View with a REST export display (image attached) that has some indexed field values from Search API.

The highlighted portion, `authors`, is a Paragraph field. Instead of the entity ID pointing to the Paragraph, how can I output a JSON object per delta with the field value?

Note, I am not using JSON:API (and cannot). Also, this is a Search API DB (and eventually Solr) based index, so 'Entity' mode cannot be used (and thus, no custom Normalizer).

What can I hook into, or what class can I create, to change how the Paragraph is being included in the result output? I thought about using a custom field formatter, but that seems like a lot of work just to output JSON data (classes, theme hooks, twig etc).

# Answer
> 1 votes
> I thought about using a custom field formatter, but that seems like a lot of work just to output JSON data

**No Code Solution:**

Install Views Field View

Create a new View, "User view" in this case (does not to be a REST view).

Go to your Rest View

* Add field of "View", select the view you added above.
    + For contextual filter, use the replacement pattern for your author's field.

---
Tags: views, 8
---


# Question
Title: Show exposed filter by logged in user in drupal 8
I have a view that in that view I set up 3 exposed filter, all filtering working fine.

* First: Filter by contact first name
* Second: Filter by Project name
* Third: Filter by Contact region/location

The third filter should be shown just for specific logged in user, and that user should be Administrator.

I tried the following codes and it does not working, even doesn't show the Var\_dump, so how should it change to work?

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

  if ($form_id == 'views_exposed_form') {

    //unset($form['average']);

    var_dump($form);

    die();
  }
}

```

> Here I attached my view configuration and settings may help you to get what I have in my view

# Answer
Following example unsets the filter `average` when user is NOT administrator, you can modify it to your specific case.

```
use Drupal\Core\Form\FormStateInterface;
function my_modulename_form_alter(&$form, FormStateInterface $form_state, $form_id){

  $roles = \Drupal::currentUser()->getRoles();
  $is_user_admin = in_array("administrator", $roles);
  $is_exposed = $form_id == 'views_exposed_form';
  $is_filter_set = isset($form['average']);

  if ( $is_exposed && $is_filter_set && !$is_user_admin ) {
    unset($form['average']);
  }
}

```

If you want to unset only on a specific view exposed form use this condition

```
$is_our_view = $form["#id"] == "views-exposed-form-article-page-1";

```
> 5 votes

---
Tags: views, 8, forms
---


# Question
Title: How to retrieve the link and description in a custom file field twig template
I have a field `field_file`. I've created a template `field--field_file.html.twig`.

How can I access the link, description (and attributes and icon ) separately in this file?

I have:

```
{% for item in items %}
  {{ item.content }}
{% endfor %}

```

which just spits out themed content.

I've debugged with dump() and there seems like the possibility of at least retrieving the 'description' somehow, but item.description does not work, for example.

# Answer
File link: `{{ file_url(item.content['#file'].getFileUri()) }}`

File description: `{{ item.content['#description'] }}`
> 2 votes

---
Tags: 8, theming
---


title: How to add a nolink menu item

text:
# Question
Title: How to add a nolink menu item
I'm creating a menu item for my main navigation bar. It looks like this:

module/module.links.menu.yml:

```
top.link:
  title: 'Operations'
  description: 'Operations'
  parent: main
  menu_name: main
  url: 'route:<nolink>'
  expanded: TRUE
  weight: -49

mod.first_option:
  title: 'Functionality 1'
  description: 'Functionality 1'
  parent: 'top.link'
  menu_name: 'top.link'
  route_name: 'mod.route_name1'
  expanded: TRUE
  weight: -49

mod.secon_option:
  title: 'Functionality 2'
  description: 'Functionality 2'
  parent: 'top.link'
  menu_name: 'top.link'
  route_name: 'mod.route_name2'
  expanded: TRUE
  weight: -47

```

I'm trying to create an empty top level link, with nested elements beneath it for a menu. I've tried `url: 'internal:##'`, `url: 'route:<nolink>'`, and `link: '<nolink>'`, Anything else I could try?

# Answer
Try adding the following, but this will still reload the page, which may not be ideal.

```
url: 'internal:#nolink'

```

These module maybe interesting as it may not be necessary to manually edit the menu code. You can add a class to a menu item and add CSS

```
pointer-events:none; cursor:default; text-decoration:none;

```

https://www.drupal.org/project/link\_attributes https://www.drupal.org/project/menu\_link\_attributes
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: How to display a link field with its link text in a twig template
A content type includes a link field `link` that accepts Link text.

A user inputs the URL `/target` with the Link text "Go to target".

How do I get twig to generate

```
   `<a href="/target">Go to target</a>`

```

I have tried what I've found by reading, including

* `{{ node.field_link }}` (crashes)
* `{{ node.field_link|render }}` (crashes)
* `{{ node.field_link.value }}` (does nothing)
* `{{ node.field_link.0.url }}` (displays `/target` but not as a link and ignores the link text)
* `{{ node.field_link.uri }}` (displays `internal:/target` but not as a link and ignores the link text)

Seems like there must be a one-step way to accomplish this.

# Answer
> 4 votes
`{{ node.field_link }}` and `{{ node.field_link|render }` crashes because `node.field_link` of type FieldItemList not a rendered array.

Instead of using `node` variable use `content` variable like `{{ content.field_link }}` or even `{{ content.field_link.0 }}` it works.

---
Tags: 8, theming
---


title: Putting footer region under body tag

text:
# Question
Title: Putting footer region under body tag
I'm fairly new to drupal and this is my first time posting on stackexchange. Constructive critisism and feedback are more than welcome.

All regions in my custom theme are placed inside the body tag from html.html.twig file. Is there any way to create a region that is located underneath the body?

The markup should look something like this:

```
<header>header region block(s)</header>
<body>...</body>
<footer>footer region block(s)</footer>

```

Right now the way it's rendered it looks like this:

```
<body>
 <header>header region block(s)</header>
  ...
 <footer>footer region block(s)</footer>
</body>

```

I'm on drupal 8.6. Thanks in advance, Geordi

# Answer
Best practice dictates that you should not put the header or footer outside of the body tag. All visible content on your site goes inside the body tag.

Correct HTML syntax looks like this (here is a basic example):

```
<head>
  <title>My Drupal site</title>
  <!-- Other metadata goes here -->
</head>
<body>
  <header>
    <!-- Top of the page content goes here -->
  </header>
  <section>
    <!-- Main body content goes here -->
  </section>
  <footer>
    <!-- Footer content goes here -->
  </footer>
</body>

```

See this page for some extra details https://www.w3schools.com/html/html5\_semantic\_elements.asp

I know this doesn't technically anwer your question, but I feel this is a "correct" response in regards to what information will be most helpful.
> 1 votes

---
Tags: theming
---


# Question
Title: Which of the two approaches to routing a module settings page is the best practice?
There seems to be two ways to link a route to a settings form for a module. I'm curious as to whether one is considered a better practice, and why.

```
_controller: '\Drupal\mymodule\Controller\MyController::myMethod'

```

or

```
_form: '\Drupal\mymodule\Form\mySettingsFormFile

```

# Answer
Without knowing what is in the controller this would be the second one. The extra custom controller class only makes sense if you do something in myMethod() the form controller invoked by \_form is not able to do.

See https://www.drupal.org/node/2117411#fapi-in-route

This integrates the form in a request so that it can receive route parameters and the request itself as well as returning a response if necessary.
> 3 votes

---
Tags: routes
---


# Question
Title: Understanding page-title.html.twig and/vs field--node--title.html.twig
This question is based on the desire to have only one wrapping tag around the title value. (I am utilizing the block system to render the page/node title)

Both of the templates utilize some sort of attribute array on the wrapping element, so I am not sure it is safe to remove either.

I am hoping to better understand why there are two levels to this elements theming, and maybe more importantly, would it be detrimental to remove the attributes from the `field--node--title.html.twig`?

**page-title.html.twig**:

```
{{ title_prefix }}
{% if title %}
  <h1{{ title_attributes }}>{{ title }}</h1>
{% endif %}
{{ title_suffix }}

```

**field--node--title.html.twig**:

```
<span{{ attributes }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</span>

```

# Answer
* Every page has a title, but not every page has title field (views pages, settings forms,...). Only fieldable entities (like node, user, taxonomy term,...) can use a `field--ENTITYTYPE--FIELDNAME.html.twig` template.
* Very often the title field of an entity is NOT the title of a page (imagine a views page showing 10 nodes), that's why the `h1` is in `page-title.html.twig`
* Modules or field formatters might use those attributes. Removing it is no showstopper, but it might have side effects depending on the modules you use. (e.g. core's QuickEdit module will not work without `{{ attributes }}`).
> 2 votes

---
Tags: 8, theming
---


title: Removing specific HTTP response header

text:
# Question
Title: Removing specific HTTP response header
I am trying to remove specific HTTP response header from my site. The header looks like this:

```
Link: <https://example.com>; rel="canonical",<https://example.com>; rel="shortlink"

```

So far I have tried this simple code in my `theme_html_head_alter`:

```
header_remove("Link");

```

But that does not remove the header. Is there some specific Drupal way to deal with this, or am I using this code in wrong function? Or am I completely wrong with this?

Thank you in advance

# Answer
> 0 votes
You can remove it using `hook_html_head_alter` like the following:

```
/**
 * Implements hook_html_head_alter().
 */
function myTheme_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $head_element) {
    if (strpos($key, 'drupal_add_html_head_link:shortlink') === 0) {
      unset($head_elements[$key]);
    }
  }
}

```

**PS :** the above code remove links with `rel="shortlink"` if you want to remove links with `rel="canonical"` just add another if and change `shortlink` by `canonical`.

---
Tags: 7, http-request
---


# Question
Title: How do I inject UserInterface into Access Control?
I am trying to create a custom access control in my custom module in Drupal 8.

But I am having issues in achieving it.

I cant find a proper way to inject UserInterface class in access method.

Basically what I am trying to do is similar to this

https://api.drupal.org/api/drupal/core%21modules%21contact%21src%21Access%21ContactPageAccess.php/8.7.x

Similar to above code I am tring to get details of **user** object in access method. But cant find a proper way to achieve this.

My Code is as follows:

**custom\_module\src\Access\CustomRoleAccessCheck.php**

```
<?php
namespace Drupal\custom_module\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserDataInterface;
use Drupal\user\UserInterface;

/**
 * Access check for Custom Controller route.
 */
class CustomRoleAccessCheck implements AccessInterface {

  /**
   * The contact settings config object.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The user data service.
   *
   * @var \Drupal\user\UserDataInterface
   */
  protected $userData;

  /**
   * Constructs a ContactPageAccess instance.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\user\UserDataInterface $user_data
   *   The user data service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, UserDataInterface $user_data) {
    $this->configFactory = $config_factory;
    $this->userData = $user_data;
  }

  /**
   * Checks access to the given user's contact page.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user being contacted.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The currently logged in account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(UserInterface $user, AccountInterface $account) {
    $contact_account = $user;
    dpm($contact_account); // Need this values for some other functionality.

    if ($contact_account->isAnonymous()) {
      return AccessResult::forbidden();
    }

    return AccessResult::allowed();
  }

}

```

**services.yml**

```
custom_module.custom_role_access_check:
    class: Drupal\custom_module\Access\CustomRoleAccessCheck
    arguments: ['@config.factory', '@user.data']
    tags:
      - { name: access_check, applies_to: _custom_role_access_check }

```

**routing.yml**

```
custom_module.accesscheck:
  path: '/custom-module/accesscheck'
  defaults:
    _controller: '\Drupal\custom_module\Controller\CustomModuleAccessCheckController::accessCheck'
    _title: 'A Test Page for Custom Module Access Check'
  requirements:
    _custom_role_access_check: 'TRUE'
    # _permission: 'access content'

```

When I am trying to acess `/custom-module/accesscheck` I am getting the following error

> The website encountered an unexpected error. Please try again later.RuntimeException: Callable "Drupal\custom\_module\Access\CustomRoleAccessCheck::access" requires a value for the "$user" argument. in Drupal\Component\Utility\ArgumentsResolver-\>handleUnresolvedArgument() (line 142 of core\lib\Drupal\Component\Utility\ArgumentsResolver.php). Drupal\Component\Utility\ArgumentsResolver-\>getArgument(Object) (Line: 54) Drupal\Component\Utility\ArgumentsResolver-\>getArguments(Array) (Line: 157) Drupal\Core\Access\AccessManager-\>performCheck('custom\_module.custom\_role\_access\_check', Object) (Line: 135) Drupal\Core\Access\AccessManager-\>check(Object, Object, Object, 1) (Line: 112) Drupal\Core\Access\AccessManager-\>checkRequest(Object, Object, 1) (Line: 109) Drupal\Core\Routing\AccessAwareRouter-\>checkAccess(Object) (Line: 94) Drupal\Core\Routing\AccessAwareRouter-\>matchRequest(Object) (Line: 115) Symfony\Component\HttpKernel\EventListener\RouterListener-\>onKernelRequest(Object, 'kernel.request', Object) call\_user\_func(Array, Object, 'kernel.request', Object) (Line: 111) Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch('kernel.request', Object) (Line: 127) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 68) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 99) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 52) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 693) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

I also tried to construct a $accoutData object in constructor in the following way but same error occured.

```
public function __construct(ConfigFactoryInterface $config_factory, UserDataInterface $user_data, AccountInterface $account_data) {
    $this->configFactory = $config_factory;
    $this->userData = $user_data;
    $this->accountData = $account_data;
  }

```

Can anyone please suggest a proper way to do it.

**Edit :**

I am trying to get details of current user.

I know there is a way to obtain current user details by using

```
\Drupal::currentUser();

```

but it doesnt have all the user information so I am trying to do that with DI.

# Answer
> 3 votes
You need to set up your route with a {user} parameter in the path, cast to a user object.

```
example_route:
  path: '/some/path/with/a/{user}/object'
  ...
  requirements:
    _custom_access: '\Drupal\example\Controller\SomeController:SomeAccessCallback'
    # Require a numeric value for {user}
    user: \d+
  options:
    parameters:
      user:
        # Load a user entity using the {user} parameter
        type: entity:user

```

In this way, the value past in the `{user}` parameter is cast to a user entity, and passed to your access callback. The user object will also be passed to your controller callback for the route.

Edit:

Adding to your comments about the user you want being the current user, the current user (`\Drupal\Core\Session\AccountProxyInterface`) is passed to access callabacks as the first argument. You have access to all methods on that object.

If you want the current user in the controller response, you can inject the `current_user` into the class, which is an object of `\Drupal\Core\Session\AccountProxyInterface`.

# Answer
> 0 votes
The recommended way of getting the current user is

```
$account_proxy = \Drupal::currentUser();

```

This returns an account proxy, from where you can load the real user if the proxy is not sufficient

you can load the full user object with

```
$user = \Drupal\user\Entity\User::load($account_proxy->id());

```

---
Tags: 8, dependency-injection
---


# Question
Title: I broke a view and i'm not sure how to fix it
I broke a view by adding the "flagged" relationship to the view, then filtering by the flag\_id, then deciding against it and removing the relationship. The filter for flag\_id was not removed when the relationship was removed so now I get an error on that view -- "The website encountered an unexpected error. Please try again later.".

The actual logged error is

> Uncaught PHP Exception Exception: "No entity type for field flag\_id on view frontpage" at ".../core/modules/views/src/Plugin/views/HandlerBase.php line 712"

I intended on going into the database to fix this but I feel like that's the nuclear option.

# Answer
Thank you to cchen above for a partial solution to the problem. I did indeed export the .yml file from `/admin/config/development/configuration/single/export` and edited it to remove the relationship and filter sections of the view.

This worked on the live portion of the site where the view is being displayed, however, the "dirty" state of the actual view remained in the database. I continued to get the PHP exception error after clearing the cache and disabling-\>re-enabling the view. Disabling the views module and views\_ui module altogether didn't work either. The only thing that ended up working was going in the database, downloading the `.bin` file from the `data` column in the `config` table for that view and then re-uploading the `.bin` file, unchanged. It fixed the ability to actually open the view in the views\_ui module for editing.
> 1 votes

# Answer
Go to `/admin/config/development/configuration/single/export` and export the .yml file for that view, manually delete the flag\_id filter section, and reimport the .yml file under "Single Item", that should fix it.
> 6 votes

---
Tags: views, 8
---


# Question
Title: Generating URLs with fromUri and the language prefix, base vs internal
What is the recommended way to generate non-route URLs that include the language prefix?

Context: In CiviCRM, an open source third-party project that integrates with Drupal, we have a function that generates internal URLs (a wrapper over the CMS-specific function).

Since not all URLs referenced have a proper route, so far fromUri has given the best results (rather than fromRoute).

However, the URLs generated by fromUri do not seem to include the language prefix for multi-lingual configurations when using `base` as the prefix. The language prefix is included with `internal`, but if I understand correctly, `internal` should only be used for user-specified links, such as a link field.

Example on a site that has English and French, with French being the default language:

```
print \Drupal\Core\Url::fromUri("base:/admin")->toString() . "\n";
print \Drupal\Core\Url::fromUri("internal:/admin")->toString() . "\n";

```

```
$ drush scr test.php
/civicrm/dashboard?reset=1
/fr/civicrm/dashboard?reset=1

```

I also tried passing in the `$language` object, but the behaviour is the same:

```
$language = \Drupal::languageManager()->getCurrentLanguage();

print \Drupal\Core\Url::fromUri("base:/admin", [
  'language' => $language,
])->toString() . "\n";

```

Related question: Generating arbitrary internal URLs

# Answer
* Drupa8 - as a Symfony application - abstracts paths with routes. So paths may change, the route stays.
* So the cited *"The internal: scheme should be avoided except when processing actual user input that may or may not correspond to a Drupal route."* means: *If you can, use a route.*
* If you can not use routes, the right prefix for routed paths is *internal:*.
* In contrast, *base:* was introduced for use cases like *README.txt* which is unknown to the symfony router and served directly by the web server.

You can find background in these issues, and help improve the docs:
> 2 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: Filter a view by the Group ID of the current logged in user
I have been looking for an answer for 3 days with no success.

Looks like this is a common requirement among plenty of Drupal 8 projects with not a single answer accross the internet about how is possible to achieve it.

I, as user id 1, created 2 groups titled: "Basketball" and "Football" of the group type (sports) and then I added some users as members to those two groups...

So I have something similar to:

Group Title: Basketball

Group Members:

* User A (whatever role)
* User B (whatever role)
* User C (whatever role)
* User D (whatever role)

Group Title: Football

Group Members:

* User 1 (whatever role)
* User 2 (whatever role)
* User 3 (whatever role)
* User 4 (whatever role)

Now, what I really want to accomplish using views is to show a table with the names of all available members registered at the same group of the current logged user.

So if for example if **User D** is the current logged in user, I want to show him a table displaying:

* User A
* User B
* User C
* User D

without showing up the other members from other groups like user 1, user 2...

and for example if **User 2** is the current logged in user, I want to show him a table displaying:

* User 1
* User 2
* User 3
* User 4

without showing up the other members from other groups like user A, user B...

Is that possible, and how?

I have followed this issue: https://www.drupal.org/node/2793631#comment-11613765 but with no success!

And this question How do I show the members in a block, contextually filtered by the currently logged in user? with no direct solution by using only the views UI.

My aim is to create an **entity reference** views to be called from a entity reference field element inside a webform.

**UPDATE:** This issue (https://www.drupal.org/project/group/issues/2793631#comment-12808833) has a solution On how to a list of all groups in which the current logged in user is a member.

However, for my requirement I need to show a list of all members that belong to the same group of the logged in user... so I did:

* Create a page view and set the content of the view to be Group content with a url: **/my-friends**
* Add a relationship to Group (The group containing the entity.)
* Add a relationship to Group content for User (Relates to the group content entities that represent the User.)
* Add a contextual filter to Group ID and when the filter value is not available set the default value to User ID from logged in user and the relationship is set to the Group content for User.

For the preview of the view, everything looks good and I, the admin, can see my name inside the display table along with all the other member with me inside the group.

However, if i log in as any other member inside this group such as: User 2 and go to the view page and receive a table with the message: **no members available.**

# Answer
I just ran into this today. Found this article and here's the solution I did (only available recently).

I create Content view showing the Content Types that I want. I setup the Relationship to "Content group content" (checkmarking the Content Types I want). I then add a second Relationship to "Group" which is now available (based on the first relationship).

Once the relationships are done, I have access to add a new filter of Group ID. I can manually enter a group ID number and it works... but current user has not been addressed yet.

Now I install: https://www.drupal.org/project/token\_views\_filter critically, with this patch: https://www.drupal.org/project/token\_views\_filter/issues/3038695

I can go back into my Group ID filter and checkbox the "Use tokens". Now I can access information about the current user via Tokens.

I felt like I should have been able to setup a Contextual Filter for this... but the system didn't allow for it, so this was my work around.
> 0 votes

---
Tags: 8, group
---


# Question
Title: Are 'safe_value' values generated dynamically from the 'value' value?
I'm changing the content of an HTML field using `entity_metadata_wrapper`, and I see 3 values, like `value`, `format`, and `safe_value`.

My question is if I have to also edit `safe_value` or it will be generated dynamically. Thanks

PS: I edited and saved only `value` then in next load, the other were empty. I went to the node and clicked `Save` and the safe value was regenerated. Maybe I should call a hook after editing value? Currently I'm using the `check_markup` function to generate the `safe_value` from the modified `value`

# Answer
> 0 votes
Yes. `safe_value` is derived from `value`; `safe_value` contains the results of `_text_sanitize()` after it applies all the filters you've set on your text field.

It isn't set after a node save; it's set on a field load; the field module loads it via `hook_field_load()` with its `text_field_load()` invocation.

---
Tags: 7
---


title: How do I apply an OR condition?

text:
# Question
Title: How do I apply an OR condition?
I've got the below code

```
$query = \Drupal::database()
  ->select("excel", "e")->fields("e");
$group = $query->orConditionGroup()
  ->condition("grupindex", 1)
  ->condition("grupkodu", NULL);
$query->condition($group);
$excel_products = $query->execute()->fetchAll();

```

When I run `SELECT * FROM excel WHERE grupkodu = 1 OR grupkodu IS NULL`, I get 1594 records, however the above code gives only 638 records, which means only grupkodu condition is taken into account. What is the proper way to apply OR?

# Answer
After a bit of dabbling, I got the answer. `->condition("grupkodu", NULL);` is not sufficient, it needs to be `->condition("grupkodu", NULL, "IS NULL");`
> 0 votes

---
Tags: 8, database
---


# Question
Title: How to Unit Test Entity Reference Field Value
I have been tasked with writing a Unit Test for a method where I pass in a Node object, modify an Entity Reference field value, and then return a Node object.

Since this is a Unit test, I am unsure as to how to write an assertion.

Note: just included relevant code.

```
class ClassIAmTesting {
    public function populateSymbols(Node $node) {

      $node->field_symbols->appendItem(['target_id' => $symbol_id]);
      return $node;
    }
}

```

I have created a mock for the Entity Reference Field:

```
$entityReferenceMock = $this->getMockBuilder(EntityReferenceFieldItemList::class)
      ->disableOriginalConstructor()
      ->setMethods(['appendItem'])
      ->getMock();

```

I have also created a mock of the Node Object

```
$nodeMock = $this->getMockBuilder(Node::class)
      ->disableOriginalConstructor()
      ->getMock();

$nodeMock->expects($this->any)
      ->method('__get')
      ->with('field_symbols_in_this_story')
      ->willReturn($entityReferenceMock);

```

The method returns a Node object but how can I assert that the Entity Reference Field Value has changed?

**Edit:** The class with more details:

```
class ClassIAmTesting {
  public function populateSymbols(Node $node) {

    $body = $node->field_body->value;

    $dom = Html::load($body);
    $xpath = new \DOMXPath($dom);

    foreach ($xpath->query('//span[@class="tooltip"]') as $xpathNode) {

      $symbol_id = $xpathNode->getAttribute('data-symbol');

      $node->field_symbols->appendItem(['target_id' => $symbol_id]);
    }

    return $node;
  }
}

```

# Answer
This is a good example of a test that would probably be better suited as a kernel test rather than a unit test since it's dealing with the Field API which can get tricky to mock, and is probably better to test with the real thing.

To test this as a kernel test you need to ensure the following:

* Either create your field `field_symbols` directly in the test's `setUp` method or place the field config and storage YAML files in a module's `config/install` directory, and enable that module for the test.
    + You'll need to also enable the `node` module, and any other module's that your code depends on

Then, in your test you can execute the custom code and ensure the expected values are set:

```
public function testFieldSymbols() {
  $node = $this->createNode();

   // Do this, or retrieve the service if your class is a service.
   $fixture = new ClassIAmTesting();

   $fixture->populateSymbols($node);

   $this->assertEquals('expected field value', $node->field_symbols->target_id);

```
> 0 votes

---
Tags: testing
---


# Question
Title: How can I add entity base field with unique constraint if some entities already exist?
The issue is that adding a base field to a custom entity type in code would result in an issue of unique constraint violation as there does not seem to be a way to preset the value to the newly added field.

`setInitialValue()` would set the same value for all the existing entities triggering a constraint violation.

`setInitialValueFromField()` would not do any good as it would only allow fetching value from fields of same type. Otherwise it would be possible to utilise the value from an ID field and then replace those initial values with something more suitable.

Is there any meaningful way for doing that?

# Answer
> 1 votes
I think you'd need to write an update hook to first add you new base field via the `EntityDefinitionUpdateManager` (an example here since automated entity updates were removed.)

```
function example_update_8701() {
  // Add the unique constraint, etc.
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $field_storage_definition = $entity_definition_update_manager->getFieldStorageDefinition('hostname', 'comment');
  $field_storage_definition->setDefaultValueCallback(Comment::class . '::getDefaultHostname');
  $entity_definition_update_manager->updateFieldStorageDefinition($field_storage_definition);
}

```

Then in a post\_update hook, you would load each entity and populate the new field with values in whatever manner makes sense and re-save.

The two methods mentioned in your question shouldn't be called since you're updating the existing entities rather than creating new ones.

---
Tags: 8, entities
---


# Question
Title: Print module download pdf file name change characters into HTML entities
I am using print module to generate pdf using dompdf library. I am facing issue with file name which node title have ampersand(&) sign, this character is converting into `&`.

For example- If file name is **hello & drupal** then the file name become `hello & drupal - 2019-04-23`

My filename filename configuration is as attached image.

# Answer
> 1 votes
I am not a specialist of dompdf, but having used fpdf, I think it's something you do in your print template or custom module that converts the fields in dompdf format. You may need to set a php rule like this:

```
$title = mb_convert_encoding($title, 'HTML-ENTITIES', 'UTF-8');

```

Source: https://stackoverflow.com/questions/16384517/dompdf-character-encoding-utf-8

Or another one like this:

```
$titlePrintFriendly = preg_replace('#&#',chr(38),$title);

```

and then print `$titlePrintFriendly`

I used the second one in the past to trick printing some special chars.
The dompdf library should be loaded in the file you add this line.

I took the char number from https://github.com/dompdf/dompdf/blob/master/lib/fonts/Symbol.afm

# Answer
> 0 votes
A hook is available for this that is: Implements hook\_print\_pdf\_filename\_alter

```
/**
* Implements hook_print_pdf_filename_alter().
*/
function MY_MODULE_print_pdf_filename_alter(&$pdf_filename, &$path) {
  $pdf_filename = htmlspecialchars_decode($pdf_filename, ENT_NOQUOTES);
}

```

---
Tags: 7
---


# Question
Title: How can I query a database created using the previous core version from the new core version?
I want to query users, nodes etc in my D7 database that I am currently migrating to D8 to compare with the migrated content.

I want to use custom Drush commands to run some checks.

Is this possible?

# Answer
You can add external databases in your settings.php file:

```
$databases['external']['default']= array(
  'database'=>'',
  'username'=>'',
  'password'=>'',
  'prefix'=>'',
  'host'=>'',
  'port'=>'3306',
  'namespace'=>'Drupal\\Core\\Database\\Driver\\mysql',
  'driver'=>'mysql',
);

```

Then, in a custom module you can query for nodes, terms etc.

```
// Switch to external database
\Drupal\Core\Database\Database::setActiveConnection('external');

// Get a connection going
$db = \Drupal\Core\Database\Database::getConnection();

$vid = 5; // The vocabulary I want to query
$query = $db->select('taxonomy_term_data', 't');
$query
  ->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
$query
  ->addTag('translatable')
  ->addTag('taxonomy_term_access')
  ->fields('t')
  ->fields('h', array(
    'parent',
  ))
  ->condition('t.vid', $vid)
  ->orderBy('t.weight')
  ->orderBy('t.name');
$results = $query->execute()->fetchAll();

```

Switch back to your current db

```
\Drupal\Core\Database\Database::setActiveConnection();

```

Save the results to a d8 vocabulary

```
foreach($results as $result) {
  Term::create([
    'tid' => $result->tid,
    'name' => $result->name,
    'vid' => 'my_d8_vocabulary_name'
   ])->enforceIsNew()->save();
}

```
> 3 votes

---
Tags: 8, database, drush
---


# Question
Title: In the Aggregator module, limit number of items per feed
I am using the Aggregator module in Drupal 8 to combine several RSS feeds, but I would like to set a limit on the number of items that are shown from any one feed. How can I accomplish this?

# Answer
This might not be the right way to do it but I solved this by using `template_preprocess_aggregator_feed(&$variables)` and then slice the items using `array_slice()`.

My items were stored at `$variables['content']['items']` but there were two other *hashtag variables* stored in the beginning of the array so I had to add that to the total count.

```
function template_preprocess_aggregator_feed(&$variables) {
  $number_of_items = 5;
  $variables['content']['items'] = array_slice($variables['content']['items'],0,2 + $number_of_items);
}

```
> 0 votes

---
Tags: views, 8, feeds
---


# Question
Title: LDAP SSO does not authenticate user on homepage
I have configured ldap sso and it is working so far for all Url paths except for the homepage.

I get authenticated on /user/login/sso and I get authenticated on /whatsoever but I don't get authenticated on / The settings for Automated SSO is checked and my settings for Apache look like this:

```
 <Location />
            AuthType Kerberos
            KrbAuthRealms xyz
            KrbServiceName HTTP/xyz
            Krb5Keytab /usr/local/apache2/conf/conf.d/drdc.keytab
            KrbMethodNegotiate on
            KrbMethodK5Passwd off
            KrbSaveCredentials on
            require valid-user
    </Location>

```

I did check the default excluded paths in the ldap sso module, but couldn't find the path / there.
I have tried to redirect every not authenticated user to /user/login/sso but somehow this results in "to many redirects" (I want to keep /user/login/ free for loggin in as admin user without kerberos)

```
if ($event->getRequest()->getRequestUri() != '/user/login' && $this->currentUser->isAnonymous()) {
  if (preg_match('/\/comment\-([\d]+)/', $current_path)) {
    $destination = str_replace('/comment-', '#comment-', $current_path);
    user_cookie_save(['destination' => $destination]);
  }
  $url = '/user/login/sso';
  $response = new RedirectResponse($url);
  $event->setResponse($response);
  return;

```

Any idea?

# Answer
> 0 votes
This works now after unchecking this setting in the SSO-Module konfig:

---
Tags: authentication-authorization
---


# Question
Title: Show certain elements based on URL query string
I am very new to drupal and also very willing to learn. I am trying to migrate old code from another tool to drupal 8. I am working on a form, using the webform module. Can I possibly show certain webform elements based on specific URL query strings? Example: test.com?user=employee, then show TextField = employee ID test.com?user=customer, then show Textfield = Company name.

Any help would be greatly appreciated.

# Answer
> 2 votes
You can create a hidden element called 'user' which can be prepopulated via the URL, then this hidden element can be used to conditionally hide/show other elements and even the submit button.

Below is the YAML source for a proof-of-concept.

```
user:
  '#type': hidden
  '#title': user
  '#prepopulate': true
customer_name:
  '#type': textfield
  '#title': 'Customer name'
  '#states':
    visible:
      ':input[name="user"]':
        value: customer
    required:
      ':input[name="user"]':
        value: customer
employee_name:
  '#type': textfield
  '#title': 'Employee name'
  '#states':
    visible:
      ':input[name="user"]':
        value: employee
    required:
      ':input[name="user"]':
        value: employee
actions:
  '#type': webform_actions
  '#title': 'Submit button(s)'
  '#states':
    visible:
      - ':input[name="user"]':
          value: customer
      - or
      - ':input[name="user"]':
          value: employee

```

Personally, I would change the 'user' from a hidden element to a select menu, just-in-case someone navigates to the form without any query string parameters, they would still be able to select the 'type of user'.

---
Tags: 8, webforms
---


# Question
Title: Updating composer autoloader after moving modules
I have been using composer to install all Drupal modules, when I realized that they had not been installing to modules/contrib. So, I added this into my composer file:

```
"installer-paths": {
  "modules/contrib/{$name}": ["type:drupal-module"]
}

```

Then, I moved all modules to /contrib under the modules directory, and rebuilt my cache with `drush cr`. No errors.

Now I cannot reload the site, I am getting fatal errors about missing modules at their old paths.

How do I clear the autoloader so it gets updated to look in modules/contrib instead of just modules for class files?

Attached picture of the error.

I tried removing the composer.lock file and running `composer update` \- no dice.

### Update

Looks like I did everything right, I just needed to reboot the VM to clear the APC cache.

Is there a way I could do that from command line *instead* of reboot the server?

# Answer
> 1 votes
I am using this to refresh module paths. I tried all other combos with apc\_clear\_cache etc and didnt help, also nginx restart didnt help, this 2 did.

```
service php7.2-fpm restart
drush cr

```

---
Tags: 8, composer
---


# Question
Title: How do I get the list of nodes of a specific content type and their titles?
A call to field\_attach\_load should be loading node titles, but they are not being loaded. Perhaps I am missing something simple, since this my first Drupal hook.

This is the code I am using to query all the published *Event* nodes and their associated fields.

```
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'event')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

  // Attach the field values to the nodes.
  $nodes = $results['node'];

  field_attach_load('node', $nodes, FIELD_LOAD_CURRENT);
  var_dump($nodes);

```

Unfortunately, this code doesn't work for me.

How do I get the list of nodes of a specific content type and their titles?

# Answer
> 0 votes
PLease try this- This will load all published nodes of type event.

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'event')
->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
$nids = array_keys($result['node']);

foreach ($nids as $nid) {
$node = node_load($nid, NULL, TRUE);
// do something awesome
 }
}

```

# Answer
> 0 votes
From the field\_attach\_load documentation page:

> $entities: An array of entities for which to load fields, keyed by entity ID. Each entity needs to have its 'bundle', 'id' and (if applicable) 'revision' keys filled in.

While your array has the required id and is keyed by id, it is missing the bundle for those nodes (in your case 'event').

So you'd either manually add this key to every array item, or use the answer provided by 'Rahul Mishra'. While abit more hard on the database, it highly depends on your use case (row count, frequency, etc.).

# Answer
> 0 votes
`field_attach_load()` doesn't load the node title, as that isn't an entity field. It loads the *body* field and every field created with the *Field UI* module.

In a Drupal 7 test site, I created two *Article* nodes and one *Page* node. I then executed the following code.

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

if (!empty($result['nodes'])) {
  $nodes = $result['node'];
  field_attach_load('node', $nodes);
}

echo '<pre>', print_r($nodes, TRUE), '</pre>';

```

The output has been the following one.

```
Array
(
    [1] => stdClass Object
        (
            [nid] => 1
            [vid] => 1
            [type] => article
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Test 1, before test 2.
                                    [summary] =>
                                    [format] => filtered_html
                                    [safe_value] => Test 1, before test 2.
                                    [safe_summary] =>
                                )
                        )
                )
            [field_tags] => Array
                (
                )
            [field_image] => Array
                (
                )
        )
    [2] => stdClass Object
        (
            [nid] => 2
            [vid] => 2
            [type] => article
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Test 2: the test before Test 3 and Test 4.
                                    [summary] =>
                                    [format] => filtered_html
                                    [safe_value] => Test 2: the test before Test 3 and Test 4.
                                    [safe_summary] =>
                                )
                        )
                )
            [field_tags] => Array
                (
                )
            [field_image] => Array
                (
                )
        )
)

```

The code to get the node title should be similar to the following one.

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

if (!empty($result['nodes'])) {
  $nids = array_keys($result['node']);
  $nodes = node_load_multiple($nids);
}

```

In my test site, I get the following output.

```
Array
(
    [1] => stdClass Object
        (
            [vid] => 1
            [uid] => 1
            [title] => Test 1
            [log] =>
            [status] => 1
            [comment] => 2
            [promote] => 1
            [sticky] => 0
            [nid] => 1
            [type] => article
            [language] => und
            [created] => 1556873868
            [changed] => 1556873868
            [tnid] => 0
            [translate] => 0
            [revision_timestamp] => 1556873868
            [revision_uid] => 1
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Test 1, before test 2.
                                    [summary] =>
                                    [format] => filtered_html
                                    [safe_value] => Test 1, before test 2.
                                    [safe_summary] =>
                                )
                        )
                )
            [field_tags] => Array
                (
                )
            [field_image] => Array
                (
                )
            [rdf_mapping] => Array
                (
                    [field_image] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => og:image
                                    [1] => rdfs:seeAlso
                                )
                            [type] => rel
                        )
                    [field_tags] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:subject
                                )
                            [type] => rel
                        )
                    [rdftype] => Array
                        (
                            [0] => sioc:Item
                            [1] => foaf:Document
                        )
                    [title] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:title
                                )
                        )
                    [created] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:date
                                    [1] => dc:created
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                    [changed] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:modified
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                    [body] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => content:encoded
                                )
                        )
                    [uid] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:has_creator
                                )
                            [type] => rel
                        )
                    [name] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => foaf:name
                                )
                        )
                    [comment_count] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:num_replies
                                )
                            [datatype] => xsd:integer
                        )
                    [last_activity] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:last_activity_date
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                )
            [cid] => 0
            [last_comment_timestamp] => 1556873868
            [last_comment_name] =>
            [last_comment_uid] => 1
            [comment_count] => 0
            [name] => admin
            [picture] => 0
            [data] => b:0;
        )
    [2] => stdClass Object
        (
            [vid] => 2
            [uid] => 1
            [title] => Test 2
            [log] =>
            [status] => 1
            [comment] => 2
            [promote] => 1
            [sticky] => 0
            [nid] => 2
            [type] => article
            [language] => und
            [created] => 1556873931
            [changed] => 1556873931
            [tnid] => 0
            [translate] => 0
            [revision_timestamp] => 1556873931
            [revision_uid] => 1
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Test 2: the test before Test 3 and Test 4.
                                    [summary] =>
                                    [format] => filtered_html
                                    [safe_value] => Test 2: the test before Test 3 and Test 4.
                                    [safe_summary] =>
                                )
                        )
                )
            [field_tags] => Array
                (
                )
            [field_image] => Array
                (
                )
            [rdf_mapping] => Array
                (
                    [field_image] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => og:image
                                    [1] => rdfs:seeAlso
                                )
                            [type] => rel
                        )
                    [field_tags] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:subject
                                )
                            [type] => rel
                        )
                    [rdftype] => Array
                        (
                            [0] => sioc:Item
                            [1] => foaf:Document
                        )
                    [title] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:title
                                )
                        )
                    [created] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:date
                                    [1] => dc:created
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                    [changed] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => dc:modified
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                    [body] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => content:encoded
                                )
                        )
                    [uid] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:has_creator
                                )
                            [type] => rel
                        )
                    [name] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => foaf:name
                                )
                        )
                    [comment_count] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:num_replies
                                )
                            [datatype] => xsd:integer
                        )
                    [last_activity] => Array
                        (
                            [predicates] => Array
                                (
                                    [0] => sioc:last_activity_date
                                )
                            [datatype] => xsd:dateTime
                            [callback] => date_iso8601
                        )
                )
            [cid] => 0
            [last_comment_timestamp] => 1556873931
            [last_comment_name] =>
            [last_comment_uid] => 1
            [comment_count] => 0
            [name] => admin
            [picture] => 0
            [data] => b:0;
        )
)

```

As side note, for nodes, the following snippets return the same value, in `$result['node']`.

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

```

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

```

In my test site, in both the cases, `echo '<pre>', print_r($result['node'], TRUE), '</pre>';` outputs the following.

```
Array
(
    [1] => stdClass Object
        (
            [nid] => 1
            [vid] => 1
            [type] => article
        )
    [2] => stdClass Object
        (
            [nid] => 2
            [vid] => 2
            [type] => article
        )
)

```

The second snippet is always valid for any entity type (and it is then preferable); the first snippet works only for those entities for which the entity type is stored in a *type* database field.

For nodes, don't use the following code.

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

```

It would throw the following exception.

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'node.bundle' in 'where clause': SELECT node.nid AS entity\_id, node.vid AS revision\_id, node.type AS bundle, :entity\_type AS entity\_type FROM {node} node WHERE (node.bundle = :db\_condition\_placeholder\_0) AND (node.status = :db\_condition\_placeholder\_1) ; Array ( \[:db\_condition\_placeholder\_0\] =\> article \[:db\_condition\_placeholder\_1\] =\> 1 \[:entity\_type\] =\> node )

Don't even use the following code.

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('type', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

```

It would return every node (entity), independently from its content type (bundle). In my test site, the content of `$result['node']` with that code is the following.

```
Array
(
    [1] => stdClass Object
        (
            [nid] => 1
            [vid] => 1
            [type] => article
        )
    [2] => stdClass Object
        (
            [nid] => 2
            [vid] => 2
            [type] => article
        )
    [3] => stdClass Object
        (
            [nid] => 3
            [vid] => 3
            [type] => page
        )
)

```

---
Tags: entities
---


# Question
Title: Manually trigger AJAX from custom JavaScript
I'm in the process of developing a form where the user enters a UK postcode and the textfield is replaced by a select list. This all works quite nicely when using the blur event, but it is not always obvious the field has changed.

I would like to use the keyup event instead, but there is a small delay each time the key is pressed as the AJAX keeps firing, I have an existing function which is bound to the field:

```
$('#edit-postcode').bind('input', function(){
  $(this).val(function(_, v){
    return v.replace(/\s+/g, '').toUpperCase();
  });
});

```

I already have a simple regex `/(^[A-Z]{1,2}[0-9]{1,2})\s?([0-9][A-Z]{2}$)/i` to ensure it's broadly the correct format. I would like to add the validation into the previous function and if the string passes validation trigger the existing AJAX functionality.

N.B. the default Drupal autocomplete functionality works almost perfectly apart from not being able to hide the ID which relates to the postcode which is why I've resorted to this method instead.

# Answer
It turns out that it's actually much easier than I thought, by using a custom jQuery event, in my case I called in `postcodeValid`:

```
'#ajax' => [
  'callback' => [$this, 'checkPostcode'],
  'event' => 'postcodeValid',
  'wrapper' => 'postcode-container',
],

```

I changed the JavaScript function I already had to:

```
$('#edit-postcode').bind('input', function() {
  var trigger = $(this);
  $(this).val(function(_, v) {
    if (isValidPostcode(v)) {
      trigger.triggerHandler('postcodeValid');
    }
    return v.replace(/\s+/g, '').toUpperCase();
  });
});

```

The `isValidPostcode` function is a simple test against my postcode regex, thanks to Delay ajax call on textfield to allow for typing I was able to discover this.
> 4 votes

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


# Question
Title: Cannot uninstall modules due to missing table br_schedule
When I hit the Uninstall tab in the UI or try to uninstall a module with Drush I get the following errors:

Drush:

```
SQLSTATE[42S02]: Base table or view not found:
1146 Table 'DATABASENAME.br_schedule' doesn't exist

```

Drupal Log:

```
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]:
Base table or view not found:
1146 Table 'DATABASENAME.br_schedule' doesn't exist:
SELECT base_table.vid AS vid,
base_table.id AS id FROM {br_schedule}
base_table LIMIT 1 OFFSET 0; Array ( ) in
Drupal\Core\Entity\EntityStorageBase->hasData()
(line 552 of MYSITEPATH/core/lib/Drupal/Core/Entity/EntityStorageBase.php).

```

I have no idea what br\_schedule is so I don't know how to rebuild that table. I have Businesses Rules installed but I see no br\_schedule module.

# Answer
> 2 votes
Found the issue. My database updates are not happening. Ran updatedb:status with drush and I get:

```
file_entity                           8004        hook_update_n   Fix entity field mismatches on the file type field.
business_rules_schedule entity type               entity-update   The Schedule entity type needs to be installed.
file entity type                                  entity-update   The File type field needs to be updated.
node entity type                                  entity-update   The node.field_zipcode field needs to be updated.

```

"Fix entity field mismatches on the file type field." is failing so the "business\_rules\_schedule" update isn't happening.

# Answer
> 1 votes
Perhaps the easiest workaround as @kevin mentions would be to download adminer or use existing phpmyadmin if you have and create that table with no content running the following (or similar) `SQL command`

```
CREATE TABLE br_schedule (
    ID int
);

```

then try again to see if it can uninstall

**NOTE:** use with caution its not a bulletproof technique, I have used it a few times and was able to complete broken uninstalls on messed up databases but as mradcliffe mentions it might screw things up as well.

# Answer
> 1 votes
I spun up a blank D8 with Business Rules installed and exported the br\_schedule table and imported it into the effected site. Now I can uninstall modules.

# Answer
> 1 votes
Just run "drush entity-updates" to create the entities before you run drush updb.

---
Tags: database, installation
---


# Question
Title: How to theming on webform field element in single twig file (for example webform--contact-us.twig.html?
I have tried a lot to get form element in webform twig file. But variables are not coming.For example : when I'm using `{{ element.elements.name }}` in `webform--contact-us.twig.html` , nothing I'm getting. Only `{{ children }}` is giving me a whole form.

Any help will be appreciated.

# Answer
Make sure that you are pointing on the right template and try this code :

{{ form.elements.YOUR\_FIELD\_NAME }} example : {{form.elements.full\_name}

you can check this link : https://www.drupal.org/project/webform/issues/2865940
> 0 votes

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


# Question
Title: How can I get all fields and values of a node at once?
I know how to get a particular field (title field) of a node by following code:

```
$publications = \Drupal::entityManager()->getStorage('node')->load($node_id);
$title = $publications->getTitle();

```

But I need to get all fields and values in that particular node. I tried `print_r($publications)`. Is there any way to get this?

# Answer
This is how you can add all values in a custom array. The `EntityManager` class and the entity.manager service are deprecated; you should use the entity\_type.manager service instead.

```
$publications = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->load($node_id);

foreach ($publications->getFields() as $name => $field) {
  $myFields[$name] = $field->getString();
}

kint($myFields);

```

You need to improve this code because for some field types that can be different.

* For multi-value fields you use `$field->getValue()`
* For entity reference fields, `$field->entity->field_name->value`
> 5 votes

---
Tags: 8, entities, nodes
---


title: Adding a line break or space in TWIG

text:
# Question
Title: Adding a line break or space in TWIG
I'm trying to configure email confirmations that are sent out by one of our web forms. At the moment they are appearing without line breaks but I want to be able to have line breaks between certain strings.

At the moment one of our vendors hosts and designs our site, so we have have limited access to edit and configure.

Is it possible to do what I want in the body?

\**we are using Drupal 7. \**below is a screenshot of what I have the ability to edit.

# Answer
In the Twig documentation, there is an entry that can help you out: https://twig.symfony.com/doc/2.x/filters/nl2br.html

```
{{ "I like Twig.\nYou will like it too."|nl2br }}

```

will output:

```
I like Twig.<br />
You will like it too.

```

So inside a string, you could use `\n` or the function `nl2br` at the end of it.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: Running drush entity:updates claimed successful but not changing anything
I am working on a project with custom entity type. My module works fine in my local environment. But when I deployed to my staging site, things are strange.

For instance, I tried to change my entity definition and then run the drush command:

```
drush entity:updates -y

```

The command gave me positive response:

```
The following updates are pending:

dharmasun_payment entity type :
The Field 1 field needs to be installed.
The Field 2 field needs to be installed.

 // Do you wish to run all pending updates?: yes.

 Finished performing updates

```

Except the database was not changed at all. So when I re-run the command, it gives me the exact same output.

The staging site might have some different module installed than my development environment. But I cannot make breaking change on the staging platform (or my workmates would be mad).

My questions:

1. How do I begin to debug this? Is there anyway I can get better log messages with the `drush entity:update` command?
2. Or is there any alternative way to update entity definition and make changes to database?

Thanks.

# Answer
> 5 votes
For deploying entity schema updates use an update hook and the entity definition update manager. See the release note of Drupal 8.7.0 and the change record Support for automatic entity updates has been removed.

`drush entup` is moving from core to contrib: https://www.drupal.org/project/devel\_entity\_updates

> This project aims to restore this functionality as a developer-only tool. This module depends on Devel and is not meant to be enabled in production environments or relied upon in deployment workflows.

---

"Or is there any alternative way to update entity definition and make changes to database?"

Yes, there is. Don't use base fields other than for the very basic things that never change (if core makes changes necessary you'll probably find then examples how to write the update hook). Instead use configurable fields (bundle fields), so that you can deploy easily through configuration.

---
Tags: 8, entities, drush
---


# Question
Title: How do I redirect a user to the front page after logging in?
Is there a way to redirect users to the front page after they log in, without using any additional modules other than the core modules. Right now they are redirected to their profiles.

# Answer
> 6 votes
I don't believe it's possible to configure this in core, but there is a fairly well established and lightweight module that can do this for you - redirect\_after\_login - https://www.drupal.org/project/redirect\_after\_login

# Answer
> 6 votes
The query parameter `destination` can be used to redirect any form submission, including the login form. Config your web server/Drupal to always add the query parameter such that http://example.com/user/login?destination=/ is the only URL to login. Upon login submission, users will be redirected to http://example.com/.

---
Tags: 8, users, redirection
---


# Question
Title: How can I have a nested slideshow with paragraphs and views?
**Initial situation**

I have a node type with a paragraph field. Each paragraph of the paragraph field is rendered among themselves.

**What I want to achieve**

* The *paragraph field* inside the node should render all the paragraphs as a slick slideshow.
* The *node containing the paragraph field and all the paragraphs* should also be part of a (second) slick slideshow (via a view filtered by the content type).

In short, the user will have finally a slideshow (with the single paragraphs) nested in a second slideshow (with the nodes).

**Problems**

The module slick views allows it to display the nodes of the node type as a slider. *That's fine to realize the node slider.*

The module slick paragraph only allows to create slideshows as a paragraph type, but not rendering the paragraphs of a node themselves as part of a slideshow. They are still rendered among themselves inside the "node slider".

So here i struggle a bit - any idea?

Thanks in advance, Phil

# Answer
**Thank you all very much** for all your answers and hints.

The following steps worked for me now:

**How to create the "inner" slider:**

1. Install and activate the module Slick Paragraphs
2. In my node type I created a new display mode
3. Inside the display mode my paragraphs field uses "Slick Paragraphs Vanilla" as its formatter. In the formatter you can adjust some settings. I used in this use case "default" everywhere.
4. Now every paragraph in the node is rendered as a slick slide slider.

**How to create the "outer" slider**

1. Install and activate the module Slick Views
2. Create a new view (in my case a page) and use "Slick Carousel" as format. I used here display "content" and used my display mode I created earlier.
3. Set your views filters as you need (in my case the content type of the node) additionally.

If you call the url of the view page, Drupal renders a flexible slideshow in another very flexible slideshow.
> 1 votes

# Answer
You could achieve this with more control by overriding node/field/paragraph templates in your theme to get the required markup, then creates the Slick sliders via custom JS code.

If you never worked with templates, you should start here https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates
> 1 votes

# Answer
In addition to Cedric\_a answer, you can also make a slick view of paragraphs instead of nodes (when you create your view at first, instead of choosing show: Content, choose show:Paragraphs) and filter it with paragraph type.
If it is not enough because you use a paragraph type on several entities, you can add a relationship "Content using field\_you\_field\_name" + use a simple filter on the content ID using this relationship.
Paragraphs are entities used by other entities (nodes) using a field bridge. A field bridge means relationship in views. You can generally bridge entities in views thanks to relationships.
> 1 votes

---
Tags: 8, paragraphs
---


# Question
Title: Error opening socket ssl://api.nodesquirrel.com:443
I am using Backup and Migrate on D7. I am unable to backup to NodeSquirrel due to the following error:

```
TYPE    backup_migrate

The NodeSquirrel server returned the following error: Error opening socket ssl://api.nodesquirrel.com:443

Could not run backup because the file could not be saved to the destination.

```

Please see below a screenshot of the error-

*Apparently, it is a bug with the `Backup and Migrate` module as mentioned in the answer.*

# Answer
> 1 votes
https://www.drupal.org/project/backup\_migrate/issues/3037038

> Update April 10: Workaround
>
> Per e5sego, the "nodesquirrel\_default\_endpoint\_urls" variable can be changed to "74.121.199.90/services/xmlrpc" to avoid the current DNS problems we're seeing, e.g. drush vset nodesquirrel\_default\_endpoint\_urls "74.121.199.90/services/xmlrpc" Just make sure to delete the variable once the DNS problems are resolved (drush vdel nodesquirrel\_default\_endpoint\_urls).

---
Tags: 7, migrations, backups
---


# Question
Title: How to reference taxonomy used by other content type?
I have two content types: **Content A** and **Content B**

Fields in **Content A**: Title, Location, Body

Fields in **Content B**: Title, Type, Location, Body

**Location** is a vocabulary (Au, Uk, Us, Ca, etc)

Type is an *entity reference* of Content A inside Content B node.

Content A has a node with information in order: *News X, Ca, This is the body of News X*

Content B has a node with information in order: *John Doe, Content A, ????, This is about John Doe*

In this question mark, I want to include **Location** but only that which is selected in that node of **Content A**.

Location can be multiple, that is, if Content A node has "location": Ca, Uk then Content B node referenced to Content A will only enlist Ca, Uk out of all other terms in that vocabulary.

---

I have looked into google, found nothing. Please help.

# Answer
> 2 votes
# For simple displaying of taxonomy term

Assuming your are using entityreference for Drupal 7 the module provides out of the box a field formatter that allows you to display the **Rendered entity** with a specific **view mode**

Thus you can display the referenced entity with the taxonomy term included.

Go to the **manage display** of your **Content B** and change the format to *Rendered entity* and choose *teaser* for the *view mode*

Go to the **manage display** of your **Content A** and modify the **teaser** view mode and add the taxonomy term field to be displayed.

# For more advanced use cases

You might want to try any combination of the following

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


# Question
Title: Rewriting image output in views: how to provide replacement pattern inside twig tag?
In views I want to rewrite output of image field by using twig function `drupal_image` (see module Twig Tweak). When I provide the image path directly, this code works:

```
{{ drupal_image('public://myimage.jpg' , image_responsive_style, responsive=true) }}

```

But I can not manage to provide image path by a variable, like this pseudocode:

```
{{ drupal_image('{{ uri }}' , image_responsive_style, responsive=true) }}

```

The problem seems to be how to provide the variable `{{ uri }}` properly inside the surrounding twig tag.

# Answer
> 4 votes
1. Remove quotes.
2. Remove wiggly brackets around.
3. Surround `image_responsive_style` by quote.
4. `responsive=true` Should passed as object:

```

    {{ drupal_image(uri , 'image_responsive_style', {responsive: true}) }}

```

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