# Question
Title: Problem with submitting ajax form with autocomplete
I've been a newbie to drupal and trying to add feature to our corporate website (this module called 'userpasswords2' searches database of local mailsystem passwords). I'm using AJAX autocomplete and modification of the form.

AJAX autocomplete works fine, I can choose the user but I have a problem - I cannot submit the form by enter key. If I submit it by hittin 'submit' button by mouse, everything works fine. But I cannot submit it from keyboard.

I would like it to work like here https://api.drupal.org/api/drupal \- user enters for example 'hook', chooses what he/she needs, hits enter, then hits enter again and get the result!

So again - clicking submit button works fine, hitting 'enter' key doesn't work.

Googled a lot, the workarounds I've found doesn't work for me. Please help.

```
function userpasswords2_menu() {
  $items = array();
  $items['userpasswords2'] = array(
      'title' => 'User passwords',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('userpasswords2_form'),
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
  );
  $items['userpasswords2/ajax_username_autocomplete_callback2'] = array(
      'page callback' => 'ajax_username_autocomplete_callback2',
      'type' => MENU_CALLBACK,
      'access callback' => TRUE,
  );
  return $items;
}

function userpasswords2_form($form, &$form_state) {
  $form = array();
  $form['user'] = array(
      '#type' => 'textfield',
      '#title' => t('Введите имя пользователя'),
      '#autocomplete_path' => 'userpasswords2/ajax_username_autocomplete_callback2',
      '#executes_submit_callback' => 'TRUE',
  );
  $form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="box">',
    '#suffix' => '</div>',
    '#markup' => '<br>',
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'userpasswords2_callback',
      'wrapper' => 'box',
    ),
    '#value' => t('Submit'),
  );
  return $form;

```

}

```
function ajax_username_autocomplete_callback2($string = "") {
  $matches = array();
  if ($string) {
    $result = db_select('my_domain_passwords')
      ->fields('my_domain_passwords',array('fullname','password'))
      ->condition('fullname', db_like($string) . '%', 'LIKE')
      ->range(0,10)
      ->execute();
    foreach ($result as $user) {
      $form['custom']['username'] = $matches[$user->fullname] = check_plain($user->fullname);
      $form['custom']['password'] = check_plain($user->password);
    }
  }
  drupal_json_output($matches);
}

function userpasswords2_form($form, &$form_state) {
$form = array();
$form['user'] = array(
    '#type' => 'textfield',
    '#title' => t('Введите имя пользователя'),
    '#autocomplete_path' => 'userpasswords2/ajax_username_autocomplete_callback2',
    '#executes_submit_callback' => 'TRUE',
);

$form['box'] = array(
  '#type' => 'markup',
  '#prefix' => '<div id="box">',
  '#suffix' => '</div>',
  '#markup' => '<br>',
);
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
    'callback' => 'userpasswords2_callback',
    'wrapper' => 'box',
  ),
  '#value' => t('Submit'),
);
return $form;
}

function userpasswords2_callback($form, &$form_state) {
  if ( (!empty($form_state['custom']['username'])) && (!empty($form_state['custom']['password'])) ) {
    $output_string = $form_state['custom']['username'] . " : " . $form_state['custom']['password'];
  } else {
    $output_string = "No such user: " . $form_state['values']['user'];
  }
  $username = $form_state['custom']['username'];
  $password = $form_state['custom']['password'];
  $element = $form['box'];
  $element['#markup'] = $output_string;
  return $element;
}

```

# Answer
I think you need to do this:

```
$form['actions']['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'userpasswords2_callback',
      'wrapper' => 'box',
      'event' => 'click'
    ),
    '#value' => t('Submit'),
  );

```

just add 'event' =\> 'click' you your submit ajax element in the form. This must be done for all forms you want to be submitted through #ajax.
> 2 votes

# Answer
If you remove your autocomplete, you can be able to submit by press enter. So the issue is in the autocomplete function. You need to patch the `misc/autocomplte.js`. Following is the patch, check out the link for more details.

```
case 13: // Enter.
case 27: // Esc.
    this.hidePopup(e.keyCode);
    if (e.keyCode == 13 && $(input).hasClass('auto_submit')) {
       input.form.submit();
    }

```

This could be help you https://www.drupal.org/project/drupal/issues/309088
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: How to add value on custom field using rule action
I am new to Drupal. Trying to get it work with Rules module.

I have added new field (decimal type) to user: `field_user_custom` which I can see in DB as `user__field_user_custom` as a table.

I want to add value to this table on each article update.

I have setup rule as this:

1. Create a Reaction rule
2. React on Event: "After updating content"
3. Action:

a. Type: set data

b. Data Value: `@user.current_user_context:current_user:field_user_custom`

c. Value: 888

However, on article update, this value is not updated. I have tested if the rule is applied with having `System Msg` and it throws the msg but doesn't update the user field.

I doubt my **Data Value** is not correct. Which is why I have tried with this:

* user:field\_user\_custom

but this didn't help either. What am I missing?

# Answer
You were close. It's actually `@user.current_user_context:current_user.field_user_custom`, per "Set a data value"?.
> 1 votes

---
Tags: 8, rules
---


# Question
Title: How to properly save the commerce_license entity?
Unfortunately, Upgrading/downgrading recurring digital service plans with Commerce License asked two years ago didn't provide any specific solution, so here is another approach.

On https://www.drupal.org/project/commerce\_license\_billing/issues/2630196 @wizonesolutions says:

> you would just make your own upgrade/downgrade form. Load the user's license, and change the product\_id. CL and CLB will then automatically notice the plan change and adjust things accordingly when you save the license.

I've loaded user's license and changed the product id with the following code:

```
$entity = entity_load('commerce_license', array($license_id));
$entity[$license_id]->product_id='32';

```

but it's not clear how to save the license. Using `entity_save('commerce_license', $entity);` is giving the error:

```
EntityMalformedException: Missing bundle property on entity of type commerce_license. in entity_extract_ids() (line 7929 of /home/domain/public_html/includes/common.inc).

```

Could anyone guide me how to take this further, please?

# Answer
> 0 votes
Surely you mean:

```
entity_save('commerce_license', $entity[$license_id]);

```

Otherwise you’re trying to save an array as an entity, which wouldn’t work.

---
Tags: commerce
---


# Question
Title: Manage Display formatting settings won't work
I've got a problem with formatting decimal fields in Drupal using the Manage Display settings. I've already specified a thousands separator for this particular decimal field:

And clicked Update and Save: (see that it displays a sample value already formatted)

However, when I go to the actual field, it doesn't have any formatting:

Already tried formatting this field using a combination of a jQuery plugin and #attributes in this field's array, but Drupal won't save the value since it only accepts the dot and numbers as valid decimal value.

Is there anything I'm missing here? I should also say that I'm using a custom theme. I'm also willing to give info about my code as long as it doesn't touch sensitive business logic.

# Answer
*Manage Display* is for the front end, not the back end (i.e. not the entity edit form).

When the field value renders on the front end, you'll see the formatting you've chosen.

There's probably not much point trying to force formatting for a number in the backend, it makes more sense to take the raw number and then only manipulate it upon output. But if you absolutely need the functionality, it'll likely be a custom JS job as Drupal doesn't have anything built in to handle it.
> 0 votes

---
Tags: 7, entities, configuration
---


# Question
Title: Unpublish node based on date field with Rules
I'm trying to unpublish a node based on a date field with Rules. I've followed this tutorial but somehow it doesn't seem to work.

Here's my Component:

```
{ "rules_unpublish_termin" : {
    "LABEL" : "Unpublish Termin",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "node", "type" : "node" } },
    "ACTION SET" : [ { "node_unpublish" : { "node" : [ "node" ] } } ]
  }
}

```

And here's the Rule:

```
{ "rules_unpublish_termin_rule" : {
    "LABEL" : "Unpublish Termin Rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert--termin" : { "bundle" : "termin" } },
    "IF" : [ { "node_is_published" : { "node" : [ "node" ] } } ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_unpublish_termin",
          "date" : [ "node:field-termin-datum:value" ],
          "identifier" : "Unpublish content ID [node:nid] ([node:title]).",
          "param_node" : [ "node" ]
        }
      }
    ]
  }
}

```

I'm fairly new to Drupal and I've never used the Rules module so I'm not sure if there's something else I'm missing here.

*edit:*
I've been looking into it a bit more. Currently I have 3 nodes in this bundle with the following dates: 2018-01-09 (which should have been unpublished today)
2018-05-12
2018-07-14

In the Tab **Schudule** under admin/config/workflow/rules/schedule I can see that the component `rules_unpublish_termin` has a **Schedule Date** for 2018-07-14 00:00 which would correlate with the very last date, this seems a bit odd..

# Answer
> 1 votes
### 1. Timing of a scheduled Rules Component

After a rule is scheduled (using the Rules Scheduler, a submodule of Rules), it will only actually *execute* **next time cron runs**. Example:

* schedule a rule to execute at `timestamp X` (which appears to be `node:field-termin-datum:value` in your case).
* if the next time that cron runs is at `Y mins after timestamp X`, then the Rules execution will only happen then (= at `Y mins after timestamp X`).

BTW, as per the edit of your question, it seems that the Rules Component actually does get scheduled, and that your real issue is related to the execution of that scheduled component ... read on for more details about that.

### 2. Cron runs anonymous

Cron (always) runs with user anonymous, rest assured about that (in any Drupal 7 site). But here is an "*educated*" guess: your site is configured so that anonymous users are NOT allowed (= do not have the permission) to unpublish nodes.

Up to you to confirm if my guess is correct, but if it indeed applies, the answer to your question is that to get this to work you *would need* to grant anonymous users the permission to unpublish nodes. I bet it is not going to be what you *want* to do (I wouldn't ...), but trust me, *that* would be a prereq to make it all work in your site.

### 3. If everything else fails ...

If none of the above helps to find out what is causing your issue, then try either of these suggestions to get a better understanding of what is (not?) happening:

* Try to execute your Rules Component "manually" (just to test), to unit-test if it works as desired, so without using the Rules Scheduler. To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).
* Do some Rules debugging ... For way more details about that, refer to the answer to "How can I display the value of a variable inside a condition?".

---
Tags: 7, rules
---


title: How to alter a Rules Core Condition?

text:
# Question
Title: How to alter a Rules Core Condition?
I need to use the core condition 'Entity has field' but without the selection list restriction.

Easiest way to implement this is to wipe out the two restrictions manually. But how do I do this in a more persistent way - surviving module updates?

Original code:

```
function rules_entity_condition_info() {
  return array(
 //other stuff
'entity_has_field' => array(
  'label' => t('Entity has field'),
  'parameter' => array(
    'entity' => array(
      'type' => 'entity',
      'label' => t('Entity'),
      'description' => t('Specifies the entity for which to evaluate the condition.'),
      'restriction' => 'selector',
    ),
    'field' => array(
      'type' => 'text',
      'label' => t('Field'),
      'description' => t('The name of the field to check for.'),
      'options list' => 'rules_condition_entity_has_field_options',
      'restriction' => 'input',
    ),
  ),
  'group' => t('Entities'),
  'base' => 'rules_condition_entity_has_field',
),
//more stuff
);
)

```

# Answer
Pretty much every `info` hook has an `alter` counterpart. `hook_rules_condition_info` is no exception so you should be able to do something like this:

```
function MYMODULE_rules_condition_info_alter(&$conditions) {
  // Change something
  $conditions['entity_has_field']['field']['restriction'] = '';
}

```
> 0 votes

---
Tags: rules
---


# Question
Title: See my custom entity as a normal page in drupal 8
I created a custom entity with the drupal 8 console. Everything works well. However, when I am logged in as an administrator, my entity appears in an admin page instead of a normal page like for nodes.

In this case, the title and the edit links (tabs) are displayed in the gray bar of the administration.

How to make my entity appear as a node without the gray bar of aministration?

Thanks for your help.

# Answer
Then you have probably defined an admin path to view the entity:

*/src/Entity/MyEntity.php*

```
 *   links = {
 *     "canonical" = "/admin/structure/my_entity/{my_entity}",

```

Change this to a non admin path:

```
 *   links = {
 *     "canonical" = "/my_entity/{my_entity}",

```
> 1 votes

---
Tags: entities
---


# Question
Title: How to add a flag link to a view that contains only fields with relationships
Normally one would add a flag link as field in a view, in order to be able to flag an entity of a views row.

However, I cannot add a flag link to a view that only shows entities using a relationship, since the flag link already uses its own relationship and apparently cannot have another relationship on top of that.

So the question is, how can I add a flag link so that it will flag entities in views rows that use a relationship?

My case: I have a view based on entities of bundle 'project'. I have added a contextual filter that selects only the currently viewed project entity. I have added fields of project content that reference the current project, using the entity reference field 'field\_project'. The view shows all content referencing the currently viewed project. However, the flag that I add to the view does not flag the project content, but the viewed project. Result is that if I press one flag link, all flags appear as flagged in the view.

# Answer
Quote from your own comment:

> I removed the flag, and re-added it, and suddenly the relationship field is available in the flag. The funny thing is that the flag was already present when I changed the view to only contain related entities, and when I tried to edit the flag relation properties, it did not give a field to add a relationship. Removing and readding the flag did help.

So it seems that "*removing and readding the flag*" is the solution to answer your question.

Credits: Yuri and Niall Murphy.
> 1 votes

---
Tags: 7, views, flags
---


# Question
Title: When a variable parameter is changed in a Rules loop, the variable is unchanged outside the loop
I have a Rules loop in which a variable parameter is modified. The variable was created before the loop, and added as parameter in the loop.

However, If I check the value of the variable after the loop, it is unchanged.

Is this by design or what causes this?

# Answer
Have a look at this example of a Rule (in Rules export format), which is a variation of what you're asking for:

```
{ "rules_show_list_of_fields" : {
    "LABEL" : "Show list of fields",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "StartOfList-" },
          "PROVIDE" : { "variable_added" : { "email_list" : "List of eMail IDs" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email" : "Current eMail" },
          "DO" : [
            { "data_set" : {
                "data" : [ "email-list" ],
                "value" : "[email-list:value][current-email:value]-"
              }
            }
          ]
        }
      },
      { "data_set" : { "data" : [ "email-list" ], "value" : "[email-list:value]EndOfList" } },
      { "drupal_message" : { "message" : "The value of the email_list variable is: [email-list:value]." } }
    ]
  }
}

```

Here is a summary of what this rule does:

* Add a new variable `email_list`.
* Init the `email_list` value with some prefix.
* For each item within the loop, append the value of that item, followed by a separator character.
* Add a suffix to the `email_list` value.

In my case I'm using a multi value text field with machine name `field_email_addresses`, which contains eMail Ids, and just want to dispay a Status message with a concatenation of those eMail IDs, separated by a "`-`", and with a prefix (=`StartOfList`) / suffix (=`EndOfList`). And I also use Rules Events "Update existing node".

BTW, You could use this rule as a template to group multiple eMails (to individual eMail IDs) in a single eMail to all of those eMail IDs.

### Demo

Here is how the Status message looks like after you create a new node, or update an existing node (of type Article):

> The value of the email\_list variable is: StartOfList-user2@example.com-user4@example.com-EndOfList.

### Conclusion

The variable was created before the loop, and modified in the loop. And I display the value of the variable after the loop, it is changed like I wanted it to be changed.

As per what is shown in my answer here, it seems *something* is wrong in your rule (which you did not show in your question).

PS: I assume this question is about D7 ...
> 0 votes

# Answer
I agree with the conclusion of Pierre.Vriens. However, I have stumbled over a similar behavior as the OP.

If you alter the number of list items within the loop, the loop counter is not affected.

Example:

```
* List A contains three elements
* Loop the list
  * Remove one of the elements
* End loop

```

The loop will run three times, regardless of the change of the number of items in the list.
> 0 votes

---
Tags: rules
---


# Question
Title: How to override the core function format_xml_elements()?
`format_xml_elements()` is defined in the core includes/common.inc file. I want to manipulate some parts of this code, but there is no way to hook into this.

How could I achieve this without hacking core?

# Answer
You cannot directly make Drupal use a different function instead of `format_xml_elements()`, but you can replace those functions that (directly or not) calls `format_xml_elements()`.
For example, to alter how the RSS page for a feed is printed, you just need to replace `theme_aggregator_page_rss()` with a function implemented from your module using `hook_theme_registry_alter()`; to alter the output for the 'blog/%user/feed, or the blog/feed, or the taxonomy/term/%taxonomy\_term/feed, you implement `hook_menu_alter()` to replace the page callback Drupal uses with your own page callback.

What changes is the code you need to write in each case.
For example, `taxonomy_term_feed()`, the page callback for taxonomy/term/%taxonomy\_term/feed, calls `node_feed()`, which calls `format_rss_item()`, which calls `format_xml_elements()`. In this case, you can use the same code `taxonomy_term_feed()` uses, except it calls another function (e.g. `mymodule_node_fee()`) instead of `node_feed()`, which has the same code, except it doesn't call `format_rss_item()` nor `format_rss_channel()`, but your own functions. For the latter two functions, you can use the same code they use, except your code will code your replacement for `format_xml_elements()` instead of `format_xml_elements()`.

In the case of replacing `theme_aggregator_page_rss()`, you write less code.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Count the nodes created in the past 24 hours, 7 days, 30 days, and 365 days
I want to count the number of nodes created in the past 24 hours, 7 days, 30 days, and 365 days. I have used the Statistics module, but it isn't working.

I will not pass the year in the URL. So I don't want to use contextual filter method here.

How can I achieve this?

# Answer
Assuming your time base is now - delta and not midnight - delta, you can use the offset format in a date criteria. E.g. -24 hours or -30 days. I use this to display recent articles all the time.

Not sure if you can pass an offset as a contextual filter. But shouldn't be a problem to create sub views with different criteria and use a menu to select which one you want.

If you are looking for midnight based stats, you'll probably have to write your own view filter.

Also, I assume you know you'll have to use aggregation to get the counts.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do I define the block visibility for content types and term pages?
I have a block and I want to show it for specific content types and taxonomy terms. There is no common pattern for those pages.

For example, the URLs could be the following ones:

I don't want to show the block on the *Demo* content type, but on nodes of the content types, and term pages, without cloning/replicating the block.

How can I achieve this?

# Answer
If you control the code for the block, then it really is a simple matter of:

* Defining the correct cache contexts (path probably)
* In the build method, determining the context (getting current node, tax info from the node, and the like.)
* Deciding what to output for the context
* If you don't want to display it, return and empty build array (or NULL).

If you don't control the block content (e.g. view or 3rd party module), you can do the same as above and use the various methods to render the block from code.
> 0 votes

---
Tags: 8, blocks
---


title: Serve static files via S3

text:
# Question
Title: Serve static files via S3
I'm developing a Drupal 7 website that will be served from multiple servers behind a load balancer.

I want all static files generated by Drupal cache (JS, CSS, and also theme and modules images) to be served via an Amazon S3 bucket.

I already did this for my content types' file upload fields, using the Amazon S3 module, but it's missing the feature I described above.

I saw there's Media Mover module, but it's far from D7 production ready.

What other solutions are there?

# Answer
> 2 votes
I ended up using the S3AutoPush module. I migrated it to Drupal 7 and hacked the hell out of it to make it fit my needs.

If anyone reads this and is interested, I'd be happy to share my code. I won't put it on drupal.org for now since it's a real hack-job and not worthy yet.

# Answer
> 2 votes
Other Drupal 7 modules like the File API do this. However I have more experience with the Amazon S3 module.

The Drupal 7 AmazonS3 module still doesn't handle JS/CSS. There is a patch for this, however it's status for the past year has been set to "Needs work", because of the following response by Andrew Berry:

> I see a few issues with this patch as-is: 1. It's possible to have two file records for the same file, under different paths. For example, public://bucket/image.jpg and s3://bucket/image.jpg. For managed files, this could lead to data corruption. 2. We had to patch quite a few modules for the S3 wrapper to work properly, since it requires a bucket in the URL. I imagine a ton of modules hardcode public:// file paths without normalizing the URL. 3. There's a performance issue in that S3 can be very slow to create new assets and do an initial stat. For image styles, we basically replaced the style generation with our own code, which is a pain to do for CSS and JS. And, we could have very similar problems with contrib modules.
>
> Anyways, if we can address all of these I'd be interested in getting this in. However, I'm guessing to do this it a way that doesn't break all the things will have to wait for D8.

Speaking of Drupal 8, there is an s3 module by @cweagans that already handles aggregated CSS/JS files as well: https://www.drupal.org/project/flysystem\_s3 Hopefully this will be helpful to someone.

# Answer
> 0 votes
**It's the good advice that you just didn't take:**

Don't place your images/css/js files on Amazon S3 storage since this will complicate the hell out of your Drupal installation, specially when it comes to synchronizing. You'll find a solution for sure, but it will be ugly.

