# Question
Title: How to filter GraphQL query by content language?
I am coding Drupal 8/Angular app and Angular is fetching data from Drupal using GraphQL. Everything works fine except now I need to query nodes in a particular language. This is my query:

<pre><code>{
  nodeQuery(filter:
    {conditions: [
      {field: "type", value: "akcia", operator: EQUAL, language: EN},
      {field: "field_datum", value: "2018-02-12T18:00:00", operator: GREATER_THAN_OR_EQUAL}
      {field: "langcode", value: "en", operator: EQUAL}
    ]}
    sort: {field: "field_datum", direction: DESC}
  )
  {
    entities {
      entityLanguage {
        id
      }
      ... on NodeAkcia {
        nid
        langcode {
          value
        }
        title
        fieldDatum {
          value
        }
        body {
          value
        }
        fieldObrazok {
          url
        }
        path {
          alias
          pid
          langcode
          pathauto
        }
      }
    }
  }
}```

Notice the `{field: "langcode", value: "en", operator: EQUAL}` line - that's the best thing I came up with, however, the query returns Slovak version of that node, not the English one.

Is there any better way ho to filter nodes based on their translation?
</code></pre>

# Answer
> 0 votes
Your query is almost correct but you need to retrieve the entityTranslation in your entities, something like below for an article in English for example:

```
 entities {
    ...on NodeArticle {
      entityTranslation(language: EN) {
        entityLabel
      }
    }
  }

```

See also here for a similar question and answer.

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


title: db_query group by to array

text:
# Question
Title: db_query group by to array
I have the following query:

```
$query = "SELECT *
      FROM mytable
      {$typeClause}
      HAVING distance <= {$radius}
      ORDER BY distance ASC"
      GROUP BY type;

    $result = db_query($query);
    $points = array();

    while(($point = $result->fetchAssoc()) != null){
    }

```

In my db there is field 'type' which is a number
How can I get all records as an array without using the while statement above (something like fetchByGroup):

```
array(
        '1' => array( [all records of type=1] ),
        '2' => array( [all records of type=2] ),
        ......................................
    );

```

# Answer
> 2 votes
You cannot do this using native Drupal 7 functionality. You need to do that grouping in PHP. You should be using a foreach, not a while loop :)

> The most common case is to iterate over the result set with a foreach() loop.

Source: https://drupal.org/node/1251174

# Answer
> 0 votes
fetchAllAssoc($field) will do the magic for you.

```
$query = "SELECT *
      FROM mytable
      {$typeClause}
      HAVING distance <= {$radius}
      ORDER BY distance ASC"
      GROUP BY type;

    $result = db_query($query)->fetchAllAssoc('fieldname');

```

---
Tags: 7, database
---


# Question
Title: How can you have Composer install the site in the project root not in web/?
I have downloaded Drupal 8.8 through composer drupal/recommended-project. The downloaded files structure is diff than previous download. Now core and other files are stored in web folder and vendor is out of core.

So my question is how to setup site in public\_html/. I have uploaded files entire files under public\_html/ but site not works. I also tried to access example.com/web but does't work.

How can I fix that?

# Answer
If the server you are using uses public\_html as document root, and not web as drupal/recommended-project expects, you need to follow what reported in Using Composer to Install Drupal and Manage Dependencies.

> If you want to modify some of the properties of the downloaded composer.json before composer install is executed, use the `--no-install` flag when running `composer create-project`. For example, it is possible that you want to rename the subdirectory 'web' to something else.
>
> To do that:
>
> 1. Run `composer create-project drupal/recommended-project my_site_name_dir --no-interaction --no-install`
> 2. Change directories to my\_site\_name\_dir and edit the composer.json file to suit your needs
> 3. Run `composer install` to download Drupal 8 and all its dependencies.
> 0 votes

---
Tags: 8, composer
---


# Question
Title: Node display based on conditional view [NULL] field entry or a Rules expression
I am trying to find a solution to empty user Content Listings shown on a User dashboard (landing page). Ideally I want to show a Mini-panel pane or Custom Content Pane instead of a users listing View which would other wise show an empty table and hence blank space on (in this case a Desktop browser, alternatives to be incorporated via CSS Bootstrap etc).

Should the user not have posted any content then a pane with a (vector.svg) graphic will show in place of the empty view blockspace based on the View being NULL or empty asking them to 'add some content' or maybe a vector graphic to instruct. I have looked at the Conditional View module and Rules, but nothing seems to show such options so I'm not quite sure is this my right approach.

Where and what should be my correct approach?

# Answer
> 1 votes
you will need flag module make a global user flag: user\_has\_content, make a rule: react on event: after saving new content of your special type, add a condition: user author is NOT flagged, inside rules action: flag it, only once your user author will be flagged, then on your view, add relationship to author & one more relationship on the new flag on author, and display content if user is flagged, make another view, display whatever you want if user is NOT flagged, this works also on D8, done.

EDIT: since you are using panels, it's easier, make 2 panes as explained, and in panels add this 2 panes, make your rules inside panels UI, display pane 1 if user is flagged, display pane 2 if user is not flagged.

---
Tags: 7, views, rules
---


# Question
Title: How to manually check if a username and password is correct?
There are a lot of answers on how to log in as a specific user. But I can't find any answer on how to check if the username and password is valid without logging in. I want to be able to do something like this:

```
$username = "bla@bla.com"
$password = "blablabla"

$valid = checkIfValidDetails($username, $password);

```

I simply want $valid = true if the username and password is correct, and false if not.

How can I do that?

# Answer
> 3 votes
Drupal 6 and 7

```
user_authenticate($username, $password);

```

Drupal 8

```
// Inject user.auth service..
$uid = $this->userAuth->authenticate($username, $password);
// or
$uid = \Drupal::service('user.auth')->authenticate($username, $password);

```

Source: How to check logged in user username/password/role using Drupal function for validation

---
Tags: 8, users
---


title: How do I theme the secondary menu?

text:
# Question
Title: How do I theme the secondary menu?
The following code allows me to print the secondary menu.

```
<?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => 'menu nav navbar-nav secondary hidden-xs'))); ?>

```

I get the following output.

```
<ul id="secondary-menu" class="menu nav navbar-nav secondary hidden-xs">
<li class="menu-6734 first"><a href="/" title="">link 1</a></li>
<li class="menu-6735 first"><a href="/" title="">link 2</a></li>
<li class="menu-6736 first"><a href="/" title="">link 3</a></li>
</ul>

```

Now, I need to add dropdown to the last menu item but I have no idea how to do it. Any guidance much appreciated!

# Answer
You can theme ***secondary menu*** using `THEME_links__system_secondary_menu` like the following:

```
function THEME_links__system_secondary_menu(&$vars) {
  // Get links:
  $links = $vars['links'];
  // Get the index of last menu item.
  end($links);
  $last_ele_index = key($links);
  // Here do your logic by change ...
  // $vars['links']['$last_ele_index'];
}

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Use rules to assign role based off custom field on user registration
I have a headless Drupal and I'm trying to figure out how to auto assign a role during registration based off of a custom field (field\_is\_student) in the registration form.

I am trying to use Rules but I don't know how to access the field to check whether it's true or false. My rule is set to "After saving a new user (rules\_entity\_insert:user)" and the only options I get in the condition Data Selector are User based.

Here's what I'm using to create my users:

```
{
    "name": {
        "value": "username"
    },
    "mail": {
        "value": "useremail@email.com"
    },
    "field_is_student":{
        "value": false
    }
}

```

# Answer
> 0 votes
The following Rule export does what you asked, for users created in the UI. In D8. I have tested it and it works. You will also need to use the (temporary) patch from https://www.drupal.org/project/rules/issues/2725525#comment-11438731 to work around the problem with in assigning roles.

The concept to understand is that Rules knows about the base fields for the entity type. But if you add fields, that's a new entity bundle, so you need to tell Rules that your data is of a certain bundle. To do that, you use the "Entity is of bundle" condition, as I show below. Then all the fields for that bundle will show up in the data selector.

```
langcode: en
status: true
dependencies: {  }
id: set_a_role_for_new_users
label: 'Set a role for new users.'
events:
  -
    event_name: 'rules_entity_insert:user'
description: 'Assign the ''student'' role to new users who identify themselves as students. Requires a boolean field ''field_is_student'' on the user object and requires an available role with machine id ''student''.'
tags: {  }
weight: 0
config_version: '3'
expression:
  id: rules_rule
  uuid: 36de9619-1401-4b21-a651-d3927c5b8dac
  weight: 0
  conditions:
    id: rules_and
    uuid: 416e90b0-d24c-4f37-8272-de0ecee5c375
    weight: 0
    conditions:
      -
        id: rules_condition
        uuid: bafe6fc4-f88f-4df2-af9b-2b3558257c2b
        weight: 0
        context_values:
          type: user
          bundle: user
        context_mapping:
          entity: user
        context_processors:
          type:
            rules_tokens: {  }
          bundle:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_is_of_bundle
        negate: false
      -
        id: rules_condition
        uuid: 28787d22-54ca-49cf-af42-6f1011ed6494
        weight: 0
        context_values:
          operation: '=='
          value: '1'
        context_mapping:
          data: user.field_is_student.value
        context_processors:
          operation:
            rules_tokens: {  }
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_data_comparison
        negate: false
  actions:
    id: rules_action_set
    uuid: 2933681a-a079-496d-bc79-f27ff53144eb
    weight: 0
    actions:
      -
        id: rules_action
        uuid: 38e8a3bb-0470-427f-80e1-53f6a703e8bf
        weight: 0
        context_values:
          roles:
            - student
        context_mapping:
          user: user
        context_processors:
          roles:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_user_role_add

```

---
Tags: 8, rules
---


title: Load webform submission

text:
# Question
Title: Load webform submission
How can I load a webform submission programmatically ?

I've tried : `$webform_submission = WebformSubmission::load($sid);`

but it return null.

I do this in a custom module call by an handler after webform submission.

