# Question
Title: How do I run PHP code when visiting a specific URL?
In Drupal 8, I want to visit a link (e.g. www.domain.com/url-link) which should activate PHP code which is in a module.

Is there a hook which support this? If so, how do I implement this?

# Answer
> 1 votes
Apart from controllers, one could also listen for Events, using code similar to the following. Depending on what the custom logic mentioned in the OP is expected to do, this could be an alternative answer.

**nncbt.services.yml**:

```
services:
  nncbt_event_subscriber:
    class: '\Drupal\nncbt\EventSubscriber\NNCBTSubscriber'
    arguments:
      - '@logger.factory'
    tags:
      - { name: 'event_subscriber' }

```

**src/EventSubscriber/NNCBTSubscriber.php**:

```
<?php

namespace Drupal\nncbt\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Drupal\Core\Logger\LoggerChannelFactory;

/**
 * An EventSubscriber for REQUEST and TERMINATE events.
 */
class NNCBTSubscriber implements EventSubscriberInterface {

  /**
   * The logger.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Logger\LoggerChannelFactory $logger_channel_factory
   *   For logging purposes.
   */
  public function __construct(LoggerChannelFactory $logger_channel_factory) {
    $this->logger = $logger_channel_factory->get(self::class);
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['earlyCode'];
    $events[KernelEvents::TERMINATE][] = ['lateCode'];
    return $events;
  }

  /**
   * This method is called for KernelEvents::REQUEST events.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The incoming event.
   */
  public function earlyCode(GetResponseEvent $event) {
    $uri = $event->getRequest()->getRequestUri();
    $this->logger->info($uri);
  }

  /**
   * This method is called for KernelEvents::TERMINATE events.
   *
   * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
   *   The incoming event.
   */
  public function lateCode(PostResponseEvent $event) {
    $uri = $event->getRequest()->getRequestUri();
    $this->logger->info($uri);
  }

}

```

Good luck!

# Answer
> 0 votes
In Drupal 8, you need to create a simple module.

Create the *modules/custom/mymodule* directory, and put the following files.

### mymodule.info.yml

```
name: Mymodule
type: module
description: Mymodule simple module.
core: 8.x

```

### mymodule.routing.yml

```
mymodule:
  path: '/urllink'
  defaults:
    _title: 'Page Title'
    _controller: '\Drupal\mymodule\MymoduleController::content'
  requirements:
    _permission: 'access content'

```

### src/MymoduleController.php

```
<?php
/**
 * @file
 * Contains \Drupal\mymodule\MymoduleController.
 */

namespace Drupal\mymodule;

use Drupal\Core\Controller\ControllerBase;

class MymoduleController extends ControllerBase {
  public function content() {
    //custom logic
    // ...
    $markup = "custom logic output";
    return array(
        '#markup' => $markup,
    );
  }
}

```

Install the module.

When you visit http://example.com/urllink on your site, the page will display whatever you put in `#markup`.

---
Tags: 8, hooks
---


title: Modify field names in REST export

text:
# Question
Title: Modify field names in REST export
I want to use a custom field in my Views REST export, but rather than having "nothing": "My custom text", I would like "mycustomtext": "My custom text". Is there a way to do this from within the UI?

# Answer
> 7 votes
*Serializer settings:* **force using field & json**

*Show:* **fields**

*Show settings:* type an alias for each field

Above settings are shown in the images below

---
Tags: views, 8
---


# Question
Title: From my child theme, how can I remove a library loaded by the parent theme?
I have hit an issue which I think is quite unusual or peculiar when settingup a child theme.

A commercial parent theme I have bought loads the Slick library like this in its theme.libraries.yml:

```
slick:
  version: VERSION
  css:
    component:
      css/vendor/slick.css: {}
      css/vendor/slick-theme.css: {}
  js:
    js/vendor/slick.min.js: {}

```

But I don't want the Slick library to be loaded by the parent theme because I will be installing the Slick module, and will be using Slick Views. I found the Slick library loaded by my parent theme was (of course it was) conflicting with the same library loaded by the Slick module.

My idea is somehow in my child theme's childtheme.libraries.yml file override and tell Drupal to ignore the instruction by the parent theme to load the Slick library. If that is not possile, then may I do that in my childtheme.theme file?

The only workaround I could find so far was to hack the parent theme and comment out the lines where Slick library is loaded, but I know this is a bad practice in case I need to update the parent theme in the future for some reason.

What is the best approach for this problem? Thank you.

# Answer
> 9 votes
You can add overrides to your child theme's info.yml file, telling Drupal not to load the slick library from the parent theme.

Refer to the "Libraries-override" section of this well documented blog post explaining and demonstrating the many options available in terms of removing/replacing files called by other modules and themes with specific ones in your theme.

For your use case, you probably just want to remove (aka disable) both css and js files for slick.js from the parent theme. So your "library override" will resemble either:

**Case 1**: slick is part of a library in the parent theme that includes multiple css and js files for the theme, not just slick

```
libraries-override:
  parent_theme/parent_theme_library_that_includes_slick:
    css:
      theme:
        path_to_parent_theme_or_vendor_slick_library_folder/slick.css: false
        path_to_parent_theme_or_vendor_slick_library_folder/slick-theme.css: false
    js:
        path_to_parent_theme_or_vendor_slick_library_folder/slick.min.js: false

```

**Case 2**: slick is part of a standalone library in the parent theme

```
libraries-override:
  parent_theme/slick_library_name: false

```

You won't need to declare a replacement in your libraries-override, since you're using the Slick module itself, and it will load relevant files needed.

---
Tags: javascript
---


# Question
Title: Views REST Endpoint With paragraph field
I've created a REST export view to get a paragraph field in a JSON format but I cannot get the result properly, so I used Rest Views module but I got the results including something like these characters `\u003Ca href=\u0022\/colors\/gray-metallic\u0022 hreflang=\u0022en\u0022\u003EGray Metallic\u003C\/a\u003E`

Also, this paragraph field includes a term reference field.

So I want to render the data properly without these characters and as a plain text

# Answer
> 0 votes
I have solved by using jQuery.parseHTML() or you can use Javascript DOMParser

Something like this

```
$.ajax({
    type: 'GET',
    url: drupalSettings.path.baseUrl + 'REST_VIEW_PATH/' + nid,
    success: function (data) {
        {
            var paragraphField = data[0]['FIELD_NAME'];
            $.each(paragraphField, function (index, item) {
                var fieldItem = $.parseHTML(item.FIELD_ID_IN_PARAGRAPH);
                console.log(fieldItem[0]['innerText']);
            });
        }
    }
});

```

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


title: Alter field value before render

text:
# Question
Title: Alter field value before render
In Drupal 8, I was thinking that's a simple task but it's not :

```
function hmytheme_preprocess_field(&$variables, $hook) {
    $element = $variables['element'];
    if (isset($element['#field_name'])) {

        if($element['#field_name'] == "bar"){
             element['#items']->value ="foo";
             //or
             element['#items']->set(0,"foo");
        }
    }
}

```

this is not afecting the render. How to ? I don't whant to save the altered value

# Answer
> 6 votes
It's too late to change the field object, because the field is already prepared for rendering. You have to find the field value inside of the render array, for example in `#markup`, and change it there. Where you find the value depends how your field display is configured in the view mode.

> While possible, there's often a better way. You could make your own formatter that returns the structure that you want. #text is a formatted text field, you could make a filter that transforms the text the way you want. Depends on what you want to do exactly.

(Comment from @Berdir)

See the drupal docs how to create a custom field formatter:

https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-formatter

# Answer
> 2 votes
As above mentioned you have to alter the #markup, example for field "field\_block\_iframe" below:

```
/**
 * Implements hook_preprocess_field().
 *
 * @param $variables
 * @param $hook
 */
function THEME_preprocess_field__field_block_iframe(&$variables, $hook) {
  $variables['items'][0]['content']['#markup'] = 'Going down, to the core.';
}

```

---
Tags: entities, 8, hooks
---


# Question
Title: How to add a new line item to existing recurring order?
I've managed to get new line items added to a recurring order using hook\_commerce\_license\_billing\_order\_refresh\_alter() and the code is:

```
$product = commerce_product_load_by_sku($sku);
$li = commerce_product_line_item_new($product, '1');
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_needs_save = TRUE;
commerce_line_item_save($li);
$line_items[$li->line_item_id] = $li;

```

It adds line items and correctly calculates new total and shows on the recurring order page. However, since this is a refresh hook it keeps creating new products, line items and licenses on every refresh. So I tried to attach already created line items the order's data array:

```
// Add line item objects to order data.
$order->data['lis'][] = $li;
// Add sku to order data.
$order->data['skus'][] = $sku;

```

and then re-use it with:

```
if (!empty($order->data['lis'])) {
        foreach ($order->data['lis'] as $key => $li) {
          $wrapper = entity_metadata_wrapper('commerce_order', $order);
          $order_needs_save = TRUE;
          $line_items[$li->line_item_id] = $li;
        }
      }

```

but, unfortunately, the new line items do not show on the recurring order. If I add `commerce_line_item_save($li);` line, then the website crashes giving:

```
EntityMetadataWrapperException: Unable to get the data property line_item_id as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 457 of /home/username/public_html/sites/all/modules/entity/includes/entity.wrapper.inc).

```

So my question is: how I should properly add new line items to existing recurring order?

# Answer
> 1 votes
It works even with:

```
if (!empty($order->data['lis'])) {
  foreach ($order->data['lis'] as $key => $li) {
    $line_items[$li->line_item_id] = $li;
  }
}

```

However, to avoid re-adding new line item every recurring cycle, the hook\_commerce\_order\_update should be used instead as recommended on https://cgit.drupalcode.org/commerce\_license\_billing/tree/commerce\_license\_billing.api.php#n129:

> Modules that need to respond to a license plan or recurring order changing should use hook\_commerce\_order\_update instead.

---
Tags: 7, commerce
---


# Question
Title: Correct way to append value to serialized array in key_value table
I have a serialized array in the value field of `key_value`, to which I constantly what to append values. An easy way to do this is to get the array, append the new value, and reinsert it. However, with a large enough array it's quite inefficient and in theory it can be done on an SQL level.

What's the correct way to do this in Drupal 8? Is there a way that does not involve getting and then setting the array?

