# Question
Title: How would we add Drupal Core modules as dependencies on custom modules post 8.6.2?
We recently updated to Drupal Core 8.6.2 and noticed there are changes to `module dependencies`. We are noticing that `drupal:` is added before the module names. We were unable to find any documentation that further explains it.

How would we add Drupal Core modules as dependencies on custom modules post 8.6.2?

**mymodule.info.yml example before 8.6.2**

```
type: module
name: my module
description: my custom module
package: 8.x
core: 8.x
dependencies:
  - field
  - image

```

**mymodule.info.yml example after 8.6.2**

```
type: module
name: my module
description: my custom module
package: 8.x
core: 8.x
dependencies:
  - drupal:field
  - drupal:image

```

# Answer
If you're referencing a recent change in a core module, it was a style/formatting change.

Adding namespaces for dependencies has been in core for a while. The `{project}:{module}` format is a better practice for removing ambiguity in the event of module/project machine name overlap, but both will work.

For documentation reference, see *Let Drupal 8 know about your module with an .info.yml file* under the example section for `dependencies`:

> > `dependencies` \- A list of other modules your module depends on. Dependencies should be namespaced in the format `{project}:{module}`, where `{project}` is the project name as it appears in the Drupal.org URL (e.g. drupal.org/project/views) and `{module}` is the module's machine name. Dependencies can also include version restrictions, for example `webform:webform (>=8.x-5.x)`. Note that if your module has dependencies on other contributed modules or libraries, these should be declared in the module's composer.json file.
> 3 votes

---
Tags: 8, hooks, upgrading
---


# Question
Title: EntityQuery on nodes related by ERR and paragraphs
I have content type Publication which relates to content type Project using paragraphs:

```
Publication [field_mention] -> Mention (paragraphs) [field_project] -> Project

```

Now I want to show all referenced Projects on Article templates. Views doesn't show all relations because of the complexity of this relationship.

I try to do it using EntityQuery with the following code used in a Custom Block Module in the following way:

```
$nids = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'publication')
    ->condition('field_mention.entity.field_project.target_id', \Drupal::routeMatch()->getRawParameter('node'))
    ->execute();

```

The result is empty (after a long loading so) and logs don't show any error.

Is *field\_mention.entity.field\_project.target\_id* the right way to do it or do I miss something?

# Answer
Newer versions of Drupal (tested with v8.6.2) can also resolve Paragraphs (Entity Reference Revisions) if you explicitly name the target entity type using dot notation:

```
$nids = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'publication')
    ->condition('field_mention.entity:paragraph.field_project.target_id', \Drupal::routeMatch()->getRawParameter('node'))
    ->execute();

```

Note the `.entity:paragraph.` instead of `.entity.` in the referenced field condition
> 5 votes

---
Tags: 8, entities, database, paragraphs
---


# Question
Title: Change sort order based on facet selection
My view displays Webinars, I use facets to choose between upcoming and archived.

The default sort order is ASC, which is fine for upcoming dates, but if you select the archived facet, I need the sort order to change to DESC. Any ideas?

# Answer
> 1 votes
This is how i solved the problem in the end, i checked the current path using `request_path()` and if it matched my facet url, then use the `search_api_query_alter` hook to reverse the sort order:

```
function MYMODULE_search_api_query_alter(SearchApiQueryInterface $query) {
    $query->sort('my_field_name', 'DESC');
}

```

---
Tags: 7, search
---


# Question
Title: Why do I get 'access denied' when viewing nodes?
I'm testing my website and I have to cope with a strange problem. Although every role has the permission "View published content", only the administrator can access nodes: anonymous users and authenticated users can't. The same problem occurs with adding content. I've tried clearing caches, saving the permissions again and rebuilding the permissions, but nothing helps. I'm not using any modules that control node access either...

How can I solve this?

# Answer
Things to try when you get inexplicable "Access denied" when non-admins try to view nodes and you're sure every role has the permission "View published content":

1. Clear all caches. Note that you need to both clear your browser's cache and the Drupal cache on the server. To clear your browser's cache, hold down *Shift* and reload the page. To clear the server cache, navigate to *Administration → Configuration → Development → Performance → Clear all caches*. If you use **Views**, clear **Views**' cache: *Administration → Structure → Views → Settings Advanced → Clear Views' cache*. If you've got *drush* installed (always a good thing to have around), a quick way to clean all caches on the server is `drush cc all`.
2. Rebuild permissions: append the path: `admin/reports/status/rebuild` to your site's base URL, or navigate to *Administration → Reports → Status report* and look for the link "Rebuild permissions".
3. Repair the Sessions table: Use *phpMyAdmin* or a similar tool, choose your Drupal database, check the box next to the `{sessions}` table, and find the "With selected" drop-down near the bottom of the page. Choose "Repair table".
4. If you've just installed a new module, make sure that you've executed a database update. To execute a database update, append the path `update.php` to you site's base URL. (There will be a link to this page on the Status reports page if Drupal thinks you need to do it.)
5. Use the **DNA** module (part of Devel) to debug node access problems. DNA will display a block telling you exactly what permissions are enforced and where they come from. Remember to give give the anonymous and authenticated user roles permission to "Access developer information" to use **DNA** to debug access problems for these roles. Report your findings here by editing your question if you don't understand the output of **DNA**.
6. If none of the above works, start disabling modules to see if one of those causes the problem. Remember to clear caches after disabling a module. You may also want to rebuild permissions (see pt. 2 above) after disabling a module, even if the module don't tell you to do it.
> 11 votes

# Answer
Something very very silly may bring you at this 'access denied'.

There's a web server serving both http and https (without a proper redirect from "http" \> "https"). In this scenario, it may happen that you login at "http" and the access content at "https". From the Drupal point of view, two different sessions. You will get thus "Access denied" if the content you want to read is not for anonymous guests. Again, it is very very silly, but it happens.
> 0 votes

---
Tags: 7, users
---


title: Move a Webform between sites

text:
# Question
Title: Move a Webform between sites
I built a few webforms on a Drupal 8 install. I see how to export the webform in YAML via the export tab on the webform.

How do I import that YAML into another site to re-create that webform?

Thanks in advance.

# Answer
The simplest way would be to go to */admin/config/development/configuration/single/import*, select *Webform* and paste the YAML.

More information: Configuration Managment.
> 3 votes

---
Tags: 8, webforms
---


title: How do I disable a fieldset?

text:
# Question
Title: How do I disable a fieldset?
I read How to unset fieldset in hook\_form\_alter? to disable fieldsets in an `hook_form_alter()` implementation, but it didn't work.

I tried using the following code, but neither of them worked.

```
// First try.
foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
  $form[$form_element_id]['#attributes']['disabled'] = TRUE;
}

```

```
// Second try
foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
  $form[$form_element_id]['#attributes']['disabled'] = 'disabled';
}

```

How can I disable fieldsets?

# Answer
> 0 votes
You can not access directly to `#fieldgroups` in `form_alter` you should add `pre_render` function like the following:

```
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'YOUR_FORM_ID') {
    $form['#pre_render'][] = 'mymodule_form_pre_render';
  }
}

/**
 * @param $form
 *
 * @return mixed
 */
function mymodule_form_pre_render($form) {
  foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
    $form[$form_element_id]['#access'] = FALSE;
  }
  return $form;
}

```

**Edit** : if you want to just disable the fields change the `pre_render` function by:

```
function mymodule_form_pre_render($form) {
  foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
    if (isset($form[$form_element_id])) {
      //- For entity reference fields
      if (isset($form[$form_element_id]['widget'][0]['target_id'])) {
        $form[$form_element_id]['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';
      }
      //- For normal input form
      if (isset($form[$form_element_id]['widget'][0]['value'])) {
        $form[$form_element_id]['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
      }
    }
  }
  return $form;
}

```

---
Tags: 8, forms
---


title: How to display a warning message

text:
# Question
Title: How to display a warning message
I have a form with a required checkbox.

If the box is not checked and I confirm my form, I receive a warning with Chrome (see the screenshot).

How to display a warning message in drupal ?

In my module, I add code to display a Drupal warning. Why is not it displayed ?

```
<?php

namespace Drupal\commerce_agree_cgv\Plugin\Commerce\CheckoutPane;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "agree_cgv",
 *   label = @Translation("Agree CGV"),
 *   default_step = "review",
 * )
 */
class AgreeCGV extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    if (!$form_state->getErrors()) {
      $values = $form_state->getValue($form['#parents']);
      $this->t('You must agree with the terms before continuing.');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $store_name = $this->order->getStore()->getName();
    $store_id = $this->order->getStoreId();
    $pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $attributes = [
      'attributes' => [
        'modal-title' => $this->t('Terms and conditions'),
        'class' => 'use-ajax',
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => auto,
        ]),
      ],
    ];
    $link = Link::fromTextAndUrl(
      $this->t('the general terms and conditions of the store "@store_name"', ['@store_name' => $store_name]),
      Url::fromUri("internal:/store/$store_id/cgv", $attributes)
    )->toString();
    $pane_form['cgv'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept @cgv.', ['@cgv' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

  /**
   * {@inheritdoc}
   */
  public function validatePaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
    $values = $form_state->getValue($pane_form['#parents']);
    if (!$values['cgv']) {
      $form_state->setError($pane_form, $this->t('You must agree with the terms before continuing.'));
    }
  }

}

```

# Answer
> 1 votes
That’s the browser validation message appearing. If you want to show Drupal messages only, you need to set the no-validate attribute on the form tag itself so browsers ignore it. Drupal will still run validation on submission.

---
Tags: 8, theming, forms
---


# Question
Title: How do I display the last person that edited content instead of the original author?
On the page `/admin/content`, there is a column for Author. We have a lot of people editing our content, so the original author isn't all that important. I want to change it to show the last person that edited the content, which I believe is stored in the revision of that content. How can I modify the view to show that? Alternatively, is there a hook I can implement in a custom module to do this?

I've checked out a couple other questions like this one and this one, but they weren't much help.

# Answer
> 8 votes
Adding a relationship of `user (content revision)` & `Content (Content revision)` proved to be fruitless.

