# Question
Title: How can I block users from registering with disposable email addresses?
I have a site where users send messages to one another using the Private Message module, and they are notified of messages by email.

On this site, there are a variety of spammers, scammers, and abusive users who attempt to register multiple accounts using disposable email addresses.

I know it's impossible to block every possible disposable email address domain, but is there anything in the Drupal world that can help me?

* I considered white-listing valid domains, but my user base is too diverse for this.
* The only project I could find on drupal.org has been abandoned.
* There are third-party APIs such as this one.

**At the moment, I'm blocking them manually using this code:**

```
/**
 * Custom validation function from the Domain Registration module (1.0).
 *
 * Checks if the domain in the email address is on a list of blocked domains.
 * @param $form
 * @param $form_state
 */

function MYMODULE_domain_registration_user_register_validate(&$form, &$form_state) {
  $default_message = t('You are not allowed to register for an account on this site.  Contact support for more information.');
  $mail = explode('@', $form_state['values']['mail']);
  $exact_domains = array(
    'ad.drupaler.org',
    'drupaler.org',
  );
  $partial_domains = array(
    'pp.ua',
    'guerrilamail',
  );
  if (isset($mail[1]) && !empty($exact_domains)) {
    if (in_array($mail[1], $exact_domains) || MYMODULE_contactinfo_check_banned_words($mail[1], $partial_domains)) {
      form_set_error('account', variable_get('domain_registration_message', $default_message));
    }
  }
}

```

# Answer
> 2 votes
Like you mentioned it is impossible to block all disposable domains.

If you want to end the madness, the most effective solution would be: Upon registration you send a confirmation link or code to a mobile phone number

Take a look at:

1. SMS Framework module
2. VoIP Drupal module

Using Unique field you could make sure that the phone number can only be used once.

Checkout: How to send SMS messages (Drupal Tutorial)

# Answer
> 1 votes
Your solution is good ( but I think sms verification is better solution),any way I improved your solution with integrate it with `block-disposable-emai`,have simple JSON BASE APIs

```
   /**
 * Custom validation function from the Domain Registration module (1.0).
 *
 * Checks if the domain in the email address is on a list of blocked domains.
 * @param $form
 * @param $form_state
 */

function MYMODULE_domain_registration_user_register_validate(&$form, &$form_state) {
  $default_message = t('You are not allowed to register for an account on this site.  Contact support for more information.');
  $mail = explode('@', $form_state['values']['mail']);
  $exact_domains = array(
    'ad.drupaler.org',
    'drupaler.org',
  );
  $partial_domains = array(
    'pp.ua',
    'guerrilamail',
  );

  $key     = '12345abcapikey'; //please get your own valid api key
  $request = 'http://check.block-disposable-email.com/api/json/'.$key.'/'.$mail[1];
  if (isset($mail[1])) {
  $response = file_get_contents($request);
  $dea = json_decode($response);
  if ($dea->request_status == 'success'){
    if ($dea->domain_status == 'block' && $dea->domain_type == 'dea_provider' && $dea->domain_is_handpicked == 1){
    // deny registration ...
              form_set_error('account', variable_get('domain_registration_message', $default_message));

    }

  }else{
    form_set_error('account', "try again");
   }
  }
  }

```

# Answer
> 0 votes
I'm facing the same problems so I create a Free API service that recognize disposable and temporary email address: Block Temporary Email

Email Endpoint:

`GET` `https://block-temporary-email.com/check/email/example@simplemail.top`

JSON response:

```
{
  "status": 200,
  "domain": "simplemail.top",
  "temporary": true,
  "dns": true,
}

```

This API is 100% free and have no limits.

This site provides a free and updated TXT list of disposable email providers too.

**Disclaimer: I made this API**

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


# Question
Title: Add custom attribute to an external JS script
It's not really clear how to add custom attributes when adding an external JS script to the page.

Currently I have this code:

```
drupal_add_js('https://code.jquery.com/jquery-3.4.1.js', array('type' => 'external'));

```

How can I add an `integrity` attribute to the rendered script tag?

The rendered script should look like this:

```
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="></script>

```

I know this post exists, but I'm not able to use that solution since the source is loaded externally and I will not be able to check on the source.

# Answer
I solved the problem using `drupal_add_html` like this,

```
$data = array(
  '#tag' => 'script',
  '#value' => '',
  '#attributes' => array(
    'src' => 'https://code.jquery.com/jquery-3.4.1.js',
    'integrity' => 'sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=',
  ),
);
drupal_add_html_head($data, 'unique_key');

```
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Displaying all values of a List (text) field, whether checked or unchecked
\[Drupal 8\]

I have a List (text) field that allows multiple values, displayed as a check box list when editing. But when viewing the node, only the checked values are displayed.

**How can I display *all* values, with an indicator which ones are checked/unchecked?** Is this possible with theming?

What I found so far:

* For Boolean fields, I can select something like this under "Output format" (e.g., "✔ / ✖"), but this doesn’t seem to be possible for List (text) fields. I guess the workaround would be to use multiple Boolean fields, but this makes Views Exposed Filters harder to use.
* For Drupal 7, there is the module Selected and unselected values formatter (via the question *How to display all values of List (text) instead of just the selected ones?*)
* I could imagine (but didn’t try) it would be possible to create a View and display it instead of the field, but then quick-editing would no longer work for this field, as far as I know.

# Answer
> 3 votes
You can easily generate a field formatter to output what you need in drupal 8 (generate field formatter =\> `drupal gpff` with drupal console) and get the result into a view.

Getting the field definition will allow you to get all possibles values (selected or not) for your list and display items as check or not considering the current node value.

```
$defs = \Drupal::service('entity_field.manager')->getFieldDefinitions('{ENTITY_TYPE}', '{BUNDLE}');
$field_definition = $defs['{FIELD_NAME}'];

```

Your custom formatter will be available in views (and everywhere it is usable, node display etc.).

# Answer
> 1 votes
'Display Selected and Unselected' module - is one of the possible solutions for Drupal 8.

---
Tags: 8, entities
---


# Question
Title: Move "Log in or Register to post comments" to the bottom of the page
For some reason any time a new post is made at the top of the post a module shows up saying

`Log In or Register to post comments`

The problem is that it shows up way at the top of the post, instead of down in the comments area, as well as at the top of every post. Meaning it will show up several times on the front page.

I was unable to see anything that seemed related in the Block Layout for my theme or anywhere else

Does anyone know if there's a way to change this?

# Answer
You need to change the fields order in Manage display `/admin/structure/types/manage/page/display` (replace `page` with your content type machine name e.g. `article`). Change Links after Comments.

If you don't want to show this information in lists, then in teaser view mode drag links under Disabled. Note that this will also disable the default read more link. If you don't have teaser tab available, then you need to enable it under Custom display settings.
> 1 votes

---
Tags: blocks
---


# Question
Title: Webform page wizard and submission data - no reference to which page the element was on
I am creating a multi-page webform questionaire using the Page wizard.

I have also created a custom handler so I can manipulate the data from the form when completed.

My issue is that when using $webform\_submission-\>getData in the method 'submitForm' in my webform handler class to gather the data, there is no reference to which page the element is from, the array simply contains the element key and value pair.

What would be a proper way of figuring out which page each element is from?

# Answer
My solution for this in the end was to use a method on the webform object called getPagesWithElements.

```
// Get webform object
$webform_obj = \Drupal::entityTypeManager()->getStorage('webform')->load('webform_id');
// Get page/element structure
$model = $this->getPagesWithElements($webform_obj);

```
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Token to get the last component of [node:url]
I'm using `[node:url:relative]` but my path has multiple parts `/content-type/node-title` . I would like to get only the `node-title` part.

Alternatively, a token that give me the node title transliterate would be fine.

# Answer
> 0 votes
`[node:title]` will give you the node title.

---
Tags: 8, tokens
---


# Question
Title: Set label of $entity programmatically in a custom form
I need to change the label of a custom content type programmatically. I've looked around but I couldn't find a solution. This is my custom form:

```
class GroupContentForm extends ContentEntityForm {

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;

    $entity->set('label', 'kkkkk');
    $status = parent::save($form, $form_state);

    $form_state->setRedirect('entity.group_content.canonical', ['group_content' => $entity->id()]);
  }

}

```

What do I need to do to change the label? `$entity->set('label', 'kkkkk');` causes an error as the field label doesn't exists, the same happens with `title` and `_title`

# Answer
It's not clear what entity type you have. In the question you ask for the label of a content type, which would be the entity `node`, then the label field is `title`. In the question title it is a more general question about the label of an entity and in the code you redirect to a `group_content` entity route, which would suggest this is another entity type.

In this case, if you don't know the entity type, you could use this generic code to get the label field name and set the label with it:

```
$label_field = $entity->getEntityType()->getKey('label');
$entity->set($label_field, 'New label');

```
> 2 votes

# Answer
If you are trying to update a node you can use `setTitle()`, like this:

```
$entity->setTitle('My custom title');

```

For other entity types you can use:

```
$entity->setLabel('My custom title');

```

I also see that you don't save the entity, make sure to save the entity after setting the title:

```
$entity->save();

```
> 1 votes

# Answer
How about using `hook_entity_presave`?

```
/**
 * Implements hook_entity_presave().
 */
function MY_CUSTOM_MODULE_entity_presave(EntityInterface $entity) {
  $type = $entity->getEntityTypeId();
  if ($type == 'node') {
    // Add more logic based on your needs.
    $entity->set('title', 'kkkkk');
  }
}

```
> 0 votes

---
Tags: 8, forms
---


title: CKEditor add custom class to table

text:
# Question
Title: CKEditor add custom class to table
I want to add a class to a table inserted in CKEditor.

I have tried to add a custom style using the styles dropdown and add this line, `table.my-custom-class|Table`, but when clicking on the table the styles dropdown is not activated and I'm not able to add the class.

Is this possible to do with the styles dropdown?

I do use the `ckeditor_tabletoolstoolbar` module, so alternativaly I can add a custom button to the toolbar, but I don't know how to do that either?

I have seen this thread, but it's for CKEditor 3, I'm using CKEditor 4.

