title: How to export a menu and blocks?

text:
# Question
Title: How to export a menu and blocks?
I created a Superfish menu in a test installation of Drupal (8.5.4) and want to import it into another install (8.5.5). How can I do this?

Is the navigation data stored in menu\_link, menu\_link\_content, and menu\_tree? I tried importing these tables into my new install, but when I try to "Place Block" in Block Layout - I don't see the old menu showing up as a Superfish block.

I also tried using the Menu Export module. But was unable to find the "Menu Export Configuration" page that they show in the image.

The new install is migrated from Drupal 7. So it lacks a config table. Where is the config installed? I think I need to copy the menu which is stored in a blob in the config table, but I don't know where to put it.

Note: The main question is "How can I export the menu"? To which the answer appears to be "Not possible." I'm still confused though as the menu information has to be stored somewhere. The other sub-questions are trying to get at pieces of the puzzle.

# Answer
Both menu link items and custom block content are treated as ***content*** within Drupal core. That's to say, they ***aren't covered*** by the configuration management system.

In instances where it make sense to have menu link items or custom block content stored in the configuration system, there are modules out there to assist with this:

* Fixed block content: Provides a way of having permanent custom content blocks without broken instances if the block does not exist.
* Config menu link: A drop-in replacement for core's Custom Menu Links module.

There many other options to store menu/block data into the config system so it's worth your time to explore other options to find the one that best matches your scenario (especially since Superfish seems to be a part of it).
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: How to fix Filter selections on VIEW result pages
1\] I am using Exposed Filters (Page Display - not Block Display) in a view.

2\] Sorting by three parameters: Materials, Machines, Industry(s)

3\] Using Paging to deliver Results

4\] Filters have "Remember last selection" turned off

5\] Display\>Page\>Advanced: AJAX (OFF - per other threads) Caching (NONE - per other threads)

6\] Drupal 8

Problem: Filter results are fine and not the problem. Filter selections change after initial page. (Illustrated here)

Regardless of browser - delivers same broken filter selections after page 1.

Help appreciated. Thanks!

# Answer
I found a patch here (see note #5) that worked in my circumstance: https://www.drupal.org/project/drupal/issues/2897694#comment-12677908 Hopefully this can help someone else.
> 0 votes

---
Tags: views, paging
---


title: Product image field best practice

text:
# Question
Title: Product image field best practice
I am building a site selling engineering components. There are many Variations of some of the products but each variant looks almost identical.

Would I be better placed having an image field for each variant or just one image field in the product type?
If I go down the 'image field in the variant' option, then each variant would have the exact same image; yet, this doesn't strike me as sensible.

# Answer
If the image doesn't really vary by variation, I would put it on the product. This will save you disk space / database space in the long run. Alternately, you may be able to use the Media module to upload the image once and reference it from all of the variations. This would let you use a single product type to handle product pages whether their variations required different images or not.

At the end of the day, there is no single best option here.
> 0 votes

---
Tags: commerce
---


# Question
Title: How can I change the "Edit" tab name to something more meaningful?
I would like to change the Edit tab from Edit to Edit Client. The content type is Client.

I tried using the following code in the bartik.theme file in the web/core/themes directory (running drupal 8.5.4).

```
function bartik_preprocess_menu_local_task(&$variables) {
  if (isset($variables['element']['#link']['title']) && $variables['element']['#link']['title'] == 'Edit') {
    $node = \Drupal::request()->attributes->get('node');
    if ($node && $node->getType() == 'client') {
      $variables['link']['#title'] = t('Edit Client');
    }
  }
}

```

# Answer
> 2 votes
Use `hook_menu_local_tasks_alter` see the docs. You can get a dynamic title combining tokens and the translation API.

---
Tags: 8
---


# Question
Title: Form filter by field on entity_autocomplete
I have a form with this field. the user can save one or more results. I want to filter by the foreign key who is on the user table but i don't know how to do this.

My code :

```
$form['referent_business'] = [
  '#title' => 'Référent',
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#required' => TRUE,
  '#tags' => TRUE,
  '#validate_reference ' => TRUE,
  '#autocreate' => false
 ]

```

So I tried another solution :

```
$form['referent_business'] = [
  '#title' => 'Référent',
  '#type' => 'textfield',
  '#autocomplete_route_name' => 'jds.autocomplete_referent_ce',
  '#autocomplete_route_parameters' => [
    'business' => $entity->id()
  ],
  '#required' => TRUE,
  '#tags' => TRUE,
  '#validate_reference ' => TRUE,
  '#autocreate' => false,
  '#access' => $user->hasRole('administrator') ? TRUE : FALSE,
];

```

With the function

```
public function autocompleteReferentCE(Request $request, $business)
{
    $matches = [];
    if($string = $request->query->get('q')) {
        $query = \Drupal::entityQuery('user')
            ->condition('status', 1)
            ->condition('id_business', $business)
            ->condition('last_name', '%'.db_like($string).'%', 'LIKE');
        $idUsers = $query->execute();
        $users = User::loadMultiple($idUsers);
        foreach($users as $user) {
            $matches[] = [
                'value' => $user->get('first_name')->value . ' ' . $user->get('last_name')->value,
                'label' => $user->get('first_name')->value . ' ' . $user->get('last_name')->value
            ];
        }
    }
    return new JsonResponse($matches);
}

```

The custom entity\_autocomplete function works. When the user saves several results, the return isn't an array, but a string.

So, someone knows how to filter with the first solution or return an array of result with the second solution ? Or another solution ?

Thanks in advance

# Answer
> 0 votes
The core autocomplete feature expects the label of the returned matches contain the id of the referenced entity like `Superuser (8)` which is parsed by the drupal.autocomplete behavior and submitted through the actual form input. The easy solution its to ensure that your response returns the expected values. But you can always implement your own. See `Drupal\entity_reference\EntityReferenceController` to see how the core implenents it.

---
Tags: forms
---


title: Entity reference selection by view

text:
# Question
Title: Entity reference selection by view
I have two content types, Location and Offer. The Offer type has an entity reference field that points to one or more Locations.

A user of my Merchant role may create Location and Offer nodes. When creating an offer, they need to select from the list of Location nodes that they created.

I created a view with an "Entity Reference Source" display to build the Merchant's list of Locations when creating Offers. I limited the Locations to this Merchant by a relationship between author (of the Location) and currently logged in user.

Now, I need Administrator users to be able to edit Offers. The problem is that the view creates a list of the Administrator's Locations instead of the author Merchant's Locations.

How can I supply a list of entities to the locations entity reference field that is the current user's Locations when an Offer is being created and the author's Locations when an Administrator edits?

# Answer
> 0 votes
You are probably looking for a way to pass a contextual filter from the current page to the entity selection view.

Currently an argument can sadly only be static.

However there is a patch that allows you to add an argument using a token provided by the current page you are on.

You can find the patch here: https://drupal.org/node/1699378#comment-6809760

# Answer
> 0 votes
You can use the Views Arguments module with the default argument callback. Your callback can return the argument exception value (typically the string `all`) which forces the view to skip the argument and return all results. This can be done when the current user is admin otherwise the current user id is returned.

---
Tags: 7, views
---


# Question
Title: How do I define a template file for a specific node paragraph ID?
I would like the ability to override a template for only 1 paragraph. Is it possible to override just one paragraph like we can with nodes node-{nodeid}.html.twig?

# Answer
> 5 votes
This can be easily achieved by implementing `hook_theme_suggestions_HOOK_alter` from within a custom module or your theme. After that you can override paragraphs by adding templates like `paragraph--123.html.twig` to your theme's template directory.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE/MYTHEME_theme_suggestions_paragraph_alter(array &$suggestions, array $variables) {
  $paragraph_id = $variables['elements']['#paragraph']->id();
  $suggestions[] = 'paragraph__' . $paragraph_id;
}

```

---
Tags: 8, paragraphs
---


title: How do I change the used PHP version?

text:
# Question
Title: How do I change the used PHP version?
I am using Drush to update modules. When I run the command php -v it correctly shows I am running version 5.5

I then use the command drush rf followed by drush up to perform any updates.

I am using the Schema.org Metatag module which requires php version 5. The website is running php version 5.5.37

The default CLI version on Hostgator shared server is 5.4.45. That is what I was originally using for drush. When I received the message below I found the path to use php 5.5 but I am still getting the same message. So I can't figure out how it still sees php ver 5.4.45 and how to resolve this so it doesn't keep disabling that module.

When Drush runs an update I get the following message: *Schema.org Metatag requires at least PHP 5.5. (Currently using PHP \[warning\] 5.4.45)*

And then it disables the Schema Metatag module.

NOTE: When I run command drush status: PHP configuration: opt/php55/lib/php.ini Drush version is 8.1.11

Thanks

## Extra information

.bash\_profile

```
PATH=$PATH:$HOME/bin
export PATH
alias composer="/opt/php55/bin/php ~/bin/composer.phar"
alias drush="/opt/php55/bin/php ~/.composer/vendor/bin/drush.php"

```

.bashrc

```
 alias php='/opt/php55/bin/php'
 alias composer='/opt/php55/bin/php ~/bin/composer'
 export DRUSH_PHP='/opt/php55/bin/php'

```
* `php -v` returns PHP 5.5.37
* `which php` doesn't return anything
* `drush status` returns PHP configuration /opt/php55/lib/php.ini

But, when I use Drush to update a module I still get: `Schema.org Metatag requires at least PHP 5.5. (Currently using PHP [warning] 5.4.45)`

# Answer
> 2 votes
* Find the path to php 5.5’s binary.
* Find the path to drush.

Execute

```
/path/to/php_55/bin/php /path/to/drush status

```

---
Tags: drush
---


# Question
Title: Error : No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view
I cannot work out some basic stuff ... what do I not correct? Using D8, distribution varbase.

I would like to create a reference from one content type to antoher in D8 so a user is able to use a select box by module chosen (https://www.drupal.org/project/chosen)

I looked up different post but cannot find the problem. The latest QA is followed is: How to create a select box field to select from a filtered list of articles? or also this post How to create a view type of Entity reference display?

So I did I create a view

```
- Add Display Entity Reference
- Format:Entity Reference list | Settings with content: title
- Show:Entity Reference inline fields | Settings with content title.

