# Question
Title: How to alternate image on left/right using "Views Parity Row" module
This great tutorial explains everything except the CSS work. http://gogrow.org/tutorials/views\_parity\_row

I need to add CSS class to each row so I can set left/right alignment accordingly in css style. Views settings allows me to set the ccs class in `Page: Style options` but this one is always the same for each row. I need the class name also to alternate.

I need something like dynamically use the `View Mode` as css class name.

Current output: `<div class="views-row">` Desired output: `<div class="views-row left">` and `<div class="views-row right">`

Or am I missing something and the CSS work is done in a complete different way?

# Answer
> 1 votes
You can just set all view-rows to be left and then do like this in your css:

```
.views-row:nth-child(2) {
   float: right;
}

```

UPDATE:

```
.views-row:nth-child(odd) {
  float: left;
}
 .views-row:nth-child(even) {
  float: right;
}

```

As @No Sssweat pointed out you can use nth-child odd and even to style every second element. You don’t need to style on the parent just use above code.

I actually wrote something wrong you can add nth-child on the .views-row elements

---
Tags: views
---


title: Views table columns not sortable

text:
# Question
Title: Views table columns not sortable
Standard drupal field types like Strings, Numbers, Dates and Taxonomies can be defined as **Sortable** in Views with `Format: Table`.

But more complex fields like Hierachical Taxonomies and Paragraphs or paragraphs don't have a checkbox to make them Sortable.

Is there any way to make them sortable using Views interface or do I have to make a custom plugin Tablesort with EntityQuery?

# Answer
Categories or Paragraphs are just references when you create a node view. Thus when you use them in the fields (as output) they are not sortable but you can add a relationship to them and then their individual fields (like name, id etc) become sortable

Here is an example with tags (on article content type)

Added term relationship **Taxonomy terms on node** and then **tag id** and **tag name** are **sortable** (among others)

**ΝΟΤΕ:** you will most certainly end up with duplicate results in the view. For this you can use aggregation, "Group results together" with group column "entity id".
> 4 votes

---
Tags: views, 8
---


# Question
Title: How can a view page work with multiple word term name
I have user views page with path /members/%. (url as members/term-name).It shows if I use CONTEXTUAL FILTERS with term id but I need url with term name.
Anyway , go back to story: academician,math, math teacher, math students are terms. It shows all members if path is members/math or members/academician.
No problem with one word term name. But it doesn't show any member if url is members/math-teacher or members/math-student.
So it works with math terms but not with math teacher.
What am I missing ?

# Answer
> 0 votes
In views, the multi-word term is a well-known active issue

**Solution 1:**
You can use pathauto module to set up automatic aliases for your taxonomy terms.
**Solution 2:**
From views:

* Choose "Specify validation criteria" in settings of `Taxonomy Term` Contextual filter.
* Then Choose `Taxonomy Term` in **Validator** field.
* Choose your **Vocabulary**.
* Choose `Term name converted to term ID` in `Filter Value Type` Field.
*Please see attached screenshots for solution 2:*
---

---

**Solution 3:** In views, you can create path aliases for term IDs by using view\_alias module.

# Answer
> 0 votes
Thanks johirpro,
Patch at your first link worked for me with my settings(below). Many many thanks

Contextual Filters(with relationship)
Provide default value-Term id from URL
Specify validation criteria-Basic Validation+Show Page not found.

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


# Question
Title: Getting redirect to phantom page /user/register/thankyou
In Drupal 8, I created a page with the path alias `/user/register/thankyou` to redirect users to after registration. Later, I changed the url of this page to simply be `/register/user/thankyou`. I have the **Redirect** module enabled, so I deleted the redirect from `/user/register/thankyou` to `/thankyou/registration`.

However, now, when I go to `/user/register`, I am automatically redirected to `/user/register/thankyou`, which results in a "page not found" error.

So, somehow, there is still a "ghost" redirect in my system, although the redirect module page shows that there are no redirects on the site, and I double-checked the page with the alias `/thankyou/registration`, which has the correct alias.

I uninstalled the redirect module but the redirect persists.

The redirect occurs when I type the URL to the user register page manually (`www.example.com/user/register`) and when I click the "register account" link.

I opened up the database in MySQL workbench and I see nothing strange in the `router` table or the `url_alias` table; my alias to `/register/user/thankyou` exists but I cannot find the `/user/register/thankyou` alias anywhere (although this is where `/user/register` is being redirected).

How do I fix this redirect error?

I tried three different browsers and cloned the site from production to my local environment; in all cases, I have this issue.

# Answer
> 0 votes
Stupid mistake... it turns out I had a redirect in a custom module that I had been using for testing.

`grep` the custom modules directory for `user/register` saved the day...

---
Tags: uri, redirection
---


# Question
Title: Print custom field in user edit form in block
Following code prints user edit form in block:

```
function notifikacie_custom_block_info() {
 $blocks['user_profile'] = array(
   'info' => t('User profile edit'),
   'cache' => DRUPAL_NO_CACHE,
 );

 return $blocks;
}

function notifikacie_custom_block_view($delta = '') {
  $block = array();

      global $user;
      module_load_include('inc', 'user', 'user.pages');
      $block['subject'] = t('Fill your profile');
      $block['content'] = drupal_get_form('user_profile_form', $user);

  return $block;
}

```

But it does not print custom fields created in admin/config/people/accounts/fields. How do I print those custom fields?

# Answer
I've just run your code and it works fine. Maybe it is permission related problem.

```
<?php
function user_profile_block_info() {
 $blocks['user_profile'] = array(
   'info' => t('User profile edit'),
   'cache' => DRUPAL_NO_CACHE,
 );

 return $blocks;
}

function user_profile_block_view($delta = '') {
  $block = array();

      global $user;
      module_load_include('inc', 'user', 'user.pages');
      $block['subject'] = t('Fill your profile');
      $block['content'] = drupal_get_form('user_profile_form', $user);

  return $block;
}

```

Output/result:
*Here **Birth Date** is custom field, created form* `admin/config/people/accounts/fields`.
> 0 votes

---
Tags: users, blocks, hooks
---


title: Views slideshow not displaying images

text:
# Question
Title: Views slideshow not displaying images
I created a content type with title, body, and slide (image) fields. I created a view block (format: bootstrap carousel, fields: slide).

After I place the block in a region, I see the slideshow block, but I don't see the image. I only see blank slideshow on my site and views.

>

How do I display images in the slideshow?

Views \> settings next to format \> selected image field to display.

>

# Answer
**Views** \> Select **Settings** next to format \> selected Slide(image) in Image drop down list. I am not sure this is a best solution. At least I can see the image now.

field to display.
> 0 votes

---
Tags: 8, views
---


title: How can I create Change Password block?

text:
# Question
Title: How can I create Change Password block?
We can create **reset password** block by `\Drupal::formBuilder()->getForm('Drupal\user\Form\UserPasswordForm')` in d8, but **change password** block `\Drupal::formBuilder()->getForm('Drupal\user\Form\UserPasswordResetForm')` didn't work for me. This is my code:

```
public function build(Request $request) {
  $session = $request -> getSession();
  $session->set('pass_reset_hash', $hash);
  $session->set('pass_reset_timeout', $timestamp);
  $user = \Drupal::currentUser();
  $expiration_date = $user->getLastLoginTime();

  $myblock = \Drupal::formBuilder()->getForm('Drupal\user\Form\UserPasswordResetForm::class', $user, $expiration_date, $timestamp, $hash);
  return array(
    '#type' => 'markup',
    '#markup' => drupal_render($myblock),
  );
}

```

# Answer
> 1 votes
First of all try to take a look at the buildForm method in the `UserPasswordResetForm` class, it takes some parameters.

So you must call getForm like this:

```
\Drupal::formBuilder()->getForm('Drupal\user\Form\UserPasswordResetForm::class', $user, $expiration_date, $timestamp, $hash);

```

This is the function docs,

> $user = User requesting reset.
>
> $expiration\_date = Formatted expiration date for the login link, or NULL if the link does not expire.
>
> $timestamp = The current timestamp.
>
> $hash = Login link hash.

So when those parameters are added the form should render perfectly.

---
Tags: views, 8, users, blocks
---


# Question
Title: webform_submission_ID post blocked by CAPTCHA module
After solving reCAPTCHA and submitting the form I am getting error:
*The answer you entered for the CAPTCHA was not correct.*

Recent log message says:

```
webform_submission_ID post blocked by CAPTCHA module: challenge reCAPTCHA (by module recaptcha), user answered "Google no captcha", but the solution was "1".

```

I couldn't find any working solution. I already tried to update reCAPTCHA and Captcha modules to newer version. Also tried to update Drupal core.

Any suggestions?

I am using Drupal core 8.5.8 and reCaptcha 8.x-2.3

# Answer
Finally I found a solution. Webform configuration files were imported after the Webform module has been updated and it caused the older configuration to be out-of-sync. As a result unexpected behaviors and errors were showing.

Clicking the 'Repair Configuration' button under '/admin/structure/webform/config/advanced' helped.
> 0 votes

---
Tags: webforms, captcha
---


# Question
Title: How to translate Groups in a multilingual site?
I have created a new grouptype and added some fields to have a "site". And then created a new group with this grouptype. I edited the overview site with some information. Now I would like to translate the site, because I have an multilingual site. Unfortunately I can't find out how to do so.

Is it possible to translate a groupsite on a multilingual site? Or do I have to create two groups for that?