# Answer
I think you have to load sid like below

```
// Load submission using sid.
/** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);

```
> 12 votes

# Answer
To load webform submissions of a particular webform programmatically -

```
    $webform = \Drupal\webform\Entity\Webform::load('WEBFORM_ID');  //webform id is the webform name
    if ($webform->hasSubmissions()) {
      $query = \Drupal::entityQuery('webform_submission')
        ->condition('webform_id', 'WEBFORM_ID');
      $result = $query->execute();
      $submission_data = [];
      foreach ($result as $item) {
        $submission = \Drupal\webform\Entity\WebformSubmission::load($item);
        $submission_data = $submission->getData();
      }
    }

```
> 4 votes

---
Tags: 8, webforms
---


title: How do I create the database tables?

text:
# Question
Title: How do I create the database tables?
I installed composer-Git and drush and was continuing with the installation of Drupal 8 from the command line. I read that you can create the database directly from drush, while in other parts I read that you must first create the database and then you can install the site from drush. I guess the answer can be create the database first but I prefer to be sure of what I can do with drush

The usage command is `drush site-install --db-url = mysql://root:pass@localhost:port/dbname`.

# Answer
> 3 votes
Drush will try to create the database if it doesn't exist. You can even provide an optional superuser account and password for the `site-install` command. Technically Drush doesn't create the database tables. The Drush `site-install` command runs the Drupal install procedure which does the job.

Reading core/INSTALL.mysql.txt you'll see that the normal procedure is to create the database first and then give the needed permissions on that databases. However, if you use a super user for you database (with the permission to create any database), Drupal will in fact also create the database when installing. This doesn't happen when you are using Drush.

---
Tags: drush
---


# Question
Title: Add payment to a commerce order using Rules
I am trying to create a component that can add payments to an existing order.(the payment is received offline). However, when I try to add an amount I receive the alert that the field is not writable ("The selected data property doesn't support writing"). Does anyone know how this may be accomplished using Rules?

This is my attempt so far:

```
{ "rules_set_order_id_as_paid" : {
"LABEL" : "Set order id as paid",
"PLUGIN" : "action set",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : { "orderid" : { "label" : "orderid", "type" : "list\u003Cinteger\u003E" } },
"ACTION SET" : [
  { "LOOP" : {
      "USING" : { "list" : [ "orderid" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "entity_fetch" : {
            "USING" : { "type" : "commerce_order", "id" : [ "list-item" ] },
            "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
          }
        },
        { "drupal_message" : { "message" : "[entity-fetched:order-number]" } },
        { "entity_create" : {
            "USING" : {
              "type" : "commerce_payment_transaction",
              "param_user" : [ "entity-fetched:owner" ],
              "param_order" : [ "entity-fetched" ],
              "param_payment_method" : "faktura"
            },
            "PROVIDE" : { "entity_created" : { "entity_payment_created" : "Created payment entity" } }
          }
        },
        { "data_set" : { "data" : [ "entity-payment-created:created" ], "value" : 1575626400 } },
        { "data_set" : {
            "data" : [ "entity-payment-created:payment-method" ],
            "value" : "faktura"
          }
        },
        { "data_set" : { "data" : [ "entity-fetched:status" ], "value" : "completed" } },
        { "data_set" : {
            "data" : [ "entity-payment-created:payment-method" ],
            "value" : "commerce_payment_example"
          }
        }
      ]
    }
  }
]

```

} }

# Answer
I ended up doing some sql statements that seem to have done the trick. One challenge was raising the event Paid in full via sql, which I ended up doing via executing a component manually. Not the most elegant solution but it did get the job done.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Multilingual Taxonomy Views - Entity Translation
I am trying to create a multilingual taxonomy view using Entity translation. So far, I am stuck displaying an English view even when using a language code.

I'm looking for the steps needed for this. At the simplest, I am trying to create blocks or pages of taxonomy terms based on language.

Any suggestions?

# Answer
> 3 votes
Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.

Also, to make view results correspond to the language switcher, add a filter for **Content Translation: User's Current Language**, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the **User's Current Language** is available in the filter criteria form, then verify your configuration at *Configuration -\> Languages -\> detection and selection*: The order should be **URL, Default, User** and not something like **Default, URL, User** (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

The above may turn out to NOT be the complete answer. Since you use the Entity Translation module, this option isn't there if you use it in 'entity' mode: if only some fields of the node are translatable the option is there but a bit more difficult to find. If you have the 'Body' of your nodes set to translatable entity then the option is "Body language" to be set to Current User Language.

**Note**: The Internationalizations Views module only has a **DEV** version for D7, but right now there are over 31K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because *+31K users can't be wrong*, right?

# Answer
> 0 votes
If you wont to show in views taxonomy terms, translated with entity\_translate, try to use "Entity translation: Name" field instead "Taxonomy term: Name (translated)"

---
Tags: 7, views, taxonomy-terms, entities, i18n-l10n
---


# Question
Title: Add inline style to render array attributes, without XSS filtering
I wish to use an inline style to add a dynamically generated background image URL to a div, e.g.

```
  $build[0] = [
    '#type'       => 'container',
    '#attributes' => [
      'id' => 'thumbnail-image',
      // the example below is a YouTube thumbnail, to be cropped using other CSS
      'style' => sprintf('background-image: url("https://img.youtube.com/vi/1234567890/sddefault.jpg");', $video),
    ]
  ];
  return $build;

```

The XSS filtering silently drops `style` attributes. Can I disable that for an individual render array, or otherwise work around it?

Note: this is generating output for a Field Formatter, used in a view.

The official advice is:

> If your markup needs any of the tags not in this whitelist, then you can implement a theme hook and/or an asset library. Alternatively, you can use the key #allowed\_tags to alter which tags are filtered.

### Things tried:

1) **using a theme hook and a template**

Here's my template:

```
<div class="test" style="background-image:url('https://img.youtube.com/vi/{{ video_id }}/sddefault.jpg');">Sample output</div>

```

It's working, except the style attribute is still being stripped out.

2) **#allowed\_tags** (but it's not a tag, it's an attribute):

```
'#allowed_tags' => array_merge(\Drupal\Component\Utility\Xss::getAdminTagList(), ['style']),

```

**Successful workaround**:

This code is in a field formatter for views, so I overrode the default views template. The views templates allowed a `style` attribute to pass through as I would have expected.

Initially I made a template for one specific field, but the problem was I needed to access the values of a separate field too and it was proving hard/impossible to retrieve them with the `row._entity` variable.