```

Then I add some fields as well. The result is a list of education Clear cache, did drush CR.

I goto to the content type I would like to have the reference (e.g. student). Add a field and would like to add this view a a selectbox to object student.

I should be entity reference the in the reference field I select Views with a filter reference. But every time I get the message here...

**No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view.**

The view list displays: Nascholingsactiviteit voor leden - Entity Reference Source

I made another view for testing purposes but no result of that as well.

I tried other fields but i cannot get it working. I though this is all in D8 core now... Any suggestions?

# Answer
> -1 votes
I solved it by chosing content as a reference. After that the options are the same but then it is displaying the view and it works.

---
Tags: 8, views
---


# Question
Title: How do I display a taxonomy term if another term is active for a node?
I have a content type that has taxonomy terms for Category, like Blog, Publication, and Project. Depending on which term is selected, the content is displayed under blogs, publications or projects. If the category selected is Project, then the user has to select the focus area from another vocabulary (not a child vocabulary) - Focus Area 1, Focus Area 2... through to Focus Area 10.

Currently, my pathauto pattern displays the Category/Node\_Title - \[node:field\_post\_category:entity\]/\[node:title\]

My objective is that I also want to display the Focus Area term in the node url, but **ONLY** if the category chosen is 'Project'. In that case, I want the url to be project/focus\_area\_n/node\_title. So the focus area is displayed in the node url only if the category is project. Is there a Pathauto pattern, or any other method that I can use to accomplish this?

I need to do this so that I can control the display of a few blocks in the sidebar that will show up depending on what the URL is.

Thanks in advance...

# Answer
It was actually quite easy! No custom-coding required. I just added the token for the other vocabulary to the URL alias pattern, and it now appears, when it's present. When not present, the regular URL is formed.

So now the new pattern is \[node:field\_post\_category:entity\]/\[field\_focus\_area:entity\]/\[node:title\]

Drupal is great!
> 0 votes

---
Tags: path-aliases
---


title: drupal 8.2 to 8.5 update error

text:
# Question
Title: drupal 8.2 to 8.5 update error
I am getting the following error.

> Recoverable fatal error: Argument 3 passed to Drupal\page\_manager\Routing\VariantRouteFilter::\__construct() must be an instance of Symfony\Component\HttpFoundation\RequestStack, none given, called in /home/ranjith/public\_html/core/lib/Drupal/Component/DependencyInjection/Container.php on line 266 and defined in Drupal\page\_manager\Routing\VariantRouteFilter-\>\__construct() (line 64 of sites/all/modules/contrib/page\_manager/src/Routing/VariantRouteFilter.php).

What does it mean? How can I fix that error?

# Answer
What you're seeing is the result of the Drupal service container failing to create a service because its cached definition doesn't match the class anymore: An extra constructor argument was added (in this change), and Drupal is not passing that argument.

This is a typical error that can happen after updating modules. Make sure to completely empty your cache manually. You might be able to do this using `drupal cr all` or `drush cr` or by visiting the admin backend, but not if the service is already loaded during bootstrap. In that case, try to empty the `cache_container` database table directly.
> 2 votes

---
Tags: 8
---


title: View multiple images with Lightbox

text:
# Question
Title: View multiple images with Lightbox
I have a list of projects in a view with one image for each project, which is displayed with Lightbox. The client asked me if it is possible to:

* Have more than 1 image, but show the first one (done)
* Clicking on the image, make the other images visible

How can I achieve this? Is there any method that is not changing the image formatter?

# Answer
Use Colorbox instead:

Formatter: Colorbox Content image style: Hide (do not display image) Content image style for first image: Thumbnail Colorbox image style: None (original image) Gallery (image grouping): Per post gallery

Under 'multiple field settings' I set it to display 'all', choosing Display type: 'Simple separator' and changing this from ', ' to ' '.

https://www.drupal.org/node/1026112 #50
> 1 votes

# Answer
Possible in views. You can use Rewrite Code in first image settings under view edit page. Here you can type your own custom html using fields inserted in the said view. For example: first-image
> 0 votes

---
Tags: 7, views, javascript
---


# Question
Title: How to install oAuth using PHP 7 and PECL OAuth library?
I am \[unsucessfully\] trying to enable the Twitter module on a Drupal 8 site that is using PHP 7 on ubuntu. The Twitter module requries oAuth to work and oAuth requires the PECL OAuth library.

If I run `sudo pecl install oauth`

I get back:

`pecl/oauth is already installed and is the same as the released version 2.0.2 install failed`

and then if I try `drush en oauth`

I get back:

`Module oauth doesn't meet the requirements to be enabled. [error]
OAuth module requires the PECL OAuth library.`

Any help with how to configure the oAuth moudle and the PECL oAuth library?

# Answer
Well, while I have no final solution, since I humbled over the same issue 2 years later today, I can at least put some more light on it and help with some more tests, etc.

First things first: There is some bug tracking missing in your report.

What is `php -m` saying? It should list all recognized php modules. The pecl php extension **oauth** should be listed here. If not, check if you carefully followed the instructions printed on the terminal while installing `sudo pecl install oauth`. It says that you have to make sure that the line `extension=oauth.so` is added to your `php.ini`. This is a standart recommendation which can also be translated to: make sure that `oauth.ini` is in `.../php/mods-available` and symlinked from `.../apache2/conf.d/...` to it to be recognized as a enabled module.

If not then check `php-config --extension-dir` to see where all your php .so extensions are really installed and then list them with `ls -ahl` to make sure that oauth has been compiled correctly.

Another thing to be aware of is that php comes in 2 modes: cli mode and server mode. Both can be mixed sometimes and can cause confusion since even Drupal mixes it all the time to check php extensions. Create a simple `test.php` file and put `<? phpinfo(); ?>` in it and run it as a local link in browser to check if **OAuth** is listed there somewhere (CTRL+F oauth). If it is listed it seems that only php cli does not recognize the extension and Drupal cannot find it. In this case repeat the step above (symlink) with the extension also symlinked in `.../php/cli/conf.d/...`. Then `php -m` would show the module recognized.

Finally, if you checked it all twice like me and found out that the oauth extension still doesn't load into your php/apache2 enviroment correctly or Drupal won't find it, you will stuck on the same level like me :) And I found out, that I am not allone. There seem to be a list of issues regarding this in the web (Google) OAuth making some trouble under php7.

But if you have checked twice that php AND(!) php-cli can find the module, you will be part of the 99% who made it work with Drupal finally then. Good luck.
> 2 votes

# Answer
Re oauth @nilsum's suggestion shed light into my seeming oblivion as well. I am on drupal 8 but i suppose solution would apply to Drupal 7.

You may check if this module is already installed in your server as it usually would be part of php in most cases. You may be able to install “PHP Pecl” modules if you have root access (SSH or WHM). Otherwise request your webhost to install particular module of interest in this case oauth.so . This would be found in '/opt/cpanel/ea-php72/root/usr/lib64/php/modules'. I was able to install the package and then added the extension to php.ini.

Again, where you have root access to php.ini, confirm this extension is present or not. If absent, (which is the reason some fail to enable oauth module and twitter), then add the extension 'extension=oauth.so'. Otherwise create a php.ini file on your drupal root server and add the extention (alongside any file/memory size changes you might wish to adjust. If successful, oauth easily enables which allows twitter to also be enabled. Hope this helps.
> 0 votes

---
Tags: 8, authentication-authorization, social-network
---


# Question
Title: How to redirect user to an url when node is flagged?
My problem is related to the **Drupal 8** versions of these two modules: **rules** and **flag**.

***What I want to achieve***

* Some node types on my site are offering a global flag as a link (for e.g. "report error" flag)
* If the user clicks on it, he should be redirected to a special contact form. The flagged node URL should be submitted to an entity reference field automatically on the contact form too.

***How I solved it in Drupal 7***

In *Drupal 7* there was a rules event "node is flagged" to trigger the redirect action. The flagging URL I could pass via Drupal 7 module "entity reference prepopulate" (which functionality is merged into core reference field in Drupal 8).

In Drupal 8 the rules event "node is flagged" seems not to exist.

Any idea how to realise a behaviour like described above in Drupal 8?

THX in advance,

Phil

# Answer
> 4 votes
You need to use the event, **After saving new flagging**

Add Condition of Flag, and enter flag machine name

Add action of Page redirect, enter the url where you want to redirect. Ex: `/node/1`

**Important**

In your flag settings, you need use a link type of **Normal link**, because it won't work with AJAX

---
Tags: 8, rules, flags
---


title: db_insert a lot of records

text:
# Question
Title: db_insert a lot of records
I am struggling to sort out how to insert a lot of records using db\_insert

Please see below for the code.

I can't have a for loop in the array. It breaks but I am dealing with looping through a lot of data. 48 (states) X 365 (# days) X 36 years.

What is the best way of accomplishing this?

Thanks!

```
$query = db_insert('HDD')
  ->fields(array(
  for ($s = 0; $s <= $cnt; $s++) {
    'HDDDAYS' => $time, //Loops through the dates
    'AL'=> $output1[$sts[0]][$dts[$s]],
    'AR'=> $output1[$sts[1]][$dts[$s]],
    'AZ'=> $output1[$sts[2]][$dts[$s]],
    'CA'=> $output1[$sts[3]][$dts[$s]],
    'CO'=> $output1[$sts[4]][$dts[$s]],
    'CT'=> $output1[$sts[5]][$dts[$s]],
    'DE'=> $output1[$sts[6]][$dts[$s]],
    'FL'=> $output1[$sts[7]][$dts[$s]],
    ....
    'WI'=> $output1[$sts[45]][$dts[$s]],
    'WV'=> $output1[$sts[46]][$dts[$s]],
    'WY'=> $output1[$sts[47]][$dts[$s]]
  }));
  $query->execute();

```

# Answer
You could define your query fields first, then set your field values in a loop before executing the query.

Example (not tested):

```
$query = db_insert('HDD')->fields(array(
  'HDDDAYS',
  'AL',
  'AR',
  ...
));

for ($s = 0; $s <= $cnt; $s++) {
  $query->values(array(
    'HDDDAYS' => $time,
    'AL' => $output1[$sts[0]][$dts[$s]],
    'AR' => $output1[$sts[1]][$dts[$s]],
    ...
  ));
}

$query->execute();

```
> 1 votes

---
Tags: 7, database, performance
---


# Question
Title: Different view page based on taxonomy depth?
I'm wondering if there is a way to show a different view (or view part) based on the current depth of the term level?

Example I have a bunch of categories and subcategories. For the categories I want to show a page that is just the name of the category, once I go in to the next level (subcategories) I want the name and the image and description or whatever you have.

Is there anyway to do this? I have a page view that is mapped to category/% so we would get category/% \** CATEGORY **/% ** SUB CATEGORY \**

# Answer
if you know the depth of the category in advance you could create different view page for each depth of the category.

For example for the main category the path would be category/% and for the subcategory the path would be category/%/%

this way when there is 1 argument after category the view page for the main category would be displayed. If there are two arguments the view page for the sub category would be displayed.
> 0 votes

# Answer
This is possible with a combination of

The trick is to have a different view mode per taxonomy depth.
You can then use views\_content + ds dynamic fields to have dedicated views show up on each view mode. This is covered in depth in other questions on drupal.stackexchange.com and drupal.org, so I'm not going to repeat it here. Instead I am going to focus on the entityaspect stuff.

Custom module code:

```
/**
 * Implements hook_entityaspect()
 *
 * @param entityaspect_InjectedAPI_hookEntityAspect $api
 */
