# Question
Title: Completing the checkout process event isn't firing
I have a Drupal Commerce 7 installation which isn't firing the Completing the checkout process event.

Steps I've tried:

* I've rebuilt Rule's cache
* I've rechecked the integrity of the rules
* I've set "Log debug information to the system log" (Log all warnings and errors)
* I've disabled all of the rules bound to the event "Completing the checkout process"
* I've created a new rule, which will only send an email.

However, the e-mail is never sent and I don't see the rule being written on the log.

I've tried to submit correctly the order in the storefront (with a "normal" user and with an Admin user).

I've tried to use different types of payment.

I've tried to change the order status to "Checkout complete" in the Backoffice.

What else I'm missing? What's making this event not firing?

Based on others posts, I've checked the rules for other events and realized there's a rule "Commerce order message: changing status", for the event "After updating an existing commerce order". It has the following actions: Creates new entity Message Type Commerce Order: state change of the order Set a data value message:message-commerce-order = commerce-order Set a data value message:arguments:order-status = \[commerce-order:status-title\] Set a data value message:arguments:order-status-previous = \[commerce-order-unchanged:status-title\]

However, this doesn't seem to be responsible for the event never firing, or is it?

Can anybody help me and shed some light on this?

This is the Rules debug information I get, after changing the Order status to Complete, directly on the Backoffice:

Rules debug information: " Reacting on event After updating an existing commerce order.

```
0 ms Reacting on event After updating an existing commerce order.
11.574 ms Evaluating conditions of rule Delete shipping line items on shopping cart updates. [edit]
13.432 ms The condition data_is evaluated to FALSE [edit]
13.442 ms AND evaluated to FALSE.
13.546 ms Evaluating conditions of rule Commerce order message: changing status. [edit]
14.047 ms The condition data_is evaluated to FALSE [edit]
14.057 ms AND evaluated to TRUE.
" Rule Commerce order message: changing status fires. [edit]
    0 ms Rule Commerce order message: changing status fires.
    6.493 ms Evaluating the action entity_create. [edit]
    7.441 ms Added the provided variable message of type message [edit]
    9.105 ms Evaluating the action data_set. [edit]
    24.349 ms Evaluating the action data_set. [edit]
    26.206 ms Evaluating the action data_set. [edit]
    26.454 ms Rule Commerce order message: changing status has fired.
40.578 ms Saved message of type message.
46.594 ms Finished reacting on event After updating an existing commerce order.

```

Still no information regarding the firing of "Completing the checkout process" event...

# Answer
> 1 votes
Debugging is the art of eliminating possible causes for an issue. In this case, your issue *could* be because ... your rule is ***disabled***.

As per the '***I've disabled all of the rules bound to the event "Completing the checkout process***" ...', double check that the rule you want to fire is (still) enabled. If it isn't, then make sure to enable it (again).

Also, your question states "*the e-Mail is never send*": it could well be because something (different from your rule not firing) is wrong. So therefor, add an extra Rules Action to the rule you're struggling with, as the very first Rules Action, and which is only to "show a message on the site"", and with a message like "Bingo" (or whatever). Then rerun your testcase, and verify if you do get such "Bingo":

* If you do, your rule has fired ... and your real issue is related to sending the eMail.
* If you don't, (temporary) remove ALL Rules Conditions in your rule and retry. If in that case you do get a "Bingo", then your issue is related to one or more of your Rules Conditions (though the rule did fire).

The above is how I typically do most of my Rules debugging, in cases where some rule seems to not fire (stupid, but pretty effective).

If none of the above debugging tips helps ... then edit your question and include an export of the rule you are debugging (in that case I might further improve my anwer).

---
Tags: 7, commerce, rules
---


# Question
Title: Nodes display links to shared document(s)
## Summary

Nodes display links to shared document(s)

## Example

PDFs to upload only once before I create the workshops:

* Booking Form Primary School
* Booking Form Secondary Schoool
* Risk Assessment for Primary School
* Risk Assessment for Secondary School

Then I would like to be able to be able to create a workshop node using a custom content type and while creating this node, be able to click check boxes of some of the forms above. When viewing the node of the workshop, for the ticked forms to be displayed as Links to download the PDFs.

This is so that when creating lots of Workshops, I can just tick the boxes for the form downloads to be displayed on each workshop page.

## My Attempt

1. I created a taxonomy called: Forms.
2. For this vocabulary I added a file field: field\_form
3. Then I added the terms and uploaded a document for each
4. Then in the Content Type adding a term reference field linking to the vocabulary.
5. **This is where I get stuck.** In the Content Type Display it only shows links to the term page and not the File download.

How would I setup the ability to upload some PDFs and then be able to then create some nodes that display links to these PDFs as downloads?

# Answer
> 1 votes
1. Create a block views of terms to display the links to term files;
2. add a filter/contextual filter in the view to show only the files of the terms of the current node;
3. set the block to show up on node pages (except node edit pages).

---
Tags: files
---


# Question
Title: How do I set the text format used in a message (from the Message module)?
I'm using the Message module on a site that has both the Filtered HTML and Full HTML text formats. By default, Message appears to use Filtered HTML, but I would like to use Full HTML instead.

However, I couldn't find an option for changing text formats in the UI. I have exported my message types to a feature using the Features module, so instead I tried changing the format from "filtered\_html" to "full\_html" in the feature and reverting, but this didn't work, either.

Is is possible to change the text format used to display messages, and if so, how?