I want to be able to toggle the class, so it's removed when clicking the button again.

How can I solve this problem?

# Answer
I solved the problem by creating a custom CKEditor plugin.

This is the JS code, in case anyone find it helpful:

```
CKEDITOR.plugins.add('tableclass', {
  beforeInit: function (editor) {
    editor.ui.addButton('addtableclass', {
      label: 'Add table class.',
      command: 'addTableClass',
      icon: '/modules/custom/mymodule/icons/add.png'
    });
  },
  init: function (editor) {
    editor.addCommand('addTableClass', {
      canUndo: true,
      exec: function (editor, data) {
        const className = 'custom-class';
        var selection = editor.getSelection();
        var selectedElement = selection.getStartElement().$;

        if (selectedElement.localName === 'table') {
          selectedElement.classList.toggle(className);
        }
        else {
          selectedElement = selectedElement.parentNode;
          while (selectedElement && selectedElement.localName !== 'table') {
            selectedElement = selectedElement.parentNode;
          }
          if (selectedElement.localName === 'table') {
            selectedElement.classList.toggle(className);
          }
        }
      }
    });
  }
});

```
> 2 votes

---
Tags: 8, wysiwyg
---


# Question
Title: How do I map attachments submitted via mailhandler?
In Drupal-7 I'm reading an imap mailbox with mailhandler. I have the mapping setup via feeds. This processes text messages creating a node but messages with attachments don't have the attachments stored.

How do I store the attachments?

# Answer
I created a file field and mapped the attachment.

1. Create the file field under structure/types. Set number of values to 'unlimited'.
2. Under the feeds mapping map attachments to File:URI
> 0 votes

---
Tags: feeds, emails
---


# Question
Title: How to save the webform data to custom table?
I designed a student registration form using webforms module. My requirement is to save data from the form to table student. How can i achieve this? Is there anyway to mention this in configuration file?

# Answer
You can add custom submit handler to your Webform through `hook_form_alter` for inserting it's data into your custom table.

To achieve it check the below example.

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

function MODULE_NAME_form_alter(&$form, $form_state, $form_id){
  if($form['#form_id'] == "YOUR_WEBFORM"){
    $form['actions']['submit']['#submit'][] = 'YOUR_CUSTOM_FUNCTION';
  }
}

function YOUR_CUSTOM_FUNCTION(&$form, $form_state){
  $query = Database::getConnection();
  $query->insert('YOUR_CUSTOM_TABLE_NAME')->fields(
    array(
      'FIELD_NAME_IN_TABLE' => $form_state->getValue('FIELD_NAME_IN_FORM'),
    )
  )->execute();
}
```
> 1 votes

---
Tags: 8, forms, database, webforms
---


# Question
Title: Can a product support recurring and not recurring payment at the same time?
So if for some product variant I check option "Allow subscriptions" all product variants of that products can be bought only in recurring way? Is that true?

I mean, I can not have one product and one set of variations that can be purchased "normal" way (by paying whole price during checkout process) and other set of variations support subscriptions and recurring payment? Is that right?

If I want to support both ways of paying (recurring and "normal") for one product I actually have to create 2 separate products? Correct?

Asking because when I edit product variation fields "Subsription type" and "Billing schedule" are both mandatory.

# Answer
> 1 votes
If you take a look at `this` page, you can see that what comes out of the box is that you create a seperate product variation for the recurring products and then create seperate products.

Instructions from the docs:

> 1. Download and install the Commerce Recurring Framework and Advanced queue Drupal modules.
>     1. Create a variation for the recurring products
>     2. Go to admin/commerce/config/product-variation-types
> 2. Add a product variation type with the “Allow subscriptions” trait
> 3. Create a product type for recurring products
>     1. Go to admin/commerce/config/product-types
>     2. Add a product type that uses the previously-created product variation
> 4. Create one or more billing schedules. The billing schedules will become options when configuring your product.
>     1. Go to admin/commerce/config/billing-schedules
>     2. Create a new billing schedule with the desired options
>         1. Fixed (specific day of month) or rolling (from creation date)
>         2. Dunning options to remind users for expiring credit cards
> 5. Create a product
>     1. Use the previously-created product type, with the recurring variation
>     2. Use the desired billing schedule

A possible solution would be to create a custom block that switches between the two products on the product page.

If you want to fetch data from the recurring product on the normal product, you might want to create a reference field to the recurring product on the normal product.

---
Tags: 8, commerce, payment-gateways
---


# Question
Title: How to limit the words in search api autocomplete suggestion?
I have a requirement to limit the words to show up in row of autocomplete suggestion. Now its showing titles but problem is titles are too long and suggestions are covering entire width of the screen. So any way to limit it? I checked with HOOK\_search\_api\_autocomplete\_suggestions\_alter hook but not getting what is the attribute to limit this feature. Any help will be appreciated.

# Answer
> 0 votes
Try below code, and you can trim $label as you want.

```
/**
 * Implements hook_search_api_autocomplete_suggestions_alter().
 */
function HOOK_search_api_autocomplete_suggestions_alter(array &$suggestions, array $alter_params) {
  $used_labels = [];
  /** @var Drupal\search_api_autocomplete\Suggestion\Suggestion[] $suggestions */
  foreach ($suggestions as $key => $suggestion) {
    $suggestion->setUrl(NULL);
    $label = $suggestion->getLabel();
    $suggestion->setSuggestedKeys($label);
  }
}

```

---
Tags: 8, search
---


# Question
Title: How can I add a link on the "Structure" admin page?
I created a view page with the path being `/abc` and I want to add this link on Administrative page with a link in Drupal 8.

# Answer
> 2 votes
You can go to /admin/structure/menu/manage/admin and add this link.

# Answer
> 2 votes
In a custom module, create a file called `mymodule.links.menu.yml`. Inside this file, add the following:

```
view.abc_links.page_1: #your view route
  title: 'ABC Link'
  route_name: view.abc_links.page_1 #your view route
  description: 'ABC Description'
mymodule.admin.structure.settings:
  title: 'API Link'
  description: 'ABC Description'
  route_name:  view.abc_links.page_1 #your view route
  parent: system.admin_structure

```

---
Tags: views, 8, navigation
---


# Question
Title: How we can get the value entered in search API autocomplete field in jQuery?
I got a requirement to send the search text to GTM for tracking purpose. I have a field which is from search api autocomplete module. I am not getting the value in jQuery on click of submit button. I tried like below but no success:

```
var search_key = $('.path-frontpage .ui-autocomplete-input').attr('value');

```

Can anybody implemented such thing. Please help

DOM:

```
<input placeholder="Search MyP&O" data-drupal-selector="edit-keywords" data-search-api-autocomplete-search="search" class="form-autocomplete form-text form-control ui-autocomplete-input" data-autocomplete-path="/search_api_autocomplete/search?display=page&&filter=keywords" type="text" id="edit-keywords" name="keywords" value="" size="30" maxlength="128" autocomplete="off">

```

# Answer
This works for me:

```
var search_key = $('.path-frontpage .ui-autocomplete-input').val();

```
> 0 votes

---
Tags: 8, javascript
---


# Question
Title: Syntax to use form_alter with array in name attribute
I would like to modify some custom fields with form\_alter in a contact form.

I know for example how to change `placeholder` for this "name" field : Note : I removed all the unnecessary html elements to make my question clearer

```
<input name="name" >

```

In `form_alter` :

```
$form['name']['#attributes']['placeholder'] = t('Nom');
$form['name']['#title_display'] = 'invisible';

```

But I don’t find the correct syntax when the name is with an array like :

```
<input name="field_prenom[0][value]" >

```

How to use `form_alter` with `field_prenom[0][value]` ?

I’ve tried this but it doesn’t work :

```
$form['field_prenom']['0']['value']['#attributes']['placeholder'] = t('Prénom');

```

# Answer
Why are you using field's attribute 'name' instead of it's machine name 'field\_prenom'? If you check in 'kint' you would get the hierarchy of 'placeholder' attribute.

You can update placeholder using `form_alter` only. Check the below example.

`$form['field_name']['widget'][0]['value']['#placeholder'] = 'Nom';`
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Simple Oauth oauth/debug?_format=json Internal Server error
When i try to test the ooauth/debug?\_format=json endpoint through Postman i get the internal server error and error code 403 forbidden. Even though i use a valid Authorization header with Bearer and the access token for a certain user. The endpoint works fine for anonymous user. So i guess it's a permission error or the token expires even though i've set a big expiration date for testing purposes. Has anyone encountered the same issue as me? If yes did you manage to solve it? I follow the tutorial step by step from the official simple\_oauth module page in drupal. Thanks in advance for reading this.

# Answer
> -2 votes
I fixed this issue by going to `admin/people/permissions` and selecting all of the Simple OAuth permissions for Authenticated User. I'm sure a more refined approach to selecting permissions will be possible, but initially selecting all of them has fixed this issue for me.

---
Tags: 8, authentication-authorization
---


# Question
Title: How to show one variation of one product in a View Pane
I have a View Pane on my home page where I list all products that are in promotion. Each product variation that can be set to "show in promo banner 1" via a taxonomy term field with checkboxes. So the store owner can now tick this checkbox to indicate that this product variation is in promotion. This works but only for product displays that have only 1 variation. When, for example, I only tick this checkbox for "product variation 4" of a particular product and no other variations, the first variation shows with a variation select widget and that's not what I want. So how can I only show that particular variation without the widget but with all the correct data and an add to cart button?

# Answer
> 1 votes
If what you're seeing is the fully rendered Add to Cart form in your View, then what you're looking to do is impossible without custom code. The Add to Cart form is rendered via the field display formatter on your product display node type. It has no way to interact with the configuration or results of a Views query.

You *can* create a View just showing variations with an Add to Cart button that doesn't invoke the entire form, but doing so will strip the creating line item of the context of what product display that variation is a part of. This means the line item won't link to the product page like it ordinarily would. You could always link it yourself if you know that each variation only exists on one node via a reverse reference, but you'd likely still lose some functionality related to the standard form's normal grouping of variations.

If that's an acceptable trade-off, then you need to recreate your View using Commerce Product entities as the base as opposed to Nodes. Otherwise you're going to have to create some custom Views plugins.

---
Tags: 7, commerce
---


# Question
Title: Get $form_state values from individual entity form fields
I have a weird use case. I created a custom form with some fields and I added some other fields from one entity form like this:

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $entity_fields = array('entity_field_1', 'entity_field_2');
    // added other form fields here
    $entityForm = \Drupal::service('entity.form_builder')->getForm($entity, 'default');
    foreach( $entity_fields as $key ) {
        $form[$key] = $entityForm[$key];
    }
    // etc
    return $form;
}

```