So then I decided to use `views-view-fields.html.twig` instead, which gives access to all the fields. This took rather longer, but as my code had a couple of conditionals and some variables used more than once, on balance the end result is cleaner than doing everything in the UI. (It's worth leaving yourself a note in the view UI admin comment and any docs that the view field is overwritten.)

# Answer
I'd use `'#type' => 'inline_template'` for this: You can do everything what you can do in a regular `.twig` file, just inlined in code:

```
  $build[0] = [
    '#type'       => 'inline_template',
    '#template'   => '<div id="thumbnail-image" style="background-image: url({{ foo }})">{{ bar }}</div>'
    '#context' => [
      'foo' => $youtube_thumbnail
      'bar' => $whatever
    ]
  ];
  return $build;

```

Here is a complete list of render elements / `#type` 's for render arrays. (For Forms API, here is the sub-list of FormRenderElements)
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Site seems to miss the "private" wrapper, how can I fix it?
I can not enable the private folder getting the warning as below:

```
Warning: file_exists(): Unable to find the wrapper "private" -
did you forget to enable it when you configured PHP? in file_save_htaccess()
(line 365 of core/includes/file.inc).

```

It's Drupal 8.6.12, multisite config, other sites use private folders.

How can I fix it ?

# Answer
Here are the necessary steps:

1. Create a directory on the server. This is typically done via SSH. For instance assuming Apache under Ubuntu, the following command can be used: `sudo -u www-data mkdir -p /var/www/html/web/sites/default/files/private`
2. Tell Drupal about your directory by editing your `settings.php` file. You need to have a line like the following:

```
 $settings['file_private_path'] = '/var/www/html/web/sites/default/files/private';

```
3. **Important**: clear the Drupal cache, for example with `drush cr` or by going to the page /admin/config/development/performance in your browser.
4. In the browser's address bar, go to /admin/config/media/file-system. You should see "Private local files" in the "Default download method" option. If not, then please visit the /admin/reports/status page to see any error messages. Make sure that PHP can write in the directory. Often, for this to work, the directory has to be writable for the `www-data` user.

For more documentation, go to https://www.drupal.org/docs/8/core/modules/file/overview#private-file-system.
> 14 votes

# Answer
From the link posted in the answer above it specifically states NOT to put the Private folder within docroot:

"add the url path to your private directory. It must exist outside of your web root directory and be an absolute path, for example /var/www/html/example.org/private with web root in/var/www/html/example.org/web or /home/username/example.org/private with web root in /home/username/example.org/web. So it should look like:

$settings\['file\_private\_path'\] = $app\_root . '/../private'; "
> 3 votes

---
Tags: files
---


# Question
Title: Installing a site from existing configuration
I tried importing a configuration after installing Drupal 8 using the standard installation profile but was getting into errors related to the installation profile being already present.

I need a clean drupal slate with only the configuration and no content. Is it possible to do that?

# Answer
> 3 votes
I found out we can do this by running the following drush command

```
drush site:install --existing-config

```

However you might encounter an error related to hook\_install found in standard install profile. To mitigate that you would need to install this patch.

https://www.drupal.org/files/issues/2018-11-27/2982052-22.patch

---
Tags: 8, configuration, installation
---


# Question
Title: How to add/remove a permission from a user role to a particular user without modifiying the user role?
Let's say that I have a user role called ARTICLE\_VIEW\_EDIT which has permissions to view and edit own articles nodes. I have the following 2 cases.

* I want to give extra permission, delete own articles permission to a user - user101 who has the user role ARTICLE\_VIEW\_EDIT and this modification must not affect the user role.
* I would like to remove edit permission from a user - user102 who has the user role ARTICLE\_VIEW\_EDIT and this modification must not affect the user role.

After doing some research I have found out that I could use the Role class to create custom user roles but that will be saved as configuration not as a record in the user\__roles tables hence I am not getting the output that I'm looking for.

# Answer
> 1 votes
You can't do that, at least with standard Drupal setup. Probably you can code a hack that allows it, but is not how Drupal is designed.

Besides this, you can use current role system to achieve what you want. You only need to add more roles. You want edit own articles, view own articles and delete own articles to be independent. You can define 3 roles, and assign to users as you need.

If your problem is you'd have lots of roles (because you want lot of different permissions to be independent) you may use Content Access along with ACL:

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.
>
> \[...\]
>
> It tries to reuse existing functionality instead of reimplementing it. So one can install the ACL module and set per user access control settings per content node.

Alternatively, you can code your own access system implementing a combination of hook\_entity\_access, hook\_node\_access and hook\_query\_TAG\_alter.

You can have a full explanation of how node access rights works on this documentation page: https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/group/node\_access/8.8.x

> Next, all implementations of hook\_node\_access() will be called. Each implementation may explicitly allow, explicitly forbid, or ignore the access request. If at least one module says to forbid the request, it will be rejected. If no modules deny the request and at least one says to allow it, the request will be permitted.

---
Tags: 8, users, hooks
---


title: Using GraphQL webform add-on

text:
# Question
Title: Using GraphQL webform add-on
I started to use GraphQL for my drupal8 application to expose some data. Now I want to use it to return a webform that I created.

I installed an add-on for webform graphl https://github.com/duartegarin/graphql\_webform but am not sure how to use it. I thought it will add a new query type called WebformQueryById but it is not showing up when I navigated to the GraphQL explorer.

I have been stuck for days on this. Is there some configuration / setting steps I might be missing? Thanks

# Answer
> 1 votes
You can use the fields defined on the `graphql_json` module in order to retrieve the webform structure.

```
{
  webformById(webform_id: "contact") {
    webform {
      elements {
        name: path(steps: "#name") {
          ... on JsonLeaf {
            value
          }
        }
        type: path(steps: "#type") {
          ... on JsonLeaf {
            value
          }
        }
        title: path(steps: "#title") {
          ... on JsonLeaf {
            value
          }
        }
      }
    }
  }
}

```

Result:

```
{
  "data": {
    "webformById": {
      "webform": {
        "elements": [
          {
            "name": {
              "value": "name"
            },
            "type": {
              "value": "textfield"
            },
            "title": {
              "value": "Your Name"
            }
          },
          {
            "name": {
              "value": "email"
            },
            "type": {
              "value": "email"
            },
            "title": {
              "value": "Your Email"
            }
          },
          {
            "name": {
              "value": "subject"
            },
            "type": {
              "value": "textfield"
            },
            "title": {
              "value": "Subject"
            }
          },
          {
            "name": {
              "value": "message"
            },
            "type": {
              "value": "textarea"
            },
            "title": {
              "value": "Message"
            }
          },
          {
            "name": null,
            "type": {
              "value": "captcha"
            },
            "title": null
          },
          {
            "name": null,
            "type": {
              "value": "webform_actions"
            },
            "title": {
              "value": "Submit button(s)"
            }
          }
        ]
      }
    }
  }
}

```

You can find the available steps with `keys` field.

```
{
  webformById(webform_id: "contact") {
    webform {
      elements {
        keys
      }
    }
  }
}

```

# Answer
> 0 votes
I've got a webform called "test", and the following query works for me:

```
{
  webformById(webform_id:"test"){
    webform{
      elements{
        keys
      }
    }
  }
}

```

It returns the following (truncated):

```
{
  "data": {
    "webformById": {
      "webform": {
        "elements": [
          {
            "keys": [
              "#type",
              "#title",
              "#webform",
              "#webform_id",
              "#webform_key",
              "#webform_parent_key",
              ...
            ]
          }
        ]
      }
    }
  }
}

```

I'm not sure what info you're trying to get out of webforms. My impression is that the graphql\_webform module is still very much a work in progress, and not particularly useful in its current state.

About the `WebformQueryById`: that's the name of the class, but there's a declaration before the the class that specifies how to call it:

```
 * @GraphQLField(
 *   id = "webform_by_id",
 *   type = "WebformResult",
 *   name = "webformById",
 *   nullable = true,
 *   multi = false,
 *   arguments = {
 *     "webform_id" = "String!",
 *   },
 * )

```

The "name" parameter specifies the name by which to call the query.

---
Tags: 8, webforms
---


# Question
Title: How do I prevent my content's title from appearing in the <description> tag of my RSS feed?
I have a newly migrated Drupal 8 site and am noticing that the RSS feed displays the Title of a node twice in my feed reader. This is because a node's title is output both in the feed item's `<title>` and within the item's `<description>`.

For example:

```
<item>
  <title>My Clever Title</title>
  <link>http://example.com/node/123</link>
  <description><span data-quickedit-field-id="node/123/title/und/rss">My Clever Title</span>

  <div data-quickedit-field-id="node/123/body/und/rss" class="field field--name-body field--type-text-with-summary field--label-hidden field--item">
  Lorem ipsum... my content displays here....
  </description>
  ...other tags here...
</item>

```

So now, a feed reader like Feedly displays my content like this:

> **My Clever Title**
>
> My Clever Title
>
> Lorem ipsum... my content displays here....

Note: In my RSS Manage Display, the content type is set to display the "Default" (not-trimmed) body field.

**How do I prevent my RSS feed from inserting the post's title into the the `<description>` tag?**

# Answer
> 2 votes
I haven't tried to reproduce this on my end, but I found a Drupal.org thread with advice that may be relevant:

https://www.drupal.org/project/drupal/issues/2946812#comment-12501714

> using 'Show: content' looks like a bad idea to begin with.
>
> I can get some nice clean output:
>
> * Choose 'Show: Fields' (so not 'Force using fields', just plain fields output)
> * Close the dialog without setting the required fields (just click the X in the top right corner)
> * Add some fields (title, body, a url, node id)
> * Go to Row style options (so click on the 'Settings' link behind 'Show: Fields'
> * Fill out the required fields with the fields you've added
> * Add more fields if you need them to fill out the required settings

If you build the description this way, you should easily be able to omit the title field. Good luck!

# Answer
> 1 votes
Following the link in hotwebmatter's answer, I found the following fix based on this comment: https://www.drupal.org/project/drupal/issues/2946812#comment-13329019

```
function MYTHEME_preprocess_views_view_row_rss(&$variables) {
  $html = $variables['description'];

  $dom = new \DOMDocument;
  $dom->loadHTML($html);
  $xpath = new \DOMXpath($dom);
  $to_replace = [];
  $replace_with = [];

  // Search for post title based on data-quickedit-field-id attribute
  $found = $xpath->query('//*[contains(@data-quickedit-field-id,"/title/en/rss")]');
  if (!empty($found[0])) {
    $to_replace[] = $found[0]->ownerDocument->saveXML($found[0]);
    $replace_with[] = '';
  }

  $html = str_replace($to_replace, $replace_with , $html);
  $variables['description'] = $html;
}

```

The title field does not have a class in my RSS output so I changed the original code to look in the quickedit attribute.

---
Tags: 8, feeds
---


title: Multi-site for user groups

text:
# Question
Title: Multi-site for user groups
I have to carry out a procedure for the management of information by a group of users. Later I could have the same need but for a group of different users. Since I haven't understood how the multisite works, I can't make up my mind.

The software will be the same, but for database copy, user management and security issues, I would prefer to have the database different for the group of users.

1. Can the multisite manage multiple databases with a single software?
2. Do I have to foresee it and create it from the beginning or can I create the software and subsequently, if there is a request, transforming it into a multisite?

# Answer
> 1 votes
> 1. Can the multisite manage multiple databases with a single software?

Yes.

> 2. Do I have to foresee it and create it from the beginning or can I create the software and subsequently, if there is a request, transforming it into a multisite?

You can perfectly start with a single site, and late on transform it into a multisite.

As an alternative to using a multisite, you may also want to consider using the Group module. From the specs in your question, it appears to me that only using this module (without a multisite setup), it could well be sufficient ...

---
Tags: multi-sites
---


# Question
Title: How do I make custom entity create new revision by default?
I made a custom entity that extends `RevisionableContentEntityBase`. I can use the web interface to create entities. If I edit an entity and check the box `Create new revision` then a new revision will be created. There is no configuration form available to set the default for `Create new revision`.

The custom entity is quite simple. It has a few base fields and was built using `drush generate module-content-entity`.

How do I make my custom entity create a new revision by default?

# Answer
Normally the default value is stored in bundle configurations. If you have no bundles then override getNewRevisionDefault() of your content entity form:

```
class MyEntityForm extends ContentEntityForm {

  protected function getNewRevisionDefault() {
    return TRUE;
  }

}

```

This class should already exist when you've generated the entity with Drush/Console. Check in the entity annotations that the class is used as form handler.
> 7 votes

# Answer
In addition to 4k4's answer here, which is very good and specific, a coworker helped me arrive at another solution in overriding `ContentEntityForm::buildForm` function:

```
class MyEntityForm extends ContentEntityForm {

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['revision'] = [
      '#type' => 'value',
      '#default_value' => TRUE,
    ];
  }
}

```

The benefit of overriding the `buildForm` function is you can have a bit more form-specific logic, e.g. making it a hidden value or a checkbox.
> 4 votes

---
Tags: 8, entities
---


# Question
Title: "Route entity.path_alias.collection does not exist"
I was using Drupal 8.7.7 and decided to update it to 8.8.1. After that the back-end side of the site isn't working anymore, I can only access the site as an anonymous user. The error I get is:

> Route "entity.path\_alias.collection" does not exist

As suggested by the release notes, I first updated Pathauto to 1.6, then Drupal Core. I ran database updates via update.php and/or drush to no luck. As a result, after rolling back the Drupal core version to 8.7.7, in some admin pages I see this warning:

> User warning: The following module is missing from the file system: path\_alias in drupal\_get\_filename() (line 277 of core\includes\bootstrap.inc).

But this warning is not the issue. I want to be running Drupal 8.8.x, not 8.7.7

Here is the full error:

```
The website encountered an unexpected error. Please try again later.
Symfony\Component\Routing\Exception\RouteNotFoundException: Route "entity.path_alias.collection" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 208 of core\lib\Drupal\Core\Routing\RouteProvider.php).
Drupal\path\Routing\RouteProcessor->processOutbound('path.admin_overview', Object, Array, Object) (Line: 52)
Drupal\Core\RouteProcessor\RouteProcessorManager->processOutbound('path.admin_overview', Object, Array, Object) (Line: 405)
Drupal\Core\Routing\UrlGenerator->processRoute('path.admin_overview', Object, Array, Object) (Line: 292)
Drupal\Core\Routing\UrlGenerator->generateFromRoute('path.admin_overview', Array, Array, 1) (Line: 105)
Drupal\Core\Render\MetadataBubblingUrlGenerator->generateFromRoute('path.admin_overview', Array, Array, 1) (Line: 754)
Drupal\Core\Url->toString(1) (Line: 174)
Drupal\Core\Utility\LinkGenerator->generate('URL aliases', Object) (Line: 63)
Drupal\Core\Utility\LinkGenerator->generateFromLink(Object) (Line: 138)
Drupal\Core\Link->toString() (Line: 29)
template_preprocess_admin_block_content(Array, 'admin_block_content', Array) (Line: 287)
Drupal\Core\Theme\ThemeManager->render('admin_block_content', Array) (Line: 431)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 200)
Drupal\Core\Render\Renderer->render(Array) (Line: 501)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 74)
__TwigTemplate_8048c6546ef7176b663c0cb00ee6d78265ecf31a4f6ee21d14e7d0d942b93fe8->doDisplay(Array, Array) (Line: 455)
Twig\Template->displayWithErrorHandling(Array, Array) (Line: 422)
Twig\Template->display(Array) (Line: 434)
Twig\Template->render(Array) (Line: 64)
twig_render_template('core/themes/stable/templates/admin/admin-block.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('admin_block', Array) (Line: 431)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 200)
Drupal\Core\Render\Renderer->render(Array) (Line: 501)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 75)
__TwigTemplate_79c329774294b89c8d91701568a3e8e91609085c38e3ab9532cabc063ddee645->doDisplay(Array, Array) (Line: 455)
Twig\Template->displayWithErrorHandling(Array, Array) (Line: 422)
Twig\Template->display(Array) (Line: 434)
Twig\Template->render(Array) (Line: 64)
twig_render_template('core/themes/stable/templates/admin/admin-page.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('admin_page', Array) (Line: 431)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 200)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 573)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)

Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)

Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 694)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

# Answer
> 3 votes
Upgrading and downgrading a site is not very well supported unless you also roll back the database.

It seems this should help:

1. Update pathauto to the latest version.
2. Run the database updates.
3. Update again to Drupal 8.8.
4. Run the database updates.
5. Ensure the path alias module is installed/enabled.

---
Tags: 8, path-aliases
---


# Question
Title: Is there any management utility for multi-site deployment?
I'm creating a multi-site instance for a client that makes heavy use of Webform. It's going to be a survey tool of sorts with a single base domain (***no sub-domains***) and a single SSL certificate.

I've set up the `/sites/default` the base of what we'd like all other sites to be like. I've gone so far as to attempt this using bash. (This is not my best code and it lives on a throw away VM\*):

```
# Create temporary password
PASS=`tr -dc a-z1-4 </dev/urandom  | head -c 10`

# File structure and empty settings file
mkdir /var/www/html/sites/$1
mkdir /var/www/html/sites/$1/files
cp /var/www/html/sites/default/default.settings.php /var/www/html/sites/$1/settings.php

mysql -u root -p -e "create database $1"
mysql -u root -p -e "GRANT ALL PRIVILEGES ON $1.* TO '$1'@'%' IDENTIFIED AS PASSWORD('$PASS');"

# And here is where things fall apart
drush si ???

```

My question is, is there a module or utility that could help create a new site inside this multi-site installation? That is, I'd like to clone the model database, create a `/sites/new-site/settings.php`, and enable a chosen set of modules.

My dream would be to have a `drush clone-site` command.

# Answer
Take a look at Aegir:

It's probably a bit more than what you are looking for, since it manages your web server vhosts (apache or nginx), which means that it kind of takes over part of the system configuration. It also works much better on Debian (with Debian packages, installation/upgrades are pretty easy.. kind of annoying otherwise).

Once it's installed, you can create your base site and clone it using the Aegir user interface (which is a Drupal site, called the "hostmaster", which is completely autonomous from the other sites you are hosting - it's just that as Drupal developers, they used Drupal for the front-end to their tool). Under the hood, Aegir uses Drush, so it's not re-inventing the wheel.

Anyway, fair disclaimer: there is a learning curve, but it has a pretty good community and it's well worth it when managing farms of small sites. It also has commercial training/support available from a few companies (listed on the project page).
> 8 votes

# Answer
There is no single management utility (maybe some managed cloud solutions) which can easily manage your all Drupal instances, so you have to learn how to mix different tools together (e.g. Puppet + drush). Most of it can be done by drush.

---

**Ansible**

Ansible is a flexible and extensible automation tool which definetly can help with multisite deployment.

See:

---

**Puppet**

Probably you don't need it, but in case you'd need to set-up whole LAMP configuration each time (e.g. on multiple servers), you should use some configuration management utility.

For example to automatize LAMP environment configuration (Linux, Apache, MySQL and PHP) you can use either Puppet or Chef. Having proper Puppet recipe, you're able to configure whole LAMP configuration in one command. Check some basic recipe example for ADS distribution: ads.dev.pp.

Installing Puppet is easy (`sudo apt-get -y install puppet`), then you've to install necessary modules (e.g. for Apt, Apache and Pear). In example:

```
sudo puppet module install puppetlabs/apt; sudo puppet module install rafaelfc/pear; sudo puppet module install puppetlabs-apache

```

For more advanced recipe (different db per vhost), check: Proper way of importing many manifest files with vhost definitions.

---

**Drush remotes**

Once you've LAMP environment ready, you need to define your remote shell aliases, so you can transfer your files and database across your sites. Check example.aliases.drushrc.php how to use it.

You can use different remotes for each multi-site instance, e.g.:

```
// The site in sites/default/
$aliases['site.default'] = array(
  'uri' => 'default',
  'root' => '/path/to/drupal',
);
// The site in sites/site1/
$aliases['site.site1'] = array(
  'uri' => 'site1',
  'root' => '/path/to/drupal',
);

```

Make sure that you'll add your SSH key into your `authorized_keys`, so it won't ask you for the password each time when running remote commands. See: How to add RSA key to authorized\_keys file?.

---

**Site installation**

If you'd like to install Drupal sites from scratch, consider using Drupal installation profiles or drush make files (writing one or generating from the existing site).

You can simply check how distributions such as Recruiter, Commerce Kickstart or ADS work.

For complex solutions, you may use phing (or ant). Check example of build.xml from ADS or check Template Phing build.xml file for Drupal projects.

See also: What is the easiest way to install clean Drupal from scratch?

---

**Transfering the files to the remote**

Once you have your shell aliases set-up, transferring files is easy.

In example:

```
drush -v rsync drupal/ @remote

```

Multi-site example:

```
drush -v rsync drupal/ @remote1,@remote1

```

Or this can be achieved by defining each e.g. `dev` alias in separate `*.aliases.drushrc.php` group alias files, so calling `@dev` would invoke all defined `dev` environments.

See also: How to rsync files between two remotes which share the same host?

---

**Synchronising database between sites**

Transfering database is easy as well by `drush sql-sync`, e.g.:

```
drush sql-sync @self @remote

```

This will transfer your local Drupal database into remote. You can also use the same command to transfer the database between two remotes.

---

**Managing settings file**

You can consider to edit your `settings.php` and include at the end extra file such as `settings.local.php` as your instance-specific configuration file (example , ), then it'll be easier to maintain (as it can be ignored by git). So if you have multiple environments, you can use the following simple approach to load the settings based on your current environment:

```
$conf['environment'] = $env = 'local'; // dev, test, prod)

```

And use the simple `switch` statement to invoke different settings per environment.

Here are the example settings files from ADS distribution which you can use.

If you want to automate changes to your settings file, you can define some drush alias to do something like `sed s/DB_NAME/real_db_name/` (drush normally accept arguments and pass them to the remote), or check Can you modify the settings.php file using drush?.

---

**Drush shell aliases**

If you want your dream to come true, use drush shell aliases to define your commands which you'd like to execute on remotes as part of your deployment script.

Same examples for your remote:

```
$aliases['dev'] = array(
'shell-aliases' => array(
  'deploy-code' => '!git fetch origin && sudo git stash && sudo git reset origin/dev --hard',
  'deploy-db' => '!drush sql-sync --yes @prod @self',
  'deploy-files' => '!drush --yes rsync @prod:%files @self:%files',
  'deploy-drupal' => "!
    sudo -uwww-data drush -y updb &&
    sudo -uwww-data drush cc all &&
    sudo -uwww-data drush -y fra &&
    sudo -uwww-data drush cron &&
    sudo -uwww-data drush status-report --severity=2 &&
    echo Deployment completed.
  ",
));

```

And then you can combine them by defining your local aliases in your `drushrc.php`, e.g.

```
$options['shell-aliases'] = array(
  'deploy-dev' => '!drush @dev deploy-db && drush @dev deploy-code && drush @dev deploy-files && drush @dev deploy-drupal',
);

```

So by running simply `drush deploy-dev` it will transfer the files and database from prod into your testing (dev) environment, run updates, clear cache, run cron, revert all features, etc.

---

**Your use case**

Based on above, your use case can be solved by the following commands on local:

1. Clone the site:

```
drush -yv @site exec drush rsync sites/site-1 sites/site-2

```
2. Upload the settings file and modify the database:

```
drush rsync examples/default.settings.local.php @site:sites/site-2/settings.local.php
drush -vy @site exec sed -i -e s/DB_NAME/real_db_name/ sites/site-2/settings.local.php

```
3. Transfer the db between sites.

```
drush -vy @site sql-sync --create-db site-1 site-2

```
4. Enable chosen set of modules:

```
drush -vy @site en module_1 module_2

```

You can create easily the drush alias for that. E.g.

```
drush clone-site site-1 site-2 # Last 2 are arguments.

```

Eventually check how to use policy.drush.inc, so you can add your own pre-process, post-process code for any of your drush command.

---

Read more:
> 7 votes

# Answer
I would install provision.

It's the backend part of Aegir, implemented as a drush extension.

It literally contains the command you are looking for: provision-clone, which will allow you to `Clone a site between platforms`. In provision language, "platform" is a Drupal install. You could just clone the site within the same platform though.

You also have another option in these two commands:

1. backup - Generates a tarball containing the sites directory, the site data configuration and the database dump.
    * This allows the tarball to act as a 'site package', which can be redeployed on other installations, or used for an upgrade.
2. deploy - Accepts a site package (backup) as argument, and redeploys it, running the upgrade processes on it.
    * Uses hook\_provision\_pre\_upgrade(), hook\_provision\_upgrade() and hook\_provision\_post\_upgrade() hooks, and allows clean roll back if any errors occur. Will include stringent checking of module versions, and allow unit tests to be run.

You can completely skip hostmaster, the UI part of Aegir, and work with provision on it's own. Among commonly known projects, I believe this is the closest you will get to what you want.
> 5 votes

# Answer
Unfortunately there is no module to do that you need. A website can’t (and must not) manage the Apache and the MySQL.

**Script base method:** On the past there were many tries to manage Drupal multi-sites with scripts.

You can enhance your custom scripts with Drush, using something like `drush -l site_name` command or `drush @site_name command` (this is why the `drush si` fall apart in your script). But it will automate only the site management and not the site deployment (MySQl, apache Vhost etc).

**Aegir:** As mentioned before by @bgm the “must” way of Drupal multi-site is Aegir. Aegir 2.x is Drupal 6 and consists but 2 major parts (+2 for UI)

* Hostmaster (A Drupal 6 install that manages the other parts)
* Provision (All the Drush based magic to deploy & manage sites)

So if you like to invoke custom scripts and break the Aegir/Drupal best practices but you want to automate site deployment you can use the Provision on a custom way over Drush. But I don't suggest this approach...

Aegir has a steep learning curve (especially if you don’t have help of OPS) but not only you will have an easy deploy/update/management Drupal server but also you will forced to learn and follow Drupal best practices.
> 2 votes

# Answer
To round out some of the answers here, there is also OpenDevShop. It aims to be an Acquia Cloud / Pantheon type hosting environment you can install on your own servers to manage your infrastructure and sites.
> 1 votes

# Answer
Take a look at Druml. It works perfectly with Drupal Multisites.
> 1 votes

# Answer
Have a look at Barracuda Octopus Aegir = BOA. It is an open-source install tool that converts a naked server into a GUI for mass creation of Drupal sites. It supports both Drupal 7 and 8. For Composer-based Drupal 8, you'll have to remove Drush 9 or 10 from `composer.json`'s `require` section.

You'll find the install steps here: https://github.com/omega8cc/boa/blob/master/docs/INSTALL.txt

I found BOA robust and fairly easy to use.

Technical internals:

* Internally, BOA sets up multisites: separate databases and content, but identical code base. That means installing security updates is quicker.
* In contrast, OpenDevShop uses completely independent Drupal installations in separate directories, which reduces coupling between sites: each can have different versions of modules installed. This is especially important for custom module development, as OpenDevShop understands Git branches. As a result, setting up a new site is slower than with BOA, because code needs to be downloaded and typically, Composer needs to run.

BOA is aimed more at non-technical folks than OpenDevShop. However, OpenDevShop has the clone command that the OP wishes for.
> 0 votes

---
Tags: 7, drush, multi-sites
---


# Question
Title: How to automatically change a Content type field value based on Date field?
I'm using Drupal 7, I have a content type, where I have two fields for project allocation:

1. Status(Active/Inactive)
2. End Date

If the "End date" is less than current date, then the "status field" should be Active(By Default, Status will be Active) and if it exceeds current date, then that particular "status field" value in Content type should automatically change to Inactive.

Now, how can I automatically change the field value without any Button trigger?

# Answer
Thanks both Jdrupal and gillarf above. I did something different here, but i used both of your logic.

First, i created a custom module and then i used hook\_menu() function. In this hook\_menu, i used a link and if i call that link then page callback function will execute.

In page callback function, i used dbquery to get the data from the DB and based on my condition, i change the data and then again i used db query to update the DB with new data.

Now, i fixed that link in drupal cron and set it to call the link by particuar time, so that it will execute everyday automatically.

That's it Thanks :)
> 0 votes

# Answer
I think you have to do this with some custom JS code.

You can do something like this:

```
$('.end-date-field').on('change', function () {
  var endDate = new Date($(this).val());
  if (endDate < Date.now()) {
    $('.status-field').val('inactive');
  }
});

```

This code is not 100% correct, but it can help you to get an idea of what you have to do.
> 2 votes

# Answer
I'm assuming this needs to happen behind the scenes rather than as a result of user interaction.

I suggest you write a custom rules action which runs on cron every 5 minutes (or whatever time period you are happy with). The rule should load all of the relevant nodes using a db\_select query, loop through them, check the end date and update the status depending on the comparison result.

Check the video here by Johan Falk on how to create a rules action: https://drupalize.me/videos/creating-rules-action?p=1152

And info for db\_select: https://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_select/7.x

If the site does not get a lot of traffic you might need to fire cron externally. You can use a service like uptime robot to do this (https://uptimerobot.com/), or you can get your server to do it. It will need to hit your cron endpoint.
> 1 votes

---
Tags: 7, rules
---


# Question
Title: How to run alterRoutes on particular condition ? Does it run on cache clear and not on normal Request?
I am trying to implement a feature where I need to run different flow than default flow while the registering user on the site.

I am trying to alter the route of "user password reset" for the for the first time logging users, Below is the code

```
    <?php

    namespace Drupal\developer_registration\Routing;

    use Drupal\Core\Routing\RouteSubscriberBase;
    use Symfony\Component\Routing\RouteCollection;
    use Symfony\Component\HttpFoundation\Request;

    /**
     * Listens to the dynamic route events.
     */
    class RouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
      // The Test is getting printed on only cache clear and not on URL Hit
      echo "Test"; exit;

      if(isset($_SESSION['developer_registration']['email_id'])) {

       if ($route = $collection->get('user.reset')) {
                 $route->setDefaults(array(
                 '_controller' => '\Drupal\developer_registration\Controller\UserCustomController::setPasswd',
              ));
             }
          }
       }
 }

