# Question
Title: How to have all the fields available in a display mode for content type D8
I'd like to be able to choose the date field or other fields that you can see in form display in 'custom display mode' for content types ?

How can I do that ?

Thank you.

# Answer
> 0 votes
You need to drag the items that you don't want to the disabled section. This works for both form display and front end display.

For your custom display mode, you should be able to select from each display mode:

# Answer
> 0 votes
The solution is to use Display suite and activate a layout in the display mode.

# Answer
> -2 votes
You can go to admin/structure/types/manage/content\_type/form-display and drag the fields under "disabled" which you don't want to show in the node edit form. Rest will be present in node edit form

But the field which you have moved under disabled, will show up in front end display.

Attached is the screen shot

---
Tags: entities
---


title: Get form ID on hook_entity_presave()

text:
# Question
Title: Get form ID on hook_entity_presave()
I want to process some details before saving the node in Drupal 8. How will I get the form ID of the submitted form?

```
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->getEntityType()->id() // this only prints "node"
}

```

Is there any other workaround?

# Answer
`hook_entity_presave()` doesn't get the form ID, and this makes sense: An entity could be programmatically saved from a module or a Drush plugin without showing to the user a form to edit/create the entity.

Since you just want to know if the entity is being edited or created:

* You don't need to know the form ID
* You can use `hook_entity_presave()` or `hook_ENTITY_TYPE_presave()` with code similar to the following one

```
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->isNew()) {
    // The entity is being created.
  }
}

```

As side note, `$entity->getEntityType()->id()` returns `'node'` as expected: You are asking to the entity object its entity type, and for nodes that is clearly `'node'`.
> 5 votes

# Answer
To answer your question without going into the details as to why you needed it. (others have answered the solution to your original problem)

However, you can get the form\_id from the request:

```
\Drupal::request()->get('form_id')

```

You should check if the variable is set in the first place and then check its value.
I had a specific case where i needed to take action on an entity save from a specific form but not on any other case.

This was the only solution i came up with.
> 5 votes

# Answer
Try :

```
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
    if($entity->isNew()){
    // NEW ENTITY HERE
    }
    else{
    //EDIT Entity here
    }
}

```
> 2 votes

# Answer
I think that hook\_entity\_presave won't help you.

But you can use hook\_form\_alter on your node form and in code of the hook add one more submit function, which would be executed when the node form is submitted.

Anyway, in Drupal 7 the solution was as follows.

By the way, here is code, where one can see an example of addition of submit function

```
 function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
    $upload_enabled_types = \Drupal::config('mymodule.settings')->get('upload_enabled_types');
    $form['workflow']['upload_' . $form['type']['#value']] = array(
      '#type' => 'radios',
      '#title' => t('Attachments'),
      '#default_value' => in_array($form['type']['#value'], $upload_enabled_types) ? 1 : 0,
      '#options' => array(t('Disabled'), t('Enabled')),
    );
    // Add a custom submit handler to save the array of types back to the config file.
    $form['actions']['submit']['#submit'][] = 'mymodule_upload_enabled_types_submit';
  }
}

```
> 0 votes

---
Tags: 8, hooks
---


# Question
Title: How to get html source code from body field in node type edit form?
In node type = "article", I have field of type body.

**In my .module file, I want to get its raw source code with actual html classes too. But all I get is:**

```
$body = $node->get('field_all_body')->value;
print_r($body);die;

```

I want the value should contain div class too. How it can be achieved?

My actual requirement is: I want to populate one field value on behalf of the class exists in `'field_all_body'` field.

Foe example, I select some text in text-editor, and mark it bold, then that particular text should get cloned in another field too.

# Answer
The basic text format filters out all but a few HTML tags. You want to select the Full HTML text format to keep your divs and classes.
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: Access to folder files without redirect to drupal index
I need to access a folder of my project. My project is at the root of my domain, and it is a Drupal (so the .htaccess redirects all traffic to the Drupal index.php).

I need to access my resource `/other_files/` and all its content through requests

```
http://www.mydomain.ext/other_files/file1.php
http: //www.mydomain.ext/other_files/file2.php
etc.

```

I have modified the HTACESS of drupal adding this:

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} !=/other_files ----> this line
RewriteRule ^ index.php [L]

```

But it does not work.

Other modifications that I have made in the HTACCESS

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} !=/other_files/file1.php ----> this line
RewriteCond %{REQUEST_URI} !=/other_files/file2.php ----> this line
RewriteRule ^ index.php [L]

```

But it does not work.

What am I doing wrong? Thank you

# Answer
> 0 votes
In Drupal 7 the default htaccess file is setup to allow you to access a .php file in exactly the way you want.

In D8 I think you need this:

```
# Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
# ADD THIS
  RewriteCond %{REQUEST_URI} !/other_files/[^/]*\.php$

```

---
Tags: redirection, .htaccess
---


# Question
Title: Disable caching for custom block for anonymous users
I have created a custom Block that extends BlockBase. I don't want the content to be cached for anonymous users (also not for authenticated users). To be more precise, caching would be fine but depending on some url query argument. In my case the url contains a parameter 'mode' (?mode=1 or ?mode=2 and so on). Depending on the parameter the content of the block varies.

I added the following function:

```
 public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), array('url.query_args:mode'));
  }

```

Still the block content seems to be cached. Is it neccessary to disable the internal page cache module? Actually I don't want to globally disable caching, I just want my block to be cached correctly depending on the url parameter mode.

# Answer
The problem is, you don't render the block in a normal way and Display Suite is obviously not able to retrieve the plugin cache metadata.

Most times it is a better option to include the cache metadata in the render array together with the data it depends on:

```
public function build() {
  $build = [];
  $request = \Drupal::request();
  $mode = $request->query->get('mode');
  $build['mode'] = [
    '#markup' => t('The query argument is mode=@mode.', ['@mode' => $mode]),
  ];
  $build['#cache']['contexts'][] = 'url.query_args:mode';
  return $build;
}

```

Then the cache metadata can bubble up, no matter where and how this block content is embedded.
> 1 votes

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


title: How do I edit a "block" on my site?

text:
# Question
Title: How do I edit a "block" on my site?
I want to edit the text within a block on my site. However, the only options seem to be configure block and configure layout - neither of which gives me the option to edit the text. Suggestions? Click the link below to see what I'm talking about. Any help greatly appreciated! Example of what I'm talking about: enter link description here

# Answer
> 1 votes
If it’s a menu block, the titles of each link is configured in the menu configuration, not the block configuration.

---
Tags: blocks
---


title: Sending Notification Messages

text:
# Question
Title: Sending Notification Messages
My team is working on a simple message notification using the message stack but a bit tricky to implement.

The goal is when a user is subscribed to content, a notification message will be delivered to the user's email address.

We are trying to follow this steps, doing the configuration in the browser. But the last step, we think should be added manually in a certain file as mentioned in this comment.

**Questions:**

* Where should I add the code to properly send the message into email?
* Is there a need to create a custom module to achieve it?

# Answer
Hooks go in the **.module** file, the only hooks that can also work in the **.theme** file are preprocess and alter hooks.

So if you want the message to be sent when a node is created or updated, use hook\_ENTITY\_TYPE\_presave.

Create a custom module, lets call it "Send Message"

**send\_message.info.yml**

```
name: 'Send Message'
description: 'Sends the message when a node of Content type Article is created or updated.'
core: 8.x
package: Message
dependencies:
  - message
type: module

```

**send\_message.module**

```
<?php

use Drupal\node\NodeInterface;
use Drupal\message\Entity\Message;

/*
 * Implements hook_ENTITY_TYPE_presave()
 */

function send_message_node_presave(NodeInterface $node) {

   if ($node->getType() == 'article') { // checks if content type is article
      $message = Message::create(['template' => 'foo_message_type', 'uid' => $node->getOwnerId()]);
      $message->set('field_node_ref', $node);
      $message->save();
      $notifier = \Drupal::service('message_notify.sender');
      $notifier->send($message);
   }

}

```
> 5 votes

---
Tags: 8
---


# Question
Title: How can I check if user logged in via mobile or using an application?
On the login page, can we check if users logged in via mobile or using an application?

Basing on that, I need to check things.

# Answer
There is a module for that, the Browscap module.

> Browscap provides an improved version of PHP's get\_browser() function. The get\_browser() function can be used to tell what a visitor's browser is capable of. Unfortunately, the version provided by PHP has a number of limitations, namely: It can be difficult or impossible to configure for shared hosting environments. The data used to identify browsers and determine their capabilities requires consistent maintenance to keep up-to-date. Browscap automates maintenance by storing browser data in a database and automatically retrieving the latest data on a configurable schedule.

Configurating it is very easy, and you can use it with the Panels module to display or not a block if the user logged-in via mobile or not.

The current Drupal 8 version is 8.x-3.0-alpha2.
> 1 votes

---
Tags: 8
---


title: How to properly use media (in core)?

text:
# Question
Title: How to properly use media (in core)?
We are converting all of our images to the image type provided by media. What I don't really understand is that there seem to be multiple ways to do this. Am I supposed to give the 'image' media type a file field, and then use that? Or, should I give the 'image' media type a 'file' media type field, and use that? Or, is there something I'm missing and the 'image' media type already has support for images?

Based on my understanding, you're supposed to create a file field in the 'image' media type, and then you use that as the source. Is that right?

# Answer
> 1 votes
You need to add a field to the media entity, that acts as the base for a media provider module (such as images, files, remote videos, google docs, etc.). The various media provider modules dictate the field, that is needed to store and retrieve the essential information (and optionally some meta data)

E.g. for creating image media entity, you select "image" as media source (provider). Then add the image field to the entity, and select this field as base for media provider. Optionally the media provider can extract additional meta data (width, height, EXIF,...) from that field and map it to other fields of your media entity.

For a Youtube video (Video embed field), the base field is an URL field. For a File media entity, the base field is a file field. And so on.

---
Tags: 8, media
---


# Question
Title: Warning: Invalid argument supplied for foreach() in form_select_options() (line 2837 of includes/form.inc)
I get the following erros on selecting the selectbox. Here onchang of this field will populate another checkbox with city details id zipcode using ajax callback.