I need to get the exact entity field widget because these fields can be updated from the interface and I can't have them hard-coded.

Now, If I submit the form, the form state values for 'entity\_field\_1', 'entity\_field\_2' are empty. `$form_state->getValue('entity_field_1')` is returning an empty array. Other fields defined manually are returning the correct value when saving.

How do I get those entity field values? In drupal 7 I used field\_attach\_submit() to attach the form values to an entity.

# Answer
> 1 votes
You could also try `$form_state->getValues()['entity_field_1']` as `getValues()` will build an array of values with the field name as the key.

---
Tags: 8, forms
---


# Question
Title: How can I programmatically apply text formats?
I've created a custom text format I'm trying to apply to a field programmatically. As best I can tell, the format IS getting applied, but it is not stripping HTML tags like it is supposed to. The below screenshot shows how my text formatter is configured:

As you can see, its supposed to filter `<span>` tags. The Nodes where this will be used get created programmatically, and I apply the text formatter as follows:

```
'field_career_job_description1' => ['value' => $job['jobdesc'],'format' => 'careers_html_formatter']

```

This appears to be working correctly, if I print the variables passed to twig, I see that the formatter is, indeed, my custom format:

However, as you can see in the sshot, `<span>` tags are still in the text.

Note that I am displaying the field in question in Twig as follows:

`{{ content.field_career_job_description1[0]['#text'] | raw }}`

# Answer
> 0 votes
As I was pressing post on this question, I realized the problem. It's the twig code. In order to get the text formatter properly applied, I had to call my field as follows:

`{{ content.field_career_job_description1 }}`

Leaving this question up because I couldn't find anything like it on google

---
Tags: 8, input-formats
---


# Question
Title: Block with Listing of custom links to redirect to pages
With Drupal 8 I want to have a block with a select list that I get programmatically from taxonomy terms and when the user clicks on Submit it redirects the user to the page I put in the list. What is the best way to achieve this? Should I make a custom block with the code for the select inside or is there a module that does this I looked at jump menu but doesn't look like what I want.

# Answer
> 0 votes
I was able to use https://www.drupal.org/project/views\_jump\_menu to create a select list from my taxonomy terms, and put it in a views block.

---
Tags: 8, blocks
---


# Question
Title: Have followed instructions to disable cache for development but it's still caching
I have followed all the instructions here https://www.drupal.org/node/2598914

I'm developing a module with a block, and when I went to the Block Layout page and clicked "Place Block", the list of blocks did not come up due to an error in my code. I edited the code and was sure it was correct, yet it still didn't work. So I tried doing "drush cr" just in case the cache wasn't really disabled ... and that made it work.

So it seems to me that the cache has not been disabled by following those instructions. Is there something missing?

Edit: This has happened again when I have made new changes, even after the plugin has successfully loaded. It happens when when I make any changes to `src/Plugin/Derivative/Foo.php` (inside my module). Those changes aren't picked up until I manually cache rebuild

# Answer
You've disabled the `render`, `dynamic_page_cache`, and `page` cache bins; plugin discovery is stored in a different bin (`discovery`). You probably don't want to disable that bin, as it's likely to slow the site down appreciably (the project will be scanned for plugins on every request).

If you just keep in mind that you need to rebuild caches manually when you add a plugin, implement a hook, or add/change a .yml file in the module's root, you'll be able to work a lot faster.
> 4 votes

---
Tags: 8, blocks, caching
---


# Question
Title: Based on location How to change the banner image?
I am new to drupal 8 how to change banner image based on location. i created one content type in that two fileds i am added one is banner image and another one is location. while loading the page based on location how to change the banner

# Answer
Welcome to Drupal Answers (and Drupal)...

First, some assumptions... by location you mean the region that the user is coming to your site. E.g. some value from a module like Apache GEOIP or from a CloudFlare proxy front end.

Drupal uses a lot of caching for performance reasons. AFAIK, there is no built in regional caching mechanism that will show different content based on some regional id.

We had the same sort of problem in trying to display the local support and sales numbers based on region. Our solution was to have the numbers set via JavaScript.

The basic process was to have a URL that just returns the country code of the caller, e.g. /geoip/country. This can just be a bit of php that looks for the server's environment variable with the country code (e.g. `$_SERVER['GEOIP_COUNTRY_CODE']`) and returns this.

The Drupal JS makes an ajax call to get this, then uses it to determine the region and phone number to display. Basically, a select statement with regional country codes.

For performance reasons, we also put the country code into a cookie and test if this is set before doing the ajax call.

This method lets Drupal and it's other caching front ends work to minimize load time while giving a regional display.
> 1 votes

---
Tags: views
---


# Question
Title: Entity Validation API: Retrieve parent field entity while validating
I'm using the Drupal 8 Entity Validation API. I've implemented my `Constraint` and `ConstraintValidator` classes and added them as a constraint against the relevant entity field.

If I understand the `validate` method signature for `ConstraintValidator` correctly, I'm given a list of fields (`$items`) and the constraint (`$constraint`). However, I need to retrieve the parent entity in my logic.

How can I get the parent entity while with the validation API?

# Answer
By using FieldItemList::getEntity like in this core validator:

*Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator:*

```
class UniqueFieldValueValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    if (!$item = $items->first()) {
      return;
    }
    $field_name = $items->getFieldDefinition()->getName();
    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $items->getEntity();

```

The first argument of a validate method is of mixed type. For the Drupal Entity Validation API this can be a field value, a field item list or an entity, depending on where you add the constraint.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: JavaScript dependencies for a specific block or page
I am migrating a Drupal 7 site to Drupal 8. I have a custom block (visible only on the home page) that has some tabs on it. Currently, the tabs are implemented using jQuery UI tabs and it would be nice (but not necessary) to keep them using that.

In order to get this to work, I need to use the jQuery and jQuery UI JavaScript files. However, everything I have seen online talks about module and theme dependencies. There doesn't seem to be any way to tell Drupal 8 that a specific block (or page, etc.) needs specific JavaScript files loaded in order to work correctly.

I know that I can just import the javascript files directly with script tags, but that doesn't seem to be the preferred method, especially considering all of the various optimizations that are part of Drupal (to make sure that a file is only included once, for example).

**How do I include the required JavaScript files (available in core) on a specific page or as part of a specific block?**

I don't really want to create a custom module for every time that I need to do this, but all of the references I have found online talk about dependencies for themes or modules, nothing for specific content.

**EDIT: Multiple suggested answers involve PHP, custom modules, YML, etc. These are not what I am looking for. I am looking for a solution for front-end content creation (pages, nodes, blocks for the "custom block library", and so on), not requiring back-end coding and development. Modules on Drupal.org that allow this to be done generically are perfectly acceptable. Maybe I need to create one and put it up there, but I would think there should be an existing solution by now. It seems strange to me that there isn't, but maybe I'm missing something.**

# Answer
1. Define an asset library in `mymodule.libraries.yml`. An asset library can declare either CSS assets or JavaScript assets, or both. It can also declare dependencies on *other* asset libraries. For example on jQuery (`core/jquery`) or perhaps your JavaScript defines a "Drupal behavior", in which case you depend on the supporting infrastructure for that (`core/drupal`). Ex:

```
example_library:
  js: path/to/some/file.js: {}
  dependencies:
    - core/drupal
    - core/jquery

```
2. Use `#attached` in your block's render array to attach the asset library:

```
// Assuming the variable containing your render array is called $build.
$build['#attached']['library'][] = 'mymodule/example_library';

```

Extensive documentation can be found at https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module.
> 1 votes

# Answer
For a specific page or content type, do:

```
/**
 * Implements hook_page_attachments().
 */
function MYMODULE_page_attachments(array &$attachments) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node->getType() === 'book') { // You can also check on certain ID's here as well.
      // Current page is a Book node.
      $attachments['#attached']['library'][] = 'mymodule/custom';
    }
  }
}

```

In `mymodule.libraries.yml`:

```
custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```
> 1 votes

---
Tags: 8, javascript
---


title: Plugin Not Found Exception

text:
# Question
Title: Plugin Not Found Exception
I am implementing REST in Drupal 8. I have created a custom plugin for REST resource, enabled the plugin and configured permissions for that REST endpoint.

After few days, I removed the code for plugin without disabling the REST endpoint. I am encountering a plugin not found function for that REST endpoint.

Following this Drupal\Component\Plugin\Exception\PluginNotFoundException: The "glossify\_taxonomy" plugin does not exist., I made changes in the config and cache config table. Still I am encountering Plugin not found exception when I click on Permissions and Extend in Menu.

How can I remove this exception?

# Answer
Could you try these steps

1. drush cex -y actual configs.
2. Find in your config folder yml file rest.resource.{YOUR\_RESOURCE\_NAME} and delete it.
3. drush cim -y this change, it will be correctly removed from DB.
4. drush cr for sure, and error will miss.

Some related discussion going here https://www.drupal.org/project/restui/issues/2889860
> 0 votes

---
Tags: 8, plugins
---


# Question
Title: How to install and enable a default and admin theme in a Drupal 8 install profile with just YML (without using hook_install() or a .profile file)?
I want to avoid using `hook_install()` so I can install from configuration.

I'd like my install profile to use `seven` for the admin theme, and my custom theme `rutherford` for the default/main frontend theme.

The annotated `*.info.yml` example on Drupal.org suggests that putting the following will install my themes:

```
# List any themes that should be installed as part of the profile installation.
# Note that this will not set any theme as the default theme.
themes:
  - rutherford
  - seven

```

My understanding of CMI is that I can then create a file called `www/profiles/rocket/config/optional/system.theme.yml` and put this in it to enable my themes:

```
admin: seven
default: rutherford

```

However none of this seems to work? My themes are found, but not installed *or* enabled:

Edit:

I've just noticed that the themes are set as default and admin, they're just not installed:

# Answer
> 1 votes
Ah ♂. Trying to install my `rutherford` theme via the web UI gave a `The rutherford theme was not found.` error message, so it seemed the theme was at fault, not the profile.

I inspected my theme's info file and realised it had a dependency which was not being met. Commenting out the dependency got everything working again!

It's a shame that the `php www/core/scripts/drupal quick-start rocket` did not give me any errors about this unmet theme dependency, otherwise I would have saved about six hours of trying various different configuration approaches! Ah well, ce la Drupal!

---
Tags: configuration, installation-profiles
---


# Question
Title: Is there a way to create hierarchical taxonomies checkboxes?
I have an issue where I want to keep sub category inside a parent category. Say, for preferred vehicle I want a checkbox like this in node creation form

```
[]Car
  []Volkswagen
  []Toyota
[]Bike
  []Kawasaki
  []Harley Davidson

```

Is there a way to implement this using taxonomy?

# Answer
> 0 votes
Taxonomy is hierarchical by nature, you can create category/sub stuff in it.

AFAIK, there is not any field widget as you describe in drupal core with taxonomy field. Maybe some contrib module (have a look at term\_reference\_fancytree ).

You also may define your own and generate a field widget dedicated to taxonomy.

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


title: How can I load a File entity?

text:
# Question
Title: How can I load a File entity?
I want to find out whether a physical file is managed by Drupal and if it is, then load it.

I'm having trouble with the documentation which keeps displaying "File not found" at crucial moments, but it seemed that this ought to work:

```
$query = \Drupal::entityQuery('file');
$query->condition('uri', $file_uri);
$entity_ids = $query->execute();
if (count($entity_ids) == 1) {
    $file = \Drupal::entityLoad($entity_ids[0]);
}

```

However, I get this message:

```
PHP Fatal error:  Call to undefined method Drupal::entityLoad()

```

# Answer
There is no such method as \Drupal::entityLoad(). Use the static method on the entity type. Assuming "File", you should use:

```
$file = \Drupal\file\Entity\File::load(reset($entity_ids));

```

Berdir pointed out in a comment that QueryInterface::execute() returns an array keyed by entity ID or revision ID so reset() is the thing to use to get the first element.
> 11 votes

# Answer
To load the entity by ID you can use the following code:

```
/** @var \Drupal\file\FileInterface|null $file*/
$file = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->load($entityId);

```

But if you need to load the file entity by the given file URI there is a method called `loadByProperties` in `EntityStorageInterface`:

```
/** @var \Drupal\file\FileInterface[] $files*/
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadByProperties(['uri' => $uri]);
if (!empty($files)) {
  $file = reset($files);
}

```

See Load a file entity by URI
> 4 votes

---
Tags: 8, entities, files
---


# Question
Title: DrupalSettings are not passing the values from block to js?
I have been trying to pass the variables from block to jquery.

In Block.php,

```
return [
      '#theme' => 'block--exampleblock',
      '#value' => 'test',
      '#attached' => [
        'drupalSettings' => [
          'example' => [
            'data' => $data,
            'color'=> $color,
          ],
        ],
        'library' => [
          'example/examplejs',
        ],
      ],
    ];

```

and I used the data and color values in js

```
drupalSettings.example.data;
drupalSettings.example.color;

```

and belows are added the dependency in the library

```
dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

```

After uninstalled and installed the modules, The variables have been passing from block to js.

But After clearing cache or sometimes Its not working.

Its showing an issue like

```
Uncaught TypeError: Cannot read property 'data' of undefined
    at Object.attach (charts.js?v=1.x:10)
    at drupal.js?v=8.6.16:25
    at Array.forEach (<anonymous>)
    at Object.Drupal.attachBehaviors (drupal.js?v=8.6.16:22)
    at drupal.init.js?v=8.6.16:16
    at HTMLDocument.t (ready.min.js?v=1.0.8:4)

```

I am not able to fix this issue.

Can anyone help to solve this?

# Answer
99 % sure it is the way your js file is set. as the above should work. for a test please do this:

```
(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.testStuff = {
    attach: function (context) {
        alert('yes i am attached');
        console.log(drupalSettings);
        if (drupalSettings.example) {
           console.log(drupalSettings.example);
        }
    }
  };
})(jQuery, Drupal, drupalSettings);

```

if you don't see that in the log then try this ...

```
$build = [];
$build['stuff'] = [
  '#theme' => 'block--exampleblock',
  '#value' => 'test',
];
$build['#attached']['drupalSettings']['example'] =  [
        'data' => $data,
        'color'=> $color,
];
$build['#attached']['library'][] = 'example/examplejs';
return $build;

```

remember to clear your cache too.
> 2 votes

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


# Question
Title: How do I add default header and footer regions to my site?
i have added regions in my theme.info file. now i want to add default header and footer with logo in all the pages of my site.This is my **page.html.twig**

```
<div class="layout-container">

  <header role="banner">
    {{ page.header }}
  </header>

  {{ page.primary_menu }}
  {{ page.secondary_menu }}

  {{ page.breadcrumb }}

  {{ page.highlighted }}

  {{ page.help }}

  <main role="main">
    <a id="main-content" tabindex="-1"></a>{# link is in html.html.twig #}

    <div class="layout-content">
      {{ page.content }}
    </div>{# /.layout-content #}

    {% if page.sidebar_first %}
      <aside class="layout-sidebar-first" role="complementary">
        {{ page.sidebar_first }}
      </aside>
    {% endif %}

    {% if page.sidebar_second %}
      <aside class="layout-sidebar-second" role="complementary">
        {{ page.sidebar_second }}
      </aside>
    {% endif %}

  </main>

  {% if page.footer %}
    <footer role="contentinfo">
      {{ page.footer }}
    </footer>
  {% endif %}

</div>{# /.layout-container #}

```

I have placed files **region--header.html.twig** and **region--footer.html.twig** .Please help me how to place logos and other contents in header and footer

# Answer
You define a region in your theme's info file and then print it in your `page.html.twig`. Content to each region is added via blocks. You only add your own region templates when you need to make some changes to the markup.

---

OK, so you added the regions in your info file, and printed them in your page template, fine. First of all, delete your `region--header.html.twig` and `region--footer.html.twig` again. Then in the backend of your site go to Structure \> Blocks. Your newly added regions should appear there. Now place some blocks in your newly added regions. Save, flush cache and visit your frontend again. Your regions should be populated now.

And regarding the `region--YOURREGION.html.twig` templates you should have deleted by now, these only will be picked up when these regions are populated – with blocks. Otherwise these regions simply won't get printed at all.
> 1 votes

---
Tags: 8, theming
---


title: How can I delete a file in a cron job?

text:
# Question
Title: How can I delete a file in a cron job?
A custom module is creating a file in `public://` folder, that should reside there only temporary. How can I delete this temporary file in a cron job?

# Answer
Also in drupal, we can delete a file on a cron job via setting the file status=0.

After 6 hours the cron job will delete the files whose status is zero.

```
     $filename = "myfile.pdf";
     $tmp_file = file_save_data('', 'public://' . $filename);
     $tmp_file->status = 0; // will automatically delete
     $tmp_file->save();

```
> 0 votes

# Answer
Write a function in a custom module:

```
/**
* Implements hook_cron().
*/
mymodule_cron() {
  // Get the file id somehow, make this more generic, perhaps use file_scan_directory()?
  $uri = 'public://temporary/myfile.pdf';
  $files = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => $uri]);
  if (count($files)) {
    foreach ($files as $item) {
      file_delete($item->id());
    }
  }
}

```
> 2 votes

---
Tags: cron
---


# Question
Title: In Views, display additional fields from an entity reference
I have a content type with a field that is an entity reference to another content type called "URLs", and the "*Allowed number of values*" is set to "*Unlimited*", meaning that one record can have multiple URLs associated to it.

When I come to the View for this node, I have added a Field for "URLs", and under "**MULTIPLE FIELD SETTINGS**" I have ticked "*Display all values in the same row*", and **Display type**: *Unordered list*.

This works well, and I get the the list of associated URLs in an unordered list, like so:

* www.domain1.com
* www.domain2.com
* www.domain3.com

Where it gets complicated, my "URLs" content type has another field called "field\_url\_type", which is a field type "**List (text)**". This contains the *type of URL*, (eg. Production, Development, Staging, Decommissioned, etc).

In the main content type display View, I would like to display this additional field from the URL content type next to the URL values, like so:

* www.domain1.com (Production)
* www.domain2.com (Development)
* www.domain3.com (Decommissioned)

I tried using the Views \> Configure Field \> REWRITE RESULTS panel to include the REPLACEMENT PATTERNS for both fields, like so:

```
{{ field_url }} ({{ field_url_type }})

```

... but this didn't work. I'm guessing it is more complicated than that!

Does anyone know how I can display this additional field from a content type referenced by an entity reference field in a node view?

# Answer
> 0 votes
Many solutions for this but to pick one :)