# Answer
I could translate the group node by enable "group" and "group content" in /admin/config/regional/content-language
> 0 votes

# Answer
Your question appears to be somehow related to this issue, which is closed and fixed. That issue contains an image which looks like so:

So check if the version of the Group module that you're using, includes the patch included in that issue.

If you don't have it included, it's probably why you don't have a "group content type" translation option in `/admin/config/regional/config-translation`. And if you do have it included, go checkout that translation option to see what happens.
> 2 votes

---
Tags: 8, i18n-l10n, multi-sites, group
---


title: Node Load performance

text:
# Question
Title: Node Load performance
I have a small question.

If I use `Node::Load` on the route of the same node for example: I go to `site.com/node/125` and in preprocess I use `Node::Load(125)`, would Drupal load that node all over again? Or is there some part in the code where it loads it without any performance impact?

# Answer
Entities are statically cached in memory, so there is no performance impact if you load the same entity multiple times within the same request.
> 4 votes

# Answer
Actually there is no reason to load the node on all node pages.

When using `MYTHEME_preprocess_node` you have `$variable['node']` that is the loaded node.
> 3 votes

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


title: Making landing pages with taxonomy

text:
# Question
Title: Making landing pages with taxonomy
I'm trying to make about 100 landing pages using taxonomy.

I'm trying to stick to Drupal 8 core features as much as possible.

I created two taxonomy vocabularies, **Places** and **Main keyword**.

Now, what I want to do is create landing pages that consist of:

**1 place + 1 keyword**

**Places**

* London
* Paris
* Berlin

**Main keywords**

* Apples
* Oranges

Combinations (each of these is a landing page using tokens from both keywords in Views blocks \[perhaps attached by Layout Builder\] to make the page)

* London + Apples
* London + Oranges
* Paris + Apples
* Paris + Oranges
* etc.

What module(s) should I use to link taxonomy terms from two different vocabularies together like this (preferably, in an automatic way so the relevant pages are automatically generated when I add a new term in either vocabulary)?

I have been experimenting with Views and Layout Builder but I haven't come up with a solution yet.

**What I tried**

* I used the Views "taxonomy term page" view to override the taxonomy term pages; this lets me do what I want for a single term in a single vocabulary, but I want to use two terms in combination from two different categories.

# Answer
> 0 votes
**How I'm doing this now**

1. Create a new content type, **Landing Page**.
2. Add two fields, an entity reference to *Places* and an entity reference to *Main keywords*.
3. Use Views blocks/Layout Builder to rewrite the HTML of the content type to show the text you want with the relevant keywords substituted in.
4. When you add a new term to either vocabulary, you have to create all the possible combinations manually by adding **Landing Page** content.

# Answer
> 0 votes
Another option is to use a custom view page that allows to filter with any taxonomy terms combined with depth.

Then create a path alias for each filtered page to hide the arguments.

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


title: Get delta of parent form field widget

text:
# Question
Title: Get delta of parent form field widget
I've got some form input fields in a paragraph whose visibility need to be dynamically toggled by the value of a another field. This can be done with the states API and the HOOK\_field\_widget\_WIDGETTYPE\_form\_alter hook.

My problem is that the paragraph is nested inside another paragraph, and I don't know how to get the delta of the parent widget, in order to build my selector name for the states API.

My node has a paragraph `field_pagebuilder`, which contains another paragraph `field_row`. All toggleable/dependant fields are inside the same sub-paragraph. This is the code I've got so far:

```
function wt_pricetable_field_widget_paragraphs_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if ($element['#paragraph_type'] == 'pricetable_frontend') {

    $deltaSelf = $context['delta'];
    //////////////////////////////
    $deltaParent = 0; // FIXME: how to I get this?
    //////////////////////////////
    $element['subform']['field_pt_showroom']['#states'] = [
      'visible' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'single_room'],
        ],
      ],
      'required' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'single_room'],
        ],
      ],
    ];
    $element['subform']['field_pt_hiderooms']['#states'] = [
      'visible' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
      'required' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
    ];
    $element['subform']['field_bem_modifier']['#states'] = [
      'visible' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
      'required' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
    ];
  }
}

```

My problem is the `$deltaParent` \- how can I retrive it?

# Answer
Found it in `$context['form']['#parents']`. This is an array that contains the keys of the parent widget. In my case it looked like

```
[ 0 => 'field_pagebuilder',
  1 => ___PARENT_INDEX___,
  2 => 'subform',
]

```

which allowed me to generate my CSS selector for the states API:

`$deltaParent = $context['form']['#parents'][1];`
> 2 votes

---
Tags: 8, forms
---


# Question
Title: getting error when doing the composer install
Drupal version was 8.6.2 and moved to new server. When doing the core update , getting an error like below.

```
 Problem 1
- remove drupal/drupal No version set (parsed as 1.0.0)|remove drupal/core 8.6.3
- don't install drupal/core 8.6.2|remove drupal/drupal No version set (parsed as 1.0.0)
- don't install drupal/core 8.6.3|remove drupal/drupal No version set (parsed as 1.0.0)
- don't install drupal/core 8.6.x-dev|remove drupal/drupal No version set (parsed as 1.0.0)
- don't install drupal/core 8.7.x-dev|remove drupal/drupal No version set (parsed as 1.0.0)
- don't install drupal/core 8.6.3|remove drupal/drupal No version set (parsed as 1.0.0)
- Installation request for drupal/drupal No version set (parsed as 1.0.0) -> satisfiable by drupal/drupal[No version set (parsed as 1.0.0)].
- Installation request for drupal/core ^8.6.2 -> satisfiable by drupal/core[8.6.2, 8.6.3, 8.6.x-dev, 8.7.x-dev]

```

i have tried the composer install by removing composer.lock, vendor and core. Still getting same error.

Updated with my composer.json

```
{
"name": "drupal/drupal",
"description": "Drupal is an open source content management platform powering millions of websites and applications.",
"type": "project",
"license": "GPL-2.0+",
"require": {
    "composer/installers": "^1.0.24",
    "wikimedia/composer-merge-plugin": "^1.4",
    "drupal/core": "^8.6.2",
    "drush/drush": "^9.2",
    "drupal/s3fs": "^3.0",
    "drupal/csv_serialization": "^1.4"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
    "preferred-install": "dist",
    "autoloader-suffix": "Drupal8"
},
"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php.",
        "This file specifies the packages.drupal.org repository.",
        "You can read more about this composer repository at:",
        "https://www.drupal.org/node/2718229"
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    },
    "installer-paths": {
        "core": ["type:drupal-core"],
        "modules/contrib/{$name}": ["type:drupal-module"],
        "profiles/contrib/{$name}": ["type:drupal-profile"],
        "themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"],
        "modules/custom/{$name}": ["type:drupal-custom-module"],
        "themes/custom/{$name}": ["type:drupal-custom-theme"]
    }
},
"autoload": {
    "psr-4": {
        "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
    }
},
"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": [
      "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
    ],
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
]

```

}

# Answer
> 0 votes
I think the composer error messages are really opaque: Took me the whole day to figure this one out. And stil am not sure how to debug the composer related problems (and I have read all the drupal documentation, lots of composer documentation, so maybe I am just losing IQ points lately...)

**Error 1: composer install**

I had the same problem on *composer install* (Clive removed my earlier remark) and thought the culprit was

*remove drupal/drupal No version set (parsed as 1.0.0)*

Couldn't figure out why that would happen: Added all modules neatly with require bladiebla and had no problem updating core to 8.6.4

Site was running smoothly

**Error 2: install module**

Trying to install backup\_migrate resulted in the error

*The package is not available in a stable-enough version according to your minimum-stability setting*

Which I also did not understand because my minimum stability was *dev* and the backup\_migrate version was a stable one

Trying different things to find out where the problem originates did not bring any solution

*composer install* *composer update* *composer diagnose* *composer why* *composer give me a break* *etc*

Is supposed that one of the modules I required conflicted with another one, but how to find out which one..... (any hints on how to debug these composer message are welcome)

**SOLUTION (in my case)**

In the end I simply did this

*starting point*

drupal 8.6.4

minimum stability dev

php 7.0.3

*actions*

1. remove core, modules/contrib, vendor, composer.lock
2. in composer.json:

2.1 start with (in my case)

```
    "drupal/core": "~8.6.0",
    "composer/installers": "^1.0.24",
    "wikimedia/composer-merge-plugin": "^1.4",

```

2.2 in the following require part require all advised highest version for all modules you use (so go to the drupal mordules site en copy the advised composer require statements)

```
   "drush/drush": "~9",
    "drupal/backup_migrate": " ^4.0",
    "drupal/backup_db": " ^1.1",
    "drupal/draggableviews": " ^1.0",
    "drupal/pathauto": " ^1.0",
    "drupal/token": " ^1.0",
    "drupal/anonymous_redirect": "^2.2",
    "drupal/ctools": " ^3.0",
    "drupal/calendar": " ^1.0",
    "drupal/geolocation": "^2.0",
    "drupal/views_taxonomy_term_name_depth": "6.x-dev",
    "drupal/views_templates": "^1.0",
    "drupal/paragraphs": " ^1.5",
    "drupal/devel": "^1.2",
    "drupal/webform": " ^5.0",
    "drupal/social_login": " ^2.83",
    "drupal/disqus": " ^1.0",
    "drupal/address": " ^1.4",
    "drupal/leaflet": " ^1.0",
    "drupal/geofield": "^1.0",
    "drupal/geophp": "^1.0",
    "drupal/geocoder": "^2.0",
    "drupal/geofield_map": "^2.20",
    "drupal/google_analytics": "^3.0",
    "drupal/video_embed_field": "^2.0",
    "drupal/better_exposed_filters": "^3.0",
    "drupal/addtoany": "^1.10",
    "drupal/typed_data": "^1.0",
    "drupal/rules": "^3.0",
    "drupal/honeypot": "^1.29",
    "drupal/field_group": " ^3.0"

```
3. run composer install
4. go to your site and run www.domain.ext/update.php