### Ok, time for plan B

Using **Views field view** we'll create a revision view, add revision user as field and then insert this view as field on the content view.

1) Create a new view

* Show: Content Revision
* Checkmark Create a block
* Items per block: 1

2) Add a contextual filter

* Originally I tried with Revision ID, but there is a bug, this contextual filter does not work.
* So instead use ID (which is the node id)

* When filter not available, `hide view`

3)

* Remove the changed & title fields
* Add `Revision User`

4) Add a Sort of `Changed`

* Select Descending sort

5) `Save` your view

---

Now go to the Content View (/admin/structure/views/view/content)

1) Add field of `ID`

* Checkmark, exclude from display

2) Add field `View`

* Select the view you just created and for contextual filter use `{{ fields.nid }}`

and that's it!

---
Tags: views, 8
---


title: How do I use a node as the homepage?

text:
# Question
Title: How do I use a node as the homepage?
I feel like I'm misunderstanding something at a fundamental level when trying to author my drupal site. Two content types, both created by me, are available - `faq` and `page`. The `faq` type is a basic question + answer type, and will be pulled into an FAQ list block which I created. The `page` type is for a generic authored page, and has a `body` property of type `entity_reference_revision` which allows content to be authored using Bootstrap Paragraphs.

Some sources online say that you just have to check the "Promote to front page" box to get a node to be the front page. Others say that you have to provide a URL path for the node. I've tried both, and neither causes the site's front page to display the authored page I've created.

Instead, on the front page, I see a list of the items that have been promoted to the front page.

How can I get my authored node to replace the content of front page, so that if I navigate to the root route (`/`), I see the authored page?

# Answer
Set the front page in Admin \> Config \> Site Information. “Promoted to frontoage” is not what you think it means in this context.
> 3 votes

---
Tags: 8
---


# Question
Title: Calling entity reference field in page template
We are working on Drupal 8 Blog Page template. We want to render entity reference fields in the page template.

I have tried `{{ node.field_name.entity.name.value }}` and `{{ node.field_name.entity.uri.value }}` but none of this is working. Do I need to update/change anything in Drupal backend for the content type?

# Answer
The entity reference field normally contains just the entity ID as value.

Looking at Twig get value of field in entity reference and Drupal 8 loop entity reference fields.twig it seems a bit that

```
{{ node.field_name.entity }}

```

or

```
{{ node.field_name.0.entity }}

```

or

```
{{ node.field_name[0].entity }}

```

might work.

---

If it doesn't work, try Twig Tweak which gives you some handy functions to print Drupal entities in Twig.

```
{% set nid = node.field_name.target_id %}
{{ drupal_entity('node', nid) }}

```

Or even easier as recommended by @4k4 in the comments:

```
{{ drupal_field('field_name', 'node') }}

```

---

> Twig Tweak is a small module which provides a Twig extension with some useful functions and filters that can improve development experience.
> 3 votes

---
Tags: 8, theming
---


# Question
Title: When can a contrib module considered to be stable?
Is there a clear definition of a module being stable in comparison with a release candidate? When can a stable version be released?

As an example, can't the Read only mode module considered stable?

# Answer
> 3 votes
Read the docs.

Release naming conventions

> **rc**: A release candidate should only be created when the all critical bug type issues are reported fixed in the project's issue queue. This tag should only be used when the developer believes that the project is ready for use on a production site. **There is no official best practice for how long a project should be a release candidate before creating a official .0 release**, but it is suggested that it should be out for at least a month with status set to "needs review". If something (e.g. a new critical bug is reported) makes it necessary to create a new release during this period, a new release candidate should be created and this should remain for at least a month with status set to "needs review".

---
Tags: 8
---


# Question
Title: How can I use pathauto to generate URLs for deeply nested vocabularies?
I am generating breadcrumbs from URL arguments as described here.

I have a vocabulary that looks like this:

Arts-\> Performing-\> Dancing-\> Ballet

I want my url to look like this: arts/performing/dancing/ballet

Using the pathauto module, I can do this for taxonomy terms:

```
[term:parent]/[term:name]

```

Which, on the Ballet page, gives me the following; not what I want:

```
dancing/ballet

```

If I use parents instead of parent, (`[term:parents]/[term:name]`); this is close but not quite:

```
arts-performing-dancing/ballet

```

How can I get from `arts-performing-dancing` to `arts/performing/dancing`?

# Answer
Found a better way that scales

```
[node:menu-link:parents:join-path]/[node:title]

```
> 7 votes

# Answer
Try something like this as your vocabulary pattern:

```
[term:parent:parent:parent:name]/[term:parent:parent:name]/[term:parent:name]/[term:name]

```

And your last question should go away.

Just be sure to repeat the `parent:` part at least as many times as max term depth expected in your vocabulary. Pathauto will smartly skip overhead items.

I know it's not super-scalable, but it works for me.
> 9 votes

# Answer
All these answer are right but you can also use the Taxonomy entity index module which provides taxonomy tokens. Problems begin when your term contains slashes.

> The taxonomy entity index module maintains a normalized index of all terms associated with a specific entity and revision. The core {taxonomy\_index} table only maintains its data for published nodes. This module maintains its data for all entity types (regardless of published or not) and also indexed by revision.
> 4 votes

# Answer
If you find pattern for Drupal 8, use `[term:parents:join:/]/[term:name]`

Example result: `arts/performing/dancing`

Because our delimiter is slash, don't forget to disable removing the slashes in **Administration \> Configuration \> Search and metadata \> URL aliases \> Settings**, go to /admin/config/search/path/settings, **Punctuation** section, find **Slash (/)** and choose "No action (do not remove)" in dropdown.
> 2 votes

# Answer
Use the following pattern for the path alias: `[term:i18n-vocabulary]/[term:parents:join-path]/[term:i18n-name]`.
> 0 votes

---
Tags: 7, path-aliases
---


title: Making a colums total (SUM) with Views

text:
# Question
Title: Making a colums total (SUM) with Views
Popular Drupal 7 modules such as Views Calc and Views aggregate plus are not available for Drupal 8, so I'm struggling with achieving the following :

Making the sum of a column (of one integer field of list of child nodes) per parent node, without any custom code. No matter what I do with the "Use Aggregation" feature , I keep on getting a list of the values of entities meeting my criteria and not the sum.

# Answer
In my initial attempts, I tried to created a view on the child nodes to which I applied a contextual filter to limit the results to the parent node. That didn't work.

In the end, the SUM worked, when I switched things around, I created a view on the parent, and establised a relation with the child nodes (through an entity reference). When I summed up the field (of the child), it worked.
> 1 votes

# Answer
Your current configuration is doing the SUM of all numbers in that field but per views row, so you'd see numbers added up within each node if you had a multivalue field.

To make it sum up across all results/nodes you need to remove the Sort criteria, that can throw aggregation off.

---

I don't think your second question is making sense, you want to make a reference to a value calculated within views?

Entityreference creates a list of entities, and the summed up value is not an entity, you can't reference it like that. You can create a Views block and show the summed up value on some content pages and wherever you need it. Is that what you're after?
> 2 votes

---
Tags: views, 8
---


# Question
Title: How can I add a condition to the list of taxonomy a view is created from
I've created a view using a taxonomy term let's say (a,b,c,d,e)

A content type can have multiple selections of these taxonomy term.

The view returns the content-type based off the taxonomy term selected "Content: Has taxonomy term (exposed)"

From this, it also returns a select list of all the taxonomy terms.

Now in the taxonomy I have a custom field "hide from public". Terms "d" and "e" in the above list have this selected.

I would like to add a condition so that the view only returns the content type where "hide from public" is "false" and then the select list only shows the values where "hide from public" is false.

I can't add the condition if "hide from public" is false in the "Filter Criteria" because I believe it's checking for the Content-Type to have this value which it does not, so it returns nothing. How do I make the taxonomy list conditional?

Thanks!

# Answer
The reason why you can't add a Filter based on a Taxonomy field is because you're building a Content type views and that information simply isn't available directly from content tables in the database. If you were using Taxonomy term views then you could add that filter directly.

But since you have an entity reference from your Content to the Taxonomy term, it is possible to add that extra information into Content Views, so you will be able to Filter your Content based on a Taxonomy term Field that is on the taxonomy term that your nodes are referencing.

With **Relationships** in Views you're allowing Views to reach into other database tables and use data from them, if they are somehow related to the entities the view is based on.

Here's how you do it in your case:

1. Add a **Relationship** to the field in your content that is referencing your relevant Taxonomy **Taxonomy term referenced from field\_mytermref**

If you Require it, it will filter out only the nodes where that field isn't empty.
2. Add a Filter **hide from public**.

It will now be available in your Add Filter list because you added the Relationship in the above step, and that Relationship will be selected by default.

Adjust the Operator and Value so that it's not equal to Hide from public, or the other combination that it's equal to it being False.

Now your results will only show the nodes tagged with terms that are "public".
3. To adjust the Exposed filter the easiest is to use the **Limit list to selected items** option in its settings, and select only the terms you want to appear (Use the `Ctrl` key).
> 0 votes

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


# Question
Title: REST export with no data over it's localhost IP
I have a REST export which provides data with a call (curl or browser) to the Drupal URL(s). But we need to get these data over a curl to vhosts IP-Address and from this address, which is 192.168.34.11.

`curl http://drupal.url/view.json` from every other device and `curl http://192.168.34.11/view.json` from others in the same NAT works.

`curl http://192.168.34.11/view.json` local from 192.168.34.11 does not work. In this case I only get `[]`

There are no access or permission restrictions set in the view. We use the https://www.drupal.org/project/domain module and I have configured a domain 192.168.34.11.

Why isn't the view accessible over it's localhost IP address?

# Answer
OK, solved. The problem was the domain access module.

I got no output because I didn't set the domain access for all nodes except one. The one I got in ouput.

There is no default value for the domain access field in field configuration in node type configuration. And it's not comfortable to set the domain access values for every single node in node edit. So I needed to disable this module.
> 0 votes

---
Tags: 8
---