* Download and enable Display Suite https://www.drupal.org/project/ds
* Go to *admin/structure/ds/fields* and a token field (see screenshot #2 for values, adjust according to your field names)
* Go to view mode of your Url content type and create a seperate view mode, e.g. called **entity\_reference\_url\_view** or something (I just picked **teaser** for this example) . Make sure to select One column layout so Display suite will make your custom token field available to you (see screenshot #1)
* add the custom token field you added earlier to the visible section
* Now go to your other content type view at e.g. *admin/structure/types/manage/your\_content\_type/display/full* and select **Rendered Entity** as the *format* and choose your previously created view mode of the URL content type (see screenshot #3
* Now view your content type and the entity reference fields should show up in the format you defined in your custom Display suite field

Screenshot #1

Screenshot #2

Screenshot #3

---
Tags: views, 8, nodes
---


# Question
Title: Cannot move block Main Page Content to different region
Realy need your help. I'm working with quite old Drupal 7 site and for some reason I cannot move the Main Page Content block to any different region. When I drag&drop it to the Header region (on block management page) and then click save, looks like it sucessfully moved, but when I go to the actual page I can see that it still located in the Content region.

Looks like something is preventing Main Page Content block from moving to different region but I don't know exactly what. I've updated Drupal to the latest release - no difference. I've switched to another theme - no luck.

What might be the problem? I'd be very gratefull for any idea.

# Answer
> 1 votes
Something similar happened to me. The problem was that the main content block was configured to show on "all pages except those listed" and the one listed was front. When I removed front, I was able to move the block, or rather my changes showed up on the front page too.

---
Tags: 7, blocks
---


# Question
Title: Can we display region label from Layouts?
We have a MYTHEME.layouts.yml file which defines regions...

```
layout
  label: 'Layout Name'
  path: templates/panels
  template: layout-template
  default_region: theregion
  regions:
    theregion:
      label: 'This is The Region'

```

In the template we display fields added to the region with

```
{{ content.theregion }}

```

Can we display the label that we defined?

# Answer
The labels are for administration purposes and should not be used in templates as they are hard coded and can't be changed in the UI. A better option would likely be to use a Text field where you want to display the label as that can easily be changed.

That said, you can output the region name in the twig template like this:

```
{{ layout.regions.theregion.label }}

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Where 'target_id' of field_data_field... tables points?
I'm extracting database information from a Drupal site that I have using SQL queries. I have seen that, in the field\_data\_field... tables can be three type of information storage:

* **field...value:** stores the value of the field directly.
* **field...val\_tid:** stores the id number of taxonomy\_term\_data value.
* **field...val\_target\_id:** stores an integer id.

I'm interested in the third field, my question is: where is this field value pointing?

# Answer
If you look in the field\_data\_field\_{field\_name} table, you will see these columns:

* entity\_type: tells which type of object the target is.
* entity\_id: which one in the entity table

For entityforms, you can go to the URL /admin/structure/entityform\_types/manage/{entity\_type}/fields, and you can see what the {field\_name} refers to by finding {name} in the list.

So if you know what type of object it is, hopefully you know how to find the list of fields.

If not, go to /admin/reports/fields and search the full list for your field.
> 0 votes

---
Tags: entities, database
---


# Question
Title: How to display a field of the parent store in my module?
I have a Drupal 8.7 site with the Drupal Commerce 2.14 module.

I created a marketplace (several merchants on the same site). In the store type, I created a "Text (formatted, long)" field with the machine name `field_terms_and_conditions`.

In this field, the merchant writes his general conditions of sale, which the customer will have to accept during the order process.

When the customer orders in several stores, this will create several shopping carts (the name of the store is displayed above each shopping cart). It works very well. Now that Drupal Commerce is handling the address book, the orders are very fast.

Currently I have created a view that displays the contents of the field `field_terms_and_conditions` on a page. I also created a custom module to display a checkbox with a link to the general conditions of sale in a modal window.

I want to directly render the field `field_terms_and_conditions` in the modal window without using a view. How to do this ?

`/src/Plugin/Commerce/CheckoutPane/MarketplaceTermsAndConditions.php` :

```
<?php

namespace Drupal\commerce_marketplace_terms_and_conditions\Plugin\Commerce\CheckoutPane;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "marketplace_terms_and_conditions",
 *   label = @Translation("Marketplace Terms and Conditions"),
 *   default_step = "review",
 * )
 */
class MarketplaceTermsAndConditions extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $store_name = $this->order->getStore()->getName();
    $store_id = $this->order->getStoreId();
    $pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $attributes = [
      'attributes' => [
        'class' => 'use-ajax',
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => 'auto'
        ]),
      ],
    ];
    $link = Link::fromTextAndUrl(
      $this->t('terms and conditions of the store "@store_name"', ['@store_name' => $store_name]),
      Url::fromUri("internal:/store/$store_id/cgv", $attributes)
    )->toString();
    $pane_form['marketplace_terms_and_conditions'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept @terms.', ['@terms' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

}

```

# Answer
Sounds fun, Here is an option to do this.

1) make a controller : routingfile:

```
my_module.store_terms:
  path: '/store-terms/{store_id}'
  defaults:
    _controller: '\Drupal\my_module\Controller\StoreTermsController::showTerms'
    _title: 'Terms'
  requirements:
    _permission: 'access content'

```

In the controller:

use Drupal\Core\Ajax\AjaxResponse;

use Drupal\Core\Ajax\OpenModalDialogCommand;

```
public function showTerms($store_id) {
  $store = \Drupal::entityTypeManager()->getStorage('commerce_store')->load($store_id);

  $terms = $store->field_terms_and_condition->value;

  $render_array = [
    '#markup' => $terms
  ];
  $response = new AjaxResponse();
  // Show a dialog box.
  $dialogText = $render_array;
  $dialogText['#attached']['library'][] = 'core/drupal.dialog.ajax';
  $response->addCommand(new OpenModalDialogCommand('Terms and Conditions',
   $dialogText, ['width' => '500']));
  return $response;
}

```

then back in your buildPaneForm method:

```
$attributes = [
  'attributes' => [
    'class' => 'use-ajax',
    ],
];
$link = Link::fromTextAndUrl(
  t('terms and conditions of the store "@store_name"', ['@store_name' =>
   $store_name]),
  Url::fromUri("internal:/store-terms/".$store_id , $attributes)
  )->toString();

```
> 0 votes

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


# Question
Title: How to display content for a Taxonomy Vocabulary?
I am using Drupal 8.

I have a Vocabulary called Fruit which contains terms:

Apple Banana Orange

I can go to page for term Apple and I can find all the content which was tagged with apple there. I want to create a page with all content tagged under Fruit as well. Is there a way to achieve this?

# Answer
> 0 votes
You need to look at creating views you can start by watching as many as the following to get the idea:

https://www.google.com/search?q=drupal+8+how+to+create+a+view&source=lnms&tbm=vid

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


# Question
Title: Where do I put configuration files for testing?
Hopefully, this will be a simple question.

I am writing a kernel test for a class, called FooConfig, that reads from a configuration file. For the purpose of facilitating this test, I need a configuration YAML file that exists purely for testing.

So the question is: is it best practice for this configuration file to live under `config/install`, or should it exist within the `/tests` directory?

# Answer
> 2 votes
One way is to create a small testing module that contains specific config you need for a test, then have the test use it as a dependency. In my case, I put that module itself under the tests directory and marked it as hidden in its info file.

Although a drawback would be keeping these config files up to date when the system changes - but failing tests should point you in that direction too.

For Kernel tests be sure to call and install the test modules config.

---
Tags: 8, configuration, testing
---


# Question
Title: Purchases with points occupying ubercart
I want to use ubercart to create a site for online purchases but I would like to know if you can use points as a form of payment, I mean that users are placed points with which they can buy items and their points are discounted for each purchase.

# Answer
Yes you can use userpoints and userpoints ubercart. I did this in the past using drupal7. If you want to use drupal8, you need to check if the modules have been converted.

* users can be allocated points by the admin person. the alternative is you have a product for purchasing points.
* on checkout, points is presented as a payment option.
* users can see their points balance and orders via their account page.

Another alternative is to use commerce\_userpoints with its dependent modules (commerce, userpoints). But I believe this approach has a few outstanding bugs on the issues queue.
> 0 votes

---
Tags: commerce, ubercart, payment-gateways
---


# Question
Title: How can I hide a field in the node add form but it unhide it on the node edit form?
I'm having a content type in that I want a field "Status" to be hidden in add content form page(I'm setting default value in that add content). Now I want that field to appear in edit form page of that node and user can able to edit it. I'm new to Drupal, so I don't know how to do this.

# Answer
> 1 votes
You can Show/Hide the status field using `hook_form_alter` like this:

```
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];

  if (!isset($node->nid) || isset($node->is_new)) {
    $form['YOUR_FIELD']['#access'] = FALSE; // Node is new!
  }
  else {
    $form['YOUR_FIELD']['#access'] = TRUE; // Node is not new!
  }
}

```

Then replace `YOUR_FIELD` with the field name of your status field.

---
Tags: 7, forms
---


# Question
Title: How do I pass the UID in URL to embedded View?
Probably a stupid question, but I'm stumped... I have a simple View which lists all terms from a Taxonomy. Within this is a Global Field Type of "View" which is trying to list any content related to the Term, and authored by the UID present in the URL. However I am unable to pass the parameter from the URL to the View using standard Replacement Patterns. I can pass the Term using \[!name\] but not a parameter from the URL.

So parent view URL is /report

This is called with the UID appeded, e.g.: /report/34

How do I get 34 passed to the embedded view as contextual filter?

Many thanks for any help on this seemingly simple use case!

\****** ANSWERED \********

Check Alfred's answer below, but also make sure the order of your Contextual Filters is correct. In this case, I was passing a blank value, rather than NULL value, as the first parameter from the parent view.

Swapping the order of the Contextual Filters over mean't I could pass a NULL value from the parent view (i.e. just the first one). Hope this makes sense.

# Answer
In an embedded view you typically use the "When the filter value is not available" option for the contextual filter to achieve this.

Select "provide default value" then choose "raw value from URL" and set the path component to be 1.

You should also set validation criteria and select what should happen when the value is missing or incorrect.
> 2 votes

---
Tags: views
---


# Question
Title: Enable admin theme in my install profile
Is it possible to enable an admin theme in my install profile?

Used this:

```
// Enable themes
  $enable = array(
    'theme_default' => 'geoslate',
    'admin_theme' => 'adminimal_theme',
  );
  theme_enable($enable);

  foreach ($enable as $var => $theme) {
    if (!is_numeric($var)) {
      variable_set($var, $theme);
    }
  }

```

# Answer
> 1 votes
Yes, you just need to set the relevant variable (`admin_theme`), e.g.

```
variable_set('admin_theme', 'seven');