```

The problem is that above alterRoute method doesn't runs on the URL hit. It only runs on cache. But my problem is that I want to run alter route on particular condition.

I am not getting the way to do the same. Please help me.

# Answer
Yes, it runs only on cache clear. You have to implement the dynamic behavior inside of the controller. By extending the core user controller you can call the parent method in case the dynamic condition doesn't apply:

```
class UserCustomController extends UserController {

  public function resetPass(Request $request, $uid, $timestamp, $hash) {
    if (!...) {
      return parent::resetPass(Request $request, $uid, $timestamp, $hash);
    }

    // return the redirect you want
  }

}

```
> 0 votes

---
Tags: users, hooks, routes
---


title: How do you build a conditional form?

text:
# Question
Title: How do you build a conditional form?
How do I build a form with :

* optgroup select for subject
* conditional display of informations depending on the selected subject
* conditional display of a part of the form if a checkbox is ticked

Example :

**\[ Subject** select optgroup **⌄ \]**

*Conditional display : The content below varies depending on what is selected from the drop-down menu.*

If you are looking for informations about \[replace with selected subject\] please have a look a this page before : \[link to the page\]

**\[ Checkbox \]** I can't find what I am looking for on this page.

*Conditional display : The form below is displayed only if the checkbox is ticked.*

* Name : **\[text box\]**
* Email : **\[email box\]**
* Message : **\[text area\]**

**\[Submit button\]**

# Answer
> 0 votes
You can implement all of this conditional logic using the Webform contrib module:

http://www.drupal.org/project/webform

Once you install the module, it provides its own documentation within your Drupal site, and even has links to excellent tutorial videos by module maintainer Jacob Rockowitz.

You could also Google "Drupal Webform conditional" and find tutorials like this one:

https://youtu.be/ic4wu-iZd4Y

That should be enough to get you started.

In the rare event that the Webform module doesn't implement all your form logic, you can export your Webform to YAML and it's a trivial exercise to translate that to Drupal Form API module code (with conditional `#states`) as PHP in a custom module, so it's always good to get as far as you can using just Webform.

