title: Entity inside a Webform?

text:
# Question
Title: Entity inside a Webform?
I have a Webform that has an option for a number of tickets. Depending on the number of tickets I need to take information for each ticket, which I was thinking would be the entity?

So if they pick 2 tickets I will need to show the fields some how for the information to then be taken twice.

Any help?

# Answer
The webform module doesn't really provide such a feature without either using unstable dev version modules (and maybe achieving it) or custom code.

An easier alternative would be to use the Entityform module, which allows you to use any add-on modules that work with Drupal's field API.

This means you could achieve your requirement using something like the Field Collection or Inline Entity Form modules to provide a repeatable group of fields. In that case you can set the field to unlimited values and it will give the user the option to 'Add another item'.

With the Inline Entity Form option, you would have a separate entity for your ticket and you form will have an Entity reference field using the inline entity form widget, which will provide the full form, inline, whenever the user clicks the 'Add another' button.
> 1 votes

# Answer
Since I see that you are not tied to the Webform Module, why not just make a separate Custom Type and make the Node Creation/Edit form for that type the Form?

You can use the Simplify module to hide the extra administrative stuff so that it is more presentable.

When using a standard custom Content Type, you have access to the Entity Reference field which would solve the limitations of Webform.
> 1 votes

---
Tags: 7, webforms
---


title: Conditional token pattern

text:
# Question
Title: Conditional token pattern
I am looking for a module or a hook that allow me to use if conditions with tokens.

For example I want to check if a field is equal to a specific value or text

\[if\]\[field\_name\]\[eq\]hello\[then\]\[field\_name\_alt\]

any ideas will be helpful.

# Answer
Here is an idea, which I have not tried yet.

Sometimes you have tokens in combination with text formats. E.g. in `commerce_checkout_completion_message_pane_checkout_form()` the token replacement happens first, before the text format is applied. I am not sure if I agree with this order, but in this case it gives us some interesting options.

You could define a custom text filter which detects and evaluates markup like this:

```
{if true}hello{else}goodbye{endif}

```

and then you can use tokens to insert the true/false.

```
{if [token-which-returns-true-or-false]}hello{else}goodbye{endif}

```

This still leaves a lot in the open. Most tokens do not produce true/false, so maybe instead you want real equation formulas. But it is a direction you can explore further.
> 0 votes

# Answer
You can try to build it with Rules, but I'm not sure.

Another way is to make you own token module to get it. Token api is one of the easiest api from drupal.
> -1 votes

---
Tags: 7, hooks, tokens
---


# Question
Title: Show a different view mode depending on role
Using the Group module, when a user views a group, I want to use a different view mode depending on whether the user is a member of the group or not.
Conceptually, this is almost identical to showing a different view mode of a node depending on the user role.

I'd have thought it was easy, but I'm struggling. What I know:

* The route is *entity.group.canonical*
* I can modify the result of that route using `alterRoutes()` in a route subcriber

```
protected function alterRoutes(RouteCollection $collection) {
  if ($route = $collection->get('entity.group.canonical')) {
    // Do something.
  }
}

```

I'm not sure how to modify the route. Swapping in a whole new custom controller seems extreme.

# Answer
> 2 votes
Turns out, there's a hook for that.

```
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {

  // For nodes, change the view mode when it is teaser.
  if ($entity->getEntityTypeId() == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}

```

---
Tags: 8, group
---


# Question
Title: what's are these "@name" and "@site-name" token-things in email_example.module and how do they work?
In the dgo.to/example module's email\_example.module's hook\_mail() function there's this line:

```
      $message['body'][] = t('@name sent you the following message:', array('@name' => $user->name), $options);

```

I haven't seen `@thing` used that way before? How does that work? What convention is that?

# Answer
Please refer to the official D8 Sanitizing Output Documentation.

### From the documentation page

There are three available placeholders in Drupal 8:

* `@variable`: When the placeholder replacement value is a string or a MarkupInterface object
* `%variable`: When the placeholder replacement value is to be wrapped in em tags.
* `:variable`: When the placeholder replacement value is a URL to be used in the "href" attribute

You can learn more about these placeholders in the FormattableMarkup::placeholderFormat() documentation.

## EDIT FOR DRUPAL 7:

See this documentation https://www.drupal.org/docs/7/api/localization-api/dynamic-strings-with-placeholders

The variables/tokens available for use as replacements is dependent on the context of the surrounding code and whether or not the script is called via Apache or from the command line.
> 1 votes

---
Tags: 7, hooks, emails
---


# Question
Title: Prepopulate an entity reference in an inline entity form
Using Drupal 8...

I have a content type, called "Qualification".

In Qualification is an entityreference field called "Specification Sections" (field\_specification\_sections).

The entityreference (field\_specification\_section) field uses an inline entity form to create a node of type "Specification Text Section" (specification\_text\_section).

In other parts of my site, I need to be able to call the 'parent' of Specification Text Section, so there is a entityreference field called that refers back to qualification.

I need to prepopulate, the field\_qualification entityreference, when I create the Specification Text Section.

I've been struggling with using hook\_inline\_entity\_form\_entity\_form\_alter, trying to get the field\_qualification to prepopulate.

I am currently using:

```
function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
     // get qualification node id from request
     $nodeId = \Drupal::request()->attributes->get('node');

     // load the node entity
     $node = is_numeric($nodeId) ? \Drupal\node\Entity\Node::load($nodeId) : null;

     if ($entity_form['#entity_type'] == 'specification_text_section'){
           $form['field_qualification']['widget'][0]['target_id']['#default_value'] = $node;

    }
}

```

But, this is not prepopulating the field in the inline entity reference.

If I still had hair, I'd be pulling it out!

Can anyone point me in the right direction?

Thanks

# Answer
I tend to use CER (Corresponding Entity References) for things like this.

As an added benefit, you can hide the reference field on `specification_text_section` giving a slightly cleaner editor experience.

I have a couple of similar setups where I have IEFs on the `grandparent`, `parent`, and `child`, so you can create all 3 from any level and CER handles reverse reference. So, if I create a `parent` node, I have 2 IEFs, one for the `grandparent` and `child`, but don't show the field referencing the `parent` in either IEF forms.
> 2 votes

# Answer
Since I was, ultimately, wanting to hide the reverse reference from the user, I decided to use a `hook_entity_presave()` function.

This is what I ended up with:

```
$parent = \Drupal::routeMatch()->getParameter('node');
if ($parent instanceof \Drupal\node\NodeInterface) {
     $nid = $parent->id();
     }
//if the field is not already filled...
if( empty($entity->field_qualification->target_id) ){
     $entity->field_qualification->target_id = $nid;
     }

```
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Prevent comment author name from truncating
In Drupal 8, long comment author names are truncated. These comments are from anonymous users. When I use the following preprocess function, Drupal responds with a HTTP 500 code, and I have to restore the site from backup.

```
function THEME_preprocess_username(&$vars) {
    $vars['name'] = check_plain($vars['name_raw']);
}

```

Is there another way of removing the truncation from author names in comments?

# Answer
> 1 votes
You are likely getting an error because the check\_plain() function doesn't exist in Drupal 8. Your error logs should be able to confirm that.

If you check the main template\_preprocess\_username() function where the truncated version of the name is set, you can see it uses User::getDisplayName() and then truncates that.

So you could do this:

```
function THEME_preprocess_username(&$variables) {
  $account = $variables['account'] ?: new AnonymousUserSession();
  $variables['name'] = $account->getDisplayName();
}

```

If you want to keep with the check\_plain() approach from your example, in Drupal 8 you can use Html::escape().

---
Tags: comments
---


# Question
Title: Users add payments to order without editing order
Use case is that users need to be able to "pay off" an order eg. Yearly Fees of $200, the user might pay it off sporadically $5 or $10 at a time until order balance reaches $0.

Users are able to add payments through admin/commerce/orders/%/payment if the permission "Edit own orders" is active. This however means that the customer is able to edit the order details (prices, products, status etc.) which is a problem.

Is there a workaround for this? Im coming up blank.

# Answer
Have found the answer in "commerce/modules/payment/commerce\_payment.module"

Lines 964-972

```
    // Creating new payment transactions.
case 'create':
  if (user_access('create payments', $account)) {
    // We currently allow any user to create any payment transaction,
    // regardless of the order, because entity_access() doesn't give us a
    // way to discriminate on the order.
    // @todo: find a way to prevent creating a payment transaction if the
    // user doesn't have access to the order.
    if (!isset($order) || commerce_order_access('update', $order, $account)) {
      return TRUE;
    }
  }
  break;

```

need to be updated to the following

```
    // Creating new payment transactions.
case 'create':
  if (user_access('create payments', $account)) {
    // We currently allow any user to create any payment transaction,
    // regardless of the order, because entity_access() doesn't give us a
    // way to discriminate on the order.
    // @todo: find a way to prevent creating a payment transaction if the
    // user doesn't have access to the order.
    if (commerce_order_access('view', $order, $account)) {
      return TRUE;
    }
  }
  break;

```

This does not appear to have any security implications.
> 0 votes

---
Tags: 7, commerce
---


title: How to enable the Webform module?

text:
# Question
Title: How to enable the Webform module?
The tick box is greyed out. What is the "Contribute" module and where can I find it?

# Answer
> 2 votes
You can found it at https://www.drupal.org/project/contribute

> The Contribute module adds a 'Community information' section to Drupal's status report (/admin/reports/status) which encourages individuals and organizations to join the Drupal community, become members of the Drupal Association, and contribute to Drupal projects, events, and more.

Maybe you should read this article: The Webform module now depends on the Contribute module

---
Tags: 8, webforms
---


# Question
Title: How can I display search filters in a view?
I'm working on a site in drupal 8 that uses commerce 2. I'm learning as I go with this and feel like I'm missing something on how everything fits together.

I made a view for products, and configured how products display, and used twig templates to add wrappers and classes etc. This seems to work fine, but when it comes to adding any functionality, Twig doesn't seem to be the place to do it. The config options in Drupal cover layouts and CSS classes but are very complex.

This is confusing when you need to make the markup a certain way. In my case I need to add the following in a horizontal row:

1. number of results found
2. Select dropdown to filter results by a taxonomy
3. Another select for different taxonomy
4. Free text search box

I need to then style these also so I'd really want to control the markup generated, to some degree. How would I go about implementing this in a view?

# Answer
> 9 votes
Below are some guidelines to setting up each of your requirements in a view. Worth noting, in order to display each in the same row, you'll need to customize the view template to combine the exposed filters and the results count from the view header.

* **Number of Results Found**
    1. In the Header section (middle column) of the View edit page, click ADD.
    2. If your view has multiple displays, be sure to select whether to apply this to all displays in the view, or just the selected/current one in the FOR section.
    3. Select "Result summary" and click the ADD AND CONFIGURE HEADER button.
    4. Edit/customize your results text with the tokens. If you want to still expose the same text pattern if no results are found, check the checkbox *"Display even if view has no result"*
    5. Click APPLY

---

* **Select dropdowns to filter results by a taxonomy**
    1. In the Filter Criteria section (near bottom of left column) of the View edit page, click ADD.
    2. If your view has multiple displays, be sure to select whether to apply this to all displays in the view, or just the selected/current one in the FOR section.
    3. Find your custom taxonomy field you wish to filter by. Note, if your field is configured to allow multiple term selection, you'll see two instances of the field listed (the field itself, and the field delta). Pick the field itself.
    4. Click APPLY.
    5. If the field is setup to allow taxonomy terms from multiple taxonomies/vocabularies, select the one you wish to show/filter on. Choose the dropdown option to set the filter as a select element.
    6. Check the checkbox to *"Expose this filter to visitors, to allow them to change it"*
    7. Select the "single filter" format and update the field label to reflect the label you'd like the user to see. Keep the operator as "is one of". In the righ column, Leave the list of terms unselected to automatically show all terms in the filter.
    8. scroll further down the form, and click the *REDUCE DUPLICATES* option; optionally- click the *REMEMBER THE LAST SELECTION* option so that users clicking a back button to return to the page will still see the previous selection.
    9. Finally, click apply to save the filter settings.
    10. If the Auto preview option is enabled, you should now see the select filter in the view preview below the view config section (even if there are no results).

---

* **Free text search box**
    1. To setup a free text search box, you'll need to use the "Combine fields filter"; but it can only be applied to search the fields configured in the view. (You can add fields and exclude from display). If your view is setup to "Show Content", you'll need to click the "Settings" for the view Format and select "Force Using Fields" to add fields to the view for filtering/searching.
    2. Add the fields for searching (title, body, etc)
    3. In the Filter Criteria section (near bottom of left column) of the View edit page, click ADD.
    4. If your view has multiple displays, be sure to select whether to apply this to all displays in the view, or just the selected/current one in the FOR section.
    5. Find and select the "Combine Fields Filter" and click APPLY.
    6. Check the checkbox to *"Expose this filter to visitors, to allow them to change it"*
    7. Select the "single filter" format and update the field label to reflect the label you'd like the user to see. Change the operator to "Contains".
    8. scroll further down the form, and click the *REDUCE DUPLICATES* option; optionally- click the *REMEMBER THE LAST SELECTION* option so that users clicking a back button to return to the page will still see the previous selection.
    9. scroll even further down and multiselect the applicable search fields.
    10. Finally, click apply to save the filter settings.
    11. If the Auto preview option is enabled, you should now see the search box in the view preview below the view config section (even if there are no results).

---

* Customizing the View Templates
    1. Refer to the "Understanding Views Templates" and "Naming Views Templates" sections of this blog post for a high level rundown of Drupal 8 view templating.
    2. This legacy Views Template listing for Drupal 6 & 7 gives a good rundown of all the various views component templates (view header, view footer, view exposed filters). Most are still applicable in drupal 8, with the .tpl.php file ending swapped out as .html.twig

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


# Question
Title: How can I add something after the day/hour/time in a date select list?
On Drupal 8, the select list provided by the Date module looks like this:

The site I am building in Japanese, and in Japanese, it's common to add a character to indicate what the number means, like this:

```
2018 2 5 15 00　-> 2018年 2月 5日 15時 00分

```

How can I add these labels? I attempted to do it through the string translation UI screen, but since the year, day, hour, and minutes are just numbers, there is no way to "translate" them. The month shows up correctly because it is translated from Jan/Feb/etc.

I am thinking the solution involves `hook_form_alter()` but I don't know how to modify the way the values are displayed in the select widget without actually changing the values input and causing the form to fail.

# Answer
> 2 votes
You can't use **hook\_form\_alter()** or hook\_field\_widget\_form\_alter() in this case. Try with hook\_element\_info\_alter()

```
function MY_MODULE_element_info_alter(array &$types) {
  if (isset($types['datelist'])) {
     $types['datelist']['#process'][] = '_mymodule_add_suffix_value';
  }
}

function _mymodule_add_suffix_value(&$element) {
  // process logic option $element['day']
  // process $element['month']
  // process $element['hour']
  return $element;
}

```

---
Tags: 8, datetime
---


title: Override element_pre_render() function

text:
# Question
Title: Override element_pre_render() function
I'm creating a module for drupal that needs to override some function on an existing module called Drag & Drop module from drupal.

The function `dragndrop_upload_element_element_pre_render` that needed to be overriden. But I haven't got any luck overriding it. Is there a way to do it?

Image below is the function that I want to edit.

Did some of these, of course would not work. Any solution for it?

* `dragndrop_upload_element_element_pre_render_alter($element)`
* `MODULE_dragndrop_upload_element_element_pre_render_alter($element)`

# Answer
> 1 votes
Use hook\_element\_info\_alter:

```
/**
 * Implements hook_element_info_alter().
 *
 */
function mymodule_element_info_alter(&$types) {
  if (isset($types['myelement'])) {
    $types['myelement']['#pre_render'][] = 'mymodule_myelement_pre_render';
  }
}

```

---
Tags: hooks
---


# Question
Title: Exclude custom content type from search ( tried everything )
so I am here after googling the hell out of this problem.

My issue is the following, I am trying to exlucde a content type from showing up in resulsts.

I am using an autocomplete module called : **Search Autocomplete** , this module does the search..

So after researching the topic, to exclude content type from searches, I instaleld **Search Configuration Module**

I configured this module to exclude everyone but the admin from doing any type of search, but whatever I do seems to have no effect... I am out of ideas and currently dont know what to do..

I also tried the lightweight search restrict plugin, but that doesnt seem to have any effect aswell.

This is the code I have inside the template.php

```
function MYSITE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#title'] = t(''); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibility
    $form['search_block_form']['#default_value'] = t(''); // Set a default value for the textfield
    $form['actions']['submit']['#value'] = t('Cautare'); // Change the text on the submit button
    $form['actions']['submit']['#attributes']['alt'] = "Search Button"; //add alt tag
    $form['search_block_form']['#attributes']['placeholder'] = t( 'Enter search terms...' );

// Add extra attributes to the text box
    $form['search_block_form']['#attributes']['placeholder'] = "if (this.value == '') {this.value = 'Cautare..';}";
    $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Cautare..';}";
    $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search Site') {this.value = '';}";
  }
}

```

# Answer
> 0 votes
Ok so all this confusion was pretty easy to solve from inside teh views module, I had to exclude in the views module the content type and that was it no need for uneccesary modules to exclude content types from search

---
Tags: search
---


# Question
Title: Drupal entity metadata wrapper no bundle property
Using `<?php
$wrapper = entity_metadata_wrapper('node', $nid);
?>`

When I `$wrapper->title->value();` I get error msg that property Title does not exist....

Using Entity 7.x 1-8 and D7.56. I am aware that `$nid` can be a node (from node\_load) or a node id.

What am I missing?

# Answer
I solved it applying this patch: https://www.drupal.org/project/entity/issues/2819665

although I to be honest don't understand why...
> -1 votes

---
Tags: entities
---


# Question
Title: Exposed date filter doesn't work with 'greater than' or 'less than' and 'is equal to'
I'm working on a Drupal 8 site where I use a exposed filter to filter on date. I created a simple version of what I want on simplytest.me.

In this example I created a article with a start and end date.

```
Start date is 28-02-2018 01:00:00
End date is 28-02-2018 10:00:00

```

I also created a view with two exposed filters to filter on date range.

```
Exposed filter 1: >= Startdate
Exposed filter 2: <= Enddate

```

>

>

>

When I add *28-02-2018* in both filters the result is null. When I look in the query, I see it says *2018-02-27* instead of *2018-02-28*

What is going wrong? It looks like it doesn't see the *is equal to* part of my filter.

>

Is this normal? How do I make this filter work as I expect?

I tried to fix it with https://www.drupal.org/project/drupal/issues/2627512#comment-12382345, but this only adds an hour, not a full day.

# Answer
> 1 votes
A friend of mine helped me out, the problem was me not adding time to the search query. I found this already along the way in finding a solution but I didn't understand it at that moment. Now I do.

By not entering a time in the search field (so searching for 28-02-2018) the search will go to 28-02-2018 00:00:00 which is the same as 27-02-2018 23:59:59.

So what I had to do was search for 28-02-2018 23:59:59 instead, when entering this in the search field, the right items do show.

---
Tags: 8, views
---


title: Lowercase in facets search api

text:
# Question
Title: Lowercase in facets search api
I have an issue with **Facets on search API** (Solr Integration).

* Facets items are all in lowercase, and thats not how the content type save them, and I've made a query to solr server directly and the index items there have uppercase letters

can someone help me ?

Thx

# Answer
You could use *hook\_facetapi\_filters()* to define a new filter for your facets.

```
/**
 * Implements hook_facetapi_filter().
 */
function MODULE_facetapi_filters() {
  return array(
    'uppercase_items' => array(
      'handler' => array(
        'label' => t('Uppercase items'),
        'class' => 'FacetapiFilterUppercaseItems',
      ),
    ),
  );
}

```

and then extend the *FacetapiFilter* class like this:

```
class FacetapiFilterUppercaseItems extends FacetapiFilter {

  /**
   * Filters facet items.
   */
  public function execute(array $build) {
    // Do your magic.
    foreach ($build as $key => $value) {
      $build[$key]['#markup'] = ucfirst($value['#markup']);
    }
    return $build;
  }

  /**
   * Adds hook documentation.
   */
  function settingsForm(&$form, &$form_state) {
    $form['uppercase_items'] = array(
      '#title' => t('Uppercase filters'),
      '#type' => 'checkbox',
      '#default_value' => TRUE,
    );
  }
}

```

I haven't actually tried this out but this is pretty much what Facet API Bonus does, which is also a great example for creating your own filters.
> 4 votes

# Answer
If your fields are of type "fulltext" (or a variant of fulltext), the captialization may be getting stripped out by an "ignore case" processor in Solr or in Search API.

You can add the same field again, but a) Drill down to the "Name" field using the (+) sign next to the field as you add it (e.g. Authored by » User » Name), and b) Choose type "String" for the field. Then use that field for your facet, instead of the first one. The facet label should then include capitalization, if the field's value is actually capitalized.

Another advantage is that string fields in facets can display multiple words, which may not be the case if you're using fulltext fields.
> 0 votes

---
Tags: search
---


title: Create a hidden character field?

text:
# Question
Title: Create a hidden character field?
How can I create a hidden character field in D7 for a text field that hides the user input like the password field does? For example a field called "social security number" should not display the users input in plain text, but instead hide the input. Is there a module that can do this? Or how would that be realized?

# Answer
> 3 votes
You can with `'#type' => 'password'` in your form.

Ex:

```
$form['social_sec'] = array(
  '#type' => 'password',
  '#title' => t('Social Security'),
  '#description' => t('Please enter your social security number'),
  '#size' => 9,
  '#maxlength' => 9,
  '#required' => TRUE,
);

```

If you want this as a field in a node's form, then you will have to use hook\_form\_BASE\_FORM\_ID\_alter and alter an already existing field.

---
Tags: 7, users, entities
---


# Question
Title: What is the form id used in user profile edit form?
I'm trying to alter some fields in the user profile form but I'm not sure why the form\_id **user-form** is not working.

What I'm trying to achieve is to bring back the REQUIRED status of the password field which I turned off in user register form.

```
//USER REGISTER FORM
function MYMODULE_form_user_register_form_alter(&$form, &$form_state,
$form_id) {
$userID = \Drupal::currentUser();
$userRole = $userID->getRoles();
if($userRole[1] == 'ROLETOCATCH'){
$form['account']['pass']['#required'] = FALSE;
$form['account']['mail']['#required'] = TRUE;
$form['account']['roles']['campaign_manager']['#default_value'] =  TRUE;
$form['account']['notify']['#default_value'] = TRUE;
}
}

//USER FORM UPDATE
function MYMODULE_form_user_form_form_alter(&$form, &$form_state,
$form_id) {
    kint('hello');
}

```

# Answer
To override the **user form** (when editing user profile) you can use `hook_form_alter` with `user_form` id.

On the following example code the `current_pass` is required so anyone making changes will need to enter it. Also we assume that any administrator would not be forced to enter the password.

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  $user = \Drupal::currentUser()->getRoles();
  //admin's probably should not be forced to enter password
  if(!in_array("administrator", $user) && $form_id == 'user_form') {
    //$form['account']['pass']['#required'] = TRUE;
    $form['account']['current_pass']['#required'] = TRUE;
  }
}

```

The **user register form** can be overriden with either one

```
function MODULENAME_form_user_register_form_alter(&$form, &$form_state, $form_id) {
   //
}

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "user_register_form"){
    //
  }
}

```

The module has to be enabled and/or the cache should be rebuild for the system to see those functions
> 1 votes

---
Tags: 8, forms
---


title: Drupal ignoring changes to settings.php

text:
# Question
Title: Drupal ignoring changes to settings.php
I made a copy of one of my drupal sites and I'm attempting to set it up to use a different database but for some reason it's ignoring changes to my settings.php file. My settings.php file is in sites/default/settings.php and contains the following

```
$databases['default']['default'] = array (
        'database' => 'my_db_database',
        'username' => 'my_db_user',
        'password' => 'my_db_password',
        'host' => 'my_db_host',
        'port' => '3306',
        'driver' => 'mysql',
        'prefix' => '',
        'collation' => 'utf8mb4_general_ci',
);

