title: Custom Block in custom 404 node

text:
# Question
Title: Custom Block in custom 404 node
I have a node.

This node is set to be the 'Default 404 (not found) page' in

> admin/config/system/site-information

I've got a custom block that I want to show within the node mentioned previous. I have used the 'restrict to certain pages' feature in configure block.

The problem is that it is not showing whenever I trigger a 404.

Can anyone offer a solution?

Thanks in advance.

# Answer
The page you configure for a 404 code in admin/config/system/site-information is not a redirect to the new path, it reuses the original request and keeps the path. You see this in the browser, where the url remains unchanged when the custom 404 page is invoked. So you can't use the path from the 404 page to control the visibility.

See this feature request: Allow blocks to be configured to show/hide on 403/404 pages. I doubt that there will be any progress soon, because there is no activity for some time and the patch no longer applies.

You could implement the block visibility in a custom condition plugin or if you are looking for a simple solution do this in preprocess on theme level.

Or what I would prefer use a custom controller instead of a block, create a route to this controller and put this in the site settings.
> 2 votes

# Answer
Just override theme\_page function then call phptemplate\_page right after from your template.php file.

Remember to rename "YOURTHEME\_page" with the name of your theme.

```
function YOURTHEME_page($content, $show_blocks = TRUE) {

// Set additional conditions to change $show_blocks if you want here..
  // The following will always set $show_blocks to TRUE.
  $show_blocks = $show_blocks ? $show_blocks : TRUE;

`// phptemplate_page is what gets called usually but the
  // theme function allows us to override it with the themes' name.
  // We're calling it directly here so we don't have to copy tons of code.
  return phptemplate_page($content, $show_blocks);
}`

```

To see why this works Look at this function. http://api.drupal.org/api/5/function/theme

If the only reason your trying to show the blocks is so it doesn't break your layout, then consider using the $layout var to set a body class. With some css knowledge it can be easily be fixed and you don't burden your sever with unnecessary load from rendering the sidebars.
> 0 votes

---
Tags: nodes, 8, configuration
---


title: How to override form id of Webform?

text:
# Question
Title: How to override form id of Webform?
I want to override form\_id of webform in Drupal 7. Example my webform form id is `webform_141` and I want to override it to `webform_en` or `webform_uk`.

Is it possible?

**Note**: I need to override it for multilingual site.

# Answer
> 2 votes
You can simply do following way, using hook\_form\_alter, paste following code in your `template.php` file, save and clear cache. Change the THEME with your themeName in code or if you are doing with costume module then with module name.

In your case the code will be,

```
function THEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_141') {
    $form['#id'] = 'webform_en';
  }
}

```

# Answer
> 1 votes
You can use hook\_form\_alter.

E.g:

```

/**
 * Implement hook_from_alter
 *
 * @param type $form
 * @param type $form_state
 * @param type $form_id
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   $form['#form_id']='webform_en';
}

```

# Answer
> 1 votes
```
/**
 * Implement hook_from_alter
 *
 * @param type $form
 * @param type $form_state
 * @param type $form_id`enter code here`
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'webform_141'){
    $form['#form_id'] = 'webform_en';
    $form['#form_id'] = 'webform-en';
    $form['form_id']['#value'] = 'webform_en';
    $form['form_id']['#id'] = 'webform_en';
   }
}

```

---
Tags: 7, hooks, webforms
---


# Question
Title: How to Import content without affecting existing contents
I have installed Data export and import

.i created nodes dataset file using above module and copied that file and pasted in another drupal site. when i import using that dataset file,it is replacing already existing contents. is it possible to import without affecting existing contents.

# Answer
Looking at the modules in question it states that the purpose is "...to export data from a site into datasets. These datasets are then imported into another site in such a way that the two sites end up with EXACTLY THE SAME DATA INCLUDING ID NUMBERS."

Looking at the drush commands the module provides there are not arguments to maintain any 'current' data. It will force the state of the dataset.
> 0 votes

---
Tags: importing-exporting
---


# Question
Title: Views search for term reference in field collection
I have content type where tagged persons names are automatically saved as a taxonomy term. These created terms have a field, which is a field collection of a date and another taxonomy term which keeps information about the unit. What I'm trying to achieve is, to search for nodes via the unit taxonomy term which will bring up nodes where persons from this unit are tagged. I have no clue how to get it work. I guess somewhere under relationships or contextual filters should be the options but so far I wasn't able to figure it out.

Node

* title
* Person (taxonomy term)

+ date / unit (taxonomy term in a field collection field of taxonomy term above)
* image

# Answer
I've solved it by adding a relation with the field which holds the taxonomy term data for persons. A second relation needed to be added, this time related to the field collection name. This way I'm now able to expose the field which holds the job data as a search option.
> 0 votes

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


title: create order - drupal commerce

text:
# Question
Title: create order - drupal commerce
I'm developing an eCommerce website using Drupal Commerce. I've been asked from my management to allow several users to use the 'create order' page in the admin store section (orders page) to stimulate sales.

The 'create order' page is sufficient by itself, but adding a product (line item) isn't that friendly, so I need to figure out a way to develop a 'browse products' function that'll allow me to add products to the order I'm creating.

Is there an easy way to do so? Maybe creating an all new 'create order' page? If so, what is the best appraoch without changing the drupal core code?

# Answer
Of course you can create custom order form and page in new custom module. I think you understand drupal 7 FORM API, so you have to create new page with form. You can process form values (i mean in form submit funtion) using entity API.

To create an order for current user:

```
global $user;

$order = commerce_order_new($user->uid, $status = 'pendig', $type = 'commerce_order');
commerce_order_save($order);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

```

To add billing info:

```
$profile = new stdClass();
$profile->type = 'billing';
$profile->uid = $user->uid;
$profile->status = '1';

$profile->commerce_customer_address['und'][0]['country'] = $your_country;
$profile->commerce_customer_address['und'][0]['locality'] =$your_locality;
$profile->commerce_customer_address['und'][0]['postal_code'] = $your_postal_code;
$profile->commerce_customer_address['und'][0]['thoroughfare'] = $address;
$profile->commerce_customer_address['und'][0]['first_name'] = $first_name;
$profile->commerce_customer_address['und'][0]['last_name'] = $last_name;

commerce_customer_profile_save($profile);

$order_wrapper->commerce_customer_billing = $profile->profile_id;

```

Then you can add products to this order:

Presume that $products is an array of arrays of products ids and quantity of this product user is buying (EG.

```
$products = array(
array('product_id' => 22, 'quantity' => 1),
 array('product_id' => 23, 'quantity' => 3),
);

foreach ($products as $item) {
$product = commerce_product_load($item['product_id']);
$line_item = commerce_product_line_item_new($product, $item['quantity'], $order->order_id);
commerce_line_item_save($line_item);
$order_wrapper->commerce_line_items[] = $line_item;

}
//to save line items and billing info in your order
commerce_order_save($order);

```
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How to store a nodes Fivestar average rating inside another field with computed fields
In order use rating to sort on inside search api, i'm trying to store the fivestar decimal value inside another field that can be indexed. This is because Fivestar doesn't play nice with search\_api, so this will be a workaround.

I have a computed field that performs different tasks on the node such as copying the field\_review\_votes\_average to field\_index\_review\_score. I'm using this code to do so.

```
$entity->field_index_review_score[LANGUAGE_NONE][0]['value'] = $entity->field_review_votes_average[LANGUAGE_NONE][0]['average'];

```

But I keep getting ***Notice: Undefined index: und***, what code can I use to to retrieve the average score?

# Answer
Eventualy I used a different methode to get the average value. Here's how

```
 //Get average rating and place in index review score
    $average_field = field_view_field('node', $entity, 'field_review_votes_average');
    $rating = $average_field['#items'][0]['average'];
$entity->field_index_review_score['und'][0]['value'] = $rating;

```
> 0 votes

---
Tags: entities, rating
---


# Question
Title: How to tell what filename to select when using twig debugging in drupal 8 theming
this is my second week with drupal 8 (or drupal in general). I want to be a drupal developer and contributer to the modules and themes community. However, I am a little lost with the file name suggestions shown in this image.

When reading books and tutorials, i see the author suggesting we use one of the filename suggestions shown, but how do you know which one to select? So like in that list, the author switched from the default selected which is the last one, to the second from top. What criteria did he use to determine which is best? Thanks in advance.

# Answer
> 1 votes
It depends on how specific you want to get. If you made a template for block.html.twig it would effect every block. block--system.html.twig would effect all of the system blocks, and block--system-branding-block.html.twig would effect the every branding-block subset of the system-block. And block--octo-branding.html.twig could possibly be every block that is using the octo-branding block plugin.

I'm not positive what template is what in your case since I don't know what is named what in your theme and plugins, but that's my best guess. Regardless the rule of thumb is it goes from most specific to most broad in order. And Drupal will use whatever template is most specific that applies in every case. For example.

I have a basic page located at /node/18. Near the top it says

```
<!-- FILE NAME SUGGESTIONS:
   * page--node--18.html.twig
   * page--node.html.twig
   x page.html.twig-->

```

If I made a template for page.html.twig, it would load that template for every page. If I made a template for page--node.html.twig it would use that template for every page for nodes. If I made a page--node--18.html.twig it would use that template only for that specific node. If I've already made any combination of those templates Drupal will use the most specific one.

---
Tags: theming, 8
---


title: Taxonomy terms display

text:
# Question
Title: Taxonomy terms display
I want to display all taxonomy terms hiearchicaly exactly like it is displayed in the administration.

Here is the sccrenshot of the administration of the taxonomy and i want to display + the titles of the articles (not included in the screenshot) the exact same thing to the users on the front-end of my drupal website.

# Answer
To build this structure there is quite some code necessary. You can see this in Drupal\taxonomy\Entity\Vocabulary::buildForm().

It might be easier to reuse the code that builds the admin page.

Load the admin form for the terms overview:

```
$vocabulary = \Drupal\taxonomy\Entity\Vocabulary::load('tags');
$form = \Drupal::formBuilder()->getForm('Drupal\taxonomy\Form\OverviewTerms', $vocabulary);

```

Extract only the terms, as we don't need the rest of the form:

```
$terms = $form['terms'];

```

Then you can remove things you don't need, for example the operations:

```
  foreach ($terms as $key => &$term) {
    if (strpos($key, 'tid:') === 0) {
      if (isset($term['operations'])) {
        unset($term['operations']);
      }
    }
  }
  unset($term);

```

This will result in a table, where there is still the drag and drop javascript active. You can do more housekeeping, until you have the result you want.

The pager of this form should still work, so you can display the second page by appending "?page=1" to the url.
> 1 votes

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


# Question
Title: How to customize pagination for the taxonomy term view page for different vocabulary?
I have 3 vocabularies as shown in this screenshot:

And I have default *Taxonomy term* view page with 10 items per page as shown in this screenshot:

I want to display 12 items per page only for the *taxonomy term pages* which are related to the *terms* of *Categories* vocabulary. Should I create new *Taxonomy term* view page for *Categories* vocabulary or is it possible to configure pagination using *HOOK\_preprocess\_taxonomy\_term* ?

# Answer
> 2 votes
I've used the Taxonomy Views Integrator module which helped me set custom pagination and view modes by creating *taxonomy view page* for different taxonomy terms and vocabularies. Some details about this module (from its project page):

> The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabulary.
>
> TVI will try not to interfere with views or taxonomy/term page displays if no TVI views exist for the current page request.

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


# Question
Title: Bizarre Behavior with Markdown Filter and Cache Clearing
We are trying to allow Markdown input on long text fields for certain content types. It is proving difficult. Here is what I have done:

1. Installed Markdown filter module.
2. Added a new Text Format in Configuration -\> Content Authoring -\> Text Formats.
3. Edited the text fields on our "Lesson Plan" content type so that the user can select "Markdown" text format.

That should be everything I have to do, right?

---

**BUT WAIT --** number 2 above is giving me very strange behavior!

* In my "Markdown" text format configuration page, I can't see the Markdown option *unless I first clear all the caches while I am on that page*.
* After I have cleared the cache, the Markdown checkbox shows up, and I can select it.
* But after hitting "Save Configuration", *the option disappears*, and none of my content formats correctly when I try to select the Markdown text format.

Why is this happening? I don't know where to start looking!

# Answer
I fixed the problem. I don't know why it acted the way it did, but it started working after I deleted the markdown folder in sites/all/modules, and re-installed using the "official" /admin/modules page (which is SSL enabled).
> 1 votes

---
Tags: 7, caching, input-formats
---


# Question
Title: Is it possible to use many plugin process for a field?
I'm working with migrate and I need to use multiple plugins for a single process.

is it possible? How?

# Answer
> 4 votes
Yes, process plugins can be chained - see the documentation under "The full pipeline".

---
Tags: 8, migrations
---


# Question
Title: Drupal alter some javascript of contrib module?
I am working on a project that implements the Drupalchat module. Everything works perfectly, but the client requests some custom changes.

They want people to be unable to have private conversations with eachother, but they do need to be able to see eachother!

They can only chat in the public chatroom, that Drupalchat provides by default.

A moderator user (drupal user role) however can chat privately with other users.

Is there a clean way to "hook" into the drupalchat.js file and alter the behaviour for this?

I have found the portion of code that needs to be altered, but of course I don't want to hack the contrib module.

I tried IRC about this, but nobody seemed to have a clue how to implement this.

Anyone done something like this in the past?

Thanks in advance!

# Answer
> 0 votes
I believe this has already been answered here: How to override jQuery from contrib module

To override the JavaScript file added to a page from a module, you need to implement hook\_js\_alter()....

---
Tags: javascript
---


# Question
Title: Token to show all the comments including comment body for a node
I am trying to set up a notification email using rules that will email a forum topic with all the comments including the comment titles and body.

The Message text I have so far is:

> A new forum comment has been posted by \[comment:author:profile-main:field-name\] with the following details
>
> \[comment:node:title\]
>
> \[comment:node:body\]
>
> Comments:
>
> \[comment:node:comments\]

However, the final token, `[comment:node:comments]`, only shows the comment titles and not the comment body.

Is there a way that I can show the full list of comments including the comment body?

# Answer
> 0 votes
To solve your issue you can create custom token which contain needed info. Basically you create a module that implements hook\_tokens and hook\_token\_info. For more details see the documentation: http://api.drupal.org/api/drupal/includes--token.inc/7.

Additional, where you can find examples: https://www.drupal.org/node/1308488 and How to programmatically create a custom token in a module

---
Tags: 7, rules, tokens
---


# Question
Title: How to create a rule to combine the terms of 2 fields to create a new term stored it in a 3rd field?
I have a content type that has 3 term reference fields:

* Field A, required, is a term reference using a vocabulary with machine name `vocabulary_a`.
* Field B, required, is a term reference using a vocabulary with machine name `vocabulary_b`.
* Field C, is a term reference using a vocabulary with machine name `vocabulary_c` and is generated automatically.

When creating or updating a node, values are entered for field A and B. I want to have a rule (using the Rules module) with some Rules Action to set a data value for field C, equal to the concatenation of the value entered for field A and B. Here is a picture of what I'm trying to achieve:

When I use a Rules Action of "Set a data value" (for field C), I can only refer to one value (eg the token from Field A), and not to the tokens from both Fields (A and B).

So how can I get this to work somehow?

Note that this is a followup to these prior questions (which are not duplicates ...):

So this question here is about (a) those 3 fields which each have their own taxonomy and (b) at the same time avoiding the duplicate terms to be created.

# Answer
My previous answer is based on using Rules Event "View a node of content type Article".

However (as confirmed by OPer after I posted a comment about that, in a comment deleted by a moderator), I think it should be (1) When a node of that content type is created and also (2) When a node of that content type is updated. But (3) when a rules event like "View a node of that content type" happens, I think that should NOT trigger any Rules Action (because viewing should not change any of those values).

Here is a variation of the previous rule, which takes the above into account:

```
{ "rules_combine_taxonomy_terms_in_a_3rd_taxonomy_for_create_and_up" : {
    "LABEL" : "Combine taxonomy terms in a 3rd taxonomy for create and update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "Value of term for Field C has to be set to \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E, i.e. the combination of the value of Field A (= \u003Cstrong\u003E[node:field-a]\u003C\/strong\u003E) and the value of Field B (= \u003Cstrong\u003E[node:field-b]\u003C\/strong\u003E)." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "combined_term" : "Combined Term" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "taxonomy_term",
            "property" : "vocabulary",
            "value" : "vocabulary_c"
          },
          "PROVIDE" : { "entity_fetched" : { "existing_terms" : "Existing Terms" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "boolean", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "new_term_exist" : "New term exists" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "existing-terms" ] },
          "ITEM" : { "current_term" : "Current term" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "text_matches" : { "text" : [ "current-term:name" ], "match" : "[combined-term:value]" } },
                  "DO" : [
                    { "data_set" : { "data" : [ "new-term-exist" ], "value" : "1" } },
                    { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "current-term" ] } },
                    { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E already existed and will be used to automatically set the value for Field C to this term also." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "new-term-exist" ], "value" : "0" } },
            "DO" : [
              { "entity_create" : {
                  "USING" : {
                    "type" : "taxonomy_term",
                    "param_name" : "[combined-term:value]",
                    "param_vocabulary" : "vocabulary_c"
                  },
                  "PROVIDE" : { "entity_created" : { "term_created" : "Created term" } }
                }
              },
              { "entity_save" : { "data" : [ "term-created" ], "immediate" : "1" } },
              { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "term-created" ] } },
              { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E did not yet exist and was created just now. It will be used to automatically set the value for Field C to this term also." } }
            ]
          }
        ]
      }
    ]
  }
}

```

To import it in your own site (using the Rules UI), use the same trick as in my prior answer.

The difference with my previous answer is (a) another Rules Event and (b) the messages that are simplified now.

Probably most important is that there is no more page refresh needed (you see the result right away).

### Demo

Some messages that will be shown, depending on the scenario used:

* Update an existing node, or create a new node, with a term for field C that already existed:

> Value of term for Field C has to be set to **Term A6Term B1**, i.e. the combination of the value of Field A (= **Term A6**) and the value of Field B (= **Term B1**).
>
> Term **Term A6Term B1** already existed and will be used to automatically set the value for Field C to this term also.
* Update an existing node, or create a new node, with a term for field C that did not yet exist:

> Value of term for Field C has to be set to **Term A3Term B1**, i.e. the combination of the value of Field A (= **Term A3**) and the value of Field B (= **Term B1**).
>
> Term **Term A3Term B1** did not yet exist and was created just now. It will be used to automatically set the value for Field C to this term also.

**`Done`** ...
> 2 votes

# Answer
Below is a variation of the rule that I already posted in my answer in the related question. The Rules Event used in this answer, is (still) related to "when viewing content (of type article)", as was (also) the question in the related questions. In another answer, I'll add some details about not using this event, but some other event(s) instead (and a variation of this rule for that scenario). This rule here will display specific Drupal messages, to indicate what has happened, and what still needs to happen (to have Field C show the requested value).

In my own setup (where I QA-tested this ...) it's using 3 fields (as in the question here):

* Field A, machine name `field_a`, a term reference using a vocabulary with machine name `vocabulary_a`, which has terms `Term A1`, `Term A2` and `Term A3`.
* Field B, machine name `field_b`, a term reference using a vocabulary with machine name `vocabulary_b`, which has terms `Term B1`, `Term B2` and `Term B3`.
* Field C, machine name `field_c`, a term reference using a vocabulary with machine name `vocabulary_c`.

But there are a few things about this rule to be aware off (more details on that below the rule). Here is my rule:

```
{ "rules_combine_taxonomy_terms_in_a_3rd_taxonomy" : {
    "LABEL" : "Combine taxonomy terms in a 3rd taxonomy",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "Value of term for Field C has to be set to \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E, i.e. the combination of the value of Field A (= \u003Cstrong\u003E[node:field-a]\u003C\/strong\u003E) and the value of Field B (= \u003Cstrong\u003E[node:field-b]\u003C\/strong\u003E). However the page is already rendered BEFORE subsequent Rules Actions will be executed. So to actually see the new value for Field C, an extra page refresh is needed." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "combined_term" : "Combined Term" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "taxonomy_term",
            "property" : "vocabulary",
            "value" : "vocabulary_c"
          },
          "PROVIDE" : { "entity_fetched" : { "existing_terms" : "Existing Terms" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "boolean", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "new_term_exist" : "New term exists" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "existing-terms" ] },
          "ITEM" : { "current_term" : "Current term" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "text_matches" : { "text" : [ "current-term:name" ], "match" : "[combined-term:value]" } },
                  "DO" : [
                    { "data_set" : { "data" : [ "new-term-exist" ], "value" : "1" } },
                    { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "current-term" ] } },
                    { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E already existed and will be used to automatically set the value for Field C to this term also ... But only \u003Cstrong\u003Enext time this node is viewed\u003C\/strong\u003E (as per the used Rules Event ...)!!! If you\u0027re in a hurry to see the new value for Field C, just refresh this page." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "new-term-exist" ], "value" : "0" } },
            "DO" : [
              { "entity_create" : {
                  "USING" : {
                    "type" : "taxonomy_term",
                    "param_name" : "[combined-term:value]",
                    "param_vocabulary" : "vocabulary_c"
                  },
                  "PROVIDE" : { "entity_created" : { "term_created" : "Created term" } }
                }
              },
              { "entity_save" : { "data" : [ "term-created" ], "immediate" : "1" } },
              { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "term-created" ] } },
              { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E did not yet exist and was created just now. It will be used to automatically set the value for Field C to this term also ... But only \u003Cstrong\u003Enext time this node is viewed\u003C\/strong\u003E (as per the used Rules Event ...)!!! If you\u0027re in a hurry to see the new value for Field C, just refresh this page." } }
            ]
          }
        ]
      }
    ]
  }
}

```

**Things to be aware of**:

For reasons I don't know (yet), you cannot simply "import" the above rule, using the typical Rules UI to do so. Try to import it somewhere, I bet you'll run into an import error which looks pretty similar (or "exactly"?) to this one:

> Integrity check for the imported configuration failed. Error message: The data type of the configured argument does not match the parameter's `<em class="placeholder">`value`</em>` requirement..

**But** there is a work around for this import "issue", based on a similar trick I found in this Group Module issue (ie comment #6 which is similar and comment #12 which describes the work around), which is to delete the Rules Action that may be causing the import problem, and then after the import succeeded, you just add those Rules Actions manually again.

In this specific case, you have to delete these lines from the above rule (in export format) before trying to import the remaining part of it (both are located within the "Loop" Rules Action, they start with `data_set`):

```
    { "data_set" : { "data" : [ "new-term-exist" ], "value" : "1" } },
    { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "current-term" ] } },

```

After you removed those 2 lines, retry your Rules import (in my case it works then). Next you need to manually (using the Rules UI) edit that rule and add these 2 Rules Actions right before the "Show a message on the site" again (using "Add Action"-link, locate to the right of "If: Text comparison"). These actions look like so:

* "Set a data value", with Data Selector = `new-term-exist` and Data Value = `True`. Next "move" that action before the "Show a message on the site", and "Save changes".
* "Set a data value", with Data Selector = `node:field-c` and Data Value = `current-term`. Next "move" that action before the "Show a message on the site", and "Save changes".

To check if you didn't introduce any mistakes with this special editing, export your rule, and compare it to the original rule in my answer here. They should match exactly (if you're using the same machine names, etc).

### Scenario for creating a new Article

This Rule does work now also as *I would like (expect)*, in the scenario where you're creating a new Article. However, to make this possible, in the `entity_query` I had to "hardcode" the machine name of the vocabulary used for Field C (= `vocabulary_c`).

If you use `[ "node:field-c:vocabulary" ]` instead, you run into some rules errors (starting with "Unable ...") that you can see if you enable Rules Debugging (in the Rules Log). Here is an example of such Rules Log, containing those unable-messages:

```
0 ms Rule Combine taxonomy terms in a 3rd taxonomy fires.
4.244 ms Evaluating the action drupal_message. [edit]
5.009 ms Evaluating the action variable_add. [edit]
5.055 ms Added the provided variable combined_term of type text [edit]
5.988 ms Unable to get the data value for the variable or parameter value. Error: Unable to get the data property vocabulary as the parent data structure is not set.
6.421 ms Unable to evaluate action entity_query. [edit]
6.52 ms Evaluating the action variable_add. [edit]
6.559 ms Added the provided variable new_term_exist of type boolean [edit]
7.031 ms Unable to get variable existing_terms, it is not defined.
7.459 ms Unable to evaluate loop. [edit]
9.287 ms The condition data_is evaluated to TRUE [edit]
10.428 ms Evaluating the action entity_create. [edit]
10.637 ms Added the provided variable term_created of type taxonomy_term [edit]
10.734 ms Evaluating the action entity_save. [edit]
10.781 ms Saved term_created of type taxonomy_term.
12.934 ms Evaluating the action data_set. [edit]
15.147 ms Evaluating the action drupal_message. [edit]
15.34 ms Rule Combine taxonomy terms in a 3rd taxonomy has fired.

```

### Demo

Here are some samples (demos) of the kind of messages shown, depending on the used scenario:

1. If the combination of terms in Field A and Field B **already exists** as a term in `vocabulary_c` (which is the vocabulary used by Field C):

> Value of term for Field C has to be set to **Term A2Term B3**, i.e. the combination of the value of Field A (= **Term A2**) and the value of Field B (= **Term B3**). However the page is already rendered BEFORE subsequent Rules Actions will be executed. So to actually see the new value for Field C, an extra page refresh is needed.
>
> Term **Term A2Term B3** already existed and will be used to automatically set the value for Field C to this term also ... But only **next time this node is viewed** (as per the used Rules Event ...)!!! If you're in a hurry to see the new value for Field C, just refresh this page.
2. If the combination of terms in Field A and Field B **does NOT YET exist** as a term in `vocabulary_c` (which is the vocabulary used by Field C):

> Value of term for Field C has to be set to **Term A2Term B1**, i.e. the combination of the value of Field A (= **Term A2**) and the value of Field B (= **Term B1**). However the page is already rendered BEFORE subsequent Rules Actions will be executed. So to actually see the new value for Field C, an extra page refresh is needed.
>
> Term **Term A2Term B1** did not yet exist and was created just now. It will be used to automatically set the value for Field C to this term also ... But only **next time this node is viewed** (as per the used Rules Event ...)!!! If you're in a hurry to see the new value for Field C, just refresh this page.
> 0 votes

---
Tags: 7, entities, taxonomy-terms, rules
---


title: Executing drupal file using shell_exec

text:
# Question
Title: Executing drupal file using shell_exec
I wish know whether a drupal function/file can be executed using 'shell\_exec()' from another drupal function. Any help is appreciated.

# Answer
Drupal imposes no limits on how you can use php. If it's possible to do what you need to do in php, it's possible in Drupal.

There are no Drupal-specific API methods to help execute code through the shell, so just approach this as you would if Drupal wasn't involved.

A simple method, depending on what you need to do, might be to install Drush and invoke commands using that. Then the bootstrap/file includes will be handled for you automatically and you'll need to write less boilerplate code.
> 2 votes

# Answer
I run command using php function exec():

```
$command_save = 'mysqldump --defaults-file='.$config_file.' '.$database_name.' > '.$db_dump_file;

exec($command_save, $output = array(), $res_save);

```

where `$config_file` \- path to configuration file consists login and password for connect to DB, `$database_name` \- name of DB, `$db_dump_file` \- dump DB file name

Also you can run command using ssh2\_exec()

```
  $server = "localhost";
  $username = "user";
  $password = "pass";

  $connection = ssh2_connect($server, 22);

  if (ssh2_auth_password($connection, $username, $password)) {

    $command = 'drush up --security-only -y';

    // Run a command that will probably write to stderr (unless you have a folder named /hom)
    $stream = ssh2_exec($connection, $command);
    $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

    // Enable blocking for both streams
    stream_set_blocking($errorStream, true);
    stream_set_blocking($stream, true);

    // Whichever of the two below commands is listed first will receive its appropriate output.  The second command receives nothing
    $result = stream_get_contents($stream);
    $result_error = stream_get_contents($errorStream);

    // Close the streams
    fclose($errorStream);
    fclose($stream);
  }

```

I use this method because if I try run drush command with exec() function I have some troubles (Drupal runs from user which hasn't necessary privileges). And for using this method you need to install libssh2 at the server.
> 2 votes

---
Tags: hooks
---


# Question
Title: How to get the administrator role id to assign new permissions?
In my module I'm creating new permissions that I want by default also assigned to the Drupal admin user.

I know how to assign new permissions to a role, but I don't know how to get the Drupal administrator role id. In the database the rid for administrator is 3, but can I rely on that being always the case? I'm using Drupal 7.

# Answer
unless you install Drupal in your custom installation profile and modify the administrator role there, the `rid` or administrator will be always `3`.
Or you could just do a `db_query()` on `role` table to return the `rid` of administrator as:

```
$result = db_query("SELECT rid FROM {role} where name like :id",array(':id' => 'administrator'));
$admin_rid = $result->fetchField(0);

```
> 3 votes

# Answer
Consider that the administrator role may have a different name than `administrator` or may have a different role ID.

Drupal 7 has a configuration available at Account Settings page: **Administrator role**

The value is stored in variable named `user_admin_role`.

```
$admin_rid = variable_get('user_admin_role');

```

After getting the role ID, you can do pretty much anything you need with it.
> 2 votes

---
Tags: 7, users
---


# Question
Title: Programmatically set URL Alias when creating node in form plugin
I'm currently importing data from a database to create nodes based on them. My node save code looks like this

```
$node = \Drupal\node\Entity\Node::create([
        'type'                 => 'issue',
        'title'                => $title,
        'body'                 => $body,
        'field_issue_category' => $term,
        'field_issue_type'     => 'publication',
        'field_pub_id'         => [
            'target_id'           => $publication_id,
        ],
        'field_issue_group' => $group_id,
        'field_date'        => $date,
    ]);
$node->save();

```

I also want to create a url alias based on the title of this node, which I create like this,

```
$nid       = $node->id();
$title     = preg_replace("/[\s_]/", "-", $title);
$path      = \Drupal::service('path.alias_storage')->save('/node/'.$nid, '/mypath/'.$title);

```

This successfully create a url alias that shows up in the URL aliases list in the URL alias config. However it doesn't show up in the URL alias field on the node edit page.

This creates a problem. One, the user can't see what the actual alias is. Also I have a block plugin that puts every node of that type in a list on a page. It also displays the url to that node. I'd like the url displayed to be the alias like '/mypath/title' but Drupal only seems to know about the '/node/nid' path.

Is there a proper way to programmatically set a nodes url alias so that it still appears in the url alias field?

# Answer
The node widget currently only shows aliases that have the same langcode as the node. https://www.drupal.org/node/2511968 will change that and also display aliases without a specific language.

But if the alias also doesn't work on the site then that sounds like something else also isn't correct yet. Does it work in that block if you create an alias manually in the UI? If so, compare the two records in the url\_alias table, do you see a difference?

You can create an alias as part of saving the node, there is a path pseudo/computed field. Try adding this to your array:

```
'path' => [
  'alias' => '/mypath/' . $title,
  'pathauto' => PathautoState::SKIP,
]

```

That should create the alias correctly as well.

And last, if your alias is so predictable, you should look at Pathauto. That allows you to set up rules for creating aliases. Among other things, it has a ton of logic to deal with special characters and duplicates, your code will have a problem if you have two nodes with the same title, for example.
> 14 votes

---
Tags: nodes, 8, uri
---


title: Why we need different menu item types?

text:
# Question
Title: Why we need different menu item types?
While I was studying hook\_menu, I came across menu item types and I found that there are 6 types of menu item types as follows :

1\] MENU\_CALLBACK

2\] MENU\_DEFAULT\_LOCAL\_TASK