(Also asked in the module's issue queue. When I get an answer, I will update both.)

# Answer
> 0 votes
I wasn't able to change the format, but I was able to get what I wanted by modifying the text format itself (then I had to adjust everything else that was using the text format in another way). Not an ideal solution, but it worked for my needs.

# Answer
> 0 votes
You can set the permission for user role to use filtered\_html or full\_html in Administer -\> people -\> permission.

# Answer
> 0 votes
Comment #1 in the issue you linked to contains "a" way to do what you're looking for:

> ... you can select the text format in the ui while writing the message text.

That same issue also contains a screenprint about this, which looks like so:

---
Tags: 7, input-formats, message-subscribe
---


# Question
Title: Admin edit of older order forces to add values to newly added required fields
In our drupal-commerce e-shop orders were already working for more than a year. Later we wanted to add some required fields (phone number and "I agree with ...." checkbox), phone field few months back and the checkbox just recently (as part of GDPR-ready effor).

Today we realized that admin editing of order to move it in workflow (change state) forces the admin to fill-in the phone number field and to check the checkbox. That is not good.

Also it looks that in order list is the name of admin now ... for those edited orders.

Does anyone know how to fix this behaviour? Any existing issue? We just want to be able to change the order state and not to change anything else.

Versions: Drupal 7.59, Commerce 7x-1.14

# Answer
How you resolve this depends on your Drupal version, so please be sure to specify Drupal 7 vs. Drupal 8 in future questions. On Drupal 8, you can likely resolve this by editing the form display mode and not including those fields on the normal admin form. However, in Drupal 7 you'll have no such option. You'll need to use hook\_form\_alter() to prevent those fields from showing up on the order edit form instead.

Re: the administrator name, there's no way for us to help you without knowing how you've constructed that View. If it's just showing the name of the last person to edit the order (i.e. create a revision of it), it makes sense that it'd be the administrator. It should normally be pulling the name from the order's billing information profile.
> 1 votes

# Answer
If administer is not same as user 1, then a simple trick could be ban administration role from editing those fields using Field Permissions Module.

else as user with ID 1 bypasses many restriction, then as Ryan said, you should have implement hook\_form\_FORM\_ID\_alter in a custom module and simply `unset` those fields or remove the required attributes.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Integrate Webform.html.twig into existing template
I am attempting to add a webform field into an existing content type which has an associated twig template. I can add the webform field to a new content type and/or use the default webform content type and the form displays without an issue. If I add the webform to an existing content type the form does not display. I tried adding the content from webform.html.twig to the existing content types template but it is still not displaying the form. I know I am missing something simple here. I can supply a few screenshots and or the twig files if that would be helpful

thank you for your patience. I have had the debugging turned on for quite some time now the development version of our site. The inspect screen appears to suggests the problem with displaying the webform field is in the page.html.twig which I have attached. Interestingly, I tried adding a few other random fields to the page content type and they do not display either so I am fairly certain now that there is a problem with the twig template.

```
{#
/**
 * @file
 * Default theme implementation to display a page.
 *
 * @see academyhealth.info.yml
 * @see template_preprocess_page()
 * @see html.html.twig
 *
 * @ingroup themeable
 */
#}

<header class="header">
  <div class="container">
    <a class="header__logo" href="/"><span class="element-invisible">AcademyHealth</span></a>
    <button class="header__menu-button"><i class="icon-hamburger"></i> Menu</button>
    <div class="header__navs">
      <a class="js-navs__close" href="javascript:void(0);"><i class="icon-close"></i> <span class="element-invisible">Close</span></a>
      <nav class="header__main-nav">
        {{ page.main_navigation }}
      </nav>
      <div class="header__util">
        {{ page.utility_navigation }}
        <div class="util__search">
          {{ page.search }}
        </div>
      </div>
    </div>
  </div>
</header>

<section class="page">
  {#
    A block titled content will be set if pages are extending this template, so
    print that instead of just printing page.content. The templates that extend
    this template, call page.content and place it appropriately.
  #}
  {% set _block_content = block('content') %}

  {% if _block_content is not empty %}
    {{ _block_content|raw }}
  {% else %}
    {{ page.content }}
  {% endif %}

</section>

<footer class="footer">
  <div class="container">
    <div class="footer__col1">
      <a class="footer__logo" href="{{ site.url }}"><span class="element-invisible">AcademyHealth</span></a>
    </div>
    <div class="footer__col2">
      <h6 class="footer__title">Connect with Us</h6>
      {{ page.footer_social_media }}
    </div>
    <div class="footer__col3">
      <h6 class="footer__title">Navigate AcademyHealth</h6>
      {{ page.footer_menu }}
    </div>
    <div class="footer__col4">
      <h6 class="footer__title">Extras</h6>
      {{ page.footer_extras }}
    </div>
  </div>
  <div class="footer__credits">
    <div class="container">
      {{ academyhealth_address_line }} | {{ academyhealth_address_line_2 }} | Tel: {{ academyhealth_phone_number }} | Fax: {{ academyhealth_fax_number }}
    </div>
  </div>
</footer>

```

# Answer
Conceptually, you shouldn't be thinking about it as including templates in other templates. Other CMS'es are more "template based" so to speak, but Drupal isn't. Building your content types and pages in Drupal means telling Drupal (through configuration or in code) how to construct its render arrays. From there on, Drupal will figure out which templates to use and how to merge the resulting HTML of one template into another template.

So that's the theory... now what's the problem in your case? The most obvious reason I can think of, is that you added the field, but did not yet configure it to be displayed. To do so, make sure Field UI module is enabled and then go the "Manage Display" page of your content type. The URL will look like `/admin/structure/types/manage/[type]/display` where "\[type\]" is the machine name of your content type. If you see your field in the "disabled" part of the form, drag it upwards to make it enabled and save the form. (This is an example of the "through configuration" method I mentioned earlier.)

If the above does not solve your problem, please add more details to your original question.
> 2 votes

---
Tags: webforms
---


# Question
Title: Restrict language based content editing for nodes and blocks
I am running a D7 multi-language site. I am looking for a solution to restrict node AND block editing for english language, only. The editor should not be allowed to edit french content. How can accomplish what I'm looking for?

So far, I have created a new user (e.g. english editor) and added them to a new role. I am also using contrib module 'Content Access' and 'block access'. However I have to restrict access per node which is not my perfect choice. With block\_access module, english editors are still able to see/modify translations

# Answer
For your solution you can implement hook\_node\_access, as you see this function takes 3 arguments $node which is the content the user wants to make an operation on it, there you can check content's language, $op is the operation which user wants to make on the content which in your case you can check if it is edition, and finally $account takes the information about the user so you can decide if user is allowed to do the operation or not.

One big consideration is that this hook is not fired for the super user (user with uid = 1) as he bypasses almost all permissions, so in this case you can use hook\_init and make a redirect based on node arguments.
> 0 votes

---
Tags: 7, users, i18n-l10n
---


title: View Path TaxonomyTerm/sub-page

text:
# Question
Title: View Path TaxonomyTerm/sub-page
I am looking to create a QUESTIONS view for all terms in a taxonomy vocabulary. Let's say I have a taxonomy that has terms apple, orange, banana. We use pathauto to go to domain.com/apple which shows one content type.

But what I am trying to do is create a sub page for each term with the path: domain.com/apple/questions

I have already set the view and added a contextual filter but for some reason, its is not working.

The path that I have for the view is (/taxonomy/term/%/questions)

Is this correct? Am I approaching this the right way? If you have a better suggestion please let me know.

# Answer
> 0 votes
The Panels module provides the views content panes which is a display type for views, there you can create your view easily, make it fetch input argument from context and show the results, then you can simply include your pane in the place you want.

if you are not much familiar with Panels module, then this tutorial can make you became familiar, hence this is for Drupal 7 but you can use it in drupal 8 as well.

# Answer
> 0 votes
If I understood your question, you do not need to create any view nor change the default taxonomy term view. You just need to create a path alias pattern for taxonomy terms of that particular vocabulary - something like this: /term-name-token/questions.

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


title: Match Users skills

text:
# Question
Title: Match Users skills
I am designing a website and there are two users 1:users and 2:company. I want two field in different account need to match with each other. If users provide specific SKILLs and company requires specific SKILLS person then matching skills show result to company and a user. Please please help me if any confusion ask me

# Answer
> 1 votes
There is more than one approach to creating different user accounts, it depends on your particular needs. Maybe Field Permissions and Multiple Registration would do.

Create a Taxonomy Vocabulary called `Skills` with terms inside for each of the skills. Then create an Entity reference field on User account settings referencing that Vocabulary. This means that each user and each company will be able to choose skills on their edit profile pages.

Then with Views you can create blocks listing users, and use Contextual filters to filter out only users that have the same skills chosen, as those selected on the page where the block is displayed. When you visit a Company page, this page will have some skills chosen, and a block there will be showing all users that have ticked the same skills.

The same can be created to be shown on User profiles, a Block displaying only Companies, but filtered out to only those companies that have the same skills selected as that user.

This is the concept of how to do it. Details are out of scope of answering it here (you can find other questions where this was solved for related content through taxonomy).

You have to be careful depending on whether you allow for one, or multiple skills to be chosen (settings are a bit different).

Emails can be sent to users (with Rules module) when a new company matching their skills is posted. The same for companies, when a new user with their skills is created.

# Answer
> 0 votes
First of all you will need two different user role, can be named as `Company` and `Expert`.

Then you will need two content types, lets call them `Job-position` and `Job-appliance` which can be created by Companies and Experts respectively (You can set permissions on that).

In next Step you will need two view blocks, you can call them `proper jobs` and `proper experts`, the first block should be viewed in a content of type 'Job-appliance' so when a user navigate to an 'job appliance' will see a list of proper job positions for that. Almost same functionality should be provided for other view as well.

These views can be modified in a manner which takes argument from context, and filter out needed results.

for ease of use with views in this situation I recommend usage of Panels module, so you can pass arguments easier.

Also if you need different registration fields for each user role, I suggest Profile module (for Drupal 8, in case of using drupal 7 you can use Profile2 and Profile2 Registration Path module)

---
Tags: comments
---


# Question
Title: How do you inject dependencies in your classes from external packages?
My project has external PHP packages pulled in via Composer.

I would like to inject one of the classes in that package as a dependency, instead of do `new Class();` inside my Controller methods.

The documentation says you can define a service like the following:

```
services:
  mymodule.example_service:
    class: Drupal\path\to\Class

```

What do you do when you want to use an external PHP package not native to Drupal?

# Answer
You should be able to use the fully qualified namespace for the injection:

```
services:
  mymodule.example_service:
    class: path\to\Class

```
> 1 votes

# Answer
If anyone want to use external packages into Drupal controller, note that you can actually use one without dependency injection. For example, if you want to use Carbon (DateTime API):

**Step 1: Install the package**

```
composer require nesbot/carbon

```

**Step 2: Use the namespace**

```
use Carbon\Carbon;

```

That's all. You are ready to use the package now.

**Code sample:**

```
<?php

namespace Drupal\foo\Controller;

use Carbon\Carbon;
use Drupal\Core\Controller\ControllerBase;

class FooController extends ControllerBase {

    public function bar() {
        return [
            '#markup' => Carbon::now(),
        ];
    }
}

?>

```
> 0 votes

---
Tags: 8, dependency-injection
---


# Question
Title: How to display a flag to anonymous users?
I'm using the Flag module, but I have a problem in displaying a flag to anonymous users.

I have 2 flags called "make feature" and "add to Favorites". I want to display this flag to anonymous users too. Currently it is displayed only to the users who are logged in (authenticated user).

I want these flags to be displayed to all users (whether logged in or not). But when an anonymous user clicks on flag than such user should be redirected to the login page. After login the user should be able to set flag.

Is this possible?

# Answer
You can do this in your 'node.tpl.php' by something like below, if user is logged in display flag as normal and if is not logged in redirect user to logging page with `destination` parameter

```
global $user;
if(!$user->uid) {
    // $flag: bookmark or make_feature, $action: flag, $content_id: $nid.....
    $flag_link = flag_flag_link($flag, $action, $content_id);
    $flag_url = $flag_link['href'];
    if(isset($flag_link['query']['token'])) {
        $flag_url .= '?'.$flag_link['query']['token'];
    }
    print l(t('bookmark'), 'user/login' , array('query'=> array('destination' => $flag_url)));
} else {
    print render($content['links']['flag']);
}

```
> 10 votes

# Answer
To **display a flag to anonymous users**, refer to what's written in the community documentation of the Flag module, i.e.:

> Flagging for anonymous users (even with page caching enabled). Requires Session API.

Something similar from the README.txt:

> Optional Installation
>
> 1) The ability for anonymous users to flag content is provided by the Session API module, available at http://drupal.org/project/session\_api.

Be aware also that Session API isn't mentioned as a dependency in the Flag module either.
> 4 votes

# Answer
https://www.drupal.org/project/flag\_anon

> Offer an option to display of "sign in or register" for a flag for anonymous users.
> 2 votes

---
Tags: 7, flags, users
---


# Question
Title: How do I add CSS and JavaScript files in a custom module?
I created a custom Drupal 8 module. I am now trying to add JavaScript and CSS files using the *my\_module.libraries.yml* file and the following code, which doesn't work.

```
lrv_key:
  version: 1.x
  js:
    js/lrv.js: {}
    dependencies:
      - core/jquery
      - core/drupalSettings
  css:
    theme:
      css/lrv.css: {}

```

How can I correctly add CSS and JavaScript files to pages from a module?

# Answer
A .libraries.yml file used from a module doesn't tell Drupal to attach the JavaScript and CSS files defined from the library to every page. To attach the library when some conditions are met, a module should implement `hook_page_attachments()`.

```
function mymodule_page_attachments(array &$attachments) {
  if (\Drupal::currentUser()->isAuthenticated()) {
    $attachments['#attached']['library'][] = 'my_module/lrv';
  }
}

```

Using that code, the library would be attached to every page visited from a logged-in user. Attaching the library to every page, even when they are requested from anonymous users just require implementing a hook similar to the following one.

```
function mymodule_page_attachments(array &$attachments) {
  // Unconditionally attach the mymodule/lrv library.
  $attachments['#attached']['library'][] = 'my_module/lrv';
}

```

The library definition shown in the question contains an error: The *dependencies* key should not be a sub-key of the *js* nor the *css* key, but it should be at the same level of the *js* and *css* keys. See how Drupal core defines its libraries, for example the ones defined in core.libraries.yml. (I removed the comment lines from the definitions I copied.)

```
jquery:
  remote: https://github.com/jquery/jquery
  version: "3.2.1"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/3.2.1/LICENSE.txt
    gpl-compatible: true
  js:
    assets/vendor/jquery/jquery.min.js: { minified: true, weight: -20 }

jquery.cookie:
  remote: https://github.com/carhartl/jquery-cookie
  version: "v1.4.1"
  license:
    name: MIT
    url: https://github.com/carhartl/jquery-cookie/blob/v1.4.1/MIT-LICENSE.txt
    gpl-compatible: true
  js:
    assets/vendor/jquery.cookie/jquery.cookie.min.js: { minified: true }
  dependencies:
    - core/jquery

jquery.farbtastic:
  remote: https://github.com/mattfarina/farbtastic
  version: "1.2"
  license:
    name: GNU-GPL-2.0-or-later
    url: https://github.com/mattfarina/farbtastic/blob/master/LICENSE.txt
    gpl-compatible: true
  js:
    assets/vendor/farbtastic/farbtastic.js: { minified: true }
  css:
    component:
      assets/vendor/farbtastic/farbtastic.css: {}
  dependencies:
    - core/jquery

```