---
Tags: 8, forms
---


# Question
Title: Is 8.6.18 insecure? Will there be 8.6.19 etc.?
I have a custom module that I think requires Drupal 8.6.x.

Is Drupal core 8.6.18 insecure? Will more 8.6.x versions be released?

# Answer
> 4 votes
According to the Drupal core release cycle documentation, the last month for security coverage for 8.6 was November 2019. There is no more planned security coverage for 8.6.

Security releases only last through the next minor release cycle. I.e. 1.0 will receive patch and security releases until 1.1 is released. Then 1.0 will continue to receive security coverage until 1.2 is released. Once 1.2 is released (the second minor release since 1.0), 1.0 is considered unsupported.

---
Tags: security
---


# Question
Title: How to display the store url in a TWIG Message?
I have a Drupal 8 site with the Commerce and Message modules.

In my TWIG Message I can display the title of the parent store of the product, but I cannot display the url of the parent store.

How to display the store url in a TWIG Message ?

```
  <a class="stretched-link" href="{{ message.field_product_reference.entity.stores.entity.value }}" title="{{ message.field_product_reference.entity.stores.entity.name.value }}"></a>

```

Do you have an idea ? I tested the following code but none of them work :

```
{{ message.field_product_reference.entity.stores.entity.value }}
{{ message.field_product_reference.entity.stores.entity.url }}
{{ message.field_product_reference.entity.stores.entity.url.value }}
{{ message.field_product_reference.entity.stores.entity }}

```