```
 $zipcode_options = get_all_zipcodes_ascending();

  // Populate Ort on auktion clone.
  $selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
  $selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
  $ort_options = _ajax_city_dropdown_options($selected);

  $form['zip_code'] = [
    '#type' => 'select',
    '#title' => t('PLZ'),
    '#options' => $zipcode_options,
    '#default_value' => isset($auktion->zip_code) ? $auktion->zip_code : "",
    '#select2' => ['width' => '100%', 'placeholder' => t('Enter a zipcode'), 'allowClear' => TRUE],
    '#empty_option' => '',
    '#validated' => TRUE,
    '#required' => TRUE,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'ajax_example_dependent_dropdown_callback',
      'wrapper' => 'dropdown-second-replace',
    ),
  ];

```

Referenced many links but cannot find a solution to resolve this issue.

References:

https://www.drupal.org/node/586576

populate drop down from results using ajax

http://techqa.info/drupal/question/203725/help-understand/solve-this-warning:-invalid-argument-supplied-for-foreach%28%29-in-views-that-requires-class-registry-clean-to-mend

# Answer
> 0 votes
Looking on the code i suspect that error lies in these lines- `$selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
 $selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
$ort_options = _ajax_city_dropdown_options($selected);`

And according to my understanding adding these lines will fix this warning-

```
 $selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
$selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
$ort_options = _ajax_city_dropdown_options($selected);
if(!is_array($ort_options)){
    $ort_options=array();
}

```

Assuming that \_ajax\_city\_dropdown\_options($selected); returns options for second select list/ Check Boxes there can be some options in first Select List or there is none selected in first list for which there is no values available for second list. So returning an empty array will address this situation and prevent this error form appearing.

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


title: Edit account creation message

text:
# Question
Title: Edit account creation message
I'm trying to change the message users see after creating an account. It currently says:

*Thank you for applying for an account. Your account is currently pending approval by the site administrator. In the meantime, a welcome message with further instructions has been sent to your e-mail address.*

What's the best way of changing this? Would the String Overrides module help? A Rule, perhaps?

Many thanks.

# Answer
This is exactly what the String Overrides module is for.

If you only need just a couple strings, you can also use `settings.php`. See this section:

```
/**
 * String overrides:
 *
 * To override specific strings on your site with or without enabling locale
 * module, add an entry to this list. This functionality allows you to change
 * a small number of your site's default English language interface strings.
 *
 * Remove the leading hash signs to enable.
 */

```

You don't want to use Rules, because although you can add a new message with a rule, the old message will still be there as well (which isn't what you want, I assume).
> 2 votes

# Answer
I solved this with Rule module because this module was already used in my application but as Patrick Kenny said we can set new message with a rule but the old message will still be there as well. This problem I solved with the help of CSS (hiding message div with display:none property).
> 0 votes

# Answer
You can change those messages in Configuration\>Account settings (admin/config/people/accounts). There is E-mails section where you can change messages used during account registeration process.
> -3 votes

---
Tags: users
---


# Question
Title: Drupal 8 paragraph access in views-view twig file
1.) I have added a paragrah with multiple field in my node form

2.) Now i have created a View and added the paragraph field and selected the Formatter as Rendered Entity

3.) In the preview section i can see all my paragraph data , as my twig debug is on i can see file suggestions where i can override the paragraph file

4.) But i want to access my paragraphs fields inside the views-view--unformatted-{{ view\_machine\_name }}.html.twig file

5.) I access the normal fields inside my content type using

```
view.field.{{ machine_name }}.getvalue(view.result[0])

```

6.) I can access the paragraph complete section by

```
view.field.{{ paragraph_machine_name }}.original_value

```

How can i access the fields inside the paragraph in this view file

# Answer
> 2 votes
This is how i solved this ..

--\> I added a relationship of the paragraph field and made it as required

--\> After that i selected the relationship in the filter criteria section

--\> And then i was able to select all the paragraph fields while adding a new field in the view

Hope this helps someone

---
Tags: views, 8, paragraphs
---


# Question
Title: How to get a class into the page template for design header?
In my page-template there is a header, footer and div for the content.

The page-template is used to put menu and footer stuff in that comes back on every page...

But on some pages the header should have a other background... try to realise that with just adding a different class on that header.

But I wonder how I can put a different class on the header in page.html.twig depending on the sort of type content that was used.

Example: So for the home page a created the content type 'home page'... for the other page i created the content type 'normal page' so how can I put different classes into the page template depending on the content type that created a page?

What is the best way to do this...

Thanks for reading!

# Answer
> 0 votes
As you have created new content types, the body tag of your new content type should have a class based on your new content types, like 'node-type-CONTENT\_TYPE'. You can use this class to change the background of your footer and header. `.node-type-CONTENT_TYPE .footer`

---
Tags: theming
---


# Question
Title: How do I find when a class is used as service?
I was searching for how to find field info and came across getFieldDefinitions on Drupal 8 (why all these deprecated functions on DP8?) which says to use `\Drupal::service('entity_field.manager')->getFieldDefinitions(xxx, xxx);`.

How can I tell from `EntityFieldManager::getFieldDefinitions()` that it needs to be called as a service, and that the service is entity\_field.manager?

Why doesn't `\Drupal\EntityFieldManager::getFieldDefinitions($etid, $bundle)` work?

# Answer
> 1 votes
From the page describing a method, you cannot know if the method is implemented from a service, but if you look at the page describing the class, you will notice the class implements a service.

>

*1 service uses EntityFieldManager* doesn't mean *the code of a service uses EntityFieldManager*, but that `EntityFieldManager` is the class that defines a service. In this case, the machine name of the service is *entity\_field.manager*, as given from the *entity\_field.manager in core/core.services.yml* line.

As for the second question, that is plain PHP. `\Drupal\EntityFieldManager::getFieldDefinitions($etid, $bundle)` means *call the `getFieldDefinitions()` static method of the `\Drupal\EntityFieldManager` class*. Since `\Drupal\EntityFieldManager::getFieldDefinitions()` is not a static method, you cannot call it like that, but you need an object, as in `$entity_file_manager->getFieldDefinition()`.

# Answer
> 1 votes
> How can I tell from EntityFieldManager::getFieldDefinitions() that it needs to be called as a service, and that the service is entity\_field.manager?

The online docs are quite effective for this. For example, look at the docs for the `EntityFieldManager` class, which contain an explicit reference:

> 1 service uses EntityFieldManager
>
> entity\_field.manager in core/core.services.yml
>
> Drupal\Core\Entity\EntityFieldManager

> Why doesn't \Drupal\EntityFieldManager::getFieldDefinitions($etid, $bundle) work?

Because `getFieldDefinitions` is not a static method; you can't call it statically.

---
Tags: entities
---


# Question
Title: Change 'href' attribute in AJAX enabled links
I have some links with the class `use-ajax`. Everything works fine with default settings.

The problem is that at some point I need to change the `href` attribute of a link and make the ajax call to the new url, which is not working. The call is made to the initial url of that link.

I tried to reattach behaviours but this doesn't seem to work.

Any help would be appreciated.

Any ideas? Thanks

# Answer
> 3 votes
Since nobody knows how to do it I think this might help:

```
var element_settings = {};
element_settings.url = $(this).attr('href');
element_settings.event = 'click';
element_settings.progress = {
  type: 'throbber',
  message: ''
};
var base = $(this).attr('id');
Drupal.ajax[base] = new Drupal.ajax( base, this, element_settings );

$(this).unbind(Drupal.ajax[base].event);

$(this).bind(Drupal.ajax[base].event, function (event) {
  return Drupal.ajax[base].eventResponse(this, event);
});

```

# Answer
> 5 votes
Drupal link based Ajax, correspond to a `Drupal.ajax['#id']` element object and drupal works with them not with DOM Objects.

So you don't have to change the href attribute you need to change the URL where it's doing POST in the `Drupal.ajax` element, in this case do this:

```
// Confirm structure first executing on console 'Drupal.ajax['#id'].options.url'
var href = 'hook_url/ajax/parameter1/parameter2';

// And change the href POST parameter
Drupal.ajax['#id'].options.url = href;

```

And it's done!

# Answer
> 0 votes
in case your link has no ID attribute, here is another solution:

```
var href = oldhref.replace('/watch/', '/unwatch/'); //your new url
var elem = $('.watchthis a'); // the link element
elem.attr('href', href);
var n = Drupal.ajax.instances.length;
for (var i = 0; i < n; i++) {
  if (Drupal.ajax.instances[i].element == elem[0]) {
    Drupal.ajax.instances[i].options.url = href+'?_wrapper_format=drupal_ajax';
  }
}

```

---
Tags: 7, ajax
---


# Question
Title: Can add the new variable in the existing node--contenttype.tpl.tpl?
I have written the query in .Module file and stored the output in a variable.

Now, I want to pass this new variable in existing node--contenttype.tpl.php

My idea is to pass the variable for the existing node.tpl.php using hook\_theme function

Is that a good way to achieve it or anyone has a better way for it ?

# Answer
You'd be better off doing in here: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/template\_preprocess\_node/7.x

"Processes variables for node.tpl.php" so should be ideal for what you need
> 0 votes

---
Tags: 7, theming
---


title: Complex Filter Criteria no Results

text:
# Question
Title: Complex Filter Criteria no Results
I'm working on a views to show different events in a calendar. I want to be able to filter on terms (In my view the field is called 'Wat?' for terms like music, art, design, etc). For this I create a filter criteria with an exposed filter for these taxonomy terms.

When I filter on *film*, only the film items are shown, perfect!

But now I want to make a complex filter by using filter groups. In both groups I want to use this genre filter. So I add another one. But for some reason this doesn't work, when I select *film* on both dropdowns and click apply it doesn't work anymore, and no results are given. I created a simplified view to test this. Here are images of my filter, and the use of it.

This is my complex filter

Using one filter gives results

But when selecting the *film* in both I get no result