# Question
Title: Setting cache max-age to 0 has no effect on Block built using BlockBase?
I've built a custom block using `BlockBase` and as the content this block displays is different depending on the URL it's accessed via (a query parameter is passed in the URL) this block needs to either not cache, or cache relative only to the specific URL it's accessed using.

I've tried the following:

```
return array(
    '#theme' => 'testing_block',
    '#testBlockData' => $testBlockData,
    '#cache' => array(
        'contexts' => array('url.path'),
    ),
);

```

Which doesn't work. So then I tried this:

```
return array(
    '#theme' => 'testing_block',
    '#testBlockData' => $testBlockData,
    '#cache' => array(
        'max-age' => 0,
    ),
);

```

This also didn't work, so I tried the two cache settings combined together:

```
return array(
    '#theme' => 'testing_block',
    '#testBlockData' => $testBlockData,
    '#cache' => array(
        'contexts' => array('url.path'),
        'max-age' => 0,
    ),
);

```

None of these work, and I can't for the life of my figure out why. According to everything I've read, this is the right way to do it.

Is it actually possible to set a block like this not to cache in Drupal? And if so, what am I doing wrong?

# Answer
> 6 votes
This is a known problem for anonymous requests, see this issue PageCache caching uncacheable responses (violating HTTP/1.0 spec) + D8 intentionally disabling HTTP/1.0 proxies = WTF.

Until this is resolved, put this trigger in your block build():

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

# Answer
> 2 votes
we can implement this method in blockbase

```
/**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 0;
  }

```

# Answer
> 0 votes
I solved it mixing both solutions:

```
  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    \Drupal::service('page_cache_kill_switch')->trigger();

    return 0;
  }

```

---
Tags: 8, blocks, caching
---


# Question
Title: Disabling node editing after first node flagging
I use flagging for signing petitions. Petitions should be editable until the first signing (flagging) is done.

Now I look for a solution to disable node edition after first signing.

My first thought is doing it with Rules. I have access to flagging reactions, node type conditions but I have no action for editability of nodes.

Is there another way to get it done with Rules or something without it?

# Answer
> 0 votes
D7, no need of rules, place this code in your MODULE

```
function MODULE_node_access($node, $op, $account) {
 if ($op == 'update') {
  $flag='';
  $flag = flag_get_flag('YOUR_FLAG_MACHINE_NAME');
            if ($flag && $flag->is_flagged($node->nid, $GLOBALS['user']->uid)) {
  return NODE_ACCESS_DENY;
    }
  }
}

```

done, enyoy.

---
Tags: rules, flags
---


# Question
Title: Drush not connecting to site's settings.php
When I run `drush --debug status` in the docroot of my Drupal site, I get the following message:

```
[user@computer]$ drush --debug status
Phar detected. Proceeding to drush_main().
Loading drushrc "/home/user/.drush/drushrc.php" into "home.drush"[bootstrap]
scope. [0.02 sec, 3.54 MB]
Cache HIT cid: 8.1.14-commandfiles-removed    [debug]
[0.03 sec, 3.59 MB]
Bootstrap to phase 0. [0.28 sec, 9.55 MB]                            [bootstrap]
Trying to bootstrap as far as we can. [0.28 sec, 9.56 MB]                [debug]
Found command: core-status (commandfile=core) [0.28 sec, 9.56 MB]    [bootstrap]
Loading outputformat engine. [0.28 sec, 9.56 MB]                        [notice]
Calling hook drush_core_status [0.29 sec, 9.85 MB]                       [debug]
Returned from hook drush_core_status [0.38 sec, 9.86 MB]
         [debug]
 PHP configuration      :  /etc/php.ini /home/user/.drush/drush.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.14
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /home/user/.drush/aliases.drushrc.php
Command dispatch complete [x.xx sec, x.xx MB]                           [notice]

```

As you may see in that output, "PHP Configuration" has two entries where as "Drush configuration" has none. And that one of the entries for "PHP Configuration" looks like the entry that should be in "Drush configuration".

I did run it within the docroot of Drupal. And I have even tried in sites/default. Plus, I have even tried my aliases and none of them are working. This all worked before though with another Drupal site. It just stopped working after I transferred the Drupal files from one server to another. I thought my permissions were correct but they don't look correct. Plus I have even tried adding --uri and --root to Drush and that didn't work either. For the transfer I used rsync options `avzp`.

`drush -d pm-info` give's the following:

```
[user@computer]$ drush -d pm-info
Phar detected. Proceeding to drush_main().
Loading drushrc "/home/user/.drush/drushrc.php" into "home.drush"[bootstrap]
scope. [0.02 sec, 3.54 MB]
Cache HIT cid: 8.1.14-commandfiles-removed    [debug] [0.03 sec, 3.59 MB]
Bootstrap to phase 0. [0.27 sec, 9.55 MB]                                              [bootstrap]
Bootstrap to phase 6. [0.28 sec, 9.56 MB]                              [bootstrap]
Command pm-info needs a higher bootstrap level to run - you will need[error]
to invoke drush from a more functional Drupal environment to run this
command. [0.28 sec, 9.56 MB]
The drush command 'pm-info' could not be executed. [0.28 sec, 9.56   [error]
MB]

```

# Answer
Changing the ownership of the some of the files in the `sites` directory seems to have fixed the issue.
> 0 votes

---
Tags: drush, configuration
---


# Question
Title: String passed to the T function in inline_template not accessible for translation
For a custom field I have a formatter:

```
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $value = unserialize($item->value);
      $elements[$delta] = [
        '#type' => 'inline_template',
        '#template' => "{{ 'translate_me'|t }} {% for key,value in info %}  {{ key|t }}  : {{ value }} <br/> {% endfor %}",
        '#context' => ['info' => $value],
      ];
    }
    return $elements;
  }

```

I tried to search for the string "translate\_me" on `admin/config/regional/translate` to translate it but cannot find it. I did clear the cache, run the cron, ensure the module the define the string has a version, and **viewed the node in the target language**. but to no avail. What am I missing?

Thank

# Answer
This was caused by the configuration for language detection and selection configuration at `admin/config/regional/language/detection`.

For the `t()` function to work, the language detection and selection for the user interface must be set to "*Language from the URL (Path prefix or domain)*". There is an issue on drupal.org that may address this one.
> 1 votes

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


# Question
Title: Why do I get "Command pm-disable needs a higher bootstrap level to run"?
Running `drush dis varnish` in the Drupal directory gives give me this message.

> Command pm-disable needs a higher bootstrap level to run.

Running `drush --debug dis varnish -y` gives the following output.

> Phar detected. Proceeding to drush\_main().
> Loading drushrc "/home/user/.drush/drushrc.php" into "home.drush" scope. \> Cache HIT cid: 8.1.14-commandfiles-0-erased
> Bootstrap to phase 0.
> Bootstrap to phase 6.
> Drush bootstrap phase: bootstrap\_drupal\_root()
> Initialized Drupal 7.59 root directory at /usr/share/www/Drupal
> Find command files for phase 1 (max=6)
> Cache HIT cid: 8.1.14-commandfiles-1-erased
> Cache HIT cid: 8.1.14-annotationfiles-1-erased
> Drush bootstrap phase: bootstrap\_drupal\_site()
> Initialized Drupal site default at sites/default
> Find command files for phase 2 (max=6)
> Drush bootstrap phase: bootstrap\_drupal\_configuration()
> Find command files for phase 3 (max=6)
> sql-query: SELECT 1;
> Executing: mysql --defaults-extra-file=/tmp/drush\_erased --database=dune --host=localhost --silent \< /tmp/drush\_erased
> sql-query: SHOW TABLES;
> Executing: mysql --defaults-extra-file=/tmp/drush\_erased --database=dune --host=localhost --silent \< /tmp/drush\_erased
> Bootstrap to phase 1.
> Bootstrap to phase 6.
> Bootstrap to phase 5.
> Command pm-disable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
> The drush command 'dis varnish' could not be executed.

`drush status` and `drush updb` work. The output of the first command is the following one.

```
Drupal version         :  7.59
Site URI               :  http://default
Database driver        :  mysql
Database hostname      :  localhost
Database port          :
Database username      :  drupaluser
Database name          :  dune
PHP configuration      :  /etc/php.ini /home/user/.drush/drush.ini
PHP OS                 :  Linux
Drush script           :  /usr/local/bin/drush
Drush version          :  8.1.14
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :  /home/user/.drush/aliases.drushrc.php
Drupal root            :  /usr/share/www/Drupal
Drupal Settings File   :  sites/default/settings.php
Site path              :  sites/default

```

# Answer
This generally means that drush can't identify the site information, e.g. which settings.php to use.

A quick fix is to cd into the directory with the setting.php file for the site.

A more permanent fix is to create a site specific drush alias for the site and use it. E.g. drush @mysite dis varnish. See this Drupal page.
> 1 votes

---
Tags: 7, drush
---


title: Change the default language of a node

text:
# Question
Title: Change the default language of a node
Given that I have a node in English as default language and Danish as a translation, is it possible to set the Danish translation as default language for the node?

# Answer
> 6 votes
Of course.

I would do it this way:

1) Install of module devel. Drupal7

2) go to drupal/devel/php Of course.

Drupal8

3. in the textarea add:

> //please, change the nid of your node

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

$nid = 1;
$node = Node::load($nid);
$node->get('langcode')->value = 'da';
$node->save();

```

In Drupal7

```
$nid=1;
$node=node_load($nid);
$node->language='da';
node_save($node);

```

# Answer
> 1 votes
After some looking around, I discovered that you can change the language, as long as there are no other translations on that language.

Therefore, what you can do is

* Backup your content
* Delete the non-default translation
* Edit your node, now under "Language" you should be able to choose the other language as well
* Select the language you want and then Save

Now your node should have the other language as a default for your node and you can swap the two translations.

This solution is a bit of a hassle since you need to keep a backup for each translation in order to swap them afterwards, but at least there is no code involved.

Finally just to add that even if you try and alter the `langcode` of the node, it will not allow you to do so if there is an existing translation for that language so still you do not avoid deleting it.

---
Tags: 8, nodes
---


# Question
Title: Where should I place hook_block_view_alter?
this may be a trivial question, but I have no clue to how to get this working. I have this theme 'nexus'. When try the hook

```
function nexus_preprocess_block(&$variables)