That resolved my problem

# Answer
> 0 votes
Check the composer.json in drupal core, I think you have an old composer.json setting, here composer.json drupal 8.6.7 :

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "require": {
        "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "^1.4"
    },
    "replace": {
        "drupal/core": "^8.6"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "drupal-phpunit-upgrade-check": "Drupal\\Core\\Composer\\Composer::upgradePHPUnit",
        "drupal-phpunit-upgrade": "@composer update phpunit/phpunit phpspec/prophecy symfony/yaml --with-dependencies --no-progress",
        "phpcs": "phpcs --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --",
        "phpcbf": "phpcbf --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ]
}

```

---
Tags: 8
---


# Question
Title: Dynamic language negotiation by multiple top level domains
I am porting www.example.com, the German version is at de.example.com, the French is at fr.example.com and so forth. I could enter these domains in `admin/config/regional/language/detection/url` but I would like them to be subdomains: if one visits www.example.test then (www,de,fr).example.test should work, and if one visits www.example.local then (www,de,fr).example.local should be the translated domains and so forth. It seems I need to make the results of `$config = $this->config->get('language.negotiation')->get('url');` dynamic. I am at a complete loss at how to implement this:

1. I could write an entirely new plugin based on `LanguageNegotiationUrl`. If I started with a copy of it, I could drop `processInbound` and half of `getLangcode` but the rest would need to stay -- and given how little change needs to happen, that's a lot of code to keep in sync with core.
2. I could patch `LanguageNegotiationUrl` factoring out the four `$config['domains']` interactions into a method and then extend accordingly. Much less maintenance pain than the previous one but at the same time, it's a core patch. Of course, composer-patch applies them after updates but still, a core patch for this?
3. I could write a config override which overrides `language.negotiation` but it seems the overrider doesn't get the data loaded. So I'd need to get the domain map from somewhere else, for example by re-reading it from the config storage. That's really, really wasteful.
4. I could write a "super saiyan config override" by decorating the config factory service so when the `language.negotiation` is `get()` then do something with it, like put the dynamic overrides in `setModuleOverride`. OK, that's not a lot of code, great, the proxy script will write most of it, even better, but now *all config calls* are a hair more complex and a hair slower.

Any clean ideas I missed...?

# Answer
> 1 votes
This sounds to me like the perfect use case for environment specific configuration. No runtime changes required. Just like you would swap the email addresses in your environments that are used to send emails and would swap the API keys in dev/test environments, you would swap this configuration there as well. You could use something like https://www.drupal.org/project/config\_split for example.

# Answer
> 1 votes
1. `config_split` I have multple problems with: one is philosophical, having multiple branches of config sounds like a good way to complicate deployments where you need to make sure the right config gets to live. The other is practical, the team is big and fluid and everyone needing to configure the domains to their preference is not ideal.
2. If I resolve to not touch the actual negotiating code (which would be very highly desirable) then the path processor is a no-go because `LanguageNegotiationUrl::getLangcode` calls `$request->getHost()`. And `Request::getHost` is not a simple getter of a property (tellingly there's no `setHost`) rather it calculates the host every time from various headers so this manipulation would need to replicate and fight this logic unsetting this , setting that... This is another no-go.

I ended with writing a class proxying `ConfigFactory` and a service provider injecting this right into the negotiatior service:

```
public function alter(ContainerBuilder $container) {
  if ($container->hasDefinition('language_negotiator') && $_ENV['SMARTSHEET_SITE_ENVIRONMENT '] !== 'prod)') {
    $definition = $container->getDefinition('language_negotiator');
    if ($definition->getClass() === 'Drupal\language\LanguageNegotiator') {
      $definition->replaceArgument(2, new Reference('sd8.language_config_factory'));
    }
  }
}

```

and then the SubdomainConfigFactory does this:

```
public function get($name) {
  $config = $this->configFactory->get($name);
  if ($name === 'language.negotiation') {
    $domainSuffix = preg_replace('/^[^.]+/', '', $this->requestStack->getCurrentRequest()->getHost());
    $override['url']['domains'] = [];
    foreach ($config->get('url.domains') as $langcode => $domain) {
      $override['url']['domains'][$langcode] = strtok($domain, '.') . $domainSuffix;
    }
    $config->setModuleOverride($override);
  }
  return $config;
}

```

This is very far from ideal and I feel there must be a nicer way to work with dynamic config and I will post if I find out how.

# Answer
> 1 votes
This can simply be overridden from your `settings.php` or `settings.local.php`.

```
$config['language.negotiation']['url']['domains']['en'] = 'www.example.test';
$config['language.negotiation']['url']['domains']['de'] = 'de.example.test';
$config['language.negotiation']['url']['domains']['fr'] = 'fr.example.test';

```

Which means, that you need to set them manually in every environment once. Each of your coworkers needs to adjust their `settings.php` or `settings.local.php` according their needs.

# Answer
> 0 votes
You could add a custom path processor. To handle the domain path part before language negotiation you need to choose a priority inbound \>300 and outbound \<100, because these are the priorities of the language path processor:

```
services:
  path_processor_custom:
    class: Drupal\mymodule\PathProcessor\PathProcessorCustom
    tags:
      - { name: path_processor_inbound, priority: 310 }
      - { name: path_processor_outbound, priority: 90 }
    arguments: ['@config.factory']