function e4btcmod_entityaspect($api) {

  $api->type('taxonomy_term')
    // Create dedicated view mode for top-level term pages.
    // (other terms can use the "full" view mode)
    ->viewMode('term_toplevel_page', 'Top-level term page')
    // Let entityaspect control "taxonomy/term/%"
    ->hijackPage('taxonomy/term/%')
  ;
}

/**
 * Implements hook_entityaspect_page__ENTITYTYPE()
 * This is responsible for
 * - Deciding what to show on the page, if it is being visited.
 * - Setting a title for the page and for the link.
 * - Deciding whether this is a tab, the tab weight, etc.
 * - Access checking:
 *   If you tell entityaspect to show something specific on the page,
 *
 * @param entityaspect_InjectedAPI_hookEntityAspectPage $api
 * @param stdClass $term
 * @param string $route
 */
function MYMODULE_entityaspect_page__taxonomy_term($api, $term, $route) {

  // Only act on taxonomy/term/% route.
  if ('taxonomy/term/%' !== $route) {
    return;
  }

  // Access check.
  // @todo: I don't remember atm if entityaspect already does a basic entity view access check.
  if (!does_the_user_have_access($term)) {
    // In case of no access, we simply return and do nothing.
    return;
  }

  // The term name should be the page and link title.
  $api->title($term->name);

  switch ($term->vocabulary_machine_name) {

    case 'my_vocab':
      // Determine if it is a top-level term.
      $parent_terms = taxonomy_get_parents($term->tid);
      if (empty($parent_terms)) {
        // Use a dedicated view mode for top-level terms in cnet_categories.
        $api->viewMode('term_toplevel_page');
        return;
      }
      // Fall through to "default" case.

    default;
      // Terms of other vocabularies, and deeper-level terms of my_vocab.
      // Let taxonomy_display handle the output.
      $api->pageCallback('taxonomy_display_taxonomy_term_page', array($term));
      return;
  }
}

```
> 0 votes

# Answer
You can use a contextual filter / relationship to achieve this, no coding or additional modules needed.

Only show parent terms in view:

* Add a contextual filter (Taxonomy term: Parent term)
* In the contextual filter settings select "Provide default value" and enter "0" for Fixed value

Only show child terms in view:

* Add a relationship (Taxonomy term: Parent term)
* Enable "Require this relationship"
> 0 votes

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


# Question
Title: Can computed fields be added to a custom entity?
How can the "computed field" contrib module's (drupal7) fields be added to custom entities (based on the entity API module)?

Or will the computed field work with nodes only?

# Answer
> 0 votes
Yes, I found that entities can take computed fields.

A very easy way to achieve that, is by the 'data' module. It takes any extra database table. Can expose that table as an entity automatically. That entity can take normal fields, in addition to it's database table field. It does all the heavy lifting in place of entity API.

---
Tags: 7, entities
---


# Question
Title: Form storage is cleared after ajax submission
I am creating a form with "add more" functionality. Form builder retrieves values according to form built. keys are generated using uuid service. I also have to save them. So they are saved into form storage.

```
$form_state->get('links', $links)
...
$form_state->get('links')

```

On the next ajax submission storage is empty?! Also I use a block configuration form. So it uses sub-forms. May be the problem is related with. This is related problem. How to prevent SubFormState storage leaking into parent?

# Answer
> 0 votes
You say this is about building the form. If you display a form on a page, then this form is rendered, but the form object is not stored yet. This happens later when the form is submitted, then you can use $form\_state.

Generally when you build a form this is the same like rendering of non form content. Put the initial values in HTML (in the form elements). Similar to default values for visible fields use hidden fields for other values. You also have to add the correct cache metadata to the form so that the render cache varies by the data and is invalidated when the data is modified.

If you don't want to transport data in a rendered form then use a session or tempstore. This kind of storage is not restricted to form requests, so strictly not connected to this issue, but for logged in users these are easily available and for anonymous you can start a session, which you need to do anyway if you want to personalize a form.

---
Tags: forms, ajax
---


# Question
Title: View field with link to excecute action plugin
How can one add a field in views with a link to a custom Action plugin?

With bulk operations it's possible to create a checkbox to perform an action to a set of results. My actions have an access check that may be different per result so using the checkbox would result in a lot of warnings when the user tries to perform the action and doesn't have access.

I'd prefer to show the action as a link and only show the link when the user has access.

# Answer
> 0 votes
I'm thinking about setting up a route with a csrf token and an access check on a controller that manually performs the action:

```
my_module.my_action_callback:
  path: '/node/{node}/my_action_callback'
  defaults:
    _controller: '\Drupal\my_module\Controller\ActionController::my_action'
    _title: 'My action'
  requirements:
    _permission: 'perform my action'
    _csrf_token: 'TRUE'
    _custom_access: '\Drupal\my_module\Controller\ActionController::my_action_access'

```

In ActionController::my\_action I could perform the action programmatically:

```
\Drupal\system\Entity\Action::load('foo')->execute($data);

```

I had hoped there was a less complex and more elegant way using an existing view plugin.

---
Tags: views, 8, actions
---


# Question
Title: Where can I declare the compute field function?
Computed fields have a `computed_field_YOUR_FIELD_MACHINE_NAME_compute()` function to compute the field value.

In Drupal in which module I use this?

# Answer
> 0 votes
Any module can defined this function.

---
Tags: 8
---


# Question
Title: Custom block automatically adds code when edited in admin
I have written some HTML in custom block, but every time I open the editor in Drupal Admin UI some extra code is added to the block. Essentially, this means I have to remove the added code every time I want to edit the file which is becoming quite annoying. I am using Drupal 8 on the Acquia Cloud. Does anyone know what might be the cause of this?

**Edit 1:**

I'm using CKEditor

**My HTML goes from this**

```
 <div>
   <div>
     <nav>
       <a>
         <img src=""/>
         <p>Test</p>
       </a>
       <button>
         <div></div>
       </button>
       <div>
         <ul>
           <li><a>Sign In</a></li>
           <li><a>Sign up</a></li>
         </ul>
      </div>
    </nav>
  </div>
</div>

```

**To this**

```
<div>
  <div>
    <nav>
      <a><img alt="" data-entity-type="" data-entity-uuid="" src="" /> </a>
      <p><a>Test</a></p>
      <a></a>
      <button></button>

      <div> </div>
      <button></button>

      <div>
       <ul>
         <li><a>Sign In </a></li>
         <li><a>Sign up </a></li>
       </ul>
      </div>
    </nav>
  </div>
</div>

```

**Edit 2:** I'm also getting the following code added to a second block

```
<div class="menu-toggle-icon"> </div>
<button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarSupportedContent" data-toggle="collapse" type="button"></button>

```

# Answer
The `data-entity-type` & `data-entity-uuid` properties are added with WYSIWYG fields when you have the **Track images uploaded via a Text Editor** filter . This filter is designed to track usage of images as they are dropped into HTML body fields and update the fields accordingly when the image is updated.

To disable it, navigate to the **Text formats and editors** admin section and configure the format that's being used for your custom block. Untick the **Track images uploaded via a Text Editor** filter option and click the **Save configuration** button to disable the filter.
> 1 votes

---
Tags: 8, blocks, acquia-cloud
---


title: Module installation order

text:
# Question
Title: Module installation order
Within my custom module i've got an optional implementation to the dynamic entity reference module: https://www.drupal.org/project/dynamic\_entity\_reference

When the module exists, I add a DER field to one of my custom tables during the module installation.

The issue i am currently facing is that I can not manipulate the installation order of my module. Within the install hook of my module i am using `module_set_weight("mymodule",1)`. However this is not effecting the installation order at all when I run `drush config-import` order or `drush site-install --config-dir="/my/conf"`.

Within my `core.extensions.yml` the weight got applied after config export: `drupal_content_sync: 1`

# Answer
> 0 votes
For me this sounds pretty simple to solve. In your custom module just set a requirement:

```
name: Foo Bar
description: 'Lorem ipsum.'
package: Custom

type: module
core: '8.x'

dependencies:
  - dynamic_entity_reference:dynamic_entity_reference

```

By that you ensure that `dynamic_entity_reference` exists and is enabled when your module gets installed. That's it. Except I misunderstand you and you are instead looking for `hook_module_implements_alter` to change the order of modules calling a certain hook.

---
Tags: 8, installation
---


# Question
Title: How to use user wildcard in a custom path?
I set the path alias for User entity to *consultant/\[user:name\]*. I need to use *consultant/\[user:name\]/job* as route and I am using the following code for a `hook_menu()` implementation.

```
$items['user/%user/job'] = array(
  'title' => 'Apply for job',
  'page callback' => 'job_application_page',
  'access arguments' => array('access content'),
  'file' => 'job.pages.inc',
  'type' => MENU_CALLBACK,
);