```

However the changes I made to it don't seem to take. It's still using the old database. As a test I even put in incorrect information and tried commenting everything out to see if I can break it, but there was no effect. I also checked to make sure there was no local.settings.php file.

Is there something that needs to be done to reload the settings.php file. If not is there a way to see what settings.php file is being used in case there's another file overriding it?

UPDATE: Turns out the issue was a dummy mistake on my part. The domain was pointing to the wrong server. However I'm not closing this question because I believe these answers could be helpful to others in similar situations.

# Answer
> 2 votes
The settings.php file is usually 444 as permission, check if the "last modified" is as you aspect, otherwise you need to change the permissions temporaly to 777 in order to overwrite it

# Answer
> 1 votes
Check with including `namespace`. Also, check if any other code override configuration or do you enabled `settings.local.php`. Add this code to the bottom of settings.php

```
 $databases['default']['default'] = array (
  'database' => 'my_db_database',
  'username' => 'my_db_user',
  'password' => 'my_db_password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

---
Tags: 8, configuration
---


# Question
Title: How can I overwrite existing menu tree manipulators?
**Or**: how can I prevent unpublished nodes' menu items to be removed in the menu select when the user does not have the *bypass node access checks* permission, but may actually edit various unpublished nodes?

Im facing the problem that in the node form, the menu item options are missing some menu items because the related node is unpublished although the user may actually see and edit those nodes.

In `/core/lib/Drupal/Core/Menu/MenuParentFormSelector.php` the function `getParentSelectOptions` builds the options list which is then used in the node edit forms.

The function is:

```
  /**
   * {@inheritdoc}
   */
  public function getParentSelectOptions($id = '', array $menus = NULL, CacheableMetadata &$cacheability = NULL) {
    if (!isset($menus)) {
      $menus = $this->getMenuOptions();
    }

    $options = array();
    $depth_limit = $this->getParentDepthLimit($id);
    foreach ($menus as $menu_name => $menu_title) {
      $options[$menu_name . ':'] = '<' . $menu_title . '>';

      $parameters = new MenuTreeParameters();
      $parameters->setMaxDepth($depth_limit);
      $tree = $this->menuLinkTree->load($menu_name, $parameters);
      $manipulators = array(
        array('callable' => 'menu.default_tree_manipulators:checkNodeAccess'),
        array('callable' => 'menu.default_tree_manipulators:checkAccess'),
        array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      );
      $tree = $this->menuLinkTree->transform($tree, $manipulators);
      $this->parentSelectOptionsTreeWalk($tree, $menu_name, '--', $options, $id, $depth_limit, $cacheability);
    }
    return $options;
  }

```

The critical part in that function is the manipulator `'menu.default_tree_manipulators:checkNodeAccess'`.

The manipulator (`/core/lib/Drupal/Core/Menu/DefaultMenuLinkTreeManipulators.php`) does the following thing (`public function checkNodeAccess`):

```
if ($this->account->hasPermission('bypass node access')) {
  $query->accessCheck(FALSE);
}
else {
  $access_result->addCacheContexts(['user.node_grants:view']);
  $query->condition('status', NODE_PUBLISHED); // <<< wtf?
}

```

**TL;DR**

So it assumes "either a user may bypass all node access checks or hide all unpublished nodes from the menu select" - which is weird...

How can I overwrite this?

# Answer
I was unable to find a way to alter tree manipulators of an existing menu. But it is possible if you render menu, let's say in a custom block.

Create your own tree manipulator service.

Copied from core.services.yml:

```
  menu.default_tree_manipulators:
    class: Drupal\Core\Menu\DefaultMenuLinkTreeManipulators
    arguments: ['@access_manager', '@current_user', '@entity_type.manager']

```

you can define your service in a similar way:

```
  mymodule.my_custom_tree_manipulators:
    class: Drupal\mymodule\MyCustomMenuLinkTreeManipulators
    arguments: ['@access_manager', '@current_user', '@entity_type.manager']

```

Then create `MyCustomMenuLinkTreeManipulators` class that extends `DefaultMenuLinkTreeManipulators`, define custom method, let's say `checkAccessIgnoreStatus()` and implement logic you need.

There are many ways to use it, I'd create a new block plugin for that. Refer to my answer for details on how to render menu with manipulators.

Use your manipulators:

```
$manipulators = array(
        array('callable' => 'mymodule.my_custom_tree_manipulators:checkAccessIgnoreStatus'),
        // ...
      );

```
> 5 votes

# Answer
I have got similar task. I have to override parentSelectOptionsTreeWalk method from this class. It is solution: add this to services.yml in sites/default

```
services:
  menu.parent_form_selector:
      class: Drupal\my_page\MyPageMenuParentFormSelector
      arguments: ['@menu.link_tree', '@entity.manager', '@string_translation']

```

next create in my\_page module in src directory file MyPageServiceProvider.php

```
<?php

namespace Drupal\my_page;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Reference;
/**
* Class MyPageServiceProvider.
*
* @package Drupal\my_page
*/

class MyPageServiceProvider extends ServiceProviderBase {
/**
* {@inheritdoc}
*/

public function alter(ContainerBuilder $container) {
$definition = $container->getDefinition('menu.parent_form_selector');
$definition->setClass('Drupal\my_page\MyPageMenuParentFormSelector');
$definition->setArguments(
  [
    new Reference('menu.link_tree'),
    new Reference('entity.manager'),
    new Reference('string_translation'),
  ]
);
}
}

```

and create your class: MyPagemenuParentFormSelector.php

```
<?php

    namespace Drupal\my_page;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Menu\MenuParentFormSelectorInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Menu\MenuParentFormSelector;

/**
 * Default implementation of the menu parent form selector service.
 *
 * The form selector is a list of all appropriate menu links.
 */

class MyPageMenuParentFormSelector extends MenuParentFormSelector implements MenuParentFormSelectorInterface {
  use StringTranslationTrait;

  /**
   * The menu link tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTreeInterface
   */
  protected $menuLinkTree;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * Iterates over all items in the tree to prepare the parents select options.
   *
   * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
   *   The menu tree.
   * @param string $menu_name
   *   The menu name.
   * @param string $indent
   *   The indentation string used for the label.
   * @param array $options
   *   The select options.
   * @param string $exclude
   *   An excluded menu link.
   * @param int $depth_limit
   *   The maximum depth of menu links considered for the select options.
   * @param \Drupal\Core\Cache\CacheableMetadata|null &$cacheability
   *   The object to add cacheability metadata to, if not NULL.
   */
  protected function parentSelectOptionsTreeWalk(array $tree, $menu_name, $indent, array &$options, $exclude, $depth_limit, CacheableMetadata &$cacheability = NULL) {
    foreach ($tree as $element) {
      if ($element->depth > $depth_limit) {
// Don't iterate through any links on this level.
        break;
      }

// Collect the cacheability metadata of the access result, as well as the
// link.
      if ($cacheability) {
        $cacheability = $cacheability
          ->merge(CacheableMetadata::createFromObject($element->access))
          ->merge(CacheableMetadata::createFromObject($element->link));
      }

// Only show accessible links.
      if (!$element->access->isAllowed()) {
        continue;
      }

      $link = $element->link;
      if ($link->getPluginId() != $exclude) {
        $title = $indent . ' ' . Unicode::truncate($link->getTitle(), 255, TRUE, FALSE);
        if (!$link->isEnabled()) {
          $title .= ' (' . $this->t('disabled') . ')';
        }
        $options[$menu_name . ':' . $link->getPluginId()] = $title;
        if (!empty($element->subtree)) {
          $this->parentSelectOptionsTreeWalk($element->subtree, $menu_name, $indent . '--', $options, $exclude, $depth_limit, $cacheability);
        }
      }
    }
  }
}

```

Here is good info about override drupal core services https://www.hs2solutions.com/blog/drupal-how-override-core-drupal-8-service
> 3 votes

---
Tags: 8, users, navigation
---


# Question
Title: Is it posible to use taxonomy terms in Context module?
We are developing a Drupal 8 site and we need to create an specific sidebar with Context module using Taxonomy Term. In D7 module version is very easy: you can select an specific taxonomy term... but in Context for D8 we cannot find this option. We only find Vocabulary.

Is it not possible in D8? Or in other words... how we can do it?

# Answer
> 1 votes
Take a look at Using Block Visibility Groups to Create Conditional Layouts in Drupal 8 about solution, and the Term condition module,

it works for me.

# Answer
> 1 votes
You can use Request Path (System) in Context for Drupal 8 if you create a URL Alias Pattern you want to target. Works fine for me.

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


# Question
Title: Removing div wrapper container of paragraph field and get only the plain text in twig
I have a paragraph template in my custom theme as `paragraph--home-page-carousel.html` and when I write like this

```
<span class="car-spec">{{ content.field_home_slide_snippet[0]|raw }}</span>

```

I get in HTML source code this

```
 <div>
    <span class="car-spec">
    FIELD CONTENT
    </span>
</div>

```

what should I do to remove the div wrapper?

# Answer
You shouldn't do `{{ content.field_home_slide_snippet[0]|raw }}`. You should do `{{ content.field_home_slide_snippet }}` and edit the twig template for `field--field-home-slide-snippet.html.twig` to have no HTML wrappers. Copy `field.html.twig` to your theme and edit as needed.
> 8 votes

# Answer
You could use the **strip tags filter** : `{{ some_html|striptags('<span>') }}`
Assuming the html is dynamically wrapped by the `<div>` tag, this will strip the `<div>` tag and leave the `<span>` tag.

so

```
{% set mycontent %}
    {{ content.field_home_slide_snippet }}
{% endset %}
{{ mycontent|striptags('<span>') }}

```

https://twig.symfony.com/doc/2.x/filters/striptags.html
> 3 votes

# Answer
I think you can use

`{{ content.field_home_slide_snippet.0["#context"].value }}`

or enable devel module and then use

`{{ kint(content.field_home_slide_snippet) }}`

to see where is value that you need.
> 1 votes

---
Tags: 8, theming, paragraphs
---


# Question
Title: Theming custom block type have multiple paragraph field
I've created a custom block type includes a paragraph type field and make it multiple. I've configured this block to display it only on the front page. I have a `page--front.html.twig` template in my custom theme. What I want to do in my front page template is looping through the paragraph field to get each field item and theming it in custom HMTL.
**So what is the correct way to do this?**
I've tried `block--BLOCKID.html.twig` and try this code.

```
{% for item in content.field_home_page_carousel %}
{{ kint(item.field_home_slide_image) }}
{% endfor %}

```

but I got nothing.

# Answer
> 1 votes
I Agree with Kevin's comment. Focus on theming the block.
Activate your theme's debug mode and view the template suggestions for your block. Add a new template and name it as one of the template suggestions, e.g. `block--views-block--more-by-this-author-block-1.html`.
It may help to duplicate the original block's code and paste into your new twig file, then find a good place to add your for loop.
Now you can loop through the paragraphs:

```
{% for item in content.field_home_page_carousel %}
    <p>{{ item.field_home_slide_image }}</p>
{% endfor %}

```

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


title: Create webform element

text:
# Question
Title: Create webform element
I'm currently trying to create a clone of the webform element 'text field' with a new name. This is simply so that the new element can be styled independently.

(I know I could use template/theme suggestions - or use the module themable\_forms - but we have a specific use case. The site editor may want to add the same element to other forms. So - for example - I clone the text field element to first\_name element - and the front-end guy can then theme the first\_name element with a relevant twig template - and if that element is used on other forms then it will pick up that (first name) template).

The difficulty I have is in creating the new webform element. Drupal's console generate:plugin:skeleton produces a Plugin class which does not work - for one thing the dependencies listed in the annotation for the class is the string 'array' (removing the dependency line fixes that) - but something else is causing the 'insert element' pop-up box to fail to load.

I'm looking to use the example webform element module - but wondered if anyone had a successful walk-through for creating a new webform element from scratch?

# Answer
To answer my own question - this is how to use the webform element example module (which is a submodule of webform) to create your own webform element.

Copy

```
webform_example_element/src/Element/WebformExampleElement.php

```

to

```
mymodule/src/Element/WebformExampleElement.php

```

and copy

```
webform_example_element/src/Plugin/WebformElement/WebformExampleElement.php

```

to

```
mymodule/src/Plugin/WebformElement/WebformExampleElement.php

```

Then in both of those files change the namespace line from:

```
namespace Drupal\webform_example_element\Plugin\WebformElement;

```

to

```
namespace Drupal\mymodule\Plugin\WebformElement;

```

Clear caches and this example element should now appear in the element list to be added to a form.

NB - you don't need to copy webform\_example\_element/config/install/webform.webform.webform\_example\_element.yml as this is used to create the an example form to display the example element. NB - the class Element/WebformExampleElement.php is needed as this is the basis of the new webform element.
> 2 votes

---
Tags: webforms
---


# Question
Title: How to relate an image to an article when posting the article in REST API
Using the following code we can post a node trough rest API. However, if there is an image attached to this article we need to post the image node first and then include the image fid in the article.I successfully posted the image also but as far as the documentation is very incomplete I am not able to find a way to add the image fid to the second request to attach it to the article.

```
$serialized_entity = json_encode([
   'title' => [['value' => $node->title]],
   'body' => $node->body_array,
   'type' => [['target_id' => $node->node_type]],
   '_links' => ['type' => [
       'href' => $base_url.'/rest/type/node/'. $node->node_type
    ]],
]);

$response = \Drupal::httpClient()
    ->post($base_url.'/entity/node?_format=hal_json', [
        'body' => $serialized_entity,
        'headers' => [
            'Content-Type' => 'application/hal+json',
            'Authorization' => 'Bearer '. $token->access_token
        ]
    ]);

```

Is this the right way to attach an image? if yes, what are the request parameters we need to add the image to the node post request?

Any help would be appreciated. Thanks

# Answer
See https://www.drupal.org/project/drupal/issues/1927648, this is not supported yet in core.

You can try using https://www.drupal.org/project/better\_normalizers to send it base64 encoded instead.
> 1 votes

---
Tags: nodes, media, 8, multi-sites
---


# Question
Title: Webform - How to filter submissions by user?
I need to make a view that displays to the current user her own submissions.

Option 1: For a specific node and then I can display also the data. Option 2: For any node and then I can just use the metadata of the submission.

Could not find how to do it... Thanks!

# Answer
You can create the view to display the webform submissions. You need to give the webform node id to fetch particular submissions.

I have added the exported view. This is just displaying the submitter name as per my webform. So this is just skeletal view. You can add fields as per your requirement. You will have to change your webform node id and manipulate as per your requirement.

```
$view = new view();
$view->name = 'webform_submission';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'webform_submissions';
$view->human_name = 'Webform Submission';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Webform submissions: Serial number */
$handler->display->display_options['fields']['serial']['id'] = 'serial';
$handler->display->display_options['fields']['serial']['table'] = 'webform_submissions';
$handler->display->display_options['fields']['serial']['field'] = 'serial';
/* Field: Webform submission data: Value */
$handler->display->display_options['fields']['value']['id'] = 'value';
$handler->display->display_options['fields']['value']['table'] = 'webform_submissions';
$handler->display->display_options['fields']['value']['field'] = 'value';
$handler->display->display_options['fields']['value']['webform_nid'] = '1';
$handler->display->display_options['fields']['value']['webform_cid'] = '1';
/* Contextual filter: Content: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'user/webform_submissions';

```
> 0 votes

# Answer
You can accomplished this task by downloading this module https://www.drupal.org/project/webform\_views

After that, you can get all the elements from your webforms in the VIEWS. Works for me.
> 0 votes

---
Tags: views, webforms
---


title: how to access $user from commandline?

text:
# Question
Title: how to access $user from commandline?
I'd like to access $user from the commandline to see what properties are available on it. I could `sdpm($user)` in my code and go inspect it in my browser, but isn't there a way I can inspect it right from my terminal?

It looks like `drush php` could be helpful here, according to http://blog.damiankloip.net/2015/drush-php, but when I use it and do `dump -a $user` I get 'Unknown variable: $user'. That's probably obvious, so I probably need to load $user into the repl first (I'm guessing)... but how? That blog post shows how to load objects in D8, but how would I do this in D7 for $user???

# Answer
You need to define the $user variable first. You can run the drush command as a particular user by specifying --user on the command line:

```
drush --user='admin' ev 'global $user; print_r($user);'

```

If you don't specify a user, drush runs as anonymous by default.

Or, you can do it like this:

```
drush ev '$user = user_load_by_name("admin"); print_r($user);'

```

It will display this:

```
stdClass Object
(
    [uid] => 1
    [name] => admin
    [pass] => *****
    [mail] => info@example.com
    [theme] =>
    [signature] =>
    [signature_format] => filtered_html
    [created] => 1443708895
    [access] => 1515415027
    [login] => 1515411954
    [status] => 1
    [timezone] => Europe/London
    [language] =>
    [picture] => 0
    [init] => info@example.com
    [data] =>
    [uuid] => f6800524-c092-4abc-abcd-f71d091623cd
    [roles] => Array
        (
            [2] => authenticated user
        )

    [force_password_change] => 0
)

```
> 2 votes

---
Tags: 7, users, drush
---


title: Is it possible to save a view as image?

text:
# Question
Title: Is it possible to save a view as image?
I have a view with a table and charts and I need to save it as image. Is this possible?

It can be an export of the page itself as long as it exports only the contents of the view without menus and other page elements.

# Answer
> 0 votes
If you are using Drupal 7, there are a couple of views to pdf modules available.

Not sure about a Drupal 8 version.

An alternative would be to use CSS print media queries to hide what you don't want to see when you print the page. This can be usefull across the site for printing pages if you set it up properly. If you need specific page settings, the body tag probably has a unique view class. If not, you can add one with a preprocess function.

If you truely need an image, then phantomjs or similar combined with the correct CSS is probably your best bet. There are some screenshot modules but they tend to use services and are probably not that configurable.

---
Tags: views, media
---


# Question
Title: How to get RAW Html code from my module?
I looked around for a few hours but wasn't able to find any available hooks to get pure raw html code. If you right-click on any webpage and do "get source", it will give you the raw html output.

However, there doesn't seem to be a function or hook available that I can find in Drupal that does this.

Does anyone know if this is possible? Thank you.

# Answer
> 0 votes
It's not totally clear what you mean by 'from my module' but if you're asking how to get the HTML code of any Url into a variable in your module, you can use the drupal\_http\_request function. Below example comes from https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_http\_request/7.x

```
$data = 'name=value&name1=value1';

$options = array(
                'method' => 'POST',
                'data' => $data,
                'timeout' => 15,
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
        );

$result = drupal_http_request('http://somewhere.com', $options);

```

You can also use curl via the cURL HTTP Request (chr) module.

---
Tags: 7, nodes, hooks
---


title: Change Views Path Programatically

text:
# Question
Title: Change Views Path Programatically
I have a custom form on my site, and on submission, I'd like to update a Views page path.

Within my module, I have a form alter which eventually attaches a custom submit function where I plan to run this Views path change. Within my submit function, so far I have:

```
function _my_module_custom_submit() {
    $view = \Drupal\views\Views::getView('custom_view');
    $view->setDisplay('page_1');
    // TODO: Change Views path

    // Save View
    $view->save();
}

```

This function is running fine, however I cannot find *how* to change the Views Display path at all. I've tried the `setHandler()` and `setHandlerOption()` methods, but these don't appear to be working for this case.

I've found plenty of examples to change the Views path programatically in Drupal 7, but have yet to come across an example for Drupal 8.

# Answer
In Drupal 8 the configuration of a View is stored in an entity, which you can load, modify and save:

```
use Drupal\views\Entity\View;

  $view = View::load('custom_view');
  $display =& $view->getDisplay('page_1');
  $display['display_options']['path'] = 'example/path';
  $view->save();

```
> 2 votes

---
Tags: views, 8
---


# Question
Title: What hook should I use to alter the File Upload field in Webform 7.x-4.16
In Drupal 7 Webform file field, might there be a way to access the link provided after the a file is uploaded?

The reason is that we have a hot-folder/watch-folder process that runs, cleans a file, converts DOCs to PDFs, checks for accessibility, etc. I'd like to link to converted version of that file.

We want to allow the user submitting everything to ensure their document is converted properly before they click the submit button.

# Answer
I believe you could go far with `hook_form_alter` in drupal 7. Unless you're implying a multiple step webform where some webform hook may apply.

Browse over the `webform.api.inc` file in the module folder and if none of the hooks sound good for your needs try a simple form alter.
> 0 votes

---
Tags: 7, webforms, files
---


title: Overriding third-party module code

text:
# Question
Title: Overriding third-party module code
I am using Composer to download third-party modules to my Drupal 8 repository.

I have a requirement that involves all of the functionality that module gives but there are unfortunately 2 lines of code that I need to remove in a PHP file in the module\_name/src/Helper folder.

The lines I've commented out are to stop the request to open a jQuery UI dialog box.

I'm curious as to what you guys think. It is a requirement from the client that I have this functionality in place.

Here is the code snippet taken from the Ajax Add To Cart Module:

```
namespace Drupal\ajax_add_to_cart\Helper;

use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\ajax_add_to_cart\Ajax\ReloadCommand;
use Drupal\block\Entity\Block;
use Drupal\Core\Ajax\ReplaceCommand;

/**
 * Class AjaxCartHelper.
 *
 * @package Drupal\modules\ajax_add_to_cart
 */
class AjaxCartHelper {

  /**
   * Ajax add to cart response.
   *
   * @param string $form_id
   *   Form id.
   * @param object $response
   *   Response object to store information.
   *
   * @return object
   *   Return response object.
   */
  public function ajaxAddToCartAjaxResponse($form_id, $response) {
    // Adding modal window.
    $options = [
      'width' => 250,
      'height' => 300,
    ];
    $settings = [
      $form_id => [
        'title' => t('Successful Added'),
        'message' => t('Cart Updated Successfully'),
      ],
    ];
    $title = $settings[$form_id]['title'];
    $message = $_SESSION['messages']['status'][0]->__toString();
    if (!empty($this->cartBlock)) {
      // ****LINE TO REMOVE****
      $response->addCommand(new OpenModalDialogCommand($title, $message, $options));
      // **********************
    }
    else {
      $customblock = $this->container->get('plugin.manager.block')->createInstance('commerce_cart', []);
      $render = $customblock->build();
      // ****LINE TO REMOVE****
      $response->addCommand(new OpenModalDialogCommand($title, $render, $options));
      // **********************
    }
    $response->addCommand(new ReplaceCommand('.block-commerce-cart', $this->cartBlock));
    $response->addCommand(new ReloadCommand());
    unset($_SESSION['messages']);
    return $response;
      }
}

```

I've added the comment - / \****LINE TO REMOVE\**** to the lines that need to be removed

My ideas are:

1. Duplicate the whole module so that it's custom and use that as the solution (even though module updates won't affect the custom module and i'll have to update it each time)
2. Comment the two lines out and then update the third-party module

Is there any other methods I'm missing? I've seen the libraries override but thats for the purposes of theming purposes- JS and CSS, I just wondered if theres anything out there in the drupal community fro overriding the PHP that modules provide?

It must be a common requirement by Drupal Devs.

# Answer
I think the best method would be to use the cweagan patch manager package with composer and a local patch file. This would allow the module to be updated normally with composer and the patch applied. If the code changes too much for the patch, it will fail and you can update the patch.

Just `require cweagans/composer-patches` and then modify your composer.json to include the patch.

Also, this is a good way to add patches from Drupal.org or github issues. If your fix is something that should be generally available, sumbit an issue with the patch. Then set up your composer patch section to use the URL to the patch in the issue. For d.o. patches, this makes it easy to find the issue related to the patch since it issue number is in the url.
> 1 votes

---
Tags: 8
---


# Question
Title: How to clone any standard webform element
I've been able to copy the example webform element, as detailed at Create webform element.

Although I've not tested submission yet, I think it's all looking good.

What would be great is if I could clone any of the standard webform elements.

I've made a copy of `src/WeformElement/Email.php` \- and it appears in the list of webform elements available to be inserted into the webform - but when viewing the actual webform, it is not rendered.

It may be that I have to use the example webform element to create a new copy, and then change stuff in there to render an email field instead, but as mentioned I'd appreciate any pointers towards being able to clone any of the elements.

(The reason we need to clone them is due to styling. One text field might be used for a name, and another for a completely different purpose which will be styled differently, and as the cloned element has a new id then we can use the module Themable forms to provide more template suggestions.)

# Answer
The WebformElement plugin acts as a wrapper around a Drupal Form element plugin. Therefore to actually create a webform element you need to define a Form element plugin with a corresponding Webform element plugin.

If you want to extend the Email element you need to extend the below classes

* \Drupal\Core\Render\Element\Email
* \Drupal\webform\Plugin\WebformElement\Email

All you might missing is a \Drupal\custom\_module\Element\CustomModuleEmail class which probably will look something like...

```
<?php

namespace Drupal\custom_module\Element;

use Drupal\Core\Render\Element\Email;

/**
 * @FormElement("custom_moduel_email")
 */
class CustomModuleEmail extends Email { }

```
> 1 votes

---
Tags: 8, webforms
---


title: Does the Nginx default block suffice?

text:
# Question
Title: Does the Nginx default block suffice?
The following conf file is my default Nginx conf (it's basically the one shipped with Nginx 1.10.3 in Ubuntu).

```
server {
    # listen, root, index, server_name, locations;
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/html;
    index index.php index.html index.htm index.nginx-debian.html;
    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}

```

This is my individual app Nginx configuration.

```
server {
    root ${drt}/${domain}/;
    server_name ${domain} www.${domain};
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ { expires 365d; }
}

```

Are these Nginx configuration files enough for basic, all-default Drupal usage (i.e. all core, no module customization, and up to 5 typical third-party modules)?

Enough in the sense of getting Drupal 8.4.x or later to work, with basic security.

# Answer
Here's our stock nginx config include file for Drupal sites. It gets modified to match any special file locations or other requirements and included at the bottom of the server section.

```
### Nginx configuration for Drupal. This configuration makes use of
### drush (http:///drupal.org/project/drush) for site maintenance
### and like tasks:
###
### 1. Run the cronjobs.
### 2. Run the DB and code updates: drush up or drush upc followed by
###    drush updb to run any DB updates required by the code upgrades
###    that were performed.
### 3. Disabling of xmlrpc.xml, install.php (needed only for
###    installing the site) and update.php: all updates are now
###    handled through drush.

## To avoid the ugly rewrite we use Lua to escape the URI.
set_by_lua $escaped_uri 'return ngx.escape_uri(ngx.var.uri)';

## The 'default' location.
location / {
  ## Drupal 404 from can impact performance. If using a module like
  ## search404 then 404's *have *to be handled by Drupal. Uncomment to
  ## relay the handling of 404's to Drupal.
  ## error_page 404 /index.php;

  ## Using a nested location is the 'correct' way to use regexes.

  ## Regular private file serving (i.e. handled by Drupal).
  location ^~ /system/files/ {
    ## Include the specific FastCGI configuration. This is for a
    ## FCGI backend like php-cgi or php-fpm.
    include conf/drupal/fastcgi_drupal8.conf;
    fastcgi_pass phpcgi;

    ## For not signaling a 404 in the error log whenever the
    ## system/files directory is accessed add the line below.
    ## Note that the 404 is the intended behavior.
    log_not_found off;
  }

  ## Trying to access private files directly returns a 404.
  location ^~ /sites/*/files/private/ {
    internal;
  }

  ## Support for the file_force module
  ## http://drupal.org/project/file_force.
  location ^~ /system/files_force/ {
    ## Include the specific FastCGI configuration. This is for a
    ## FCGI backend like php-cgi or php-fpm.
    include conf/drupal/fastcgi_drupal8.conf;
    fastcgi_pass phpcgi;

    ## For not signaling a 404 in the error log whenever the
    ## system/files directory is accessed add the line below.
    ## Note that the 404 is the intended behavior.
    log_not_found off;
  }

  ## If accessing an image generated by Drupal 6 imagecache, serve it
  ## directly if available, if not relay the request to Drupal to (re)generate
  ## the image.
  location ~* /imagecache/ {    access_log off;
    expires 30d;
    try_files $uri @drupal;
  }

  ## Drupal 7 generated image handling, i.e., imagecache in core. See:
  ## http://drupal.org/node/371374.
  location ~* /files/styles/ {
    access_log off;
    expires 30d;
    try_files $uri @drupal;
  }

  location ~* files/advagg_(?:css|js)/ {
    access_log  off;
    gzip_static on;
    access_log  off;
    expires     max;
    add_header  ETag '';
    add_header  Cache-Control 'max-age=31449600, no-transform, public';
    try_files $uri @drupal;
  }

  ## All static files will be served directly.
  location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|html?|xml|svg)$ {
    access_log off;
    expires 30d;
    ## No need to bleed constant updates. Send the all shebang in one
    ## fell swoop.
    tcp_nodelay off;
    ## Set the OS file cache.
    open_file_cache max=3000 inactive=120s;
    open_file_cache_valid 45s;
    open_file_cache_min_uses 2;
    open_file_cache_errors off;
  }

  include conf/other/cross-domain-fonts.conf;

  ## PDFs and powerpoint files handling.
  location ~* ^.+\.(?:pdf|pptx?)$ {
    expires 30d;
    ## No need to bleed constant updates. Send the all shebang in one
    ## fell swoop.
    tcp_nodelay off;
  }

  ## MP3 and Ogg/Vorbis files are served using AIO when supported. Your OS must support it.
  location ~* ^/sites/*/files/.*\.(?:mp3|ogg)$ {
    directio 512; # for ext3 or similar (block alignments)
    tcp_nopush off;
    aio on;
    output_buffers 1 2M;
  }

        ## Pseudo streaming of H264/AAC files.
        ## Cf. http://nginx.org/en/docs/http/ngx_http_mp4_module.html.
  location ~* ^/sites/*/files/.*\.(?:mp4|mov|m4a)$ {
    mp4;
    mp4_buffer_size 1M;
    mp4_max_buffer_size 5M;
  }

  ## Advanced Help module makes each module provided README available.
  location ^~ /help/ {
    location ~* ^/help/[^/]*/README\.txt$ {
      ## Include the specific FastCGI configuration. This is for a
      ## FCGI backend like php-cgi or php-fpm.
      include conf/drupal/fastcgi_drupal8.conf;
      fastcgi_pass phpcgi;
    }
  }

  ## Replicate the Apache <FilesMatch> directive of Drupal standard
  ## .htaccess. Disable access to any code files. Return a 404 to curtail
  ## information disclosure. Hide also the text files.
  location ~* ^(?:.+\.(?:htaccess|make|txt|engine|inc|info|install|module|profile|po|pot|sh|.*sql|test|theme|tpl(?:\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
    return 404;
  }

  ## First we try the URI and relay to the /index.php?q=$uri&$args if not found.
  try_files $uri @drupal;
}

########### Security measures ##########

## Restrict access to the strictly necessary PHP files. Reducing the
## scope for exploits. Handling of PHP code and the Drupal event loop.
location @drupal {
  ## Include the FastCGI config.
  include conf/drupal/fastcgi_drupal8.conf;
  fastcgi_pass phpcgi;

  track_uploads proxied 60s;
}

location @drupal-no-args {
  ## Include the specific FastCGI configuration. This is for a
  ## FCGI backend like php-cgi or php-fpm.
  include conf/drupal/fastcgi_no_args_drupal8.conf;
  fastcgi_pass phpcgi;

}

include conf/other/protect-system-files.conf;

## Disable access logs for robots.txt.
location = /robots.txt {
  access_log off;
  ## Add support for the robotstxt module
  ## http://drupal.org/project/robotstxt.
  try_files $uri @drupal-no-args;
}

## RSS feed support.
location = /rss.xml {
  try_files $uri @drupal-no-args;
}

## XML Sitemap support.
location = /sitemap.xml {
  try_files $uri @drupal-no-args;
}

## Support for favicon. Return an 1x1 transparent GIF if it doesn't
## exist.
location = /favicon.ico {
  expires 30d;
  try_files /favicon.ico @empty;
}

## Return an in memory 1x1 transparent GIF.
location @empty {
  expires 30d;
  empty_gif;
}

## Any other attempt to access PHP files returns a 404.
location ~* ^.+\.php$ {
  return 404;
}

```
> 0 votes

---
Tags: 8
---


title: How to use a block as a field?

text:
# Question
Title: How to use a block as a field?
I'm working with this module which is providing me a block for uploading the file as mentioned in the doc https://drupal.org/project/jquery\_file\_upload

Is there a way, where I can use this block as a field while adding the content, for instance at `node/add/[my_custom_content]`?

# Answer
> 2 votes
The Drupal 7 block\_reference module will allow you to select a block as a field. But you need to be careful that you don't also enable the global block for that path, or you'll get TWO of the same block.

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

# Answer
> 1 votes
No, fields are totally independent concept than blocks. Of course there is a way to have a region inside field, and you could then drop that block to region, but there would be no connection between block's uploading capabilities and created node.

If you have a fancy file uploading requirements, it would be better to write them down and ask what module can do it for your file or image field.

# Answer
> 0 votes
Use the module DS(https://drupal.org/project/DS), or else use block api in your content body(https://api.drupal.org/api/drupal/includes%21module.inc/function/module\_invoke/7).

# Answer
> 0 votes
yes - you cannot use blocks as fields ..

the plupload module does exactly what you want, combinated with filefield.

---
Tags: 7, entities, files, javascript
---


title: Clear session on checkout complete

text:
# Question
Title: Clear session on checkout complete
I'm using the following code to remember shopping carts per session. The code works just fine, but the problem is that the cart is not emptied on checkout complete, but shows the contents of the completed order. So the session needs to be cleared on checkout completion so that a new empty order will be created. How do I accomplish this?

```
function mymodule_commerce_cart_order_id($uid = 0) {
  $key = $uid . '-' . session_id();
  $carts = variable_get('mymodule_carts', array());
  if ( isset($carts[$key]) ) {
    return intval($carts[$key]);
  } else {
    // create a new cart for this session
    $order = commerce_cart_order_new($uid);
    $order->data['last_cart_refresh'] = REQUEST_TIME;
    $order_id = intval($order->order_id);

    // save the new order id to the module settings cache
    $carts[$key] = $order_id;
    variable_set('mymodule_carts', $carts);

    return $order_id;
    }
}

```

# Answer
I took some ideas form the commerce\_cart\_order\_id() function and changed the code, seems to work like I want it to now:

```
function mymodule_commerce_cart_order_id($uid = 0) {

 $status_ids = array_keys(commerce_order_statuses(array('cart' => TRUE)));

 // If a customer uid was specified...
 if ($uid) {
   // Look for the user's most recent shopping cart order, although they
   // should never really have more than one.
   $cart_order_ids[$uid] = db_query('SELECT order_id FROM {commerce_order} WHERE uid = :uid AND status IN (:status_ids) ORDER BY order_id DESC', array(':uid' => $uid, ':status_ids' => $status_ids))->fetchField();
 } else {
   // Otherwise look for a shopping cart order ID in the session.
   if (commerce_cart_order_session_exists()) {
     // We can't trust a user's IP address to remain the same, especially since
     // it may be derived from a proxy server and not the actual client. As of
     // Commerce 1.4, this query no longer restricts order IDs based on IP
     // address, instead trusting Drupal to prevent session hijacking.
     $cart_order_ids[$uid] = db_query('SELECT order_id FROM {commerce_order} WHERE order_id IN (:order_ids) AND uid = 0 AND status IN (:status_ids) ORDER BY order_id DESC', array(':order_ids' => commerce_cart_order_session_order_ids(), ':status_ids' => $status_ids))->fetchField();
   }
   else {
     $cart_order_ids[$uid] = FALSE;
   }
 }

 if($cart_order_ids[$uid]) {
   return $cart_order_ids[$uid];
 } else {
     // create a new cart for this session
     $order = commerce_cart_order_new($uid);
     $order->data['last_cart_refresh'] = REQUEST_TIME;
     $order_id = intval($order->order_id);

     return $order_id;
  }
}

```
> 0 votes

# Answer
I figured out a solution, but I'm not sure if it's the best solution yet. I modified the code so that it creates a new order if the $uid of the order doesn't match and order is placed.

```
function mymodule_commerce_cart_order_id($uid = 0) {
   $key = $uid . '-' . session_id();

   $carts = variable_get('mymodule_carts', array());
   if ( isset($carts[$key]) ) {
     $order = commerce_order_load(intval($carts[$key]));
   }

   if ( isset($order) && $uid == $order->uid && $order->placed == '0') {
      return intval($carts[$key]);
   } else {
       // create a new cart for this session
       $order = commerce_cart_order_new($uid);
       $order->data['last_cart_refresh'] = REQUEST_TIME;
       $order_id = intval($order->order_id);

       // save the new order id to the module settings cache
       $carts[$key] = $order_id;
       variable_set('mymodule_carts', $carts);

       return $order_id;
   }
 }

```
> 0 votes

---
Tags: commerce, sessions
---


# Question
Title: How to change the value of a field in its preprocess method?
I am trying to figure out Drupal 8's `$variables` array ...

So I have a `MYTHEME.theme` file, complete with a working `MYTHEME_preprocess_field()` function. (I know it works because I use it for other fields that need customization.)

Right now I'm focusing on the title of an article displayed on the front page of my site. I can access it with the following code.

```
if ($variables['field_name'] == 'title') {
    $title = $variables['element'][0]['#context']['value'];
    // ...
}

```

What I want to do is replace all instances of *®* (the registration mark) with `<sup>®</sup>`. However, setting this value in the array to something else does *not* change it on the site.

Is there something I'm missing? A few sources I found said to alter (or add) the *#markup* element in the array, but there's a dearth of information about this online.

How do I change the value of a field? This seems like it should be something basic and easy to do.

# Answer
> 4 votes
In Drupal 8 front page is a view called **frontpage** if the view is not modified it should `show: "Content"` by default (instead of fields). If so the following can be applied to change each node title

```
function THEMENAME_preprocess_node(&$variables) {
  //for views that show: "Content" (not fields)
  if($variables["is_front"]){
    $variables["label"][0]["#context"]["value"] .= " end of title";
  }
}

```

---
Tags: 8, theming, entities
---


title: How do I clone a product?

text:
# Question
Title: How do I clone a product?
Is there any method yet for cloning existing products in Drupal Commerce 2?

# Answer
Be careful with the https://www.drupal.org/project/entity\_clone module. Because it may happen that you've made a ton of product clones and then decided to edit, let say, price of some variation on a clone or a "parent" product. The price will change everywhere. The same with deletion of variation. Moreover, the same with deletion of any of the clones or the "parent". All variations will be deleted everywhere. But that's not the end. If you try to delete any of variation-less clones you'd get fatal error. So, to delete this clone you need to save at least one variation.

That's because variations are entities which can be referenced by multiple products. Read more: https://www.drupal.org/project/commerce/issues/2941524

So, as I understand you need cloning for cutting off the time spent on variations creation, which is quite tedious work, I'd say. If so, you may try the Commerce Bulk module.
> 1 votes

# Answer
You could try the following module. I've heard it might work for products but not for other commerce entities.

https://www.drupal.org/project/entity\_clone
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: How to catch twig errors and display custom 500 error page?
I have a patch to add some custom handling of 500 errors that run through the code in errors.inc, so that it returns a themed page in those cases.

This works well in certain conditions, but I have an error that occurred with a misnamed twig template, so I got

```
Twig_Error_Loader: Template "@mytheme/search-result/search-result--event.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "@mytheme/search-result/search-result--event.twig" in the Drupal theme registry.) in "themes/custom/mytheme/templates/node/node--admissions-event--search-result.html.twig" at line 1. in Twig_Loader_Chain->getCacheKey() (line 129 of /var/www/mytheme-qa/site/vendor/twig/twig/lib/Twig/Loader/Chain.php).

```

After some digging I see that this error is generated here: /core/lib/Drupal/Core/Template/Loader/ThemeRegistryLoader.php

```
if ($throw) {
  throw new \Twig_Error_Loader(sprintf('Unable to find template "%s" in the Drupal theme registry.', $name));
}

```

The problem is this type of error isn't handled by Drupal. It's a Twig engine error. So an exception subscriber doesn't catch this.

Any suggestions on how to return a themed 500 page in fatal error cases like this at the theme layer?

# Answer
> 1 votes
Just checked, there is no special handling of Twig exceptions in core, so they end up in `FinalExceptionSubscriber`. You can add a custom exception subscriber catching `Twig_Error_Loader` or `Twig_Error_Syntax` and return a themed response (though you might need to theme this yourself when the theme layer is broken because of the Twig error).

`error.inc` has nothing to do with this as long as there is no fatal error not catchable by Symfony (but this would be a failure of the Twig layer, which normally protects you from low level errors)

---
Tags: 8, theming
---


# Question
Title: can I call my entity checkCreateAccess function from custom code?
I have several custom entities in my projects.

To check access for certain links, I would like to utilize the `checkAccess()` and `checkCreateAccess()` functions in the `MyEntityAccessControlHandler` classes.

How do I call these from the Controller class or from the module file?

# Answer
Something like this should do the trick.

```
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

$entity_type_mgr = \Drupal::getContainer()->get('entity_type.manager');
if (!$entity_type_mgr->getAccessControlHandler($type)->createAccess($bundle)) {
  $permission = "create $bundle $type entities";
  throw new AccessDeniedHttpException("You don't have permission to " . $permission);
}

```
> 0 votes

---
Tags: entities
---


# Question
Title: How to perform some Rules Actions WHILE some condition is TRUE?
Using Rules, how can you perform a set of Rules Actions ***`WHILE`*** (`some condition` = `TRUE`)?

About that condition: I'm not talking here about a Rules Condition ... Instead I mean some sort of boolean expression that evaluates to either `TRUE` or `FALSE`.

Also, even though Rules has the concept of "Lists and Loops" (for which you can typically iterate over each item of such list via a Rules Loop), that's not what my question is about either.

# Answer
> 1 votes
I'm not aware how to implement such WHILE-construction by only using Rules. However, if you also enable the Conditional Rules module, you can implement such WHILE-construction.

### Example

Consider this rule (in Rules export format):

```
{ "rules_execute_a_while_loop" : {
    "LABEL" : "Execute a while loop",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_nr" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Value specified for \u0022Free format nr\u0022 is: [node:field-free-format-nr]" } },
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "1" },
          "PROVIDE" : { "variable_added" : { "loop_counter" : "Loop counter" } }
        }
      },
      {
        "WHILE" : { "NOT data_is" : {
            "data" : [ "loop-counter" ],
            "op" : "\u003E",
            "value" : [ "node:field-free-format-nr" ]
          }
        },
        "DO" : [
          { "drupal_message" : { "message" : "Do your thing for \u0022loop_counter\u0022 value = [loop-counter:value]" } },
          { "data_calc" : {
              "USING" : { "input_1" : [ "loop-counter" ], "op" : "+", "input_2" : "1" },
              "PROVIDE" : { "result" : { "incremented_counter" : "Incremented counter" } }
            }
          },
          { "data_set" : { "data" : [ "loop-counter" ], "value" : [ "incremented-counter" ] } }
        ]
      }
    ]
  }
}

```

Some more details about this rule:

* Rules Events: After creating a new node, or after updating an existing node.
* Rules Conditions:
    + Content is of type "Article".
    + Entity has field, for field with machine name `field_free_format_nr` (which is of type `integer`).

The above Rules Events and/or Rules Conditions can be more or less anything (I just used some of the popular ones). The actual magic is in the Rules Actions:

* `Show a message on the site`, just for demo / testing purposes, to show the value enter for the `field_free_format_nr` field.
* `Add a variable`, with machine name `loop_counter`, and initial value `1`.
* `While: NOT Data comparison`, whereas the test is to check if NOT (`loop-counter` is greater than `[node:field-free-format-nr]`), in which case all of the below Rules Actions are performed:

+ `Show a message on the site`, just for demo / testing purposes, to show a message like
> Do your thing for "loop\_counter" value = \[loop-counter:value\]

+ `Calculate a value`, to increment `loop_counter` with `1`, and (temporary) store the result in `incremented_counter`
    + `Set a data value`, to copy the value of `incremented_counter` in `loop_counter`

BTW, it could well be that the last 2 Rules Actions can be consolidates in a single one, though using 2 Rules Actions should be easier to understand what's happening.

### Demo

With the above rule enabled, these are the messages shown if I create or update an article, and specify a value of `3` for the `field_free_format_nr` field:

```
Value specified for "Free format nr" is: 3
Do your thing for "loop_counter" value = 1
Do your thing for "loop_counter" value = 2
Do your thing for "loop_counter" value = 3

```

---
Tags: 7, rules
---


# Question
Title: Group Module: Join & Remove users from user account/profile 2?
I added an entityreference to the user's Account so users can select what group they want to join (checkboxes). They check it and via a rule, it automatically adds them to that group. I did this for multiple Group Types.

Now i need it to remove user (unsubscribe) from group if "unchecked". Right now users keep on getting added if they select a new checkbox, but they are not removed from the previous group.

How can the we remove them from the now unchecked group and add them to the newly checked rule?

I found how to delete all group subscriptions on one rule. However, it removes all subscriptions, even those not found in this entityreference. How can we limit to add/remove users from only these group types?

Willing to pay for support on this issue.

Thank you.

# Answer
I solved this. :)

I used the views\_rules module to create a view that filtered a list of exactly what i needed (filtering the group type per user).

I then created a rule:

* Before saving a user account
* Condition if previous is equal to new saved (Negate). So it will only run if there are changes in the field in question.
* Added View Loop i created. Add action \> Delete entity mid from the view loop.

Done. This deletes or unsubscribes any unchecked boxes/groups.

Now to create any new memberships/subscriptions to selected groups...

I added condition...

-If field empty... do nothing

-Else

-Loop the field in question (gmem\_created)

-Create new entity of type group membership

-Save a data value

Data: \[gmem-created:group\], Value: \[account:field-yourgroup\]

-Save a data value

Data: \[gmem-created:user\], Value: \[account\]

-Save entity

Entity: \[gmem-created\], Force saving immediately: true
> 0 votes

---
Tags: users, group
---


title: Linking taxonomy terms in views

text:
# Question
Title: Linking taxonomy terms in views
I am using Drupal 8 and I am creating an internship placement system where students sign up and have a skills field (using taxonomy terms).

Employers can create job postings, which have same skills field.

How do I link matching fields (skills) in a view so that when a student logs in they only see jobs related to their skills?

# Answer
You need to use views as described below

## 1. Create a user view (not content view)

## 2. Add contextual filter user id with default value current logged in user

## 3. Add relationship on terms referenced from field skills (of user)

## 4. Add relationship with term from skills

**The previous relationship should be autoselected**

## 5. Now you can add content fields to view and the field skills relationship should be autoselected

when a user visits the view page the jobs will be contextually filtered based on their profile selections
> 0 votes

---
Tags: views
---


# Question
Title: Webform 5.x lookup validation via data table lookup
I want to block/validate a new entry based on another submitted form

e.g.

If a site number has been used I want to block any new entry that wants to use that number?

Is this possible?

If so How?

Thanks all

# Answer
> 0 votes
Webform elements support unique value validation, which I should be able to address your requirement. If not, you may need to write a custom form alter hook with a custom validate callback.

---
Tags: webforms
---


# Question
Title: How to hide the unflag link text once the flag is set?
I have a node flag abuse and I want to remove/hide unflag link text "non-abuse" once the abuse flag is set.

How to do this in Drupal? Since I am new to Drupal, I can't think of a solution for this.

**Note**: I'm using this inside the Panels module.

# Answer
> 2 votes
In Drupal 7 you can use The Flag API (JavaScript) for this

> **The flagGlobalAfterLinkUpdate event** : This event is triggered immediately after a flag link has been updated. (Flag links appear in two flavors: "Bookmark this!" and "Unbookmark this!", and when we speak of "update" we mean this change in appearance).

```

    (function ($) {
        $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
            if (data.flagName == 'yourFlagName' && data.flagStatus == 'flagged') { //dont forget to add your flag name
                var flgName = '.flag-'+data.flagName;
                $(flgName).hide('slow');
            }
        });
    })(jQuery);

```

# Answer
> 1 votes
In the flag settings page under *`FLAG ACCESS`* you have `Roles that may use this flag` Just un-check `UNFLAG` option for all the roles.

# Answer
> 0 votes
So u are using Panels. It would be better to add a visibility criteria on the flag link block.

For that, go to that block on the panels page -\> Click on **Visibility rule** -\> Click on **Add a new Rule** -\> Check on **Content is flagged**.

So when u hit save it would show you all the flags that are there.

In my case it shows this

So select the desired flag and check the Reverse(Not) checkbox.

Hit save and it would serve your purpose.

# Answer
> 0 votes
I am new to Drupal Javascript, but try this. https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

Declare JS in root theme .info file - put mycustomjs.js in theme root folder

````
(function ($) {

```

Drupal.behaviors.exampleModule = {
 attach: function (context, settings) {
 // Code to be run on page load, and
 // on ajax load added here
 }
 };
}(jQuery));`

---
Tags: flags
---


# Question
Title: How do I convert a Drush make commit-level dependency into Composer?
I am remaking old project to use composer for building and I have a problem I cannot find solution to. Basically this is how library is defined in `profile.make` file:

```
; HybridAuth
libraries[hybridauth][directory_name] = 'hybridauth'
libraries[hybridauth][type] = 'library'
libraries[hybridauth][download][type] = 'git'
libraries[hybridauth][download][url] = 'https://github.com/hybridauth/hybridauth.git'
libraries[hybridauth][download][revision] = 'd4e5bc34008e8c187c302eb4e94200ee4a208c63'

```

How should I rewrite it correctly in my composer.json file? To be precise, how to get revision? This is what I have so far:

```
{
      "type": "package",
      "package": {
        "name": "library/hybridauth",
        "version": "d4e5bc34008e8c187c302eb4e94200ee4a208c63",
        "type": "drupal-library",
        "dist": {
          "url": "https://github.com/hybridauth/hybridauth.git",
          "type": "git"
        }
      }
    },

```

it is complaining about my `"version"` line:

```
  [Composer\Repository\InvalidRepositoryException]
  A repository of type "package" contains an invalid package definition: Inva
  lid package information:
  version : invalid value (d4e5bc34008e8c187c302eb4e94200ee4a208c63): Invalid
   version string "d4e5bc34008e8c187c302eb4e94200ee4a208c63"
  Invalid package definition:
  {"name":"library\/hybridauth","version":"d4e5bc34008e8c187c302eb4e94200ee4a
  208c63","type":"drupal-library","dist":{"url":"https:\/\/github.com\/hybrid
  auth\/hybridauth.git","type":"git"}}

```

# Answer
The location you're defining it at is wrong. When defining your own packages, the `version` tag is used to target **branches** or **tags**. If you want specify a commit-level project requirement, do it in `require` object where you're specifying your requirement in the `dev-${BRANCH}#${COMMIT_HASH}` format.

In `repositories`:

```
{
  "type": "package",
  "package": {
    "name": "hybridauth/hybridauth",
    "version": "master",
    "type": "drupal-library",
    "source": {
      "url": "https://github.com/hybridauth/hybridauth",
      "type": "git",
      "reference": "master"
    }
  }

```

In `require`:

```
"hybridauth/hybridauth": "dev-master#38f0735",

```
> 1 votes

---
Tags: drush, composer
---


# Question
Title: D7: Resetting ALL user fields (Boolean) at once
In a nutshell, I'm trying to stop my users from getting e-mailed more than once per day.

* I have some rules set up that will e-mail users when content particular to them is updated.
* I have added a Boolean field to user profiles that starts off 'checked' (1) - indicating they have not (yet) been emailed today.

Any rules that e-mail users will first check this user profile value and proceed only if they haven't been e-mailed (field value is 1), but then set this Boolean value to 0 using set a data value in Actions - thus they won't get e-mailed again until the value is changed.

What's the best/easiest way to 'reset' that field in ALL user profiles periodically? (probably once a day)

i.e. at 10:00PM set the boolean field "field\_user\_not\_emailed\_today" for ALL users to 1. (checked)

I've seen VBO recommendations for this sort of thing, but seems unnecesary given the ALL users thing. Is there perhaps a PHP snippet I could call in Rules that would do the trick?

Thanks!

# Answer
> 1 votes
The Rules Once per Day module provides a 'Once per day' rules event that you can use to trigger your boolean flag update.

For bulk updating a list of users, if you have an action that loads a list of users you can then loop through and act on those users with rules.

There are a number of ways you can load a list of users in rules. Some of them are:

1. The Views Bulk Operations module provides some actions including 'Load a list of entity objects from a VBO view'
2. The Views Rules module provides the 'Collect view result rows' action.
3. The Rules Bonus Pack module provides a number of actions, including 'Load a user list with Views'.
4. You can create a custom action of your own via a custom module. See the rules developer documentation and various blog posts for more details.

I'm not sure of any easier way to loop through all users in the system, but the views approach is fairly straight forward and low maintenance anyway.

Also, you might not always want to loop through all users. for example you might want to exclude administrators or only loop through users where your boolean field is set to 1, to avoid unnecessary processing in the case that not all users have been set to 1 for whatever reason.

The action you use to load the users will create a new variable (eg. 'entity-list') that will be available in future actions. You can then use the 'Add loop' option in the rules actions section to loop through that new variable. That loop will create another new variable for the current item (eg. 'list-item') your are looping over and then you can add actions that act on that variable (eg. data set on list-item:field-user-not-emailed-today).

---
Tags: entities, users, rules
---


# Question
Title: How to get url and description of FileFieldItemList's items in node template
I have a content type called publication which results the node's twig template: `node--publication.html.twig`. This content type contains a multiple file fields where the description is allowed.

I would like to share it with you, because it took a lot of time for me to find out how can I iterate through and render the items of a `FileFieldItemList` which would be a very easy thing without the drupal theming system.

Some of you might find useful it.

# Answer
I am able to access the `uri`, and I can generate url from it by a Twig filter.

```
{{ content.field_document.0['#file'].uri.value|urlFromUri }}
{{ content.field_document.1['#file'].uri.value|urlFromUri }}
{{ content.field_document.2['#file'].uri.value|urlFromUri }}

```

and the `description`:

```
{{ content.field_document.0['#description'] }}
{{ content.field_document.1['#description'] }}
{{ content.field_document.2['#description'] }}

```

the Twig filter:

```
<?php

namespace Drupal\something_general\TwigExtension;

use Drupal\Core\Url;

class Custom extends \Twig_Extension
{

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters()
  {
    return [
      new \Twig_SimpleFilter('urlFromUri', array($this, 'UrlFromUri')),
    ];
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName()
  {
    return 'custom.something_general.twig_extension';
  }

  /**
   * @param $uri
   */
  public static function UrlFromUri($uri)
  {
    $realpath = drupal_realpath($uri);
    $path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $realpath);

    return $path;
  }

}

```

I am also able, to get the number of the items of the `FileFieldItemList`:

```
{% for index in 1..node.field_document.getValue|length %}
{% endfor %}

```

And finally the iteration in the `node--publication.html.twig` file:

```
{% for index in 1..node.field_document.getValue|length %}
  {% set document = content.field_document[ (index-1) ] %}

  {{ dump(document['#file'].uri.value|urlFromUri) }}
  {{ dump(document['#description']) }}

{% endfor %}

```
> 0 votes

---
Tags: 8, theming
---