```

in the file nexus.theme, it works,

but `function nexus_block_view_alter(&$data, $block)` doesn't.

Should I put it in a module? I tried creating a module using hello\_world example, and put in the the module's controller but no avail.

Any hint would be much helpful.

# Answer
> 1 votes
In drupal 8 the declaration of `hook_block_view_alter` changed from `hook_block_view_alter(&$data, $block)` (Drupal7) to `hook_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block)` (Drupal 8).
For more info check hook\_block\_view\_alter Documentation page.

`hook_block_view_alter` be better in custom module not theme, see guide to building basic Drupal 8 module, and flush all caches.

# Answer
> 0 votes
While normally the alter hooks are invoked also when they are implemented from the theme used to render the page, there are cases where this doesn't happen. The method that invokes `hook_entity_view()`, `hook_entity_view_alter()`, `hook_ENTITY_TYPE_view()`, and `hook_ENTITY_TYPE_view_alter()`, `EntityViewBuilder::buildMultiple()`, invokes only module hooks.

```
  $this->moduleHandler()->invokeAll($view_hook, [
    &$build_list[$key],
    $entity,
    $display,
    $view_mode,
  ]);
  $this->moduleHandler()->invokeAll('entity_view', [
    &$build_list[$key],
    $entity,
    $display,
    $view_mode,
  ]);

  // ...

  // Allow modules to modify the render array.
  $this->moduleHandler()->alter([$view_hook, 'entity_view', ], $build_list[$key], $entity, $display);

```

In a theme, you can implement `hook_preprocess_block()`, but the other hooks require a module.

---
Tags: 8, blocks
---


# Question
Title: Cannot deal with multiple iterations of same form on one page
I am designing a site that has a variety of points in which I need to render "workflow" buttons that are used to send actions to an external application.

I used the form API to generate these buttons, and am using the #submit =\> option on my buttons to direct specific button types to custom functions. I am also using hidden fields to house data that I use to facilitate the action.

The problem I am having is that these buttons can and should show up multiple times per page, for different aspects of the application, and whenever I click one of the buttons Drupal attempts to submit all of the forms.

I guess what i am asking is, how can I have multiple instances of the exact same form on screen at any given time, and know with certainty that the submit buttons are only going to trigger actions for the specific instance of the form they belong to?

thanks in advance!!

**Edit**

So here is the crux of the problem - it appears that the getFormId needs to return a unique value, but I cannot figure out how to pass unique values into it.

# Answer
Yes, each form must have a unique form ID. See https://www.drupal.org/node/766146 and the comments there.

You need to find something that uniquely identifies each form and put that in the form ID.
As commented there, that can be a bit tricky as `getFormId()` is called very early, so you need to instantiate the form object yourself and pass it to the form builder.

See FormBuilder::getFormId() for what happens when you pass in a string, it is passed to `$this->classResolver->getInstanceFromDefinition($form_arg);`, that creates the object and uses the create() method if available, you can use that or just do it yourself with a new Object(), then pass that to getForm() instead.
> 6 votes

# Answer
You could also add something like this to your form class

```
 /**
  * Keep track of how many times the form
  * is placed on a page.
  *
  * @var int
  */
protected static $instanceId;

/**
 * {@inheritdoc}
 */
public function getFormId() {
  if (empty(self::$instanceId)) {
    self::$instanceId = 1;
  }
  else {
    self::$instanceId++;
  }

  return 'my_form_id_' . self::$instanceId;
}

```
> 10 votes

---
Tags: 8, forms
---


# Question
Title: Why are Drupal hosting providers using Solr 3.x instead of 4.x or 5.x?
As of April 2016,

The current release of Solr is 5.5.0 (2016-2-20).

3.5 was released on November 25, 2011.

3.6 was released on April 11, 2012.

4.10 had its final release on October 14, 2015 (but it was first released on September 2, 2014).

Is there a reason to stick with 3.x vs. Solr 4 or 5? Search API Solr supports all three versions. Normally I would just use the latest version, but when major hosts that specialize in Drupal are on a version that is more than three years old, it makes me wonder.

# Answer
> 3 votes
It probably comes down to LTS and backwards compatibility, though you'd have to ask each organisation for their specific motivation.

Solr 5 is not backwards compatible with 4, 4 is not BC with 3. So if there are users on legacy systems using older versions, upgrading would require all customers to upgrade their schema/integration too. Installing newer versions on new servers might mean customers can't migrate from one server to another, might break the generic model of system deployment, etc, etc.

Some companies will offer newer versions, but you'll probably find the older versions are always available too, otherwise the company is likely to have at least a few pretty irate customers when they switch it off.

Basically, if you tell someone that you're going to support a version of software for the foreseeable future, you have to do that. It's why so many shared hosting companies support obsolete versions of PHP - because the people hosting there have no intention of upgrading their code, but their sites still need to work.

There's no Drupal-specific reason (that I know of) to choose one version of Solr over another, as long as the contrib module you're using has support for that version.

# Answer
> 3 votes
There is one reason you would need newer Solr.

Older versions cannot parse Japanese because Japanese does not have spaces between words, so there is an open source parser called Kuromoji that can be installed to make Solr usable with Japanese content. Newer Solr versions like 5 and 6 include it in the Lucene project, but older versions require that you install it separately.

Pantheon, for example, will not install Kuromoji and will not allow you to use a higher version, so if you want the option of using Chinese, Japanese, or Korean content to appeal to those markets, you will have to maintain and host your own Solr elsewhere. This will mean additional hosting and support costs, paying extra for a static IP connection to your Solr, and more time spent on paperwork and maintenance.

---
Tags: search
---


# Question
Title: Entity Reference Filter: Filter users by role
I want to attach managers to site customers. I made Entity Reference "user-to-user" and now I want to select users only with role "Managers".

How can I make such filter?

# Answer
> 6 votes
As far I understood you want to see only "Managers" in Entity Reference widget on user add/edit page.

Entity reference widget can filter values by using "Views" module.

You can just create an "Entity reference view" and get all users with role "Manager" there.

Here is instruction for widget settings: https://drupal.stackexchange.com/a/38917/6309

# Answer
> 0 votes
Its Good To simple Alter you form, update the field options, Drupal did not provide a simple way to select a user by a role in the entity reference

```
feedback_form_events_node_form_alter(&$form, $form_state, $form_id) {

```

if($form\_id== 'events\_node\_form'){

```
   $form['event'] = array(
    '#type' => 'select',
    '#title' => t('Select Event'),
    '#options' => $event,
    '#required' => TRUE,
    '#prefix' => ' <li class="custom-select">',
    '#suffix' => '</li>',
);
  }

```

}

---
Tags: users, entities
---


title: Get route name from path with wildcard

text:
# Question
Title: Get route name from path with wildcard
we've wanted to implement a policy to consider some URLs as whitelist, I've provided a config form to admin to enter whitelist Urls, separated by newline, it must support `*` ( wildcard).

sample urls are

```
/user/*/edit
/coming-soon

```

and my implementation

```
$config = $config_factory->get('mint_coming_soon.softlaunchconfigadmin');

$white_route_list = $config->get('white_path_list');
$white_route_list = $white_route_list ? preg_split("/\\r\\n|\\r|\\n/", $white_route_list) : NULL;
$is_white_route = FALSE;
foreach ($white_route_list as $route) {
  $route_name = $this->pathValidator->getUrlIfValid($route);
  $route_name = $route_name ? $route_name->getRouteName() : NULL;
  drupal_set_message($route_name);
  $current_route_name = \Drupal::routeMatch()->getRouteName();
  if ($current_route_name == $route_name) {
    $is_white_route = TRUE;
    break;
  }
}

```

`$this->pathValidator->getUrlIfValid` **doesn't work on URLs with the wildcard**, my question is **how can I get the route name of Url which contains a wildcard?**

**Notice:** wildcard in this question is particularly `*`.

# Answer
> 4 votes
```
$pattern = '/user/*/edit';
$route_provider = \Drupal::service('router.route_provider');
$found_routes = $route_provider->getRoutesByPattern($pattern);
$route_names = [];
foreach ($found_routes as $route_name => $route_object) {
  $route_names[] = $route_name;
}

```

---
Tags: 8, routes
---


# Question
Title: Date of Birth in Views: Age is 1 day ahead of desired value
Drupal 7.15 with Date module version 7.x-2.6

Date, Date API, Date Views enabled.

I added a date of birth field to a content type, and added 'child' nodes with their dates of birth.

In Views, I want to see the age of the children, so in the View I have:

Configure field: Content: Date of birth

Formatter = Time ago

Display = Time ago

My problem is this.

Right now, it is Thursday 6 September 2012 1500

A person has Monday 7 September 2009 as their date of birth.

The 'time ago' is showing as 3 years 15 hours ago.

However in real life they haven't yet reached their third birthday, so I want the result to say 2 years until midnight tonight when the child becomes 3.

How can I fix this?

# Answer
The problem is that "Time ago" has no understanding of leap years so when it is calculating an interval it uses a "common year" which is 365 days.

If we go back 30 years ago from today (2018-11-08) to 1988-11-08 and then use a date time calculator we get 30 years exactly, OR 360 months, OR 10957 days.

If the "Time ago" was smart enough to subtract the years, following by the months, followed by the days then it would come up with 30 years, 0 months, and 0 days. The problem is that it does all of its math in days and then tries to convert to years.

10957/365 = 30.019 common years or 30 years and a week. This is because there was 7 leap years between 2018 and 1988...

So there isn't anything wrong per say. It is actually doing exactly what you asked it to do.

You can get much closer if you divide the date by 365.2425 which is the average length of the year of 365.25 which is defined as a Julian year. Julian years are used in astronomy.
> 1 votes

---
Tags: views, datetime
---


# Question
Title: How to embed a view or a rendered node into a field group
I'm afraid my question is a bit to general because I don't quite know where to start. I still really don't have my head wrapped around the drupal 7 theming system.

## Scenario

I have two content types:

1. `Type main`
2. `Type secondary` (this type has a required entity reference field, referencing `Type main`

The display on `Type main` has a set of 2 horizontal tabs htabs group named `group_expandables`.

## Desired Outcome

What I would like to happen is, if an entity of `Type secondary` has been added referencing this node; add a third horizontal tab containing the `Type secondary node` and make it the default.

## Initial Approach

These are the steps I thought through that should probably happen on page load for a node of `type Main`:

1. Look for a `Type secondary` node referencing this node, return if not found
2. If found, build up a new render array for the `Type secondary` node htab. I was thinking it would be easiest to build this display in views, and load in the view, but doing it in a template file would probably work too.
3. Once the variable has been for the new htab, insert it in the htabs render array and modify the render array to remove the open by default indicator on the old default tab.

So far I have used hook\_preprocess\_page to grab the `$variables['page']['content']['system_main']['nodes'][nid]['#fieldgroups']['group_expandables']` and add a new group name to its children, clone one of the htab field groups and append it to the `['#fieldgroups']` array, and modify the elements that referenced the old htab and replace them with the name for the new tab. Once I figured out that I needed an entry in `#group_children` too, I actually got the tab to appear in the group, but I haven't had any luck getting content to show up in it yet.