```

The route should match, for a user whose username is Joan, the /consultant/joan/job path. That does not work and it returns a 404 error.

What should I correct in the code to make it work?

# Answer
> 3 votes
You've picked `user_load` as your wildcard's load function - that takes an ID, and loads a user object. Your requirement is to load by username, which will work differently.

A function ending with `_load` doesn't exist for that, so you'll have to create your own:

```
$items['user/%MYMODULE_user_name/job'] = array(
...

function MYMODULE_user_name_load($name) {
  return user_load_by_name($name);
}

```

---
Tags: 7, routes
---


# Question
Title: Custom code for after submitting a webform
**I have found this question here to fit my exact needs since the rules modules is not ready yet**

How to create a node out of a webform submission?

I am hardly a coder, can someone please explain where i should use place this code in my Drupal 8 website ?

**MY USE CASE:**

1) **Content type (xyz) with below fields:**

* field\_xyz\_id (default Title field)
* field\_xyz\_name *(Text Field)*
* field\_xyz\_telephone *(Telephone field)*
* field\_xyz\_category *(Taxonomy reference field)*
* field\_xyz\_company *(Group reference field)*
* field\_xyz\_user *(User reference field)*
* field\_xyz\_color *(Color field)*
* field\_xyz\_image *(multi value image field)*

2) **Webform (registerxyz) with below fields:**

* form\_registerxyz\_name *(Text Field)*
* form\_registerxyz\_telephone *(Telephone field)*
* form\_registerxyz\_category *(Taxonomy reference field)*
* form\_registerxyz\_company *(Group reference field)*
* form\_registerxyz\_user *(User reference field)*
* form\_registerxyz\_color *(Color field)*
* form\_registerxyz\_image *(multi value image field)*

When a registered user with role **manager** submit the webform **regisyer xyz**, a new node of type **xyz** will be created and the webform submission value to be transfered to the node's fields.

**Back in D7:** I used to use the **webform rules** to accomplish the above but until today both rules and webform rules are not ready yet

Any help in where i can place the above code in my drupal 8 website ?

I am open to any other suggestions (if any) to **create a node out of webform submissions !**

**UPDATE # 1:**

I have create a custom module (**my\_module\_name**) and inside `\my_module_name\src\Plugin\WebformHandler\ExampleWebformHandler.php` i have placed the below code:

```
<?php

namespace Drupal\my_module_name\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Create a new node entity from a webform submission.
 *
 * @WebformHandler(
 *   id = "Create a node",
 *   label = @Translation("Create a node"),
 *   category = @Translation("Entity Creation"),
 *   description = @Translation("Creates a new node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class ExampleWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
 // Create node object from webform-submission.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

  /** @var Node $node */
   $node = Node::create([
    // node type
        'type' => 'article',
    // mandatory fields
        'title' => $webform_submission->getData('subject'),
    // optional fields
        'body' => $webform_submission->getData('message'),
    ]);
    $node->save();

  }
}

```

I also under the **settings** of the default built-in **contact webform**, i have added the above handler.

Now, after i create a new Webform submission, the below errors appear in **the recent log messages section**:

**FIRST ERROR:**

```
Notice: Undefined variable: webformSubmission in Drupal\my_module_name\Plugin\WebformHandler\ExampleWebformHandler->submitForm() (line 45 of S:\Setup Ideas Sites\drupal8\modules\Custom\my_module_name\src\Plugin\WebformHandler\ExampleWebformHandler.php) #0 S:\Setup Ideas Sites\drupal8\core\includes\bootstrap.inc(582): _drupal_error_handler_real(8, 'Undefined varia...', 'S:\\Setup Ideas ...', 45, Array) #1 S:\Setup Ideas Sites\drupal8\modules\Custom\my_module_name\src\Plugin\WebformHandler\ExampleWebformHandler.php(45): _drupal_error_handler(8, 'Undefined varia...', 'S:\\Setup Ideas ...', 45, Array) #2 S:\Setup Ideas Sites\drupal8\modules\Contrib\webform-8.x-5.x-dev\webform\src\Entity\Webform.php(2250): Drupal\my_module_name\Plugin\WebformHandler\ExampleWebformHandler->submitForm(Array, Object(Drupal\Core\Form\FormState), Object(Drupal\webform\Entity\WebformSubmission)) #3 S:\Setup Ideas Sites\drupal8\modules\Contrib\webform-8.x-5.x-dev\webform\src\WebformSubmissionForm.php(1441): Drupal\webform\Entity\Webform->invokeHandlers('submitForm', Array, Object(Drupal\Core\Form\FormState), Object(Drupal\webform\Entity\WebformSubmission)) #4 [internal function]: Drupal\webform\WebformSubmissionForm->submitForm(Array, Object(Drupal\Core\Form\FormState)) #5 S:\Setup Ideas Sites\drupal8\core\lib\Drupal\Core\Form\FormSubmitter.php(111): call_user_func_array(Array, Array) #6...

```

**SECOND ERROR:**

```
Error: Call to a member function getData() on null in Drupal\my_module_name\Plugin\WebformHandler\ExampleWebformHandler->submitForm() (line 45 of S:\Setup Ideas Sites\drupal8\modules\Custom\my_module_name\src\Plugin\WebformHandler\ExampleWebformHandler.php) #0 S:\Setup Ideas Sites\drupal8\modules\Contrib\webform-8.x-5.x-dev\webform\src\Entity\Webform.php(2250): Drupal\my_module_name\Plugin\WebformHandler\ExampleWebformHandler->submitForm(Array, Object(Drupal\Core\Form\FormState), Object(Drupal\webform\Entity\WebformSubmission)) #1 S:\Setup Ideas Sites\drupal8\modules\Contrib\webform-8.x-5.x-dev\webform\src\WebformSubmissionForm.php(1441): Drupal\webform\Entity\Webform->invokeHandlers('submitForm', Array, Object(Drupal\Core\Form\FormState), Object(Drupal\webform\Entity\WebformSubmission)) #2 [internal function]: Drupal\webform\WebformSubmissionForm->submitForm(Array, Object(Drupal\Core\Form\FormState)) #3 S:\Setup Ideas Sites\drupal8\core\lib\Drupal\Core\Form\FormSubmitter.php(111): call_user_func_array(Array, Array) #4...

```

Any help please ? look like i have to define some variables to hold the webform submissions !??

**UPDATE #2**

After fixing the **S** in the above code, and trying again to submit the **contact** webform, two new errors are now displayed:

Error Nbr1:

Error Nbr 2:

Your help is much appreciated, thank you

# Answer
As that link suggests, you can solve this problem by creating your own custom (webform submission) handler. So create a custom module (the easiest way is probably to use the drupal console and run `drupal generate:module` in a terminal from your website's root folder). Besides all the necessary files for your module (like \*.info.yml etc.) create a file named `your-module-name/src/Plugin/WebformHandler/CustomWebformHandler.php`. This is where your put all your logic of reading the webform submitted fields and saving them as a node.

As an additional help see this link for an example of how to create a user after a webform submission (the function createUser() is where the node-creation logic is in this example).

**Update** To create your content type just write your logic similar to this code-draft and read more about custom webformhandlers.

```
class CustomWebformHandler extends WebformHandlerBase {
  ...
  // Create node object from webform-submission.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Before you actually save the node, make sure you get what you
    // want. So at first comment the line further down with
    // $node->save(), run the debug code, check the output and then
    // uncomment the $node->save() and delete the debug foreach loop.
    // You can use whatever debug method you prefer, this is just a
    // simple one-time example.
     foreach($values as $key=>$value) {
       drupal_set_message($key . ' -> ' . $value);
     }

    // This is the node creating/saving part.
    $node = Node::create([
      'type'        => 'type-of-your-content',
      'field_xyz_name' => $values['name'],
      'field_xyz_telephone' => $values['telephone'],
      ....
    ]);
    // Before you un-comment this line, make sure you get all the
    // values you need from the webform data (in the foreach loop).
    //$node->save();
  }
}