# Answer
Normally an entity doesn't have a field `url`. The url is built dynamically, but you don't have access to these methods from Twig.

So you use an entity route to build the url:

```
{{ path('entity.node.canonical', {'node': node.id}) }}

```

See https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

In your case use `message.field_product_reference.entity.stores.entity.id` as route parameter. You can find out the route name by visiting a store page and look for `_route` in the output of Devels "Current route info".
> 1 votes

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


# Question
Title: MachineName field element: How do I use the source and exists properties?
In my custom form, I am trying to create webform entities. Since webforms need unique machine names, I'm using the MachineName (machine\_name) form element. The D8 MachineName element documentation suggests that we can get the field to auto-populate based on the text input of another field, AND there can be an AJAX callback to call a function that can check to see if the machine name is unique.

Neither is working for me. These are the form elements I am using.

```
//----------------- general settings ------------------
$form['settings'] = array(
  'label' => ['#type' => 'textfield','#title' => 'Form Title'],
  'id'=> array(
    '#type' => 'machine_name',
    'label' => 'hh',
    '#source' => ['label'],
    '#maxlength' => 64,
    '#description' => $this->t('A unique name for this item. It must only contain lowercase letters, numbers, and underscores.'),
    '#machine_name' => array(
      'exists' => array(
        $this,
        'webform_id_exists',
      ),
    ),
  ),
);

```

Can anyone advise? I have a callback function named, but no idea what it should look like.

# Answer
We can look at Drupal\node\NodeTypeForm.php for an example.

We see the name and type fields defined like:

```
$form['name'] = array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  // ...
);
$form['type'] = array(
  '#type' => 'machine_name',
  // ...
  '#machine_name' => array(
    'exists' => [
      'Drupal\node\Entity\NodeType',
      'load',
    ],
    'source' => array(
      'name',
    ),
  ),
  // ...
);

```

This shows us how to define the special machine\_name type properties in the array. We can see that both exists and source are defined inside `#machine_name`. Additionally, we see that the exists callback is just calling the `NodeType::load()` (which is actually inherited straight from Drupal\Core\Entity\Entity::load()).

For our exists callback, given this example, we'll want to use the equivalent method for whatever kind of entity we're creating a machine name for. Given your example, we're creating webforms, so we'd use the `Drupal\webform\Entity\Webform::load()` method for the exists callback.

We also see, from the machine\_name element documentation, that the source property needs to be the `#array_parents` of the source field. Since your fields are nested inside `settings`, you'll need to include it in the source property.

Given the above, your updated code should be:

```
$form['settings'] = [
  'label' => [
    '#type' => 'textfield',
    '#title' => 'Form Title'
  ],
  'id'=> [
    '#type' => 'machine_name',
    'label' => 'hh',
    '#maxlength' => 64,
    '#description' => $this->t('A unique name for this item. It must only contain lowercase letters, numbers, and underscores.'),
    '#machine_name' => [
      'exists' => [
        'Drupal\webform\Entity\Webform',
        'load',
      ],
      'source' => [
        'settings',
        'label',
      ],
    ],
  ],
];

```
> 3 votes

---
Tags: forms, webforms
---


# Question
Title: How to get image with image style path to a twig template
I had created a field called tv\_adbackground on the settings filed to be a ble to uplaod a background image.

The upload works great!

How to get the path of the file or the image style medium or thumbinal in to a twig template like this?

```
...
 <div id="advertisement"> <!-- background-image uploaded on theme settings page should be used here ->

 <div id=advertisement-dimmer>

 <h3 class="adheading">{{ tv_adheading }}</h3>

<div id="admessage">{{ tv_admessage }}

<div class="btn-group adbuttons" role="group" aria-label="Basic
example">
<button type="button" class="btn btn-primary btn-lg"><a
style="color:#fff;" href="/signup">Register</a>
</button>
<button type="button" class="btn btn-default btn-lg"><a
href="/user/login">Login</a></button>
</div>
</div>

```

I would use css to retrive thte image path but with css i dont get teh variable to get the file path.

I am new to drupal 8 so it would be great if there will be anyone to help

# Answer
> 2 votes
It can be done with the help of two additional modules.

Then in your Twig template you would use something like this to get the image style path:

```
{{ content.field_image.entity.uri.value | image_style('medium') }}

```

where `field_image` is the name of the image field.

If you use something like the Media module then your images come from a referenced entity. In that case you could use

```
{{ file_url(content.field_referenced_entity | field_target_entity.field_image.entity.uri.value | image_style('medium')) }}

```

and `field_referenced_entity` would be the media/entity reference field and `field_image` the name of the image field on the referenced entity. Notice that in the second case the whole path is wrapped in `file_url()`.

# Answer
> 0 votes
As per @Clive on this post.

```
use Drupal\image\Entity\ImageStyle;

$path = 'public://images/image.jpg';
$url = ImageStyle::load('style_name')->buildUrl($path);

```

This is the equivalent of `image_style_url('style', uri)` in Drupal 7.

# Answer
> 0 votes
To get the image with custom style in node.html.twig -

```
<img src="{{ node.IMAGE_FIELD.entity.uri.value | image_style('IMAGE_STYLE_NAME') }}">

```

---
Tags: theming
---


# Question
Title: Twig template for custom entity not working
I created a custom entity (*Representative*) using the Drupal Console `generate:entity:content` command.

The entity works correctly. I added fields, added some content, and I can query this entity.

My problem is that I can't render this entity in a template file, using the following code.

```
$build = [
  '#theme' => 'representatives',
  '#representative_entity' => $representative
];

```

I get the following error.

> Exception: Object of type Drupal\kelk\_representatives\Entity\RepresentativeEntity cannot be printed. in Drupal\Core\Template\TwigExtension-\>escapeFilter() (line 476 of core/lib/Drupal/Core/Template/TwigExtension.php).

Can anyone help?

# Answer
You need to use the entity view builder, to correctly render an entity, like the following code.

```
$view_builder = \Drupal::entityTypeManager()
  ->getViewBuilder('representatives');
$entity_view = $view_builder->view($representative);

$build = [
  '#theme' => 'representatives',
  '#representative_entity' => $entity_view,
];

```
> 3 votes

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


# Question
Title: Print module theming address for user page
I am using the print module to have print-friendly pages. I followed theme suggestions, I could not make the theming work for user pages. So far, I tried the following I would like to theme user pages for printing but I could not figure out how.

```
print--html--user.tpl.php
print--html--user--%.tpl.php
print--html--page--user.tpl.php

```

Example pages to view theme suggestions, here and here.

# Answer
> 0 votes
The Print module only works for nodes. You can use the Entity Print module for Drupal 7.

You can read Entity Print / Usage to understand how to override the default template.

> **Overriding Templates**
>
> You can copy the entity-print.tpl.php template into your theme to take control of the global PDF template.
>
> If you wish to have per entity type templates you can do so by implementing hook\_theme() for different entity type keys, for example:
>
> ```
> function MODULE_theme($existing, $type, $theme, $path) {
>   return array(
>     'entity_print__commerce_order' => array(
>       'base hook' => 'entity_print',
>       'template' => 'entity-print--commerce-order',
>     ),
>   );
> }
>
> ```

---
Tags: 7, theming
---


# Question
Title: How deal with taxonomy term parameter in multilingue site?
I have a custom controller, who take the tid parameter :

```
/myroute/{tid}

```

The tid is upcast with the taxonomy Term so in my controller method I have:

```
public function index(TaxonomyTerm $tid)

```

In this function I can get the taxonomy entity.

But for call my controller, it's not SEO friendly... i have : /myroute/43 for example.

So I won't pass the term name, because you can have spécial caractere and it's not a good pratice in a multilingue site.

So for me the best way is to work with pathauto, generate the path for the taxonomy term so i can have :

/\[term\_category\]/\[term\_name\]

Now my question is how pass this to my controller.

I need to call my controller like that:

`<a href="myroute/{param_taxo}">`

So I am not sure how get the tid of the term with friendly url for SEO.

Any experience about that?

# Answer
> 3 votes
You must edit your route to be like this, `/myroute/{alias}`.

Then you can load the term in your controller like this:

```
public function index($alias) {
  // Find the term by path alias.
  $path = \Drupal::service('path_alias.manager')->getPathByAlias($alias);
  if (preg_match('/taxonomy\/term\/(\d+)/', $path, $matches)) {
    $term = $this->entityTypeManager->getStorage('taxonomy_term')->load($matches[1]);
  }
  if (isset($term) && $term instanceof TermInterface) {
    $term_id = $term->id();
  }
}

```

**NB:** The `path_alias.manager` service is added in Drupal 8.8.x, if you use an older version you must use the `path.alias_manager` service instead.

---
Tags: 8, entities, taxonomy-terms, path-aliases
---


# Question
Title: Enable a button basing on multiple form values being equal
I would not like users to be able to submit a form until:

1. All fields are filled out
2. The password and confirm password fields are equal

I can do this with JavaScript, potentially, but then the JavaScript code would managing some states and the PHP code would manage other states. It seems messy.

This is the code I wrote.