```

# Answer
> 0 votes
For Drupal 8 you can add this to your `my_custom_profile.install` file:

```
<?php

  function my_custom_profile_install() {
    // Set 'Seven' as the default administration theme
    \Drupal::configFactory()
      ->getEditable('system.theme')
      ->set('admin', 'seven')
      ->save();

```

---
Tags: users, installation
---


# Question
Title: How do I make rows of views blocks on a basic page reacting collectively to an exposed filter?
I have to make a page, containing 3 rows with 3 blocks with content teasers. Preferably the page layout should be made through a basic page content type item, through the Layout Builder, so it is easy to add other stuff.

At the top of the page should come a view's exposed filter for the teasers. So, the teasers that are shown must be filtered for some selected content types plus for some taxonomy terms. I've been able to make that filter on a normal view page. Also I accomplished to get the filter in a separate block. But, because of the fact that both a basic page and a view page need a url, I couldn't accomplish this idea.

Is it possible to make a basic page with separate rows of view blocks via the Layout Builder, reacting collectively to an exposed views filter?

# Answer
> 0 votes
Views Attachments Displays have the option to inherit the exposed and contextual filters from the Views displays they're attached to. So you can try to create one Views Page Display with some of your results, then create as many Attachment Displays (not Block Displays) as you need and attach them to the Page Display.

I haven't tried the Layout Builder with different Views displays like that, but I think it may work to rearrange them a bit.

I think you could also have Views Blocks (that are on the same Views) share the same Exposed filter settings (don't override them), and use the `Exposed filter in a block` option where you place the exposed filter part of Views as a block in a theme region instead of always appearing it automatically above the Views results.

You may also want to check out the Views Global Filter module that affects all Views exposed filters once a user chooses one option.

---
Tags: 8, views, layout-builder
---


# Question
Title: Is accessing the current node from multiple block plugins on a single page costly from a performance perspective?
I use a combination of Block plugins and panels to populate the layouts of the display modes of various content types.

Here's an example:

```
class MyBlockPlugin extends BlockBase
{
    /**
     * {@inheritdoc}
     */

    public function build()
    {
        $node = \Drupal::routeMatch()->getParameter('node');
        $profile_pic = ImageStyle::load('350x300')->buildUrl($node->field_image->entity->getFileUri());
        return [
            '#theme' => 'mytwigtheme',
            '#name' => $node->title->value,
            '#headshot' => $profile_pic
        ];
    }
}

```

It certainly works but I'm wondering if this is a bad path to travel because I'll have multiple block plugins loading and accessing the same node. I suppose I could access the node with a preprocess block hook but I'm assuming that will load for every block as well.

If the performance cost is trivial then I'm not too worried about redundancy. Is my method okay? If not, what would be a better way for a block plugin to access the data of the current node it appears on?

Update: Just another thought. Is me using a twig template making this a non issue as long as it's been loaded before?

# Answer
> 2 votes
No performance issue concerning the node entity, which is loaded only once per request and then stored in memory.

For caching between requests there are also no performance issues, because the rendered twig template(s) of a block are cached by default. But you have to make sure you provide the correct cache data, which is possible via a plugin context in the annotations (preferred) or by adding the cache metadata to the render array. See Block cache depending on current node and its last modification time

---
Tags: 8, blocks, hooks
---


# Question
Title: How can I repeat parent table field only once for a group of child table fields?
I am using Drupal Views module. I have Student accounts table that can have multiple students in it. Is there a way to create a table like the following?

```
╔════╦═════════════╦═════════════╦═══════╦═════╗
║ id ║ Title       ║ Student Name║ Gender║ age ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 1  ║ Acount 1    ║ Jack        ║ Male  ║ 50  ║
║    ║             ╠═════════════╬═══════╬═════╣
║    ║             ║ Smith       ║ Male  ║ 33  ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 2  ║ Acount 2    ║ Ellis       ║Female ║ 42  ║
║    ║             ╠═════════════╬═══════╬═════╣
║    ║             ║ Joe         ║ Male  ║ 43  ║
╚════╩═════════════╩═════════════╩═══════╩═════╝

```

My current table shows the data like this:

```
╔════╦═════════════╦═════════════╦═══════╦═════╗
║ id ║ Title       ║ Student Name║ Gender║ age ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 1  ║ Acount 1    ║ Jack        ║ Male  ║ 50  ║
║════║═════════════╠═════════════╬═══════╬═════╣
║ 1  ║ Acount 1    ║ Smith       ║ Male  ║ 33  ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 2  ║ Acount 2    ║ Ellis       ║Female ║ 42  ║
║════║═════════════╠═════════════╬═══════╬═════╣
║ 2  ║ Acount 2    ║ Joe         ║ Male  ║ 43  ║
╚════╩═════════════╩═════════════╩═══════╩═════╝

```

I want to avoid the repeat of of id and title columns. Any idea how to do this?

This is the setting for my view:

# Answer
The only way I can think of doing this without custom coding is by using the Views Field View where you create two different Views Displays, one with the contextual filter, save them both, then "embed" the contextual one into the other view.

This type of database query can be very performance intense, and caching is recommended. Or avoid it if you can.

In your case you can keep your original accounts view, but remove the student fields. Add another Display (Block) that is showing student name gender and age, and add a contextual filter for the account, save the view. Then in your original views display add the field for the student info.

You may need to adjust how the labels are shown, so you don't have them duplicate/in odd places because of the recursion.
> 0 votes

---
Tags: views
---


# Question
Title: Rewrite results output creates 2 links for one for one rewritten custom text field
I am using replacement patterns to rewrite the results of my content title field with the manufacturers name in front of the title. I am using the following custom text within the title field to accomplish this:

```
{{ field_tool_manufacturer }}<br>{{ title }}

```

I am then outputting this field as a custom link, with the path `Node/{{ nid }}`

Both the manufacturer and title fields render linked to the node correctly, but the problem is that they should be a single rewritten text link, but it's being output as 2 separate links. One link for the manufacturer, and a separate one for the title. This of course isn't optimal for UX as it communicates 2 separate links especially with css hover styling, etc.

The results are the same when removing the `<br>` line break. The manufacturer field is excluded from the display, and it is not set to be output as a link in the original field. I have tried multiple style settings with no better luck.

I did this with very little trouble in Drupal 7, so I am wondering if this is a bug that I should create an issue for, or if there is a structural change that is causing the 2 links. I'm new to Drupal 8, so I might be missing something simple. Any help would be appreciated, and let me know if I left out any useful info.

Thanks!

# Answer
> 1 votes
When rewriting a field into a custom link you have to make sure that the tokens used for the link *text* aren't formatted as links, because links can't be nested one into the other.

Edit the field settings for the fields corresponding to `{{ field_tool_manufacturer }}` and `{{ title }}` and make sure their `Formatter` option is set to Plain text, or that the option to "link this field to content" is ***not*** checked.

Most field settings will be applied to the token in the Rewrite field option, so you have to control the output yourself.

You can test what the field output is by simply viewing the field without any Rewrite options, and if you see the field output as plain text, and not a link, you can proceed to set up the Rewrite options.

---
Tags: views, 8
---


# Question
Title: How to show snippet of an event when clicked in the calendar in Drupal 7 with the Calendar Module
I created a calendar with the Calendar Module, but I don't know what to do to show a snippet of the event when clicked. This calender is a perfect example of what I mean https://hutchinscenter.fas.harvard.edu/calendar. Thanks!

# Answer
There are probably many different ways of doing it.

One possibility is the Calendar Tooltips module.

Another is using Colorbox module to control the popup, you construct the Views output yourself so that the Colorbox library displays it as a popup: Does Calendar Popup Module exist in D7?, using-colorbox-display-event-details-popup
> 0 votes

---
Tags: views
---


# Question
Title: Changing the html and order of system fields(pass/email/locale/etc) of user edit form
I have changed a number of forms accessible by users to fit a certain style. To do this I used an #after\_build function that adds prefixes and suffixes to fields, as well as a bit of javascript. This was straightforward enough(and I hope the appropriate way to do that, though I'm not sure).

However, coming upon the user edit form, it does not behave as other forms do. The default system fields such as password, locale, email, etc, cannot be reordered and I can't seem to add prefixes or suffixes to them to insert my HTML.

I have read some things about using a template for forms via hook\_theme() function, however I could not get Drupal to use my template file for the user profile edit form, though it works just fine for other forms. This was a last resort, however, and I prefer other means if possible.

How do I correctly alter the layout and html of the user profile edit form? Thank you for your time.

# Answer
The reason the template method was not working on my site was the result of a caching issue.

To use a template file for the user profile form you can put this(or find the existing implementations of the hooks) in your template.php:

```
function yourtheme_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'user_profile_form';
}

function yourtheme_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'form',
      'template' => 'templates/form--user_profile',
    ),
  );
}

```

Template file name, in this example, becomes form--user\_profile.tpl.php
> 0 votes

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


# Question
Title: Custom line items to be included in $order->getTotal()
I am using Ubercart for our e-commerce on Drupal 8 website. Everything seems to be working fine except for the `$order->getTotal()` function - it does not somehow pickup the amount from my custom line items (for eg. 'shipping and handling') that I have added to the order.

It only seems to be going over the default 3 line items (subtotal, total, generic) that are provided by the `uc_order` module.

How can I achieve that? Thank you in advance.

# Answer
I was able to achieve this by adding type as 'generic' for all my custom line items. Sample code:

uc\_order\_line\_item\_add($order-\>id(), 'generic', 'Promotion', -100, 6, NULL);
> 0 votes

---
Tags: 8, ubercart
---


# Question
Title: How do I move a https site to localhost?
I am moving a site from the live server where it has an SSL certificate and is accessed by HTTPS to my localhost. After moving the site over, I get an ERR\_SSL\_PROTOCOL\_ERROR.

I am uncertain of how to fix the issue. I tried turning off Clean URLs before the move. And I also tried changing the .htaccess file.

# Answer
As Kevin suggested in the comments, I did not have a local certificate installed. Using MAMP, I ended up following the instructions here to solve the issue.
> 0 votes

---
Tags: 7, ssl
---


# Question
Title: How to programatically change a view's style_options when user clicking the exposed filter apply button?
In a Leaflet Map view, the exposed filter is a list(text) field. On user clicking the Apply button of the exposed filter form, I need to programatically change the value of $handler-\>display-\>display\_options\['style\_options'\]\['map'\], I mean to change the Leaflet map style (which is defined in the module leaflet\_more\_maps).

How to make it?

# Answer
The hook\_views\_pre\_render() works.

```
function my_misc_views_pre_render(&$view) {
  if($view->name == 'classrooms_map') {
    $view->style_plugin->options['map'] = ($view->exposed_data['type'] == 'All') ? 'all' : $view->exposed_data['type'];
  }
}