3\] MENU\_LOCAL\_TASK

4\] MENU\_NORMAL\_ITEM

5\] MENU\_LOCAL\_ACTION

6\] MENU\_SUGGESTED\_ITEM

I have read the documentation on Drupal.og and doc says that we have different application of each menu item type.

But I am not able to differentiate when to use which menu item type? can I anyone help me to understand that which menu item type should be used ?

If any one explains use of each menu item type with example then it will be appreciated.

# Answer
> 1 votes
I realize this is a bit late, but just in case it helps anyone who stumbles across this...

1) MENU\_CALLBACK - Menu callbacks are a special type of page that isn't meant to be viewed by a user. They are used as an endpoint for APIs (such as AJAX requests). Menu callbacks sort of act as a way for an API to "call a function".

2) MENU\_DEFAULT\_LOCAL\_TASK - The default local task is just the local task that is selected by default. An example of this is the "view" tab on nodes. See more about local tasks below.

3) MENU\_LOCAL\_TASK - Local tasks are tabs. When viewing a node as an admin, several tabs are visible (view, edit, etc). Each of those tabs a local task.

4) MENU\_NORMAL\_ITEM - This is a page. Simple as that.

5) MENU\_LOCAL\_ACTION - Local actions are similar to local tasks, except they are meant to conduct an action, rather than display information. An example of this is the "Add Content" link that displays on the Content Administration page.