Use a reverse proxy on your static content directly on your production server. You can separate the images/css/js on a separate static subdomain (eg. assets.yourdomain.com). You could utilize Static Server Drupal Module for this.

Use Amazon S3 for a higher purpose, like ec2 snapshot backups, database backups, etc.

---
Tags: 7, files
---


# Question
Title: How to setup external CSS and JS to prevent render-blocking from Google PageSpeed?
We are using Google's PageSpeed to help optimize the site. A couple constant issues that come up include render blocking CSS and JS. We have tried the following in our libraries.xml file, but cannot find the appropriate way to do this in D8.

We have found this to be an issue with our local aggregated CSS files that come from our theme and with external CSS and JS

We have tried:

1. AddAgg module but that still does not solve the issue as we still get render blocking CSS and JS
2. code below is what we have tried with and without preprocess = false. setting the attributes to async: true does not load the page properly so we using defer: true
3. We also tried moving the css-placeholder and js-placeholder from our html.html.twig file to the bottom of the page but that has side effects.

mytheme.libraries.yml

```
fonts:
  css:
    theme:
      //fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i: { type: external, preprocess: false, minified: true }
      //maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css: { type: external, preprocess: false, minified: true }

slick_carousel:
  css:
    theme:
      //cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css: {type: external,preprocess: false, minified: true}
  js:
    //cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js: { type: external, preprocess: false, minified: true, attributes: { defer: true }}

```

What is the proper way to add external and local CSS and JS without render-blocking?

# Answer
> 2 votes
Defer for JavaScript is how to do js. CSS is a lot harder. You need to generate critical css and inline it and then still load the CSS in a deferred way. This explains how to do so with the 7.x version of AdvAgg; the 8.x version shouldn't be that far off.

https://groups.drupal.org/node/517292

Font's are their own special thing, the advagg relocate sub module handles the browser cache part, the advagg font module makes font loading async.

This is the easiest site to use to generate critical css https://www.sitelocity.com/critical-path-css-generator but it might not give the best results.

---
Tags: 8, theming
---


# Question
Title: Cant find any info on this method being removed in webform or how to fix
I am writing a patch for a module that used an old beta or even alpha of webform for drupal 8.

There is a line `WebformEntityReferenceItem::getEntityWebformFieldName($node);` in the module that errors out saying `getEntityWebformFieldName()` does not exist and sure enough in `Drupal\webform\Plugin\Field\FieldType\WebformEntityReferenceItem` the method does not exist.

I checked an older release and the method was there at some point. I've been searching since yesterday but cannot find a workaround or even an answer as to why it was removed. Any ideas?

***EDIT***

So I managed to get it working, but this certainly seems like the incorrect way to do it.

`$node->get('webform')->getValue()[0]['target_id'];`

So it seems `WebformEntityReferenceItem::getEntityWebformFieldName($node);` just gets the webform on the webform node and then grabs its 'target\_id' value.

```
$webform_field_name = WebformEntityReferenceItem::getEntityWebformFieldName($node);
$webform_id = $node->$webform_field_name->target_id;

```

What I posted in my edit, I do not believe is the correct solution, albeit it is now working. Any suggestions would be appreciated.

# Answer
The WebformEntityReferenceItem::getEntityWebformFieldName() static method was not removed but it was refactored and moved to the 'webform.entity\_reference\_manager'service.

Here is an example of showing how to use the service.

```
/** @var \Drupal\webform\WebformEntityReferenceManagerInterface $entity_reference_manager */
$entity_reference_manager = \Drupal::service('webform.entity_reference_manager');
$field_name = $entity_reference_manager->getFieldName($node);
...

```

@see \Drupal\webform\WebformEntityReferenceManager

@see \Drupal\webform\WebformEntityReferenceManagerInterface
> 5 votes

---
Tags: 8, webforms
---


# Question
Title: How can I set a different theme basing on the language currently used for the page?
We have built one website in English and we want to translate it in Arabic.

Since I am new to Drupal, I am not sure how I can set a theme for English, and one for Arabic. How should I achieve this?

# Answer
you can check the current language with the languageManager (docs here)

```
Drupal::languageManager()

```

and then you can set a different theme with the theme service

```
\Drupal::service('theme_handler')->setDefault('test_theme');

```

Hope it helps,
> 1 votes

---
Tags: 8, theming, multi-sites
---


# Question
Title: Admin edit ... page not found because of alias with characters
hi everyone … my problem is in the title I can not edit pages that have accent in alias path e.g.: http://localhost:8888/MYSITE/bôbô/ïèéà/my-contënt

i got a page not found .. but i still able to edit my content if i write the same url without any accent e.g.: http://localhost:8888/MYSITE/bobo/ieea/my-contënt

So in a nutshell, if i have custom alias with path that contains characters accents it is NOT OK ( tells me page not found when i want to edit it) http://localhost:8888/MYSITE/anypath\_with\_accent\_1/anypath\_with\_accent\_2/edit?destination=node/ANYNODE

but if i replace in url

http://localhost:8888/SYDEV/node/ANYNODE/edit?destination=node/ANYNODE

that’s ok i can edit my content

So anyone has any idea to solve that ?

My idea is to force url ( only for admin ) to be node/ANYNODE/edit?destination=node/ANYNODE

But i simply don’t know how and even if it’s possible.

Thank you for advice or solutions

.. and of course i wish you an happy new year !!!

# Answer
The standard URL aliases of Drupal work for the view URLs only. No matter of enabled transliteration or not.

An example: If you have a content node with ID `10`, then the regular view URI would be `/node/10`, but you can alias it with e.g. `/my-path/my-node`. If you want to edit the node, you still use `/node/10/edit`.

Enabling the redirect module, you can make sure that the content will not be viewable by both URIs `/node/10` AND `/my-path/my-node`, but only by tha aliased version `/my-path/my-node` (which is desirable for avoiding search engine penalties). The edit URI remains being `/node/10/edit`.

In some of your comments (you should add such information to the original question) you stated, that you created automatic alias patterns using the pathauto module to automatically generate the aliases for content.

If your use case requires sub paths as `/edit` to be rewritten to your alias as well, so in above example `/node/10/edit` to `/my-path/my-node/edit`, have a look to the subpathauto module. You might even have it installed and enabled already, as you state that such URIs are working for non-accented aliases.

But be aware, that it's in beta stage and has some bugs in conjunction with the above mentioned rewrite module. So to make the rewrite working with the currently available development version for Drupal 8, you might still have to apply the latest patch from issue #2875026.

And if the above patch is applied, but rewriting still doesn't work when you use accented characters in the URL aliases, then you will have to create an according issue within the subpathauto issue queue, as this is the right place for module specific errors.
> 0 votes

# Answer
The Pathauto module has an option (*Transliterate prior to creating alias*) which replaces some characters with equivalent characters in the US-ASCII alphabet; for example, it replaces *è* with *e*. By default that is selected, but you can deselect it in /admin/config/search/path/settings.

>

There is also another setting that replace the characters with characters in the ASCII-96 set, but as you see from the screenshot, that is disabled by default.

Notice also that page contains other settings that alter the characters present in a path alias, for example the one for the words that should not appear in the path alias, which by default are: *a*, *an*, *as*, *at*, *before*, *but*, *by*, *for*, *from*, *is*, *in*, *into*, *like*, *of*, *off*, *on*, *onto*, *per*, *since*, *than*, *the*, *this*, *that*, *to*, *up*, *via*, *with*.

>

As for the *Pathauto i18n* module you installed, that is not ready for Drupal 8. Its code is still for Drupal 7, with the exception of few functions. Drupal 8 will recognize it as Drupal 8 module simply because it has a .info.yml file as requested, but most of the code is still using Drupal 7 functions. That is also the cause of the error you reported in your comment.

Uninstall it, or you will not be even able to visit the settings page of the Pathauto module.

Finally, if you want the path alias to work also, for example, node/30/edit, then you need to install the *Sub-pathauto (Sub-path URL Aliases)* module, which in its project page clearly states:

> For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.

Keep in mind the module is still in beta phase, and check the issues opened for that module, for example Redirect module causes redirect back to unaliased path, which is of interest for you if you also use the *Redirect* module.
> 2 votes

# Answer
Are you using Pathauto? If you are and it's creating the paths, make sure that you have `Transliterate prior to creating alias` checked in the settings, then it will make sure that all of your aliases are being saved with web-safe characters in the URL.
> 0 votes

# Answer
well in fact i had menu items without node destination ... so breadcrumb shown alias and not title .. i just had to create node destination for items menu and voilà. Thank you everyne for your help
> 0 votes

---
Tags: nodes, path-aliases
---


# Question
Title: Multiple Views filters criteria : query with LEFTJOIN instead of INNERJOIN?
I created a view with 2 FILTER CRITERIA (Content: Has taxonomy term) exposed to visitors.

For testing purpose, I have 2 vocabularies with 2 terms inside :

**Vocabulary 1**

1. T1
2. T2

**Vocabulary 2**

1. T3
2. T4

I have 2 articles. Article 1 is only PART of T1.

If I select T1 and Any, I have no results but I should have result because I use OR operator(see screen shot).

Is the view filter criteria correct ?

If this article is T1 and T3 and i select T1 and T3, it works. If I select any and any, it works and i see my 2 articles.

See 2 cases :

1)

2)

How can I have a query with LEFTJOIN instead of INNERJOIN ?

# Answer
Checking the "reduce duplicates" fixed the issue for me.

In "Views setting" (admin/structure/views/settings), check "Show the SQL query"

Then, we can see the SQL query built with views.

With reduce duplicates, `INNER JOIN` are converted to `LEFT JOIN`, which is exactly what I need I think.

When it was unchecked, the SQL query was :

```
SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
INNER JOIN {taxonomy_index} taxonomy_index ON node_field_data.nid = taxonomy_index.nid
LEFT JOIN {taxonomy_index} taxonomy_index2 ON node_field_data.nid = taxonomy_index2.nid AND taxonomy_index2.tid != '2'
WHERE ((taxonomy_index.tid = '2')) AND ((taxonomy_index2.tid = '10'))
ORDER BY node_field_data_created DESC
LIMIT 11 OFFSET 0

```

When it is checked :

```
SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {taxonomy_index} taxonomy_index_value_0 ON node_field_data.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = '2'
LEFT JOIN {taxonomy_index} taxonomy_index_value_1 ON node_field_data.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = '10'
WHERE (taxonomy_index_value_0.tid = '2') OR (taxonomy_index_value_1.tid = '10')
ORDER BY node_field_data_created DESC
LIMIT 11 OFFSET 0

```
> 1 votes