Putting the *dependencies* key in the wrong place would not allow Drupal to load the libraries from which your library depends. Your library would work only when Drupal already loaded the *core/jquery* and the *core/drupalSettings* libraries for other libraries.
This and not implementing `hook_page_attachments()` are two possible reasons for your library not to work; another reason could be errors in the JavaScript code or in the CSS code (for example a wrong CSS selector).

The `hook_page_attachments()` implementations I shown use the following library definition.

```
lrv:
  version: 1.x
  js:
    js/lrv.js: {}
  css:
    theme:
      css/lrv.css: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

The name of the library is *my\_module/lrv* because it is defined as key *lrv* (the one I used in the code I shown) in the file my\_module.libraries.yml (the one you seem to use).

See Defining a library and Attaching a library to page(s).

### Note about theme libraries

What I described in this answer is valid only for modules: Themes just need to use a .libraries.yml file. Drupal will attach the libraries defined in the active theme to every page.
That is done in `system_page_attachments()`, which uses the following code. (See the comment before the quoted code.)

```
// Attach libraries used by this theme.
$active_theme = \Drupal::theme()->getActiveTheme();
foreach ($active_theme->getLibraries() as $library) {
  $page['#attached']['library'][] = $library;
}

```
> 7 votes

# Answer
This is because you've got this formatted incorrectly. Your dependencies are on the library itself, not for the js or css components individually. Assuming you have a js file at `YOUR_MODULE/js/lrv.js` and a css file at `YOUR_MODULE/css/lrv.css` you should update your declaration like so:

```
lrv_key:
  version: 1.x
  js:
    js/lrv.js: {}
  css:
    theme:
      css/lrv.css: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

You can read more in the Defining a library section of the drupal docs.

One note I'll make is that you may want to define your css under `component` rather than `theme`, but I'm not sure exactly what you're doing. You can read more about component vs theme in the defining a library section referenced above.
> 2 votes

---
Tags: 8
---


# Question
Title: Can not unset rows of a view programmatically
I created a view of terms using views\_tree module. I need to remove some of the terms under some conditions. This is my code

```
function THEME_views_pre_render(&$views) {
    for($i = 0 ; $i < sizeof($views->result) ; $i++)
       unset($views->result[$i]);
}

```

But it still prints all of the terms and doesn't delete any of them. I tried this code

```
function THEME_views_pre_render(&$views) {
    for($i = 0 ; $i < sizeof($views->result) ; $i++){
        $views->result[$i]->taxonomy_term_data_name ="Hello";
    }
}

```

It successfully renamed every term, But when I tried the following code, every name turned back to what it was from the beginning and nothing removed.

```
function THEME_views_pre_render(&$views) {
    for($i = 0 ; $i < sizeof($views->result) ; $i++){
        $views->result[$i]->taxonomy_term_data_name ="Hello";
        unset($views->result[$i]);
    }
}

```

How can I remove some terms ?

# Answer
> 1 votes
It should work on `template.php` too. Module implementation does not look mandatory here. I have noticed a few issues in the code sample that you have pasted.

1. There is a typo. It should be **$view** not **$views**.
2. Instead of

```
for($i = 0 ; $i < sizeof($view->result) ; $i++){
}

```

Do

```
$sizeof_result = sizeof($view->result);
for($i = 0 ; $i < $sizeof_result ; $i++)

```

The following code works for me:

```
function MYTHEME_views_pre_render(&$view){
  if($view->name == 'MY_VIEW'){
    $sizeof_result = sizeof($view->result);
    for($i = 0 ; $i < $sizeof_result ; $i++){
      //IF Condition
        unset($view->result[$i]);
    }
  }
}

```

The reason for using variable `$sizeof_result` instead of `sizeof($view->result)` in `for loop` is:

For each execution of the loop, the value of sizeof($view-\>result) changes(decreases by 1). Due to this, the for loops does not work as expected.

# Answer
> 0 votes
Use basically the same code in THEME\_views\_post\_execute(&$view) https://api.drupal.org/api/views/views.api.php/function/hook\_views\_post\_execute/7.x-3.x

# Answer
> 0 votes
As jackrabbithanna said, maybe implementation of the code in a module may resolve your problem, I also had excluded some view results in a project using an auxiliary result set as code below , hope that helps:

```
/**
  * Implementation of hook_views_pre_render().
  */
function MYMODULE_views_pre_render(&$view) {
  $new_result = [];
  foreach ($view->result as $key => $value) {
   if(SHOULD NOT EXCLUDED)
    $new_result[] = $value;
  }
  $view->result = $new_result;
}

```

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


# Question
Title: Invalid translation language (fa) specified
I'm trying to add "fa" language in a Drupal 8 installation. I added it from admin/config/regional/language. Everything is OK and the language added successfully and added in language switcher in front-end. But when I click on it, I get this error:

```
InvalidArgumentException: Invalid translation language (fa) specified. in Drupal\Core\Entity\ContentEntityBase->getTranslation() (line 748 of core/lib/Drupal/Core/Entity/ContentEntityBase.php).

```

Note: This is not a clean installation. The Drupal I have is a working site with some modules which I want to add Persian as its 6th language. Any suggestions?

Thanks.

# Answer
Basically, this error appears when some translation methods like $entity-\>getTranslation('LANGUAGE\_CODE') or $entity-\>addTranslation('LANGUAGE\_CODE') are called and there is no translation of the entity in the specified language.

The solution is to check if the entity hasTranslation using **$entity-\>hasTranslation('fa')** before calling the getTranslation or addTranslation like this:

```
if ($entity->hasTranslation('fa')) {
  $translation = $entity->getTranslation('fa');
}

```
> 6 votes

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


# Question
Title: How to prevent my ZURB theme from stripping out part of the JSON LD element?
I use ZURB theme and following I post the code of my template.php file.

My problem is, that `type="application/ld+json"` in `<script type="application/ld+json">` gets stripped out so it is rendered as just `<script>`.

The problem with this is that I can't add structured markup to any pages.

To reproduce just insert jsonld script in any way (third party module or using custom fields for nodes) and display it with a zurb theme.

The same issue has already been reported for ZEN: https://www.drupal.org/project/zen/issues/2934644

To I have to adapt my template.php in a similar way as suggested in the ZEN patch in terms of not stripping out JSON-ld?

Here is my template.php