```
> 0 votes

---
Tags: views
---


# Question
Title: How to change a view field programatically
I want to change the result of a view field in a custom module.I’m not sure which of the hooks to use for this there are not a lot of examples of how to use the views hooks for d8

# Answer
> -4 votes
You can user the Views PHP module

You add your php logic to the field and manipulate the view field results as you wish.

If you really need to use a hook in your custom module you can use the

`custom_module_views_pre_view($view, $display_id, array &$args)` hook

---
Tags: views
---


# Question
Title: How do I perform outstanding entity updates after 8.7?
I have just tested the update to 8.7.1 (from 8.6.x) which includes the removal of the old automatic entity update functionality, which means `drush entup` no longer works. As far as I understand the change record, developers now need to perform the updates inside update hooks. However, after updating the core with composer and performing the database update (which ran without any errors), I get a warning in the status report:

> The following changes were detected in the entity type and field definitions.
> taxonomy\_term entity type :
> The Moderation state field needs to be installed.

But without the drush `entity-update`, I have no idea what I'm supposed to do here. How do I perform the update? Drush `dbup` ran successfully (and now reports no outstanding updates), which drush `entup` doesn't work anymore. How can I handle this error?

For the record, this is the output of the first drush updb, not sure if it's relevant:

```
server:~/httpdocs$ drush updb
 ------------------- ----------------------------------------------- --------------- -----------------------------------------------------------------------------
  Module              Update ID                                       Type            Description
 ------------------- ----------------------------------------------- --------------- -----------------------------------------------------------------------------
  system              8701                                            hook_update_n   Remove the unused 'system.theme.data' from state.
  system              8702                                            hook_update_n   Add the 'revision_translation_affected' entity key.
  file                8700                                            hook_update_n   Set the 'owner' entity key and update the field.
  node                8700                                            hook_update_n   Set the 'owner' entity key and update the field.
  taxonomy            8701                                            hook_update_n   Add an index on the 'taxonomy_term__parent' field table.
  menu_link_content   make_menu_link_content_revisionable             post-update     Update custom menu links to be revisionable.
  system              add_expand_all_items_key_in_system_menu_block   post-update     Initialize 'expand_all_items' values to system_menu_block.
  system              clear_menu_cache                                post-update     Clear the menu cache.   @see https:www.drupal.orgprojectdrupalissues3044364
  system              fix_jquery_extend                               post-update     Clear the library cache and ensure aggregate files are regenerated.
  taxonomy            make_taxonomy_term_revisionable                 post-update     Update taxonomy terms to be revisionable.
  taxonomy            remove_hierarchy_from_vocabularies              post-update     Remove the 'hierarchy' property from vocabularies.
  views               exposed_filter_blocks_label_display             post-update     Update exposed filter blocks label display to be disabled.
  views               make_placeholders_translatable                  post-update     Rebuild cache to allow placeholder texts to be translatable.
 ------------------- ----------------------------------------------- --------------- -----------------------------------------------------------------------------

 Do you wish to run the specified pending updates? (yes/no) [yes]:
 > yes

 [notice] Update started: system_update_8701
 [ok] Update completed: system_update_8701
 [notice] Update started: system_update_8702
 [ok] Update completed: system_update_8702
 [notice] Update started: file_update_8700
 [ok] Update completed: file_update_8700
 [notice] Update started: node_update_8700
 [ok] Update completed: node_update_8700
 [notice] Update started: taxonomy_update_8701
 [ok] Update completed: taxonomy_update_8701
 [notice] Update started: menu_link_content_post_update_make_menu_link_content_revisionable
 [notice] Custom menu links have been converted to be revisionable.
 [ok] Update completed: menu_link_content_post_update_make_menu_link_content_revisionable
 [notice] Update started: system_post_update_add_expand_all_items_key_in_system_menu_block
 [ok] Update completed: system_post_update_add_expand_all_items_key_in_system_menu_block
 [notice] Update started: system_post_update_add_expand_all_items_key_in_system_menu_block
 [ok] Update completed: system_post_update_add_expand_all_items_key_in_system_menu_block
 [notice] Update started: system_post_update_clear_menu_cache
 [ok] Update completed: system_post_update_clear_menu_cache
 [notice] Update started: system_post_update_fix_jquery_extend
 [ok] Update completed: system_post_update_fix_jquery_extend
 [notice] Update started: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Taxonomy terms have been converted to be revisionable.
 [ok] Update completed: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Update started: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Taxonomy terms have been converted to be revisionable.
 [ok] Update completed: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Update started: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Taxonomy terms have been converted to be revisionable.
 [ok] Update completed: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Update started: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Taxonomy terms have been converted to be revisionable.
 [ok] Update completed: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Update started: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Taxonomy terms have been converted to be revisionable.
 [ok] Update completed: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Update started: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Taxonomy terms have been converted to be revisionable.
 [ok] Update completed: taxonomy_post_update_make_taxonomy_term_revisionable
 [notice] Update started: taxonomy_post_update_remove_hierarchy_from_vocabularies
 [ok] Update completed: taxonomy_post_update_remove_hierarchy_from_vocabularies
 [notice] Update started: views_post_update_exposed_filter_blocks_label_display
 [ok] Update completed: views_post_update_exposed_filter_blocks_label_display
 [notice] Update started: views_post_update_exposed_filter_blocks_label_display
 [ok] Update completed: views_post_update_exposed_filter_blocks_label_display
 [notice] Update started: views_post_update_make_placeholders_translatable
 [ok] Update completed: views_post_update_make_placeholders_translatable
 [success] Finished performing updates.

```

# Answer
> 3 votes
One option is to use the new Devel Entity Updates module, which was built for this exact purpose:

> In #2976035: Entity type CRUD operations must use the last installed entity type and field storage definitions the ability to run drush entup was removed, see the related change record for more details. This project aims to restore this functionality as a developer-only tool. This module depends on Devel and is not meant to be enabled in production environments or relied upon in deployment workflows.

# Answer
> 3 votes
Put it in an update hook again. Put it in the your\_module\_name.install file. (Make sure it existed already in the module when installed, otherwise put it in an other modules install file)

```
/**
 * Update- Create your_entity_name entity.
 */
function your_module_name_update_8002() {
  //check if the table exists first.  If not, then create the entity.
  if(!db_table_exists('your_entity_name')) {
    \Drupal::entityTypeManager()->clearCachedDefinitions();
    \Drupal::entityDefinitionUpdateManager()
      ->installEntityType(\Drupal::entityTypeManager()->getDefinition('your_entity_name'));
  }
  else {
    return 'your_entity_name entity already exists';
  }
}