# Answer
The best way to go about doing this is by using config API. If somehow this option is not suitable for your use case. You can also use the DB API to update the desired congratulation table records. In both cases, you will need to unserialize the blob then change the data and serialize it back before inserting it into the database.

https://www.drupal.org/docs/8/api/configuration-api/configuration-api-overview
> -1 votes

---
Tags: 8
---


# Question
Title: How do I set a variable to the value of a field another field?
How do I set a variable to the value of a field another field?

For example, what is the equivalent of the following code, which should set the value of `video_Source` to the value of the field that is not empty/null?

```
{% set video_Source = content.field_video_upload or content.field_video_youtube %}

```

# Answer
> 1 votes
This is something better suited for preprocess in my opinion (I don't like a lot of conditional etc logic in twig files):

```
$variables['node_video'] = NULL;

if ($node ... field_a has value) {
  $variables['node_video'] = // set to render element for field a in 'content';
}

if ($node ... field_b has value) {
  $variables['node_video'] = // set to render element for field b in 'content';
}

```

Then in twig:

```
{% if node_video %}
  {{ node_video }}
{% endif %}

```

Basically, if this variable is not null, it should point to one of the `$variables['content']['field...']` items from the preprocess code, then render it. `{{ node_video }}` in this case is the equivalent of `{{ content.field_name }}`, to spare a lot of IF/ELSE/OR stuff in Twig.

But what is likely easier is leveraging Media and Media Youtube with Media Video and using one field. That should scale. Imagine you want to add Vimeo, Twitch, or other supported Media sources in the future, you would have to keep expanding on this code.

---
Tags: theming
---


# Question
Title: Too few arguments to function drush_migrate_tools_migrate_messages()
I'm in the middle of a D7-\>D8 migration and tried running the command `drush migrate-messages` but got the following error:

```
ArgumentCountError: Too few arguments to function drush_migrate_tools_migrate_messages(),
0 passed in /mysite/vendor/drush/drush/includes/command.inc on line 422 and exactly 1
expected in drush_migrate_tools_migrate_messages()

```

but I've never had this error before running the same command and can't find anything in the documentation about it.

# Answer
The **Examples** section makes it pretty clear. `drush migrate-messages` expects one parameter, the machine name of your migration for it to display the migration messages. There's no "show all" option. Run `drush migrate-status` to see all migration machine names (left column) available.
> 0 votes

---
Tags: drush, migrations
---


title: Remove links in the login block

text:
# Question
Title: Remove links in the login block
I want to remove the following default links on the login block.

* Create new account
* Reset your password

I used `hook_form_alter()` but there is nothing in there that creates these links.

# Answer
> 3 votes
**Method #1**

Implement *hook\_preprocess\_block()* in your module/theme.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function HOOK_preprocess_block__user_login_block(&$variables) {
  $variables['content']['user_links']['#access'] = FALSE;
}

```

**Method #2**

Override *block--user-login-block.html.twig* template and replace `{{ content }}` with the following `{{ content|without('user_links') }}`.

Note that hiding those links would not protect respective pages (*user/register* and *user/password*) from direct access.

# Answer
> 0 votes
It's better to set proper permissions, because removing the links won't prevent users from typing `user/register` and `user/password` in the browser's address bar and reaching them directly.

However, if you really want to remove those links from the login block using the hook, then the following code should work:

```
function hook_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block') {
    unset($form['links']);
  }
}

```

---
Tags: 8, forms, users
---


title: Where should modal content be placed?

text:
# Question
Title: Where should modal content be placed?
I would like to create modals for special offers and promotions. I know how to open them either using drupal.dialog or OpenModalDialogCommand. This works fine.

But what is the best place to put the content for the modal? I started adding it in the JS with .appendTo('body'). This works, but the modal content is complex and contains a lot of elements. I would like to know wheter there is a better place to put this modal content?

# Answer
> 0 votes
There are couple of things you could consider before deciding on a particular approach.

1. **Is this data static**?

If yes, then you could store data in memory and retrieve as needed. Performance should no longer be an issue as our js libraries are being loaded on demand and I am sure there are many other ways to optimize your code to work for your particular need.

2. **Is this dynamic data stored in db?**

You could expose your data using the built in REST solution. Once you have your data exposed. You could just use jQuery REST api's to retrive your data.

Hope this helps.

---
Tags: 8, theming
---


# Question
Title: How to group-by fields in view AND control output via template file
I 'm hitting a brick wall on this one, so trying to reach out for help. I did try to research this but could not find anything helpful.

What I have: I have a content type of 'courses', which have title, code, credits and semester (semester ranges from 01 to 10, and it is a vocabulary and each course is linked to a term from this vocabulary).

What I want: I want to create a view page, which lists **all** courses, i.e. their title, code and credits, and those courses should be grouped (and sorted) by their semester.

Ideally, I want all this to be presented with an accordion, so for example the final page should be something like:

```
Course Title     | Course Code     |     Course Credits   {titles}

-- Semester 01 -- [ collapsible accordion header]
Course #1 title  | Course #1 Code  |     Course #1 credits
Course #2 title  | Course #2 Code  |     Course #2 credits
Course #3 title  | Course #3 Code  |     Course #3 credits
-- Semester 02 -- [ collapsible accordion header]
Course #4 title  | Course #4 Code  |     Course #4 credits
Course #5 title  | Course #5 Code  |     Course #5 credits
-- Semester 03 -- [ collapsible accordion header]
Course #6 title  | Course #6 Code  |     Course #6 credits
Course #7 title  | Course #7 Code  |     Course #7 credits
Course #8 title  | Course #8 Code  |     Course #8 credits
Course #9 title  | Course #9 Code  |     Course #9 credits

```

I hope this above sketch shows what I 'm trying to achieve.

I am new to Drupal and I don't have a good grasp of Views yet, so this probably adds to my confusion. I feel quite confident with twig and templates, so I tried to do it from there, but hit a problem.

What I did:

Created a new View, where I show **content** of type **courses**.

In it, I create a **page** of **unformatted list of teasers** and using filename suggestions with the debug mode enabled, I created the file:

node--view--\[course\_content\_type\_name\].html.twig

I can write the accordion markup in there and everything, the problem is that the 'semester' info obviously pops up in every row...

The best I can come up with, is something like:

```
-- Semester 01 -- [ collapsible accordion header]
Course #1 title  | Course #1 Code  |     Course #1 credits
-- Semester 01 -- [ collapsible accordion header]
Course #2 title  | Course #2 Code  |     Course #2 credits
-- Semester 01 -- [ collapsible accordion header]
Course #3 title  | Course #3 Code  |     Course #3 credits
-- Semester 02 -- [ collapsible accordion header]
Course #4 title  | Course #4 Code  |     Course #4 credits
-- Semester 02 -- [ collapsible accordion header]
Course #5 title  | Course #5 Code  |     Course #5 credits
-- Semester 03 -- [ collapsible accordion header]
Course #6 title  | Course #6 Code  |     Course #6 credits
-- Semester 03 -- [ collapsible accordion header]
Course #7 title  | Course #7 Code  |     Course #7 credits
-- Semester 03 -- [ collapsible accordion header]
Course #8 title  | Course #8 Code  |     Course #8 credits
-- Semester 03 -- [ collapsible accordion header]
Course #9 title  | Course #9 Code  |     Course #9 credits

```

I tried with 'fields' instead of 'content', added those that I want and 'excluded' semester from showing, but that didn't really help.

I understand that the teaser template runs once for every 'row' so there is no way to really 'group' results according to semesters, which is what I want.

Is there a way to get all data somewhere and format it in one template file, so I can use loops and ifs etc. to 'group' and present my data the way I want ?

Sorry for the ridiculous length of this message .. I wanted to be as specific as possible in order to be easily understood...

---

**This question seems fairly similar**, but the very useful and detailed answer mentions a solution ***if not using a view mode/template***. I want to use a template because it helps me control exactly how the data is shown. I 've found other tips and info here and there, but none could be of any real help.

What should I try in order to achieve what I want? Any help would be greatly appreciated, I 'm really stuck on this one ...

Please shed some drupal light towards my way ... :)

# Answer
> 0 votes
> Is there a way to get all data somewhere and format it in one template file, so I can use loops and ifs etc. to 'group' and present my data the way I want ?

Unless I'm misunderstanding something, you're sort of describing the views-view-unformatted.html.twig template:

```
{#
/**
 * @file
 * Default theme implementation to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 * - view: The view object.
 * - default_row_class: A flag indicating whether default classes should be
 *   used on rows.
 *
 * @see template_preprocess_views_view_unformatted()
 *
 * @ingroup themeable
 */
#}
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}

```

As you can probably infer from the comments, the template is rendered for each group of rows in an aggregated View, and the title of the group is made available. That seems like the perfect place to add your accordion markup, so overriding that will probably do the job.

You might find the Views template files docs useful in deciding on the best file name to use for the template.

---
Tags: views, theming
---


title: how to change base url in drupal 8

text:
# Question
Title: how to change base url in drupal 8
I had installed a drupal website inside a folder in web root on an amazon ec2 instance. I used to access it by calling http://xx.xx.xxx.xx/folder .Now that the site is finished i created virtual hosts in my http.conf file to point the domain name to folder. I edited trusted host patterns in settings.php. So far so good! http://mydomainname.com points to front page.

PROBLEM: when i click on links it shows 404 because path is http://mydomainname.com/folder/link instaed of http://mydomainname.com/link The front page parameter in site settings in admin side is uneditable. How can I change that..? Please Help.

# Answer
> 1 votes
```
sudo nano /etc/apache2/sites-enabled/000-default.conf

```

Make sure it looks like this:

```
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

ServerAdmin webmaster@localhost
        ServerName mydomainname.com
        ServerAlias www.mydomainname.com
        DocumentRoot /var/www/html/drupal

<Directory /var/www/html/drupal/>
        Options +FollowSymLinks
        AllowOverride All
        order allow,deny
        allow from all
</Directory>

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

```

---
Tags: 8, database, configuration
---


# Question
Title: how to give relative path in drupal for setting an image
**Hi all, iam trying to set image here in a module .The image is in the same module folder. but iam not able to get the image path**

```
<td><img src="projectsetup.jpg "  width="42" height="42"></td>