---
Tags: views
---


title: Setting up a grid to carousel?

text:
# Question
Title: Setting up a grid to carousel?
Alright everyone, I'm sure this is a relatively simple thing, but I'm on the verge of tearing my hair out.

What I'm trying to accomplish is setting up images to appear in a grid, that when clicked pulls up a gallery/carousel, allowing you to scroll through the images there as well.

I've downloaded the slick modules, and correct dependencies. I also have bootstrap correctly set up as well. Honestly if you have an alternative your prefer more, please let me know.

https://www.drupal.org/project/slick -https://github.com/kenwheeler/slick/ -https://github.com/gdsmith/jquery.easing https://www.drupal.org/project/slick\_media https://www.drupal.org/project/media\_entity\_image https://www.drupal.org/project/video\_embed\_field https://www.drupal.org/project/blazy

Drupal 8

# Answer
> 1 votes
I prefer the Lightgallery module which is available for Drupal 7 and Drupal 8 also. It integrates the lightGallery jquery plugin into Drupal. This is compatible with Views and it also provides an image field formatter.

You can see demos for the lightGallery jquery plugin here.

# Answer
> 0 votes
I almost always use Slick for carousels, but it sounds like you're maybe asking for the image to pop up in a modal window.

For Drupal 8, the Colorbox module is good for that.

https://www.drupal.org/project/colorbox

You can use it for image fields or views.

Edited to add: Here's a tutorial!

https://www.ostraining.com/blog/drupal/drupal-8-responsive-colorbox-gallery-with-caption-text/

---
Tags: 8, media
---


# Question
Title: How to replace the title of the profile in the breadcrumb, by the name of the user?
I installed the "Profile" module. I have rewritten the url with the username instead of the profile title.

When I visit a profi, the url is corect but the breadcrumb is still indicating the title of the prodil.

How to replace the title of the profile in the breadcrumb, by the name of the user ?

# Answer
> 0 votes
you can implements this hook in a custom module or in your theme.

```
hook_preprocess_breadcrumb()

```

Then you can access `$variables` and manage it easily (like put the username in the last element of the array). Regards,

---
Tags: views, 8, users, breadcrumbs
---


# Question
Title: How to identify which Rule is triggered?
I have a collection of email notifications created with Drupal Rules module and a separate custom database table with the ID's of the rules and emails to exclude from individual notifications.

I need to know which rule is being triggered so I can query my custom table for the correct emails to exclude. Creating custom conditions would not work because I have 20+ rules using the same custom action.

The only hook that I can find that is triggered after a rule is executed is hook\_rules\_config\_execute but it does not give me information only on the specific rule that triggered.

# Answer
Below are 2 approaches that might work ...

### Approach 1

Create a NEW Rules Component like so:

* It uses some "identifier" as a *parameter*, of type something like "text" or "integer".
* All this component does, is to also perform your custom action.

For each of your existing rules, rework that Rules Action like so:

* Replace it by performing the new Rules Component.
* For the (required) parameter of the Rules Component, use some unique value (just an integer, or maybe the machine name of the rule?), so that when the Rules Component is executing, you do know which rule it was that triggered the execution of the Rules Component.

### Approach 2

Update each of your rules to contain and pass in a unique identifier. You can just do that by adding another parameter to the existing Rules Action in your `rules_action_info` hook. Though you'd have to update all your existing rules to make that work.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Drush error when running dmu-analyze to update drupal modules
I'm using `drupal module upgrader` with drush to update the modules which are drupal 7 compatible at the moment. I'm getting this error when I try running `drush dmu-analyze MODULE_NAME`

I can't seem to find a solution on the net to fix this issue. I have tried re-installing the module or drush. Even when I type `drush status` I'm also getting this error.

# Answer
One of the modules in your installation is incorrectly using references to services without quoting them.

e.g.

```
[@container.namespaces]

```

instead of the valid:

```
['@container.namespaces']

```

The error message doesn't provide enough details to be able to identify which module is causing the problem. It's going to be a contrib/custom one, though, so check the .services.yml file for the extra modules you have installed and you should find the culprit. It's likely to be under a service whose name begins with `plugin.manager.`.
> 1 votes

---
Tags: drush
---


# Question
Title: After upgrading, the autoloader is not working
Recently, I updated from 8.1.8 to 8.1.10 (via `composer update`). In my local environment (running scotchbox, PHP 5.6.14), it runs fine. When deployed to the staging server (running CentOS 6.7, PHP 5.5.17), the site returns a 500 and writes the following to error\_log:

> PHP Fatal error: Class 'Drupal\Core\Site\Settings' not found in /home/\[site\]/public\_html/drupal/core/lib/Drupal/Core/DrupalKernel.php on line 964

I copied basically everything except the /sites/ directory, so I don't think I'm missing anything.

I tried restarting httpd to no avail.

It seems like a problem with the autoloader and possibly due to the PHP version mismatch. There are many layers between autoload.php and the DrupalKernel.php bootstrap process. I'm at a loss as to what's going on here. Any help would be appreciated.

# Answer
> 1 votes
It sounds like the changes that composer made to your local environment weren't carried over. Without knowing any of the details of what might be different, you'll have to do some introspection. You can test the autoloader in both your dev/staging environment to tease out what's occurring differently in each environment.

There a few things you can do to test the autoloader:

* Within **index.php** you can use the statement `var_dump($autoloader)` to dump the autoloader; it should have a `classMap` property which should have a keyed array that maps classes to PHP files. It should include a value for `Drupal\Core\Site\Settings`.
* Within **vendor/composer/autoload\_real.php** is the logic that registers the autoloader and includes other **autoload\_\*.php** used to build the autoloader object. You can various `var_dump()` statements to follow the path of execution to make sure the autoloader is being built correctly.
* Within **vendor/composer/ClassLoader.php** you use the `var_dump($class)` statement in the `ClassLoader::loadClass($class)` method to have PHP spit out classes as the autoloader is including them.

# Answer
> 1 votes
I solved a similar problem changing file permissions. Try changing group ownership of files to "www-data" recursively both in vendor and web folder.

```
chown -R $USER:www-data vendor web

```

CentOS server should use "apache" instead of "www-data"

```
chown -R $USER:apache vendor web

```

---
Tags: 8, composer
---


# Question
Title: Views - Add a wrapper around fields or rows
Example:

I have a view with fields:

```
[field_name]    == Field collection item: Name
[field_title]   == Field collection item: Title
[field_text]    == Field collection item: Text

```

I can wrap these fields by excluding from display first two of them, and rewriting the output of the third field with tokens, for example:

```
<div class="span4">
    <div class="some_style">
        <blockquote>[field_text]</blockquote>
        <h5>[field_name] // [field_title]</h5>
    </div>
</div>

```

It seems a bit tricky, so here is my first question:

**Is there any module or just another way to wrap fields in views?**

*I know Semantic Views module which solve the problem, but there is no recommended releases for Drupal 7.*

**Question #2**

All my fields are wrapped in their div like in above mentioned example, but this is only the one row, and I have several rows. I need wrap all of them in another div.

**Do I have to create a view template file only for that?** which contain for example:

```
<?php if($rows): ?>
    <div class="rows">
        <?php print $rows; ?>
    </div>
<?php endif; ?>

```

I have a feeling like I miss something when I have to create a special template file only for one wrapper.

# Answer
> 5 votes
I think it's pretty safe to say that most people tackle both of your questions using the Cascading features of CSS.

For example, a typical view's HTML looks somewhat like this:

```
<div class="view view-NAME view-id-VIEWID view-display-id-VIEW-DISPLAY-id">
  <div class="view-content">
    <div class="views-row views-row-1 views-row-odd views-row-first">
      <div class="views-field views-field-FIELDNAME1">
        <span class="field-content">
           <!-- field content here -->
        </span>
      </div>
      <div class="views-field views-field-FIELDNAME2">
        <span class="field-content">
           <!-- field content here -->
        </span>
      </div>
    </div>
    <div class="views-row views-row-2 views-row-even">
     <!-- etc etc etc -->
    </div>
  </div>
</div>

```

So, to your 1st question, Views already creates a div that wraps each row, that's the `<div class="views-row ...">` one. You can style it per view by doing something like this:

```
.view-NAME .views-row {
  /* styles for the rows div goes here */
}

```

And to your 2nd question, Views also already creates a `<div>` that wraps all the rows, that's the `<div class="view-content">` one. To style it for a particular view you can do something like this:

```
.view-NAME .view-content {
  /* styles for the div wrapping your rows goes here */
}

```

Now, somewhat obviously, this is all dependent upon your theme. I am aware that some out there dislike all the markup Drupal by default creates and has overridden a lot of the standard templates to create leaner markup.

If that's the case in your instance, you should still be to instruct Views to add a class to each row if you want. This is accessed via the overall Style Settings (where you can also look at each Views template that is used for the particular view).

You could also instruct Views to add a class to each field wrapper. This is accessed from the config widget by each field.

ADDITION based upon commentary:

The Views template that creates the output of the view-content div is `views-view.tpl.php` and the code in question is:

```
<?php if ($rows): ?>
  <div class="view-content">
    <?php print $rows; ?>
  </div>
<?php elseif ($empty): ?>
  <div class="view-empty">
    <?php print $empty; ?>
  </div>
<?php endif; ?>

```

so without changing this up, you're right, Views doesn't allow quick and easy preprocessing of the View to insert any other variables into that div's classes.

You could however use Views' preprocessing hooks to create an additional variable so you don't need to create lots of additional templates but rather just one more.

For example, copy `views-view.tpl.php` to your theme (easiest) or module (requires special Views theme incantations :) and modify it along these lines:

```
<?php if ($rows): ?>
  <div class="view-content <?php print $my_special_content_class; ?>">
    <?php print $rows; ?>
  </div>
<?php elseif ($empty): ?>
  <div class="view-empty">
    <?php print $empty; ?>
  </div>
<?php endif; ?>

```

and then create a views preprocess hook along these lines:

```
function YOURTHEMEORMODULE_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='VIEWYOUWANT' && $display_id=='DISPLAYYOUWANT') {
    $vars['my_special_content_class']='FOO';
  } else {
    $vars['my_special_content_class']=''; // so we don't have to isset() or !empty() it in our template :)
  }

}

```

Save everything and clear your theme cache and now you should be on your way.

SECOND ADDITION:

Upon further thought, and a 'doh!' moment, you can do this without a template at all in preprocess like this:

```
function YOURTHEME_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='VIEWYOUWANT' && $display_id=='DISPLAYYOUWANT') {
    $vars['rows']='<div class="FOO">' . $vars['rows'] . '</div>';
  }

}

```

if you don't mind another wrapped div in there. And, I think you will need to/should do this in your theme instead of a module so you make sure this happens in the right order, eg, you want this to happen after Views is all said and done with things, and the theme hooks always run after the module hooks.

# Answer
> 1 votes
You could also use the `rewrite` feature inside the view.

Assuming you have `field_name`, `field_title` and `field_text` and you would like to add a div with a class called `content` around these:

1. In the view under `FIELDS` click on `field_name`
2. Scroll down to `REWRITE RESULTS` and check `Rewrite the output of this field`
3. In the text box that appears, fill in something like `<div class="content">[field_name]` **NOTICE** that you don't should close the `div`
4. Save the field
5. Under `FIELDS` click on `field_text`
6. Scroll down to `REWRITE RESULTS` and check `Rewrite the output of this field`
7. In the text box that appears, enter `</div>` **THIS CLOSES THE CONTENT DIV**
8. Save you field

I guess the above will not always work depending on what kind of wrapper elements your field have.

# Answer
> 0 votes
You can use views field or row templates but you will need to create template for every field.

May be this page will help you. Here is the sample code:

```
<?php
/**
  * Generic preprocess that is still working on D7
  */
function MYTHEME_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name)) {
    $function = __FUNCTION__ . '__' . $vars['view']->name . '__' . $vars['view']->current_display;

    if (function_exists($function)) {
     $function($vars);
    }
  }
}

/**
  * Then the specific preprocess that worked without the above code for D6
  */
function MYTHEME_preprocess_views_view_fields__VIEWNAME__DISPLAY(&$vars) {
  // my specific preprocess code
}
?>

```

Related: Specific preprocess functions for theme hook suggestions are not invoked at Drupal.org

# Answer
> 0 votes
You can also use Semantic Views.

> This Views plugin makes unformatted styles, field row styles and other output more readily configurable without needing to override template files. Instead of overriding row style templates for views where you want to specify different HTML elements (tags) and class attributes, you can specify these inside the Views UI and avoid overriding templates for each view.

# Answer
> 0 votes
To preprocess field\_collections and override output, try the following example found on dropbucket which give you some handy snippet by @dane:

```
function mytheme_preprocess_field(&$vars) {
  if($vars['element']['#field_name'] == "field_your_fc_field"){
    $fcs = array();
    foreach (element_children($vars['element']) as $key) {
      $fcs[] = array_pop($vars['element'][$key]['entity']['field_collection_item']);
    }
    // now you have all your fcs pulled out of that nasty array
    foreach ($fcs as $fc) {
      # code... that
    }

    // I would recommend overrideing items markup for whatever black magic you desire
    $vars['items'] = array(
      '#markup' => "Whatever you need to render",
    );
  }
}

```

# Answer
> 0 votes
To add a wrapper to fields such as field collection, you should define the logic in `hook_preprocess_HOOK` (where HOOK can be `views_view_field`), then expose these variables into template file, for example:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_views_view_field(&$vars) {
  $view = $vars['view'];
  switch ($view->name) {
    case 'my_view':
      $node = entity_metadata_wrapper('node', $vars['row']->nid);
      $vars['name']  = $node->field_name->value();
      $vars['title'] = $node->field_title->value();
      $vars['text']  = $node->field_text->value();
    break;
  } // end: switch
}

```

So now you can use these variables inside the template file (`$name`, `$title` and `$text`), so you can wrap it easily.

# Answer
> 0 votes
Try Views Rows Wrapper module. It wraps every N rows with Div/Span element with custom class or id name.

# Answer
> -2 votes
You can use Drupal 7 Field Formatter CSS Class Module.

> The **Field formatter CSS class** module allows you to set any text/list/option/taxonomy field to render as CSS class on the node. This enables the node author to select predefined CSS styling per node.

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


# Question
Title: Programatically accessing block settings
Is it possible in Drupal 7 to load block visibility settings programatically in module? I'm rendering block programatically and I want to include checking those settings, so it still will be possible to hide block from UI. Property of "status" and "visibility" are not enough, since it's possible that the block won't be placed in any region at all.

# Answer
Sure, `block_load` gives you the contents of the whole row from the `block` table:

```
$block = block_load('module', 'delta');

$region = $block->region;
$weight = $block->weight;
$custom = $block->custom;
$visibility = $block->visibility;
$pages = $block->pages;
$title = $block->title;

```

And so on.
> 0 votes

---
Tags: blocks
---


title: Template override doesn't work

text:
# Question
Title: Template override doesn't work
I am trying to develop a Drupal 8 module in which I have to override the html.html.twig template. The idea is that I do not want any of the default html.html.twig template returned instead I only want the custom template returned. I have been spending hours Google hunting and trying to make sense of the many examples and I have gotten myself totally confused.

What is happening is the content of my custom template are being displayed in the default html template so I am seeing the custom content inside the default html template rather than overriding the default content.

For the sake of getting this template override working I have simplified the module as much as possible and simply want to return the contents of a variable into a placeholder in the twig template. Once this override is working I can go back and add the code that will create the correct content to be output into a number of variables in the template.

What I do not understand is exactly how to I override the html.html.twig template.

My module is called unsw\_blocks and in the unsw\_blocks.module I have the following

```
function unsw_blocks_theme() {

$theme = [
'unsw_blocks' => [
     'variables' => ['test_var' => NULL],
    ],
];

return $theme;
}

```

In the Unsw\_blocksController.php have the following

```
class Unsw_blocksController extends ControllerBase {

  public function unsw_blocks($name) {
  return [
    '#theme' => 'unsw_blocks',
    '#test_var' => $this->t('The variable called test_var simply passes this text itself to the theme template'),
  ];
  }
}

```

In the custom modules templates directory I have unsw-blocks.html.twig which simply contains

```
<h1>Testing Template</h1>

<p>test_var: {{ test_var }}</p>

```

# Answer
HI please follow the below steps.

Step 1: create routing file **docroot\modules\custom\product\product.routing.yml**

```
product.custom_form:
  path: '/product/details/{product}'
  defaults:
    _controller: '\Drupal\product\Controller\ProductDetailsController::details'
    _title: 'Product Details'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      product:
        type: entity:node

```

Step 2: Create a controller: **modules\custom\product\src\Controller\ProductDetailsController.php**

```
   /**
   * Callback for route product.custom_form.
   */
  public function details($product)

    return [
      '#theme' => 'product-details',
      '#content' => [
        '#contextual_links' => [
          'node' => [
            'route_parameters' => ['node' => $product->id()],
          ],
        ],
      ],
      '#product' => $product,

    ];
  }

```

Step 3: In your theme create a file following the directory **themes\custom\mytheme\templates\product-details.html.twig**

```
<div class="my-form-class">
    <div class="page-header">
        <h1>{{ product.title.value }}</h1>
        <h2>
            {% if product.field_title_description %}
                {{ product.field_title_description.value }}
            {% endif %}
        </h2>
    </div>

```
> 0 votes

# Answer
AFAIK you can't override html.twig in a module, but you can create module with a route and a controller that returns a Symfony response to bypass this limitation. There is background-information and a code example in this question:

Override html.twig.html within custom module
> 0 votes

---
Tags: 8, theming
---


title: user_delete function is very slow

text:
# Question
Title: user_delete function is very slow
I am writing a script to delete 200+ users. To achieve this, I write a **db\_select** query and got all the UIDs. The I wrote **foreach** loop to delete users using '**user\_delete**' function. But this is taking lot of time to delete a single user. It will be very hard to delete 200+ users.

Can someone help me to solve this program to delete bulk users programmatically?

# Answer
If you want to maintain data integrity, there's not much you can do to speed the process up except upgrade your server's hardware.

`user_delete` calls `user_delete_multiple`, and it has plenty to do for each record; not just deleting the user record, it deletes fields/data, invokes hooks, clears caches, etc. All of that needs to happen or you're likely to find problems further down the line.

If you're finding that the slowdown is causing the script to timeout, you can process the list with the Batch API and solve that at least.

Incidentally, if you *don't* care about data integrity, you can just cherry pick the lines from `user_delete_multiple` that you do need, and execute those directly instead.
> 2 votes

---
Tags: 7, users
---


# Question
Title: How to unset or hide a view header / footer when an exposed filter is being applied?
I have a header in a view that should be visible only if there are no values in the exposed filters. So, once the user enters any value in any filter and sends the form, this header should not be visible. And the same for a footer in other views.

How to unset or hide a view header / footer when an exposed filter is being applied?

# Answer
> 3 votes
I found this solution that is really very simple:

```
use Drupal\views\ViewExecutable;
/**
 * Implements hook_views_pre_view().
 */
function MODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'nouvelles' && $display_id === 'block_1' && !empty($view->getExposedInput())) {
    $view->removeHandler($display_id, 'header', 'view');
    //or
   // $view->removeHandler($display_id, 'header', $view->getHandlers('header')['view']['id']);
  }
}

```

With the getExposedInput() function you can figures out what the exposed input for this view is, so wee need to check if the returned value is not empty.

The function removeHandler() is the key here, but wee need to know:

> public ViewExecutable::removeHandler($display\_id, $type, $id)

```
$display_id -> is in the function params
$type -> can be header or footer
$id -> view (see the getHandlers() output)

```

You can found additional info with the getHandlers() function:

```
dpm($view->getHandlers('header'));

```

> ```
> Array (
>     [view] => Array
>         (
>             [id] => view
>             [table] => views
>             [field] => view
>             [relationship] => none
>             [group_type] => group
>             [admin_label] =>
>             [empty] => 1
>             [view_to_insert] => en_vedette:block_1
>             [inherit_arguments] =>
>             [plugin_id] => view
>         )
>
> )
>
> ```

# Answer
> 1 votes
For a Better Approach, you can use:

```
hook_preprocess_views_view(&$variables)

```

And Apply condition on the basis of $view-\>exposed\_data

And Implement it in the Views Twig file: For Example: In sub\_theme.theme

```
if($view->exposed_data['type'] = 'content_type'){
$variables['this_val'] = 'content_type_name';
}
```

In Views.html.twig

```
{% if this_val == 'content_type_name' %}
{{ footer }}
{% endif %}