```
'disabled' => array(
// disable button if missing required fields
        array(
          ':input[name="field1"]' => array('value' => ''),
        ),
        array(
          ':input[name="field2"]' => array('value' => ''),
        ),
        array(
          ':input[name="password"]' => array('value' => ''),
        ),
        array(
          ':input[name="confirm_password"]' => array('value' => ''),
        ),
      ),

      // only enable the button when passwords are ==
'enabled' => array(
        array(
          ':input[name="password"]' => array('value' => ':input[name="confirm_password"]')
        )
      )

```

# Answer
> 0 votes
```
'array('value' => ':input[name="confirm_password"]')

```

This means the value equals the literal string ":input\[name="confirm\_password"\]". As far as I know, `#states` can't check if the value of two fields are the same.

> I can do this with JavaScript, potentially, but then the JavaScript code would managing some states and the PHP code would manage other states. It seems messy.

Here is a way that may seem less messy. Use a hidden `compare_passwords` field whose value will indicate whether the `password` and `confirm_password` fields have the same value:

```
$form['compare_passwords'] = array('#type' => 'hidden', '#default_value' => 'fail');

```

Use the value of that field in the `#states` array for your button.

```
':input[name="compare_passwords"]' => array('value' => 'match')

```

Write some JavaScript that changes the value of `compare_passwords` whenever the value of `password` or `confirm_password` changes (use .on() instead of bind() if your site uses jQuery 1.7+):

```
var password_selector = ':input[name="password"]';
var confirm_selector = ':input[name="confirm_password"]';
var compare_selector = ':input[name="compare_passwords"]';
$(password_selector + ',' + confirm_selector).bind("change paste keyup blur", function () {
  if ($(password_selector).val() == $(confirm_selector).val()) {
    $(compare_selector).val('match').change();
  } else {
    $(compare_selector).val('fail').change();
  }
});

```

By the way, you can use `'!value'` to put all your *"does not equal empty string"* conditions under "enabled", using the Boolean "AND" structure. The Boolean "OR" structure, which is wrapping each condition in its own array, is harder to understand if you aren't familiar with `#states`.

```
// Only enable the button when all fields have a value and passwords match.
// The value in "compare_passwords" is dynamically updated by my_script.js
//  whenever the user types inside the password or compare_password fields.
$form['my_button']['#states'] = array(
  'enabled' => array(
    ':input[name="field1"]' => array('!value' => ''),
    ':input[name="field2"]' => array('!value' => ''),
    ':input[name="password"]' => array('!value' => ''),
    ':input[name="confirm_password"]' => array('!value' => ''),
    ':input[name="compare_passwords"]' => array('value' => 'match'),
  ),
);

```

---
Tags: 7, forms
---


# Question
Title: “admin/people” filters not available anymore
I have Drupal 8.7.3 so at admin side on people listing page I can't see the filter to find a particular user.

# Answer
I would check:

1. Is the views module still enabled?
2. Is this specific view enabled?
3. Did the configuration get changed for the view that exists at admin/people?

For #1, go to the modules page and scroll down to views and confirm it is enabled.

For #2, I noticed that I was able to "Disable" the `user_admin_people` view and then I get a screen at `admin/people` that looks exactly like yours. The resolution to that problem is to go to `/admin/structure/views/` and "Enable" the `user_admin_people` view.

For #3, you could install a fresh version of Drupal 8.7.3 and compare the configurations of the view to find if it's wrong.
> 2 votes

# Answer
As greggles mentioned it, first thing is to check that the configuration of the view did not change. Go to yoursite.com/admin/structure/views/view/user\_admin\_people and look for any exposed filters in the "Filter criteria" section (maybe your features altered the configuration).

Here is an example of Drupal default configuration for this view.
> 1 votes

---
Tags: views
---


# Question
Title: How to use text from a block view as a prefix to a node title
> What I would like to do

In Durpal 7, I am using a block view to display our manufacturers name above our node titles. We added a custom region above content, and that is working fine. However, I would like the manufacturer to be display **inline** with the node title.

> How I handled it in Drupal 8

In this related question I asked about a Drupal 8 solution.The drupal 8 solution was a little simpler in that we migrated all manufacturer fields into 1 manufacturer field. which made things much easier to code. In my drupal 7 site, the manufacturer fields are separate making it a little messier to handle with code in that there would need to be an instance of the code for every manufacturer/node combo.

> My question

For drupal 7 is it possible to render a **block view** as an inline prefix to a node title? Placing a block view in this circumstance seems like it would be a much simpler and more front end Drupal approach. Especially since I can have all of the manufacturer fields in the one block view, and they will render according to Taxonomy term ID contextual filter.

# Answer
So this is what I did, in case anyone wants to accomplish the something similar.

You first have to add a new region just above the content region in your `MY_THEME.info` file which in my case was:

```
regions[manufacturer_prefix_title]    = Manufacturer Prefix Title

```

Then I overwrote the `page.tpl.php` which contained:

```
  <?php if ($title): ?>
    <h1><?php print $title; ?></h1>
  <?php endif; ?>

```

to each node instance I needed `page--MY-NODE.tpl.php` which now contains:

```
  <?php if ($title): ?>
    <?php print render($page['manufacturer_prefix_title']); ?>
  <?php endif; ?>

```

(The above required a preprocess\_page hook.)

Then I created a block view, with the **contextual filter** set to `NID`. I also added **filter criteria** to get only the desired content types.

I added the 3 Content: Manufacturer fields, ticked `exclude from display` on each, and ticked `rewrite the output of this field` on each so that I could use the **replacement pattern** for those fields and wrap each one in the `span class` I wanted:

`<span class="MY-CLASS">[field_MY_FIELD]</span>`.

I also made sure to tick `hide if empty` under **no results behavior** so that the span class would not get rendered when the field was empty, as these fields are not required.

I then added the Content: Title field once, and ticked `rewrite the output of this field` and used replacement patterns for each of the manufacturer fields, leaving one space in front of the title:

```
[field_MY_FIELD_1][field_MY_FIELD_2][field_MY_FIELD_3] [title]

```

Since the **contextual filter** was set to `NID`, the title will only grab the appropriate taxonomy reference field, as only one is allowed per node.

Then all that was left was to simply place the new view block @`admin/structure/block` into the new region that was created in the `MY_THEME.info` file. I also configured the block to only show on the same content types that i defined in the **filter criteria** of the block view.

Hope this helps someone! :)
> 0 votes

---
Tags: 7, views, theming
---


# Question
Title: How do I create a view for a single node?
I have a *Company details* content type used to create 20 nodes. I created a view for that content type which displays all its nodes.

I want to create a view for a single node. Is it possible? How?

# Answer
> 1 votes
You can view the item at /node/{node\_id}. If you need the item in a view, you can add a filter to the view for the node's id.

---
Tags: views, nodes
---


# Question
Title: Migrations dependencies: run one by one?
I have a few migrations in the same group for singe multi-language entity type set up. One migration handles one language. I need to make sure that default English language migration runs first and then it triggers all the others when I execute migration for the English language via admin UI of migrate tools module.

Can not find how make it through dependencies in yml for the default language, because dependencies list gets processed first. Is there proper way to do it?

# Answer
> 0 votes
First of all, you only need two yaml files, one for the default language and one for the translations.

If you are migrating for example a content type of bundle `pages` and your default language migration is eg. `my_website_migrate_node_page`, then in the `my_website_migrate_node_page_translation` define your dependencies as follows

```
migration_dependencies:
  required:
    - my_website_migrate_node_page
  optional: { }

```

---
Tags: 8, migrations
---


# Question
Title: Shipping method and shipping service from a placed order
I am trying to get the shipping method and the shipping service values after i place an order on a Drupal 8 commerce website so i can use it inside an email im sending the website's owner (not the receipt for the client). I know Swift email would be an option but i have to continue with what i have. So far the owner of the website does receive an email but i need to add more information to it like the shipping method and shipping service.

I've got as far as finding out that $order-\>shipments-\>entity will give me, among other values, these 2 fields shipping\_method and shipping\_service.

```
Shipment {#4521 ▼
  #values: array:19 [▼
    "shipment_id" => array:1 [▶]
    "type" => array:1 [▶]
    "uuid" => array:1 [▶]
    "order_id" => array:1 [▶]
    "package_type" => array:1 [▶]
    "shipping_method" => array:1 [▼
      "x-default" => "2"
    ]
    "shipping_service" => array:1 [▼
      "x-default" => "PRIORITY_OVERNIGHT"
    ]

```

Where do I find the values of the shipping method value whose ID is 2 and the shipping service value whose ID is PRIORITY\_OVERNIGHT?

# Answer
> 6 votes
Since *shipping\_method* is an entity reference field, you can use `$order->shipments->entity->shipping_method->entity` to get the referenced entity.

`$order->shipments->entity->shipping_service` is not a entity field, so you get its value with `$order->shipments->entity->shipping_service->value`.

---
Tags: 8, entities, commerce
---


# Question
Title: Trigger custom code on existing Webform Submissions
I have created a custom Webform handler which submits the Webform data to an external webservice via SOAP. All is working but now I need to submit (to the same external web service) all the older Webform submissions that were received before I enabled my custom handler.

My current custom handler has my custom SOAP code wrapped in the function

```
public function preSave(WebformSubmissionInterface $webform_submission)

```