```

# Answer
> 0 votes
As pointed out by @MoritzLost, relying on `drush entup` is a workaround. The proper solution would be to rely on the WBM patch or wait for it to be released before updating to 8.7. More details available at https://www.drupal.org/project/devel\_entity\_updates/issues/3082442.

---
Tags: entities, database, drush
---


# Question
Title: Creating a Paragraph type programmatically
I have a custom module that is installed on a number of sites. In an hook\_update\_n function I would like to add a completely new *Paragraph type* (not actual instance of a Paragraph) to every site, using the same configuration.

Adding or updating fields to an existing type is well documented, but I can't find out how to create an actual type (node or paragraph) programmatically.

# Answer
> 0 votes
There are two issues here. To start with, the config files for a paragraph type should be placed in the config folder of the module, for which there is now a console command. See Export Paragraph bundle with Drupal Console

Then there is the general problem, how sites can update the config of an already installed module. You'll find different solutions in this topic How do I update the configuration of a module?

---
Tags: 8, paragraphs
---


# Question
Title: twig problem, how to override base templates?
I have installed Bootstrap and the Radix theme, and created a sub-theme, which is all working OK. But I am unable to get some of my twig files to override the base theme twig files...

The file themes/custom/mytheme/templates/page/page.html.twig contains: {% embed '@radix/navbar/navbar.twig' with {

I would like to create a navbar.twig in my subtheme and use that instead of the standard radix one. Changes I make to themes/contrib/radix/src/components/navbar/navbar.twig will show up on my site (as this is what the embed refers to), but changes to themes/custom/mytheme/src/components/navbar/navbar.twig do not.

**How can I change that embed line so that it includes the subtheme twig rather than the base?** It's some kind of twig namespace? I have not been able to figure out where it is defined.

# Answer
You can't. Create your own `page.html.twig` instead and use `{% embed '@my_subtheme/navbar/... %}` in there.

Use the machine name == directory of your subtheme for `@my_subtheme`. Only lowercase, digits and underlines are allowed for machine names. The Twig file must be placed below the templates subdir, but do not include `templates/` in the embed string
> 1 votes

---
Tags: theming
---


# Question
Title: How to import git commit from development to testing in Aegir
So, I have established Aegir to take care of my sites workflow.

Now I made changes to my development site, used git to load the commit to development site. How do I import the latest commits to Staging or Production ?

# Answer
> 0 votes
With the Hosting site Git module you can create a git pull task from the hostmaster frontend.

> This module extends Aegir with the option to do a 'git pull' in a site directory.

# Answer
> 0 votes
From stage to production (in case every custom module, feature, theme have it's own repository)

1. Create a new tag on your repository.
2. Create a new make file that gets this tag-version of the module, theme etc.
3. Create with this make file a new platform in Aegir.
4. Migrate the site to the new platform.

We assume that on the production server we must have the absolute control over the code.
It's a painful but reliable workflow.

# Answer
> 0 votes
The assumed architecture model is problematic. You shouldn't have an "Aegir hub" server separately from Dev, Staging and Prod servers; you should simply have Aegir Dev, Aegir Staging and Aegir Prod servers.

To move sites from one Aegir environment to another, you would remotely import them.

For details on this topic, see Aegir DevOps: Deployment Workflows for Drupal Sites.

For updating code on whichever server, you would navigate to *Platforms » Add Platform*. From there, you would choose a deployment strategy involving Git. See the Deployment Strategies documentation page for more information.

---
Tags: 7, drush, version-control, aegir
---


# Question
Title: how to stop a view from executing within a views hook
I am using custom code with a views pre\_execute and i want the view to return an empty set if certain conditions are met , or not to return the view at all. how can i do this ? this is what i tried.

```
function mymodule_views_pre_execute(&$view) {
   // if certain conditions are met i want this view to be empty or not come out at all
  if ($myconditions){
   $view = null;
  }
}

```

# Answer
this worked for me, i unset all the results and the view disappeared

```
foreach ($view->result as $key => $value) {
    unset ($view->result[$key]); // delete a row

  }

```
> 0 votes

---
Tags: views, 8
---


title: Anonymous permissions with Nodeaccess

text:
# Question
Title: Anonymous permissions with Nodeaccess
1. Content type: Webform
2. Allowed grants: View, Edit
3. Allowed roles: Anon, authorized, admin

---

1. Go to the webform node eg. node/20
2. Click Grants tab
3. Tick authenticated and admin users can View, anonymous is unticked
4. Page is still accessed by anonymous?

node/20:

Global Nodeaccess settings:  At the bottom Webform is ticked to View for anon/authenticated/admin because we want anonymous to see all webforms by default, except one that needs to be logged in. Doesn't really matter because unticking View for anonymous, anonymous can still view the page?!

# Answer
> 0 votes
With every Nodeaccess permission change, Permissions need to be rebuilt every time, for some reason I am not getting the warning message on save, run it at `/admin/reports/status/rebuild`

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


# Question
Title: Date and links formatting in node template
Drupal 8.x

I have 2 quick questions. I have the following node template `node--briefing--teaser.html.twig`

```
<div>
  <span>{{ date }}</span>
  <span>{{ label }}</span>
  <a href="{{ content.links.uri }}"></a>
</div>

```

Now the questions are:

* How can I format the date to the following `d/m/Y`
* How can I get the URI of the read more field (links)

With a normal link field you can simply do `content.my_link.0['#url']` to get this but that doesn't seem to be the case with the node links field.

Thanks in advance!

# Answer
> 1 votes
Answer for the date formating: {{ date.value|date('U')|format\_date('custom', 'j/m/Y') }}

For the URI investigate the data structure with twig vardumper.

---
Tags: theming
---


# Question
Title: Load a block contents dynamically / via AJAX?
I need to have a custom block on the page (will be sitewide) that has two states - one for when a cookie is present and has a certain value, and the other for when that cookie is not there or the value is outdated. Think of it like login states, but no authentication through Drupal.

What is the proper way to go about this with the block build() method? Do I implement a lazy loader that has the logic in it that builds the render array? Do I also add a cache context based on this cookie and its value so it is unique to those users?

# Answer
You can get the cookie from the request, see Can't find cookie for validation in EventSubscriber. Set the context and trigger the kill switch like in the code example and it should work. But this is not good for performance. So I would deliver an empty block container, attach a js library to the block, get the cookie value client side and then initiate an ajax request to get the block content.

See the code of the module Ajax Block as example how to lazy load a block client side: https://git.drupalcode.org/project/block\_ajax
> 2 votes

---
Tags: 8, blocks, ajax
---


# Question
Title: How to detect Panelizer use in template_preprocess_html()?
In Drupal 7, you could look for `$node->panelizer` or use `page_manager_get_current_page()` to check if the current page uses a panelizer layout. How do you do that in Drupal 8?

I'm trying to add a body class if the current page contains a specific pane.

# Answer
Turns out you do have access to $node-\>panelizer. So here's what I did:

```
function MYMODULE_preprocess_html(&$vars) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    if (isset($node->panelizer)) {
      $panelizer = $node->panelizer->getValue();
      // do whatever checks are needed
      // and use $vars['attributes']->addClass('MYCLASS') when ready
    }
  }
}

```
> 0 votes

# Answer
I'm not sure if this is quite what you're after, but these hooks will fire if your page is using panelizer.

```
/**
 * Implements hook_preprocess_panels_pane().
 */
function YOURTHEME_preprocess_panels_pane(&$$variables) {
  // If this triggers then you are in a panels pane.
}

```

OR

```
/**
 * Implements hook_panels_pane_content_alter().
 */
 function YOUR_MODULE_panels_pane_content_alter($content, $pane, $args, $contexts) {
  // If this triggers then you are altering panels content.
}

```

If you want to check for panelizer in the node you could try something like this:

```
$node = \Drupal::routeMatch()->getParameter('node');
if ($node->hasField('panelizer')) {
  // Do stuff
}

```
> 1 votes

---
Tags: 8, theming, panels
---


# Question
Title: Views date exposed filter by year in checkboxes
I have date field. In views I want to add the a date exposed filter.

This filter will only display year and we can select multiple years.

Just like this

I have checked the better exposed filter module, date view and I did not find any option to display them in checkboxes nor I find any option to select multiple dates like in the picture we can select multiple years.

With the date views and better exposed filter, I can display year only in select list.

Is it achievable? Any suggestion?

# Answer
You can construct the Exposed Year filter yourself using the `Grouped filters` option:

1. Add your Date field Filter and Expose it
2. Select `Grouped filters` under `Filter type to expose`
3. Tick `Allow multiple selections`
4. Select `Radios` under Widget type
5. Adjust the Label and Description if you need to
6. In the items table change **all** Operators to `Is between` and configure each year like so:

```
 2019   Is between   2019-01-01
                     2020-01-01

 2018   Is between   2018-01-01
                     2019-01-01

 2017   Is between   2017-01-01
                     2018-01-01

 ...

```

and so on for all the years. The times are assumed to be 00:00:00.

You don't have to use the Better exposed filters, they may interfere with the display of the grouped options.

BTW this issue may be relevant: Grouped exposed filter with "Allow multiple selections" ignores widget setting
> 2 votes

---
Tags: 7, views, datetime
---


# Question
Title: Can we output individual form items within a Layout?
We are using Layouts (via mytheme.layouts.yml) to create regions for our Node Edit forms. This looks something like...

```
edit_nodelayout:
  label: 'Edit Node Layout'
  category: edit
  path: templates/panels
  template: edit-nodelayout
  default_region: toplayout
  regions:
    toplayout:
      label: 'Top'
    details:
      label: 'Details'
    other:
      label: 'Other'

```

We have placed each field for the content-type into the appropriate region via the admin UI. At least one of our fields is a reference field to a Paragraph entity-type.

In our template, which is defined in the yml as /templates/panels/edit-nodelayout.html.yml, we are currently outputting all content as full regions.

```
{# some html here #}
{{ content.toplayout }}

{# some html here #}
{{ content.details }}

{# some html here #}
{{ content.other }}

```

How would we access individual items within a region? For example, if within the content.details region, we have placed a field called "Foo", how do we output that individually? We have tried this...

```
<p>Please enter everything you know about Foo</p>
{{ content.details.foo }}

```

This becomes interesting when the field called "Foo" is a reference to a Paragraph entity-type. How would we then output individual fields within "Foo" entity?

```
<p>Output the "bar" field within the "foo" Paragraph type</p>
{{ content.details.foo.bar }}

```

Any help, pointers to documentation appreciated.

# Answer
> 0 votes
That is not how you're *supposed* to use layout templates as those should be for for placing content, just like normal Drupal regions, and then modify the output using field and node templates. The general idea being to be able to reuse the templates in other places and as such reducing the number of templates needed.

Of course you *can* output content directly in the layout template. I would recommend you install the Twig Tweak module. You can then use `{{ dd() }}` to see what is available to you. As an example you can display a field value like this:

```
{{ node.field_myfield.value }}

```

It depends on what you want to display, but that's the general idea, very similar to the node template.

---
Tags: 8, theming
---


# Question
Title: How do I iterate over values of a multivalued field with entity_metadata_wrapper?
For instance, I have a taxonomy\_term\_reference field with cardinality -1. If one or more terms are selected, I can use this code:

```
  foreach ($wrapper->field_myterms as $t) {
    $terms[] = $t->name->value();
  }

```

But if the field has zero values selected, this code throws:

```
EntityMetadataWrapperException: Unable to get the data property name as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 442 of sites/all/modules/entity/includes/entity.wrapper.inc).

```

This happens in a preview form step while creating a custom entity. The entity has not yet been saved but I am showing a preview of the properties and field data by creating a temporary entity with this code:

```
$entity = entity_get_controller('ams_survey')->create($form_state['values']);
$wrapper = entity_metadata_wrapper('ams_survey', $entity);

```

# Answer
> 3 votes
I can't reproduce this behaviour having used the following simple test:

1. Add a new article with no Tag terms, and note the nid (`field_tags` is a taxonomy term reference field with a cardinality of -1).
2. Run the following code:

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

foreach ($wrapper->field_tags as $item) {
  dpm($item);
}

```

No debug messages are printed (as you'd expect), but I get no errors either.

The only thing I can think that might be causing the problem is that the entity in question was created *before* you added the `field_myterms` field. In that case there would be no entry in the field table for that entity, and it might cause some strange behaviour.

# Answer
> 4 votes
The problem is in this file: /sites/all/modules/entity/includes/entity.wrapper.inc

Whenever a field\_foobar-\>value() is called, and the field isn't set, then the class throws an Exception. That is just silly, because having an empty field isn't an error.

Inside that field, when checking to see if a field is empty, it uses this code:

```
$data = $this->dataAvailable() ? $this->value() : NULL;

```

But using "if ($wrapper-\>field-\>foobar-\>dataAvailable())" before each echo of the value is aggravating. Sigh, why can't things in Drupal ever be simple?

# Answer
> 0 votes
For those who came later. Based on this page Entity metadata wrappers, you should use `->getIterator()`:

```
$wrapper = entity_metadata_wrapper('node', $node);
foreach ($wrapper->field_taxonomy_terms->getIterator() as $delta => $term_wrapper) {
  // $term_wrapper may now be accessed as a taxonomy term wrapper.
  $label = $term_wrapper->name->value();
}

```

---
Tags: 7, entities
---