6) MENU\_SUGGESTED\_ITEM - This is almost exactly like a regular menu item, except it's disabled by default. This can be used by module makers to suggest a menu item to the user, but leave it up to the user to actually enable it.

---
Tags: hooks, navigation
---


# Question
Title: Stopping 404 pages when adding get variable to the URL
I have a Drupal 8 website with a URL like http://mywebsite.com/my-content-url/my-content-url. What I have done is adding a variable to the URL, making it like http://mywebsite.com/my-content-url/my-content-url/myvariable.

How do I get Drupal 8 to stop seeing /myvariable as a part of the URL and giving me a 404 error?

# Answer
You need a menu callback that accepts the variable. For more info, take a look at the Drupal docs.

Another way to do this is to pass your variable as a query parameter like http://mywebsite.com/my-content-url/my-content-url?var=myvariable. You can then use code to parse that parameter from the URL. You can get those parameters by using something like `\Drupal::request()->query->all();`
> 2 votes

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


# Question
Title: Assign file to entity image field (Programmatically)
```
//class:Drupal\file\Entity\File
$file=file_save_data($image_data,$save_path,FILE_EXISTS_REPLACE);

//field_someimage = entity 'image' field
//field class:FileFieldItemList
//It contains objects with class FieldType\ImageItem
$field_someimage=$entity->get('field_someimage');

```

How can i add $file to the field\_someimage of $entity? (entity already exists). Do i need to construct new ImageItem somehow?

# Answer
You add an image to the field by assigning the file id to target\_id:

```
$entity->field_someimage[] = [
  'target_id' => $file->id(),
  'alt' => 'Alt text',
  'title' => 'Title',
];
$entity-save();

```

You can add other properties at the same time. An image usually needs a title and an alt text.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How to fetch fields in a view in the overrided twig file?
I have created a view like so:

I have written a twig file for it named `views-view--employee_details--block_1.html.twig`, which is placed in folder `/project_name/themes/theme_name/templates/views`.

I want to fetch fields from the view into `views-view--employee_details--block_1.html.twig` file.

How can I do so?

# Answer
> 1 votes
You can do it like this:

```
{{ fields.[machine_name].content }}

```

The machine name is shown in your content type manage fields.

So it would be:

```
{{ fields.title.content }}
{{ fields.field_designation.content }}

```

Also, your template name needs to be: **`views-view-fields--employee-details--block-1.html.twig`**

Make sure you clear/flush the cache to see the changes.

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


# Question
Title: How to find which pages use a certain view?
I am working on a site that has a lot of views with multiple displays, and to make life easier for our team we are trying to document where views are in use; including view blocks.

In other words, I want a simple way to know which pages use a certain view for each view. The site also has views that are enabled but not in use on any page, so it would be nice to be able to find out which ones may be candidates for deletion to make administration easier.

# Answer
> 1 votes
You can use the Devel module and enable the **Web Profiler** module that comes with Devel. This module will tell you which view is being used when you visit a page.

Alternatively, you could try the answers from here, Where are my views being used?

---
Tags: 7, views
---


# Question
Title: Views, find content types with field NOT IN other content type
Content Type A -Nid A -Field A

Content Type B -Nid B -Reference Nid A

How can I find in a view all As that have no reference in B ?

in sql this is

```
select A.field
FROM TABLE A
LEFT JOIN TABLE B
ON A.KEY = B.KEY
WHERE B.key IS NULL

```