# Answer
> 0 votes
The problem of my above question is a core bug. I added it to the Drupal Core issues, hope it will be solved soon. https://www.drupal.org/project/drupal/issues/2935113

In the mean time I found a work around. I use two different filters in the two added groups. Both filter on the same thing.

So in group 2, I filter on my Wat? field.

In group 3, I filter with the 'Has taxonomy filter'.

Both filter on the same taxonomy term but because they are different filters it does work now.

---
Tags: 8, views
---


title: How to filter a date range?

text:
# Question
Title: How to filter a date range?
I'm having troubles figuring out how to filter by date using the date range module from Drupal 8 core.

I, of course, found this post: How to filter a View by Date Range (start, end)?

But this doesn't tell me how to use the filter, it only makes the filter work better. So I used this patch but how to make this filter work?

I'm creating a calendar with cultural events and I want to be able to filter on date and genre with exposed filters. So let's say I have a design event from 05-01-2018 until 05-02-2018 (`dd-mm-yyyy`).

And I want it to show up when I'm searching for what is going on today or this month that concerns design? How to set up the filter for this?

What is the best and most simple way to do this?

# Answer
I found a solution for this I have two exposed filters for my `begin_date` (`begin_filter_1` and `begin_filter_2`) and two exposed filters for my `end_date` (`end_filter_1` and `end_filter_2`).

* When the `begin_filter_1` is entered, this input will be copied to `end_filter_2`.
* When the `end_filter_1` is entered, this input will be copied to `begin_filter_2`.

No the filter looks like this

```
Published Yes

AND

Category - Exposed (Taxonomy Term) = Design
Begin Filter 1 - Exposed >= Begin_Date
End Filter 1 - Exposed <= End_Date

AND

Has Taxonomy Term - Exposed = Design
Begin Filter 2 - Exposed(but hidden via css) <= Begin_Date
End Filter 2 - Exposed(but hidden via css) >= End_Date

```

As you can see in the second Group I use a different filter to filter on the category. This is because of a bug in Drupal Core: Complex Filter Criteria no Results
> 0 votes

---
Tags: 8, views, datetime
---


title: Get select list Value in node template

text:
# Question
Title: Get select list Value in node template
I have a integer selection list field in my content types with some `key|Value` options.

```
0|CEO
1|CTO
2|Manager

```

now in my template I want get value. I try `{{node.field_positon.value}}` but it return me `key` value (it return 0 or 1 or 2 ).

**My question is** how can I get value of selection option in template file?

**notice:** I know I can paly with `content.field_position` ( but it put some markup wrappers around field),**I want get it** by `node` variable.

# Answer
> 5 votes
Just use the following, and you will obtain what you want to achieve.

```
{{ content.field_position[0]['#markup'] }}

```

# Answer
> 2 votes
To get the raw value use:

```
{{ content.field_position.0 }}

```

---
Tags: theming, nodes, 8
---


# Question
Title: Node object doesn't exist when not logged in
I am trying to use the preprocess\_page hook to add some twig variables.

All worked fine, until I logged out. When I'm logged out, the hooks $variables does not contain a node object.

Sample code:

```
function MYTHEME_preprocess_page(&$variables) {
  $variables['hero_image'] = '';

  if (!empty($variables['node'])) {
    $node = $variables['node']; // if logged in, this is set, logged out, it's not
    // other code here...
  }

}

```

# Answer
Maybe you should check the anonymous user permisions www.yourwebsite.com/admin/people/permissions/anonymous
> 2 votes

---
Tags: 8, theming, hooks
---


# Question
Title: SearchAPI Autocomplete - Pass in contextual filter to alter query
I'm trying to modify the Autocomplete module query with `hook_search_api_alter_query`. I would like to pass in the contextual filter of the page I embed the search in into the module so I can add it to the query. In a `hook_search_api_alter_query` function I wrote, I just used `arg(1)`, which works for the actual search, however when the autocomplete module runs, `var_dump(arg(1))` returns `Response Type: string(33)` followed by the autocomplete results and their html tags.

Is it possible to pass in the contextual filter into the autocomplete module so that I can use it , since the contextual filter has been changed to `/search_api_autocomplete/search_api_views_[view name]/-`?

My current query alter hook:

```
    function hook_search_api_query_alter(SearchApiQueryInterface $query) {
      var_dump(arg(1));
        $prod_code = arg(1);
        $tid = taxonomy_get_term_by_name($prod_code);
        if (!empty($tid)) {
            $base_filter = $query->createFilter('AND');
            $or_filter = $query->createFilter('OR');
            while (!empty($tid)) {
                $or_filter->condition('field_prod_code', array_shift($tid)->tid);
            }
            $base_filter->filter($or_filter);
            $query->filter($base_filter);
        }
    }

```

My problem is that `arg(1)` within the autocomplete module isn't the taxonomy term, therefore the function doesn't go through the if statement. I need a way to get the contextual filter for the autocomplete function so that it can alter my query like it does when searching.

# Answer
> 1 votes
I ran into the same issue. You could save your data in a session in `hook_init` or `hook_boot`.

```
/**
 * Implements hook_init().
 */
function hook_init() {
  $arg = arg();
  if (isset($arg[2]) && $arg[0] == 'taxonomy' && $arg[1] == 'term' && is_numeric($arg[2]) ) {
    $_SESSION['last_term'] = $arg[2];
  }
}

```

---
Tags: 7
---


# Question
Title: Use checkbox to set image as background-image for content type
For a better user Experience in our backend, I want to enable content managers to select the picture, that will be set as background-image for a specified content-type.

Background-story: To add picture as background-image for our content, we use a file-upload image provided by the 'fieldfield\_sources' module. Sometimes this process is very annoying. In order to improve the process of 'content creation/edition/' instead of using the file upload each time we create/edit a content type, we want to add a new field that already holds the needed images when creating/editing a content type. The content manager can choose per checkbox which image will be set as background-image.

Please have find in attachement how the solution could looks-like (here blue and orange image, blue is selected per default).