```

Clear your cache.

Then in your webform's settings-general (UI) check "Disable saving of submissions".

Then under settings-email/handlers add your CustomWebformHandler as a new submission handler.

These are the basic steps that should help you move on.
> 1 votes

---
Tags: 8, nodes, webforms
---


# Question
Title: How to edit webform's email field default error message?
How to edit webform,s email field default error message ? My case is: I have to place error message just below the email field for this purpose i have used inline error message module and client side validation ,these modules worked well for me .

But the problem is that webforms default error message of email field commimg below the email text (say: your email address is not valide) but i dont want this default error message .suppose i want to print error message (say: you must provide a valid email address) for this i have created a custom validation function but after creating custom validation fuction my error message showing above the text box not below the textbox only default error message showing below the email field by using inline error message module that is not my requirement.

If i change the default error message(say: your email address is not valid) to (say: you must provide a valid email address) i can acheive the desired task

But how to achieve?

# Answer
> 1 votes
String Overrides module may be an alternative.

> Provides a quick and easy way to replace any text on the site.

# Answer
> 0 votes
Webform Required message This module will provide you with an interface so you can custom error messages for required fields.

---
Tags: 7, webforms
---


# Question
Title: Is it possible to change the "add new comment" text on certain content types?
Is it possible to change the "add new comment" text on certain content types? Also is it possible to only allow certain roles to post comments on this content type?

# Answer
> 5 votes
Check the roles/permission grid to restrict certain roles posting comments.

hook\_node\_view\_alter(&$build) would help to replace the label with your custom one.

e.g.

```
 function MODULE_node_view_alter(&$build){
    if ( in_array($build['#node']->type, array('page')) )
    $build['links']['comment']['#links']['comment-add']['title'] = l('New Label', 'comment/reply/'. $build['#node']->nid);

```

There can be another easy way using String Overrides but it will not let you do on specific content types.

# Answer
> 1 votes
Node.tpl.php has this "$content\['links'\]\['comment'\]\['#links'\]\['comment-add'\]" in the code. Maybe take closer look at that array with dpm (devel module) or just print\_r, to see if you can alter this or just alter the final markup for that link. Here you have list of variables you can use when you override node.tpl.php: http://api.drupal.org/api/drupal/modules!node!node.tpl.php/7

You can use one node.tpl.php or keep different node.tpl.php files for different content types - check out the naming convention (something like node--content-type.tpl.php)

# Answer
> 1 votes
You can easily do this by editing the comment-wrapper.tpl template just copy this template from the core comment module and paste it in your theme. You will find the below code in the template. For roles based comment you can add logic to your node template.

```

print t('Add new comment');

```

# Answer
> 0 votes
For the label part, possibly simplest to override the template in your theme.

In Drupal 8, it uses `field--comment.html`

You can name it by content type, e.g.

```
field--node--field-comments--foo.html.twig

```

Enable Twig debugging to get all the possible filenames.

---
Tags: comments
---


title: Placing the Rocket Chat block on a page

text:
# Question
Title: Placing the Rocket Chat block on a page
I'm trying to include a Drupal 8 Rocket Chat plugin module in my website. I installed the plugin module, set up a chat server, but I'm failing, of all places, at actually placing the block on a page (/chat). How do I do that? I'm completely new to Drupal.

# Answer
> 1 votes
> * **install the livechat module** and rocket\_chat module.
> * Setup the rocket\_chat module.
> * Go to \[Structure\]\[Block layout\]. there you can place the livechat block using the "Place block" button. This works as a normal block we recommend you add it to a footer or alike for performance.

<sub>**Source:** Rocket chat module README.md</sub>

In other words, go to `/admin/structure/block` find the Footer region and click on `Place block` search for "RocketChat Livechat" and click `Place block`.

# Answer
> 0 votes
You seem to want the block on a specific page rather than all pages, so to build on No Sssweat's answer:

---
Tags: 8, blocks
---


# Question
Title: How to create a raw link in view(with contexual filter) custom text
I am creating a block in view. I have a content type with a field(plain text). I am passing contexual filter "content id" from url.

I am giving value in the fields as "www.facebook.com/SomePage" Now i want that to be created as link text from custom text in views.

In custom text i am providing

```
    <a href="{{ field_abc }}" target="_blank">Click Here</a>

```

Now when i click here it is redirecting me to "\[sitename\]/node/www.facebook.com/SomePage"

I want to open like www.facebook.com/SomePage.

How to do. Any suggestion?

# Answer
I'd rather add a 'Custom text' field to the view, give it some text ("Click here"), and under "Rewrite Results" check "Output this field as a custom link", link path is `{{ field_abc }}` and then check "External server URL"
> 1 votes

---
Tags: views
---


# Question
Title: How to stop using Hindi number in Arabic translation of products
When using English version of website, price is shown in Arabic number (common one). But when using Arabic version of website, price is shown in Hindi number.

I don't want price to be shown in Hindi Numbers.

English view of products (Arabic Numbers)

Arabic view of products (Hindi Numbers)

How to force using Arabic Numbers in both versions.

# Answer
> 1 votes
Subscribe to the NumberFormatDefinitionEvent ("commerce\_price.number\_format") and change $definition\['numbering\_system'\] to 'latn' for your locale.

# Answer
> 0 votes
I think your theme use this font, you must change font used in price, for test, use inspect element in chrome browser and change font and see result.

---
Tags: commerce, i18n-l10n
---


title: How does Drupal 7 Load its Modules

text:
# Question
Title: How does Drupal 7 Load its Modules
I'm debugging a Drupal 7 system I didn't setup, and I'm trying to understand how Drupal loads its modules.

This system appears to have modules nested within one other -- here's one example.

```
modules/custom/modulename/modulename.info
modules/custom/modulename/modulename.install
modules/custom/modulename/modulename.module
modules/custom/modulename/modulename_statistics/modulename_statistics.drush.inc
modules/custom/modulename/modulename_statistics/modulename_statistics.inc
modules/custom/modulename/modulename_statistics/modulename_statistics.info
modules/custom/modulename/modulename_statistics/modulename_statistics.module

```

It appears there's one module named `modulename`, and inside this module there's another named `modulename_staticstics`.

Is this a "legal/normal" setup? Does nesting one module within another confer any special features between the two modules? Where in the drupal source code are modules searched for/loaded? Is there any canonical piece of documentation that covers how module loading works? (my googling didn't turn up a lot)

(experienced software engineer here, but only passingly familiar with Drupal)

# Answer
> Is this a "legal/normal" setup?

It's perfectly legal, and yes it's normal for modules that need or want to break their functionality down that way.

> Does nesting one module within another confer any special features between the two modules?

No, they’re just standard modules.

> Where in the drupal source code are modules searched for/loaded?

I think this is pretty much exhaustive for Drupal 7:

* /modules/\**
* /profiles/\*/modules/\**
* /sites/\*/modules/\**

> Is there any canonical piece of documentation that covers how module loading works?

I wouldn't have thought so - following the code is probably the best way to understand how it works. Core is pretty well commented.
> 2 votes

---
Tags: 7
---


# Question
Title: Change the order of product variations on the "add to cart" form
I have a product type with three variations (to make this simple, let's assume it's a t-shirt store):

* Color
* Size
* Team

On the "Add to Cart" form (configured at /admin/commerce/config/order-item-types/default/edit/form-display/add\_to\_cart), I have **Purchased entity** set to **Product variation attributes**.

This displays three dropdown menus that let me select the values for Color, Size, and Team.

How do I change the display order of these menus (for example: change the order to Team, Color, Size)?

Drupal 8/Commerce 2

# Answer
Similar to Drupal 7, Drupal Commerce for Drupal 8 respects the ordering of attribute fields on the product variation form when rendering them into the Add to Cart form. To find these options, you'll need to navigate to **Administration \> Commerce \> Configuration \> Product variation types** and select the *Manage form display* option from the Operations dropdown for the variation type in question. Reorder the fields there, and they'll appear in the new order on the Add to Cart form.
> 2 votes

---
Tags: 8, commerce
---


# Question
Title: Copy data from a selected view in a fieldcollection field
I have content\_type TYPE1 content with two fields:

* **fiedl\_1** is a viewfield type that allows me to display a view inside a node.
* **fiedl\_2** is fieldcollection type.

Is it possible to copy the rows resulting from the view into my fielcollection?

Thanks a lot

# Answer
> 0 votes
Yes, it's possible but you're going to have to do some hoop jumping to make it happen:

* Determine *when* this copy action will happen (e.g. `hook_entity_update` trigger).
* Programmatically retrieve the View's data (e.g. via `Views::getView()` / `views_get_view()` depending on your Drupal version)
* Parse the view data an update the update relevant node fields with the view data. (which will also depend on your Drupal version).

---
Tags: views, entities
---


# Question
Title: Customize the HTML of a link field from a custom theme
I've a *Link* field named `field_home_link`, attached to a *Content Type* named `Home`, and I'm trying to customize how it is rendered as HTML from inside a custom theme.

Instead of the default generated HTML:

```
<a tabindex="0" href="http://example.com">Link text</a>

```

I need to render this HTML, adding custom CSS classes on it:

```
<a href="http://example.com" class="btn-circle btn-circle--blue js-open-modal">
  Link text
</a>

```

But I would like to have **most flexibility as possible** on the rendered HTML, not only adding classes. For example I might need to add other attributes on the tag `<a>` or maybe also change the tag `<a>` with something else.

Would be enough having access to the link's properties (url and text) and arrange them in some custom HTML code.

How can I do this?

---

I tried to create a template for the link field:

```
field--field-home-link.html.twig

```

but inside this template I don't know how to access link's elements (url and text) and I'm stuck with this:

```
{% for item in items %}
  <!-- item.content contains the link element -->
  {{ item.content }}
{% endfor %}

```

Is there no way to do something like this?:

```
{% for item in items %}
  <a href="{{ item.content.url }}" class="btn-circle btn-circle--blue js-open-modal">
    {{ item.content.text }}
  </a>
{% endfor %}

```

# Answer
Try this:

```
{% for item in items %}
  <a href="{{ item.content['#url'] }}" class="btn-circle btn-circle--blue js-open-modal">
    {{ item.content.text }}
  </a>
{% endfor %}

```

Found it in a video from 2015, where MortenDK is showing off It's about 25 min. in

DrupalCon Los Angeles 2015: Drupal 8 Theming with Love
> 3 votes

# Answer
Spent 2 days on this similar problem. Sebastian, you almost had it. Twig snippet should look more like this:

```
{% for item in items %}
  <a href="{{ item.content['#url'] }}" class="btn-circle btn-circle--blue js-open-modal">
    {{ item.content.['#title'] }}
  </a>
{% endfor %}

```

`['#title']` \- is really important to place the text in the a href tag

Definitely MortenDK was very helpful: https://www.youtube.com/watch?v=bvaz9eb54c4
> 3 votes

# Answer
If you're using views (as I understood as you mentioned the machine name `field_home_link`, you can simply hide the link field by ticking the checkbox saying *Exclude from display* in view.

Below you will see replacement patterns and overwrite option where you can write your snippet-

```
<a href="http://example.com" class="btn-circle btn-circle--blue js-open-modal">
  Link text
</a>

```

save your view, it's done.
> 1 votes

# Answer
I have tested for both external and internal URL by using like below, it's working as desired.

```
<a href="{{ content.field_my_link[0]['#url'] }}" class="button buy-now-btn">{{ content.field_my_link[0]['#title'] }}</a>

```
> 1 votes

---
Tags: theming, 8, navigation
---


# Question
Title: How duplicate order automatically with commerce 2
How do I automatically duplicate an order? I use Drupal 8 and Drupal Commerce 2. I need to duplicate some orders, each week, automatically.

Orders have a Boolean field (recurrent\_order). When the field is filled, the web site has to create the same order at the end of the week.

I have achieved this with rules and VBO on Drupal 7: On maintenance task, a rule finds an array filled by a VBO view, and a component duplicates the content.

In Drupal 8 there isn't VBO view access from a rule.

How can I achieve this? Regards,

# Answer
Here is the code for duplicate order with a cron job:

```
function commande_et_paiement_cron() {
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'abonnement');
$query->condition('field_livraison', 3);//livraison le vendredi
$entity_ids = $query->execute();

foreach ($entity_ids as $entity_id) {
$abo = Node::load($entity_id);

//utilisateur
$user = $abo->get('field_utilisateur')->getValue()[0]['target_id'];
$utilisateur = \Drupal\user\Entity\User::load($user);

//profile
$entity_manager = \Drupal::entityTypeManager();
$profile = $entity_manager->getStorage('profile')->load($user);

//abonnement
$nid= $abo->id();

//livraison
$date_livraison = new DateTime();
$date_livraison->modify('next friday');

//ligne de commande
$line_items = array();
$abo_array= $abo->get('field_abo_produits')->getValue();

foreach ($abo_array as $abo_item) {
    $ligne = $abo_item['target_id'];
    //load produit abonnement
    $item = \Drupal\commerce_order\Entity\OrderItem::load($ligne);
    $quantite = $item->getQuantity();
    $produit = $item->getPurchasedEntity();

    $order_item = \Drupal\commerce_order\Entity\OrderItem::create([
    'type' => 'default',
    'purchased_entity' => $produit,
    'quantity' => $quantite,
    //'unit_price' => $role_price,
    ]);

    $order_item->save();
    array_push($line_items,$order_item);
    }

//creation de la commande
$order = \Drupal\commerce_order\Entity\Order::create([
      'type' => 'default',
      'store_id' => 1,
      'checkout_flow' => 'boulangerie',
      'uid' => $user,
      'billing_profile' =>$profile,
      'field_abonnement' => $nid,
      'placed' => time(),
      'field_date_livraison' =>$date_livraison->format('Y-m-d'),
      'order_items' =>$line_items,
      'state' => 'draft'
    //'completed' => time(),

    ]);
    $order->save();
    $order->set('order_number', $order->id());
    $order->save();
    $order->set('state', 'complete');
    /*$comment = 'blabla';
     $logStorage = \Drupal::entityTypeManager()->getStorage('commerce_log');
    $logStorage->generate($order, 'order_comment', ['comment' => $comment])->save();      */
    $order->save();
   }
}

```
> 0 votes

---
Tags: commerce, rules, views
---


# Question
Title: Using Mysql LOAD DATA LOCAL INFILE with drush
I want to able to load a huge CSV file directly into the database using LOAD DATA LOCAL INFILE like below:

`LOAD DATA LOCAL INFILE 'Subscriber.csv' INTO TABLE temp_data FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'IGNORE 1 ROWS`