```

---
Tags: 8, views
---


# Question
Title: display field group in different tab/URL
I have been struggling with this. Views cannot help me (or I didn't figure out how).

I have created a new tab to my profile 2 in my custom module using custom\_menu custom\_menu\_alter custom\_menu\_local\_tasks\_alter

The URL is mywebsite.com/profile-main/%user/preferences

*Preferences* is the new URL linked to the new tab.

My aim is to display a field group with a bunch of preferences info in that new tab/URL Technically under that tab I want the user to log any preferences they have regarding newsletters and how we contact them etc...(GDPR related stuff) I need the data to be attached to the specific user.

I can't seem to figure it out. I am not very confident with hooks and custom code and at this point I am stuck. What did I miss?

Any clue on how I could achieve this?

I am using Drupal 7. What I want is to move fields (in a field group) from the main profile 2 registration page form and display them in the new tab accessible when logged in to profile 2 account, instead of having everything in the same form. But I am happy to have to create a different form if it would work better. This is what's returned by custom menu:

```
$items['profile-main/%user/preferences'] = array(
  'title' => t(' Preferences'),
  'page callback' => 'custom_user_preferences',
  'page arguments' => array(1), // Uid
  'access callback' => TRUE,
  'access arguments' => array('access candidate_dashboard'),
  'type' => MENU_LOCAL_TASK,
);

```

This is the array for custom\_user\_preferences:

```
'custom_user_preferences' => array(
  'file' => 'includes/user_preferences.inc',
  'template' => 'templates/user_preferences',
  'variables' => array(
    'profile' => NULL,
    'approved' => NULL,
    'cust_type' => NULL,
  )
),

```

**edit:** Am I right to assume that I have to

1. programmatically create a form
2. which upon submission saves the data in relevant profile2 fields
3. display the form in the new path I created

**edit 11/jan**

In the end I am creating a form as the fields I need to add are not in the profile 2 set up to start with (the profile 2 registration form has more than 180 fields in it). I've been receiving error:

```
*Warning: Illegal string offset '#tree' in form_builder() (line 1891 of /**/**/**/site/includes/form.inc).
Warning: Illegal string offset '#tree' in form_builder() (line 1911 of /**/**/**/site/includes/form.inc).
Warning: Illegal string offset '#parents' in form_builder() (line 1911 of /**/**/**/site/includes/form.inc).
Notice: Array to string conversion in form_builder() (line 1911 of /**/**/**/site/includes/form.inc).
Warning: Illegal string offset '#array_parents' in form_builder() (line 1916 of /**/**/**/site/includes/form.inc).
Notice: Array to string conversion in form_builder() (line 1916 of /**/**/**/site/includes/form.inc).
Warning: Illegal string offset '#weight' in form_builder() (line 1920 of /**/**/**/site/includes/form.inc).
Warning: Illegal string offset '#processed' in form_builder() (line 1802 of /**/**/**/site/includes/form.inc).
Error: Unsupported operand types in form_builder() (line 1812 of /**/**/**/site/includes/form.inc).*

```

I am not sure if the problem is my form or the callback or something else...

```
function site_menu() {
    $items = array();
    $items['profile-main/%user/preferences'] = array(
        'title' => t(' Preferences'),
        'page callback' => drupal_get_form,
        'page arguments' => array('site_upload_form', 1), // Uid
        'access callback' => TRUE,
        'access arguments' => array('access content'),
        'type' => MENU_LOCAL_TASK,
    );
}

function site_upload_form($form, &$form_state){
    $form['email']= array(
        '#type'=>'textfield',
        '#title'=>t('Confirm email address'),
        '#maxlength'=> 255,
        '#required'=> TRUE,
    );
    $form['frequencyemail']= array(
        '#type'=>'select',
        '#title'=> t('How often do you want to hear from us?'),
        '#options'=> array(
            0 =>'Regularly',
            1 => 'Quarterly',
            2 => 'During the Summit',
            3 => 'Never',
            ),
        '#required'=> TRUE,
    );

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

```

Not sure what I am looking for

# Answer
Your assumption is correct I suppose! You might want to remove the said fields from the original profile edit form additionally.

I hope you're familiar with Form API! Take a look at `user_profile_form`. This function is the main form function for the profile form. This form calls `user_account_form` function and passes the `$form` variable by reference, and in `user_account_form` the profile fields are created and put into the `$form` variable.

So:

1. Programmatically create a new form. If I were you, I'd just call `user_account_form` from here too, but then unset the fields you don't want. The form could also call the default validate and submit handlers then: `$form['#validate'][] = 'user_profile_form_validate';` and `$form['#submit'][] = 'user_profile_form_submit';`
2. `hook_form_alter` to alter the original `user_profile_form` and `unset` the fields which you are showing in your other form. (Or you can set `'#access' => false` too)
3. Show the form at the path you created. This is just a case of returning `drupal_get_form` as your `page callback` and your form ID as `page arguments`. Or you can `return drupal_get_form('your_form_id');` from your `page callback` function. Whatever works for you.
> 0 votes

---
Tags: entities, users, hooks
---


# Question
Title: Can adding a cache tag create another cache row in database
I want Node breadcrumbs to be updated when the content is updated, so I added the following code to my breadcrumb generation class:

```
// Set cache tags
$node_cache_tag = 'node:'.$node->id();
$breadcrumb->addCacheTags(array($node_cache_tag));

```

My concern is that this is a bad idea for sites with a lot of content (300,000+). I saw this post https://www.drupal.org/node/2891281 and noted that the default cache row limit is 5,000. Would the above code be an issue with over 300,000 nodes? Should I cache the breadcrumbs based on the taxonomy term that created the breadcrumbs (~1300 terms)?

# Answer
First of all you should add tags of all nodes/terms you use to build the breadcrumb. You can't set too many tags, because a tag doesn't influence how many cache entries are stored.

This is only a problem you have by adding cache contexts. By default this is `url.path.parent`. But if you use for example the title of the current node, then you need `url.path`. When you have 300.000 nodes this can indeed make caching quite useless and you could consider setting a cache max-age of 0 to disable caching. Perhaps by doing this you also benefit from lazy loading of the breadcrumb block by Big Pipe, if this is for logged-in users, I've never tried this. And for anonymous users pages are cached for each path anyway.
> 3 votes

---
Tags: 8, caching, breadcrumbs
---


# Question
Title: Aegir+ Ubercart + Freetrial + ARB. Not working
I'm trying to set an automated approach to do the following:

* Customer signs up for a 30-day trial. Enters CC#, but is not charged for 30-days until free trial converts.
* CC# is verified (but not charged) on initial registration.
* CC# is NOT stored in cleartext in my database (need PCI compliance).
* IF account is active (i.e. I don't manually delete account), the account will automatically recur a monthly transaction every 30-days .

I have Aegir and store Admin set up with Authorize.net. I just signed up for Auth.net ARB, but I'm unsure how I set this up to accomplish what I'm describing above. As you can see in the screenshot below, I can manually charge the CC through the Admin interface, but that would imply that I would need to go in and charge the CC# in 30-days, and then manually every 30days thereafter.... That will become unmanageable quickly... As I said, I signed up for Auth.net's ARB, but the documentation on setting this up with Drupal is pretty poor. http://screencast.com/t/kB0xixRAerIo

Secondly, and perhaps a bigger problem with Drupal, is the fact that as the admin, I can see the customer's full CC# right there in cleartext when I click "view card details". Yikes. There must be a big mistake in all this, but don't know where. http://screencast.com/t/Kj46n17spnRq

Should I sign up for Auth.net's CIM to capture/store/hold customer's CC# throughout free-trial period, and then charge and and convert to ARB for automated monthly charges? If so, I'm stumped on how to set this up.

And... lastly the primary issue I have is that orders are being rejected due to no Bill-to address being populated with Auth.net. The order page shows no bill-to data was recorded, but when I look at the registration side, I can see that the bill-to address info was indeed captured. There seems to be some missing link where the bill-to address data recorded at registration is not being passed through to Auth.net (but CC# and name is being passed through). So it's the missing Bill-to data that is causing the rejection on Auth.net side. Any thoughts on why this address data is not being populated on Auth.net's side?

Thoughts/leads? we have a couple SyAd guys stumped on this. Thanks!

# Answer
> 0 votes
While this question is now 6 years old, the way to go about this nowadays is via Aegir Site Subscriptions, which isn't quite ready yet, but is on the way. So far, there's code for Recurly, but no other recurring billers.

---
Tags: ubercart, aegir, payment-gateways
---


# Question
Title: Dynamic route's controller method not firing
I'm trying to use the Background Image module, but there seems to be a problem with the dynamic route it registers for generating CSS. I've been debugging it, but I have run into a wall. It's basically a duplicate of the core Image module's routing setup, so I'm not sure what's wrong, but the controller method never fires; the controller isn't even instantiated. Here's the config file:

```
route_callbacks:
  - '\Drupal\background_image\Routing\BackgroundImageRoutes::routes'

```

Here's the `routes` method:

```
  public function routes() {
    error_log('Router::routes');
    $routes = [];
    // Generate background image CSS files. If clean URLs are disabled the
    // files will always be served through the menu system. If clean URLs are
    // enabled and the file already exists, PHP will be bypassed.
    $directory_path = $this->streamWrapperManager->getViaScheme('public')->getDirectoryPath();

    $routes['background_image.css'] = new Route(
      '/' . $directory_path . '/background_image/css/{background_image}/{scheme}/{file}',
      [
        '_controller' => '\Drupal\background_image\Controller\BackgroundImageCssController::deliver',
      ],
      [
        '_access' => 'TRUE',
      ]
    );
    error_log(print_r($routes, true));
    return $routes;
  }

```

Here's the `$routes` object:

```
Array
(
    [background_image.css] => Symfony\Component\Routing\Route Object
        (
            [path:Symfony\Component\Routing\Route:private] => /sites/default/files/background_image/css/{background_image}/{scheme}/{file}
            [host:Symfony\Component\Routing\Route:private] =>
            [schemes:Symfony\Component\Routing\Route:private] => Array
                (
                )
            [methods:Symfony\Component\Routing\Route:private] => Array
                (
                )
            [defaults:Symfony\Component\Routing\Route:private] => Array
                (
                    [_controller] => \Drupal\background_image\Controller\BackgroundImageCssController::deliver
                )
            [requirements:Symfony\Component\Routing\Route:private] => Array
                (
                    [_access] => TRUE
                )
            [options:Symfony\Component\Routing\Route:private] => Array
                (
                    [compiler_class] => Symfony\Component\Routing\RouteCompiler
                )
            [compiled:Symfony\Component\Routing\Route:private] =>
            [condition:Symfony\Component\Routing\Route:private] =>
        )
)

```

If I try to hit a URL such as `/sites/default/files/background_image/css/3/public/dq5DbF1hqHxkHXGiHSl9yuXubPox08bOX6nE12gX2h0.css?p2aptq` (which the module correctly generates when I've got a background image set up on the site) I get a 404 error and nothing in the error log.

I'm using docker4drupal and have checked the nginx config and am 99% sure that's not the issue (there are no rules for /sites/default/files/ and I do see the 404 in the nginx log.)

Why doesn't the dynamic route work as it should, and as it doesn't for the Image module?

# Answer
> 0 votes
Well, I'm an idiot. The problem was nginx after all. There actually was a block to handle CSS/JS assets that was preventing the dynamic route from executing because of a lack of physical files. I had to place the following above that rule:

```
location ~ ^/sites/.*/files/background_image/ {
    try_files $uri @drupal;
}

```

Here's the offending rule:

```
location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|xml|otf|ttf|eot|woff|woff2|svg|svgz)$ {
    expires 30d;
    tcp_nodelay off;
    open_file_cache off;
    open_file_cache_valid 45s;
    open_file_cache_min_uses 2;
    open_file_cache_errors off;

    location ~* ^.+\.svgz$ {
        gzip off;
        add_header Content-Encoding gzip;
    }
}