```

For more information see Do new routes in Drupal 8 \*require\* a static first portion?

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


# Question
Title: Batch API to process millions of records
I need to run Batch API on a huge dataset. Specifically I have a custom table with a lot of rows which I need to iterate over. The batch process works fine using small numbers. When using the full set I run out of memory before it even starts because I am loading a very large array of IDs to pass in to the batch function. Think of a 5 million item array. What is a good way to handle this? Break it into smaller chunks somehow to then pass in to Batch API? Increase the memory limit to an (ungodly) amount?

# Answer
Add a column for 'processed'. Each time you run the batch process select rows with a limit of 100 unprocessed rows for you batch process and then mark each row as processed.

You could run this on cron or something or run a nested batch.
> 1 votes

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


# Question
Title: How can I process a node form from a custom submit handler?
I have a use case where I have a custom submit button on a node edit form that will take the user off to another page to do some other editing.

If the user has made some changes to the node, such as changed the title, **I need to save the current node** before redirecting them off to the new page (along with some other generated ID's).

For the life of me, I cant seem to see how I can save the changes to the node in my custom submit handler.
I have tried using `$formState->prepareCallback('::submitform())` but that doesn't seem to do what I expected of processing the form.

Anyone done this before or got any good ideas?

# Answer
Typically, I found the answer 10 minutes after posting!

For anyone else, in your custom submit handler get the form object from the form state.

```
$formObj = $formState->getFormObject();

```

You can then call `submitForm()` on the form object and pass the form and form state variables.

```
$formObj->submitForm($form, $formState);

```

Then finally just simply trigger the `save()` function on the object.

```
$formObj->save($form, $formState);

```
> 2 votes

---
Tags: 8, nodes, forms
---


# Question
Title: Add programmatically exposed filter to view without removing the existing ones
I want to add an exposed filter to a view which contains already exposed filters but without altering them. When I add the following code it messes up the exposed filters from the view and only the programmatically coded exposed filter works correctly.

I use the following code:

```
function music_m_views_pre_view(&$view, &$display_id = null , &$args = null)
{
$filter = $view->display['default']->handler->options['filters'];
$current_latter = arg(1);
$filter['field_last_name_value']['value'] = $current_latter;

$view->display_handler->override_option('filters', $filter);
}

```

# Answer
The hook function used was wrong. I had to use hook\_views\_pre\_build(&$view) so I have now the following (and the other exposed filters don't get messed up):

```
 function music_m_views_pre_build(&$view) {

$view_filters = $view->display['default']->handler->options['filters'];

 $current_latter = arg(1);

 if($current_latter)
 {
    $view_filters['title']['value'] = $current_latter;

 }
$view->display[$view->current_display]->handler->handlers['filter']['title']->value = $current_latter;

```

}
> 0 votes

---
Tags: 7, views
---


title: How to add print stylesheets

text:
# Question
Title: How to add print stylesheets
How do I add a print stylesheet in Drupal 8? Here is what my libraries file looks like in my theme...

```
global-styling:
  version: 8.0
  css:
    base:
      css/style.css: {}
    theme:
      css/print.css: { media: print }

```

Does that look correct? If it is correct, should I also include print media queries in the print.css file? Or do I not need those media queries because of the "media: print" annotation in my libraries file?

Since I can't inspect the print-preview source, how do I know what classes to use in my print CSS?

(And is there anything else in Drupal 8 that influences the print styles? I am working on a site I did not build, and it has print styles, but I don't know where they are coming from. I thought maybe they were coming from the base theme, but I removed the base theme from my theme's info file and I continue to see styled output when I print-preview the page. The styled output is bad, and needs to be corrected, but I don't know where it's coming from.)

# Answer
> If it is correct, should I also include print media queries in the print.css file?

It's correct, and there's no need for media queries in the CSS file.

(Separately, I'm still trying to determine what else is supplying the print styles in my site, aside from the ones I'm adding intentionally. But I can confirm that the above annotation example works.)
> 4 votes

---
Tags: 8
---


# Question
Title: How do I integrate a custom filter inside a view
I am using entity browser to view my uploaded images. And now I want to integrate a new filter to the view. My objective is to filter the images from the URI path. Currently view has a field in Filter Criteria section in the view with a textfield to enter a part of a URI and filter. But I need to filter the images with a custom dropdown which has only specific values in the URI.

Lets say my URIs looks as below.

```
s3://2019-01/image-set-one/image.jpg
s3://2019-01/image-set-two/image.jpg

```

I need to integrate a dropdown to the filter criteria of the view with elements `image-set-one` and `image-set-two` which will filter the images accordingly. I am using entity browser, so I need to add that field inside the view instead of getting the results and filter after.

This is a screen shot of the view that I am using.

Below is a preview of my entity browser that I am using with the above view.

# Answer
> 0 votes
I found a solution for above. I can add a field in the filter criteria selecting the URI. And expose that filter to the user with a grouped filter. In the grouped filter I can define my own keys and parameters with an operator. That worked pretty well.

---
Tags: views, 8, files
---


# Question
Title: How to print alt or title field image in custom block programmatically?
I want to print alt or title field image file in custom module Drupal 8. I load file entity `use Drupal\file\Entity\File;` I checked `core/modules/file/src/Entity/File.php`all public function but not get any function which return title or alt text.

```
$graph_data = Paragraph::load($graph['target_id']);
$output .= '<div class="swiper-slide">';
$output .= '<div class="slide-inner">';
foreach ($graph_data->field_slider_image as $item) {
 $title_img =    "Need image title here";
if ($item->entity) {
$slide_uri = $item->entity->getFileUri();
$url = ImageStyle::load('orignal')->buildUrl($slide_uri);
$output .= '<div class="col-md-6"><img src="'.$url.'" class="img-responsive"><h2>'.$title_img.'</h2></div>';
}
}

```

Please anyone give idea ?

Thankyou

# Answer
You can load the node and then fetch the paragraph targetid . Later you can load paragraph targetid and then get all attributes of the image.

```
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\node\Entity\Node;

$node = Node::load($nid);
$paragraph_field = $node->get("field_paragraph")->getValue();
$paragraph = Paragraph::load($paragraph_field[0]['target_id']);
$image_alt = $paragraph->my_image_field->alt;
$image_title= $paragraph->my_image_field->title;

```
> 5 votes

# Answer
That information isn't stored against the file entity, its on the image field attached to your source entity (e.g. your node)

So you could do something like:

```
$node->my_image_field->alt
$node->my_image_field->title

```

and that would give you the alt/title
> 4 votes

---
Tags: 8, files
---


title: Color palettes for content types

text:
# Question
Title: Color palettes for content types
We would like to give admin users of a custom theme the ability to set a color palette for each content-type for all visitors to a site.

The color module gives a way to allow admin users some control of a single color palette for the whole website but we want to let them set a palette for each content type (or leave the base color theme for each). Including any new content types, they may create in the future.

Is this feasible?

I have been poking around the color module but I am not sure how hard it would be to write a custom module that extended it in this way. Any ideas if this is even possible?

This is for a Drupal 8 site and theme.

# Answer
> 1 votes
Found this after 5 seconds of googling:

The search query was: drupal color field.

---

1. Choose one,
2. add one color field per content type to the user entity type (users should be able to edit their profile),
3. then retrieve the current user and the selected values and add them as node class via `template_preprocess_node`.

---

> I may have been unclear. I don't want to let each user set their own color palette, I want users with the right permissions to be able to set the palette for an arbitrary content type for ALL users/anonymous users accessing the site. (I'll update my question) – tanbog

For that you need to create a configuration form. @see docs Working with Configuration Forms.

You can get a list of all content types to build your form. @see question Get the list of all content types.

You also may want to use the `color` FormElement. @see docs `class Color`.

In the end you probably still use `template_preprocess_node`, to get the stored config in there, and then set the CSS class according the current node type.

---
Tags: 8, theming
---


# Question
Title: Add a class retrieved from a sibling field to responsive image
I have a **Profile** paragraph type that has the following fields:

* Profile Image \[Responsive Image Field format\]
* Profile Headline \[Plain Text\]
* Profile Description \[Plain Text\]
* Rounded Profile Image \[Boolean\]

What I'm trying to do is that when the `field_rounded_profile_image` boolean is selected, that it will add the `rounded-circle` class to the image attributes of the `field_profile_image` field.

Currently, this is what the code for the image looks like when it is printed:

```
<div data-quickedit-field-id="paragraph/196/field_profile_image/en/default" class="field field--name-field-profile-image field--type-image field--label-hidden field__item">
  <picture>
    <source srcset="/sites/default/files/styles/profile_large/public/paragraphs/image/profile/image1.jpg?h=74e1741d&itok=WLlku9ED 1x, /sites/default/files/styles/profile_large/public/paragraphs/image/profile/image1.jpg?h=74e1741d&itok=WLlku9ED 2x" media="all and (min-width: 992px)" type="image/jpeg">
    <source srcset="/sites/default/files/styles/profile_small/public/paragraphs/image/profile/image1.jpg?h=74e1741d&itok=p2VQAa0P 1x, /sites/default/files/styles/profile_small/public/paragraphs/image/profile/image1.jpg?h=74e1741d&itok=p2VQAa0P 2x" media="all and (min-width: 768px)" type="image/jpeg">

    <img src="/sites/default/files/styles/profile_small/public/paragraphs/image/profile/image1.jpg?h=74e1741d&itok=p2VQAa0P" alt="Image" typeof="foaf:Image" class="img-fluid">

  </picture>
</div>

```

I'm trying to write a preprocess hook to do this but this part of my Drupal game is lacking so I was wondering if anyone could help me out.

I've tried something along the lines of the following to no avail:

```
// Note that me adding the __profile_card below does work due to another hook I have running to allow me to specify which paragraph type to target
function MYTHEME_preprocess_paragraph__profile_card(&$variables) {
  if ($variables['content']['field_rounded_profile_image'][0]['#markup'] == "On") {
    $variables['content']['field_profile_image']['attributes']['class'][] = "rounded-circle";
  }
}

```

Any help on this would be great and I can provide any follow-up details if needed.

# Answer
> 1 votes
What I'd recommend is to simply preprocess the paragraph, get the "round image" Boolean, and use it to add a class to the paragraph. This should be just enough to style the responsive image accordingly.

```
/**
 * Implements template_preprocess_paragraph__PARAGRAPH_TYPE.
 */
function MYTHEME_preprocess_paragraph__profile_card(&$variables) {

  // Get paragraph.
  $paragraph = $variables['paragraph'];

  if (!$paragraph->get('field_rounded_profile_image')->isEmpty()) {

    // Get Boolean.
    $rounded = $paragraph-> field_rounded_profile_image->first()->getValue();

    if ($rounded['value'] == '1') {
      $variables['attributes']['class'][] = 'rounded-image';
    }
  }
}

```

And then via CSS (Sass) you'd do:

```
.paragraph-profile-card {
  &.rounded-image {
    .field-profile-image {
      // rounded image styles
      // ...
    }
  }
}

```

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


# Question
Title: unable to create new draft programatically for published node
I am using workbench\_moderation module.

When I edit the node and save it using `node_save($node)` it is changing the status of actual node to draft and original node is getting unpublished.

While I want to keep original node as published and want to create new reversion in draft status.

I used below code too but it is not working form me(It is immediately publishing my changes).

```
node_save($node);
workbench_moderation_moderate($node, 'published');

```

# Answer
> 0 votes
I've not tested or checked against the source code but I think you should try to node\_load after node\_save and before workbench\_moderation\_moderate.

```
node_save($node);
$saved_node = node_load($node->nid);
workbench_moderation_moderate($saved_node, 'published');

```

---
Tags: 7, workbench
---


title: Administrator role missing

text:
# Question
Title: Administrator role missing
I have installed Drupal 8.6.3 minimum profile and found out that there's no Administrator role under permissions section. Is this normal or am I missing something?

We have few people that needs to be using Admin roles, so without a Administrator role, I can't assign them to such a role.

# Answer
> 18 votes
Yes, that is expected, since the *Minimal* profile creates less entities than the *Standard* profile. You can see that by comparing the config/install directory in the first profile with the config/install directory in the latter profile.

As per creating the role from the user interface, that would be possible, but the created role would be a role like the others, while the *Administrator* role created from the *Standard* profile automatically gets all the permissions defined in a Drupal site. In fact, `Role::hasPermission()` uses the following code.

```
  if ($this->isAdmin()) {
    return TRUE;
  }
  return in_array($permission, $this->permissions);

```

For the *Administrator* role, `$this->isAdmin()` always return `TRUE`; for every role you create from the user interface, `$this->isAdmin()` would return `FALSE`.

If you need that role, and you cannot reinstall Drupal using the *Standard* profile, you can create a custom module, for which you create a config/optional/user.role.administrator.yml file with the following content.

```
langcode: en
status: true
dependencies:
  enforced:
    module:
      - yourmodule
id: administrator
label: Administrator
weight: 2
is_admin: true
permissions: {  }

```