I have tried Views reference filter, but it is very slow and consume a lot of memory (the trick with this modules is not a join but a SELECT... NOT IN (...).

Which is very inefficient, because, i have 16.000 As and 14.000 Bs.

Is there any efficient solutions with views?

Thanks.

# Answer
> 1 votes
Well, maybe it is idiotic, but finally I understood the issue with the relationships and the "referenced vs referencing"

So, what I did was:

relationships : "Content referenCING Content from A\_REFERENCE\_IN\_B" Fields A (the fields you want) Filter type = Type A Filter NID (using the relationship) , is null.

Amazing, and super fast.

The important part is REFERENCING not referenced.

Thanks.

---
Tags: 7, database, views
---


# Question
Title: Can blocks created via the admin UI be cached?
I am trying to understand if blocks created using the admin UI can be cached or not? I had a look at the `block` table in the database and it would appear that the cache value is set to `-1` regardless of whether block caching is enabled or not. So I am assuming that blocks created via the admin UI cannot be cached. Is that correct?

# Answer
> 0 votes
https://www.drupal.org/project/blockcache\_alter might be what you are looking for.

---
Tags: 7, blocks, caching
---


title: Migrating image with fields

text:
# Question
Title: Migrating image with fields
Working on a migrate task for images. On d7 and d8 I've file\_entity with two fields, but values are not imported.

Here is my source json:

```
{
  "items": [
    {
      "id": "2417",
      "uuid": "b0ad2fca-d100-45bf-9423-2474f00af68b",
      "filename": "terremoto_irpinia.jpg",
      "filepath": "public://terremoto_irpinia.jpg",
      "url": "http://localhost/sites/default/files/terremoto_irpinia.jpg",
      "links": [
        {
          "url": "http://www.foggiacittaaperta.it/news/read/terremoto-irpinia-1980-il-ricordo-da-napoli-a-foggia-35-anni-dopo",
          "title": "http://www.foggiacittaaperta.it/news/read/terremoto-irpinia-1980-il-ricordo-da-n...",
          "attributes": [],
          "html": false,
          "query": null,
          "fragment": null,
          "absolute": true,
          "display_url": "http://www.foggiacittaaperta.it/news/read/terremoto-irpinia-1980-il-ricordo-da-n..."
        }
      ],
      "alt_text": "some text",
      "created": "1472139573",
      "stato": "Permanente",
      "created_year": "2016",
      "directory": "public://immagini/2016/terremoto_irpinia.jpg"
    },
]
}

```

On yml, this is my process:

```
source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  urls: http://localhost/modules/custom/migrando/files/download_immagini.json
  item_selector: items
  fields:
    -
      name: fid
      selector: id
    -
      name: filename
      selector: filename
    -
      name: uuid
      selector: uuid
    -
      name: filepath
      selector: directory
    -
      name: url
      selector: url
    -
      name: links
      selector: links
    -
      name: alt_text
      selector: alt_text

  ids:
    fid:
      type: string

process:
  uid:
    plugin: default_value
    default_value: 1
  filename: filename
  uuid: uuid
  status:
    plugin: default_value
    default_value: 1
  created: created
  alt: alt_text
  field_image_alt_text: alt_text
  field_fonte_immagine:
    plugin: iterator
    source: links
    process:
      uri: url
      title: title
      options: attributes
  uri:
    plugin: file_copy
    source:
      - url
      - filepath

```

Don't work field\_image\_alt\_text and field\_fonte\_immagine fields. What's wrong?

Thanks!

# Answer
> 2 votes
I don't see the destination configuration here - presumably the plugin is entity:file, correct? Are you setting default\_bundle there, so the file entities are created with the correct type (the bundle those fields are attached to)?

---
Tags: 8, migrations, navigation
---


# Question
Title: Migrating into custom node type with multi value field
I'm doing a migration into D8, and I'm migrating into a custom video player field with multiple values. Here's the schema for the field as defined in its plugin:

```
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return array(
      'columns' => array(
        'vid' => array(
          'type' => 'int',
          'size' => 'normal',
          'not null' => TRUE,
          'default' => 0,
        ),
        'video' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'video_hd' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'video_sm' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'thumbnail' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'poster' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
        'show_ads' => array(
          'type' => 'int',
          'size' => 'tiny',
          'not null' => TRUE,
          'default' => '1',
        ),
        'raw_file' => array(
          'type' => 'varchar',
          'length' => 256,
          'not null' => FALSE,
        ),
      ),
    );
  }

```

I have a custom source plugin that gathers all of the information needed for these columns into appropriately named items. My question is, how do I get those pieces of data into the destination field. Can I do it in the .yml file configuration, as can be done with the body field?

```
  'body/format':
    plugin: migration
    migration: d6_filter_format
    source: format
  'body/value': node_body
  'body/summary': teaser

```

Or do I need to have a custom destination plugin that takes these pieces of data and puts them into the correct places in the node? I'm seeing a lot of blogs and documentation on source and process plugins, but not much on destination plugins, so I'm not sure.

Thanks.

# Answer
> 0 votes
Nothing to do with destination plugins, what you need to do would be in the process pipeline. You could write a custom process plugin like, say, d6\_cck\_link. Or, you can use the iterator process plugin - see, for example, how d6\_upload.yml in core populates the target\_id/display/description columns of the 'upload' field.

---
Tags: 8, migrations, plugins
---


# Question
Title: Creating 2 forms to work together on the same page for the same query
I'm facing trouble coming up with the following approach:

I will have 3 separate forms acting on the same query from third party API's.

On the front page there is a shorter quick-form that would lead to the page of the other 2 forms. In some cases the information from the first form is sufficient to query the information and the information will be queried.

In other cases additional input from the second form is required to make the query. The third form is for fine-tuning an existing query.

The first form isn't an issue, it's a separate block on the front page that will store the information internally for the second form to see with multiform functionalities and on submit redirect to the second forms page, where the form can process the information and see if a query can be made or will give results and go ahead with it, if not, then ask for further input.

The second and third form are on the same page, where the second form has necessary input fields for the query, which can also be changed to change the results, and the third form is just for fine-tuning this query like a filter or so.

Right now I'm stuck with the second 2 forms working together on the same page, being separate forms but altering the same query/information. And would appreciate all and any help with this approach that would be "the Drupal way".

**Better visualization:**

Imagine a flight booking site: first form is your departure airport that takes you to the second 2 forms, where already a lot of flights from your airport can be displayed, second form takes in a destination, dates and passengers; the third form would let you fine-tune travel class, meals, airlines to avoid airlines preferred, how many layovers, how long layovers and so on..

All the information with each form is queried from different airline API's and will have to be redone on every change.

# Answer
> 0 votes
From your question... you are saying you have 3 forms...

The first form (on its own page) leads to the other 2 forms (which are on a different page, but both forms are on that single page)... it's not completely clear what the problem is - only that both forms are supposed to alter a query, but this is not happening?

Perhaps you could place the fields for both forms in a single form and assign different actions to each of the submit buttons... technically there will only be one form, but visually through styling you can make it appear as two separate forms through CSS - for example using tabs where the fields for the first form is on the first tab... and the fields for the second form is on the second tab... the first tab would have a submit button defined like this:

```
        $form['submit1']=array(
        '#type' => 'submit',
        '#value' => t('Submit form 1'),
        '#submit' => array('::processForm1'),
        );

```

and on the second tab you can define another submit button:

```
        $form['submit2']=array(
        '#type' => 'submit',
        '#value' => t('Submit form 2'),
        '#submit' => array('::processForm2'),
        );

```

Enough to say in the form object, you will need to define both the processForm1 function and the processForm2 function... in order to decipher which button triggered the submit in the formValidation and formSubmit functions you will use a line such as:

```
      $trigger=$form_state->getValue('op');

```

where $trigger will hold the label of the triggering button.

Hope that helps and makes sense.

# Answer
> 0 votes
You are loading a first form in a block. On click submit the first form. In first form submit handler redirect a page to result page i.e.. Create a new router in custom module routing yml file and controller method check all necessary information you got to show result, if yes then render the result array or else render second and third form.

While redirecting to result page pass $formstate object as first argument so that you can access the necessary argument and you also said filters are present in result page . If filters are ajax based then form ajax submit handler should load result render array. else pass filter values also in result page url.

You can render a form in a controller with code similar to the following one.

```
$result['content'] = \Drupal::formBuilder()->getForm('\Drupal\custom_module\Form\Formname', <arguments for the form>);

```

---
Tags: forms, 8
---


# Question
Title: How do I programmatically know the jQuery version using a script or a hook?
How do I programmatically know the jQuery version using a script or a hook?

I have used this script for getting the site's jQuery version.

```
if (typeof jQuery != 'undefined') {
// jQuery is loaded => print the version
alert(jQuery.fn.jquery);

```

How could i get the same by using some database query or hook programmatically?

# Answer
> 1 votes
you can use this code to get all installed modules list

```
module_load_include('inc', 'update', 'update.report');
$available = update_get_available(TRUE);
$data = update_calculate_project_data($available);
dpm($data);  // provides installed modules details as an array
dpm($data['jquery_update']['existing_version']); // provides jquery_update module existing version

```

---
Tags: 7, hooks
---


title: How do I render the comment form?

text:
# Question
Title: How do I render the comment form?
I have attached a comment type to a content type via a field. Right now all I can see is a link called ***Add new comment***. How do get the comment form to render on the node and not show the link?

# Answer
> 2 votes
If I've assumed your question correctly, you want to show the comment form when displaying the node content page. You can do this by enabling a setting "**Show reply form on the same page as comments**" in Comment field. Check screenshot below:

1. Edit Comment field

2. Enable "**Show reply form on the same page as comments**" setting checkbox and click on "**Save Settings**".

---
Tags: 8, comments
---


title: Static Frontpage

text:
# Question
Title: Static Frontpage
I'm a seasoned front-end developer and extremely new to Drupal. I've just created a new instance of Drupal 8 and all I am trying to do is create a static one pager for a client who needs a simple web presence before building the full Drupal8 site in the new year.

Using a purchased theme, all I need is to create and route a static homepage, but I'm not sure where to begin.

Can someone point me in the right direction.

Thanks

# Answer
Add a node of the type page and fill it with the static html:

```
/node/add/page

```

Then go to

```
/admin/config/system/site-information

```

and configure the "Default Front Page". If the page you've created earlier is the first node, then this is `/node/1`.
> 6 votes

# Answer
I'd say the easiest way to make a static (but CMS editable) frontpage is to make a Basic Page node (`page`) and set that URL at the frontpage in the CMS settings (admin/config/system/site-information). For example, `node/1`.

We tend to do this with a dedicated custom node type so that we can add extra fields (eg an image field that can be styles for a carousel, or entity references for promoting frontpage blog posts, etc).
> 2 votes

---
Tags: 8, routes
---


# Question
Title: How do I find the user whose field is equal to the email address?
I am trying to fetch a Username where a field equals the value of another field.

On my content type, I have an Entity Reference fields that creates a select list of email addresses.

In Rules, reacting on Creating/Updating nodes in this content type, I am trying to Fetch a User Entity where the value the select list field equals the user's email.

How can I do that?

---

## What I have tried:

I first chose to "Fetch Entity by Property".

The Value is "User", the Property was set to "Name", and the Value was set to the title of the Entity Reference field in the first screenshot (The title of each node in the select list is an email address)

The Fetched Entities are called "fetched\_user".

When trying to Add a Variable, it shows multiple values, so I assume I would need to make a loop first.

So I created a loop:

I am very lost on what to do next. Can anyone help me?

Thank you.

# Answer
Your first mistake is in your fetch by property action. The property must be set to email for the users to be found.

After that, the fetch by property action will always return a list even if it's only one result. So you just need fetched-user:0:name. No loop required.

In php, 0 is the first item in a list.
> 3 votes

# Answer
Below is an answer to this part of your question:

> on what to do next

It seems that for the `list_item` being processed, you want to add some extra "test" (similar to a Rules Condition), to verify if the user being processed is the one with the eMail Id you're looking for.

But you're within a Rules Action already, where you cannot add such "test" anymore. Except if you use the Conditional Rules module, which allows you to add such tests within a Rules Action. For some examples of a rule that uses this module, refer to my answer to either of these questions (which include a rule in Rules export format):

Another solution which does not require that extra module, is to add a Rules Component at that very same spot, in which you can add a Rules Condition again, and where you then also add the rest of the required Rules Action(s) to complete the rest of your Rules logic (if that remaining Rules logic can indeed be implemented like so). For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".

**Note**: I also agree with Niall's additional "***recommendations***".
> 1 votes

---
Tags: users, rules
---


# Question
Title: How to disable i18n language dropdown in node form?
I'ld like to prevent editors from changing the language of a node. Role check works. But I how to disable the language field? Why doesn't it work like any other form field? How is this field placed there? Where can I alter it? This doesn't work:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    $node_edit = isset($form['#node_edit_form']) && $form['#node_edit_form'] ? TRUE : FALSE;

    if ($node_edit && $editor) {
        $form['language']['#disabled'] = TRUE;
        $form['language']['#access'] = FALSE;
    }
}