```

I found the solution after searching for relevant issues on other modules that generate dynamic files, such as `imagecache`, which led me to the official nginx Drupal guide. Definitely a learning exercise.

---
Tags: routes
---


# Question
Title: Show pages with a specific template when user is logged-in
I would like to know if there is a way to show an existing node with a custom template if user is logged-in or has a specific role.

I have tried with a custom module route.

```
custom_module.presentation:
  path: '/node/1'
  defaults:
    _controller: '\Drupal\custom_module\Controller\myController::custom_presentation'
    _title: 'presentation'
  requirements:
    _permission: 'access content'
    _user_is_logged_in: 'TRUE'

```

In the page controller, I used the following code.

```
public function custom_presentation() {
        $myVariables = array();

        $build = [
            'description' => [
                '#theme' => 'my_custom_template',
                '#scriptVars' => $myVariables
            ]
        ];
        return $build;
    }

```

It doesn't work, though. What is the correct way of doing it?

# Answer
> 0 votes
The most basic way of providing a custom template for a node that meets certain criteria, is using theme hook suggestions.

You can for example add a custom theme suggestion by implementing hook\_theme\_suggestions\_HOOK\_alter() in a custom module. There you can check whether your criteria are met and add a custom theme suggestion, if they are:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_node_alter(array &$suggestions, array $variables) {

  if (
    // Do your checks here, e.g authenticated user?
    \Drupal::currentUser()->isAuthenticated()
  ) {
    // Add your custom template here. The following
    // example would apply to 'my-node.html.twig'.
    $suggestions[] = 'my_node';
  }

}

```

---
Tags: 8, theming, routes
---


# Question
Title: How to define alias dependent Drush extensions?
I have a stage and an anonymized instance of a project both managed under the same user (www-data). The anonymized instance is taken from production instance and has a drush extension that can have a different version than the stage instance.

With one instance per user I can simply symlink the extension to the ~/.drush folder, but how would I do that with two different versions of the same extensions? Is there a way to define alias dependent extensions in Drush? If Drush does not support this, what would be a good OS work around?

# Answer
> 1 votes
Instead of installing the drush extensions in a user specific scope within your user's profile, you can install them on a per-project (Drupal instance) base in your `{PROJECT_ROOT}/drush` folder.

Drush 9 checks for the existence of a `drush` folder one level above the Drupal web root.

This is easiest to manage by utilizing Composer for dependency management and adding a Drush installer path, Drush and any Drush extensions to the `composer.json` file. But of course you can also setup everything by hand.

---
Tags: drush
---


# Question
Title: Pass block configuration item text field value to variable
I have a custom block module that has a configuration form of type text\_field. If there is a value entered into the configuration form, I want to store that value in a variable.

Here is the configuration hook:

```
/**
 * Implements hook_block_configure().
 */
function roadmap_block_configure($delta = 'roadmap') {
  // This example comes from node.module.
  $form = array();

  switch($delta) {
    case 'roadmap' :
      $form['roadmap_configuration_form'] = array(
      '#type' => 'text_format',
      '#title' => t('Enter an alternative URL.'),
// the URL entered will be sanitized and attached to hook_block_view(), and ultimately passed to a custom JavaScript file.
    );
    break;
  }
  return $form;
}

```

If there is a value entered into the configuration form, how can I store it in a variable?

# Answer
> 1 votes
So if this is for admin/editors only, one way to do it is to use the built-in Drupal hook\_settings\_form in your custom module. Here is a nice DO tutorial: https://www.drupal.org/docs/7/creating-custom-modules/creating-the-configuration-form

So in your case, this could look something like:

```
/**
 * Implements hook_settings_form() to configure module.
 */
function roadmap_settings_form($settings) {

  $form = array();
  $form['roadmap_url'] = array(
      '#type' => 'text_format',
      '#title' => t('Enter an alternative URL.'),
  );
  return system_settings_form($form);
}

```

this form will save the value as a system variable 'roadmap\_url' or whatever value you enter in the form field's machine name. you'd probably need to call this from some admin page in your custom module like so:

```
/**
 * Implements hook_menu().
 */
function roadmap_menu() {
  return array(
    'admin/config/roadmap_OR_SOME_OTHER_PATH' => array(
      'title' => t('Roadmap settings'),
      'page callback' => 'drupal_get_form',
      'page arguments' => array('roadmap_settings_form'),
      'access arguments' => array('administer roadmap OR SOME OTHER PERMISSION'),
      'type' => MENU_LOCAL_TASK,
    ),
  );
}

```

Now you should be able to go to your config page, enter your URL setting and it will be saved automatically by Drupal. To access this variable, you just need to call:

```
$url = variable_get('roadmap_url');

```

---
Tags: 7, forms, blocks, configuration
---


# Question
Title: ContentModerationStateFormatter does not work
I am building Views with a field to display the entity's content\_moderation\_state. For FieldFormatter, I select 'Content moderation state', which is the ContentModerationStateFormatter defined within Content Moderation module. On executing the view, I see that the field content is not so formatted. The machine name, not the label is displayed.
In fact, when debugging, I find that we do not even hit the ContentModerationStateFormatter! Views is displaying the machine name and disregarding the request to format.

Has anyone else had this problem or have a solution? Many Thanks.

# Answer
Please note, that the content moderation module is still in Beta as for the current stable Drupal core. You should always check the Drupal issue queue for issues with it.

If you are on Drupal 8.4.4, there is still an issue with the moderation state formatter, which has been fixed for 8.5: https://www.drupal.org/project/drupal/issues/2859381 Applying these fixes to Drupal 8.4.4 made it work for us.

If you are on a Drupal version before 8.4, you may even have to migrate the workflows to 8.4 first, as there have been some breaking changes to the workflows module while maturing to stable.
> 1 votes

---
Tags: views, entities
---


# Question
Title: Programmatically set the block visibility
I set *Configuration type* to *Block* and selected my custom block to export the configuration from *development/configuration/single/export*. I got the following block visibility configuration.

```
visibility:
  _menu_position:
    id: _menu_position
    _menu_position:
      'main:menu_link_content:016650bb-ecd4-43e4-9d04-fef05ebcf186': 'main:menu_link_content:016650bb-ecd4-43e4-9d04-fef05ebcf186'
      'main:menu_link_content:2d195963-d98d-4f02-8129-6498c5db4b87': 'main:menu_link_content:2d195963-d98d-4f02-8129-6498c5db4b87'

```

For this, I have used the following function.

```
function placeBlock(EntityInterface $entity) {

    $config = \Drupal::configFactory();
    $settings = [
        'plugin' => '_block_module_block', // Set the plugin id
        'region' => 'header', // Set region to header
        'id' => $entity->id() . '-_bm_autoheader', // Use the page id and the module name for machine name
        'theme' => $config->get('system.theme')->get('default'),
        'label' => $entity->label(), // Use the page label
        'visibility' => [],
        'weight' => 0,
        'label_display' => 0, // disable label
        'page_id' => $entity->id(), // Reference page
    ];
    $values = [];
    foreach (['region', 'id', 'theme', 'plugin', 'weight', 'visibility'] as $key) {
        $values[$key] = $settings[$key];
        // Remove extra values that do not belong in the settings array.
        unset($settings[$key]);
    }

    foreach ($values['visibility'] as $id => $visibility) {
         $values['visibility'][$id]['id'] = $id;
    }

    $values['settings'] = $settings;
    $block = Block::create($values);
    $block->save();
}

```

In my case, `$visibility` gets a `NULL` value.

```
langcode: de
status: true
dependencies:
  module:
    - _block_module
  theme:
    - _drupal_theme
id: 57148-_bm_autoheader
theme: _drupal_theme
region: header
weight: 0
provider: null
plugin: _block_module_block
settings:
  id: _block_module_block
  label: 'Header Contact'
  provider: _block_module
  label_display: '0'
  page_id: '57148'
visibility: {  }

```

I need help to understand the block visibility setting. How does it work in Drupal 8? How can I programmatically set it?

Thanks in advance.

# Answer
I have found the solution, set the visibility configuration by the following function using $menuLinkItem-\>uuid().

> function setVisibilityConfig($instance\_id, array $configuration)

```
$block->setVisibilityConfig('_menu_position', array('id' => '_menu_position',
        '_menu_position'=> [
              'main:menu_link_content:'.$menuLinkItem->uuid() => 'main:menu_link_content:'.$menuLinkItem->uuid()
            ],
        'negate' => null,
        )
    );

```

Thanks, @SumitMadan for helping out to understand the visibility concept.
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: Drupal 8: Class not found from module Controller, but works fine from module EventSubscriber
I created a custom D8 module in:

```
<root>/modules/custom/mymodule

```

In that custom module are `src/Controller/MyController.php` and `src/EventSubscriber/MySubscriber.php`.

I wrote some custom code in my custom theme in `<root>/themes/mytheme/src/MyClass.php`.

My namespaces are: `Drupal\mymodule` and `Drupal\mytheme`.

I can add/use MyClass in MySubscriber.php (`use Drupal\mytheme\MyClass`) and it works fine.

However, when trying to add MyClass to MyController.php, it creates a PHP error claiming that it cannot find MyClass. The MyClass code is identical between the two module files.