If I enter into the mysql via command line using `drush sql-cli` and run the command above I get;

`ERROR 1148 (42000): The used command is not allowed with this MariaDB version`

After some research I found out that if you access mysql via the command line using the `--local-infile` flag, I can be able to use the LOAD DATA LOCAL. Below will be the statement that I use to get into mysql :

`mysql --local-infile -u root -p -h mysql`

Using the command above will make it possible for me to use LOAD DATA in mysql but i want to be able to use it with `drush sql-query`. How can I apply the `--local-infile` flag.

# Answer
`drush sql-query` has a not-very-well documented option flag called `--extra`. This flag is used when connecting via the `mysql` command to add extra options to the command string. So a `drush sql-query --extra '--local-infile'` should enable Drush to connect the client with your needed option.
> 2 votes

---
Tags: 8, database
---


# Question
Title: How do I run queries against a view configuration
Where is all the config for Views stored? I am working on a Drupal site with a very large number of Views. What's the easiest way to find *"All the Views which have a Relation of a certain type"*, or *"All the Views which output a specific field?"*

It would be nice to do this with some SQL but I'm stumped as to how.

# Answer
It's stored in the `views_display` table, as a serialised PHP string. So unfortunately direct querying isn't really feasible.

The best approach is to load each View object in turn (in PHP), and apply your filter logic there.

The `views_ui_field_list()` function is a good example of what's required. Incidentally that's the callback for a page that already exists in the admin which should help you find *All the Views which output a specific field*. It's at /admin/reports/fields/views-fields.
> 0 votes

# Answer
Just expanding a bit on @Clive's answer. Load all views, iterate through them and check what you need.

Views has a function that will help, `views_get_all_views()`, https://cgit.drupalcode.org/views/tree/views.module#n1536

From there, you can go through them and get what you need.

Basically,

`$views_list = views_get_all_views();
 foreach ($views_list as $view) {
 //Logic operating on the $view object
 }`

This will probably be useful as well, https://api.drupal.org/api/views/includes!view.inc/class/view/7.x-3.x
> 1 votes

---
Tags: 7, views
---


title: HTML markup is removed from email

text:
# Question
Title: HTML markup is removed from email
I am trying to send an email with a small html form of hidden fields and a submit button. I have been piecing this together from several very incomplete answers and documentation sources that take several approaches to this but no answer so far has worked for me (so please do not mark this as a duplicate).

I have a module, my\_module, and in the my\_module.module file I have the following hook.

```
function ten_sixteen_mail($key, &$message, $params) {
    if (isset($params['subject'])) {
        $message['subject'] = $params['subject'];
    }
    if (isset($params['body'])) {
        $message['body'][] = $params['body'];
    }
    if (isset($params['headers']) && is_array($params['headers'])) {
        $message['headers'] += $params['headers'];
    }
}

```

Elsewhere in my\_module.module I send an email with the following code. I am getting the email, but without the form and button html, only the

text.

```
$to = "someone@example.com";
$subject = "This is an email subject";
$body = "<p>Here is some text.</p>";
$body .= '<form name="someform" action="https://www.example.com/somepage" method="post">';
$body .= '<input type="hidden" name="somecode" value="' . $somecode . '" />';
$body .= '<input type="hidden" name="something" value="' . $something . '" />';
$body .= '<input type="submit" style="padding: 10px; background-color: #d42c2c; border: 2px solid #cccccc;" value="Click This" />';
$body .= '</form>';
$params = array(
    'headers' => 'Content-type: text/html',
    'subject' => $subject,
    'body' => $body,
);

$message = drupal_mail("my_module", "my_module", $to, language_default(), $params, "serviceaccount@example.com");

```

I have Mail System and Mime Mail installed and enabled.

I'm pretty confused about the config options for both modules. For Mail System I have set the 'theme to render the emails' to my custom theme, though I really don't require any theme-ing of the email it was not an option to disable this.

I have created a new module and key setting with the key my\_module for the module my\_module.

Mime Mail is set to use the Full HTML Email format.

What am I doing wrong that is preventing my html form from coming through in the email?

# Answer
> 0 votes
The hook\_mail headers need to be like this:

```
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';

```

---
Tags: 7, mimemail
---


# Question
Title: Custom module to act on module configuration change
I'm working on a custom module to change the administrative menu structure. A few extra menu items are added; for some of them, I want to be able the change the name via a configuration page of the module.

This might sound like a lot of work for creating a few menu items, and it might be, but I hope it will save me some time in the future when setting up the site for my clients.

I think it is a good way to learn how to create custom modules with configuration pages (I only created modules without configuration pages) till now.

I have a custom module in the `modules/custom/svds_adminmenu` folder. Structure inside this folder is:

* src
    + Form
        - ModuleConfigurationPage.php
* svds\_adminmenu.info.yml
* svds\_adminmenu.module
* svds\_adminmenu.routing.yml

This is what I have at this moment:

**ModuleConfigurationPage.php**

```
namespace Drupal\svds_adminmenu\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Defines a form that configures forms module settings.
 */
class ModuleConfigurationForm extends ConfigFormBase {

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

    /**
     * {@inheritdoc}
     */
    protected function getEditableConfigNames() {
        return [
            'svds_adminmenu.settings',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $config = $this->config('svds_adminmenu.settings');
        $form['link_title'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Link Title'),
            '#default_value' => $config->get('link_title'),
        ];
        $form['link_path'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Link Path'),
            '#default_value' => $config->get('link_path'),
        ];
        return parent::buildForm($form, $form_state);
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        $values = $form_state->getValues();
        $this->config('svds_adminmenu.settings')
            ->set('link_title', $values['link_title'])
            ->set('link_path', $values['link_path'])
            ->save();
        parent::submitForm($form, $form_state);
    }
}

```

**svds\_adminmenu.info.yml**

```
name: Change Admin Menu
description: 'Change Admin Menu'
type: module
package: SVDS
core: 8.x
configure: svds_adminmenu.admin_settings

```

**svds\_adminmenu.module**
*I first created the module so it creates the menu items on install, now I want to change it to create/edit on configuration page save. So I don't want to use the hook\_install anymore.*

```
use Drupal\menu_link_content\Entity\MenuLinkContent;

function svds_adminmenu_install() /*don't want to use this hook anymore*/
{
    $menu_main = 'administration';

    $content_overview = MenuLinkContent::create([
        'title' => 'Content Overview',
        'link' => ['uri' => 'internal:/admin/content'],
        'menu_name' => $menu_main,
        'expanded' => FALSE,
        'parent' => 'system.admin_content',
        'weight' => -10,
        'id' => 1000,
    ]);

    $content_overview->save();

    $content_edit = MenuLinkContent::create([
        'title' => 'Edit Content',
        'link' => ['uri' => 'internal:/admin/content'],
        'menu_name' => $menu_main,
        'expanded' => TRUE,
        'parent' => 'system.admin_content',
        'weight' => 1,
        'id' => 1001,
    ]);

    $content_edit->save();

    $content_edit_sub = MenuLinkContent::create([
        'title' => /* CONFIG LINK TITLE HERE */,
        'link' => ['uri' => /* CONFIG LINK PATH HERE */],
        'menu_name' => $menu_main,
        'expanded' => TRUE,
        'parent' => 1002,
        'weight' => 0,
    ]);

    $content_edit_sub->save();
}

function svds_adminmenu_uninstall(){
    $menu_link = MenuLinkContent::load(1000);
    $menu_link->delete();
    $menu_link = MenuLinkContent::load(1001);
    $menu_link->delete();
    $menu_link = MenuLinkContent::load(1002);
    $menu_link->delete();
}

```

**svds\_adminmenu.routing.yml**

```
svds_adminmenu.admin_settings:
  path: '/admin/config/svds/admin_menu'
  defaults:
    _form: '\Drupal\svds_adminmenu\Form\ModuleConfigurationForm'
    _title: 'SVDS Admin Menu Configuration'
  requirements:
    _permission: 'administer site configuration'

```

So I know how to programmatically create menu items, and I have a configuration page. Now I have to connect the two things together: When the configuration is changed, the module should run again to change the menu.

I found this to fetch the configuration data.

```
$variables['var'] = \Drupal::config('my_module.settings')->get('var');

```

I have to trigger my action via some kind of hook, and I don't know which one. It should only trigger once after the configuration is changed, not on a preprocess function, or something similar.

So how can I do this?

# Answer
So as Clive said I don't need a hook and .module file to do this. This is what I did.

I copied the code from my .module file to the ModuleConfigurationPage.php and put it inside the submitForm function:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
    $menu_main = 'administration';
    //catch values from the form
    $linkTitle = ($form['settings']['main']['link_title']['#value']);
    $linkPath = ($form['settings']['main']['link_path']['#value']);

    //delete dynamically created menu items
    for($i = 1000; $i <= 1002; $i++){
        $menu_link = MenuLinkContent::load($i);
        if($menu_link) {
            $menu_link->delete();
        }
    }

    //create content overview link in content dropdown
    $content_overview = MenuLinkContent::create([
        'title' => 'Content Overview',
        'link' => ['uri' => 'internal:/admin/content'],
        'menu_name' => $menu_main,
        'expanded' => FALSE,
        'parent' => 'system.admin_content',
        'weight' => -10,
        'id' => 1000,
    ]);

    $content_overview->save();

    //create content edit content link in content dropdown
    $content_edit = MenuLinkContent::create([
        'title' => 'Edit Content',
        'link' => ['uri' => 'internal:/admin/content'],
        'menu_name' => $menu_main,
        'expanded' => TRUE,
        'parent' => 'system.admin_content',
        'weight' => 1,
        'id' => 1001,
    ]);

    $content_edit->save();

    //create menu item with config settings
    $content_edit_sub = MenuLinkContent::create([
        'title' => $linkTitle,
            'link' => ['uri' => 'internal:'.$linkPath],
            'menu_name' => $menu_main,
            'expanded' => TRUE,
            'parent' => 1002,
            'weight' => 0,
     ]);

    $content_edit_sub->save();

    //set new config values
    $this->config('svds_adminmenu.settings')
        ->set('link_title', $linkTitle)
        ->set('link_path', $linkPath)
        ->save();

    //refresh menu cache to see changes
    $renderCache = \Drupal::service('cache.menu');
    $renderCache->invalidateAll();

    //submit form
    parent::submitForm($form, $form_state);
}