```

# Answer
> 2 votes
So, the i18n dropdown is attached to the node form afterwards. For now I simply `unset($form['#after_build'][0])` where `_i18n_node_form_node_form_alter` is called. Unsetting it hides all other available languages from the dropdown making it impossible to change it. To me that seems fine. If there's a more appropriate way to do this, please let me know.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    if (isset($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE && $editor) {
        unset($form['#after_build'][0]);
    }
}

```

---

Finally I did it like @J.Reynolds suggested with `hook_module_implements_alter` to ensure that my module runs after Locale module

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    $node_edit = isset($form['#node_edit_form']) && $form['#node_edit_form'] ? TRUE : FALSE;

    if ($node_edit && $editor) {
        $form['language']['#disabled'] = TRUE;
    }
}

function MYMODULE_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'form_alter') {
        $module = 'MYMODULE';
        // store
        $group = array($module => $implementations[$module]);
        // unset
        unset($implementations[$module]);
        // add to the end
        $implementations = $implementations + $group;
    }
}

```

# Answer
> -1 votes
You can do this easily by disabling multi language from your content type.

For example admin/structure/types/manage/YOURCONTENTTYPE

Go to publising option and disable the multilanguage

Save the content type That's it.

---
Tags: forms, i18n-l10n
---


title: Aegir hostmaster custom profile

text:
# Question
Title: Aegir hostmaster custom profile
I created a custom profile with a custom theme for Aegir. I would like to enable that theme by default when a user install hostmaster during the Aegir installation. In the Aegir installation hostmaster is installed when the user runs the below drush command

drush hostmaster-install

I would like to know is there any way to modify this command or any other way to set my custom profile as defautt one during the Aegir install process.

Thanks

# Answer
> 1 votes
The `hostmaster-install` command has options for `--profile` and `--makefile`.

I use these options for OpenDevShop, which has it's own makefile and profile.

You can use a URL or a path for makefile option.

```
    drush hostmaster-install --makefile=/path/to/mymake.make --profile=mycustomprofile

```

# Answer
> 0 votes
It's done in hostmaster.install: `theme_enable(array('eldir'));`

You could patch that or better create a mini module of your own to later enable your own theme.

---
Tags: aegir, installation-profiles
---


title: Select on change

text:
# Question
Title: Select on change
With Drupal 8, I have a form with two selects, both filled. I want to add a button/link after each of these two selects, looking like this.

```
[__SELECT__v][BUTTON]
[__SELECT__v][BUTTON]

```

The buttons, however, don't have a fixed link because the link target depends on what is selected in the select. Also, the link needs to open a new tab.

For example, if in the select "car1" the key "12345" is selected, the link should open /cars/12345; if "car2" is selected with the key "67890" then "/cars/67890"

This is the code I am using.

```
$form['select_g1'] = array(
                    '#type' => 'select',
                    '#prefix' => '<div class="container-inline">',
                    '#title' => t('Select       '),
                    '#options' => $contarray,
                    '#empty_value' => '',
                    '#default_value' => ($ext) ? $row['model'] : "",
                    );
$form['button'] = array(
                    '#markup' => ' <a target="_blank" href=""><span class="button js-form-submit form-submit"><img src="/sites/default/buttons/edit.png"></span></a></div>',
                    );

```

Can someone help me there?

# Answer
This is easy to do with javascript.

You can do an onchange event for your select that updates the link,

or you can do a mousedown event on your link that grabs the value from the select.

A quick google search shows many possibilities:

https://stackoverflow.com/questions/11758659/compose-a-link-based-in-selects-option-value

https://stackoverflow.com/questions/20357075/how-to-update-append-to-it-an-href-based-on-dropdown-selection

To add javascript to your form, you need to add the js to your custom module, say in mymodule/js/updatelink.js

then add a mymodule.libraries.yml file in your module

```
mymodule.updatelink:
  version: VERSION
  js:
    js/updatelink.js: {}
  dependencies:
    - core/jquery
    - core/drupal

```

then attach it to your form like this:

```
$form['#attached']['library'][] = 'mymodule/mymodule.updatelink';