```

**This is the error which iam getting ..cleary states no path**

> How to get a relative path in module to display images?

# Answer
Drupal has ways to get the relative path from document root but not for individual module/theme folder.

You can get the path to current module or theme using `path_to_theme`

```
<img src="/<?php echo path_to_theme() ?>/images/projectsetup.jpg"/>

```

path\_to\_theme from the documentation

> Returns the path to the current themed element.
>
> It can point to the active theme or the module handling a themed implementation. For example, when invoked within the scope of a theming call it will depend on where the theming function is handled. If implemented from a module, it will point to the module. If implemented from the active theme, it will point to the active theme. When called outside the scope of a theming call, it will always point to the active theme.
> 0 votes

# Answer
Try this code.

```
$path = drupal_get_path('module', 'myModule') . 'image/projectsetup.jpg';

```

now set src = '$path' into your .module file where you set image src.
> 0 votes

---
Tags: 7, media
---


# Question
Title: How do I define a Route with multiple different paths?
Does Drupal's routing system support a regular expression or other means for multiple route paths? I have a route that I would like to be able to hit from two different endpoints, `/api/v1/foo` and `/api/v1/foo_bar`. One route is newer, the other I want to keep for backwards compatibility reasons.

In my module's `my_module.routing.yml` file, I have defined:

```
foo:
  path: 'api/v1/foo'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

foo_bar:
  path: 'api/v1/foo_bar'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

```

This works, but as you can see everything after the route name and `path` property is copy/pasted. It's not exactly adhering to the DRY principle. Now this is a simple case, but imagine if I had a much more involved route with complex requirements and parameters. There would be a very high chance of making a typo or pasting mistake in one.

Is it possible to define the `path` as a regular expression or something similar so I don't have to repeat all the route properties?

# Answer
```
cool:
  path: 'api/v1/{dynamic}'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

```

Then in your controller

```
public function doItAction($dynamic) {

  if($dynamic == 'foo' || $dynamic == 'foo_bar') {
    // your code
  }

}

```
> 3 votes

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


# Question
Title: How to re-add deleted articles using the same node ids?
I am running a drupal 7 website with about 1800+ articles. There were about 40 articles deleted overtime from the website. What I want to do is add those articles again using the same deleted NIDs. How should I go about it?

Is adding these articles manually through phpMYAdmin a good idea? Are there other database tables I have to consider other than the following:

(1) node

(2) field\_data\_body

# Answer
It really depends on the amount of data you have at hand. If the missing nodes have simple structure with only default body field,title, none or just a few custom fields, then 40 is not that big number to sweat over the code, so I would do it via database UI as phpMyAdmin. Just note other involved tables like `node_revision` and custom field tables if nodes had ones.

However, if the missing nodes have multiple fields and too much data to enter manually, then I would create and upload data to 40 new nodes iterating:

```
$entity = entity_create('node', $values);
$service_wrapper = entity_metadata_wrapper('node', $entity);
$service_wrapper->title->set($product->title);
$service_wrapper->field_custom_field_1->set($data_1);
$service_wrapper->field_custom_field_2->set($data_2);
$service_wrapper->field_custom_field_N->set($data_N);
$service_wrapper->save();