## Question

Here are the places I'm really hung up:

1. Is hook\_preprocess\_page the best place to start this?
2. Is my general strategy for how to go about this sound?
3. How would I build my desired content into the new htab?

I'm sorry for the broad nature of the question, any pointers would be greatly appreciated.

# Answer
> 1 votes
I'm not sure your general strategy is the absolute best way to go, but I don't see any major problems, I think `hook_preprocess_page` is too broad as it runs everywhere and would suggest template\_preprocess\_node instead (even though this is a template preprocess it can be run like a normal hook preprocess in a module)

In regards to getting the content you will need to do a EntityFieldQuery using the `nid` of the page being viewed as a `fieldCondition`, the only problem I can see is when there is more than one secondary type assigned to the same main type.

An alternative approach would be to see whether it's possible to write a View which takes the `nid` as a Contextual Filter and then builds all the content, I think you'd need to add a Relatonship to the secondary type, etc. and if it's possible this would cut down on the amount of custom coding needed.

---
Tags: 7, theming
---


# Question
Title: disabled="disabled" on a checkbox entity field
I can't seem to figure out how to make checkbox field on my entity display as disabled in the admin form area. Looked in Drupal 8s "documentation" but couldn't seem to find anything on it.

I tried variations on the code below but nothing seemed to work. Any help is appreciated. Thank you.

```
$fields['some_field'] = BaseFieldDefinition::create('boolean')
 ->setLabel(t('Some Field'))
 ->setDescription(t('A Field description'))
 ->setReadOnly(TRUE)
 ->setRevisionable(FALSE)
 ->setDefaultValue(FALSE)
 ->setDisplayOptions('form', [
   'type' => 'boolean_checkbox',
   'attributes' => array(
    'disabled' => true,
   ),
   'weight' => 0,
]);

```

# Answer
The BooleanCheckboxWidget has no settings for HTML attributes. You either have to create your own Widget or use `hook_field_widget_WIDGET_TYPE_form_alter` to add the disabled attribute.

Not tested personally, but you might also take a look at the Read-only Field Widget, could save you some coding: `setDisplayOptions('form', ['type' => 'readonly_field_widget', ...])`
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Using Drupal 8's Migrate API, how can I map a nested (hierarchical) taxonomy term to the imported entity?
We have a vocabulary of nested (hierarchical) category terms on a site and are using the Migrate API (via CSV) to import product entities that each have a category term.

The problem is that some of the nested term names are repeated so the importer would not know which nested term to use. For example:

PARENT 1--Child 1 PARENT 1--Child 2 PARENT 2--Child 1 PARENT 2--Child 2

As you can see, the term "Child 1" is used twice, but with different parents.

I can see two possible solutions but I don't know how to go about achieving them. So any help would be appreciated.

1) Would it be possible to include the hierarchy in a delimited field on the CSV and let Migrate create and nest all of the terms and then map the product entity term referring to the last term automatically.

For example. "Parent 1, Child, 1, Child 2"

2) Or, using a source plugin and TWO fields on the CSV, where one is the product category term and the other field is the parent and somehow have Migrate know which parent term ID to use for the category?

Currently, the category YML looks like this:

```
 field_prod_category:
    -
      plugin: explode
      source: WebCategory1
      delimiter: ','
    -
      plugin: entity_generate
      source:
      value_key: name
      bundle: product_categories
      entity_type: taxonomy_term
      ignore_case: true

```

# Answer
On my project, I created a group migration with two migrations

* **taxonomy** migration all taxonomy term.
* **taxonomy\_parent** update parent for terms have parent.

There are example code (I use the embedded\_data source plugin for the sake of simplicity so that this example can be copy-pasted as a working example ) and source like that:

Migration group: **migrate\_plus.migration\_group.taxonomy.yml**

```
id: taxonomy
label: Import Taxonmy
description: Import Taxonomy.

```

Migration all term: **migrate\_plus.migration.taxonomy.yml**

```
id: taxonomy
label: Import term taxonomy
migration_group: taxonomy
source:
  plugin: embedded_data
  data_rows:
    -
      id: 1
      name: 'Parent 1'
    -
      id: 2
      name: 'Children 1'
    -
      id: 3
      name: 'Children 2'
    -
      id: 4
      name: 'Children children 1'
  ids:
    id:
      type: integer
destination:
  plugin: entity:taxonomy_term
  default_bundle: custom_taxonomy
process:
  name: name

```

Set parent for term: **migrate\_plus.migration.taxonomy\_parent.yml**

```
id: taxonomy_parent
label: Set parent taxonomy
migration_group: taxonomy
source:
  plugin: embedded_data
  data_rows:
    -
      id: 2
      parent: 1
    -
      id: 3
      parent: 1
    -
      id: 4
      parent: 2
  ids:
    id:
      type: integer
destination:
  plugin: entity:taxonomy_term
  default_bundle: custom_taxonomy
  overwrite_properties:
    - parent
process:
  tid:
    plugin: migration_lookup
    migration: taxonomy
    source: id
  pid:
    plugin: migration_lookup
    migration: taxonomy
    source: parent
  parent: '@pid'

```

and result:
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: Is there a way to change Views base table dynamically?
I have a couple of Search API indexes for different server environments (test, qa, uat, prod) with different configurations.

Instead of create 4 views in the admin, I just want to use one, and depending on environment, swap the base table (index). That way I can have one view at one URL.

Is that possible in Drupal 8?

# Answer
> 0 votes
Just use configs overrides services like described here https://www.drupal.org/docs/8/api/configuration-api/configuration-override-system

Example:

```
if (in_array('views.view.config.name', $names)) {
  $overrides['views.view.config.name'] = ['base_table' => 'your_base_table'];
}

```

---
Tags: views, 8, search
---


# Question
Title: Alter Multiple Field Values by Testing "Field Type"
Drupal 8.x

I would like to alter the value of all/any ckeditor/text fields on a node.

Currently working with HOOK\_node\_presave().

Ideally, I'd like an agnostic approach that doesn't mind where the field is coming from, e.g. paragraph, node, taxonomy, etc.

How can I loop through all fields, check the field type, get and replace the value?

---

**MYMODULE.module**

Working with the below code gets me close I think:

```
use Drupal\Core\Entity\EntityInterface;

function MYMODULE_node_presave(EntityInterface $entity) {
  $fieldsArray = \Drupal::service('entity_field.manager')->getFieldMapByFieldType('text_long');

  foreach($fieldsArray as $longTextName=>$key) {

    kpr($key); // This returns an array of the values I need.
    if ($entity->hasField($key)) {
      $entity->get($result)->value = preg_replace(
        $toReplace,
        $replaceWith,
        $entity->get($result)->value
      );
    }
  }

}

```

---

Try #2;

```
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_presave(EntityInterface $entity) {
  // Get form config.
  // Get config Node field names.
  // Get config Paragraph names.
  // Get config Paraghraph field names.

  // Loop through our Node field names.
  foreach($nodeFieldNames as $fieldName) {
    // Check if the entity has field.
    if ($entity->hasField($fieldName)) {
      // Get the field.
      $entity->get($fieldName)->value = $newValue;
    }
  }

  // Loop through our Paragraph names.
  foreach($paragraphNames as $paragraphName) {
  // Check if the entity has field.
  if ($entity->hasField($paragraphName)) {
    $paragraphs = $entity->$paragraphName->getValue();
    foreach ($paragraphs as $paragraphItem) {
      $p = \Drupal\paragraphs\Entity\Paragraph::load( $paragraphItem['target_id'] );
      foreach($paragraphFieldNames as $paragraphFieldNamesitem) {
        if ($p->get($paragraphFieldNamesitem)->value) {
          // kpr($p->get($paragraphFieldNamesitem)->value);
          $p->get($paragraphFieldNamesitem)->value = $newvalue;
          // kpr($p->get($paragraphFieldNamesitem)->value);
          // This does alter the value, just does not get saved.
        }
      }
    }
  }
}

```

# Answer
You can use FieldConfigInterface to get fields info.
Try the following:

```
use Drupal\Core\Field\FieldConfigInterface;

function MYMODULE_node_presave($node) {
  //- Call helper function to get all the fields
  $fieldsArray = getContentTypeFields($node->bundle());
  //- Loop through fields
  foreach ($fieldsArray as $fieldName => $fieldConfig) {
    ///- Example to check if type is text_with_summary
    if ($fieldConfig->getType() == 'text_with_summary') {
      /**
       * @TODO : Something here for field of type text_with_summary
       */
    }
  }
}

/**
 * Helper function to Get all fields of content type:
 *
 * @param $contentType
 *
 * @return array
 */
function getContentTypeFields($contentType) {
  $entityManager = Drupal::service('entity.manager');
  $fields = [];
  if (!empty($contentType)) {
    $fields = array_filter(
      $entityManager->getFieldDefinitions('node', $contentType), function ($field_definition) {
      return $field_definition instanceof FieldConfigInterface;
    }
    );
  }

  return $fields;
}

```
> 1 votes