```
    <?php

/**
 * Implements template_preprocess_html().
 *
 */
//function gonzo_preprocess_html(&$variables) {
//  // Add conditional CSS for IE. To use uncomment below and add IE css file
//  drupal_add_css(path_to_theme() . '/css/ie.css', array('weight' => CSS_THEME, 'browsers' => array('!IE' => FALSE), 'preprocess' => FALSE));
//
//  // Need legacy support for IE downgrade to Foundation 2 or use JS file below
//  // drupal_add_js('http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE7.js', 'external');
//}

/**
 * Implements template_preprocess_page
 *
 */
//function gonzo_preprocess_page(&$variables) {
//}

/**
 * Implements template_preprocess_node
 *
 */
//function gonzo_preprocess_node(&$variables) {
//}

/**
 * Implements hook_preprocess_block()
 */
//function gonzo_preprocess_block(&$variables) {
//  // Add wrapping div with global class to all block content sections.
//  $variables['content_attributes_array']['class'][] = 'block-content';
//
//  // Convenience variable for classes based on block ID
//  $block_id = $variables['block']->module . '-' . $variables['block']->delta;
//
//  // Add classes based on a specific block
//  switch ($block_id) {
//    // System Navigation block
//    case 'system-navigation':
//      // Custom class for entire block
//      $variables['classes_array'][] = 'system-nav';
//      // Custom class for block title
//      $variables['title_attributes_array']['class'][] = 'system-nav-title';
//      // Wrapping div with custom class for block content
//      $variables['content_attributes_array']['class'] = 'system-nav-content';
//      break;
//
//    // User Login block
//    case 'user-login':
//      // Hide title
//      $variables['title_attributes_array']['class'][] = 'element-invisible';
//      break;
//
//    // Example of adding Foundation classes
//    case 'block-foo': // Target the block ID
//      // Set grid column or mobile classes or anything else you want.
//      $variables['classes_array'][] = 'six columns';
//      break;
//  }
//
//  // Add template suggestions for blocks from specific modules.
//  switch($variables['elements']['#block']->module) {
//    case 'menu':
//      $variables['theme_hook_suggestions'][] = 'block__nav';
//    break;
//  }
//}

//function gonzo_preprocess_views_view(&$variables) {
//}

/**
 * Implements template_preprocess_panels_pane().
 *
 */
//function gonzo_preprocess_panels_pane(&$variables) {
//}

/**
 * Implements template_preprocess_views_views_fields().
 *
 */
//function gonzo_preprocess_views_view_fields(&$variables) {
//}

/**
 * Implements theme_form_element_label()
 * Use foundation tooltips
 */
//function gonzo_form_element_label($variables) {
//  if (!empty($variables['element']['#title'])) {
//    $variables['element']['#title'] = '<span class="secondary label">' . $variables['element']['#title'] . '</span>';
//  }
//  if (!empty($variables['element']['#description'])) {
//    $variables['element']['#description'] = ' <span data-tooltip="top" class="has-tip tip-top" data-width="250" title="' . $variables['element']['#description'] . '">' . t('More information?') . '</span>';
//  }
//  return theme_form_element_label($variables);
//}

/**
 * Implements hook_preprocess_button().
 */
//function gonzo_preprocess_button(&$variables) {
//  $variables['element']['#attributes']['class'][] = 'button';
//  if (isset($variables['element']['#parents'][0]) && $variables['element']['#parents'][0] == 'submit') {
//    $variables['element']['#attributes']['class'][] = 'secondary';
//  }
//}

/**
 * Implements hook_form_alter()
 * Example of using foundation sexy buttons
 */
//function gonzo_form_alter(&$form, &$form_state, $form_id) {
//  // Sexy submit buttons
//  if (!empty($form['actions']) && !empty($form['actions']['submit'])) {
//    $classes = (is_array($form['actions']['submit']['#attributes']['class']))
//      ? $form['actions']['submit']['#attributes']['class']
//      : array();
//    $classes = array_merge($classes, array('secondary', 'button', 'radius'));
//    $form['actions']['submit']['#attributes']['class'] = $classes;
//  }
//}

/**
 * Implements hook_form_FORM_ID_alter()
 * Example of using foundation sexy buttons on comment form
 */
//function gonzo_form_comment_form_alter(&$form, &$form_state) {
  // Sexy preview buttons
//  $classes = (is_array($form['actions']['preview']['#attributes']['class']))
//    ? $form['actions']['preview']['#attributes']['class']
//    : array();
//  $classes = array_merge($classes, array('secondary', 'button', 'radius'));
//  $form['actions']['preview']['#attributes']['class'] = $classes;
//}

/**
 * Implements template_preprocess_panels_pane().
 */
// function zurb_foundation_preprocess_panels_pane(&$variables) {
// }

/**
* Implements template_preprocess_views_views_fields().
*/
/* Delete me to enable
function THEMENAME_preprocess_views_view_fields(&$variables) {
 if ($variables['view']->name == 'nodequeue_1') {

   // Check if we have both an image and a summary
   if (isset($variables['fields']['field_image'])) {

     // If a combined field has been created, unset it and just show image
     if (isset($variables['fields']['nothing'])) {
       unset($variables['fields']['nothing']);
     }

   } elseif (isset($variables['fields']['title'])) {
     unset ($variables['fields']['title']);
   }

   // Always unset the separate summary if set
   if (isset($variables['fields']['field_summary'])) {
     unset($variables['fields']['field_summary']);
   }
 }
}

// */

/**
 * Implements hook_css_alter().
 */
//function gonzo_css_alter(&$css) {
//  // Always remove base theme CSS.
//  $theme_path = drupal_get_path('theme', 'zurb_foundation');
//
//  foreach($css as $path => $values) {
//    if(strpos($path, $theme_path) === 0) {
//      unset($css[$path]);
//    }
//  }
//}

/**
 * Implements hook_js_alter().
 */
//function gonzo_js_alter(&$js) {
//  // Always remove base theme JS.
//  $theme_path = drupal_get_path('theme', 'zurb_foundation');
//
//  foreach($js as $path => $values) {
//    if(strpos($path, $theme_path) === 0) {
//      unset($js[$path]);
//    }
//  }
//}

// Enabling customized login form (attempt I)
// function gonzo_theme() {
//   $items = array();
//
//   $items['user_login'] = array(
//     'render element' => 'form',
//     'path' => drupal_get_path('theme', 'gonzo') . '/templates',
//     'template' => 'user-login',
//     'preprocess functions' => array(
//        'gonzo_preprocess_user_login'
//     ),
//   );
//    $items['user_register_form'] = array(
//      'render element' => 'form',
//      'path' => drupal_get_path('theme', 'gonzo') . '/templates',
//      'template' => 'user-register-form',
//      'preprocess functions' => array(
//        'gonzo_preprocess_user_register_form'
//      ),
//    );
//    $items['user_pass'] = array(
//      'render element' => 'form',
//      'path' => drupal_get_path('theme', 'gonzo') . '/templates',
//      'template' => 'user-pass',
//      'preprocess functions' => array(
//        'gonzo_preprocess_user_pass'
//      ),
//    );
//   return $items;
// }

// function gonzo_preprocess_user_login(&$vars) {
//   $vars['intro_text'] = t('This is my awesome login form');
// }

//  function gonzo_preprocess_user_register_form(&$vars) {
//    $vars['intro_text'] = t('This is my super awesome reg form');
//  }
//
//  function gonzo_preprocess_user_pass(&$vars) {
//    $vars['intro_text'] = t('This is my super awesome request new password form');
//  }

// Enabling customized login form attempt II
function gonzo_form_alter(&$form, $form_state, $form_id) {
  //print_r($form) // This will display form elements.
  if($form_id == "user_login_block") {
      $form['actions']['submit']['#value']= "›";
  }
}

// Enabling customized Teaser Display
function gonzo_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__teaser';
  }
}

// Customizing visibilty radio buttons in edit/create form
// function theme_form_element (https://api.drupal.org/api/drupal/includes!form.inc/function/theme_radios/7)
function gonzo_form_element($variables) {
  $element = &$variables ['element'];

  // This function is invoked as theme wrapper, but the rendered form element
  // may not necessarily have been processed by form_builder().
  $element += array(
    '#title_display' => 'before',
  );

  // Add element #id for #type 'item'.
  if (isset($element ['#markup']) && !empty($element ['#id'])) {
    $attributes ['id'] = $element ['#id'];
  }
  // Add element's #type and #name as class to aid with JS/CSS selectors.
  $attributes ['class'] = array('form-item');
  if (!empty($element ['#type'])) {
    $attributes ['class'][] = 'form-type-' . strtr($element ['#type'], '_', '-');
  }
  if (!empty($element ['#name'])) {
    $attributes ['class'][] = 'form-item-' . strtr($element ['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  }
  // Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element ['#attributes']['disabled'])) {
    $attributes ['class'][] = 'form-disabled';
  }

  // only prints the wrapper for elements that are not radio elements
  $output = '';
  if ($element['#type'] != 'radios' && $element['#type'] != 'radio') {
    $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
  }

  // If #title is not set, we don't display any label or required marker.
  if (!isset($element ['#title'])) {
    $element ['#title_display'] = 'none';
  }
  $prefix = isset($element ['#field_prefix']) ? '<span class="field-prefix">' . $element ['#field_prefix'] . '</span> ' : '';
  $suffix = isset($element ['#field_suffix']) ? ' <span class="field-suffix">' . $element ['#field_suffix'] . '</span>' : '';

  switch ($element ['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= ' ' . $prefix . $element ['#children'] . $suffix . "\n";
      break;

    case 'after':
      $output .= ' ' . $prefix . $element ['#children'] . $suffix;
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
      break;

    if (strpos($element['#id'], 'edit-group-content-access-und') !== FALSE) {
      $output .= "<span class=\"switch-selection\"></span>\n";
    }

    case 'none':
    case 'attribute':
      // Output no label and no required marker, only the children.
      $output .= ' ' . $prefix . $element ['#children'] . $suffix . "\n";
      break;
  }

  if (!empty($element ['#description'])) {
    $output .= '<div class="description">' . $element ['#description'] . "</div>\n";
  }

  //only prints the wrapper for elements that are not radio elements
  if ($element['#type'] != 'radios' && $element['#type'] != 'radio') {
    $output .= "</div>\n";
  }

//  if (strpos($element['#id'], 'edit-og-group-ref') !== FALSE) {
  return $output;
//  }

//  dpm(strpos($element['#id'], 'edit-og-group-ref'));
//  if (strpos($element['#id'], 'edit-og-group-ref') !== FALSE) {
//  dpm(strpos($element));
//  return $output;
//  }

}

// function theme_radios (https://api.drupal.org/api/drupal/includes!form.inc/function/theme_radio/7)
function gonzo_radios($variables) {
  $element = $variables ['element'];
  $attributes = array();
  if (isset($element ['#id'])) {
    $attributes ['id'] = $element ['#id'];
  }
  $attributes ['class'] = 'form-radios';
  if (!empty($element ['#attributes']['class'])) {
    $attributes ['class'] .= ' ' . implode(' ', $element ['#attributes']['class']);
  }
  if (isset($element ['#attributes']['title'])) {
    $attributes ['title'] = $element ['#attributes']['title'];
  }
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element ['#children']) ? $element ['#children'] : '') . '<span class="switch-selection"></span></div>';

}

/**
 * Custom changes by Gonzo 13. 1. 2018 from https://drupal.stackexchange.com/questions/107311/eliminate-render-blocking-javascript-and-css-in-above-the-fold-content#107332
 * Implements hook_page_alter().
 */
function gonzo_page_alter(&$page) {
  // Get critical css file.
  $filename = FALSE;
  $current_path = current_path();
  $path = drupal_get_path('theme', $GLOBALS['theme']);
  // Detect frontpage.
  if (!$filename
    && drupal_is_front_page()
    && is_readable("$path/critical-css/urls/front.css")
  ) {
    $filename = "$path/critical-css/urls/front";
  }
  // Detect specific urls.
  if (!$filename
    && is_readable("$path/critical-css/urls/{$current_path}.css")
  ) {
    $filename = "$path/critical-css/urls/{$current_path}";
  }
  // Detection by node type.
  if (!$filename) {
    $object = menu_get_object();
    if (isset($object->nid)
      && is_readable("$path/critical-css/node_type/{$object->type}.css")
    ) {
      $filename = "$path/critical-css/node_type/{$object->type}";
    }
  }

  // Add inline critical css for front page.
  if (!empty($filename)) {
    $inline_css = advagg_load_stylesheet("$filename.css", TRUE);
    $page['content']['#attached']['css']["$filename.css"] = array(
      'data' => $inline_css,
      'type' => 'inline',
      'group' => CSS_SYSTEM - 1,
      'weight' => -50000,
      'movable' => FALSE,
      'critical-css' => TRUE,
    );
    // Add in domain prefetch.
    if (is_readable("$filename.dns")) {
      $domains = file("$filename.dns", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $domains = array_unique($domains);
      foreach ($domains as $domain) {
        advagg_add_dns_prefetch($domain);
      }
    }
  }
}

```

# Answer
TL;DR – Simply deactivate this behavior in Zurb's theme settings. See screenshot below.

---

The issue you mentioned already has a working patch attached that actually seems to fix the issue in Zen by adding a simple condition to the function in the base-theme that causes this unwanted behavior.

**Before the Zen patch**

```
if (isset($tag['#attributes']['type']) && $tag['#attributes']['type'] !== 'text/ng-template') {
  unset($tag['#attributes']['type']);
}

```

**After the Zen patch**

```
if (isset($tag['#attributes']['type'])) {
  if ($tag['#attributes']['type'] !== 'text/ng-template' && $tag['#attributes']['type'] !== 'application/ld+json') {
    unset($tag['#attributes']['type']);
  }
}

```

---

So all you have to do now is to go over to Zurb, create an issue, create a patch, add that patch to the issue, then patch your theme with that patch, done :)

Just look out for the `zurb_foundation_process_html_tag` function in Zurb's `template.php` and then write the same condition as above around the following responsible line:

**Before you created the Zurb patch**

```
// Remove type="..."
unset($el['#attributes']['type']);

```

**After you created the Zurb patch**

```
// Remove type="..."
if (isset($el['#attributes']['type'])) {
  if ($el['#attributes']['type'] !== 'text/ng-template' && $el['#attributes']['type'] !== 'application/ld+json') {
    unset($el['#attributes']['type']);
  }
}

```

---

Creating a patch for the first time might seem a little bit scary, but actually it's pretty simple. Just git clone the repo, checkout the branch you wanna apply this patch for, then change the code, then type `git diff` and define a filename where `XXXXX` is the number of the issue and `YY` is the comment number.

```
git diff > issue_title_or_short_description-XXXXX-YY.patch

```

See Making a Drupal patch with Git for more detailed info.

---

## Theme settings

Dayum, only after I wrote this whole long answer I became aware of this line in the code:

```
function zurb_foundation_process_html_tag(&$vars) {
  if (theme_get_setting('zurb_foundation_html_tags')) {

```

Means there are theme settings and you can simply **disable** "Prune HTML Tags":
> 1 votes

---
Tags: theming
---


# Question
Title: How do I restore the comment body field I deleted from a content type?
I deleted the comment body from the content type settings, and replaced it with another field. When posting comments, I get this error:

> Notice: Undefined property: stdClass::$comment\_body in function `comment_submit()` (line 2201 in file /modules/comment/comment.module).

Can this error be avoided?

It was needed to delete the field comment\_body becase field permissions are inherited for all the content types and that is why another field was created and this one was deleted.

# Answer
> 2 votes
* Create a random content type
* Restore the comment\_body field from existing field\`s, because it's existing now
* Delete the random content type

# Answer
> 1 votes
There is also a patch which actually needs review in Drupal Core concerning this issue: https://www.drupal.org/node/2717717

I applied it and it works.

# Answer
> 0 votes
First delete that field and clean Drupal's Cache, if that doesn't work just try to use this patch:

https://www.drupal.org/files/issues/1038652-comment-body-field-95-test-and-fix-D7.patch

# Answer
> 0 votes
I recovered comments with recreating the tables (take care: **all the comments will be removed**):

* comment,
* field\_data\_comment\_body,
* field\_revision\_comment\_body;

and reset statistics with:

```
UPDATE node_comment_statistics SET comment_count = 0;

```

Where to get SQL query to recreate them? Get it from another Drupal installation *with* comments.

---
Tags: comments
---


# Question
Title: Google Page Speed Insights recommends Leverage browser caching
Google complains on leverage browser caching on the following files:

```
Leverage browser caching for the following cacheable resources:
https://www.googletagmanager.com/gtm.js?id=GTM-xxxxxx (15 minutes)
https://www.googleadservices.com/pagead/conversion_async.js (60 minutes)
https://www.google-analytics.com/analytics.js (2 hours)

```

I have the following in my .htaccess file which should set all files to 2 weeks:

```
# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

```

I verified that I have the mod\_expires module enabled.

In Cloudflare I have Browser Cache Expiration set to 2 hours.

# Answer
> 3 votes
As these files ain't located on your server you can't do anything about it except wondering why Google Page Speed isn't smart enough to distinguish between on-site resources and external resources. Or why Google itself doesn't do with these files what it suggests should be done with them. I guess, that's some weird kind of paradox ;)

All you could do (highly hypothetically) is to download these files and add them to your own server and let Drupal use these local copies instead of the remote files. But I assume very strongly that this would break the functionality of these services.

---
Tags: .htaccess
---


# Question
Title: How to edit the content page fields column in the admin section?
In the admin section --\> Content menu displays all the contents of the site.

I want to have options (or atleast to know where I have to change) for adding and removing the columns in the content section.

# Answer
> 0 votes
I would say the easiest way is to install the admin views module (and its dependencies).

That module will replace Drupal core's implementation of that listing (and the taxonomy, comment, user and book listings) with a views based one. You can then edit the 'Administration: Nodes' view and change the columns ('Fields' in the Views UI) as you see fit.

Alternatively, you could create own custom view that uses the admin/content path, to override the core listing. That would have the same effect but would be a little extra effort in setting up the view.

# Answer
> 0 votes
You can use hook\_form\_FORM\_ID\_alter() and do your changes inside that.

Example:

```
function YOUR_MODULE_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
 // YOUR CUSTOM CODE GOES HERE
}

```

---
Tags: 7
---


# Question
Title: Execute some steps before REST POST request
I have created a custom content type and configured it to be created via REST POST method using REST client like POSTMAN or any frontend(like angularJS or react).

I want to execute few steps before creation of content type when a POST request is made. For example, make a SOAP call to SAP or make a query to external DB, and based on some condition like if data is received from SAP or external DB, then only content type should be created else it should throw some custom error.

I am new to Drupal and any guidance is welcome.

# Answer
> 0 votes
There is a hook called entity\_presave.

This is always called when you persist a new or updated entity through Drupal API. You can always check for the current request's method to see if it was a POST method (you can also check for the route itself). So these presave changes (or can be save or post save) will be only taken place if that criteria is met.

---
Tags: nodes, hooks, 8
---


# Question
Title: Show nodes contaning same company term in Views
I need to show a block on a node page which will show all nodes containing same company name taxonomy term.

What is the way to do it? I've tried adding a field\_company term relationship but it's not working.

A product whose company term contains Samsung so when this product(node) is viewed I want to display other products from same company Samsung.

# Answer
> 3 votes
Create a new block view either selecting the single content type or all. Now, we will add two contextual filters. Content Id and the field which has taxonomy term id.

Configure Content Id filter as follows:

1. Provide default value: Content ID from URL
2. Under More tab - Check next to Exclude

Configure field which has taxonomy term id as follows:

1. Provide default value: Taxonomy term ID from URL
2. Uncheck: Load default filter from term page
3. Check next to Load default filter from node page, that's good for related taxonomy block
4. Multiple value handling: Filter items that share any value.
5. Under more tab check: Allow multiple values.

That's it. After saving your view go to bock page and enable it where ever you want.

---
Tags: views, 8
---


# Question
Title: Declaration of DrushInputAdapter::hasParameterOption($values) must be compatible with Symfony
I have a Drupal 8 site set up with Acquia Dev Desktop on my localhost. I am using PHP 7.0.14; everything is working fine, and the site works perfectly.

I installed Drush 8. When I try to run `drush cr all`, I get this error message.

> PHP Fatal error: Declaration of Drush\Command\DrushInputAdapter::hasParameterOption($values) must be compatible with Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in /Applications/DevDesktop/tools/vendor/drush/drush/lib/Drush/Command/DrushInputAdapter.php on line 27

The lines causing the error are the following ones.

```
class DrushInputAdapter implements InputInterface {
    protected $arguments;
    protected $options;
    protected $interactive;