```

Then I would replace nids either manually in `nodes` and `node_revision` tables or by saving the missing nids in form of `$nids = array(0 => 'first nid', 1 => 'second nid, 2 => '2nd nid', n => 'so forth')` and then iterating them through foreach loop in custom module's function.
> 0 votes

# Answer
Good news!

It worked with a few experiments. Once I run the following commands through SQL tab of phpMyAdmin for drupal database.

```
INSERT INTO `url_alias` (`source`, `alias`, `language`) VALUES ('node/470', '470', 'und');

INSERT INTO `node` (`nid`, `vid`, `type`, `language`, `title`, `uid`, `status`, `created`, `changed`, `comment`, `promote`, `sticky`, `tnid`, `translate`) VALUES (470, 470, 'article', 'und', 'Title of Old Article', 1, 0, 1452492094, 1520839370, 1, 1, 0, 0, 0);

INSERT INTO `node_revision` (`nid`, `vid`, `uid`, `title`, `log`, `timestamp`, `status`, `comment`, `promote`, `sticky`) VALUES (470, 470, 1, 'Title of Old Article', '', 1520839370, 0, 1, 1, 0);

INSERT INTO `field_data_body` (`entity_type`, `bundle`, `deleted`, `entity_id`, `revision_id`, `language`, `delta`, `body_value`, `body_summary`, `body_format`) VALUES ('node', 'article', 0, 470, 470, 'und', 0, 'Body of old article.', '', 'full_html');

INSERT INTO `field_revision_body` (`entity_type`, `bundle`, `deleted`, `entity_id`, `revision_id`, `language`, `delta`, `body_value`, `body_summary`, `body_format`) VALUES ('node', 'article', 0, 470, 470, 'und', 0, 'Body of old article.', '', 'full_html');

```

Then I can edit this article from drupal admin section like:

http://mywebsite.com/node/470/edit

And then I can add data to all the fields including taxonomy terms and custom fields.

It is working good so far, if something goes wrong I will update here.

So there are 5 basic tables for adding an article to drupal 7:

* url\_alias
* node
* node\_revision
* field\_data\_body
* field\_revision\_body
> 0 votes

---
Tags: database
---


# Question
Title: webform add more module does not show add more button
I would like public to be able to add records by person name and city.

I enabled the module https://www.drupal.org/project/webform\_addmore

I created a webform.

I added a fieldset "Records".

I added 2 text fields: Name, city. I placed the fields under the fieldset.

Edit the fieldset \> selected the checkbox "Add More fieldset"

Save

When I go to the webform page as public user, I can see the webform with the fieldset and fields. I do not see the Addmore button. How can I display the addmore buttons to webform fieldset?

# Answer
> 1 votes
It seems the module has no good support and does not work properly with latest versions of webform I think both 3 and 4 versions

Here is the issue that describes the problem you are having and I am posting this as a solution as there is numerous workarounds there that might give you a solution and some patches to try but none were tested by me.

If admins say this is not fit for an answer I will erase.

---
Tags: webforms
---


# Question
Title: How to exclude nodes with a taxonomy term from XML Sitemap?
We can exclude content type, or individual node from XML Sitemap. But, is there anyway to exclude nodes with specific taxonomy term? For example excluding nodes with `longlivethetroll` tag.

# Answer
> 1 votes
You can use hook\_xmlsitemap\_element\_alter() to check if the node has a particular taxonomy term & exclude it.

```
function MYMODULE_xmlsitemap_element_alter(&$element, $link, $sitemap) {
  // Check if link is a node link
  if ($link['type'] == 'node') {
    $node = node_load($link['id']);

    // Code to check if $node has taxonomy term goes here
    if ($node has taxonomy term) {
      $element['disabled'] = TRUE; // This removes the node link from sitemap
    }
  }
}

```

---
Tags: xml-sitemap
---


# Question
Title: Need to add custom element in sitemap.xml file
I have installed sitmap module to create sitemap.xml file.
Now I want to add some custom element like

```
<expires>2010-10-10</expires>

```

for some URLS.

# Answer
If you don't mind a programmatic approach, then follow these steps:

1. Ensure that XML Sitemap module is installed & enabled
2. Create/use a custom module (say, MYMODULE) & use the following hook:

```
  function MYMODULE_xmlsitemap_element_alter(&$element, $link, $sitemap) {
    // Some logic to generate datetime
    // or hardcoded value
    $element['expires'] = '2010-10-10';
  }

```
3. Go to admin/config/search/xmlsitemap/batch-generate & click on 'Run'
4. Go to admin/config/search/xmlsitemap/rebuild & click on 'Rebuild sitemap'
5. Go to sitemap.xml, inspect element or view page source & verify that 'expires' tag is included

Hope this helps.
> 1 votes

# Answer
The expires tag is not valid Sitemaps.org Protocol - http://www.sitemaps.org/protocol.html

You can configure the overall sitemap lifetime on this page: /admin/config/search/xmlsitemap/settings

Set it the Minimum sitemap lifetime to "1 Day" and make sure your nodes are unpublished when you want them to expire, either manually or using a module like Scheduler, and they will be removed from the sitemap.xml
> 0 votes

---
Tags: 7, xml-sitemap
---


# Question
Title: How to properly recognize a session id generated by drupal?
I'm storing stuff in a session that is sometimes handled by drupal. The session id is passed forward to another service, which checks back to the original server to get the session data.

When the session id is generated by drupal, i want to recognize it so i can include the drupal bootstrap instead of creating a normal php session. What would be a proper way to recognize drupal session ids ?

Is there a way to make it more specific, like change the sessionid myself ?

# Answer
> 1 votes
Drupal will let you override the default session handler using the `session_inc` variable. This is what Drupal actually uses to bootstrap the session:

```
require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');

```

So to replace that with your own, set the variable to your own path:

```
variable_set('session_inc', 'sites/all/modules/MYMODULE/session.inc');

```

And re-implement the functions from the core session.inc in your custom file, making changes where necessary.

# Answer
> 0 votes
You can get seesion id by calling `session_id()` function. For session name you can use `session_name()`.

---
Tags: 8, sessions
---


# Question
Title: How to track user node views and quiz results
I am searching for the easiest way to track wether particular user has read particular group of nodes (training material) and did the quizes that are related to those nodes. In success case I would like to grant user some points and a badge and for the site administrator to have a list of all the training material with "read"/"not read" results per user. I know that there could be various ways to do this, but I am not sure, which one would be the easiest one.

* using Goals + Rules (but I can't find how exactly can I track wether user has visited particular node).
* using Activity module?
* using Heartbeat module?

None of these looks like it is possible to do such thing without coding, or I am missing something?

thanks!

# Answer
> 2 votes
I'd use the Goals module (disclosure: I'm its maintainer) to "*track wether user has visited particular node*" (as in your question). No need for custom coding. Read on for details how to do so ...

# Configure a goal

Navigate to the relative path `admin/config/goals/manage` and use the link "Add a goal" to define just 1 **goal**, with a description (say):

***`View some node, only 1 time`***.

# Configure a task

To achieve the above *goal*, define the **Task(s)** to be completed. Even though there could be multiple tasks to be completed for a single goal, in your case you just need 1. It's simply ***`View a node`*** (assume we use a machine name like `view_a_node`).

# Track progress while performing tasks

To track the progress made by a single user to complete this task, you only have to write an appropriate rule, using the Rules module, to record relevant events happening in your site, which are related to the completion of the ***task*** to reach the ***goal***.

For the goal/task described above, you'd only need 1 (extremely basic) rule, which would look like so:

* **`Rules Event`**: Content is viewed.
* **`Rules Events`**:
    + Check user has role "authenticated" (how else would you know which user it is ...).
    + Check the node id of the node being viewed (eg: node=123).
* **`Rules Action`**: Record a task for Goals (obviously, the task to be recorded is "View a node"). This is where part of the Goals magic happens, such as verifying the requirements in the optional task configuration options for a task (only once an hour, etc).

Here is a rule which you could probably use for this (if you have a "task" defined with the exact machine name `view_a_node`, just use the Rules UI to import it in your own site to get you going, if not adapt that machine name prior to starting such import):

```
{ "rules_record_task_view_a_node" : {
    "LABEL" : "Record task view_a_node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "rules", "goals" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "data_is" : { "data" : [ "node:nid" ], "value" : "123" } }
    ],
    "DO" : [
      { "goals_task_record" : {
          "task_name" : "view_a_node",
          "user_to_save_for" : "[site:current-user]",
          "task_id" : "Node ID of viewed node = [node:nid]"
        }
      }
    ]
  }
}

```

The above gets you started for a single node like `node/123`. To enhance it to also verify node/124, node/125 and node/126 (it doesn't matter in which order they are viewed ...), this is how to do so:

* Add 3 similar tasks to be tracked (for the 3 other nodes), with a machine name that includes the relevant node id.
* Duplicate the above rule for each of the other nodes (only difference is the node id in the Rules Condition and the machine name of the Task in the Rules Action). As an alternative, use the Conditional Rules module to consolidate those 4 rules in a single rule.

---
Tags: userpoints, quiz, 7
---


# Question
Title: How to move Drupal 8 with composer, to another server
We've recently got a few Drupal 8 sites, and needed to move them away from a plesk server. The plesk server is now shutdown for good, and we need to restore the sites on our cpanel server. The sites are using composer, which we don't have any experience with. On top of that, we are not very familier with the drupal structure or system.

We've tried to restore the sites by copying the files relatively with the composer "vendor" folder and replacing strings in the entire project, but it didn't seem to work, or maybe we missed something..

We've also tried to create a new composer project and copied the drupal project into the newly created composer project, but that gave an infinite loop that used up all the ressources and gave an 503 error in the end.

Does anyone know how to move/migrate a Drupal 8 site with composer, from one server to another?

# Answer
As already said in the comments composer does not have a way to help with transfering a site.

With a site build with composer I usually zip the composer directory (which includes the drupal directory) and get a database dump. On the receiving server just copy the files on a similar directory structure and import the database.

For going from plesk to cpanel you probably have to set the document root correctly. In plesk its usually `httpdocs/docroot` but in cpanel it should probably be set to `public_html/docroot`

Also I don't suppose you will need but it does not hurt to run `composer update`

**NOTE:** this is a quick and dirty way of transferring from on host to the other assuming that php version and other parameters stay the same, this is by no means a best practice in transferring a site to a new host.

For **best practice** you should follow the advice in the comments and see the guide on Use Composer to manage drupal site dependencies and the section for *Managing existing sites using Composer* might come in handy.
> 2 votes

---
Tags: 8, composer
---


# Question
Title: Preventing a block's custom template file from being cached
I have built a module that needs to provide a small piece of dynamic content on every page load of a certain content type. It works great, however the section of code I provided is always cached in Drupal theme registry (it seems). The Variables I need generated on each pageload are "$userpicturepath" and "$variables\['userfullname'\]" How do I prevent this from being cached? For completeness, here is my module's code:

*subscribe\_blocks.module*

```
//implementation of hook_block_info
function subscribe_blocks_block_info() {
    $blocks['author_subscribe_block'] = array(
        'info' => t('Author Subscribe Block'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $blocks;
}

//implementation of hook_block_view
function subscribe_blocks_block_view($delta = '') {
    switch ($delta) {
        case 'author_subscribe_block':
            $blocks['content'] = theme('subscribe_blocks_block');
            break;
    }
    return $blocks;
}

// Implementation of hook_theme
function subscribe_blocks_theme(){
    if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
        $node = node_load(arg(1));
    }
    $user_fields = user_load($node->uid);

    return array(
        'subscribe_blocks_block' => array(
            'template' => 'subscribeblocks',
            'variables' => array(
                'userfullname' => $user_fields->field_name['und'][0]['safe_value'],
                'userpicture' => $user_fields->picture->filename,
                'userfields' => $user_fields,
            ),
        ),
    );
}

```

*subscribeblocks.tpl.php*

```
<?php
drupal_page_is_cacheable(FALSE);

if ($variables['userpicture'] != NULL){
    $userpicturepath = 'sites/example.com/files/styles/user_profile/public/pictures/' . $variables['userpicture'];
} else{
    $userpicturepath = 'https://someimgurl';
}
?>

<div class='subscribe-bar'>
    <div class='container'>
        <div class='col-sm-9 col-sm-offset-2'>
            <div class='subscribe-left'>
                <img src=<?php echo $userpicturepath; ?> class='subscribeuserpic' >
            </div>
            <div class='subscribe-right'>
                <p>Never miss another story by <strong><?php echo($variables['userfullname']); ?></strong>. Subscribe today.</p>
                <div class='slideInFormContainer'>
                    <?php
                    $block = module_invoke('webform', 'block_view', 'client-block-5401');
                    print render($block['content']);
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

```

I'm using Drupal 7, have all other caching turned off (for now), and have tried using several modules including CacheExclude (https://www.drupal.org/project/cacheexclude) and Ajax Blocks (https://www.drupal.org/project/ajaxblocks).

# Answer
Probably not the best way to do this, but I was able to overcome this by rebuilding the theme cache when this block was run using:

```
<?php
drupal_theme_rebuild();

```

I'd love if someone could help with a better answer though!
> 0 votes

---
Tags: theming, blocks, caching
---


title: Display field's content as an image

text:
# Question
Title: Display field's content as an image
I'm using webform\_multiple\_file. To display my submissions, I created a view and added as field **Webform submission data: Value**

To customize my view I used **print $fields\['value\_1'\]-\>content ;**

This displays somthing like this:

> image1.png
>
> image2.jpeg

But I want to display just the first data and as an image like

```
<img src="image1.png" />

```

Below the HTML return

```
<div class="webform-multiple-file"><a href="http://localhost/mydrupal/sites/default/files/webform/image1.png">image1.png</a></div><div class="webform-multiple-file"><a href="http://localhost/mydrupal/sites/default/files/webform/image2.jpeg">image2.jpeg</a></div>

```

Any idea please? Thank you

# Answer
Try something like this:

```
file_dir  = $file_create_url("public://");

print '<a href=' . $file_dir . '/'. $fields['value_1']->content . '</a>';

```
> 0 votes

---
Tags: 7, entities, webforms
---


# Question
Title: How to Add Multiple Values to Prefix for Currency field as a Drop Down
I have a custom Decimal field, Salary, for one of my custom content type. How do I add multiple prefixes that I can display as a drop down in the node add/edit form for users to select their respective currencies while updating the salary field?

I have tried the currency module, however, I didn't find any option in it to add a decimal/ integer value in it.

Also tried Field Collection Module, it does give the option for combining multiple fields, but, the result looks a bit crude. The Fields come one above the other rather than alongside each other.

Is there any option for me to add Multiple prefixes in the Field and display the same as Drop Down List in the Node Add/Edit form?

Please advice.

Thanks

# Answer
> 0 votes
Found the Solution in this post. Used the Measured Value Field in Conjunction with Units and Currency. Got a pretty neat solution.

---
Tags: 7, nodes, entities
---


# Question
Title: How to disable CACHE in VIEW PAGE display
DRUPAL 8

I am using VIEW module to create a page which loads data from a database table.

Seems this view page is caching because whenever I add a new record in this table via custom input form, it doesn't show on view page immediately after refresh. I can clearly see this new entry in the database table but not on view page.

Then I have to manually clear cache from the site \> performance section and then I can see new entry on the view page.

Please note that database table is a custom table and I am using hook\_views\_data() to add custom table fields in the view page.

BTW I had disabled 'Disable views data caching' on '/admin/structure/views/settings/advanced' page but it has no effect on my view page.

Can anyone please advise what should I do to avoid CACHE?

Thanks.

# Answer
You have to add a cache tag to the View, the name is arbitrary, for example `custom-data-list`.

You can do this in a view hook:

```
function mymodule_views_pre_view($view, $display_id, array &$args) {
  if ($view->id() == 'my_custom_data_view') {
    $view->element['#cache']['tags'][] = 'custom-data-list`;
  }
}

```

or use the module Views Custom Cache Tags.

By this all cache entries that contain the View, for example blocks or pages and the view itself are tagged with this tag.

Now the only thing you have to do, whenever you change the data in the database (this is for all CRUD operations, that write to the database), invoke:

```
\Drupal\Core\Cache\Cache::invalidateTags(['custom-data-list']);

```
> 1 votes

# Answer
The only way I found to add a custom cache tag to a view is implementing a *views cache plugin*.

Adding the tag as @4k4 suggested doesn't works. I have tried using different views hooks and different ways without be able to get it working.

With `$view->element['#cache']['tags'][] = 'custom-data-list'` or `$view->storage->addCacheTags(['custom-data-list'])` the tag appears in *X-Drupal-Cache-Tags* header, but the view cache is not invalidated when I invalidated the tag.

Then investigating *Views Custom Cache Tags* module code I found a way to implement it in a custom class:

```
namespace Drupal\data_view\Plugin\views\cache;

use Drupal\views\Plugin\views\cache\Tag;

/**
* Add custom cache tags for rows in custom tables.
*
* @ingroup views_cache_plugins
*
* @ViewsCache(
*   id = "table_tag",
*   title = @Translation("Tag for custom tables"),
*   help = @Translation("Tag based caching of data. Caches will persist until any table cache tag are invalidated.")
* )
*/
class TableTag extends Tag {