```

This way the menu gets updated each time you click the submit button.
> 0 votes

---
Tags: 8, hooks, navigation
---


# Question
Title: How to change Stars in Webform-star module?
I have just implemented the Fivestar option in one of the evaluation form created by webform, I used the Fivestar module and Webform-fivestar module. But now I want to change the stars with different layout or design. In some of the article i read that we can change in manage display tab of the contentype but that option is not applicable for webform components. So that changing option is not available in the webform configurations. So please help me how to achieve this.

# Answer
The webform-fivestar module currently doesn't have the option to select which star widget to use, however there is a patch you can apply at https://www.drupal.org/project/webform\_fivestar/issues/2071161

There is information regarding how to apply patches at https://www.drupal.org/patch/apply

You can then select the widget per component, when editing the component, in the display settings (see screenshot).
> 1 votes

---
Tags: 7, webforms, rating
---


# Question
Title: How to use Drupal 8 ajax API for Menu links
I have a taxonomy menu on the left side of the screen. When I select a menu item I want the results to appear in the main content area of the screen.

I want this to happen using AJAX. I have been reading the AJAX API documentation from Drupal: https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.4.x

It says I can add a "use-ajax" class to the link, which I have. But then there is no documentation regarding how to get the link to load in a target ID.

# Answer
> 1 votes
You can try this for adding 'use-ajax' class to menu link:

```
/**
 * Implements hook_menu_links_discovered_alter().
 */
function MYMODULE_menu_links_discovered_alter(&$links) {
  if (isset($links['MENU_LINK_ID'])) {
    $links['MENU_LINK_ID']['options']['attributes']['class'][] = 'use-ajax';
    $links['MENU_LINK_ID']['options']['attributes']['data-dialog-type'] = 'modal';
  }
}

```

---
Tags: ajax
---


# Question
Title: Drush 9 - Destination Argument Does Not Exist
I've been struggling a lot with Drush 9 sql:sync the past few months. I've gotten it to work a few times, but I've been stumped by this most recent problem:

`$ drush sql:sync @prodv2 @local --debug
Using the Drush script found at /Applications/MAMP/htdocs/ianmoffitt/vendor/drush/drush/drush using proc_open
 [preflight] Config paths: /Applications/MAMP/htdocs/ianmoffitt/vendor/drush/drush/drush.yml,/Applications/MAMP/htdocs/ianmoffitt/drush/drush.yml
 [preflight] Alias paths: /Applications/MAMP/htdocs/ianmoffitt/web/drush/sites,/Applications/MAMP/htdocs/ianmoffitt/drush/sites
 [preflight] Commandfile search paths: /Applications/MAMP/htdocs/ianmoffitt/vendor/drush/drush/src,/Applications/MAMP/htdocs/ianmoffitt/drush
 [bootstrap] Bootstrap to none [0.13 sec, 8.14 MB]
 [bootstrap] Drush bootstrap phase 0 [0.13 sec, 8.14 MB]
 [bootstrap] Try to validate bootstrap phase 0 [0.13 sec, 8.14 MB]
 [error] The "destination" argument does not exist. [0.13 sec, 8.19 MB]`

Can't find anything online towards this specific error message. Not sure what I'm missing or what to even check.

Again, this command worked about a week or so ago. All I've done since then is run composer update. Did something change recently?

Using Drush 9.3.0.

# Answer
Definitely a problem with Drush 9.3.0, revert back to Drush 9.2.3 with `composer require drush/drush:9.2.3` fixed it for me
> 0 votes

# Answer
Just for the record - in my case, given "destination" argument was coming from an outdated custom Policy command I got when I was setting up the project - https://github.com/drupal-composer/drupal-project/blob/8.x/drush/Commands/PolicyCommands.php

It should be "target" instead and the current state of https://github.com/drupal-composer/drupal-project reflects that change.
> 2 votes

---
Tags: database, drush
---


# Question
Title: How to find operation type in validating form?
I have created a custom validate function for **specific node form**.

But validate rules are **different** between edit a current node or add a new node modes.

Now, I want to know, is there any way that we understand whether we are in **edit mode or create mode** in form\_validate function ?

# Answer
> 3 votes
A new node will not have a node ID.

So you can check the form values or the original form for that to determine whether it is a new node or not.

For example:

```
if (empty($form_state['values']['nid'])) {
  // This is a new node.
}
else {
  // This is an existing node.
}

```

# Answer
> 2 votes
Rooby solution is good, but I usually check the presence of "nid" property in $form\['#node'\]

```
function my_module_form_validate_func(&$form, &$form_state) {
  if (!isset($form['#node']->nid)) {
    //new node
  }
  else {
    //existing node
  }
}

```

---
Tags: 7, forms
---


title: Alter the user registration form

text:
# Question
Title: Alter the user registration form
I'm trying to change the label and field instructions for the name field on the User Account Creation form. I'm new to coding, and thought this would be an easy task.

My custom module is enabled and I've cleared caches, but none of my changes show up. Here is my code. I've tried a bunch of variations and a bunch of searching, but I never see a single sign of this working.

```
<?php

/**
 * @file
 * Contains mymodule.module.
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter() on behalf of mymodule.module.
 * @see \Array method Array at Array
 */
function mymodule_form_account_alter(&$form, FormStateInterface $form_state, $form_id) {
  // print_r($form); die;
  // ksm($form_id);
  if ($form_id == 'user_register_form') {
    // print_r($form); die;
    // kint($form_id);
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('First and last name'),
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#description' => $this->t("Rewrite this about spaces, periods (.), hyphens (-) and apostrophes (')."),
    );
  }
  drupal_set_message('mymodule_form_account_alter() executed.');
}

```

# Answer
> 8 votes
This is the right code.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['account']['name']['#title'] = t('First and last name');
  $form['account']['name']['#description'] = t("Rewrite this about spaces, periods (.), hyphens (-) and apostrophes (').");
}

```

# Answer
> 3 votes
The reason you aren't seeing any change in the user registration form is that the `hook_form_FORM_ID_alter()` implementation for the *user\_register\_form* form has the wrong name: Instead of `mymodule_form_account_alter(&$form, FormStateInterface $form_state, $form_id)` (which supposes it is defined from a module whose machine name is *mymodule*), it should be `mymodule_form_user_registration_form_alter(&$form, FormStateInterface $form_state, $form_id)`. Alternatively, you could implement `hook_form_alter()` with the `mymodule_form_alter()` function. In this case, checking the form ID would be correct, as the hook would be invoked for each form used by Drupal.

Fixed the hook name, there are still errors in the code you are showing.

1. Inside a function `$this` doesn't have any value/meaning. Only a class method that isn't static can use `$this`.
2. A line like `if ($form_id == 'user_register_form')` is not necessary for `mymodule_form_user_registration_form_alter()`, since that hook is invoked for that form, and not any form a Drupal module is using.
3. If you need to change some of the properties of a form element, you don't use `$form['name'] = array( /* .... */);` which is removing all the properties of that form element and adding **only** the ones you add to the array.
4. The form field for the username, used in the account registration form, is `$form['account']['name']`, not `$form['name']`.

The correct code would be similar to the following one.

```
function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['account']['name']['#title'] = new TranslatableMarkup('First and last name');
  $form['account']['name']['#description'] = new TranslatableMarkup("Rewrite this about spaces, periods (.), hyphens (-) and apostrophes (').");
}

```

Notice that:

* While `$form_id` is one of the parameters passed to the hook, you don't need it to understand for which form the hook is invoked. Actually, I cannot think of any reason for `hook_form_FORM_ID_alter()` to use that parameter, except in the case the form ID must be concatenated to another string. (In that case, I would use `$form_id . 'another string'`.) This means the last hook parameter can also be omitted, since the code isn't using it.

```
function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  $form['account']['name']['#title'] = new TranslatableMarkup('First and last name');
  $form['account']['name']['#description'] = new TranslatableMarkup("Rewrite this about spaces, periods (.), hyphens (-) and apostrophes (').");
}

```
* I used the `TranslatableMarkup` class to output a translated string, which is Drupal 8 suggested class to use in this case, but you could use `t()` which is a function Drupal 9 still implements.
* If you are testing when a hook is invoked, don't use `drupal_set_message()` (which is also a deprecated function). Use the Drupal logger, for example with a line like `\Drupal::logger('mymodule')->notice('mymodule_form_account_alter() executed.');`.

---
Tags: 8, forms
---


title: Loading a queue?

text:
# Question
Title: Loading a queue?
How can I use Drush to pass data into a Drupal Queue?

```
function hook_cron_queue_info() {
  $queues['my_queue_name'] = array(
    'worker callback' => '_my_queue_callback', // This is the callback function for each queue item.
    'time' => 25, // This is the max run time per cron run in seconds.
  );
  return $queues;
}

function module_name_load_queue($item) {
  $queue = DrupalQueue::get('my_queue_name');
  $queue->createItem(json_encode($item));
}

```

My ultimate goal is to pre-process data using a few bash scripts and then pass the end result to `module_name_load_queue($item);` using Drush.

Is this possible? If so, how do I go about this?

# Answer
Yes We can use drush queue run to initiate a queue

**Example :**

```
#!/bin/sh
SLEEP=${2} #Make the sleep time as configurable
while true
do
   drush5 --uri=${1} queue-run <Your QUEUE NAME> #${1} Domain URI
   sleep ${SLEEP}
done

```
> 0 votes

# Answer
The most common practice is to create a custom cron job that populates the queue. Failing that you could use drush ev "my\_callback()" to accomplish this.
> 0 votes

---
Tags: 7, drush, queue
---


title: Hide node if user has viewed it

text:
# Question
Title: Hide node if user has viewed it
I have a restaurant with a Drupal site and would like to post coupons for patrons to use. They would have to create a user account to view it. The coupon would be an image field and if a user wants to use it they would click use coupon and it would hide it from that user only. Is this possible?

Thanks

# Answer
> 1 votes
You can with Flag \+ Rules

In `/admin/structure/flags/add` add flag of "Content" and call it something like "use coupon" flag.

I presume your Nodes teasers are listed in view. So in Views:

* In Relationships add "Content flag"
    + Uncheck include only flagged content
    + Flag: Slect your flag
    + By: Current User

* In Filter Criteria add "Flagging" and select not flagged.

To prevent from viewing node directly by typing the url, in Rules:

* In `/admin/config/workflow/rules` create Rule with action of "Flagging is viewed".
* Add Action of "Page redirect" and send them to some custom /url that says you already redeemed this coupon. (Create a basic page for this)

# Answer
> 0 votes
Another option is to use the statistics module to see if the user has view the content. Note the statistics module has some performance implications.

---
Tags: views
---


# Question
Title: Administrative page still accessible by anonymous users?
It's almost 2 years I don't program modules in D7. I'm creating a module that shows 2 forms. One is public (and to's working) and one is a setup form under /admin space. The issue is that the one in the admin still accessible to anonymous, even when I check the checkbox into the "permission" page. Could you help me please to find out what I miss?