(Replace *yourmodule* with the module name.)

When the module is installed, the role will be created. Since the file contains `is_admin: true`, the role will have all the permissions, automatically, like the *Administrator* role created by the *Standard* profile.

The alternative method that doesn't involve writing modules is importing the user.role.administrator.yml file in the site. The content of the file is similar to the content of the file I previously suggested, with the exception that there aren't dependencies.

```
langcode: en
status: true
dependencies: {  }
id: administrator
label: Administrator
weight: 2
is_admin: true
permissions: {  }

```

I would use the custom module method if there are other entities/bundles that you normally create when installing Drupal for a new site.
If instead you don't have the need to create other entities/bundles, importing a single file is quicker.

If you installed Drush, with `drush config-edit user.role.administrator` you can edit that file and set `is_admin` to `true`.

---
Tags: users
---


# Question
Title: How do I programmatically load a custom block?
I created a new custom block type in /admin/structure/block/block-content/types to which I added two fields. Then, I created a block with that block type.

How can I programmatically load this block via code?

How do I get the values of its fields (*x*, an image field, and *y*, a text field)?

I tried this code, but it didn't work.

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

```

# Answer
Place the block in the disabled section at admin/structure/block, this creates a block instance with your block\_content type, give it a nice easy machine name to remember.

By placing it in the disabled section, it won't show up, until you load it programatically.

Then using your machine name:

```
$machine_name = 'myblock';

$block = \Drupal::entityTypeManager()
  ->getStorage('block')
  ->load($machine_name);
if (!empty($block)) {
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);

  $pre_render = $block_content;
}

```

If you really want to get the rendered fields, you can do:

```
$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->build($pre_render);

```

But it is more standard practice to use Drupal's formatters and such and perhaps a custom template, rather than building the block and extracting elements from the rendered render array.
> 8 votes

# Answer
There are two questions. How to load and render a configured block is answered perfectly by @oknate.

For the second question, *How do I get the values of its fields (*x*, an image field, and *y*, a text field)?* That's easy, because you've already loaded the block content entity, where the fields are stored in the database.

```
$block = \Drupal\block_content\Entity\BlockContent::load($bid);

```

You can access the value from the text field

```
$text = $block->field_y->value;

```

and get the url from the image field.

```
$image_url = file_create_url($block->field_x->entity->uri->value);

```
> 1 votes

# Answer
Try this code by including `EntityInterface`:

```
// Block
use Drupal\Core\Entity\EntityInterface;
// the last part of the parameter is the block id
$block = \Drupal\block\Entity\Block::load('yourblockid');
$block_content = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);
\Drupal::service('renderer')->renderRoot($block_content);

```
> 0 votes

# Answer
```
$block = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);
      if (!empty($block)) {
        $recArticleAdView = \Drupal::entityTypeManager()
          ->getViewBuilder('block_content')
          ->view($block);
        $rendered = \Drupal::service('renderer')->render($recArticleAdView);
        $response = new CacheableResponse($rendered);
        $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($recArticleAdView));
        $variables['content']['sponsored_content'] = Markup::create(trim(strip_tags($response->getContent(), '<div>')));
      }

```
> 0 votes

---
Tags: 8, blocks
---


# Question
Title: Creating a node via REST - Entity reference field value not updating
I'm trying to create a node on a Drupal 8 site via REST. Passing all the values to create the fields work fine apart from the field that is an entity reference field. The field is an entity reference to Drupal users. Drupal creates the node, there is no validations errors, but the entity reference field has no value. I've tried changing 'target\_id' to 'value', same thing, the node gets created without errors but no value is given to the user entity reference field.

Any ideas?

```
$serialized_entity = json_encode([
    'title' => array(
      'value' => 'some_title',
    ),
    'type' => array(
      'target_id' => 'node_type',
    ),
    '_links' => array(
      'type' => array(
        'href' => $base_url . '/rest/type/node/node_type',
      ),
    ),
    'entity_reference_field' => array(
      'target_id' => $entity_id, // This does not work. Using a valid uid.
    ),
    'normal_field' => array(
      'value' => 'some_data',
    ),
]);

```

# Answer
I managed to get working by changing this...

```
'entity_reference_field' => array(
  'target_id' => $entity_id,
),

```

to this...

```
'entity_reference_field' => array(
  array('target_id' => $entity_id),
),

```

I also had to disable using an entity reference view as the 'Reference type' on the field and just have the option as 'Default'. Not sure if this is a bug or if there's something wrong with my entity reference view.
> 0 votes

---
Tags: 8, entities
---


title: Can't install drush with composer

text:
# Question
Title: Can't install drush with composer
When I run...

```
composer global require drush/drush:dev-master

```

...I get...

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: consolidation/output-formatters[3.1.12, 2.1.3].
    - Can only install one of: consolidation/output-formatters[3.1.12, 2.1.3].
    - Can only install one of: consolidation/output-formatters[3.1.12, 2.1.3].
    - drush/drush dev-master requires consolidation/output-formatters ^3.1.12 -> satisfiable by consolidation/output-formatters[3.1.12].
    - Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
    - Installation request for consolidation/output-formatters (locked at 2.1.3) -> satisfiable by consolidation/output-formatters[2.1.3].

```

---

My PHP version is 5.6.11.

# Answer
> 4 votes
The solution in my case was to run...

```
composer global update
composer global require drush/drush:dev-master

```

Previously, I had been running `composer update` but needed to run `composer global update`.

# Answer
> 2 votes
Assuming this is a Drupal 8 question; The recommended method of installing Drush is to now install it as a dependency of your project, not a system application.

```
composer require drush/drush

```

This will of course install Drush 9. If for some reason you need Drush 8 then other methods are available. But really not having to get the sysadmin involved in order to upgrade Drush is a relief.

---
Tags: drush, composer
---


# Question
Title: How do I force the download of a .zip file, with contents retrieved using drupal_http_request()?
when i do this curl request my files are getting saved in drupal root instead of getting downloaded to browser in the bottom. can anyone help me what wrong am i doing here. below is the code i'm using.

```
$product_name = "myproduct";
$zipFile = $product_name.".zip"; //Local Zip File Path

$options_array = array (
  'method' => 'GET',
  'headers' => array(
    'Authorization' => 'Basic somepassword',
    'Content-Type' => 'application/text',
    'Content-Disposition' => 'attachment',
    'charset' => 'utf-8',
    'Cache-Control' => 'no-cache' ,
  ),
);
$url = "someurl";

$result = drupal_http_request($url,$options_array);
$fp = fopen($zipFile, "w");
header('Cache-Control: no-cache');
header('Content-Length: '.strlen($result->data));
header('Content-Type: application/text');
header('Content-Disposition: attachment; filename='.$fp);
fwrite($fp, $result->data);
fclose($fp);
echo $zipFile;

```

# Answer
> 1 votes
In the same way you are using drupal\_http\_request() to make your remote request, there is a Drupal API for forcing a file download.

To do this, you will first need to create the file in the temporary directory so it can be served. You can do this using file\_unmanaged\_save\_data(), setting the destination to start with (or be) `temporary://`, and passing the data in drupal\_http\_request() to be the contents of the zip file.

Then, you will force the download of the file with file\_transfer(). This will force the browser to download the file. You can use the the file you crated above, referring to it with the `temporary://` stream wrapper.

```
// Step 1: Make HTTP Request using drupal_http_request()
// Step 2: Validate successful request
// Step 3: Create .zip file in temporary files directory, using file_unmanaged_save_data(), passing result of request made in Step 1 to be contents of .zip file
// Step 4: Serve file using file_transfer(), passing it the URI of the temporary:// file created in step 3

```

Note that the contents retrieved from the remote URL must be those of a valid .zip file.

# Answer
> 1 votes
this worked for me, thanks @Jaypan for the suggestion.

```
  $result = drupal_http_request($url,$options_array);
  $destination = 'public://swagger_files/' . $zipFile;
  // what to do when the destination file already exists
  $replace = FILE_EXISTS_REPLACE;
  $my_file_obj = file_save_data($result->data, $destination, $replace);
  $headers = file_get_content_headers($my_file_obj);
  file_transfer($my_file_obj->uri,$headers);

```

---
Tags: 7, hooks
---


# Question
Title: How to get views header and footer in view block template
I have created view as block and in block twig template i can print view fields as content\['#view'\].field\['field\_machine\_name'\].value(row) HOw can i print text in textarea that i set as header and footer for this view.

# Answer
> 1 votes
if you want to display view header or footer in twig template, look at core views-view.html.twig and all the available variables. In your case :

> header: The optional header.
>
> footer: The optional footer.

In your twig `views-view--[view-name].html.twig`, you can display your variable like this :

```
<p>{{ header }}</p>

```

---
Tags: views, theming, blocks
---


# Question
Title: How to implement custom access to node revisions?
I want to implement a custom access check in Drupal 8, where users assigned to the node field node-owner have view/edit and **revisions** view/edit permissions for this specific node.

I have implemented it for node view/edit using the node access system with `hook_node_access_records()` and `hook_node_grants()`. But I cannot find how to implement it for the node revisions, since the access check performed in `NodeRevisionAccessCheck` takes into account only the 'view revisions' and 'revert revisions' role permissions and I cannot see a relevant hook.

Should I do **custom access checking on routes** as described here? https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes

And if yes, how do I implement the route check and fetch the current node?