  /**
  * {@inheritdoc}
  */
  public function summaryTitle() {
    return $this->t('Table tag');
  }

  /**
  * {@inheritdoc}
  */
  public function getCacheTags() {
    // Here you can also create tags for single records in the form "your-table:id"
    return ['custom-data-list'];
  }

}

```

Then in the view settings page, in the *Other* section, select *Tags for custom tables* in *Caching*.

In your code don't forget to invalidate the cache every time you change a record in your custom table.
> 1 votes

---
Tags: views, caching
---


# Question
Title: Access data from previously submitted values in buildForm in FormBase plugin
I have a FormBase plugin for an admin configuration page. My desired behavior is to select a series of checkboxes and when you submit the form based on those values a new set of fields will show. However I'm not sure how to build the form after submitting the form with new values.

Here's my current buildForm function

```
    $form['pages'] = [
        '#type' => 'checkboxes',
        '#title' => 'Pages to clone:',
        '#options' => [
            'about' => 'About',
            'home' => 'Home',
            'blog' => 'Blog',
        ],
    ];

    $form['actions'] = [
        '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
    ];

```

(Sidenote: Not sure if or why the last bit with the 'actions' is necessary) The form is build fine and in my submitForm function I have

```
public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->set('pages', $form_state->getValue());
    $form_state->set('test_parameter', 'test_value');
}

```

However when I add a var\_dump($form\_state) to the buildForm function and submit the form like so

public function buildForm(array $form, FormStateInterface $form\_state) { var\_dump($form\_state); $form\_state-\>set('pages', $form\_state-\>getValue()); $form\_state-\>set('test\_parameter', 'test\_value'); }

I get some information about the form\_state but nothing about the parameters I set.

> object(Drupal\Core\Form\FormState)#599 (33) {
> \["complete\_form":protected\]=\> NULL \["build\_info":protected\]=\>
> array(4) { \["args"\]=\> array(0) { } \["files"\]=\> array(0) { } \["callback\_object"\]=\> object(Drupal\my\_plugin\Form\PageCloner)#600 (10) { \["number":protected\]=\> int(1) \["requestStack":protected\]=\> NULL \["configFactory":protected\]=\> NULL \["routeMatch":protected\]=\> NULL \["\_serviceIds":protected\]=\> array(0) { } \["linkGenerator":protected\]=\> NULL \["loggerFactory":protected\]=\> NULL \["redirectDestination":protected\]=\> NULL \["stringTranslation":protected\]=\> NULL \["urlGenerator":protected\]=\> NULL } \["form\_id"\]=\> string(9) "page\_pack" } \["rebuild\_info":protected\]=\> array(0) { } \["rebuild":protected\]=\> bool(false)
> \["invalidToken":protected\]=\> bool(false) \["response":protected\]=\> NULL \["redirect":protected\]=\> NULL \["no\_redirect":protected\]=\>
> NULL \["method":protected\]=\> string(4) "POST"
> \["requestMethod":protected\]=\> string(3) "GET"
> \["cache":protected\]=\> bool(false) \["no\_cache":protected\]=\> NULL \["values":protected\]=\> array(0) { }
> \["cleanValueKeys":protected\]=\> array(4) { \[0\]=\> string(7) "form\_id" \[1\]=\> string(10) "form\_token" \[2\]=\> string(13) "form\_build\_id" \[3\]=\> string(2) "op" } \["input":protected\]=\> array(0) { } \["always\_process":protected\]=\> NULL \["must\_validate":protected\]=\> NULL \["programmed":protected\]=\> bool(false)
> \["programmed\_bypass\_access\_check":protected\]=\> bool(true)
> \["process\_input":protected\]=\> NULL \["submitted":protected\]=\>
> bool(false) \["executed":protected\]=\> bool(false)
> \["triggering\_element":protected\]=\> NULL
> \["has\_file\_element":protected\]=\> NULL \["groups":protected\]=\>
> array(0) { } \["storage":protected\]=\> array(0) { }
> \["buttons":protected\]=\> array(0) { } \["temporary":protected\]=\>
> array(0) { } \["validation\_complete":protected\]=\> bool(false)
> \["errors":protected\]=\> array(0) { }
> \["limit\_validation\_errors":protected\]=\> NULL
> \["validate\_handlers":protected\]=\> array(0) { }
> \["submit\_handlers":protected\]=\> array(0) { } }

What is the best way to get information retrieved in the formSubmit function back to when the buildForm function is fired again after submit? Or is there a better way I'm not considering to create a new form based on these values?

UPDATE: 4k4's solution worked but I ran into another issue where the form state wasn't properly saving. I resolved this by adding

```
parent::submitForm($form, $form_state);