(I'm using the preSave function as the Webform is a multipage form.)

I was just wondering what function I should use to run the same SOAP code on existing submissions?

As I know the range of submission ID's that are affected, is there code that can loop through the submissions and trigger the code based on the Submission ID?

Or alternatively, as there only about 20 of the older submissions, I could open and save each one to trigger a Handler based on submission update - in which case, what is the function call I need to wrap my SOAP code in the custom handler?

Thanks

F

# Answer
> 0 votes
Just install devel php run your code and then uninstall it. https://www.drupal.org/project/devel\_php As it is great for quick adhock tasks.

but yep keep back up of your database ect.

---
Tags: webforms
---


# Question
Title: Why I am not able to add custom validate Handler function for UserPasswordResetForm on form_alter?
I am trying to override default reset password functionality by using hook\_form\_FORM\_ID\_alter as below: The below code is written in custom module called usr\_registration.module file

```
    /**
     * Implements hook_form_FORM_ID_alter().
     */
    function usr_registration_form_user_pass_reset_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id, AccountInterface $user = NULL, $expiration_date = NULL, $timestamp = NULL, $hash = NULL) {

            $form['account']['pass'] = [
            '#type' => 'password_confirm',
            '#size' => 25,
            '#description' => t('Provide a password for the new account in both fields.'),
            '#required' => TRUE,];

             $form['#validate'][] = 'usr_registration_validate';
             $form['actions']['submit']['#submit'][] = 'usr_registration_form_user_pass_reset_custom_submit';
    }

    // this function itself is not getting called
    function usr_registration_validate(&$form, FormStateInterface $form_state) {

      //unable to see below debug message and form is getting submitted
       echo "I am here"; exit;

       if($never_login) {
                        //some custom logic
       } else {
                       //some custom logic
       }

     }

```

The important thing I noticed in UserPasswordResetForm class(user core module's form) is that there is no default validate method defined. I am unable to find out that why I cant alter the UserPasswordResetForm and custom validate handler over here.

note: My question is similar to this but not exactly same so please dont mark it as redundant.

# Answer
> 3 votes
$form\['#validate'\] will not work as that form "This form works by submitting the hash and timestamp to the user.reset" aka redirects you to the user.reset from

what you can do is something like temp replace this form with a custom one though. however i don't really see the point

```
/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'user_pass_reset') {
    $action = $form['#action'];
    // Set the original action.
    $form_state->set('original_action', $action);
    // temp replace from with custom one.
    $form = \Drupal::formBuilder()->buildForm('\Drupal\yourmodule\Form\AlterTheLoginResetFrom', $form_state);
    return $form;
  }
}

```

then do

```
class AlterTheLoginResetFrom extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'alter_the_login_reset_from';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Get the stuff you need from ...
    dump($form_state->get('original_action'));
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
      // @TODO: Validate fields.
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // redirect to original as uses get
  }
}

```

or alter the user.reset directly see Drupal\user\Form\UserPasswordResetForm; line 60 & 71 and see how core does it (resetPassLogin) \Drupal\user\Controller\UserController::resetPassLogin

if all else fails perhaps just validate the passwords in js.

---
Tags: forms, hooks
---


# Question
Title: Looking for a way to trigger an event for testing custom event subscriber
I am looking for ways to trigger an event in my local dev to check out a custom event subscriber. The actual event is triggered by Google social auth and I don't think it is possible to do that locally.

Is it possible to trigger events using devel

# Answer
> 5 votes
You can use the *event\_dispatcher* service to trigger an event, for example with `\Drupal::service('event_dispatcher')->dispatch(MyModuleEvents::MY_EVENT, new MyModuleEventClass());`.

You need to replace `MyModuleEvents` and `MyModuleEventClass` with the class names you are effectively using, and `MyModuleEvents::MY_EVENT` with the effective event name. (It is better to use a class constant.)

You can run the code using `drush php "\Drupal::service('event_dispatcher')->dispatch(MyModuleEvents::MY_EVENT, new MyModuleEventClass());"`.

See Subscribe to and dispatch events for more details.

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


# Question
Title: Search api solr: The Solr server could not be reached
I've got a working solr server, however my drupal always fails to connect, what am I doing wrong?

When adding my server and clicking on the solr server url it takes me to my server (so my path is correct), yet I keep getting a message: The Solr server could not be reached.

I am hosting apache solr on a server (not locally).

* Host: Server IP address
* Port: 8983
* Instance: /solr

Can anyone help me out ?

# Answer
> 4 votes
@see "Your site was unable to contact the Apache Solr server"

I follow this article https://www.lullabot.com/blog/article/installing-solr-use-drupal ,some day comes this errors after I reconfig of my site& apache. but I sloved like this

# Answer
> 1 votes
I was experiencing the same problem: Drupal 7.41 Tomcat 8 Solr 4.10.4

So my work around was: Step 1: Solr path config - enter :/solr/. This caused the SOLR and Drupal to be able to communicate.

However, the index fails because the URL cannot be used for the httpPost or httpGet. The following error will surface: SearchApiException while deleting items from server : "400" Status: HTTP method POST is not supported by this URL: HTTP method POST is not supported by this URL

Step 2: Remove '#/~cores/' The correct URI is the path listed in SOLR w/o the extra characters. Surprisingly, once I ran cron and restarted tomcat - the servers were still able to communicate and the index ran as designed.

NOTE: I had to delete the index configuration that failed and reconfigure AFTER making these changes. It seems there's some type of weird caching that 'remembers' the configuration ::shrug:::

Worked for me. And I hope it works for you. It took me a couple of hours to figure it out.

/r

# Answer
> 1 votes
For some reason, in my case, the following string worked: /solr/#/drupal

So, the full URI: http://127.0.0.1:8983/solr/#/drupal

# Answer
> 1 votes
In `Solr Host` field, you can try entering value: `127.0.0.1` and for Solr path you can leave it empty.

# Answer
> 1 votes
I was experiencing this bug *only when indexing*. Which was making me think it's due to misconfiguration.

```
    Drupal\search_api\SearchApiException while trying to
index items on index main:
Solr endpoint https://mysite:443/solr/main/ unreachable

```

It turns out, this error can happen when it actually *has* reached the server, but you try to do something that throws an error in SOLR.

```
    [c:main s:shard2 r:core_main_node2 x:main]
o.a.s.h.RequestHandlerBase org.apache.solr.common.SolrException:
ERROR: [doc=mysite-main-entity:node/10:en]
multiple values encountered for non multiValued
field bs_mycustom_field: [true, true]

```

I was trying to add an array to a boolean in my custom processor!

It had worked previously but something changed where it was less forgiving.

I changed from this:

```
$mycustomfield->addValue(($data_item['status'] === "1"));

```

to this:

```
$mycustomfield->setValues([$data_item['status'] === "1"]);

```

in my custom SearchApiProcessor plugin (Drupal 8), then it indexed without issue.

The big takeaway here is, this error can be misleading! It did reach SOLR!

---
Tags: 7, search
---


# Question
Title: Is there a way to get a value of a multi value field of an entity reference (reference a field value of a referenced term)?
I hope that maybe someone had a similar use case and has an idea how to solve it: I have content type that has an entity reference field to a vocabulary. With that I would like to achieve it to not only reference to the term itself in the manage display (in my case a country name), but also choose a certain value of a multiple value field of that term (one of the several historic names of that country). I created a hack with an additional list field in the content type (choose historic name 1, 2, 3...), but this is no good solution because as soon as I modify the order of the field items (e.g. because of adding one), the name is displayed wrongly all over the website. So there is the need to directly reference the field value of the referenced term itself.

# Answer
You can do this in a custom field type based on the core reference field, adding a second property and dynamically filling the options of the select list depending on the first property.

For the multi-value part of your question a non-coding solution would be a paragraph containing both fields. Adding the dynamic behavior can then be done in a form alter hook or you can try Business Rules and adjust this recipe to your requirements: https://www.drupal.org/docs/8/modules/business-rules/advanced-usage/dependent-field
> 2 votes

# Answer
You achieve this with a multi-level taxonomy. Your country name would be the term on the top level and then the historic names would exist as children terms. You could write some code to infer the root term based on the historic term selected. Maybe as simple as having a second field on your entity and just populating it with the historic term's parent on entity save.
> 0 votes

---
Tags: 8, entities, taxonomy-terms
---


# Question
Title: List options without typing on autocomplete
Is it possible to show options when user clicks to the input field instead of showing after typing at least one matching character?

Autocomplete starts showing the options after user types one character but it is hard to guess for new users what's the possible options for related field.

# Answer
> 1 votes
A possible solution is showing the field as a select list and use the Chosen module to be able to search through the options.

> By default the module will automatically apply itself to any select elements that have more than 20 options, which is a reasonable default for which having Chosen will be useful. To change or disable this automatic enhancement, you can change the selectors (or remove all selectors) from the *Apply Chosen to the following elements* field on the Chosen administration page.
> You can force enable/disable Chosen for certain field widgets: Select list (for both list and date fields), and Select (or other) list. If you have a field using one of these widgets, in the field settings, you will find a *Apply Chosen to the select fields in this widget?* option with three values: Apply, Do not apply, or No preference (which will fall back to using the automatic application).

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


# Question
Title: I cannot update because of Ubercart and Google Analytics module error
I tried updating my Google Analytics module today, but when I went to the update.php page I got this error:

```
Unresolved dependency. Google Analytics (Version !=7.x-2.4 required)
Google Analytics for Ubercart requires this module and version.   Currently using Google Analytics version 2.4

```

I've tried everything to resolve this error. I found this page pretty easy, but none of the suggestions work. I installed Google Analytics 7.x-2.6, so I shouldn't be getting this error.

So far, I've tried:

* Clearing my cache
* Installing Google Analytics 7.x-2.3 and 7.x-2.x-dev
* Downloading the latest version of Ubercart
* Refreshing update.php and clearing browser's cache
* Modifying ubercart module's uc\_googleanalytics.info like the link above describes

I can't disable the Google Analytics module either because the checkbox is greyed out

# Answer
If you are seeing the message `Unresolved dependency. Google Analytics (Version !=7.x-2.4 required)` when you have Google Analytics 7.x-2.6 installed, then almost certainly you have a duplicate copy of the Google Analytics module somewhere under your web root. That is not allowed in Drupal. When Drupal scans the file system looking for modules it will find both copies, and you don't know which copy Drupal will end up using (you can even have a case where some files from one copy are used and some files from the second copy are used!). Make sure you delete the old module entirely, or if you really want to save a copy then move it somewhere NOT under the Drupal web root.
> 0 votes

---
Tags: 7, ubercart, updating, google-analytics
---