# Answer
> 3 votes
As you said, node revision does not have hook implement for check access. So you need other way to resolved your problem. My way is alter existing services. Just following document, there is file **my\_module/src/MyModuleServiceProvider.php**

```
<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class MyModuleServiceProvider.
 *
 * @package Drupal\mymodule
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('access_check.node.revision');
    $definition->setClass('Drupal\my_module\Access\MyModuleNodeRevisionAccessCheck');
    $definition->setArguments(
      [
        new Reference('entity.manager'),
      ]
    );
  }

}

```

After alter **access\_check.node.revision** service. I'll define new class check access view node revision with extend class NodeRevisionAccessCheck and override method access like this. File **src/Access/MyModuleNodeRevisionAccessCheck**

```
<?php

namespace Drupal\my_module\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\node\Access\NodeRevisionAccessCheck;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\Routing\Route;

/**
 * Provides an access checker for node revisions.
 *
 * @ingroup node_access
 */
class MyModuleNodeRevisionAccessCheck extends NodeRevisionAccessCheck {

  public function access(Route $route, AccountInterface $account, $node_revision = NULL, NodeInterface $node = NULL) {
    if ($node_revision) {
      $node = $this->nodeStorage->loadRevision($node_revision);
    }
    $operation = $route->getRequirement('_access_node_revision');
    // You can override logic check access here or provide a new hook.
  }

}

```

---
Tags: 8, nodes
---


# Question
Title: Import images from RSS with Feeds module without Feeds Image Grabber
I'm passing all the sites from D7 to D8 and so far so good. But one of my sites gives me a couple of problems.

I was populating the RSS site in Drupal 7 using Feeds Image Grabber. Now, Feeds Image Grabber for Drupal 8 is not there. So how do I get RSS images then?

I read that maybe you can do it with the Feeds extensible parsers module.

Any advice?

# Answer
> 0 votes
RSS feeds are XML files, so you could indeed use the XML parser from Feeds extensible parsers to extract data from it. This parser works with XPath queries. XPath is a query language to select data from a XML file. So to select the image from the RSS feed, you'll need to figure out how to select that data with the right XPath query.

It would be a good idea to learn more about XPath before using the XML parser. I think that the XPath tutorial from W3Schools is a good resource for this.

---
Tags: 8, feeds
---


# Question
Title: How to print "Time" field in twig template
I have a time field in my content type. But when I entered time in the format 05:00 AM, I get a five digit timestamp eg. 18000 (for 05:00 AM).

When I print this using `node.field_time.value|date('h:i A')` it prints

> 10:30 AM

which is 05:30 Hrs extra than the entered one. How do I'll get the correct time?

The default timezone is set to Kolkata which is +05:30 UTC. Is this something causing the problem?

# Answer
By default, it considers the entered time as UTC. So when we render the value of the time field, it prints the value according to the user's timezone.

I used below code to print the same value as entered in the backend

`node.field_time.value|date('h:i A', 'UTC')`

or we can also use `false` instead of `UTC` to get the same output without setting any time zone.
> 1 votes

---
Tags: 8, theming, datetime
---


# Question
Title: User name in view arguments and title of page
I created a content type named "Post" and allowed certain roles to add posts on my website.

I also created a view that displays these posts, as a page and block view. Now, I want to add a contextual filter to display posts from specific authors, but in filters I find only the author UID so that my URL is `post/1` and so on. Is there a way to have user name instead of user ID as wildcard in the URL?

I also want to set the page title such as "Posts of \[user-name\]", but I don't know if it is possible to do.

I'm very sorry, but I googled for this but I found nothing.

# Answer
You can add on "Relationships" (right side of your view edit page, under Advanced) "Content: Author". Now the name of the author (User: Name) will be available to you in fields and/or filters. You could also follow this: http://www.drupalden.co.uk/using-views-display-nodes-author-name
> 2 votes

---
Tags: 7, views
---


title: Error updating modules with composer

text:
# Question
Title: Error updating modules with composer
I'm trying to update a module with composer. This is the command (but it the same if I try to update another module):

```
composer update --with-dependencies drupal/geofield_map

```

This is the output of composer prohibits:

```
drupal/drupal  dev-master  requires  drupal/geofield_map (^2.10)

```

I obtain these error when I try to update:

```
Problem 1
    - don't install drupal/core 8.6.5|remove drupal/drupal dev-master
    - remove drupal/drupal dev-master|remove drupal/core 8.6.5
    - don't install drupal/core 8.6.5|remove drupal/drupal dev-master
    - Installation request for drupal/drupal dev-master -> satisfiable by drupal/drupal[dev-master].
    - Installation request for drupal/core (locked at 8.6.5, required as ^8.6) -> satisfiable by drupal/core[8.6.5].

```

I'm not a "composer expert" and I'm not able to solve it.

Here is my composer.json

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "require": {
        "composer/installers": "^1.0.24",
        "wikimedia/composer-merge-plugin": "^1.4",
        "drupal/search_api_solr": "^2.0",
        "drupal/address": "~1.0",
        "mpdf/mpdf": "^7.0",
        "drupal/geofield_map": "^2.10",
        "drupal/console": "~1.0",
        "swiftmailer/swiftmailer": "5.4.5",
        "lullabot/amp": "^1.0.0",
        "drupal/csv_serialization": "^1.4",
        "drupal/core": "^8.6",
        "webflo/drupal-core-strict": "^8.6"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "drupal-phpunit-upgrade-check": "Drupal\\Core\\Composer\\Composer::upgradePHPUnit",
        "drupal-phpunit-upgrade": "@composer update phpunit/phpunit --with-dependencies --no-progress",
        "phpcs": "phpcs --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --",
        "phpcbf": "phpcbf --standard=core/phpcs.xml.dist --runtime-set installed_paths $($COMPOSER_BINARY config vendor-dir)/drupal/coder/coder_sniffer --"
    },
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ]
}

```

\[EDIT\] If I try to replace "drupal/core": "^8.6" with "drupal/core": "8.6.5" I obtain:

```
 Problem 1
    - drupal/core 8.2.x-dev requires symfony/psr-http-message-bridge v0.2 -> satisfiable by symfony/psr-http-message-bridge[v0.2] but these conflict with your requirements or minimum-stability.
    - don't install drupal/core-render 8.2.0|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-beta1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-beta2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-beta3|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-rc1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-rc2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.3|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.4|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.5|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.6|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.7|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.8|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.0|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.0-alpha1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.0-beta1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.0-rc1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.0-rc2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.3|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.4|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.5|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.6|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.7|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.8|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.9|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.3.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.0|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.0-alpha1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.0-beta1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.0-rc1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.0-rc2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.3|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.4|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.5|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.6|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.7|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.8|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.4.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.0|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.0-alpha1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.0-beta1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.0-rc1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.3|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.4|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.5|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.6|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.7|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.8|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.5.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.0|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.0-alpha1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.0-beta1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.0-beta2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.0-rc1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.3|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.4|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.5|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.6.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.7.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core 8.3.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core 8.4.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core 8.5.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.5|remove drupal/drupal dev-master
    - don't install drupal/core 8.6.x-dev|remove drupal/drupal dev-master
    - don't install drupal/core 8.7.x-dev|remove drupal/drupal dev-master
    - remove drupal/drupal dev-master|remove drupal/core 8.6.5
    - don't install drupal/core 8.6.5|remove drupal/drupal dev-master
    - Installation request for drupal/drupal dev-master -> satisfiable by drupal/drupal[dev-master].
    - Installation request for drupal/core-render ^8.2 -> satisfiable by drupal/core[8.2.x-dev, 8.3.x-dev, 8.4.x-dev, 8.5.x-dev, 8.6.5, 8.6.x-dev, 8.7.x-dev], drupal/core-render[8.2.0, 8.2.0-beta1, 8.2.0-beta2, 8.2.0-beta3, 8.2.0-rc1, 8.2.0-rc2, 8.2.1, 8.2.2, 8.2.3, 8.2.4, 8.2.5, 8.2.6, 8.2.7, 8.2.8, 8.2.x-dev, 8.3.0, 8.3.0-alpha1, 8.3.0-beta1, 8.3.0-rc1, 8.3.0-rc2, 8.3.1, 8.3.2, 8.3.3, 8.3.4, 8.3.5, 8.3.6, 8.3.7, 8.3.8, 8.3.9, 8.3.x-dev, 8.4.0, 8.4.0-alpha1, 8.4.0-beta1, 8.4.0-rc1, 8.4.0-rc2, 8.4.1, 8.4.2, 8.4.3, 8.4.4, 8.4.5, 8.4.6, 8.4.7, 8.4.8, 8.4.x-dev, 8.5.0, 8.5.0-alpha1, 8.5.0-beta1, 8.5.0-rc1, 8.5.1, 8.5.2, 8.5.3, 8.5.4, 8.5.5, 8.5.6, 8.5.7, 8.5.8, 8.5.x-dev, 8.6.0, 8.6.0-alpha1, 8.6.0-beta1, 8.6.0-beta2, 8.6.0-rc1, 8.6.1, 8.6.2, 8.6.3, 8.6.4, 8.6.5, 8.6.x-dev, 8.7.x-dev].