```

to the submitForm function before $form\_state-\>setRebuild(); this led to an error saying

> Cannot call abstract method Drupal\Core\Form\FormInterface::submitForm()

to resolve that I changed the form from extending FormBase to extending ConfigFormBase instead like so

```
class MyPlugin extends ConfigFormBase {

```

# Answer
If you want to rebuild the form with the values of `$form_state` you have to set the form to be rebuilt after processing:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->set('test_parameter', 'test_value');
  $form_state->setRebuild();
}

```

Otherwise the form redirects to a new form build.
> 2 votes

---
Tags: 8, plugins
---


# Question
Title: What is the relationship between hook_cron() and hook_cron_queue_info()?
Some modules (e.g. Feeds, Rules Scheduler, Revision Scheduler) implement both `hook_cron()` and `hook_cron_queue_info()`. When used with Ultimate Cron and the `Enable cron queue processing` setting enabled, this causes two jobs to appear in the jobs list. Are both jobs necessary?

Taking the Revision Scheduler module as an example, its `hook_cron()` seems to add items to the queue:

```
function revision_scheduler_cron() {
  $ids = db_query("SELECT * FROM {revision_scheduler} WHERE time_scheduled <= :now AND time_queued = 0 AND time_executed = 0 ORDER BY id ASC", array(':now' => REQUEST_TIME))->fetchCol();
  if ($operations = revision_scheduler_operation_load_multiple($ids)) {
    $queue = DrupalQueue::get('revision_scheduler');
    foreach ($operations as $operation) {
      if ($queue->createItem($operation)) {
        db_update('revision_scheduler')
          ->fields(array('time_queued' => REQUEST_TIME))
          ->condition('id', $operation->id)
          ->execute();
      }
    }
  }
}

```

whereas its `hook_cron_queue_info()` function calls a function that processes single revision operations:

```
function revision_scheduler_cron_queue_info() {
  $info['revision_scheduler'] = array(
    'worker callback' => 'revision_scheduler_operation_process',
    'time' => variable_get('revision_scheduler_cron_time', 30),
  );
  return $info;
}

```

Is it the case that `hook_cron()` adds the items to the queue and `hook_cron_queue_info()` processes them?

The documentation for `hook_cron_info()` says this:

> While there can be only one hook\_cron() process running at the same time, there can be any number of processes defined here running. Because of this, long running tasks are much better suited for this API. Items queued in hook\_cron() might be processed in the same cron run if there are not many items in the queue, otherwise it might take several requests, which can be run in parallel.

I'm not sure how to interpret that, but it seems to suggest tasks should be processed with one or the other.

# Answer
The relationship is they are 2 independent hooks that can be used in conjunction with one another depending on what the task is.

* `hook_cron()`: Provides a means to supply a *custom function to respond to a cron event*.
* `hook_cron_queue_info()`: Provide a means to supply *queue metadata for a cron event that will need a queue* (i.e. any task that can't be fully processed in the limited time during a cron event).

In your example above:

* Yes `revision_scheduler_cron` is adding to the queue.
* But no, `revision_scheduler_cron_queue_info` is not processing the queue, it's providing the **function** (`revision_scheduler_operation_process`) to call for processing and **how long** (`revision_scheduler_cron_time`) it should be allowed to execute for processing.
> 5 votes

---
Tags: 7, cron
---


title: Theming image.html.twig

text:
# Question
Title: Theming image.html.twig
What name do I have to give to my image.html.twig so the template only being used in content type "project" because I need to add class to an `<img>` tag. I already tried

* image--node--field-afbeeldingen--project.html.twig
* image--node--field-afbeeldingen.html.twig

# Answer
> 0 votes
I'm not sure about overriding the `<img>` tag itself, but for your approach I would recommend overriding the field template. Assuming your field is named `field_afbeeldingen`, you can create a template called `field--field-afbeeldingen.html.twig`.

Within there, you could manually render your `<img>` tag as needed, with whatever additional classes required.

---
Tags: 8, theming, media
---


# Question
Title: How can i set the value of first field to the second in same form
I have a form with a value field and i would like to set the value to a markup field as shown below. The problem is that it retuns empty. Is there other alternatives.

```
public function buildForm(array $form, FormStateInterface $form_state) {
     $form['container']['#tree'] = TRUE;
     $form['container']['#type'] = 'container';
     $form['container']['store_value'] = [
         '#type' => 'value',
         '#value' => 'Angeline Mnene'
     ];
     $form['container']['show_value'] = [
         '#type' => 'markup',
         '#markup' => 'The stored value is: ' . $form_state-
          >getValue(['container','store_value']),
     ];

     return $form;
}

```

# Answer
> 0 votes
I finally got an answer and would like to post it here, to help someone who may run into this problem as well.

```
public function buildForm(array $form, FormStateInterface $form_state) {

     //SET THE VALUE HERE
     $form_state->setValue('store_value', 'The stored value is: Angeline
     Mnene');

     $form['container']['#tree'] = TRUE;
     $form['container']['#type'] = 'container';
     $form['container']['show_value'] = [
         '#type' => 'markup',
         '#markup' => 'The stored value is: ' . $form_state-
          >getValue('store_value'),
     ];

     return $form;
}

```

---
Tags: forms
---


# Question
Title: Encrypt module; Is there a way of using db_query() on encrypted values?
I've installed the encrypt module because we will be handling a lot of personal data. For those in the EU there is serious consequences under GDPR for failing to protect users data.

I've also installed Real AES and Field Encryption.

So I have got the values encrypted and followed the instructions. I can see the encrypted values in the database. For example:

> a:6:{s:4:"text";s:88:"fYGWIfFfoQuar4yy/ySsyTtK2Qt/flgz9mg4GdRD6hlDOM8f8fevf9Q6O35Yp+WDwByB7SXGg0yPQLXfCC3FlQ==";s:6:"method";s:17:"authenticated\_aes";s:12:"key\_provider";s:4:"file";s:7:"options";a:1:{s:6:"base64";b:1;}s:15:"method\_settings";s:0:"";s:17:"provider\_settings";a:2:{s:4:"path";s:15:"../keys/xscodes";s:6:"method";s:13:"base64\_decode";}}

Views also displays the decrypted values. I can also see them when viewing and editing one of my entities.

This particular Drupal install is used to store customer and sales info from many Commerce sites in a centralised place. As a result I'm doing lots of db\_query()'s when I receive some order information via a JSON call.

My plan was to encrypt the values given. Then use that encrypted value in my call to db\_query().

In the PHP block that comes with Devel I have this while testing:

```
  $lastname = encrypt('Jones', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');
dpm($lastname);

    $lastname2 = encrypt('Jones', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');
   dpm($lastname2);

    $lastnamede = decrypt($lastname);
    dpm($lastnamede);

    $lastname2de = decrypt($lastname2);
    dpm($lastname2de);

```

So the $lastname gives me:

> a:6:{s:4:"text";s:88:"dQApE9dYu1QE2Cz5N5f9rLRW8xuDEYKvDaq3jmJFEC+GBljGqbQ68XfQjv92fNicECsPnoK+s11agTPX0LRQuQ==";s:6:"method";s:17:"authenticated\_aes";s:12:"key\_provider";s:4:"file";s:7:"options";a:1:{s:6:"base64";b:1;}s:15:"method\_settings";s:0:"";s:17:"provider\_settings";a:2:{s:4:"path";s:15:"../keys/xscodes";s:6:"method";s:13:"base64\_decode";}}

The $lastname2 gives me:

> a:6:{s:4:"text";s:88:"RDsHVHv2wvcK9012xAElHs/tx3rltR57DjyhUXGcBVXrN1j/RqBt/UVkLY6hxEmyLm9zQkqXtET9SgtKmB8q/Q==";s:6:"method";s:17:"authenticated\_aes";s:12:"key\_provider";s:4:"file";s:7:"options";a:1:{s:6:"base64";b:1;}s:15:"method\_settings";s:0:"";s:17:"provider\_settings";a:2:{s:4:"path";s:15:"../keys/xscodes";s:6:"method";s:13:"base64\_decode";}}

Both values then de-crypted as expected. $lastname and $lastname2 being different values presents me with a problem when it comes to db\_query() calls.

The query I'm trying to do is this:

```
$firstname = encrypt('Peter', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');
$lastname = encrypt('Jones', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');
$email = encrypt('pj@some.com', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');

$customer_id = db_query("SELECT c.id
  FROM {eck_customer} c
  LEFT JOIN {field_data_field_customer_first_name} first_name ON c.id = first_name.entity_id
  LEFT JOIN {field_data_field_customer_last_name} last_name on c.id = last_name.entity_id
  LEFT JOIN {field_data_field_customer_email} email ON c.id = email.entity_id
  WHERE email.field_customer_email_email = :email
  AND first_name.field_customer_first_name_value = :first_name
  AND last_name.field_customer_last_name_value = :last_name
  AND type = 'customer'", array(':email' => $email, ':first_name' => $firstname, ':last_name' => $lastname))->fetchField();
if ($customer_id) {
dpm($customer_id);
 }

```

The above query is correct. It works without encryption being involved.

I tried entity field query in case that worked but no joy there.

So the question is, does anyone know of a method to achieve what I want? How can I query the database on encrypted fields?

# Answer
> 1 votes
There wasn't a way to do what I needed out of the box for the reasons mentioned by others. Every time you encrypt a value using AES, you get a different output.

One approach I was introduced to suggested storing a HMAC hash of the value. When you encrypt a value using HMAC you always get the same result. As long as you're using the same key to do so. However it can't be decrypted. I could then search the database using that hash.

So I had to patch the field\_encrypt module: https://www.drupal.org/project/field\_encrypt/issues/2948313#comment-12522830

With this patch, every field that gets encrypted also has the HMAC value stored into a separate column. The column has the same name with the \_hmac suffix. The patch also leverages the key module for the HMAC key. I wanted offsite key management.

An example of my working code to query the database is:

```
$key_id = variable_get('field_encrypt_hmac_key');
$key = key_get_key_value($key_id);
$first_name = drupal_hmac_base64('Guy', $key);
$customer_id = db_query("SELECT c.id
      FROM {eck_customer} c
      LEFT JOIN {field_data_field_customer_first_name} first_name ON c.id = first_name.entity_id
      WHERE first_name.field_customer_first_name_value_hmac = :first_name
      AND type = 'customer'", array(':first_name' => $first_name))->fetchField();
  if ($customer_id) {
    return $customer_id;
     }

```

The one biggest drawback I can think of is that only exact matches are possible.

Hope this helps others

# Answer
> 1 votes
You can see from your DPM that your encryption method is returning an array containing several different values. You can't use an array for a database field value it would need to be a string in this case. So you need to use just the encrypted hash string from that array in your db\_query e.g.

```
array(':email' => $email['text'])

```

# Answer
> 0 votes
As you've already noted, encrypting the same plain text multiple times will produce a different result every time.

That's because the encryption algorithm is using a randomly generated "Initialisation Vector" (like salting a password before hashing it) which is stored in the first few bytes of the encrypted text to facilitate decryption.

Therefore, I don't think there's any way to query the encrypted text directly in the database because the Initialisation Vector for your query input will always be different to that of the stored values.

---
Tags: 7, database
---


title: How do I modify the query parameters?

text:
# Question
Title: How do I modify the query parameters?
I want to modify query parameters used when accessing a Drupal page. I tried implementing `hook_url_inbound_alter()`, but it only allows to parse/modify the path, and it doesn't allow any interaction with the query string.

I see there is also `drupal_get_query_parameters()`, which allows to read the query parameters.

I *could* detect the presence of a query value in index.php and do a string replacement on the value if needed, but I don't want to pollute the front controller.

Do you have any better advice?

# Answer
> 4 votes
1) you need to implement EventSubscriber, use `KernelEvents::REQUEST` in getSubscribedEvents() method

2) then you use `\Drupal::request()->query->set('key', 'value');`

---
Tags: 7, uri
---


# Question
Title: Why are two database tables (node and node_field_data) used for node data?
I would like to understand the database architecture of Drupal 8. I noticed that Drupal 8 has two separate tables (node and node\_field\_data) which include almost the same columns. Can anyone give some clarification on this?

# Answer
> 0 votes
To add additional information to @jaypan's answer following are my observations

**node\_field\_data** contains 6 fields

```
nid     int(10) unsigned
vid     int(10) unsigned
type    varchar(32) The ID of the target entity.
status  tinyint(4)
title   varchar(255)
uid     int(10) unsigned    The ID of the target entity.
revision_translation_affected   tinyint(4)NULL

```

the **nid** is primary key in this table and referred by node and other fields as target id. The **type** attribute tells what kind of content it is referring to, like posts, article or custom. In case of custom, it will store the name of the content type.

---
Tags: 8, nodes
---


# Question
Title: Value from ajaxified form field not passed to ajax callback
This is a continuation of this issue, where I couldn't get the ajax to fire on an entity reference field in a node edit form. With the following code, I'm able to get the ajax to fire.

```
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function mymodule_form_blog_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_video_reference']['#ajax'] = array(
    'callback' => 'mymodule_video_ajax_callback',
    'wrapper' => 'my-path-div',
  );

  $form['my_path'] = array(
    '#markup' => t('My path'),
    '#prefix' => '<div id="my-path-div">',
    '#suffix' => '</div>',
    '#weight' => 6,
  );

  if (!empty($form_state['values']['field_video_reference']['und'][0]['target_id'])) {
    $form['my_path']['#markup'] = 'Token path: http://www.mysite.org/node/' . $form_state['node']->field_video_reference['und'][0]['target_id'];
  }
}

function mymodule_video_ajax_callback($form, $form_state) {
  return $form['my_path'];
}

```

The problem is that the value from field\_video\_reference isn't being passed to the if statement in the form builder or my callback, so the value from that field isn't displayed in the my\_path field when the value is first selected on the node create form (it works fine if the node has already been saved and there is a value in field\_video\_reference when I edit the node). I'm following examples from the "Drupal 7 Module Development" book as well as from the Examples module, so I can't see what I'm missing.

Thanks.

# Answer
`$form_state['values']['field_video_reference']['und'][0]['target_id']` looks wrong to me.

I would expect the value to be in `$form_state['values']['field_video_reference']`.

If you haven't already then install the Devel module and then use can use `dpm($form_state);` to output the array to the message area and inspect it to find the correct path.

Sometimes for ajax requests Devel Debug Log is also useful as it allows you to send a dump of a variable to a log so you can inspect it even if it is not possible to send content to the message area.
> 0 votes

# Answer
Try to replace with the code

```
if (!empty($form_state['values']['field_video_reference']['und'][0]['target_id'])) {
    $form['my_path']['#markup'] = t('Token path: http://www.example.com/node/' . $form_state['node']->field_video_reference['und'][0]['target_id']);
  }

```

The issue was that you need to put every content of #markup into the t('text') function.
> 0 votes

---
Tags: ajax, forms
---


# Question
Title: Use Rules to notify original author when their node is published
In short, I'm simply looking to notify the original author when their node goes from a non-published state to a published state. I have Workbench Moderation enabled if it makes a difference.

I've tried implementing the exact solution that was provided / accepted here (https://drupal.stackexchange.com/a/159103/79465) but can't get it to work for some reason.

Solved for with the following config:

# Answer
Rules is great, but sometimes also tough to debug if things don't work as you'd expect. In your case, either something unexpected happens in your Rules Conditions, or there is some error in your Rules Action.

There are some typical facilities to do such debugging (further detailed below), but a **K**eep-**I**t-**S**uper-**S**imple technique I often use, is my ***BINGO***-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

If the above doesn't help, then there are typically 2 ways of more advanced debugging, as further detailed below.

# Rules Evaluation Log

Within the Rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "***Rules Evaluation Log***" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

# Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

# More info

For way more details about these 2 variations, refer to **Rules debugging**, as explained in the answer to "How can I display the value of a variable inside a condition?".
> 1 votes