Please here part of the code

```
function MyModule_permission() {
  return array(
    'administer MyModule' => array(
      'title' => t('Administer MyModulemodule'),
      'description' => t('Perform administration tasks for MyModule module.')
    ),
  );
}

```

here below the address of the 2 forms

```
/**
 * Implements hook_menu().
 *
 * Displays module information.
 */
function MyModule_menu() {
  $items = array();

  // It should be accessible by everybody
  $items['fillin'] = array(
    'title' => 'Participation Data',
    'description' => 'Please fill here below the fields in',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_form'),
    'access callback' => TRUE
  );

  // it should be accessible only by admin
  $items['admin/config/setup_collection'] = array(
    'title' => 'Participation Text',
    'description' => 'Text for the presentation',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_setup_form'),
    'access arguments' => array('administer'),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE
  );

  return $items;
}

```

Here below the setup form with the default content, that should be accessible only by the administrator

```
/**
 * Implement hook_form()
 *
 * Creates the form for the setup page
 *
 */
function MyModule_setup_form($form, &$form_state) {
  $form['MyModule_message'] = array(
    '#type' => 'textarea',
    '#title' => t('TEXT '),
    '#wysiwyg' => TRUE,
    '#default_value' => variable_get('MyModule_message', 'Subscribe fill in the form below'),
  );

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('SUBMIT'),
  );
  return $form;
}

```

Here below just a part of the form accessible by the anonymous user

```
/**
 * Implements hook_form().
 *
 * Creates the form for the user.
 */
function MyModule_form($form, &$form_state) {

  global $conf;

  $form['MyModule_main_message']['hello'] = array(
    '#markup' => variable_get('MyModule_message'),
  );

  $form['first_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Put your first name'),
    '#size' => 50,
    '#maxlength' => 50,
    '#required' => TRUE,
  );

            ...
            ...
            ...

```

# Answer
1. The problem is you are setting `'access callback' => TRUE` this gives access to all.
2. I also to sure that administer is a valid permission in `'access arguments' => array('administer'),` instead try `'access arguments' => array('administer site configuration'),`.
> 3 votes

# Answer
In the "admin/config/setup\_collection" array you use:

```
'access callback' => TRUE

```

In this way all users can access to this url and it overrides the "access arguments" array.

Remove line with "access callback" and clear cache.
> 2 votes

# Answer
As the other answers are telling you, setting the access callback to `TRUE` is making Drupal allow the access to that page to every user, without checking which permissions they have. Instead of TRUE, you should set the access callback to `'user_access'` (yes, a string), or not set it at all, and Drupal will use the default value, which in most cases is `'user_access'`.
If you don't want any issue, especially if it's possible you are going to change the route your module defines, and make admin/config/setup\_collection a `MENU_DEFAULT_LOCAL_TASK` route, set the access callback explicitly, even if you are going to use the default value Drupal uses.

What the other answers aren't telling you is that setting the access arguments to `array('administer')`, you aren't telling Drupal to check the currently logged-in user who is trying to access admin/config/setup\_collection has the permission you defined in `MyModule_permission()`. For that, you would need to use code similar to the following one.

```
function MyModule_menu() {
  $items = array();

  // It should be accessible by everybody
  $items['fillin'] = array(
    'title' => 'Participation Data',
    'description' => 'Please fill here below the fields in',
    'access callback' => TRUE,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_form'),
  );

  // it should be accessible only by admin
  $items['admin/config/setup_collection'] = array(
    'title' => 'Participation Text',
    'description' => 'Text for the presentation',
    'access callback' => 'user_access',
    'access arguments' => array('administer MyModule'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_setup_form'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

As side note, never use capital letters in the module machine name. While PHP is not case sensitive, you are going to have issues when you will implement `hook_update_N()` for your module (and usually modules are going to implement that hook) because the Drupal code that gets the list of update hooks implemented from a module **is** case sensitive, as you can see from the following code used from `drupal_get_schema_versions()`.

```
// Prepare regular expression to match all possible defined hook_update_N().
$regexp = '/^(?P<module>.+)_update_(?P<version>\\d+)$/';
$functions = get_defined_functions();

// Narrow this down to functions ending with an integer, since all
// hook_update_N() functions end this way, and there are other
// possible functions which match '_update_'. We use preg_grep() here
// instead of foreaching through all defined functions, since the loop
// through all PHP functions can take significant page execution time
// and this function is called on every administrative page via
// system_requirements().
foreach (preg_grep('/_\\d+$/', $functions['user']) as $function) {

  // If this function is a module update function, add it to the list of
  // module updates.
  if (preg_match($regexp, $function, $matches)) {
    $updates[$matches['module']][] = $matches['version'];
  }
}

```

Since the content of `$regexp` **isn't** `'/^(?P<module>.+)_update_(?P<version>\\d+)$/i'`, the regular expression used from Drupal **is** case-sensitive.

This means that if the machine name of your module is *MyModule* and, by accident, you define an update hook as `mymodule_update_7100()`, it will not be recognized as update hook for your module.
It would also be true if the update hook would be named `MyModule_UPDATE_7100()`.
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: Invalidating render cache items for anonymous?
We have a certain content type in Drupal 8 that has a small grid of data on it that is populated from an API call when the node view is being built.

In that call, I am checking for cache and setting cache instead of talk to the API every request:

```
if ($cache = $this->cache->get($cache_key)) {
  return $cache->data;
}

// $content = request...

$this->cache->set($cache_key, $content, REQUEST_TIME + 3600, ['mymodule']);

```

Where `$cache_key` is just `mymodule:remote_id:subscription_id`. My default cache bin is handled via Memcache.

The Drupal page cache time is set to 30 minutes, and Varnish sits in front of it for anonymous traffic.

I am noticing that even though my custom cache data is set for an hour timer, and the Drupal cache is set for 30 minutes, users are able to see data from 3 days ago but I am not sure how. As soon as I go view the site (authenticated) and refresh, the data updates.

I tried backtracking this but nothing jumped out as missing, perhaps other than some cache tags I might need to add. Even still, the render object is what is being shown from cache, which the data is a part of before it is cached, not the cached data item itself.

System cron is running every hour. Shouldn't it purge invalidated cache as part of `system_cron`?

Edit: I switched my local from Memcache back to the default cache (MySQL) and noticed render cache items all have an expiration of -1.

At what point are entity render cache items invalidated? I feel like that *might* be my issue, but not sure how to address it.

# Answer
> 0 votes
> the max-age (maximum age) ... defaults to "permanently (forever) cacheable"
>
> ...
>
> Cache contexts, tags and max-age **must always be set**, because they affect the cacheability of the entire response. Therefore they "bubble": parents automatically receive them.
>
> Cache keys must only be set if the render array should be cached.

from https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays

Render arrays are cached indefinitely by default and setting the page cache expiration time doesn't change the cacheability metadata of render arrays in general. As on the linked page above, ideally you do something like:

```
// Merges the cache contexts, cache tags and max-age of the config object
// and user entity that the render array depend on.
$renderer->addCacheableDependency($build, $config);
$renderer->addCacheableDependency($build, \Drupal\user\Entity\User::load($current_user->id()));

```

But this doesn't work here because the data lives outside of Drupal - or more specifically, if you add anything that doesn't implement `Drupal\Core\Cache\CacheableDependencyInterface` as a dependency, the render array is marked as non-cacheable and it bubbles up: see `Drupal\Core\Cache\RefinableCacheableDependencyTrait::addCacheableDependency()`.

So in this case I think you just have to set the max-age yourself.

---
Tags: 8, caching
---


title: Change the location of Edit Profile

text:
# Question
Title: Change the location of Edit Profile
I am using Profile 2.

When the user clicks the 'Edit My Profile' tab, I would like its destination to be:

```
/user/175/edit/about-you

```

Where about-you is a Profile2 type.

How do I change the path of the tabs?
I am also using TabTamer, but this module does not let you change the path, only the label and enable/disable the link.

EDIT
I have tried the below code in template.php with no results.(after changing the theme name)

```
function THEMENAME_menu_alter(&$items) {
  $items['user/%/edit'] = $items['user/%/edit/about-you'];
  unset($items['user/%/edit']);
}

```

# Answer
> 0 votes
You can do this by custom module.For this please use below code.First you need to create custom menu using hook\_menu.

```
/**
* Implements hook_menu().
*/
function custom_menu() {
 $items['user/%/edit/about-you'] = array(
  'title' => 'About You',
  'page callback' => 'edit_about_you',
  'page arguments' => array(1),
  'access callback' => TRUE,
 );
return $items;
}

```

Now You need to write page callback for this menu item.

```
function edit_about_you($uid){
  $profile = profile2_load_by_user($uid,'profile_type'); // or by default main
  $form_state = form_state_defaults();
  form_load_include($form_state, 'inc', 'profile2_page');
  return entity_ui_get_form('profile2', $profile, 'edit', $form_state);
}

```

This will return profile edit page for user.Now you need to redirect user when click Edit My Profile tab for this you can user hook\_init for that. Check your path argument and redirect user to new created path.

Thanks

---
Tags: 7, users
---


# Question
Title: how to reinitiate a default field value every time the content edition is loaded?
i have a field that , if opt-in, send notifications. I would like that when editing the content , the value is always reinitiated to opt-out, sitll leaving the possibility for the editor to opt-in again

this code below does it but then it is not possible to save an opt-in nomore

```
use Drupal\node\NodeInterface;

function mymod_entity_load(array $entities, $entity_type_id)    {

  foreach ($entities as $entity) {
    if ($entity instanceof NodeInterface) {
      if($entity->bundle()=='evenement'){
         $entity->field_notif=0;
      }
    }
  }
}

```

# Answer
> 3 votes
You need to use hook\_form\_alter

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

    /*
     * Implementation of hook_form_alter()
     */
    function mymod_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      if($form_id == 'node_evenement_edit_form'){ // target a specific form
        $form['field_notif']['widget']['#default_value'] = 0;
      }
    }

```

---
Tags: 8, entities
---


# Question
Title: How to display calculated values in Drupal 8 views?
Lets say I have an account field called **euro-budget**, and I have a content type **exchange rate** including the field **usd-value**" which import the USD exchange rate every 2 hours. In the view which displays all users including the field **euro-budget**. I want to have a calculated field which multiplies the field **euro-budget** with the latest **usd-value** field. What is the easiest way to do this? I already tried Views PHP but it is somehow not compatible with the latest **Drupal 8** version.

# Answer
Create a field formatter for your euro-budget field and then select that for your field in your view.
> 1 votes

---
Tags: views, 8
---