    public function __construct($arguments, $options, $command = false, $interactive = true)
    {
        $this->arguments = $arguments;
        $this->options = $options;

        // If a command name is provided as a parameter, then push
        // it onto the front of the arguments list as a service
        if ($command) {
            $this->arguments = array_merge(
                [ 'command' => $command ],
                $this->arguments
            );
        }
        // Is it interactive, or is it not interactive?
        // Call drush_get_option() here if value not passed in?
        $this->interactive = $interactive;
    }

```

With Drupal Console, I get something similar.

> PHP Fatal error: Declaration of Drupal\Component\DependencyInjection\Container::set($id, $service) must be compatible with Symfony\Component\DependencyInjection\ContainerInterface::set($id, $service, $scope = self::SCOPE\_CONTAINER) in /Users/josue/WebDevelop/drupal-8.4.0/core/lib/Drupal/Component/DependencyInjection/Container.php on line 47

# Answer
Updating to Drush 9, as suggested in the comment by user3346970, is certainly one solution to this problem. If you wish to stick with Drush 8, upgrade to version 8.1.15 or later. The problem you report above was fixed somewhere around version 8.1.12.

I'm not certain about the exact versions of Drupal Console to use with each version of Drupal, but I believe that you will probably also discover that updating to the latest version should resolve things as well. The error you are seeing indicates you are crossing Symfony version 2 (e.g. in an old version of Drush or Drupal Console) with Symfony version 3 (e.g. in Drupal 8.4.0 and later).
> 3 votes

# Answer
I have updated my drush version from 8.1.10 =\> 8.1.15 using below command and working fine.

> composer global update drush/drush
> 1 votes

---
Tags: 8, drush
---


# Question
Title: Why can't I save a Send HTML Email action?
I have a rule component set up that currently sends an HTML email. I need to change the body of the email to include a new field, but when I do and press Save, it doesn't return to the Rule page, it just goes to the top of the page and loses the changes I've made.

If I overwrite the HTML with a simple piece of text or a small piece of HTML, it works OK.

I'm wondering if there's some validation going on, but there are no error messages displayed or in the logs. I've validated the html through the W3C Validation Service and cleaned it up so there are only a couple of warnings.

My other thought is that maybe there's some limit that I've hit? The HTML is quite long, as it was generated by an online generator.

I can't include an export of the rule as it's too big for this message.

Any help?

I am using Drupal 7.59 and Rules v7.x-2.10; MimeMail v7.x-1.0. Have tried the latest dev version MimeMail too, but made no difference.

# Answer
> 1 votes
Thanks Pierre for your suggestion. I didn't need to try it, but it makes a lot of sense. Wish I'd have thought of it!

In the end (before I saw your suggestion), I rebuilt the email using a different generator tool, which seemed to produce much smaller and cleaner HTML. This works OK. It looks like there was either a problem with the HTML or there is some kind of limit on length.

# Answer
> 0 votes
You could try to add 2 Rules Actions, something like so:

* Add a variable of type text
* Set a data value for that variable, with value the HTML string.

While doing so, you have the Rules power available to include any relevant conditional logic. And if you then use the "replacement tokens" within the "Message type" you're working with (to make the value of your new variable available as a token in the message you want to create), you should be good to go.

Did I mention there is zero custom code involved?

---
Tags: 7, rules, mimemail
---


title: Rewrite Links Array to include Nesting

text:
# Question
Title: Rewrite Links Array to include Nesting
I'm attempting to modify the language switcher links in a block so that the items are properly nested per my site's menu structure.

Currently, it outputs:

```
<ul>
<li>English Link</li>
<li>Japanese Link</li>
<li>Spanish Link</li>
</ul>

```

I need:

```
<ul>
<li>English Link</li>
<ul>
    <li>Japanese Link</li>
    <li>Spanish Link</li>
</ul>
</ul>

```

The `$build['content']['#links']` array contains:

```
array (size=4)
  'en' =>
    array (size=5)
      'url' =>
        object(Drupal\Core\Url)[14062]
        ...
    'ja' =>
        array (size=5)
          'url' =>
            object(Drupal\Core\Url)[14062]

```

How can I modify this array so that elements are nested in a `ul` under the first link?

# Answer
In my experience, the structure you're looking for is created by the template layer. I would not recommend changing the link array directly. A good example template is core's stable theme's menu.html.twig. It uses a recursive twig macro to create nested lists.
> 1 votes

---
Tags: 8, theming
---


title: Installing the Waypoints plugin

text:
# Question
Title: Installing the Waypoints plugin
I’m using Drupal 8.5.4 and I have installed the Advanced CSS/JS Aggregation module. I’m trying to install the Waypoints plugin without success via the module: jQuery waypoints (still on alpha1 for D8). Is there a way to simply install the plugin manually?

# Answer
Yupp, simply download the Waypoints library, extract and rename the folder to just `waypoints`, then put it into `themes/custom/MYTHEME/libs` or into `modules/custom/MYMODULE/libs` and follow one of the following instructions:

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

---

Basically all you have to do is to create the corresponding `MYTHEME/MYMODULE.libraries.yml` file

```
waypoints:
  js:
    libs/waypoints/lib/jquery.waypoints.min.js: {}
  dependencies:
    - core/jquery

```

and then attach the library to all pages via `hook_page_attachments()` or `hook_page_attachments_alter()` inside the `MYTHEME.theme` or `MYMODULE.module` file.

```
<?php

function MYTHEME/MYMODULE_page_attachments_alter(&$attachments) {
  $attachments['#attached']['library'][] = 'MYTHEME-or-MYMODULE/waypoints';
}

```
> 2 votes

---
Tags: 8, javascript
---


# Question
Title: Trying to Conditionally Add JS File to page if in a paragraph block reference on that page
I am not sure how to accomplish this...

I want to have a custom block that I have created and referenced via paragraphs to implement code in that block and push it into the header of the page. The idea is that we want to have single pages that run specific JS files and this is the way for the content author to place these files on the pages that they want. If there is a better way to do it, I am open to suggestions.

Here is where I am now:

I have a custom block that I am referencing via paragraphs in pages that will house the JS files. I believe I need a preprocessor script for this, but I am having a lot of issues with figuring out what kind of preprocessor I need.

Here is what I have but I think it is totally wrong and definitely incomplete:

```
if ( isset($vars['content']['#block_content']) ) { // check for custom content
    if ($vars['content']['#block_content']->type[0]->getValue()['target_id'] == 'js_file_block') { // only run on js_file_block types

      $vars['foobar'] = $js_files_page; // export var to twig
    }
  }

```

I need to be able to make more than one file load if added to the block, and I need it to attach to the header of the page that the block is referenced from. Can anyone point me in the right direction?

I am sure I need to add a $routematch and other things but I am not sure.

# Answer
> 0 votes
In Drupal 8 `drupal_add_js()` as well as `drupal_add_library()` and `drupal_add_css()` were removed in favor of `#attached`. Means you now can use the `#attached` key in any render array or preprocess or build function to attach your library only where you need it. Please read the following articles on DO:

\[Docs\] Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

\[Docs\] Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

\[Forum\] Adding js to the block through module Drupal 8

---
Tags: 8, javascript, blocks, paragraphs
---


# Question
Title: Module ldap_sso lost when updating module to the new version
I am in a process of updating the drupal core and some of the modules **(quite deactualized)**. One of them is `ldap` module, on this server I have no way to update through the drupal administration page, currently the installed version is `ldap 7.x-1.0-beta12`, the system will follow me to install the ldap version `7.x-1.0-beta15`.

As I mentioned, the only way I have to update is manually, I have deleted the files from the server and I have placed the new ones with the version ldap `7.x-1.0-beta15`, when I run the update **(update.php)** it appears that there is a missing module called **ldap\_sso**, and effectively when I review the contents of the ldap module there is no internal module called **ldap\_sso**, but in the ldap version `7.x-1.0-beta12` if it is.

How can I update the module in this case?

Thanks

# Answer
I found the solution, In the mentioned version of ldap, ldap\_sso was removed to a separate project, I proceeded to compare the code in case there was any important difference and the result is that they are the same.

So I proceeded to download:

**ldap\_sso** from https://www.drupal.org/project/ldap\_sso/releases/7.x-1.0-beta15 and

**ldap** from: https://www.drupal.org/project/ldap/releases/7.x-1.0-beta15 (by suggestion of drupal)

Now these modules go separately and I ran the update and it did not give any problem.

regards
> 0 votes

---
Tags: 7, authentication-authorization
---


# Question
Title: How to set end date relative to start date in date range field
Is it possible to set the end date relative to the selected start date in a D8 date range field? I have a date range field that I use to specify an accounting period. The end date should now be put to one year minus one day from the selected start date. For example, the start date 2016-07-01 will give the end date 2017-06-30. How is this possible?

# Answer
> 1 votes
The current widgets in core for the Datetime Range module do not allow this.

You would need to create a custom widget for this. Off the top of my head, I would create one that extends `DateRangeWidgetBase()` and mostly mirrors what `DateRangeDefaultWidget()` does, except to collect a relative period in a plain text field for the end date. Then, add a `massageFormValues()` function to turn the relative date into an absolute one, and then call `parent::massageFormValues()`. You may also be able to do this with a `#process` callback on the end date element, but I forget which of the two runs first during form processing.

---
Tags: datetime
---


# Question
Title: How to use default field_image if value is not provided?
We are using Schema.org Metatag module to display meta tag attributes to the Article content type. We have a field that we using as an ImageObject using the `field_image` field. The `field_image` is setup so that if an image is not selected, then a default image will be displayed in the twig templates.

We had to add a `[node:field_image:large:url]` into the url field under ImageObject. When an image is selected, the correct url is added to the page. However, when the image is not selected (a default image should be used), the url field is displaying empty.

How to get the token to display the default value is the image is not added through the node edit process?

Current behavior:

```
"image" : {
  "@type" : "ImageObject",
   "representativeOfPage": "True",
}

```

Expected behavior (when image is not selected)

```
"image": {
  "@type": "ImageObject",
  "representativeOfPage": "True",
  "url": "https://path/to/default-image/large/cloud.jpg",
  "width": "400",
  "height": "260"
},

```

# Answer
Seems the default image procedure as it is now doesn't store a file ID or something more useful in that image field. Means the image field doesn't get populated properly.

What I'd try is to create a custom module that adds a config page with a form and a `'#type' => 'file_managed'`field. The resulting file ID on upload now becomes variable via `\Drupal::configFactory()->getEditable()->set()` (and together with the right config/install and settings YML files).

Then I'd alter the node form via `hook_form_BASE_FORM_ID_alter` (see comments) and add a custom validate and/or submit function. Maybe just an element validate callback on the image field. And then check on submit if this field is empty, and if so then retrieve the file ID from the config page via `\Drupal::config()->get()`, load the file and save it into the image field (maybe the file ID is just enough).

Now the image field should be populated properly and everything else should work as expected.

---

## Proof of Concept

OK I just tried what I wrote above and it's working quite fine. Except I didn't use the node form but `hook_entity_presave` instead to check if the image field is empty before setting the file ID retrieved from the settings value of the uploaded file on said config page.

1. Download or clone https://gitlab.com/leymannx/tdi
2. into `/modules/custom`.
3. Enable the module.
4. Go to `/admin/config/media/tdi` and upload a default image, save.
5. Now in your IDE or code editor open `/modules/custom/tdi/tdi.module` and
    1. update the bundle `if ($entity->bundle() == 'XX-YOUR-NODE-TYPE-HERE-XX') {`
    2. and the field name `$entity->get('field_XX-YOUR-FIELD-NAME-HERE-XX')->setValue([['target_id' => $fid]]);`
6. Save the module file.
7. Go to a node with an empty image field, edit and resave it, done.

On every node creation or update this module will check if the image field is empty and add a real managed image with a real file ID then. Now the metatag module should work just fine. If updating all nodes manually is too fiddly I'd recommend you let some code do that instead :)

I'm thinking about extending this approach to let admins choose content types and field names this default image should be set automatically. Maybe tomorrow ;)

---

## Alternatively

If this doesn't work or if it's just too messy, the next thing I'd try is to hook into `hook_page_attachments_alter` same as `schema_metatag_page_attachments_alter` does to actually attach its values to the HTML head, and try to alter the values there. Which might become messy as well, depending on what methods you have available when you get there or if all you get is just a string to be manipulated quick and dirty.
> 1 votes

---
Tags: 8, theming, entities, meta-tags
---


# Question
Title: Error on hook_theme_suggestions_HOOK_alter()
I am trying to set a custom theme suggestion for the item-list template. It does work but I am getting an error message:

User error: "attributes" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

Function:

```
function MYTHEME_theme_suggestions_item_list_alter(array &$suggestions, array $variables) {
  $moduleclass = str_replace('-', '_', $variables['attributes']['class']);
  $suggestions[] = 'item_list__' . $moduleclass;
}

```

Not sure what the probleme is here?

# Answer
Every time it calls the hook, the variables may or may not have the array key 'attributes' - so the error happens on certain hook call, but not others. It's easy to fix, just check if it exists

```
function MYTHEME_theme_suggestions_item_list_alter(array &$suggestions, array $variables) {
  if (!empty($variables['attributes'])) {
    $moduleclass = str_replace('-', '_', $variables['attributes']['class']);
    $suggestions[] = 'item_list__' . $moduleclass;
  }
}

```
> 0 votes

---
Tags: 8, theming
---


title: Listing variable values using drush

text:
# Question
Title: Listing variable values using drush
I would like to list the values of certain variables using Drush in order to make sure they are in fact the variables that I intend to add to my feature. It seems that some variables are parents which contain multiple children. I use a drush/features/git workflow with a purchased but customized theme and following is my example for clarity.

In my feature `myfeature_theme_helper` there are two variables that I exported to it: `theme__settings` and `theme_settings`. I want to be able to view what values each are storing so I can determine if they should be removed from my helper. One of them contains an active tab, for example, which is not a setting that I want to commit to code.

Thank you!

# Answer
> 2 votes
If you do

```
drush vget theme_THEMENAME_settings

```

it will give you all nested variables but **nested variables don't work**

```
drush vget theme_THEMENAME_settings.toggle_name
drush vget theme_THEMENAME_settings:toggle_name

```

so **the only way I found** to get nested variables is with the use of *grep*

so for my theme I would do something like this

```
drush vget theme_THEMENAME_settings | grep toggle_name:

```

or do further processing using cut to get just the value of this variable

```
drush vget theme_THEMENAME_settings | grep toggle_name: | cut -f2- -d:

```

where `theme_THEMENAME_settings` is my variable and `toggle_name` is the nested variable name

# Answer
> 1 votes
Even though I like grep a lot, I think it's worth adding new tools to the toolbox from time to time ;-) Using jq and JSON output (instead of Yaml that is the default), you can use:

```
drush vget --format=json theme_THEMENAME_settings | jq -r '.theme_THEMENAME_settings | .toggle_name'

```

or the slightly shorter

```
drush vget --format=json theme_THEMENAME_settings | jq -r '.[] | .toggle_name'

```

---
Tags: 7, drush, features, configuration
---


# Question
Title: How do I hide bulk operations form for a specified user role?
I have a view where I list user's own contents, this contains bulk operations. Users with "add article" permission can see this bulk operations thing but I would like to hide this bulk operations "form element" / "functions" for users in employee role.

How can I do this?

# Answer
> 4 votes
To remove the bulk operations "form element" use ViewExecutable-\>removeHandler in hook\_views\_pre\_view():

```
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_view().
 */
function rgr_main_views_pre_view(ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() === 'content') {
    $account = \Drupal::currentUser();
    $is_employee = in_array('employee', $account->getRoles());

    if ($is_employee) {
      $view->removeHandler($view->current_display, 'field', 'node_bulk_form');
    }
  }
}

```

This will hide the dropdown form elements, the checkbox in the row and the submit buttons.

# Answer
> 0 votes
You need to set the appropriate permissions for the employee role.

What you need to look for is not views bulk operations permission, or similar, what you really need is to uncheck the permissions related to nodes.

So if you uncheck the permissions for adding, editing and deleting content, then those bulk operations should be gone as well.

---
Tags: views, 8
---


title: Assign an action to a simple button

text:
# Question
Title: Assign an action to a simple button
I am trying to render a simple button with a submission handler. I tried two methods, and this is the code I used.

## First method

### mymodule.module

```
function mymodule_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity->bundle();
  if ($type == "property") {
    $build['#attached']['library'][] = 'mymodule/custom_styling';
    $build['mymodule_btn'] = [
      '#type' => 'submit',
      '#value' => 'Generate PDF',
      '#submit' => ['mymodule_generate_pdf'],
      '#weight' => -1,
    ];
   }
}

function mymodule_generate_pdf() {
  // ...
}

```

## Second method

### mymodule.module

```
function mymodule_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity->bundle();
  if ($type == "property") {
    $build['#attached']['library'][] = 'mymodule/custom_styling';
     return \Drupal::formBuilder()->getForm(Drupal\MyModule\Form\MyModuleForm::class);
  }
}

```

### MyModuleForm.php

```
namespace Drupal\MyModule\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Generate the button.
 */
class MyModuleForm extends ConfigFormBase {

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

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['mymodule_btn'] = [
      '#type' => 'submit',
      '#value' => 'Generate PDF',
      //'#submit' => ['mymodule_pdf_generate_pdf'],
      '#weight' => -1,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}.
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    // ...
  }

  /**
   * {@inheritdoc}.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // ...
    \Drupal::formBuilder()->submitForm('mymodule_form', $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
  }
}

```

The first method generates the button, but the submission handler is not executed. The second method doesn't even generate the button.

How can I fix the code I wrote?

# Answer
> 0 votes
In Method 2 you want to add the form as an element in the $build array.

Should be something like this:

```
$build['my_form'] = \Drupal::formBuilder()->getForm(Drupal\myModule\Form\myModuleForm::class);

```

Also you don't need to return anything, `$build` is passed by reference, so anything you add to it will stick.

---
Tags: 8, forms
---


# Question
Title: How to mandate the password policy in custom form fields?
I have custom form which has password field values and by using that user will be created in our website. So the requirement is to use password policy module functionalities to this form also. The form is able to show the policies below the password field and now those suggestions like use alphanumeric etc.. are not mandatory. But how I can mandate the password must contain alphanumeric etc etc... Please help me in this regard.

# Answer
> 0 votes
You can use the 'password\_confirm" #type in your form to get the exact field Drupal uses.

Add this to your Form function.

```
$form['account']['pass'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#description' => t('To set or change the password, enter the new password in both fields.'),
    );

```

This will give you the field, javascript and the validator without any extra code.

---
Tags: 7, users, forms
---


title: Override config per role

text:
# Question
Title: Override config per role
I have implemented a service with the tag `config.factory.override`. In my class I check if the current user is logged in, and if so I change the `system.site.page.front` variable to a different page. This kind-of works, but I have a problem with cache. If the first user to visit my site is not logged in that frontpage will be used for everyone, and if a logged in user is first, that version is used for everyone.

This is my current attempt at the `getCacheableMetadata`:

```
/**
 * {@inheritdoc}
 */
public function getCacheableMetadata($name) {
  $metadata = new CacheableMetadata();

  $metadata->setCacheContexts([$this->isLoggedIn ? 'user.roles:authenticated' : 'user.roles:anonymous']);

  return $metadata;
}

```

# Answer
> 2 votes
As @4k4 commented, I don't think that works.

I'd suggest you either use Page Manager/Panels, which allows to create a page with multiple displays and conditions like based on the user role.

Alternatively, you could create your own controller and return the desired page.

I don't know what you want to do exactly, but yet another option would be to keep two separate pages and redirect authenticated users to the different frontpage. That's similar to how drupal.org works, where you can configure whether your front page should be the default or your dashboard as an authenticated user.

---
Tags: 8
---


# Question
Title: Getting field label with entity_metadata_wrapper
Say I am iterating through a list of field names, and I have loaded a particular node using entity\_metadata\_wrapper().

```
$wrapper = entity_metadata_wrapper('node', $node);

```

Shouldn't I be able to just grab the label by using the following command?

Or is this not the correct command to do what I want?

```
        foreach($field_names as $item)
        {
           $label = $wrapper->$item->label();
        }

```

Here's the field as it is in the actual node:

```
'field_grade_comment' =>
    array (size=13)
      'default_value' => null
      'description' => string '' (length=0)
      'display' =>
        array (size=4)
          'default' =>
            array (size=5)
              ...
          'email' =>
            array (size=5)
              ...
          'teaser' =>
            array (size=4)
              ...
          'node_reference_embedded_view' =>
            array (size=4)
              ...
      'label' => string 'Grade Comment' (length=13)

```

# Answer
How about this?

```
$wrapper = entity_metadata_wrapper('node', $node);
$fields = $wrapper->getPropertyInfo();

foreach($fields as $field => $info) {
  $label = $info['label'];
}

```
> 3 votes

# Answer
```
$entity_type = 'node';

$bundle_name = 'article';

$field_name = 'field_some_field';

$info = field_info_instance($entity_type, $field_name, $bundle_name);

$label = $info['label'];

```
> 0 votes

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


# Question
Title: Make canonical URL in document HEAD absolute
I have a requirement to use absolute URLs for the canonical URL element generated by Drupal 8.

`hook_page_attachments_alter` doesn't seem to have access the HTML element. Is there any other way I can access it?

# Answer
True, for nodes you can't use `hook_page_attachments_alter`. You have to use `hook_ENTITY_TYPE_view_alter`!

And very likely you also find all of them in the end in `hook_preprocess_html`.

Here's how I got it working:

```
/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function MYMODULE_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if (isset($build['#attached']['html_head_link'])) {
    foreach ($build['#attached']['html_head_link'] as $key => $head) {
      if ((isset($head[0]['rel']) ? $head[0]['rel'] : FALSE) == 'canonical') {

        $url = \Drupal\Core\Url::fromRoute('<current>', [], ['absolute' => 'true'])
          ->toString();

        $build['#attached']['html_head_link'][$key][0]['href'] = $url;
      }
    }
  };
}

```

Source: How to remove specific meta-tag from header section of page?

---

Alternatively you can use Metatag. All you have to do is to set the `[node:url:absolute]` token into the Canonical URL form field in the Advanced section of the Metatag configuration for all Content.

And only then, all of sudden, they become available to be preprocessed in `hook_page_attachments_alter`. There I removed their trailing slash which gets added by default.

```
/**
 * Implements hook_page_attachments_alter().
 */
function MYTHEME/MYMODULE_page_attachments_alter(array &$attachments) {

  // Remove trailing slash from canonicals.
  foreach ($attachments['#attached']['html_head'] as $key => $head) {

    if ((isset($head[1]) ? $head[1] : FALSE) == 'canonical_url') {

      $href = isset($head[0]['#attributes']['href']) ? $head[0]['#attributes']['href'] : FALSE;

      if ($href) {
        $attachments['#attached']['html_head'][$key][0]['#attributes']['href'] = rtrim($href, '/');
      }
    }
  }
}

```
> 3 votes

---
Tags: 8, uri
---


title: Print view in twig template

text:
# Question
Title: Print view in twig template
My page--front.html.twig is working ok. I want to print the block\_1 display of the recent\_comments view. I tried this but it does not seem to work.

```
{{ view.comments_recent(block_1) }}

```

# Answer
> 4 votes
You can preprocess a new variable and use `views_embed_view` like:

```
$variables['my_view'] = views_embed_view('view_id', 'display_id');

```

So in your case:

```
$variables['my_view'] = views_embed_view('comments_recent', 'block_1');

```

And then in the twig file:

```
{{ my_view }}

```

See views\_embed\_view. It can also take arguments.

# Answer
> 2 votes
You want the Twig Tweak module. It provides a function to render a view directly in a twig template without the need for preprocessing.

https://www.drupal.org/project/twig\_tweak

It also provides a few other functions which might come in handy.

---
Tags: views, 8, theming
---


title: remove link tags in head

text:
# Question
Title: remove link tags in head
I am working on a project involving migrating a site with many static pages to Drupal 8. Since a number of the pages are old blog posts, there's often broken links, broken images, etc.

For quality assurance, we are using the httrack command line tool to traverse the new Drupal 8 site and report broken links and images.

It turns out that Drupal 8 is putting some extra `<link>` tags in the page head (the `<head>` section of the html, not the header region or anything like that).

First, when there is a page with a taxonomy term in it, there are links to the term's admin pages in the head, like so:

```
<link rel="devel-definition" href="/devel/taxonomy_term/226/definition" />
<link rel="clone-form" href="/entity_clone/taxonomy_term/226" />
<link rel="token-devel" href="/taxonomy/term/226/devel/token" />
<link rel="display" href="/taxonomy/term/226/manage-display" />

```

These links are on the page even for anonymous users.

Second, we have media images in our pages, and they are getting weird head link tags, also. For instance, if we have the image `inside-a-classroom.jpg`, we'll have this: `<link rel="image_src" href="Inside A Classroom" />`.

The problem is, httrack is finding these links in head, trying to download them, and returning a 404. And of course it would, because when it spiders, it's not logged on and can't access admin menus. In the case of images, they're not even proper links to the image.

Is there any way we can turn these off? They are false negatives in our scraping, and make it difficult to quality check our work.

# Answer
Links like this are handled as attachments to the page. They are inserted where the Drupal placeholder tags (like head-placeholder) are in the twig file.

To modify these, you need to use hook\_page\_attachments\_alter(). Here's example code that fixes a problem with canonical URLs containing query string not getting generated properly by core (converts & to &).

```
/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(array &$attachments) {
  if ( isset($attachments['#attached']['html_head'])) {
    foreach ($attachments['#attached']['html_head'] as $key => $item) {
      if (in_array("canonical_url", $item)) {
        $href = $item[0]['#attributes']['href'];
        $attachments['#attached']['html_head'][$key][0] = [
          '#type' => 'inline_template',
          // Formatted to include a newline in page source.
          '#template' => "{{ href|raw }}
",
          '#context' => [
            'href' => '<link rel="canonical" href="' . $href . '"/>',
          ]
        ];
      }
    }
  }
}

```

In the case of these entity links, these are in the 'html\_head\_link' area of the attachments.

FYI - This is also related to this core issue.
> 1 votes

---
Tags: 8, performance
---


# Question
Title: How to alter a main menu link path programatically drupal 7?
In my case, My site URL is www.example.co.uk and also have a content page www.example.co.uk/bbc.

There is a menu link called **BBC** with *https://www.bbc.co.uk* under my **menu menu** menu link list. I can change the link from backend but how I alter that link-path programmatically?

I want to change "www" depending on sites, like if it's on test site then the link should be ***wwwtest.bbc.co.uk*** or in develop then ***wwwdev.bbc.co.uk*** .

# Answer
> 0 votes
```
/**
 * Implements template_preprocess_menu_link().
 */
function my_module_preprocess_menu_link(&$variables) {
  $element = !empty($variables['element']) ? $variables['element'] : array();
  if (!empty($element['#title']) && $element['#title'] == 'BBC') {
    $url = $variables['element']['#href'];
    $url_parts = parse_url($url);
    $path = $GLOBALS['base_url'] . $url_parts['path'];
    $options = array();
    foreach (array('query', 'fragment') as $part) {
      if (!empty($url_parts[$part])) {
        if ($part == 'query') {
          $option = drupal_get_query_parameters(drupal_get_query_array($url_parts[$part]));
        }
        else {
          $option = $url_parts[$part];
        }
        $options[$part] = $option;
      }
    }
    $variables['element']['#href'] = url($path, $options);
  }
}

```

---
Tags: 7, navigation
---


# Question
Title: Comparing node creation and modification dates in twig
I want to compare a node's creation date and modified date in Twig, and it drives me bonkers. I've looked at various examples and snippets as part of this, this, this or this external source.

Using Drupal 8, Bootstrap 3, Bootstrap Layouts, Display Suite, and a custom sub-theme, I have a twig template customising what is going to be displayed and how. This custom template is a copy of the default bootstrap layouts 1 column template.

Within the template, I can access and print the dates using this:

```
{{ main.content.node_changed_date }}
{{ main.content.node_post_date }}

```

and all is well.

However, I want to compare the dates in my template like so:

```
{% if main.content.node_post_date|date('Y-m-d') > main.content.node_changed_date|date('Y-m-d') %}
    {{ main.content.node_post_date }}
{% endif %}

```

But this barks at me with the following error:

```
The website encountered an unexpected error. Please try again later.
TypeError: DateTime::__construct() expects parameter 1 to be string, array given in DateTime->__construct() (line 455 of /home/michel/devel/vendor/twig/twig/lib/Twig/Extension/Core.php).

DateTime->__construct(Array, Object) (Line: 455)
twig_date_converter(Object, Array, Object) (Line: 380)
twig_date_format_filter(Object, Array, 'Y-m-d') (Line: 77)

```

Yes, I use Composer to manage my installation.

What am I doing wrong?

*Pulling my hairs*

Michel

# Answer
> 1 votes
You can't compare render arrays. To compare fields better use raw values stored in the node:

```
{% if node.getCreatedTime > node.getChangedTime %}
    ...
{% endif %}

```

(The comparison doesn't make much sense, probably you want to swap both dates)

The `node` object is available in node and page templates. In other templates you might find it in a deeper level. If not and the node is displayed as main content you can add it in preprocess:

```
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
  }

```

---
Tags: 8, theming
---


# Question
Title: Taxonomy term doesn't show up in admin/structure/taxonomy/manage/tags/overview
I migrated a Drupal 6 site to Drupal 8. Current running version is: 8.5.3 I created 4 terms in the Tag taxonomy and referenced in the content type Article.

The terms, however, do not show up in the overview page.

>

They are in the database.

>

They are also visible when creating nodes.

>

How do I fix this?

# Answer
> 2 votes
It sounds like they are missing parent value of 0 in the term hierarchy table. That will do it. That table just needs the tid and parent value of '0'. Try it by adding one of the tag term tids to that table, clear the cache and reload that page. This is easy to miss in migrations.

---
Tags: taxonomy-terms
---


# Question
Title: Firefox is caching ajax form values from previous submit after if I press the browser back button
I've implemented a custom multistep AJAX form like:

STEP #1 Question 1: A or B (radiobutton Ajaxified) -\> AjaxCallback: step + 1

STEP #2 Question 2: C or D (radiobutton Ajaxified) -\> AjaxCallback: step + 1;

STEP #3 Question 2: E or F (radiobutton Ajaxified) -\> redirect to other page (ajax command)

Everything works as expected but after being redirected to the new page if I click the browser back button in firefox the form shows the first step with the option \[A\] selected of the first step. This does not happen in Chrome.

I'm running Firefox 54.0.1

Does it make sense to anyone? How could I fix it?

Thanks in advance!

# Answer
> 2 votes
It seems chrome makes a refresh of the page and firefox a cache. Seeing this question the reasons are answered here

You can try disabling caches using http headers: https://stackoverflow.com/questions/13640109/how-to-prevent-browser-cache-for-php-site

# Answer
> 2 votes
On Drupal 8, I was having an issue with Firefox that was caching the value of a field, selected by the user before refreshing the page.

It was basically overriding the #default\_value of the field.

My solution was to Turn Off Form Autocompletion (https://developer.mozilla.org/en-US/docs/Web/Security/Securing\_your\_site/Turning\_off\_form\_autocompletion).

You can do it at the level on the input if that's an , but since it was a in my case I had to do it at the form level :

```
$form['#attributes']['autocomplete'] = 'off';

```

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


# Question
Title: #default_value Not Working In Select Field
First off, I have tried to do my homework before coming here. I have referenced this, and this and I still cannot get my code to work.

I am simply trying to set a default value in a select form field on a Drupal 8 block configuration form. Here are the relevant parts of my code:

```
$options = array(
  'test' => 'value',
  'random' => 'string',
  'kiwi' => 'pear',
);

$form['menu_selected'] = array(
  '#type' => 'select',
  '#title' => 'Test Title',
  '#description' => 'Test Description',
  '#options' => $options,
  '#default_value' => 'random',
);

```

The $form then gets returned as per usual in a block build. Everything else works in the form; The options populate, the description and title display. The only thing that doesn't work is the default value. I have tried using keys and values. I even saw a comment that said to use '#value' instead of '#default\_value' and still it didn't work. Can someone please tell me what I'm doing wrong? I can provide more code if needed.

# Answer
Your code is absolutely correct but if it not work then also try one thing as

```
$options = array(
  'test' => 'value',
  'random' => 'string',
  'kiwi' => 'pear',
);

$default = 'random';

$form['menu_selected'] = array(
  '#type' => 'select',
  '#title' => 'Test Title',
  '#description' => 'Test Description',
  '#options' => $options,
  '#default_value' => $default,
);

```

I hope it will helpful.
> 2 votes

# Answer
On Drupal 8 form, I was having an issue with Firefox that was caching the value of a select field, selected by the user before refreshing the page.

It was basically overriding the #default\_value of the field.

My solution was to Turn Off Form Autocompletion (https://developer.mozilla.org/en-US/docs/Web/Security/Securing\_your\_site/Turning\_off\_form\_autocompletion).

You can do it at the level on the input if that's an input, but since it was a select in my case I had to do it at the form level :

```
$form['#attributes']['autocomplete'] = 'off';

```
> 7 votes

---
Tags: 8, forms
---


# Question
Title: Topics are not getting associated with forum
I am testing out the Drupal 8 core Forum module. I am using a theme that I based off of Acquia Lightning. I have successfully installed the module and added Containers, Forums and Topics. My issue is that the Topics I create don't seem to get associated with the Forum taxonomy. In other words, when I go to /forum I see my containers and forums but every forum has Topics: 0, Posts: 0, Last Post: n/a.

I have tried clearing cache, running cron, looking at the watchdog logs but nothing seems to indicate why it isn't working. I am not receiving any memory errors, white screen of death, etc. All other site functions seem to work properly: I can save content and taxonomies, create new views, assign blocks, etc.

See the attached screen grab. I could use some ideas on what might be causing this. Any assistance would be greatly appreciated.

# Answer
> 0 votes
Try:

```
drush state:set comment.maintain_entity_statistics TRUE

```

Explanation:

core/modules/comment/src/CommentStatistics.php in the update() function says this:

```
// Allow bulk updates and inserts to temporarily disable the maintenance of
// the {comment_entity_statistics} table.
if (!$this->state->get('comment.maintain_entity_statistics')) {
  return;
}

```

In my case, somehow this was not set, causing this function to bail out and not update the comment\_entity\_statistics table. Drupal needs this table updated to display the proper forum posts.

"drush state:get comment.maintain\_entity\_statistics" can be used to check if this is already set.

---
Tags: 8, nodes
---


title: Unpublish node instead of deleting it

text:
# Question
Title: Unpublish node instead of deleting it
In my web application, I would like to prevent accidental or unauthorized deletions or modifications (e.g. a student steals teacher's credentials and deletes or changes bad marks). But, at the same time, I'm trying to keep the interface as easy and straightforward as possible.

I've already enabled node revisions, so if a mark is changed we can restore the previous state, but I also hid the revision message, because it confuses non-techie teachers.

The next step would be transparently prevent mark deletion. The user should see and use the "Delete" button and the deletion confirmation page, but when confirming, Drupal should not delete the node and just unpublish it. Is this possible to do?

(I would then create a view to see/administer the revised/unpublished nodes, to check unauthorized modifications)

# Answer
Use hook\_node\_delete. This hook is being invoked right before node deletion.

```
function YOURMODULE_node_delete($node) {
  if ($node->type == 'NODETYPE') {
    $node->status = 0;
    node_save($node);
    unset($node);
  }
}

```
> 1 votes

# Answer
I fixed the unset() problem using a redirect

`$node->status = 0;
node_save($node);
drupal_set_message(t('The node has been deleted.'));
drupal_goto('node/');
exit();`
> 0 votes

---
Tags: 7, nodes, users
---