---
Tags: 7, rules, workbench
---


# Question
Title: Use Rules to email all members of a role that is specified within a taxonomy field attached to a node
I tried to concisely explain what I am looking to accomplish in the subject, but will go into more details here. I think I'm really close but my Google-fu is failing me.

**My question:** How can I use the role reference field coming through field\_responsible\_team in a dynamic fashion opposed to the static fashion I've solved for currently?

**Current Setup:**

Content Type: Question

-- Taxonomy: Category (attached to Question content type)

---- Taxonomy Field: Responsible Team (user role) / (attached to Category taxonomy)

**Example Question node:**

Node Type: Question

Category: Training

Responsible Team: Learning & Development

```
    { "rules_XYZ" : {
    "LABEL" : "XYZ",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--question" : { "bundle" : "question" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_category" } },
      { "AND" : [] },
      { "entity_has_field" : {
          "entity" : [ "node:field-category" ],
          "field" : "field_responsible_team"
        }
      }
    ],
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "4" : "4" } },
          "subject" : "XYZ [node:workbench-access-sections]",
          "message" : "XYZ"
        }
      }
    ]
  }
}

```

I got excited when this worked, but realized I had limited this to just users of role 4.

Preferred solution: Dynamically pull in the role from the new node created and use that for the role selection in the "mail\_to\_users\_of\_role" function. I would've thought I could've used the "node:field-category:field-responsible-team" data selector, but it's telling me that "The data type of the configured argument does not match the parameter's roles requirement." I'm using the Role Reference module.

Secondary solution (solved - see below): Create one rule for each of the roles and specify the categories within the rule set (not ideal).

```
{ "rules_XYZ" : {
"LABEL" : "XYZ",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_insert--question" : { "bundle" : "question" } },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "node:field-category" ],
      "field" : "field_responsible_team"
    }
  },
  { "AND" : [] },
  { "data_is" : {
      "data" : [ "node:field-category:field-responsible-team" ],
      "value" : "4"
    }
  }
],
"DO" : [
  { "mail_to_users_of_role" : {
      "roles" : { "value" : { "4" : "4" } },
      "subject" : "XYZ",
      "message" : "XYZ"
    }
   }
  ]
 }
}

```