Why won't it work in MyController.php while working fine in MySubscriber.php?

I've tried a lot of testing, resetting the cache, etc., but cannot find a reason for this. I can use Drupal core classes in myController.php, but nothing from the themes directory (I tried to include custom code from another custom theme).

Any hints? Any best-practice work-arounds?

# Answer
> 2 votes
I never tried accessing theme classes from within any module classes. The reason is simple: The best practice you asked for is **not doing so**.

Whereas you can add classes to a theme for theming using object-oriented code, you should limit the operations performed by the theme to manipulating output generated by Drupal core and modules.

This should happen in a manner that allows for easily replacing your theme by another theme which is not featuring these classes.

Making a module dependent in a theme class will break this functionality.

Without having screened the core of Drupal, I could imagine that autoloading theme classes won't take place before theme negotiation happened.

Consider moving whatever your theme class does and is required by your module to a custom service provided by your module instead of the theme.

EDIT:

According to your comment, your original theme class had the use of creating a data table that should be themed for output.

The "Drupal way" then would be to moving your class to your custom module and making it a service by creating an according `mymodule.services.yml` (read more about creating a custom service here or here):

```
services:
  mymodule.myclass:
    class: Drupal\mymodule\MyClass

```

Then you can create an instance of your service by either using dependency injection (within the scope of other classes as your controller and/or event subscribers), or the static `\Drupal::service('mymodule.myclass')` getter within procedural `*.module` and `*.theme` files.

Your service could either have a method that returns the data table only, or even have a method for returning a themed version of the data table (render array with a `#theme` wrapper), whereas you implement a custom hook\_theme() with a template and/or pre-processing from within your module.

---
Tags: 8, theming, page-controller, event-subscribers
---


# Question
Title: How to print a taxonomy term's field value alongside a Views grouping header?
In Drupal 8.4.4 I have a *"Living Things"* taxonomy vocabulary. One field on the terms in the vocabulary is *"Most Common Name"*, with machine name `field_most_common_name`. On my *"Animalia"* term its value would be *"Animal"*.

In Views, I have a *"Taxon Media"* view which lists media related to the taxonomy term. I display it in a block on the taxonomy term's pages themselves (**not** on nodes). In the view I group media by another field, *"Primary Taxon"*, which is a reference to the term. It prints on the page as the grouping heading (e.g. *"Animalia"*).

How can I print the value of my *"Most Common Name"* field next to that title? i.e. "Animalia Animal".

I have made a template, `views-view-grouping--taxon-media.html.twig`, cloned from the one in the Classy template, tested that works, then added the 4th line and tried a few other things such as `content.field_most_common_name`, but cannot get the field's value to display:

```
<div class="view-grouping">
  <div class="view-grouping-header">
    {{ title }}
    {{ field_most_common_name }}
  </div>
  <div class="view-grouping-content">{{ content }}</div>
</div>

```

# Answer
> 1 votes
Thanks to Mario's helpful hint in the first comment, I was able to do this in the View and not in the twig template:

1. In the FIELDS section of the View, add "Most Common Name" as a field.
2. Select "Exclude from display", because I only want it in the title, not the results themselves. (3. Select "Link to the Taxonomy term", because I want it to be a link.)
3. Next to "FIELDS", under the "Add" drop-down menu, choose "Rearrange".
4. Drag "(field\_primary\_taxon: Taxonomy term) Taxonomy term: Most Common Name" above "Media: Primary Taxon" \> Apply
5. Click "Media: Primary Taxon \[hidden\]" field
6. Check "Override the output of this field with custom text"
7. REWRITE RESULTS \> and copy the required tokens from the "REPLACEMENT PATTERNS" list, and paste into the "Text" area. I also inserted brackets outside of those tokens, so my Text area looks like this:

{{ field\_primary\_taxon }} ( {{ field\_most\_common\_name }} )
8. Apply \> Save \> Clear all caches if necessary \> Refresh the page.
9. Title now in my example is "Animalia (Animal)". "Animalia" and "Animal" are links to the taxonomy page.

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


# Question
Title: How do I force nodes to have revisions by default when using REST?
We have a headless Drupal 8 content repository which we access via the REST API. I'd like Drupal to track revisions automatically for all nodes, as soon as they are created. I'm only aware of the "create new revision" checkbox on the node edit form.

How might I set Drupal to create revisions automatically?

All nodes are created programmatically via the REST API.

# Answer
> 7 votes
The node type setting mentioned by the other answers only applies to the node form, it does not affect programatically saved nodes.

You could try to implement hook\_node\_presave() and call setNewRevision(TRUE) or maybe the same in hook\_node\_load(). Or override the rest plugin (assuming you use that and not your own controllers).

# Answer
> 2 votes
You should be able to set this option to be checked by default. If you go to the edit page for your content bundle (i.e. `admin/structure/types/manage/article`), under *Publishing options*, you can enforce new revisions by default.

# Answer
> 2 votes
For Drupal 8 you can do the following in your custom .module file

```
use Drupal\Core\Entity\EntityInterface;

/**
 * @param \Drupal\Core\Entity\EntityInterface $node
 *
 */
function my_module_node_presave(EntityInterface $node) {
  // Force creating of new revision
  $node->setNewRevision(TRUE);
  // Set data for the revision
  $node->setRevisionLogMessage('My custom revision message.');
  $node->setRevisionUserId(123);
  $node->setRevisionCreationTime($_SERVER['REQUEST_TIME']);
}

```

# Answer
> 1 votes
I have developed a solution that works for us, based on Berdir's advice. My biggest trouble was improper implementation of hooks. I didn't know that in D8 hooks must (still) go into the .module file. Here's what we do to patch nodes via a rest route and force new revisions.

Patch via rest like this:

```
function patchNode(csrfToken, id, package) {
                    $.ajax({
                        url: 'http://example.com/cms/node/' + id + '?_format=hal_json',
                        method: "PATCH",
                        data: JSON.stringify(package),
                        headers: {
                            "X-CSRF-Token": csrfToken,
                            "Accept": "application/hal+json",
                            "Content-Type": "application/hal+json"
                        },
                        success: function(data, status, xhr) {
                            console.log('patchNode successful.')

                        }
                    });
                }

```

Create a module to implement setNewRevision via hook\_node\_presave. Hooks should go in to the .module file for your module.

```
<?php

/**
 *
 * @file
 * Force Revisions
 *
 * creates a new revision of a node on every save event
 *
 */

use Drupal\Core\Entity;
use Drupal\node\Entity\Node;
use Drupal\Core\Entity\EntityInterface;

function force_revisions_node_presave(EntityInterface $node) {
   $node->setNewRevision(TRUE);
}

```

---
Tags: nodes, 8
---


# Question
Title: Fatal error: Allowed Memory Size of (X Size) when running drush migrate-upgrade
I'm trying to use `drupal migration module` with `drush` to migrate a database. I'm getting this error below. Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /Applications/XAMPP/xamppfiles/htdocs/drupal-eight-iom/core/modules/migrate\_drupal/src/Plugin/migrate/source/DrupalSqlBase.php on line 76

I have already tried editing the `memory_limit` on php.ini file

`memory_limit=5024MB`

Not sure what else I need to do in order to make it work. I'm using `Drupal 8.4.4`

```
$databases['default']['default'] = array (
  'database' => 'drupal-eight-iom',
  'username' => 'root',
  'password' => '',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['upgrade']['default'] = array (
    'database' => 'drupal-seven-iom',
    'username' => 'root',
    'password' => '',
    'prefix' => '',
    'host' => '127.0.0.1',
    'port' => '3306',
    'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
    'driver' => 'mysql',
  );

$settings['install_profile'] = 'standard';
$config_directories['staging'] = 'sites/default/config';
$config_directories['sync'] = 'sites/default/files/config_zB_DnNUK68i5Owp5a8FzTiClQfp3d3jrwcy0_HuS1hNCGv9Y_Iva2Ahm8LCH-P0j0M2jwmQAsA/sync';

```

# Answer
> 5 votes
You need to check for the right `php.ini` file. Be aware, that drush is using the CLI (command line interface) version of PHP, which might use a different `php.ini` file than the version used by your web server.

Your above error message states, that the CLI version has a memory limit of 128MB only (which is the default value that might even be used when there is no php.ini file for your PHP version).

In Windows you can find out the used `php.ini` file - or the folder where it is expected - by typing the following command to your Windows command prompt:

`php -i | findstr /c:"php.ini"`

In Unix compatible systems you could use grep instead:

`php -i | grep "php.ini"`

---
Tags: drush, migrations
---


# Question
Title: Can I programmatically add a string to the translation interface?
I have used `t()` to translate a string value. To translate it from the user interface, I first need to view the page on which this string is displayed in a different language. Only then, the string is added to the translate interface.

I want to be able to translate the string before doing that. Can I programmatically add the string to the translation interface?

# Answer
> 1 votes
Assuming that your question is in regard to translating a (custom) module or theme. In that case, I'm using the Translation template extractor to get all strings of a module/theme that are used in the t() functions. For more information about using this module, look at this discussion. Though a pretty old discussion, it's still very useful.

# Answer
> 1 votes
For a quick solution, add something like this to a custom module:

```
/**
 * Implements hook_flush_caches().
 *
 * Using this as a way to get certain phrases into the t() workflow, that don't
 * seem to otherwise make it. To get these items to show up in the Translate
 * interface, go to a different language and in the Drupal admin clear the
 * Drupal cache. (ie, at /admin/config/development/performance
 */
function mymodule_flush_caches() {

  t('foo');
  t('bar');
}

```

# Answer
> 0 votes
## you can write custom code for that like this function

```
//$sourse :- string for en language or default language
//$translation :- string you want to add in other language translation
//$langcode :- language code in which you translate string

function addInManually($source, $translation, $langcode){
  $report = array(
    'skips'=>0,
    'updates'=>0,
    'deletes'=>0,
    'additions'=>0
  ); // ??
  $source = $source;
  $translation = $translation;
  $textgroup = 'default'; // field , node, default, menu ...
  $langcode = $langcode; // 'en', 'de'
  $mode = LOCALE_IMPORT_OVERWRITE; // LOCALE_IMPORT_KEEP
  $location = ''; //  'menu:menu:management:title', '/node/3', ...
  $context = '';
  _locale_import_one_string_db($report, $langcode, $context, $source, $translation, $textgroup, $location, $mode);

  // Clear locale cache.
  cache_clear_all('locale:', 'cache', TRUE);
}

```

---
Tags: i18n-l10n
---