Now my questions: \- Is there a module that can handle this feature for me? \- May I have to extend the 'fieldfield\_source' module to behave like I want (I'm not sure how to) \- Could some one give me some advice how to implement this feature?

Thank you in advance

H.

# Answer
There are many ways to do this, but if you want a way that doesn't require writing extra code or installing a new module you can start with this logic and create a view. https://drupal.stackexchange.com/a/218882/21300

The answer there shows how you pass the node from the url to the view. That way you can get fields from the node, like image fields or body text based on the current node that you're on. Then inside the view you can add a custom text field where you can write the html for how you want the background image and text to be displayed.

UPDATE:

If you would like to perform this using code you could create a module with a block plugin.

```
<?php

namespace Drupal\your_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

/**
 * @Block(
 * id = "your_block_id",
 * admin_label = @Translation("Your block name"),
 * )
 */

class YourBlock extends BlockBase {

    public function defaultConfiguration() {

        return array();
    }

    public function blockForm($form, FormStateInterface $form_state) {

        return $form;
    }

    public function build() {
        $current_node = \Drupal::routeMatch()->getParameter('node');
        $image_style = \Drupal\image\Entity\ImageStyle::load('machine_name_of_image_style');
        $image_url = $image_style->buildUrl($node->image_field_name->entity->getFileuri());
$text = $node->text_field_name->value;
        $render = [
            '#markup' => '<div style="background:url("'.$image_url.'");">'.$text.'</div>',
        ];
        return $render;
    }
}

```

I haven't double checked the syntax but that's the idea. This will add a new block available for you that will return html containing the image and the text based on the fields of the current node. You should be able to alter the html however you want.

NOTE: This is assuming that you want the content of the current node, if you're trying to get content that isn't the current node you'll have to retrieve that info in another way, based on a query or a queue or however else you may have it set up. Either way this is an example of displaying content in a custom way based on the info you retrieve from within a function.
> 0 votes

---
Tags: entities
---


# Question
Title: Capturing Data on Multistep form to send to an API
I am connecting to an API that returns some data based on a user's zipcode. This data needs to be included in the payload of a second call to the API along with sone other form values.

I wanted to build the webform as a multistep, the first page collects the zip code and after the Next Page is clicked, do an API call to send the zipcode and save the response from that call, so that on the second page the Submit sends via another API call that response data plus all of the form values.

This Get the draft data in the webform hook\_form\_FORM\_ID\_alter() seems to be the answer but not quite.

# Answer
> 2 votes
You should write a custom WebformHandler that adds the return API data to $form\_state and then alters the form elements as needed. There are some blog post available about writing webform handlers.

Here is how to get the current page from the $form\_state.

```
/** @var \Drupal\webform\WebformSubmissionForm $form_object */
$form_object = $form_state->getFormObject();
$current_page = $form_state->get('current_page');

```

---
Tags: 8, webforms
---


# Question
Title: Why might form values not be passed from input to values?
Somewhere between buildForm and validateForm the $form\_state's 'input' becomes the 'values'. The values are listed as 'null'. For some reason, some sort of validation from core seems to be preventing only SOME of my values to be left behind, and there's no reason I can come up with, because the data is identical. Both are textfields representing URLs. My form is kind of complicated, so I can't post it unfortunately.

I have a feeling the problem is involving ajax somehow. The fields which are failing are fields which are added to the form by ajax. Sometimes the values turn to null, and other times the values turn to an empty string.

Where should I look in core to figure out what validation might be getting mad at my fields? Do you know of any typical thing that might prevent a user's input from passing to values?

EDIT: Here are the contents of my buildForm:

```
$items['redirect']['old'] = [
  '#type' => 'textfield',
  '#title' => t('Old'),
  '#default_value' => '',
  '#size' => 40,
  '#maxlength' => 502,
  '#description' => t('Old URL.'),
  '#required' => TRUE,
];

$items['redirect']['new'] = [
  '#type' => 'textfield',
  '#title' => t('New'),
  '#default_value' => '',
  '#size' => 40,
  '#maxlength' => 502,
  '#description' => t('Redirect URL.'),
  '#required' => TRUE,
];

$defs = $this->grabDefaultValues();

FormHelper::elementClone($form, $form_state, $items['redirect'], ['old'=>$defs['olds'],'new'=>$defs['news']]);

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

return $form;

```

The FormHelper part is just some reusable code for cloning the two elements together, so I get old1, old2, old3, etc. old1 always works, but old2 and old3 mess up sometimes. The thing is, I have used this code before, and it worked, so I don't know what's happening in this case.

# Answer
> 0 votes
Apparently, around line 1162 of FormBuilder.php, Drupal checks to see if there is a #name element to the field element you're using. If there's not, it uses the parent's name, which seems to be the previous form element's name.

The clone function wasn't setting unique #name's. I could have sworn it worked before, but maybe not.

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


# Question
Title: drush not able to download and enable modules whenever executing drush en <module_name> on Windows OS
I keep getting this pop-up screen that tries to locate an app to open .launcher files whenever I try to execute `drush en <Module_Name>` commands to download and enable a module on Drupal 8. On mac nothing like this happens, I'm not sure what needs to be done in order for the commands to work.

# Answer
First, use composer require for module installation.

Second, I don't use windows long time, but as I remember, there is a PATH variables that need to be configured so drush can work properly.

Take a look at this: https://modulesunraveled.com/drush/installing-drush-windows
> 1 votes

---
Tags: drush
---


# Question
Title: Any way to add CSS for a single page/node?
I'm cleaning up my big crazy style sheets (possibly pertinent to a future question) and I'm wondering the best way to add custom CSS to a specific node or page.

In particular, my work site's home page is a Panel Page and it has a bunch of different styling. Right now the CSS is just included with the main theme style sheet.

Is there a way to say, "if this is node Foo, then add foo.css"? Is CSS Injector what I'm looking for?

I *might* be interested in generalizing this to other nodes/sections/etc, but at the moment I just want to handle this one item.

# Answer
This is the sort of thing that I'd do by code, but that's because that's just the way I roll.

In the template.php you will want something like:

```
function MYTHEME_preprocess_node($vars) {
  if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'foo') {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/foo.css");
  }
}

```

Replace foo with values related to your own code.
> 70 votes

# Answer
Create a Context for your page/section and then use the Context Assets module to load CSS and/or javascript for that given context.

**Context:**

> Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
>
> Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.

**Context Add Assets:**

> Context add assets allows you to do this. It has an easy to use UI to allow you to do this all without writing any code. Because it uses ctools all of this is also exportable.
> 16 votes

# Answer
If it's a small amount of CSS, maybe considering making your CSS selectors based on the node and including the css in your theme's CSS? Drupal 7 provides the body.page-node-NODEID selector, and Zen for Drupal 6 provides similar body CSS classes.
> 12 votes

# Answer
If the criteria for which adding a CSS style depends from some node properties, then I would implement `MYTHEME_preprocess_node(&$variables)`; one of the values passed to the function is `$variables['node']` (not `$variables['#node']`).

```
MYTHEME_preprocess_node(&$variables) {
  if ($variables['node']->nid == 3) {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/foo.css");
  }
}

```

If the criteria don't depend from any node property, I would implement `MYTHEME_preprocess_page(&$variables)`; `$variables['node']` contains a node object, if the shown page is a node page.

The documentation for page.tpl.php lists the variables available in `hook_preprocess_page()` and the template file. Between them, there is `$variables['is_front']`, which can be used to determinate when the viewed page is the front page. An implementation of `hook_preprocess_page()` that needs to add CSS files to the front page could use the following code.

```
MYTHEME_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    // The viewed page is the front page: Add the desired CSS file.
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/foo.css");
  }
}

```
> 7 votes

# Answer
You could create a custom module and use `hook_preprocess_node()` to selectively load CSS files based on the node ID.

```
function MYMODULE_preprocess_node($vars) {
  if (arg(0) == 'node' && is_numeric(arg(1)) && arg(1) == 3) {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/foo.css");
  }
}

```

Replace *MYMODULE* with the module name, and *MYTHEME* with the name of the theme containing the CSS file.
> 6 votes

# Answer
For an admin based way of doing it I'd look at the CSS module. It adds a field where you can add *CSS* to the `node/add` and `node/edit` pages.

**CSS:**

> The CSS module adds, for users with enough permissions and enabled nodes, a CSS field on the node creation page.
>
> Users might insert CSS rules in the CSS node field and those rules will be parsed on the node viewing.
>
> This way CSS experienced users might create complex CSS based design for nodes contents.
>
> **Important:** note that the CSS editing permissions should be given only to trusted users (administrators). Malicious users which have this permission might broke your site design and also introduce security issues (XSS).
> 5 votes

# Answer
CodePerNode is great, but CSS Injector is simpler to install (no libraries needed). The module allows the content manager to dynamically add CSS to specific pages, without touching PHP code or INFO files at all. 15777 installs can't be wrong - this is a social proof this module works. The CSS is also cached with the regular caching system.
> 3 votes

# Answer
Since you're already using Panels, it might be easier to to just add your CSS as a Panel Style for each region of your homepage panel. You can define custom markup there and reuse it across your site.

You can also just go to the General section of the page manager variant rule for your homepage. There is a section here for adding CSS IDs and rules for only the current panel.

Note: this is all in D7, so it might be that this approach is better supported by Panels than it was in prior versions.
> 2 votes

# Answer
/\* An example using bartik theme to add css based on content type \*/

```
function bartik_preprocess_node(&$variables) {
if(!empty($variables['node'])) {
    if($variables['node']->type == 'my_custom_content_type')
    {
      drupal_add_css(drupal_get_path('theme', 'any_theme_name') . "/css/foo.css");
    }
  }
  // Some other code here
}

```
> 2 votes

# Answer
Try to add this in your 'template.php' file:

```
function mytheme_preprocess_page (&$variables)
{
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('theme','mytheme'). '/css/front.css');
  }
}

```

Replace 'mytheme' with name of your theme directory and '/css/front.css' with path where is your CSS file.

To unset 'front.css' file from other pages try to add to 'template.php':

```
function hook_css_alter(&$css) {
  if (!drupal_is_front_page()) {
    unset($css[drupal_get_path('theme', 'mytheme') . '/css/front.css']);
  }
}

```

Again, replace 'mytheme' with name of your theme directory.

If you need to unset 'styles.css' from front page just combine these two codes.

Lets assume that you need 'front.css' without 'styles.css' on front page, and 'style.css' without 'front.css' on all other pages. Code will look something like this:

```
function mytheme_preprocess_page (&$variables)
{
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('theme','mytheme'). '/css/front.css');
  }
  else {
    drupal_add_css(drupal_get_path('theme','mytheme'). '/css/styles.css');
  }
}

function hook_css_alter(&$css) {
  if (drupal_is_front_page()) {
    unset($css[drupal_get_path('theme', 'mytheme') . '/css/styles.css']);
  }
  else {
    unset($css[drupal_get_path('theme', 'mytheme') . '/css/front.css']);
  }
}

```

Also, replace 'mytheme'.

I hope this will be helpful.
> 2 votes

# Answer
I would've skipped touching template.php altogether and just add another item in your theme's .info file

Say your stylesheet is in `css/foo.css`.

This is how your theme\_name.info file would look:

```
name = Theme Name
...
stylesheets[all][] = css/foo.css

```

Then you benefit from having it cached with the main stylesheets, and since I'm assuming this is for your homepage it would make sense.
> 1 votes

# Answer
You can print the page node in the body-tag

```
<body page-node-26419 ...>

```

Then you can restrict

```
body.page-node-26419 {
    background: red
}

```

This is useful for minor quick changes
> 1 votes

---
Tags: 7, theming, panels
---


# Question
Title: How does the #submit property works with #ajax?
I'm having trouble understanding how works the `#submit` property of a submit element in Drupal 8, when Ajax is used.

I found this code, as an example of how to implement ajax buttons which add or remove items to/from a form : https://gist.github.com/leymannx/72d41cf0baa4dee62d6ddc89bc7c7a5a

The "add item" submit button in the form is described by the code below :

```
$form['container']['actions']['add_item'] = [
  '#type'   => 'submit',
  '#value'  => $this->t('Add another name'),
  '#submit' => ['::MYMODULE_MYFORM_add_item'],
  '#ajax'   => [
    // Could also use [ $this, 'colorCallback'].
    'callback' => '::MYMODULE_MYFORM_ajax_callback',
    'wrapper'  => 'my-container', // CHECK THIS ID
  ],
];

```

There are 2 callback functions used here : the value of the `#submit` property and the value of `callback` in the `#ajax` property.

What happens exactly when the user clicks on the button ? As I understand it, `MYMODULE_MYFORM_add_item` function is first called, then `MYMODULE_MYFORM_ajax_callback` function.

But, in a custom module, I'm currently doing something like this :

```
// Implementation of hook_form_FORM_ID_alter(), to customize the user register form
function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    // Add a "Fill username" button
    $form['account']['fill_username'] = array(
        '#type' => 'submit',
        '#value' => t('Fill username with Bob'),
        '#weight' => -1,
        '#submit' => ['mymodule_fill_username_submit'],
        '#ajax' => array(
            'callback' => 'mymodule_fill_username_callback',
            'wrapper' => 'edit-account'
        )
    );
}

// #submit function of the button
function mymodule_fill_username_submit( $form, FormStateInterface &$form_state ){
    \Drupal::logger('mymodule')->notice('mymodule_fill_username_submit');
    $form_state->setValue('name', 'Bob');
    $form_state->setRebuild( true );
}

// callback function of the button
function mymodule_fill_username_callback( $form, FormStateInterface &$form_state ){
    \Drupal::logger('mymodule')->notice('mymodule_fill_username_callback');
    return $form['account'];
}

```

The aim is to inject a value in the "Username" field, just to try and understand how this works.

As I click on the button, `mymodule_fill_username_callback` is called (I see the log) but `mymodule_fill_username_submit` never. And, of course, the field is not filled at all...

I don't understand what happens here. Nor how it's supposed to work.

Can anybody help ?

# Answer
I don't think its good idea to handle form submission using the submit\_form function in case of AJAX form. All the form submission logic should be handled in AJAX callback only. https://drupalabc.xyz/question/how-handle-form-submission-using-ajax-drupal-8

The following link has a running example of AJAX form submission in Drupal 8. I hope this helps. Thanks.
> 0 votes

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


# Question
Title: Why is my library not attached when programmatically rendering a block?
I have this block:

```
public function build() {
  $build = [
    '#attached' => [
      'library' => [
        'mymodule/mylibrary',
      ],
    ],
    '#markup' => '<!-- see template -->',
  ];

  return $build;
}

```

Somewhere I am rendering this block via custom text filter:

```
{{ '[embed:block:mymodulemyblock]' | text_format }}

```

This is my text filter that replaces the "token" with the rendered block:

```
public function process($text, $langcode) {
  if (preg_match_all('/\[embed:.+\]/isU', $text, $matchCodes)) {
    foreach ($matchCodes[0] as $index => $token) {
      $parts = explode(':', $cleaned);
      array_splice($parts, 0, 1);

      $entityType = trim($parts[0]);
      $entityId = trim($parts[1]);
      $viewMode = isset($parts[2]) ? trim($parts[2]) : 'full';

      if ('block' == $entityType) {
        $rendered = '';

        if ($block = entity_load('block', $entityId)) {
          $replacement = entity_view($block, 'block');
          $rendered = drupal_render($replacement);
        }
      }
      $text = str_replace($token, $rendered, $text);

    }
  }
  return new FilterProcessResult($text);
}

```

It works fine, except the block's library isnt attached. Not even when I add this inside the **block template**:

```
{{ attach_library('mymodule/mylibrary') }}

```

When I place the block in the block layout it works fine.

Why isnt the library attached?

---

Edit

This is how I register the template for the block itself:

```
function mmodule_theme($existing, $type, $theme, $path) {
  return array(
    'block__mymodulemyblock' => array(
      'render element' => 'elements',
      'template' => 'block--foobar',
      'base hook' => 'block',
    ),
  );
}

```

# Answer
I think it's because attached needs to be a separate element than your markup.

This is one render element for markup, with the attached attached to it:

```
$build = [
    '#attached' => [
      'library' => [
        'mymodule/mylibrary',
      ],
    ],
    '#markup' => '<!-- see template -->',
  ];

```

The correct way to set up a build array is with the markup being a separate element:

```
$build = [];

$build['#markup'] = ['#markup' => '<h1>testing 123</h1'];

$build['#attached']['library'] = ['mymodule/mylibrary'];

return $build;

```
> 0 votes

# Answer
If you haven't figured this out yet, I'm pretty sure that you have to output {{ content }} in your twig template for the block. You can exclude other variables by doing {{ content|without('var1', 'var2') }}. That will ensure the attached library is actually attached.
> 0 votes

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


# Question
Title: theming field collection in node add form
I have themed node/add form of a special content type using the following instruction:

https://www.drupal.org/node/1092122

and I have changed this form to a table.

Now I'm struggling with a field collection with unlimited number of item. As I have hidden the default form of displaying node/add form when I click on 'add another item' of the field collection, nothing happens.

What I want is to show the next form of the field collection as the next row of the table ready for the user to fill it out.

Any help would be appreciated. thanks in Advanced.

# Answer
> 0 votes
You'll need to hook into the field collection entity on insert, and add a callback function to trigger the new row to appear via ajax in your table.

Check out `field_collection.api.php` in the field collection module for a full list of field collection api calls/methods.

Also, you may find the responses to this previous post as a good indicator of the direction to take: Perform actions on field collection insert or update

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


title: Fatal error: Cannot redeclare class

text:
# Question
Title: Fatal error: Cannot redeclare class
I am trying to convert a module from D7 to D8. I had parts of it working earlier but after some code edits i now get:

```
Fatal error: Cannot redeclare class Drupal\delete_fields\DeleteFields in E:\www\drupal8\sites\all\modules\delete_fields\src\Form\DeleteFields.php on line 128

```

when i try to do a cache clear.

128 is the last line of the file and i have searched entire project and the only place DeleteFields shows up is in my module's class file:

```
namespace Drupal\delete_fields;

/**
 * Defines a class to build a listing of fields.
 *
 * @see \Drupal\field\Entity\Field
 * @see field_ui_entity_info()
 */
class DeleteFields extends ConfigEntityListBuilder
{

```

My guess is the class is getting cached somewhere and there is a bug in Drupal which is not letting this get cleared.

I tried drush rr but it seems like this is no longer available (i get command not found); even though it is listed in drush docs.

# Answer
Given your question's source code and namespace, the class code you pasted is located in `delete_fields/src/DeleteFields.php`.

When you compare this with the error message, you will find that you have another `DeleteFields` class in `delete_fields/src/Form`.

Despite the possible different sub-namespaces, this doesn't work in Drupal, as it autoloads all classes of enabled modules into the `\Drupal` namespace and having two loaded classes with the same name within a namespace is not possible in PHP. Therefore your class names should be unique.

Rename your form class to `DeleteFieldsForm` or `DeleteFieldsSettingsForm`, or whatever name describes its purpose and reason for existence best.
> 1 votes

---
Tags: 8
---


# Question
Title: How to add large number of pages to a content type?
I created a content type "cities", with Fields: Title, body, location(text field)

I would like to create about 200 pages for this content type.

I can create manually one by one. It will take a lot of time to do that. Is there faster way I can add the pages by using some bulk load methods?

# Answer
> 1 votes
Use the Devel module, and its `devel_generate` submodule.

Using this submodule, you can perfectly create 200 nodes (with randomly generated content) of any content type.

# Answer
> 1 votes
You can create the nodes from a php array:

```
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;

    $values = [
      'type' => 'my_content_type',
      'title' => 'test title',
      'body' => [
        [
          'value' => 'test body',
          'summary' => '',
          'format' => 'filtered_html',
        ],
      ],
      'field_location' => 'test locatation',
      'status' => NodeInterface::PUBLISHED,
    ];

    $node = Node::create($values);
    $node->save();

```

---
Tags: nodes
---


title: Adding CSS styles to a block

text:
# Question
Title: Adding CSS styles to a block
**UPDATED** *Added other files just in case the error is somewhere else*

I just created a custom module for Drupal 8 that defines a block. I want to add some CSS styles to the content of the block.

My last attempt to achieve this was adding a libraries.yml file to the module linking the block\_header.css file. In the render array, I added #prefix and #suffix with the CSS classes (`<div class='foo'>`).

The code doesn't give me any error, but it's not applying the font weight I would expect.

Could you point me to the right direction?

These are the files.

### block\_header.info.yml

```
name: Block Header creator
type: module
description: 'Create block with a main header and a text on mouseover'
core: 8.x
package: Fussion Corp - Custom Modules
configure: block_header.settings

```

### block\_header.routing.yml

```
block.content:
  path: '/block'
  defaults:
    _controller: '\Drupal\block_header\Controller\BlockController::content'
    _title: 'Block Header'
  requirements:
    _permission: 'access content'

```

### block\_header.libraries.yml

```
block_header:
version: 1.x
css:
    theme:
        css/block_header.css: {}

```

### BlockController.php

```
<?php
/**
 * @file
 * Contains \Drupal\block_header\Controller\BlockController.
 */
namespace Drupal\block_header\Controller;
class BlockController {
  public function content() {
    return array(
      '#type' => 'markup',
      '#markup' => t('Sample Text!'),
    );
  }
}

```

### block\_header.module

```
<?php

/**
 * Implements hook_preprocess_HOOK()
 */
function block_header_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_header') {
    $variables['page']['#attached']['library'][] = 'block_header/block_header';
  }
}

```

### BlockHeader.php

```
<?php

namespace Drupal\block_header\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'Header' Block.
 *
 * @Block(
 *   id = "block_header",
 *   admin_label = @Translation("Block Header"),
 *   category = @Translation("Block Header"),
 * )
 */

class BlockHeader extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();

    if (!empty($config['block_header_title']) && ($config['block_header_text'])) {
      $title = $config['block_header_title'];
      $descp = $config['block_header_text'];
    }
    else {
      $title = $this->t('<div>Atención! Titulo no configurado!</div> </p>');
      $descp = $this->t('<div>Atención! Descripción no configurada!</div>');
    }
    $block = array
        (
            'title' => array
            (
             '#prefix' => '<div class="title"><p>', /* HERE I ADD THE CSS TAGS */
             '#suffix' => '</p></div>',
             '#markup' => t('@title', array('@title' => $title,)),
            ),
            'description' => array
            (
             '#prefix' => '<div class="descp"><p>', /* HERE I ADD THE CSS TAGS */
             '#suffix' => '</p></div>',
             '#markup' => t('@descp', array('@descp' => $descp,))
            ),
        );
    return $block;

  }

   /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['block_header_title'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Titulo del Bloque'),
      '#description' => $this->t('Titulo del Bloque'),
      '#default_value' => isset($config['block_header_title']) ? $config['block_header_title'] : '',
    );

    $form['block_header_text'] = array(
      '#type' => 'textarea',
      '#title' => $this->t('Descripción'),
      '#description' => $this->t('Descripción del bloque'),
      '#default_value' => isset($config['block_header_text']) ? $config['block_header_text'] : '',
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    $this->configuration['block_header_title'] = $values['block_header_title'];
    $this->configuration['block_header_text'] = $values['block_header_text'];
    $this->configuration['block_header_title'] = $form_state->getValue('block_header_title');
    $this->configuration['block_header_text'] = $form_state->getValue('block_header_text');
  }
}

```

This is the structure of the directory containing the module.

>

What am I doing wrong?

# Answer
> 4 votes
Hooks go inside the .module file.

**block\_header.module**

```
<?php

/**
 * Implements hook_preprocess_HOOK()
 */
function block_header_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_header') {
    $variables['#attached']['library'][] = 'block_header/block_header';
  }
}

```

Just FYI, this did not work:

```
    $variables['elements']['#attached']['library'][] = 'block_header/block_header';

```

**block\_header.libraries.yml**

```
block_header:
  version: 1.x
  css:
    theme:
      css/block_header.css: {}

```

# Answer
> 4 votes
The attachment should be on the block itself:

```
$block = [
        '#attached'=> ['library' => ['block_header/block_header']],
        'title' => array
        (
         '#prefix' => '<div class="title"><p>', /* HERE I ADD THE CSS TAGS */
         '#suffix' => '</p></div>',
         '#markup' => t('@title', array('@title' => $title,)),
        ),
        'description' => array
        (
         '#prefix' => '<div class="descp"><p>', /* HERE I ADD THE CSS TAGS */
         '#suffix' => '</p></div>',
         '#markup' => t('@descp', array('@descp' => $descp,))
        ),
    ];

```

And remember YAML is sensitive to white space, make sure your libraries file is formatted correctly:

```
block_header:
  version: 1.x
  css:
    theme:
      css/block_header.css: {}

```

---
Tags: 8, theming
---


title: Migrate creating custom fields

text:
# Question
Title: Migrate creating custom fields
I have 2 server rather than the localhost ex: staging & development. And I am creating custom fields on the local machine and those fields from different types \[entity reference - user reference - image - ...etc\] so how to migrate creating these fields on the other servers\[staging & development\] and even \[production server\] from inside the code, instead of repeating the same process from the Admin of Drupal-7 every time on different server!?

# Answer
You might want to have a look to the Features module.

By creating a feature, you can export entities, fields and many other settings created using the admin UI to a module, that then can be installed to your target site.

You may also consider creating a dedicated custom module that holds all your database-stored settings and pre-populated entities/content (e.g. basic taxonomy vocabularies, user roles, permission assignments, ...) set by code instead of the admin UI.

Every setting you can do within the admin UI can be done by code as well, using according hooks, function calls or database queries. And each time you extend your site and settings, you will add an according update hook to keep sites up-to-date that have your module running already. (Staging / Production)

This approach is considerably difficult for beginners to work with, but once you know how to do it, it's worth the efforts. (Speaking from experience.)

Last but not least, you can always synchronize entire databases. For example using the Backup & Migrate module or manual database exports/imports. You just need to make sure to do your settings on a clean version without test data. This approach starts becoming messy once your site is live, but may suit your needs while you still create it.

In Drupal 8, I'd suggest configuration export/import instead, which makes the entire process of configuration management a whole lot easier.
> 0 votes

---
Tags: entities, migrations
---


# Question
Title: How do I control what to publish as Facebook Instant Articles?
I am using this Facebook Instant Articles module to integrate articles being published as Instant articles on Facebook. I have successfully tried to publish instant articles using the *RSS Feed* and *Views* modules.

When I look at the preview of the feed, the articles being added on the feed are all the articles recently published. This is not what I want. I checked the configuration, and I found out that I have to select each article.

Now, after doing this, I still can't filter out the articles which are selected to be published as instant articles. I tried adding a filter, but I can't add a Filter on my view. I have not yet added custom codes just via the administrative dashboard.

What I want is to freely filter out specific articles I want to publish as instant articles. In my case, the articles processed from the feed are the latest ones; if I edit an article to add it as instant article, it won't be shown.

Can someone help me here?

# Answer
You can for example add a taxonomy to the articles and filter by that in the view.
> -2 votes

---
Tags: 7, views, social-network
---


# Question
Title: How to set default value for taxonomy autocomplete field?
I am using Drupal 7. I have created a content type with autocomplete taxonomy field. I need to set default value programmatically. I am using this code under `hook_form_alter`:

```
$form['field_school_locality_city_level'][LANGUAGE_NONE]['names']['#default_value'] = tid;

```

It's giving me just `term id`, but I need it in format `Bhopal[tid:8193]`.

# Answer
> 3 votes
Load taxonomy term using term id then, generate data in your required format.

```
 // Term id.
 $tid = 8193;
 // Obtain the term.
 $term = taxonomy_term_load($tid);
 // Format data.
 $data = $term->name . '[tid:' . $tid .']';

$form['field_school_locality_city_level'][LANGUAGE_NONE]['names']['#default_value'] = $data;

```

---
Tags: 7, forms
---


# Question
Title: Checkbox value incorrect in custom validation
I have a custom form like this :

```
public function buildForm(array $form, FormStateInterface $form_state){

      $form['first_name'] = [
        '#type' => 'textfield',
        '#title' => t('First name'),
      ];

      $form['t_and_c_accepted'] =[
         '#type' => 'checkbox',
         '#title'=> t('I accept the terms and conditions'),
         '#return_value' => 1,
         '#default_value' => 0,
      ];
 }

public function validateForm(array &$form, FormStateInterface $form_state){

          $values = $form_state->getValues();
          if(empty($values['first_name'])){
             $form_state->setErrorByName('[first_name]', t('Fill in a first name'));
          }

          if($values['t_and_c_accepted'] !== 1){
             $form_state->setErrorByName('[t_and_c_accepted]', t('Accept the t&c's);
          }
    }

```
1. If I uncheck the checkbox and submit the form, it gives me an error about the unchecked checkbox, as expected.
2. If I check the checkbox, leave the first\_name empty and submit the form, it gives me an error that my fist\_name is empty, as expected.
3. But if I then fill in first\_name, UNcheck the checkbox an submit. The validation passes! So not as expected.
4. If I then go back to the form (back from my landing page), I can reiterate this sequence

I have monitored the `$form_state->getValue('t_and_c_accepted')` value throughout my tests and it gives me indeed `value=1` during the unexpected behavior. So it is consistent with what I see, but I have absolutely no idea what's going on.

So any help would be appreciated

**Update:** When looking into the http headers I see that the browser does the POST request with form data `t_and_c_accepted:1` while the checkbox is unchecked.

So Drupal's form api seems to handle the request correct, but why does the browser doesn't post the correct checkbox status value ?

# Answer
ok, I've found the cause of the issue: I rendered `$form['t_and_c_accepted']` twice in the twig template which caused the browser to post a value that was different from the checkbox that was visible.

So it was my own mistake but I answer this question anyway in case anyone else would be wasting time solving the same issue
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Redirection after adding new groups and gnodes using group module
I am using **Group module** and Drupal 8.

1. After adding a new group, the page will be redirected to the corresponding group page(ie. /group/5) but I want to change it to be the **group edit page** (ie. /group/5/edit)
2. After relating/creating an entity in group, the page will be redirected to the gnode page (ie. /group/5/content/116) but I want to change it to be the **group content page** (ie. /group/5/content)

I have read this issue but I want to solve this problem using either installing modules or creating a custom module.

I am new to Drupal and programming so it is great to have some clear and complete elaboration.

Thanks!

# Answer
> 0 votes
**If The issue you posted about promises to solve your problem** then your best bet would be to test the patch (always on a test server) and help this issue forward so others can take advantage of that in the future, because this is how drupal progresses mostly.

Just download the latest .patch that you find in the group modules directory and open up up a command window (in windows) or shell in linux based systems and apply the patch

in a linux based system you could run the following commands, assuming group is in `modules/contrib/group` and using latest patch as an example

```
cd modules/contrib/group
wget https://www.drupal.org/files/issues/2817109-by-rachel_norfolk-ericras-How-to-redir.patch
git apply -v 2817109-by-rachel_norfolk-ericras-How-to-redir.patch

```

If the patch does not report any errors you will probably get a configuration field to do what you are asking and it would be great to post in the thread how the patch went for you.

More on patches here

**If you want something different** you should create your own module and implement a `hook_form_alter` to set `setRedirect` for both of the forms that you mention similar to what `rachel_norfolk` does in comment #3

---
Tags: 8, redirection, group
---


title: How to use variable value in twig file?

text:
# Question
Title: How to use variable value in twig file?
I have below code in:

```
{% set img_url = item.image.url ? item.image.url : {{ base_path ~ directory }}'/images/default.png' %}

```

Twig file. How to make it work so it will take full default image path?

# Answer
To get the `base_url` (path) you will need this in your `THEMENAME.theme` file

```
function THEMENAME_preprocess_page(&$variables) {
  global $base_url;
  $variables['base_path'] = $base_url;
}

```

Then it will be available in your twig template

But most of the times you will not need the full path to display an image

You can try the following

```
{% set img_url = item.image.url ? item.image.url : '/'{{ directory }}'/images/default.png' %}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Using `hook_field_attach_presave` for replacing characters
In Drupal 7, I used hook\_field\_attach\_presave() to replace characters of a body field in the moment when the node is saved. Now i want to use the code for Drupal 8, but could not get it to work:

```
function my_module_field_attach_presave($entity_type, $entity){
  dpm($entity);
  $replacement_pattern = '/(?<=\d\ )x(?= \d)/'; // replace a "x" surrounded by numbers with symbol "×"
  if(!empty($entity->body->value)){
    $entity->body->value = preg_replace($replacement_pattern, ' × ', $entity->body->value);

```

} The above code does not work, not even the dpm($entity) is printed. What is the problem here, is the hook not available in D8? I just found it here, not on official drupal sites. So if it does not exist, what's the alternative?

EDIT: Thanks to @Clive I got it working. Here's the code:

```
function my_module_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->setTitle('dd The new Title');
  $replacement_pattern = '/(?<=\d\ )x(?= \d)/';
  if(!empty($entity->body->value)){
    $entity->body->value = preg_replace($replacement_pattern, ' × ', $entity->body->value);
  }
}

```

# Answer
> 2 votes
`hook_field_attach_presave()` was removed some time ago, there's no such operation in Drupal 8.

You can, however, use `hook_entity_presave()` or `hook_ENTITY_TYPE_presave()` instead.

---
Tags: 8, hooks
---


# Question
Title: How to properly redirect users to their own pages from 404 or 404 error pages
Instead of using one of multiple contributed modules, which deal with redirections from error pages, I'd like to simply redirect users from the pages with other users uids in the path they tried to access to exactly the same pages, but with their own uids.

For example, if a user with uid '3' tried to access a page with the path `ssh-keys/user/4/add` then she should be redirected to `ssh-keys/user/3/add`. To achieve the goal I composed the following simple function:

```
function return_users_page_alter(&$page) {
  $current_path=(current_path());
  // make sure we have 'user' in path.
  if (strpos($current_path, 'user') !== false) {
    global $user;
    // exclude site team members.
    if (!in_array('administrator', $user->roles) && !in_array('support', $user->roles) && !in_array('billing', $user->roles)) {
        $path_items=explode('/',$current_path);
        foreach ($path_items as $key => $value) {
          if ($value == 'user') {
            $found_uid = $path_items[$key+1];
            break;
          }
        }
        // If user is really different one.
        if ($user->uid != $path_items[$key+1]) {
          $redirect = str_replace($path_items[$key+1], $user->uid, $current_path);
          drupal_goto($redirect);
        }
      }
    }
  }

```

but, unfortunately, it doesn't work. What is wrong with my code?

# Answer
> 0 votes
After reading Clive's comments on 7 - drupal\_goto() ignores $path if $\_GET\["destination"\] is set?, I've added added `unset($_GET['destination']);` just before `drupal_goto` command and it works now fine:

```
      unset($_GET['destination']);
      drupal_goto($external, array('external' => TRUE));

```

---
Tags: redirection
---


# Question
Title: Want to Display latest node on the basis of taxonomy term
Actually I want to display latest node on the basis of taxonomy term.. Suppose I created a vocabulary called event. With field

```
1. Term name
2. Description
3. Image
Now I have a node with following field
1. Title
2. Term reference field reffering event
3. Event date.

```

Now I want to display exactly 1 latest node basis of term name.. Suppose I have 3 term so I want to display latest 1 node for each term.. using view.

Please help me on that thank you..

# Answer
If I'm understanding correctly, you'll want to create a View for your event nodes, and then add a relationship to the "Event category" or whatever your term reference field is called on the node. You should then be able to add a sort by Event date descending, and a filter for the "Term name" that should be available through the relationship you've added. You could limit your results to 1 node only in the pager settings in Views. Then you should have the latest event for a specific term.
> 0 votes

---
Tags: views
---


# Question
Title: How do I include my libraries in a theme?
This is a continuation of a previous question I was asked to open as a new question with all of my changes incorporated. I'm trying to use an Angular front end as my theme, but despite following the docs, no GET requests are being made, so the files aren't being rendered.

ng.info.yml

```
name: ng
type: theme
base theme: classy
libraries:
  - ng/base
  - atlas/global-css
  - atlas/global-js
description: 'An theme that makes Angular do all the work'
core: 8.x

```

ng.libraries.yml (attempt 1)

```
base:
  version: 8.x
  css:
    dist/styles.bundle.css: {}
  js:
    dist/inline.bundle.js: {}
    dist/polyfills.bundle.js: {}
    dist/vendor.bundle.js: {}
    dist/main.bundle.js: {}

```

ng.libraries.yml (attempt 2)

```
base:
  version: 8.x
  css:
    theme:
      dist/styles.bundle.css: {}
  js:
    theme:
      dist/inline.bundle.js: {}
      dist/polyfills.bundle.js: {}
      dist/vendor.bundle.js: {}
      dist/main.bundle.js: {}

```

templates/html.html.twig

```
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Hand of Death</title>
    <!-- Set base href for Angular routing -->
<script>document.write('<base href="' + document.location + '" />');</script>
    <meta name="description" content="A D.I.Y. record label for heavy music.">
    <css-placeholder token="{{ placeholder_token }}">
    <js-placeholder token="{{ placeholder_token }}">
  </head>
  <body>
    <app-root></app-root>
    <js-bottom-placeholder token="{{ placeholder_token }}">
  </body>
</html>

```

However, if I hardcode the the JavaScript and CSS into `html.html.twig`, the browser makes the GET request, succeeds, and the page renders fine.

# Answer
> 0 votes
You have an error in each of the libraries.yml attempts.

The first is missing the extra level for CSS. The second is adding an *extra* level to the JS, which shouldn't be there.

In either case the correct version is:

```
base:
  version: 8.x
  css:
    theme:
      dist/styles.bundle.css: {}
  js:
    dist/inline.bundle.js: {}
    dist/polyfills.bundle.js: {}
    dist/vendor.bundle.js: {}
    dist/main.bundle.js: {}

```

Other than that the code is fine (assuming the files are located at theme\_name/dist/\*); if your Angular app isn't working check the HTML source and see what's different between your static working version and the version in Drupal, and add some debugging code to the application.

# Answer
> 0 votes
It sounds like you may have implemented this in a technically correct way already, per the Drupal docs (https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme) :

> In the case of front-end/styling (e.g. hosted font services), the JS belongs in the theme. Put the JS directly in your html.html.twig file. In the case of fonts, this will also allow you to put it right in the place that gives you the best (and fastest) end user experience, because it allows you to prevent a FOUT (Flash Of Unstyled Text) while the font is still loading (fonts loaded through JS must be listed in the HTML before the CSS)!

Potentially you could also look at using a `hook_page_attachments_alter()` per the other Drupal.org article: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module:

> In the other case, the JS belongs in the module. In the appropriate hook — likely hook\_page\_attachments() — define attached HTML data by using the 'html\_head' key in the #attached property:

```
function fluffiness_page_attachments(array &$attachments) {
  $attachments['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // The value of the HTML tag, here we want to end up with
      // alert("Hello world!");.
      '#value' => 'alert("Hello world!");',
      // Set attributes like src to load a file.
      '#attributes' => array('src' => ''),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world',
  ];
}

```

---
Tags: theming, javascript
---


title: Base URL/Domain problem

text:
# Question
Title: Base URL/Domain problem
I moved a Drupal site to a development domain, but for some reason none of the menu links have updated. For example, in the main menu, one of the links is www.example.com/product. I would expect it to change to www.devdomain.com/product after moving it to my dev domain, but it doesn't.

Similarly, even the links in the Seven admin theme still point to www.example.com (my live site) instead of the dev domain. So clicking "Structure", for example, tries to route me back to the live site.

Anyone ever experience this and know how to solve? There are no references to base\_url in my settings.php file for this site, and I am not using the trusted host patterns setting (though I have tried with and without).

A few other things I have tried:

* running update.php
* drush cr
* searching for instances of example.com in codebase (there are none)

Any help on this would be appreciated.

# Answer
> 1 votes
Turns out multilingual modules were on, and using URL detection. When that is set, the URL for the particular language you are looking at gets inserted into all links.

---
Tags: 8, uri, migrations
---


# Question
Title: Is there a way to get (and use) an environment variable in a template file?
I would like to add a JavaScript call to my `html.html.twig` file, but there are two separate .js sources depending on which environment I'm on (production, and non-production). I believe Acquia Cloud (which we use) provides such variables, but they are for PHP.

I'm still relatively new to Drupal 8, so I might be missing something obvious with this. Is there a way to use Acquia Cloud's environment variables in a template file?

I forgot to mention that I tried accessing the environment variables from a few preprocess functions, for example `themename_preprocess_html()` and `themename_preprocess_page()`, but they are apparently not set at all.

# Answer
> 1 votes
So I guess my problem was that I was on a Local environment, where Acquia does *not* provide any environment variables. I had to push my test code to Dev in order to see any effect.

---
Tags: 8, theming
---


# Question
Title: How to get granted and expires fields of commerce license updated?
I have similar problem as described on Commerce License Billing: How do I charge or refund a prorated amount when the user's plan changes and the billing cycle is prepaid? by @wizonesolutions, but with different goal.

On a Drupal 7 website with the Commerce License Billing module used for subscriptions, the changing subscriptions plan by saving the new product\_id on the license entity ($license-\>product\_id) does in fact update the license and the due amount on the next recurring payment order, however, it does not update the `granted` and `expires` fields of the license.

So I tried to get those fields' values from the license, make my calculations and save them together with the whole license entity like so:

```
$bct=$form_state['storage']['target_product']->cl_billing_cycle_type[LANGUAGE_NONE][0]['target_id'];
    if ($bct == '1') { // hourly
      $target_date = strtotime('+1 hour', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } elseif ($bct == '2') { // daily
      $target_date = strtotime('+1 day', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } elseif ($bct == '3') { // monthly
      $target_date = strtotime('+1 month', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } elseif ($bct == '4') { // quarterly
      $target_date = strtotime('+3 months', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } elseif ($bct == '5') { // biannually
      $target_date = strtotime('+6 months', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    } else { // biannually
      $target_date = strtotime('+1 year', REQUEST_TIME);
      $license[arg(1)]->expires = $target_date;
    }
    $license[arg(1)]->granted = strtotime("now");
    $license[arg(1)]->product_id = $form_state['storage']['selected_plan'];
    entity_save('commerce_license', $license[arg(1)]);
    drupal_set_message('License has been updated.');

```

And the `admin/commerce/licenses` page after saving the license entity shows that all the relevant fields - new product\_id, granted and expired fields have been in fact updated.

But the problem is that when expire time comes, the `granted` field reverts back to initial value and the `expired` field's value is calculated based on the initial `granted` field.

In other words, guess I have two billing cycles - hourly and daily - and if an initial order is placed with hourly billing cycle, then license with the following fields is created:

```
Cycle: Hourly
Granted: 15 January 2018 - 17:50
Expires: 15 January 2018 - 18:50

```

If I update the license with the new product id, granted and expires field then the `admin/commerce/licenses` shows:

```
Cycle: Daily
Granted: 15 January 2018 - 17:52
Expires: 16 January 2018 - 17:52

```

And when 16 January 2018 - 17:52 comes and all the relevant cron tasks are processed then the same page shows:

```
Cycle: Daily
Granted: 15 January 2018 - 17:52
Expires: 15 January 2018 - 20:48

```

Meanwhile bunch of extra orders are charged and the new recurring order with `Recurring: Open` status are created and then only the license admin page showing the granted and expires fields (with values behind from 16 January 2018 - 17:52) constantly changing with every cron execution:

```
Cycle: Daily
Granted: Active 15 January 2018 - 17:52
Expires: 16 January 2018 - 01:48

```

So my question is:

If changing the values for the `granted` and `expires` fields in license entity does not take effect, where else I should be looking for changing those values?

# Answer
> 0 votes
After monitoring how database tables change with recurring products, I've noticed that saving license with the new data was not sufficient and that the `cl_billing_cycle` should also be updated with the new granted and expire dates.

I am doing that with a direct database query for now. Let me know if there is a better way to update the `cl_billing_cycle`.

---
Tags: commerce
---


# Question
Title: How to get Webform Field data for a custom module?
I'm trying to set up a view permission based on a webform field. I've been able to get to my custom module using hook\_webform\_submission\_access().

So I have an email field in the webform, and I want to check that based on the current user's email address. Should be pretty simple, I just can't get the field data. Anyone know?

Example:

```
if ($submission->data['field_email'] == $user->mail)

```

What is the correct syntax instead of $submission-\>data\['field\_email'\]

I'm on Drupal 7 and Webform 4.x branch.

# Answer
> 1 votes
Provided Token is installed, you can use token\_replace to access Webform submission values by field name.

```
$email = token_replace('[submission:values:email]', array('webform-submission' => $submission));

```

Note: The Devel module can be useful for exploring object properties and tokens (among other things).

---
Tags: 7, webforms
---


# Question
Title: Where to put a personnalized copy of a layout from layout_discovery?
I want to personnalised core/modules/layout\_discovery/layouts/twocol/layout--twocol making a copy of it renamed with a suggested name in the display mode but I don't know where to put it in my subtheme of Bootstrap... I've tried different places, but none worked...

Any help will be appreciated.

Drupal 8.4.3.

# Answer
I putted my layout in drupal\themes\mytheme\layouts\twocol\layout--twocol--node-end-of-a-suggested-name.html.twig and declare it in a mytheme.layouts.yml file at the root of my theme and it worked.
> 1 votes

---
Tags: theming
---


# Question
Title: Reuse images in articles with file_field_sources module
I would like to reuse the already posted images in the articles of my blog.

I am using the core field\_image in articles and when I installed the file\_field\_sources module, there were no options in my "content type -\> manage fields" page.

Is this module able to use / extend the core field\_image?

# Answer
> 1 votes
IMCE is an image/file uploader and browser that supports personal directories and quota. https://www.drupal.org/project/imce

---
Tags: entities, media
---


# Question
Title: How can I display the block only to the content types and a specific page?
**Created a content type.**

Name: Cities we serve

Machine name: cities\_we\_serve

**Created a page using views.**

Page URL: examplesite.com/blog

**Created a block.**

I would like to display the block to the above content type and the views pages.

Edited the block as follows:

```
$nodeType = "Cities We Serve";

// valid node id in view mode
if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE ) {
    $node = node_load(arg(1)); // cached
    if ( ($node->type == $nodeType) OR ($node->nid == blog) ) {
        return TRUE;
    }
}
return FALSE;

```

Now I see the block on all pages. How can I display the block only to the content types and the blog pages?

# Answer
> 2 votes
There is another way to answer your question, ***without PHP in the block settings***: you can use the Rules block visibility module for this. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the appropriate menu block is shown on the appropriate pages). And combine this with a check in such rule for your specific content type ("*Cities we serve*").

For an illustration of how to use this module, refer to my answer to "How to show blocks by url, when nodes have multiple paths?". It includes some Rules Components (in Rules export format), which you should replace by your variations to make it match your specific question.

To actually "*determine the path structure in rules*", you might want to use a Rules Condition using a regular expression. Similar to the Rules Condition in the rule I included in my answer to "How to automatically skip intermediate redirects?".

Using regular expressions opens up many more situations (on top of the Rules block visibility module) where this solution can work. If you're not familiar with Regular Expressions (not obvious ...), then maybe you also want to look at my answer to "How do I suppress a warning or error message for site users?".

### Bonus:

This approach ***does NOT require the PHP filter to be enabled*** either (which you should try to avoid whenever possible) ... Refer to "PHP in database: bad practice but" for more details about this.

# Answer
> 0 votes
Not a very polite solution, but you can create 2 "cloned" blocs and set content type condition in one of them, and a path condition in the second.

You can, also, use context module, but I think this manage all your blocks.

Ps: I'm sure you can look for a php code to do it if you prefer not use 2 blocks.

---
Tags: 7, blocks
---


# Question
Title: Migrating content type with different translations/languages
I'm currently migrating a specific content type that has 16,000 nodes with different translations (english, french and spanish). After entering commands `drush ms`. It's only showing only half what is currently inside.

```
Group: Import from Drupal 7 (migrate_drupal_7)  Status  Total  Imported  Unprocessed
upgrade_d7_node_press_release                   Idle    6042   0

```

---

I tried importing those nodes for my curiosity and it only shows the english translations. Is there a way I can migrate all of those nodes with mixed translations.

Here is the YML configuration.

```
uuid: 9b022d2e-a1ab-40a4-ab72-4042222dc24b
langcode: en
status: true
dependencies: {  }
id: upgrade_d7_node_press_release
class: Drupal\migrate\Plugin\Migration
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
migration_group: migrate_drupal_7
label: 'Nodes (Press Release)'
source:
  plugin: d7_node
  node_type: press_release
process:
  nid: tnid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  comment_node_press_release/0/status: comment
  body:
    plugin: get
    source: body
  field_date_publish:
    plugin: sub_process
    source: field_date_publish
    process:
      value:
        plugin: format_date
        from_format: 'Y-m-d H:i:s'
        to_format: 'Y-m-d\TH:i:s'
        source: value
  field_image:
    plugin: sub_process
    source: field_image
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height
  field_region_country:
    plugin: sub_process
    source: field_region_country
    process:
      target_id: tid
  field_themes:
    plugin: sub_process
    source: field_themes
    process:
      target_id: tid
  field_pbn_additional_items:
    plugin: get
    source: field_pbn_additional_items
  field_pbn_file:
    plugin: sub_process
    source: field_pbn_file
    process:
      target_id: fid
      display: display
      description: description
  field_pbn_analysis:
    plugin: get
    source: field_pbn_analysis
  field_tags:
    plugin: sub_process
    source: field_tags
    process:
      target_id: tid
  field_default:
    plugin: sub_process
    source: field_default
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height
  field_multimedia: field_multimedia
  field_press_release_type:
    plugin: sub_process
    source: field_press_release_type
    process:
      target_id: tid
destination:
  plugin: 'entity:node'
  default_bundle: press_release
migration_dependencies:
  required:
    - upgrade_d7_user
    - upgrade_d7_node_type
  optional:
    - upgrade_d7_field_instance
    - upgrade_d7_comment_field_instance

```

# Answer
You have to create a YML configuration file for each language and add as migration\_dependencies the original language YML configuration file wich is english in your case "upgrade\_d7\_node\_press\_release":

```
migration_dependencies:
  required:
    - upgrade_d7_node_press_release

```
> 1 votes

---
Tags: drush, migrations
---


# Question
Title: Addressfield: format US state as two letter abbreviation?
Using Drupal 7 with Address Field module. How do I get the US state (i.e., the administrative\_area) to show as a standard two letter abbreviation rather than the full state name?

What shows now is:

```
123 Main St
Somewhere, Florida 12345

```

I want the node to show:

```
123 Main St
Somewhere, FL 12345

```

**UPDATE**

In address.inc in the addressfield module files, there is a function `addressfield_format_address_generate` which defines an '#options' array of all the different states (an associative array with 2-letter state abbreviations as the keys and state names as the values).

In addressfield.module, there is a function `_addressfield_render_address` which I believe checks if there is an '#options' defined and if so, tries to get the value for the given key.

So it would seem if I want to change this behavior I somehow need to override `_addressfield_render_address`

# Answer
> 1 votes
As part of this commit, U.S. states (and other countries' administrative areas) will now use their two letter abbreviations when rendered in address formats. Additionally, we now properly provide a comma between the city and state.

Additional code to get this format will no longer be required as of Address Field 7.x-1.0-beta4.

# Answer
> 0 votes
One way to do this is

* Go to the address field and then "Rewrite Results".
* Select "rewrite the output of this field" checkbox.
* There in the text area provided, you can construct the result you want using "Replacement Patterns". The pattern for state is \[your\_field\_name-administrative\_area\]. The patterns for all the fields will be available by clicking "Replacement Patterns"

This will be required only for a few countries for the states are defined in address.inc

# Answer
> 0 votes
Addressfield can be extended with ctools based plugins.

However, rather than a writing a whole addressfield plugin, it is worth trying a simpler hook\_ctools\_plugin\_post\_alter

That way it may be possible to preserve the default plugin definition and adjust the render callback only.

For example:

```
function EXAMPLE_ctools_plugin_post_alter(&$plugin, &$info) {
  // Override a function defined by the plugin.
  if ($info['type'] == 'address') {
    $plugin['render callback'] = 'EXAMPLE_format_address_render';
  }
}

```

Clone, as a base for the render function \_addressfield\_render\_address(&$format, $address) {}

I hope that helps!

# Answer
> 0 votes
I have shared some snippets for formatting addressfields on the new DropBucket site. One of them formats states as two letter abbreviations:

Show US State as a 2 letter abbreviation: http://dropbucket.org/node/60
Show only street address and city: http://dropbucket.org/node/229

# Answer
> 0 votes
In Drupal 8, showing the abbreviation of the administrative area (in my case for a state in the Unite States)in views can be done using a similar approach to what Varshith described above:

1. Under the field list, click "Add"
2. Add the entire address field, not just the administrative area.
3. For documentation purposes, you will likely want to add the label of "state" to this field to remind yourself later what you are displaying.
4. Open the "Rewrite Results" section.
5. Check the "Override the output of this field with custom text" box.
6. Scroll down and expand the "Replacement patterns" section.
7. Find the token that ends with "== Raw administrative\_area." It should look {{ \__administrative\_area }}
8. Copy the token into Text area directly underneath the "Override the output of this field with custom text" check box.
9. Click Apply to save the field.

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