# Answer
Preface: there is no need for the "AND" in your Rules Conditions (that's the default). Moreover, that "AND" applies to all Rules Conditions *following* the "AND" (but you only have 1 Rules Condition that follows it). Therefor, start by simplifying your Rules to get rid of the "AND". Refer to my answer to "How to make an OR statement in rules?" for more details about all this.

What you could do for sure is to rework your 2nd Rule (for role "4"), into a rule that performs a (new) Rules Component. To start, at least perform these changes:

* Create a Rules Component which uses a parameter named (say) "Selected term". Use a data type of "Taxonomy term".
* In your original Rule:
    + Replace the Rules Action (to send an eMail) by a Rules Action to just execute the (new) Rules Component. While doing so, pass `node:field-category` as the value of "Selected term".
    + Remove the last Rules Condition (with the hardcoded role "4").

The above changes will be a good start, but still it won't be sufficient. The remaining challenge (in the rules Component) will be related to the "Data selector" you need to specify for the Rules Action "Send mail to all users of a role" (= the replacement for your hardcoded "4"). That challenge is because the rules Component parameter "Taxonomy term" is a single value, while for the roles to be emailed you need a *list* (repeat: *list*!), as indicated also below the roles label, where it says "*Select the roles whose users should receive the mail.*" (note: "roles", not "role"!).

Too bad, if we don't have a list, we'll massage the single value (Taxonomy term) into a "list". What follows is an example of a Rule and related Rules Component, with which I could make it work in my own setup:

### Main rule

Here is my sample rule (in which I'm using 2 Rules Events, just to simplify testing and so that the logic is also triggered when updating content):

```
{ "rules_notify_users_of_selected_role_about_new_content" : {
    "LABEL" : "Notify users of selected role about new content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_demo_tags" } }
    ],
    "DO" : [
      { "component_rules_do_something_with_selected_term" : { "selected_term" : [ "node:field-demo-tags" ] } }
    ]
  }
}

```

Note that I'm using a field like `field-demo-tags` (instead of `field_category` as in your case). I'm NOT using the Role Reference module, no need for it. The Rules Action is to only perform a Rules Component, in which the real magic will happen (see below).

### Rules component

Here is my sample Rules Component:

```
{ "rules_do_something_with_selected_term" : {
    "LABEL" : "Do something with selected term",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_term" : { "label" : "Selected term", "type" : "taxonomy_term" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-term" ], "field" : "field_related_role" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Field \u0022field_related_role\u0022  (for Related role ID) is [selected-term:field-related-role]." } },
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cinteger\u003E", "value" : [ "" ] },
          "PROVIDE" : { "variable_added" : { "list_of_roles" : "List of roles" } }
        }
      },
      { "list_add" : {
          "list" : [ "list-of-roles" ],
          "item" : [ "selected-term:field-related-role" ],
          "unique" : "1"
        }
      },
      { "mail_to_users_of_role" : {
          "roles" : [ "list-of-roles" ],
          "subject" : "Some eMail subject (delivered to all users with role id = [selected-term:field-related-role])",
          "message" : "Some message content related to the term named [selected-term:name] (delivered to all users with role id = [selected-term:field-related-role])"
        }
      }
    ]
  }
}

```

The field `field_related_role` is an extra field I added to my taxonomy term I'm using (single value, data type integer), instead of `field_responsible_team` as in your case.

Some more details about this Rules Component:

* Rules Conditions:
    + Check the type of node (in my case "article", adapt to fit your needs).
    + Check that the entity (node being created or updated) has a field `field_demo_tags` (the term I'm using).
* Rules Action:
    + Show a message on the site (just for QA-testing purposes, omit if not needed anymore).
    + Add a variable, i.e. a "*list of integers*", which will become the "List of roles" we'll need in a subsequent Rules Action.
    + Add to this list, the value of `selected-term:field-related-role` (part of the Rules Component parameter).
    + Send mail to all users of a role, whereas we use the newly created "List of roles" to get it all to work (adapt eMail subject, message, etc to fit your needs).

The above works like a charm, at least in my case/setup: I have 3 users with a role related to a taxonomy term I used while updating an article, and each of those 3 users did receive an eMail as in my last Rules Action.

***Voilà*** ...
> 1 votes

---
Tags: 7, rules
---


# Question
Title: How to properly perform a patch so that the correct directory is used?
I attempted to make a patch using Making a Drupal patch with Git and ran into one issue after creating the patch. For some reason, I cannot get the proper location to be stored in the patch.

How can I get the desired results in the patch?

Issue

* the issue is that it is setting diff --git "a/docroot/modules/contrib/video\_embed\_vidyard/src..."

Command used to generate the patch:

```
git diff <commit#1> <commit#2> > patch-name.patch

```

Current results:

```
diff --git a/docroot/modules/contrib/video_embed_vidyard/src/Plugin/video_embed_field/Provider/Vidyard.php b/docroot/modules/contrib/video_embed_vidyard/src/Plugin/video_embed_field/Provider/Vidyard.php
index 94a7dc26b..4de97deb7 100644
--- a/docroot/modules/contrib/video_embed_vidyard/src/Plugin/video_embed_field/Provider/Vidyard.php
+++ b/docroot/modules/contrib/video_embed_vidyard/src/Plugin/video_embed_field/Provider/Vidyard.php

```

Desired results:

```
diff --git a/src/Plugin/video_embed_field/Provider/Vidyard.php
b/src/Plugin/video_embed_field/Provider/Vidyard.php
index 94a7dc2..be635ad 100644
--- a/src/Plugin/video_embed_field/Provider/Vidyard.php
+++ b/src/Plugin/video_embed_field/Provider/Vidyard.php

```
* I want to be able to generate `a/src/..` instead of `a/docroot/modules/contrib/video_embed_vidyard/src`

# Answer
> 4 votes
The command `git diff` always creates a diff (patch) for the current repository you are working with. If you want to create a patch for a certain module, but get a diff with full paths including your Drupal root, it's very likely that you are either

(a) not within the directory of the module's Git repository, or

(b) your module is not a git repository, thus Git is using the next repository it finds while traversing up the folders.

**How to fix it?**

If you want to create a diff using `git diff`,

(1) make sure you are using a version of the module that has been cloned from a Git repository. When using Composer for dependency management and your module is a contrib module, you can do so by requiring the dev version of the module, e.g. with your video\_embed\_vidyard module:

```
composer require "drupal/video_embed_vidyard:1.x-dev"

```

Make sure to backup your applied changes first to another location, as running the above command will most likely overwrite them; then re-apply them before proceeding with step (2).

If you are NOT using Composer for dependency management, you can manually clone the module. Every contrib module has a *Development* section within the sidebar of its project page. Locate the *Browse code repository* link.

On the bottom of the repository listing, you'll find the public clone URL. For your module, the clone command would be:

```
git clone https://git.drupal.org/project/video_embed_vidyard.git

```

You might have to switch to the correct branch after cloning, as some modules still use the 7.x branch as default or did not set any.

(2) make sure to run `git diff` from within the module root (Git repository root of the module), not the Drupal root:

```
cd docroot/modules/contrib/video_embed_vidyard
git diff > ../video_embed_vidyard.patch

```

This will save your patch in your contrib folder. If you intend to send this patch to the Drupal issue queue of this module, you should also include the issue number in the name of the patch file.

(3) \[optional\] once again, if you are using Composer for dependency management (highly suggested for Drupal 8), then post your patch to the drupal.org issue queue and also enable patching (cweagans/composer-patches) and include the patch in your `composer.json`. This ensures your changes being applied to your version of the module every time you are running a Composer install (until your patch was approved by the maintainers and merged with the module's code base).

# Answer
> 4 votes
Actually, there is a fairly easy way to generate a patch for a certain path with `--relative`.

So in your case, just run `git diff --relative=docroot/modules/contrib/video_embed_vidyard`.

---
Tags: 8, version-control
---


# Question
Title: How to pass additional arguments in $form['#after_build']
```
function custom_third_level_auto_suggest_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$form['#after_build'] = 'custom_third_level_auto_suggest_widget_selection_afterbuild';

}

```

I need to pass $element across #after\_build function, how I can implement it?

# Answer
Most of callbacks like `#after_build` will received automatically 2 arguments: $elements and $form\_state, like this :

```
my_callback_after_build($element, &$form_state){
//...
}

```

So you simply have to push your var in the form\_state var from where you add your callback :

```
function custom_third_level_auto_suggest_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
   $form['#after_build'] = 'custom_third_level_auto_suggest_widget_selection_afterbuild';
   $form_state['foo'] = 'bar';
}

```

And you'll get it in the form\_state var of your callback like this:

```
function custom_third_level_auto_suggest_widget_selection_afterbuild($form, &$form_state){
   var_dump($form_state['foo']); //will print "bar"
}

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Visibilities permissions of children links in the Toolbar
In a project started with the Thunder distribution, I'm currently managing the permission of the "editor" group.

By default, it only have access to the content menu, and it's a good thing. But what if I want to give permission to some children links (and only some specific children) of the others menu ?

**Exemple:**

I give to this group the ability to access, add, edit and delete some taxonomy terms.

I can access to the relative admin page, but the `structure -> taxonomy` link in the Admin Toolbar is not appearing.

For now I have to manually create those links, but I think it's not the right way to do this because they will constitute duplicate link for the "administrator" group.

I suppose I need to give visibility right for the parent link "structure", but how?

# Answer
> 2 votes
This is not a problem with the Admin Toolbar module, I think that you're not given the correct permissions.

In **Drupal \>= 8.5** you need to give the following permissions:

* Use the administration pages and help
* Use the administration toolbar
* Tags: Create terms
* Tags: Delete terms
* Tags: Edit terms
* Access the taxonomy vocabulary overview page

In **Drupal \< 8.5** as the *Access the taxonomy vocabulary overview page* not exists you need to assign the following permissions:

* Use the administration pages and help
* Use the administration toolbar
* Tags: Create terms
* Tags: Delete terms
* Tags: Edit terms
* Administer vocabularies and terms

The problem here is that the user will have the permission to create new vocabularies.

You can read about this in New term overview and create permissions and in Add a dedicated permission to access the term overview page (without 'administer taxonomy' permission)

---
Tags: 8, taxonomy-terms, users, navigation, toolbar
---


# Question
Title: How to give blocks a meaningful name in the views overview page?
I think, the image will speak for itself:

I have tried the block & display titles, the block name & also the new administrative comment field. Still the views overview looks not very informative.

Thanks!

# Answer
Right now, there's no way to add a description for views displays for better visual distinction.
> 0 votes

# Answer
Currently your description is empty, you can add a description to your view which will help somewhat.

Click on the `edit view name/description` button
> 2 votes

---
Tags: views, 8
---


title: Drupal 8 Menu always show as expanded

text:
# Question
Title: Drupal 8 Menu always show as expanded
I'd like to have a menu show as expanded regardless of whether it is checked or not in the UI (or always checked when a new menu item is created by a user)

I have been looking at `hook_menu_links_discovered_alter`

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook\_menu\_links\_discovered\_alter/8.1.x

> expanded: (optional) If set to TRUE, and if a menu link is provided for this menu item (as a result of other properties), then the menu link is always expanded, equivalent to its 'always expanded' checkbox being set in the UI.

How could I implement this?

# Answer
If you are placing the menu in a block for display, check out the Menu Block module https://www.drupal.org/project/menu\_block it has an option to expand all menu links.
> 3 votes

# Answer
If this is for a custom module:

1) Make a file called \[modulename\].links.menu.yml

2) add information about the link to the file, for example:

```
[modulename].menulink1:
title: 'View 1'
parent: main
menu_name: main
route_name: [modulename].route1
expanded: TRUE
weight: 2

[modulename].menulink_child1:
title: 'View 2'
description: 'View the second'
parent: [modulename].menulink1
route_name: [modulename].route2
menu_name: main
weight: 2

[modulename].menulink_child2:
title: 'View 3'
description: 'View the Third'
parent: [modulename].menulink1
route_name: [modulename].route3
menu_name: main
weight: 3

```

3) Refresh the cache. As long as the routes are defined in your \[modulename\].routing.yml file, the menu will appear in the main menu block, and the parent menu will be auto-expanded.
> 1 votes

# Answer
Quick solution to expand the entire menu, you can do this with drush or phpmyadmin:

First get the machine-name of the menu you want to set expanded. To see a quick list use this query in phpmyadmin:

```
//In Phpmyadmin:
SELECT DISTINCT menu_name FROM menu_tree;

//with Drush:
drush sqlq "SELECT DISTINCT menu_name FROM menu_tree;"

```

Once you know the machine name you can use this query to convert the entire menu to expanded:

```
//in Phpmyadmin:
UPDATE menu_tree SET expanded='1' WHERE menu_name='replace_menu_name_from_previous_query';

//with Drush:
drush sqlq "UPDATE menu_tree SET expanded='1' WHERE menu_name='replace_menu_name_from_previous_query';"

```

Afterwards it might be necessary to clear the caches.
> 1 votes

---
Tags: 8
---


# Question
Title: Best practice to deploy an update which depend of a new configuration
In an entity type, I need to replace a field by another with a more complexe behavior. This new behavior can reproduce the old field and add new. Like this behavior have an impact on the design, I need to update all entities with this new field to keep the data of the old field before delete it.

This import is done with a hook update. My problem is, in my hook\_update is executed before I import my configuration. But I can't migrate my data in my new field like it doesn't exist yet. So, my question is, what's the best practice to do that:

* Should I create programmatically my new field on my entity type in a hook\_update and migrate my datas in the new field before import my configuration. This possibility allow me to delete the old field with configuration and everything will be over. But, if I create my field programmatically, I can do some errors or difference between what I have in my configuration. And, additionally, I want be lazy and don't reproduce a code which exist elsewhere. It's a little problem and I see I can improve this workflow.
* Can I import configurations which concern only (and only that) the new field, do my migration of datas and import the rest of my configuration as usually? This seems be the best practice but I don't know if it's possible.
* An other solution?

I thought about import all configurations before do the hook\_update but this solution seems the worst thing to do: I can have update of contrib modules in my release and configurations could be apply only after these updates (I never met this case, but it's could be possible). Additionally, I will keep my old field until the next deploy.

I suppose my first solution is the only I can do but, maybe I don't thought about another.

# Answer
I would recommend that you create the field programatically. In your update function. You could also create multiple update functions, just create the field in one, then migrate the data then remove the old field.

If you have a lot of data, then your update function should be done as a batch, so it doesn't run in any PHP timeouts or memory limits. In that case, having the update functions separate makes it easier to implement them.

To avoid duplicating code, you could read the config from the config sync storage and create it through the config entity storage, something like this:

```
$config_record = \Drupal::service('config.storage.sync')->read('field.storage....');
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$entity = $storage->createFromStorageRecord($config_record);
$entity->save();

```

This is usually fine for custom update functions in projects because it will only be executed once. This approach is risky for core/contrib/reused modules (which usually import it from their default config) because you don't know when the update will be executed. Maybe you have to make another change to that config next week and add another update function to deal with that change, but if someone didn't execute the first yet, this initial update will already create the field based on the latest schema and then your update logic might get very confused about that.
> 5 votes

---
Tags: 8, deployment
---


# Question
Title: Adding a new variable to account menu for twig rendering
I am trying to add a variable to render in the menu-account.html.twig file.

Here is my preprocess function in my .theme file.

```
function HOOK_preprocess_menu__account(&$variables) {
    $variables['account_name'] = Drupal::currentUser()->getAccountName();
}

```

*HOOK is replaced with my theme name*

And in my twig file I have this snippet:

```
<div class="welcome-message">
    Welcome, {{ account_name }}!
</div>

```

So I can edit pre-existing variables but I cannot seem to add a new one.

I was reading that new variables cannot be added in a preprocess function and that the HOOK\_theme\_registry\_alter should be used.

Here is what I attempted and by using xDebug I can tell that it is getting looked at when flushing caches.

```
function HOOK_theme_registry_alter(&$theme_registry) {
    $theme_registry['menu']['variables']['account_name'] = [];
}

```

Does anyone know the steps to get a new variable to be rendered in the menu twig file. This my first time using the theme registry hook so I might be doing something wrong there as well.

Thanks,

EDIT: "menu--account.html.twig" was named correctly in my code but mistyped in my question. Thank you to GiorgosK for pointing this out.

# Answer
> 1 votes
In your `THEMENAME.theme`

```
function THEMENAME_preprocess_menu__account(&$variables) {
  $variables['account_name'] = Drupal::currentUser()->getAccountName();
}

```

And in your `menu--account.html.twig`

```
<div class="welcome-message">
  Welcome, {{ account_name }}!
</div>

```

Just tested and it works, so basically what you posted should work but probably you mistyped the twig file name which needs two dashes (--)

---
Tags: 8, theming
---


title: How do I migrate user passwords?

text:
# Question
Title: How do I migrate user passwords?
I have refactored an old Drupal 6 site to Drupal 8 and my only problem is, i migrated the users but the password is incorrect. i know that the password in Drupal 6 is a MD5 hash, but i cannot find a solution to convert this password, that Drupal 8 can read it.

Is there any solution for the password migration yet? can i give the MD5 hash a prefix inside of the database to make it readable?

# Answer
> 3 votes
User and user password migration is part of the `Migrate` and `Migrate Drupal` modules that come with Drupal 8 and that can easily be accessed using the `Migration Drupal UI`.

One word of warning though, from the guide on Upgrading using the migration user interface:

> Due to password encryption, user accounts take particularly long to import.

# Answer
> 5 votes
Security wise it would make sense to import them in Drupal and then use the Mass Password Reset module to reset all passwords.

# Answer
> 0 votes
See Migrating MD5 hashed passwords

There is also a D6 migration example in `/core/modules/user/migration_templates/d6_user.yml`:

```
id: d6_user
label: User accounts
migration_tags:
  - Drupal 6
source:
  plugin: d6_user
process:
  ...
  pass: pass
  ...
...
destination:
  plugin: entity:user
  md5_passwords: true
...

```

Key solution here to correctly migrate the passwords is to use the `md5_passwords: true` option for the destination user entity. So make sure you include that option in your user migration config.

---
Tags: 8, users, migrations
---