---
Tags: 8, hooks
---


# Question
Title: Programmatically render a custom form in a view template while passing view argument to form
I have built a custom form (in its own module using FORM API) and have exposed this form also as a block using Plugin API.

I can add this form fine to page and get it to render using Block Layout but it doesnt appear in the correct place.

I am trying to get it to appear in the main page content of a `Page View` which has a Header and Footer. The form seems to appear after the footer content, even after shifting the block around in the block layout.

So now I have been trying to use the various view template hooks by loading the form via the snippet:

```
$block = \Drupal\block\Entity\Block::load('auctioncataloguerequestform');
$block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
$variables['form_auction_cat_request'] = $block_content;

```

`auctioncataloguerequestform` is the machine name of the "form block" added to Block Layouts (Its in the content section, but disabled)

But in XDebug I cannot find the `form_auction_cat_request` variable and `{{ form_auction_cat_request }}` renders nothing.

Hooks I tried using where: `template_preprocess_views_view`, `template_preprocess_views_view_field` and `template_preprocess_views_view_unformatted`

At the moment I am simply trying to get the form to render but once this is done I then need to pass a `string` variable which is a field of the view in question to be passed to the form.

Am I on the right track or completely missing the mark?

View screenshot

# Answer
Print form before the views:

```
function mymodule_preprocess_views_view(&$variables) {
  $form = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\DefaultForm');
  $variables['attachment_before'][] = $form;
}

```

===

Another way is to add your custom form and the views in own controller (and route),

In views add filters and expose them, set exposed in block = yes (this will detach the form from the views),

in exposed filters settings set the names as they are in your form - for each one,

make your form to redirect on submit to the route passing the values as query params (?param\_name=value&param\_name2=value2), for multiple select or checkboxes params are in format: param\_name\[6\]=6&param\_name\[17\]=17

the rest will be done by views - it will get params automatically

Controller:

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\views\Views;

/**
 * Class DefaultController.
 */
class DefaultController extends ControllerBase {

  /**
   * Content.
   *
   * @return string
   *   Return Content string.
   */
  public function content() {

    $elements = [];

    $elements['form_search'] = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\DefaultForm');
    $elements['form_search']['#weight'] = 0;

    $views_name = 'machine_views_name';
    $display_id = 'page_1';
    $view = Views::getView($views_name);
    $view->setDisplay($display_id);

    $elements['view'] = $view->render($display_id);
    $elements['view']['#weight'] = 1;

    return $elements;
  }

}

```

example module with controller, form and exported views "Content list": https://github.com/svetlio/mymodule
> 3 votes

---
Tags: views, theming, forms
---


# Question
Title: How to do a hard redirect when in Ajaxified form?
I have an Ajax multistep form and I want to redirect user to specific route when some conditions are met (specifically if the user is inactive for more than N seconds and the form is submitted after this limit).

I wanted to do the redirection in the validation handler but no luck. So I tried with a submit handler but still no luck. I'm quite buffled.

I tried to return a redirect response, I tried to set redirect response on the form state, I tried to set redirect on the form state, I have tried to disable form state rebuild, I have tried to copy the goto action logic and use an event dispatcher, I tried to unset the `\Drupal\Core\Form\FormBuilderInterface::AJAX_FORM_REQUEST` from request but still no luck.

I could maybe return the redirect in an Ajax callback as redirect command but I want to make this work with disabled JS so invoking `window.location` would not be enough.

# Answer
> 4 votes
After **quite** some experimenting I have came to this working solution.

The condition has to be in the beginning of the submit handler:

```
  if ($condition) {
    $form_state->setRedirect('foo.bar')->disableRedirect(FALSE)->setRebuild(FALSE);
    // Return here so the code that activates form rebuilding for ajax or any data processing logic is not invoked.
    return;
  }

```

And the ajax callback has to be formatted like this:

```
public static function ajaxRebuildForm(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Form\FormSubmitterInterface $submitted */
    $submitter = \Drupal::service('form_submitter');
    /** @var \Symfony\Component\HttpFoundation\RedirectResponse $redirect */
    $redirect = $submitter->redirectForm($form_state);
    if ($redirect) {
      return (new AjaxResponse())->addCommand(new RedirectCommand($redirect->getTargetUrl()));
    }

    return $form;
  }

```

This is working for both js-enabled and js-disabled environment. If JS is enabled the ajax callback will detect the set redirection and return ajax response with redirect command instead of render array(which is internally turned into ajax response as well). If the js is disabled the redirect is handled as redirect response when form is submitted.

---

Edit: I have found that this is not 100% working solution. I have a route controller that either returns the form or perofrms redirect. Once I'm in the ajaxified form and the controller does the redirect(ie. some conditions were un/met) I'm stuck on the form and cannot do anything since the ajax callback is not triggered so I am basically doing requests to page that returns redirects and no form logic is invoked anymore. Which means I have to implement additional logic, again, into the controller, not just the form, since the form API won' have a chance to get invoked and process the form in the first place.

I had to implement this in my controller:

```
  if ($request->request->get(AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER)) {
    return (new AjaxResponse())
      ->addCommand(
        new RedirectCommand(
          $this->redirect(
            $this->currentRouteMatch->getRouteName()
          )->getTargetUrl()
        )
      );
  }

```

# Answer
> 15 votes
In my case (D8), I just had to implement the RedirectCommand in my AjaxSubmit :

Code of the submit button :

```
$form['submit_' . $this->uniqueIdentifier] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes' => [
    'class' => ['btn', 'btn-primary']
  ],
  '#ajax' => [
    'callback' => [$this, 'submitModalFormAjax'],
    'event' => 'click',
  ],
];

```

Code of the submit callback:

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

  if ($form_state->hasAnyErrors()) {
    // Do validation stuff here
    // ex: $response->addCommand(new ReplaceCommand... on error fields
  }

  else {
    // Do submit stuff here

    $url = Url::fromRoute('page_route');
    $command = new RedirectCommand($url->toString());
    $response->addCommand($command);
  }

  return $response;
}

```

Do not forget to declare :

```
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Url;

```

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


# Question
Title: How do I add a color hex code field to a product attribute using drupal commerce 2?
How to add a color hex code field to a product attribute using drupal commerce 2

I can add the form field but do not know how to create the field type: color or the corresponding hex code.

Thanks

# Answer
> 3 votes
For anyone else grappling with this issue in future here is what I did:

\****How to add a color hex code field to a product attribute using drupal commerce 2\****

*see also: https://drupalcommerce.org/blog/44310/enabling-fancy-attributes-commerce-2x*

Use the Color Field module to add a color field to your Color attribute. https://www.drupal.org/project/color\_field

Install with Composer: $ composer require 'drupal/color\_field:2.x-dev'

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Product Attributes \>\> Add Colour Attribute \>\> Manage Fields

Add:

Label: Color Hex Code

Machine Name: field\_color\_hex\_code

Field type: color

DEFAULT VALUE The default value for this field, used when creating new content.

COLOR HEX CODE

Color #D3D3D3

Opacity 1

Record Opacity Ticked

FIELD SETTINGS TAB

Format storage #123ABC Choose how to store the color.

Allowed number of values: Limited 1

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Product Attributes \>\> Add Colour Attribute \>\> Manage form display

FIELD WIDGET

Name Textfield textfield size: 60

Color Hex Code Color default No placeholder

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Product Attributes \>\> Add Colour Attribute \>\> Manage display

FIELD LABEL FORMAT

Color Hex Code Hidden Color Swatch Square Width: 40 Height: 40

Note: Remember to change the attribute selection widget to use the rendered option for your attribute.

---
Tags: commerce
---


# Question
Title: Guidelines on customisation options when using hook_views_default_views?
Are there any good instructions for the customisation options available when creating a default Views files using hook\_views\_default\_views()?

The API for the function can be found here: http://api.drupal.org/api/views/views.api.php/function/hook\_views\_default\_views/7

However I have yet to find any explicit information on the values that can be used and the options that are available when using the display\_options array.

As an aside, here is an example where the lack of instruction become a problem for a novice Drupal developer: it's hard to know what to put for:

```
$handler->display->display_options['access']['type'] = 'none';

```

Do you add just add the name of a permission, or a role, if you want to restrict access? Is this even what the option means?

# Answer
> 5 votes
There is one neat and simple way. Create view normally, using GUI. Then export it. I created view `default-demo` for demonstration purposes:

http://example.org/admin/structure/views/view/default\_demo/export

gives:

```
$view = new view();
$view->name = 'default_demo';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'default demo';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially     */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'default demo';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'default-demo';
$translatables['default_demo'] = array(
  t('Master'),
  t('default demo'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Page'),
);

```

As you can see that's exactly what you would want to put into hook\_views\_default\_views function. Simple as this :D

If you can't find export link, it's at top right, drop down `edit view name/description` to see it.

Everything available from code is supposed to be available from GUI too, with the notable exceptions of `$view->core` and `$view->api_version` that are always set by gui to the current release and must match what you set in hook\_views\_api() in your module.

For specific line you asked for:

```
$handler->display->display_options['access']['type'] = 'none';

```

You need to go to `Page Settings > Access`, set things as you want them, export view. Done. It seems that Views developers chooses to use their time to give us tools, not documentation, when their time is limited, but the tools they give us are comprehensive.

# Answer
> 1 votes
The modular way in which views is written is very clever and interesting, yet a little daunting the first few times :). I am afraid the only option here is going through the code (with some patience and grep :). Also some interesting info is written in the advanced help for views, people tend to forget about it.
Basically : any display can define any options, some of them are common. The options are defined in special hooks in the displays (check the plugins folder under views).
Access is slightly more complicated, because it is a plugin in a plugin :). So basically in the type option you select one of the available plugins (and you can write your own) and the plugin sets the values for the other options. The default access plugins are `'none' 'role' and 'perm'`.
Another way to find these 3 values out is to check the source of the form, ofcourse.