```

# Answer
I just had the same issue as you -- really bizarre. Instead of using composer update, I removed the module I was trying to update from my composer.json and ran composer require again instead for the newest version of the module (in your case this would be `composer require drupal/geofield_map:^2.10`).

I also had to remove the merge-plugin section of my composer.json (actually this may fix the issue without worrying about manually re-requiring the module).
> 1 votes

# Answer
1. You can use the administrative interface: ==\> admin/reports/updates/update
2. Use drush
3. Use the composer command : `composer update` ==\> will update all your librairies
> -2 votes

---
Tags: updating, composer
---


title: Edit Shipping Address on existing order

text:
# Question
Title: Edit Shipping Address on existing order
Is there any way to edit the shipping address on an existing order? I only see the billing address in the edit screen.

# Answer
> 0 votes
Not sure if that works in all cases, but in mine - I managed to enable shipping form this way:

1. go to Home \>\> Administration \>\> Commerce \>\> Configuration \>\> Order types \>\> Edit \[your order type\] (/admin/commerce/config/order-types/\[order\_type\]/edit/form-display)
2. select "Manage form display" there
3. find "Shipments" line there
4. switch it to `Inline entity form - Complex`

And instead of autocomplete for shipments I got form with edit button that allows me to change shipping address for order.

Order display settings screen:

Edit order page shipping block after update:

---
Tags: commerce
---


# Question
Title: Access denied to all users after migrating site to new server
Please don't consider this as a duplicate post. I have tried all the solutions that worked for others, but still struggling to fix the problem (all users including admin taken to 403 page). This is a Windows server running Drupal 7.

Things I have tried -

* No base\_url value given
* No cookie\_domain value given
* Session table truncated
* Cache tables truncated
* No file permission differences
* Tried Reset password email but the link takes to 403 page
* Deleted browser cache

Please let me know if anyone has experience with a similar issue or what else I could try.

This is what I can see in watchdog table.

Thanks

# Answer
> 2 votes
I finally figured it out!

We are enforcing secure flag on our cookie and therefore had to disable the corresponding rewrite rule from IIS, as we didn't have a SSL certificate in new server.

# Answer
> 1 votes
Check the user table in the DB. sometimes when importing DBs it starts auto-numbering from 1, so you don't have a user with the id of 0, which Drupal uses for its anonymous user.

---
Tags: users
---


title: Properly merge array values

text:
# Question
Title: Properly merge array values
We have the following `mymodule_preprocess_node` hook where we add two arrays with two `key-value pairs`. In `twig`, we would like to merge the values.

How would we merge the two arrays in `twig`?

Here is what we tried.

**mymodule\_preprocess\_node**

```
function mymodule_preprocess_node(&$variables) {
  // perform some logic.

  $variables['content']['ary']['foo'] = 'foo_value';
  $variables['content']['ary']['bar'] = 'bar_value';
}

```

**node--article.html.twig**

```
{% set twigAry = [] %}
{% for key, value in content.ary %}
  {$ set twigAry = twigAry|merge({ key : value }) %}
{% endfor %}

```

This results in `twigAry` only having the following. It basically prints the last `key` and `value`, which is `bar` and `bar_value`. Strangely enough, instead of setting the key to `bar` it results in the key being `key`.

```
[
  'key' => 'bar_value'
]

```

**Desired Output**

```
[
  'foo' => 'foo_value`,
  'bar' => 'bar_value',
]

```

In the twig template, we are adding an inline `<script>` tag that needs to have the array in the desired output as such we need to have in this format in twig. For example, when we load the Marketo form, we want to set some values like this. Rather than hardcoding items in twig, we will just use the `['foo']` and `['bar']` from the preprocess method.

```
MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
    // Set the value of the Phone and Country fields
    form.vals({ "Phone":"555-555-1234", "Country":"USA"});
});

```

**Final twig:**

```
{% set twigAry = [] %}
{% for key, value in content.ary %}
  {$ set twigAry = twigAry|merge({ key : value }) %}
{% endfor %}

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
  // Set the value of the Phone and Country fields
  form.vals({ twigAry });
});