```

You'll want to wrap your code in a Drupal.behaviors class. See https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
> 2 votes

---
Tags: forms, 8, navigation
---


# Question
Title: CKeditor has empty node body for some nodes
On Drupal 7.52 and ckeditor module 1.17 (library version 4.6.1) and this is driving me insane. Here's a list of things I've noticed and tried:

1. Seems to primarily happen with unpublished nodes but not all unpublished nodes seem to have it. I have been testing using account 1 which has all privileges so I doubt it's permission related.
2. If I refresh the page, I can see the node body show up where ckeditor would be for half a second. When ckeditor loads it's gone though.
3. Checking the page source I can in fact find the textarea with the entire node body, so it is being sent to the browser.
4. No errors at all on the browser's console.
5. Can get in both Chrome and Firefox.
6. Disabling ckeditor makes the node body viewable again, re-enabling brings me back to the same problems.
7. Typing something on the empty ckeditor field, going to plain text mode and I can see the HTML, then going back to rich text mode and it's all gone again! This behavior happens when creating new nodes as well, but not with already published nodes that show the node body from the beginning. This also produces no console errors!
8. Updated ckeditor from 4.5.9 to 4.6.1.

Anyone have any ideas as to things I can test to pinpoint this problem?

# Answer
If anyone is ever having this problem, you should check your response headers for requests sent by ckeditor. It will attempt to send a request to /ckeditor/xss to run XSS filters and if that fails it will silently just hide the entire contents of the form. In the response header I noticed a Location parameter that is only available when the form fails. The location parameter was: /user/login?destination=ckeditor/xss. This obviously means that ckeditor's request for the XSS filters is being intercepted by some other module and sending it to the login page.

In my case, the problematic content was unpublished nodes. I have yet to find the exact module causing the redirect for ckeditor, but disabling the XSS scan in includes/ckeditor.utils.js on line 163 worked perfectly to solve all my issues (seen on post #9 here https://www.drupal.org/node/2069871)
> 1 votes

# Answer
I recently had a similar issue, not exactly the same scenario, but pretty close, using Drupal 7.50.

After all sorts of things I tried, and which didn't work, I downgraded the CK Editor library to 3.6.6.1. And sure enough: the issue disappeared. Not really a "fix" IMO, but at least the WYSIWYG editor started working again.
> 0 votes

---
Tags: nodes, javascript, wysiwyg
---


# Question
Title: Better Search Api Solr score sorting for strict word match in Drupal
**Given the following configuration:**

* A Search Api views page(connected with a Solr server) with a "Search: Fulltext search" exposed filter searching only on one "Full Text" aggregated field (Node Title).
* All the content is in Dutch;

**The issue:**

Having a list of node titles as following:

* AVENE CREM NUTRITIVE COMP POT 50 ML
* Widmer Nutritive Creme Parf 50ml
* AVENE TRIXERA NUTRITION NUTRI-FLUIDE 400
* NUTRITIC MEMOTONIC 7 FLAC
* NUTRITIC VIT A-D GINKGO 30 TABL

Searching for the keyword "Nutritic" will return me the following order:

* **NUTRITIC** MEMOTONIC 7 FLAC
* AVENE CREM NUTRITIVE COMP POT 50 ML
* Widmer Nutritive Creme Parf 50ml
* AVENE TRIXERA NUTRITION NUTRI-FLUIDE 400
* **NUTRITIC** VIT A-D GINKGO 30 TABL

It seems like the keyword "NUTRITI" is considered the same as "NUTRITIC".

How can ensure that searching on keyword "NUTRITIC" the content containing specifically "NUTRITIC" will have the bigger score than others?

# Answer
> 1 votes
Having just worked with Solr myself (for English) text. You need to assure Solr is *Configured* to search how you want. Out of the box the Solr configuration provides:

* a case insensitive, stemmed search (fuzzy, such as "savage" searches for "savage", "savages", "savaged", etc. and the search ignores punctuation. It also supports short phrase searching such as "find me this text" although Search API in 7.x-1.20 has a bug that removes min\_length words from quoted strings: https://www.drupal.org/node/2832196

This issue is resolved in the current -dev release available on 12/09/2016.

### You have 2 options

1. So, if the default stemmed search works for you as-is OK. If you want exact word searching with no stemming you need to alter the Solr schema to index `text` content differently than it does out of the box.

For non-stemmed, case sensitive searches change the analysis and query and multi-part logic to not use SnowballPorterStemmer and CaseInsenitive.

This is kinda outlined, but out of date for Solr 5x in this drupal issue. https://www.drupal.org/node/1319516#comment-5158076 Solr 5x depercated `enablePositionIncrements=true` so don't do that in the comments, and it will work.
2. If you like the searching as-is. You can alternatively *boost* the exact words to score higher than the inexact results. You would do this by:

* adding a fake entity property using an alter hook, and copying the text content from your fields into that field.
    * You would then define a Solr field in the solr schema to use for this drupal entity property field which doesnt use stemming to returned results
    * include this fake property field in your drupal search api Index.
    * use an alter hook for the solr query include this field with a boost (`&myfield="FOOBAR"^10`) in your search query.

Here's how you add a fake entity property to then be boosted: http://cornel.co/article/add-entity-property-node-which-can-be-used-search-api-index-field

Then it's simply a query alter in your form (here for apachesolr module, but for search API it's the same thing): https://www.phase2technology.com/blog/techniques-to-improve-your-solr-search-results/

Isn't Solr fun!!! (sigh) it's really cool, but also cumbersome.

---
Tags: 7, search
---


title: Remove disabled modules from Database

text:
# Question
Title: Remove disabled modules from Database
i just recently learned that i must unistall the module before delete it from modules folder ( "I thought that the deleting is the unistall" ), so can you please give a solution to delete the disabled modules from database ? and is that make a problem?

# Answer
> 3 votes
Yes, you can get errors when you delete the module files without disabling it first. It's best to completely uninstall the module, which allows the module to clean up after itself (eg. delete configuration from the database). After that, you can safely delete the files.

If you already deleted the files, the easiest way to get rid of bits and pieces left in the database, is to restore the files (download the module again and put the files back where they were), follow the uninstall process, and delete the files. Make sure you download the exact same version of the module you had installed earlier.

So how do you know which module version you had? Ideally you are already using a version control system (such as Git) to manage your code, so you can always look back in the history to find out which module version you were using. If you don't have version control, you can try to find the version number in the database as described in this answer. As a last resort, try to remember when you installed or last updated the module and look in the module's releases list to find a version close to that date.

---
Tags: 7
---


# Question
Title: Migration: the "csvrownum" should start from the second row
I am importing some nodes from csv file in drupal.

I am assigning row number to one of the field of that content type.

The first row in the csv is the header which contains the column names only. The data start from the second row.

I am using the "csvrownum" for the csv row number. But it starts from the first row. It should exclude the first row as the data starts from the second row. How will I do this?

Here is my code:

```
$this->source = new MigrateSourceCSV($path, $columns, array('header_rows' => 1));
          //The destination CCK (boundle)
          $node_options = MigrateDestinationNode::options("en", "full_html");
          $this->destination = new MigrateDestinationNode('lot', $node_options);
          $this->map = new MigrateSQLMap(
              $this->machineName, array(
            "csvrownum" => array(
              'type' => 'int',
              'unsigned' => TRUE,
              'not null' => TRUE,
              'alias' => 'import'
            )
              ), MigrateDestinationNode::getKeySchema()
          );
          //Field mapping
          $this->addFieldMapping('title', 'Title');
          $this->addFieldMapping('field_number', 'csvrownum');

```

# Answer
> 1 votes
I think that's the expected behavior, you could use the prepareRow() method to increment csvrownum in whatever your header\_rows is.

# Answer
> 0 votes
Why not use the feeds module?

By default the parser is set to read Row 1. as a header row (although this can be turned off in the options) at the very least the code in 'FeedsCSVParser.inc' file will do something very similar to what you want and would be a good reference...cf. https://drupal.org/node/776854

# Answer
> 0 votes
What worked for me recently is defining the `$columns` array and passing it to `new MigrateSourceCSV`.

You may also need to use single-quotes instead of double-quotes (inconsistent above).

# Answer
> 0 votes
In order to skip first n lines you need to specify the 'header\_rows' option.

e.g:

```
$options = array(
  'header_rows' => 1,
  'delimiter' => ','
);

$csvcolumns = array(
  0 => array('title_nl', 'Title NL'),
  1 => array('title_en', 'Title EN'),
  2 => array('title_fr', 'Title FR'),
);

$this->source = new MigrateSourceCSV("/../filename.csv", $csvcolumns, $options);

```

---
Tags: 7, migrations
---


# Question
Title: How to register or track the views of a node per user?
I'm looking for a way to count the number of times each user has viewed a particular node. I have many nodes but I need that number to give user points to the viewing user if he or she has accessed that node X number of times over a time span of 24 hours and this on a daily basis.

Is there anything that can do (track) this or is there a way that I could create this feature "without" writing my own module and without writing php code? I'm no Drupal Ninja ...

I've been looking at the node view count module but that doesn't allow the users themselves to see their view count. The best way of displaying that number would be through Views (obviously). I've been thinking about creating an integer field on the user account settings page but that wouldn't actually not show me which node that user has accessed.

Any ideas?

**Update**: The Node View Count module (suggested in one of the answers) is unstable (throws errors, breaks the site), has no documentation and simply does NOT provide a count of how many times 1 particular user has viewed each node (of a certain content type).

# Answer
Using the Rules module to solve this challenge is part of the solution you're looking for. But the key part of your challenge is that your question is about something (= `access that node`) which:

1. has to be repeated (= `X number of times`).
2. within a specified timeframe (= `over a time span of 24 hours`).
3. don't all happen at the very same moment.

Rules is great (amazing), but it does **not** support any of the 3 bullets above. So far the bad news ...

However, your question seems like a pretty good fit for using the Goals module (disclosure: I'm its maintainer), together with the Rules module. Below is a possible configuration to achieve your ***Goal***, using Goals.

# Configure a goal

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

***`View some node, 8 times within 24 hours with a limit of 1 view per hour`***.

Obviously, you can replace the `8` by whatever value of `X` you'd want.

# Configure a task

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

Obviously, that doesn't take into account the ***`8 times within 24 hours`***-part of your question. For that you would use some of the more advanced ways to use (configure) Goals, i.e. by using these optional configuration options for this specific task:

* this task has to be repeated multiple times: in your case **8 times**.
* this task requires some amount of time to expire in between any 2 similar tasks: in your case, if a user performs multiple refreshes of the same page in just a few seconds, **only the first one of them should count**. That why I'd use **a limit of 1 view per hour**.
* this task must be completed within a specific time frame (a number of times, expressed in hours, days or weeks): in your case **24 hours**.

# Track progress while performing tasks

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

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

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

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

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

```

# Use Rules to process completed goals

After all tasks specific to a goal are completed by a user, the goal is automagically marked as completed. **But**, that's where it gets really interesting: you can also create additional rules that will be triggered (Rules Event) when a goal is completed by a user.

With that, the answer to your question is extremely easy. You actually have 2 possible answers to pick from:

1. Just let the Goals grant the user points (if you have the **Goals Extras** submodule enabled).
2. Perform a Rules Action to "***... grant user points to the user who completed the goal***" ... which is exactly what your question is about, no?

# More info

Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for additional details about the Goals module.

Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).
> 1 votes

# Answer
I think You've missed something from the Node View Count module.

> Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

**Note:** Make sure to give permission for users to see their node view count.
> 0 votes

---
Tags: 7, views, nodes, users, userpoints
---


# Question
Title: How do print the query which is built using search api
I have created a view using search api now i just want to print my query.But when i used hook\_views\_pre\_execute(){ dpq($view-\>build\_info\['query'\]); } it does not show my query.

# Answer
Enable Views query preview in **Views Settings** (`admin/structure/views/settings`) by checking the box "**Show SQL query"**.

Then you will be able to see the query created by your view while you constructing it.
> 1 votes

# Answer
Search API does *not* show the query in views preview, which is a known bug.

A fix has been committed to the dev release, but it's not yet in the current stable 1.20 release.
> 0 votes

---
Tags: search, views
---


title: How to add fields to a content type?

text:
# Question
Title: How to add fields to a content type?
I installed Drupal 8 minimum. Create content type. Like normal there is one field. The body field.

I can't add an other field. In extend/modules all field types are enabled. Also fields and fields UI. What am I missing or have to enable to add fields to content type like: Image, link, references, etc.

I ran `drush cr` a couple of times.

# Answer
I highly suggest that you do not use the **minimal** install in Drupal, and go with the **standard** install.

It is way more efficient to use the standard install and then remove the modules that you do not want, than to use the minimal install and install a bunch of stuff.
> 4 votes

# Answer
Agree with using Standard.

That said, you're probably just missing the local actions block, you probably also can't see an "Add content" button on /admin/content. Go to block layout and make sure all the standard blocks like Page title, local actions, local tasks, messages and so on are there.
> 2 votes