# Answer
> 0 votes
Regarding the original poster's question about details of the Views API in terms of adding access permissions to Views:

```
$handler->display->display_options['access']['type'] = 'none';

```

The default perm given to a new view is:

```
$handler->display->display_options['access']['type'] = 'perm';

```

What I found confusing when trying to figure out how Views works is that the view definition will not explicitly identify which perm is actually required if the default perm is left in place: "View published content" (whose machine name is 'access content').

However, if the perm required for access is anything but "View published content" then there will need to be another line in the views definition like this:

```
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'administer comments';

```

The perm name used in the Views definition is the perm's machine name (which does allow spaces unlike other machine names in Drupal).

To find the machine name of a perm: install and enable the Devel module. Then go to: `Configuration => Development => Devel settings (/admin/config/development/devel)` and tick on the checkbox `Display machine names of permissions and modules`. Then you go to the permissions page and hover over the perm you want.

Or you can just use the Views UI to select the perm, then export the View and then you can see its machine name in the exported code.

---
Tags: 7, views, hooks
---


# Question
Title: How to have a field with a select list widget and custom list entries?
In my content type there is a text field that is set using a list (combobox).

When adding new content, the list is displayed with static elements.

I would like to query an external site when the user adds content (or edits the page) and then build the list from the query result. The user can then select from these elements.

Is that possible?

# Answer
**For Drupal 8**

Yes, is possible, but you will need to implement your own field type.

You should take a look into the Country module as you will need to implement the OptionsProviderInterface interface.

In the getPossibleOptions method, you will query the external site and get the possible options for your field.

**For Drupal 7**

You can always take a look inside the Examples module even for Drupal 8 you will find a very useful boilerplate code for your projects. If you want to check another example just go to the Countries module.
> 3 votes

---
Tags: 7, nodes
---


title: SQL query to CSV

text:
# Question
Title: SQL query to CSV
I'm doing some queries on my Drupal site using the `drush sql-query` command. I'd like to export the results to a CSV. Is it possible to do this via the command options, some plugin, or some other alternative method?

# Answer
> 2 votes
The awk part should be like this

```
drush sqlq "SELECT nid, title, alias from node
LEFT JOIN url_alias ON url_alias.source = CONCAT('node/', node.nid)
LEFT JOIN field_data_field_myfield ON node.nid = field_data_field_myfield.entity_id
WHERE type = 'blog' AND field_data_field_myfield.entity_id IS NULL;"| awk 'BEGIN { FS = "\t"} ; {print "\""$1"\",\""$2"\",\""$3"\""}' > output.csv

```

# Answer
> 3 votes
I found it easiest to export the results to .tsv format

* D7: `drush sql-query "SELECT nid, title FROM node LIMIT 10" > nid-title.tsv`
* D8: `drush sql-query "SELECT nid, title FROM node_field_data LIMIT 10" > nid-title.tsv`

You could also convert TSV to CSV from the linux terminal with something like:

```
cat nid-title.tsv | tr "\\t" "," > nid-title.csv

```

or with an editor like Libre Offic Calc: open .tsv, save as .csv

---
Tags: database, drush, importing-exporting
---


title: Passing Image through hook

text:
# Question
Title: Passing Image through hook
# Background:

Im working in Drupal 8 and I have a paragraph type that contains a title and an image and I am trying to pass it through the preprocessor hook so I can set it inside a html template. For testing purposes all I have on my template is div that calls the image variable. Im more worried about the pre\_processor than I am the html

# Code:

```
function theme_preprocess_node(&$variables) {
  if ($variables['node']->getType() == 'landing_page') {
    $paragraphs = $variables['node']->field_section->getValue();
    $section = [];
    foreach ($paragraphs as $key => $paragraph) {
      $p = Paragraph::load($paragraph['target_id']);

      echo "<pre>".print_r($p,TRUE)."</pre>";

      switch ($p->getType()) {
        case 'tabbed_body':
          foreach ($p->field_body_tab_content->getValue() as $tab) {
            $t = Paragraph::load($tab['target_id']);
            $title = $t->field_body_tab_title->getValue();
            $content = $t->field_tab_content->getValue();
            $image = $t->field_body_image->getValue();
            $section[$key]['tabbed_body'][] = [
              'title' => $title[0]['value'],
              'content' => $content[0]['value'],
              'image' => $image[0],
            ];
          }
          break;
      }
    }
    $variables['sections'] = $section;
   }
}

```

Image Settings:

# Answer
You can pass only the image `uri`, and render image using it in the twig. Try the following suggestion: In your loop try to get image as the following:

```
  $image_field_values= $t->field_body_image->getValue();
  /**
   * @TODO: if you have multiple values loop through them i will test just by the first
   */
  $image_target_id = $image_field_values[0]['target_id'];
  $image_file = File::load($image_target_id);
  $section[$key]= [
    'image_uri' => $image_file->getFileUri()
  ];

```

In your twig will be something like:

```
<img src="{{ file_url(section[0]['image_uri'])}}" >

```

Don't forget `use Drupal\file\Entity\File;`.
> 0 votes

---
Tags: 8, theming, hooks, media, paragraphs
---


# Question
Title: how to use "views field view" for entity reference - Not taxonomy
I've got a view of "webinars," that contains an entity reference "speakers" that can have multiple entries. I can't get those entity references and their own fields into the listings for each webinar, correctly.

I've tried to do this with Views Field View module, but every tutorial shows Taxonomy ID is used. I can't. This isn't a taxonomy. I tried using Content ID, but it doesn't work. What the heck am I missing?

I want:

> WEBINAR 1
> speaker1, title, company
> speaker2, title, company
>
> WEBINAR 2
> speaker 2, title, company
> speaker 3, title, company

# Answer
> 2 votes
You don't need additional modules to introduce data from referenced entities into your views, you can do it with Relationships.

Your question title is about the Views field view module, but your question text reveals what you're really after, so I won't go into the Views field module solution because it's not the best way to go (performance-wise) if you can do it otherwise.

The Entityreference field on your "Webinar" nodes only lists titles of the "Speaker" entity, both on node pages and in Views.

To display information other than Title of the "Speaker" entities within "Webinar" views you have to add a Relationship through the entityreference field. That acts as a bridge to the other tables/data and makes them available for use within views.

In your case you should:

1. Add a Title field and the "Speaker" entityreference field for your "Webinar" nodes (you probably already have this step)
2. Edit the Speaker field and under `Multiple field settings` **untick `Display all values in the same row`**.

This will make every speaker display as a separate views row.
3. Add a Relationship **Content referenced from field\_speakers** (or whatever the field name is in your case), require it if you don't want to see webinars in your results that don't have any speakers selected
4. Add the "Speaker title" field, it will automatically use the above Relationship
5. Add the "Speaker company" field, it will automatically use the above Relationship
6. Under `Format` Settings set the **Grouping field Nr.1** to **Title** (the Webinar one).

This will take care of the way you want results grouped under each webinar title.
7. Edit the Title field (Webinar) and set it to **Exclude from display** and under `Style settings` set the **Customize field and label wrapper HTML** to **H2** or whatever makes the most sense in your case.

---
Tags: views, entities
---


title: Reindex Taxonomy URLs?

text:
# Question
Title: Reindex Taxonomy URLs?
I have a list of terms all with assigned URLs already. When I change the term and the URL, it is not updating.

I feel like there's a cache or reindexing needed ?

# Answer
Do you have change the taxonomy term name manually or the url alias? If you only have change the name you must to check the field "Generate automatic URL alias" is checked to change the url automatically.

If is checked or you have change URL alias manually then clear cache in /admin/config/development/performance

I hope that helps.
> 0 votes

---
Tags: taxonomy-terms
---


title: Refresh default migrations

text:
# Question
Title: Refresh default migrations
I done a migration of a website, but new content were created during I done that. So how can I refresh default migrations created by the drush command :

```
drush @alias  migrate-upgrade --legacy-db-url=mysql://user:pass@localhost/d6ce --legacy-root=http://d6-site.vmdev --configure-only

```

I know about the `update` option for `drush mim "migration"` but here, I need to recreate migration. Perhaps I just need to re-run the original command ?

Thanks

EDIT: the way seem to be:

```
- drush @alias mr "migration_name"(rollback migration)
 - drush @alias mrs "migration_name"(set to Idle)
 - drush @alias migrate-upgrade XXX (re-create migration)

```

EDIT2: I get an error on a content type:

```
Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '591' for key 'node__vid': INSERT   [error]
INTO {node} (nid, vid, type, uuid, langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3,
:db_insert_placeholder_4); Array
(
    [:db_insert_placeholder_0] => 494
    [:db_insert_placeholder_1] => 591
    [:db_insert_placeholder_2] => page_europe
    [:db_insert_placeholder_3] => 95cc248e-6c93-4cfa-ad29-b19db86425c5
    [:db_insert_placeholder_4] => fr
)
 in Drupal\Core\Database\Connection->handleQueryException() (line 683 of /var/www/drupal-8/core/lib/Drupal/Core/Database/Connection.php).
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '591' for key 'node__vid': INSERT INTO {node} (nid, vid, type, uuid, langcode) VALUES           [error]
(:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array
(
    [:db_insert_placeholder_0] => 494
    [:db_insert_placeholder_1] => 591
    [:db_insert_placeholder_2] => page_europe
    [:db_insert_placeholder_3] => 95cc248e-6c93-4cfa-ad29-b19db86425c5
    [:db_insert_placeholder_4] => fr
)
 (/var/www/drupal-8/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:783)
Processed 31 items (30 created, 0 updated, 1 failed, 0 ignored) - done with 'd6_node:page_europe'                                                                     [status]
d6_node:page_europe Migration - 1 failed.

```

With or without roolback...no issue on another content type.Related to taxonomy ? How can I fix that ? I notify that if I just run: drush @alias ms I get this kind of infos:

```
upgrade_d6_file      Idle  1521   1497      21         2018-10-29 14:57:40

```