```

# Answer
The hash `{ key: value }` is equivalent to `{ 'key': value }`.

Solution:

```
{# key as expression (the expression must be enclosed into parentheses) #}

{ (key): value }

```

See https://twig.symfony.com/doc/2.x/templates.html#literals
> 1 votes

# Answer
Associative arrays must use curly brackets in Twig:

`{% set twigAry = {} %}`

Arrays with square brackets `[]` defined in Twig don't have key names
> 1 votes

---
Tags: 8, theming, hooks
---


title: Get form values in hook_user_insert()

text:
# Question
Title: Get form values in hook_user_insert()
How can I get form values like first name, last name, email and password in `hook_user_insert()` in Drupal 8?

# Answer
> 1 votes
The $account argument have the data that you like, but the password is protected.

It's not the best practice, but you can use reflection to get it:

```
/** @var \Drupal\Core\Field\FieldItemList $passObject */
$passObject = $account->get('pass');
/** @var \Drupal\Core\Field\Plugin\Field\FieldType\PasswordItem $passItem */
$passItem = $passObject->get(0);
$reflection = new \ReflectionClass($passItem);
$reflectionProperty = $reflection->getProperty('values');
// This do the magic.
$reflectionProperty->setAccessible(true);
$pass = $reflectionProperty->getValue($passItem)['value'];

```

See more about hook\_user\_insert here.

---
Tags: users, hooks
---


# Question
Title: Drupal.behaviors, attach and origin of it
The structure of `Drupal.behaviors` is rather similar in Drupal 7 and Drupal 8. Where do `attach()` and `detach()` come from? Thid code is from drupal.js , still wondering where attach method in this.attach is defined?

```
Drupal.attachBehaviors = function (context, settings) {
  context = context || document;
  settings = settings || Drupal.settings;
  // Execute all of them.
  $.each(Drupal.behaviors, function () {
    if ($.isFunction(this.attach)) {
      this.attach(context, settings);
    }
  });
};

```

# Answer
The attach() and detach() methods are part of the Behaviors interface defined by Drupal:

> Any object defined as a property of Drupal.behaviors will get its attach() method called when the DOM has loaded both initially and after any AJAX calls.

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
> 4 votes

---
Tags: 8, javascript
---


# Question
Title: else condition does not work in my code in twig template
In the code given below

`content.field_image_link[0]['#url']`
is empty but it still enters the if condition and adds html
what is incorrect in the below code due to which it enters the if
condition whereas it should enter the second if condition given below

{% if content.field\_image\_link\[0\]\['#url'\] %}

```
{% block paragraph %}

 <div{{ attributes.addClass(classes) }}>

    {% block content %}

{% if content.field_image_link[0]['#url'] %}

<a href="{{ content.field_image_link[0]['#url'] }}">

{{ content.field_image_2 }}
</a>
<h2>
<a href="{{ content.field_image_link[0]['#url'] }}">
{{ content.field_image_link[0]['#title'] }}
</a>
</h2>
{% endif %}
{% if content.field_image_link[0]['#url'] == '' %}
{{ content.field_image_2 }}
<h2>
{{ content.field_image_link[0]['#title'] }}
</h2>
{% endif %}
    {% endblock %}
  </div>

{% endblock paragraph %}

```

# Answer
> 1 votes
If they are suppose to be mutually exclusive shouldn't you have an if/else statement?

In any case, Testing for an empty value can be a pain with twig.

See this answer

Short answer, based on above link:

```
{% if content.field_image_link[0]['#url']|render|striptags|trim %}

```

You want to render to get the field then remove/trim whitespace.

# Answer
> 2 votes
You need to check if variable is defined (defined in twig) and additionally also check the length of variable in twig.

```
{% if content.field_image_link[0]['#url'] is defined and content.field_image_link[0]['#url'] | length > 0 %}
    //do stuff
{% else %}
    //do another stuff
{% endif %}

```

---
Tags: 8, theming
---


# Question
Title: Adding field collections programmatically
I'm trying to add a field collection to my user account on an event, and it seems to be being created properly, the fields are updated as expected and it parents it to the user account, however, even though the field collection is setup to have unlimited possible values, it only seems to keep the last value, it seems to keep overwriting the old one whenever a new field collection is added.

My code is below

```
global $user;

$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_downloads'));
$field_collection_item->setHostEntity('user', $user);
$field_collection_item->field_subqueue[LANGUAGE_NONE][] = array('target_id' => $subqueue->subqueue_id);
$field_collection_item->field_file[LANGUAGE_NONE][] = array('fid' => $file->fid, 'display' => 1, 'description' => $filename);
$field_collection_item->save(TRUE);
field_attach_update('user', $user);

```

As mentioned, it appears to be creating the field collection properly, I can check in my account and it saves the file and correctly sets the entity reference for the `field_subqueue` field too, but it only seems to save 1, like I say, the field is definitely set to allow unlimited values, it even shows me the button to 'add another item' if I check it in the user account directly.

Is there something I'm doing wrong?

**EDIT**

I really need to try to get this fixed so I'm gonna open it up to a bounty.

The full context of this code is that it's on the callback of an AJAX form that I've written, everything about the code seems to happen correctly, the form submission happens correctly, it seems to save the field collection, it just seems to overwrite the previous entry each time. It isn't running as part of a loop or anything, each time the form is submitted, it should save it using the `field_attach_update` line

```
/**
 * Submit handler for saving a new deck
 */
function my_module_form_submit($form, &$form_state){
    global $user;

    // Load the PHP library
    libraries_load('my_library');

    // Prepare an ajax command to insert the node html into our ajax wrapper.
    $commands = array();
    $commands['effect'] = 'fade';

    if (form_get_errors() !== null) {
        $message = t('You have an error');
        $commands[] = ajax_command_invoke(NULL, array('firePopup'), array(json_encode($message), 'error', 3500)); // This is just a custom Javascript command I have called firePopup
    }
    else {
        $values = $form_state['values'];
        $values['my_var'] = json_decode($form_state['input']['_my_vars']);
        $filename = empty($values['title']) ? date("F j Y - g-ia") : $values['title'];

        // Custom function here to generate a 'subqueue' from the module 'node_queue', returns a $subqueue object

        // Add the downloaded file to the field collection for the user
        $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_downloads'));
        $field_collection_item->setHostEntity('user', $user);
        $field_collection_item->field_subqueue[LANGUAGE_NONE][] = array('target_id' => $subqueue->subqueue_id);
        $field_collection_item->field_file[LANGUAGE_NONE][] = array('fid' => $pptx->fid, 'display' => 1, 'description' => $filename);
        $field_collection_item->save(TRUE);
        field_attach_update('user', $user);

        // Set the response message
        $message = t('Your download is available.');
        $download_link = l(t('Download'), file_create_url($field_collection_item->field_file[LANGUAGE_NONE][0]['uri']), array(
            'attributes' => array(
                'class' => array(
                    'button-type',
                    'download'
                ),
            'download' => file_create_url($field_collection_item->field_file[LANGUAGE_NONE][0]['uri']))));

        $commands[] = ajax_command_invoke(NULL, array('refreshView'), array('downloads'));
        $commands[] = ajax_command_invoke(NULL, array('firePopup'), array(json_encode($message), 'status', 0, $download_link));
    }

    // Render the commands into JSON and print them.
    return array('#type' => 'ajax', '#commands' => $commands);
}

```

If there's any variables here which look like they come out of nowhere, don't worry about that too much, it's only because I've removed some of the sub-functions and it's probably more confusing to add multiple sub-functions in too etc.

The code all appears to work fine, no errors, it just seems to overwrite the field collection each time.

# Answer
> 0 votes
After almost bringing myself to tears trying to figure this one out, I figured out what the problem was

calling `global $user` doesn't get the full user object, and it doesn't bring back the additional fields you've added in to it, so every time I tried running my code, setting the new property and saving it, I was effectively writing it as a new property in my `$user` object and thus it was overwriting the existing value, because it never loaded the original values in the first place.

The resolution was just to add `$account = user_load($user->uid);` after the `global $user;` line, and from then on do everything to the $account object instead.

# Answer
> 1 votes
The `$user` entity needs explicit handling (clearing the cache as well as calling attach\_presave), when using `field_attach_update()`. You could try this:

```
entity_get_controller('user')->resetCache([$user->uid]);
field_attach_presave('user', $user);
field_attach_update('user', $user);

```

If this doesn't do it for you, you can go a step less efficient and call `user_save()` after attaching the new field\_collection manually, e.g.:

```
entity_get_controller('user')->resetCache([$user->uid]);
$user->field_downloads[LANGUAGE_NONE][] = array(
  'value' => entity_id('field_collection_item', $field_collection_item),
);
user_save($user);

```

**Update:**

This needs some more debugging, one way to work with it would be to break it down and see what works. I would start with such a function:

```
function _debug_fci_additions($uid) {
  $user = user_load($uid);
  for ($i = 0; $i < 2; $i++) {
    $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_downloads'));
    $field_collection_item->setHostEntity('user', $user);
    $field_collection_item->save(TRUE);
  }
  user_save($user);
}

```

Once this function is in place, you could call it using drush, e.g.:

```
drush ev "_debug_fci_additions(1234);"

```

and then check is the field collections were added.

**Update 2**

Reading through the `FieldCollectionItemEntity::save()` comment I see this clear suggestion:

> For creating an item a host entity has to be specified via setHostEntity() before this function is invoked. For the link between the entities to be fully established, the host entity object has to be updated to include a reference on this field collection item during saving. So do not skip saving the host for creating items.
>
> @param $skip\_host\_save (internal) If TRUE is passed, the host entity is not saved automatically and therefore no link is created between the host and the item or revision updates might be skipped. Use with care.

So, I would suggest trying your code using:

```
    $field_collection_item->save();

```

instead of

```
    $field_collection_item->save(TRUE);
    field_attach_update('user', $user);

```

Good luck!

# Answer
> 0 votes
From my understanding you create the same entity each time. This overwrites the previous entity holding in its place.

```
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_downloads'));

```

try adding a count feature like this:

```
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_downloads[1]'));

```

replace 1 with a variable of your choice that will count++ every time you save a new one.

---
Tags: 7, users, entities
---


# Question
Title: Webform limit to multiple choice question
Anyone know of a way to take a multiple choice (checkbox) question on a Webform and only allow the person to select two or three options and all other options become disabled? Using WebForm module? Version: 7.x-4.15

# Answer
> 0 votes
Discovered a module called Webform Validation, works fine. But the user will only know that he can't submit more than x answers after clicking the submit button.

---
Tags: 7, webforms
---


# Question
Title: Add icon to module's menu item in Administration menu
I've searched for a bit and I haven't found a solution to my liking: I want to avoid adding more modules to the project.

I'm very new to Drupal, so I have minimal knowledge on that matter. I have this project which somebody else has made. They created a module which adds a menu item on the Administration menu. What this module *doesn't* do, is add an icon to the menu item, which makes it look bare.

I want to add a custom icon I've made next to the menu item text. The reason it needs to be a custom icon and can't be fontawesome (or anything of its liking), is because it has to be a variation of the site logo.

Is there a way to accomplish this without adding more modules to the project, or is adding more modules the only way?

It's Drupal 8 with Lightning on Debian 9 with Apache2.4 and PHP7.2.

# Answer
> 2 votes
I figured it out. Now, this might not be the very best way to solve it, and some things should probably be changed, but this will be fine for now. Let's assume the module name is ***pizza***.

**First**, create a directory called `css`. Inside this folder, create a css file with the name of the module. In this case it would be `pizza.css`. Since there needs to be an icon next to the module's menu item title on the administration menu, this is the CSS we'll need (or similar):

```
.toolbar-icon-pizza-main::before{
    background-image: url('../../../../../sites/default/files/pizza-icon.png');
}

```

**Second**, we will need a libraries file in the module's root (where `pizza.info.yml` is located); call it `pizza.libraries.yml`. Inside this file write something along the lines of this:

```
toolbar-icon:
  version: 1.0
  css:
    base:
      css/pizza.css: {}

```

Here, `base` probably should be changed to `theme`, since this is an aesthetic to the module.

**Third**, move into `pizza.info.yml`, we need to include the library we made into the module. Add this to the bottom:

```
libraries:
  - pizza/toolbar-icon

```

**Fourth**, move into `pizza.module`, where we're going to add this:

```
/*
 * Implements hook_toolbar_alter()
 */
function pizza_toolbar_alter(&$items) {
  $items['administration']['#attached']['library'][] = 'pizza/toolbar-icon';
}

```

This fixed it for me. **Source:** https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

---
Tags: navigation
---


# Question
Title: Location subfields problem to render in teaser template node
I have tried render only two array´s parameters. Street and postal code but don´t display anything this code.

```
<?php print render($content['field_mapa']['und'][0]['street']); ?>and <?php print render($content['field_mapa']['und'][0]['city']); ?>

```

However with this code print all parameters.

```
<?php  print render($content['field_mapa']); ?>

```

I don´t understand where is the problem with this field.

# Answer
The location field module wrap fields inside `#location` so try with :

```
<?php print render($content['field_mapa'][0]['#location']['street']); ?>

```

and

```
<?php print render($content['field_mapa'][0]['#location']['city']); ?>

```
> 0 votes

---
Tags: 7, theming, location
---


# Question
Title: Text will not vertical-align to the top in Drupal table
I am trying to edit a table in my Drupal editor that has images on one row (4 `td` elements) and a second row with text (also 4 `td` elements). I have applied `vertical-align:top` to the cells in the text row and they look fine in the editor. However, when I preview the page after saving the changes, the text appears to be at different vertical alignments. I tried doing `vertical-align:middle` to see if that would help, but the same results occurred. Could this be a browser issue (I am using `IE`)? Or is there something else I need to do to resolve this issue?

# Answer
> 1 votes
Try adding `valign="top"` to the `TD` element like `<td valign="top">...</td>` and see if it works.

---
Tags: theming, nodes, entities
---


title: Update webform without composer

text:
# Question
Title: Update webform without composer
I need to update webform from 8.x-5.0-beta18 to 8.x-5.1 but unfortunately, I cannot use Composer because it is not possible to install it on my server due to server restrictions.

This also apply to:

* Clientside Validation 8.x-1.0-rc3 to 8.x-1.0
* Poll 8.x-1.1 to 8.x-1.2
* SMTP Authentication Support 8.x-1.0-beta3 to 8.x-1.0-beta4

as they all appear in the admin/reports/updates/update

Is there anyway to do it manually?

# Answer
> 0 votes
Before doing any updates, make sure that you've backed up your production site to avoid loss of data. Also make sure that you have an easy way to restore the backups (:

## Solution 1

You can replicate the site on your local dev environment. Then, apply the updates using composer and upload the relevant files to the prod site.

## Solution 2

You can use `drush up MODULENAME` to update specific modules. However, make sure you've tested the updates on a dev site. However, some modules have dependencies which need to updated separately. It is for these dependencies that people recommend using `composer` for updating Drupal packages.

---
Tags: webforms, composer
---