---
Tags: 8, installation
---


# Question
Title: How do I add 2 blocks side-by-side in Bootstrap theme's "Content" region?
I have block views on the first page in the **"Content" region** of the Bootstrap theme that I would like to display as follows:

```
 _________________
|                 |
| another block   |
|_________________|
|        |        |
| block1 | block2 |
|________|________|

```

Is there a way to do this easily, without using float left/right for block1/block2 (as Bootstrap using a grid layout using rows and columns)?

Normal Bootstrap syntax would make **block1** go in the first `<div class='col-md-6'>` element and **block2** go in the second `<div class='col-md-6'>` so that the two blocks appear as equal-sized columns.

I see that regions are laid out in **themes/contrib/bootstrap/templates/system/page.html.twig**.

If there is not an easy way to achieve the desired layout, do I need to somehow create a twig template, similar to page.html.twig, in my Bootstrap subtheme that defines say 2 side-by-side regions under the existing "Content" region (i.e. "Sub-Content Left" and "Sub-Content Right" regions)? If so, how is this done and how to make the template apply to a specific page?

I looked into Bootstrap Layouts and Display Suite, but it wasn't clear how to integrate the two to accomplish the above.

Thank you very much in advance for your help.

# Answer
> 1 votes
You can extend the page twig like this.

Make a copy of page.html.twig in your theme template folder and put a twig block around the content:

**page.html.twig**

```
...
{% block content %}

  {{ page.content }}

{% endblock %}
...

```

Then create a new file, and name it so that it will target the specific page, for example the view "myview":

**page--view--myview.html.twig**

```
{% extends "page.html.twig" %}

{% block content %}

  {{ page.content }}

  <div class="..">
    {{ page.subleft }}
  </div>

  <div class="..">
    {{ page.subright }}
  </div>

{% endblock %}

```

This new file extends the page twig and contains only a new version of the the twig block "content". You can define multiple twig blocks in one file and replace them.

# Answer
> 1 votes
There is block attributes module for drupal 8, we can attributes to the blocks in drupal with that module.

1. Just install and enable the block attributes module,
2. then you can give a class value for the blocks from block configuration page, you are using bootstrap so just add "col-md-6" or any one of bootstrap's grid class in the attributes field in your block configuration.

I hope, it would solve your problem without any custom changes with codes.

# Answer
> 0 votes
You can accomplish this using a grid framework like Bootstrap or Foundation, as well as

www.drupal.org/project/blockgroup
www.drupal.org/project/block\_class

The first module allows you to create block groups, then place the block group in your block layout.

The second module allows you to put your classes on the block in block layout.

Create a new block group: my-group

In block layout, look for the region: block group: my-group

Place 3 blocks
Block a - col-md-12
Block b - col-md-6
Block c - col-md-6

Place the block 'block group: my-group' in the region you want it to display (content, etc)

---
Tags: 8, blocks, theming
---


# Question
Title: Using Rules and Rules Once per day how can I check when a node's date has expired?
I have a content type which has an end date field, once the current date is past this end date then I need to change a boolean field to `0` on that particular node.

I am really struggling to get anything close to working (using the Rules module), I am getting values such as this in my Data selectors:

* `node:field-category:0`
* `node:field-category:1`
* `node:field-category:2`
* `node:field-category:3`

I don't know why these delta values are there or how to get rid of them, every video tutorial I watch the persons data selection is working perfectly.

I understand I need to drill down by adding a Rules Condition to check for a particular field on the node type in question. But, like I said, I am just getting these delta values.

Now coming to the loop and I am unable to get the value from the end date for the very reason that it is not there.

Even when I have gotten close to having the loop working, when I look for the boolean field which needs to be altered if the `current date > end date`, this is also showing me several values with numbers after them.

What am I doing wrong?

# Answer
From the "***...adding a condition to check for a particular field on the node type in question...***" in your question, I bet you are aware about the importance of adding a Rules condition `Entity has field` (related to your field you're looking for). If not have a look at what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

However, even though nowhere in your question you indicate which Rules Event you're using, I bet you're using the wrong one. And the "Rules once per day" in your title is probably a good indication of what you really try to use as a kind of Rules Event (which is not really an event).

Nevertheless, I think you're just using the wrong approach (sorry). What I would do in your scenario, is a variation of my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder". Some more details about how to adapt that answer to fit your case here:

* Create a variation of the Rules Component (in Step 2) to change that boolean field for "a" node (which at least requires the node id as a parameter). Use the "execute" link in front of the Rules Component to QA-test your component (with a single node id, etc).
* Create a variation of the Rule (in Step 3) like so:

+ Use a Rules Event like "when such node gets created or updated" (something that fits your case).
    + In the Rules Condition of that rule, for sure you'll be able to use the "Entity has field" condition (for your date field).
    + In the Rules Action, you "schedule" the execution of the Rules Component mentioned above. For this you need to enable the Rules Scheduler, and that should do the trick.

Last but not least, be patient ... and wait until the specified date arrives, then wait for your next cron job to run (if you don't run that, nothing will actually get executed, be aware!). And then: **`voilà`**.
> 0 votes

---
Tags: 7, entities, rules
---


# Question
Title: Revert configuration languages overrides
Suppose you have a Drupal 8 multi site installation, with multi language support, and a custom module used across multiple sites.

This module has a view, with the yml file in:

`custom_module/config/install/views.view.custom_view.yml`

You also have to maintain some strings translations for this view to multiple languages (the view title among others). So for each language, you have:

`custom_module/config/install/language/[langcode]/views.view.custom_view.yml`

You install a new site enabling the custom module, and then adding languages to the site, and the configuration languages overrides are loaded properly into `config` table with `collection` attribute to `language.[langcode]`.

But… then you update the language file, adding missing strings or editing one of existing. Replicating those translations manually into production environment is not an option, because you have dozens of sites using this module… How can you reload these strings translations in a programmatically way for preparing a `hook_update_n` in the custom module, or via a drush command?

For updating configurations I'm using `config_update` module, with the following approach:

```
$configUpdate = \Drupal::service('config_update.config_update');

// Reload existing config
$configUpdate->revert('view', 'custom_view');

// Import a new config
$configUpdate->import('view', 'new_view');

```

But for reverting translations of those configurations I haven't found any approach yet. Any idea?

Thanks in advance.

# Answer
Answering to myself, I think I've found the solution:

```
$langcode = 'es';
\Drupal::service('language.config_factory_override')->installLanguageOverrides($langcode);

```
> 0 votes

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


# Question
Title: Image title in Views replacement patterns?
I can not seem to find the title token for images in replacement patterns in D8 views. In D7 it was \[field\_image-title\] but there is no title option in D8. I have tried {{ field\_image\_title }} and {{ field\_images-title }}.

# Answer
> 0 votes
The replacement pattern is:

```
{{ field_image__title }}

```

See this screenshot from Views:

---
Tags: views, 8, media
---


# Question
Title: Entity reference with ddf, dynamic dependent fields
I'm not able to configure ddf module, I followed the instructions but still nothing.

I'm sure is the best module for my necessity.

I have a content type "house" with a field "rooms" with cardinality +1.

In another content type I have a field "house", an entity reference of the "house" c. type and a dependent select list of rooms that should be updated by the value chosen on the precedent field.

I installed the ddf module, I created the view with the contextual filter and configured the dependent value with dynamic argument.

Unfortunately I'm missing something and the dependent value doesn't reload with the correct values.

Any tip will be much appreciated !

# Answer
DDF is a complex-looking module but there are only a few areas where you might make a mistake. Try enabling the submodule "DDF Entity Reference" on the modules page if you have not done so already. If you are still having problems after enabling the submodule, post here and I'll take another look at your entity reference view setup.
> 0 votes

---
Tags: entities
---


# Question
Title: How to assign a section to a specific node with Workbench?
I'm creating nodes using a custom modules

```
$node = new stdClass();
$node->type = $link['content_type'];

node_object_prepare($node);

$node->uid = $user->uid;
$node->name = $user->name;

$node->title = $html['title'];
$node->language = LANGUAGE_NONE;
$node->body[$node->language][0]['value'] = $html['html'];
$node->body[$node->language][0]['summary'] = $html['summary'];
$node->body[$node->language][0]['format'] = 'filtered_html';

$node->menu['enabled'] = 0; // 1 to enable providing a link in main menu
$node->menu['link_title'] = urlencode($html['title']);
$node->menu['description'] = urlencode($html['summary']);
$node->menu['parent'] = 'main-menu:0';

$node->menu['weight'] = 5;
$node->path['alias'] = urlencode($html['title']) . time();
$node->comment = 1;

$node->status = 1;        // 1 means published
$node->promote = 0;
$node->revision = 0;

$node->changed = $_SERVER['REQUEST_TIME'];
$node->created = $_SERVER['REQUEST_TIME'];

node_submit($node);
@node_save($node);

$node->path['alias'] .= '+' . $node->nid;

node_submit($node);
@node_save($node);

db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('vid', $node->vid)
    ->execute();

```

But now I need to assign each node a I create a workbench section, so I tried doing this:

```
$node->workbench_access = array('66');

node_submit($node);
@node_save($node);

$node->path['alias'] .= '+' . $node->nid;

node_submit($node);
@node_save($node);

db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('vid', $node->vid)
    ->execute();

```

This add the workbench access id temporarily, but when the page is refreshed it doesn't apply it. Is there a way to assign a node to a workbench section using php?

# Answer
> 0 votes
You could try an insert query to inject the access ID, node ID and access scheme into the workbench\_access\_node table.

---
Tags: 7, users
---