So new files are mentionned and would be able to be imported as is with --update option ,not ?

# Answer
I needed something similar, I solved it by first making a rollback and then I launched the original command.

`drush mr`

You can find more information about the command on this link https://drushcommands.com/drush-8x/migrate/migrate-rollback/
> 0 votes

---
Tags: 8, migrations, updating
---


# Question
Title: How can I set a default value for the country in an addressfield?
I'm trying to set the default value for a country in an addressfield (caught in `hook_form_alter`) and ensure that the associated fields (administrative area, etc.) are refreshed properly. How can I do this?

# Answer
> 3 votes
Finally figured it out. The idea is to emulate the code in `addressfield_field_widget_form()`. Here's the recipe:

```
 /**
  * Implements hook_form_FORMID_alter() for `commerce_checkout_form_checkout`.
  */
 function mymodule_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
    // Get the addressfield element we're modifying.
    // Adapted from addressfield.module/addressfield_field_widget_form()
    $element =& $form['customer_profile_shipping']['commerce_customer_address'][LANGUAGE_NONE][0];
    $element_key = $element['element_key']['#value'];
    $field = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['field'];
    $instance = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['instance'];
    $delta = $element['#delta'];
    $settings = $instance['widget']['settings'];
    $langcode = $element['#language'];
    $items = array($delta => $element['#address']);

    // Get the default address used to build the widget form elements, looking
    // first in the form state, then in the stored value for the field, and then
    // in the default values of the instance.
    $address = array();

    if (!empty($form_state['addressfield'][$element_key])) {
      // Use the value from the form_state if available.
      $address = $form_state['addressfield'][$element_key];
    }
    elseif (!empty($items[$delta]['country'])) {
      // Else use the saved value for the field.
      $address = $items[$delta];
    }
    else {
      // Otherwise use the instance default.
      $address = (array) $instance['default_value'][0];
    }

    // Merge in default values to provide a value for every expected array key.
    $countries = _addressfield_country_options_list($field, $instance);
    $address += addressfield_default_values($countries);

    // Set our default country.
    // THAT'S THE PAYLOAD!
    if ($address['country'] != $my_default_country) {
      $address['country'] = $my_default_country;
      $address['administrative_area'] = '';
    }

    // Add the form elements for the standard widget, which includes a country
    // select list at the top that reloads the available address elements when the
    // country is changed.
    if ($instance['widget']['type'] == 'addressfield_standard') {
      // Generate the address form.
      $context = array(
        'mode' => 'form',
        'field' => $field,
        'instance' => $instance,
        'langcode' => $langcode,
        'delta' => $delta,
      );
      $element = array_merge($element, addressfield_generate($address, $settings['format_handlers'], $context));

      // Mark the form element as required if necessary.
      $element['#required'] = $delta == 0 && $instance['required'];
    }
  }

```

# Answer
> 1 votes
The problem that I ran into, is that I could set the default values by doing the following...

If making use of the commerce module, you can load the entity, and access the address values using the following code

```
$address_info_profile = commerce_customer_profile_load($profile_id);
$address_info = $address_info_profile->commerce_customer_address[LANGUAGE_NONE][0];

```

$address\_info now contains all of the default values, with $address\_info\['country'\] containing the country code.

Now, you can set the default values for an addressfield widget using the following code

```
$form['commerce_customer_address'][LANGUAGE_NONE][0]['#address'] = $address_info;

```

#address is the important part, as that is where the default values are set.

Another problem arises if you allow for multiple countries. If your websites default country is Canada (CA) as my client is, and your profile is for United States (US), you run into an issue with the widget loading the correct default country, but the 'administrative\_area' shows the wrong #title, and the wrong #options. The have it show the States, you have to select a different country, and back to United States.

Furthermore, those requests are handled via #ajax, so you want this to happen only once.

The result I came up with is as follows. I am leaving in the comments to assist others

```
//verification that we have a default value to work with
if (isset($address_info_profile->commerce_customer_address) &&
    isset($address_info_profile->commerce_customer_address[LANGUAGE_NONE]) &&
    count($address_info_profile->commerce_customer_address[LANGUAGE_NONE]) > 0) {

  //obtain the default address information to use as defaults
  $address_info = $address_info_profile->commerce_customer_address[LANGUAGE_NONE][0];

  //set the default values for the addressfield
  $form['commerce_customer_address'][LANGUAGE_NONE][0]['#address'] = $address_info;

  //verify that this is not an ajax request, otherwise country changes will not be able to change the administrative_area information.
  //in otherwise, let this section only happen once, and let ajax make changes as expected
  if (!(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')) {

    //obtain the default country code. If the default values country and the servers default country match, no reason to call the bit of code
    $default_country = variable_get('site_default_country', NULL);

    if ($address_info['country'] != $default_country) {
        module_load_include('inc', 'addressfield', 'plugins/format/address');

        //create a new default addressfield to use, which will use the default values country as the default country, as opposed to the servers default
        $default = addressfield_default_values(array($address_info['country']=>$address_info['country']));

        //where all of the data will be stored when function is called
        $format = array();

        //required by addressfield_format_address_generate, and returns the content as rendered
        $context = array('mode' => 'render');
        addressfield_format_address_generate($format, $default, $context);

        //new defaults and administrative_area have been generated. set these values to the already built form
        $form['commerce_customer_address'][LANGUAGE_NONE][0]['locality_block']['administrative_area'] = $format['locality_block']['administrative_area'];
    }
  }
}

```

Hopefully that helps you out if you are having similar problems getting default values to load.

Also, this was done using field attach form, to attach the commerce\_customer\_profile.

```
$type = 'billing';
$profile = commerce_customer_profile_new($type, $user->uid);
field_attach_form('commerce_customer_profile', $profile, $form, $form_state);

```

# Answer
> 1 votes
Use `hook_addressfield_default_values_alter()`:

```
function YOUR_MODULE_addressfield_default_values_alter(&$default_values, $context) {
    // Set default to Belgium.
    if (empty($default_values['country'])) {
        $default_values['country'] = 'BE';
    }
}

```

# Answer
> 0 votes
Load the default value in the '#default\_value' as you need. Alsso need to populate the related drop-down options using your '#default\_value' and put it in the related drop downs '#options'. For changing the values on select of parent dropdown you need to do an ajax call.

# Answer
> 0 votes
I know this is old, but this is one of the few answers I've found out there. I wasn't able to get the default code working, so I modified it a little in case anyone else needs it.

```
/**
 * Implements hook_form_FORMID_alter() for `commerce_checkout_form_checkout`.
 */
function mymodule_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
  // Get the addressfield element we're modifying.
  // Adapted from addressfield.module/addressfield_field_widget_form()
  $element =& $form['customer_profile_shipping']['commerce_customer_address'][LANGUAGE_NONE][0];
  $element_key = $element['element_key']['#value'];
  $field = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['field'];
  $instance = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['instance'];
  $delta = $element['#delta'];
  $settings = $instance['widget']['settings'];
  $langcode = $element['#language'];
  $items = array($delta => $element['#address']);

  // Get the default address used to build the widget form elements, looking
  // first in the form state, then in the stored value for the field, and then
  // in the default values of the instance.
  $address = array();

  if (!empty($form_state['addressfield'][$element_key])) {
    // Use the value from the form_state if available.
    $address = $form_state['addressfield'][$element_key];
  }
  elseif (!empty($items[$delta]['country'])) {
    // Else use the saved value for the field.
    $address = $items[$delta];
  }
  else {
    // Otherwise use the instance default.
    $address = (array) $instance['default_value'][0];
  }

  // Set the default country here, based on the available values
  // provided by the addressfield module.
  // THAT'S THE PAYLOAD!
  if ($address['country'] != 'SOME_COUNTRY_CODE') {
    $address['country'] = 'SOME_COUNTRY_CODE';
    $address['administrative_area'] = '';
  }

  // After setting the value above, merge the default values
  // to provide a value for every expected array key.
  $countries = _addressfield_country_options_list($field, $instance);
  $address += addressfield_default_values($countries);

  // Add the form elements for the standard widget, which includes a country
  // select list at the top that reloads the available address elements when the
  // country is changed.
  if ($instance['widget']['type'] == 'addressfield_standard') {
    // Generate the address form.
    $context = array(
      'mode' => 'form',
      'field' => $field,
      'instance' => $instance,
      'langcode' => $langcode,
      'delta' => $delta,
    );
    $element = array_merge($element, addressfield_generate($address, $settings['format_handlers'], $context));

    // Mark the form element as required if necessary.
    $element['#required'] = $delta == 0 && $instance['required'];
  }
}

```

Mostly I just moved the code that actually modifies the country and placed it above the array merge that changes those fields to something that the form api can work with.

# Answer
> 0 votes
I found that implementing `function hook_field_widget_addressfield_standard_form_alter(&$element, &$form_state, $context)` then changing `$element['#address']` items did the trick. Changing the city: `$element['#address']['locality'] = 'Zurich';`, for example. I needed this method since the suggested address data needed to come from the `$form_state`, which wasn't possible with the default address hook provided by the module.

# Answer
> 0 votes
```
 $form['field_supplier_address']['widget'][0]['address']['#default_value']['country_code'] = "IL";

```

---
Tags: 7, entities
---


# Question
Title: How can I build a redirect from submitted form values?
I'm working on a short weather app.

What I want to do, is to catch name of the input of city and redirect users to the city's page URL after submit.

```
function form_findYourCity_submit($form, &$form_state) {

  $city = $form_state['values']['city_name'];

  // catching city name from input and assigning it to a variable
}

```

And I want after submit redirect user to new page with `url/something/?city=something` on which I then want to use if `isset $_GET['city']` and then do my operations with the weather API database and pulling data based on the city.

# Answer
Okay I have figured it out by myself.

Here is what I needed:

```
function form_findYourCity_submit($form, &$form_state) {

  $city = $form_state['values']['city_name'];

  $form_state['redirect'] = [
    'showCity',
    [
      'query' => [
        'city' => $city,
      ],
    ],
  ];

}

```
> 1 votes

---
Tags: 7, forms, redirection
---