# Question
Title: Where can I get a list of all the Views handler properties when building my own Views handler?
I'm learning about Views handlers and need some clarification on how its built.

Looking through the Views Bulk Operations module as seen below. There are 2 IF statements that checks for **base table** name and **revision table**. Now my questions are:

* When it says table, are they referencing to a table name in the database?
* title, group, help, etc... where can I find a list of other parameters for this as seen below in the screen shot?
* These fields show up when you click on the "add field" button in the View, but what dictates if it shows up in a *content* type or *user* type view?

# Answer
> 0 votes
> When it says table, are they referencing to a table name in the database?

Often yes, but not always. A Search API index View declares a "table", for example, but if Solr etc. integration is enabled, it won't necessarily be talking to a database/table. A lot of the time though, yes, a "table" tells Views the base table to select data from; the `FROM` part of the SQL query.

> where can I find a list of other parameters for this as seen below in the screen shot?

The `hook_views_data()` API docs walk you through all the possibilities in comments and code.

> These fields show up when you click on the "add field" button in the View, but what dictates if it shows up in a content type or user type view?

The loop in the code you've shown, combined with the condition immediately after. All entity types are looped over, and if their known Views data has a base and/or revision database table, a new field is added to provide operations (because VBO knows it can process those "tables").

---
Tags: 7, views
---


# Question
Title: How to selectively disable CKEditor on specific pages?
On a site I am developing, I have installed and enabled CKEditor version 7.x-1.13.

On two of the pages, I need to completely disable the editor from being active when accessing the admin to edit the page.

I am not sure how I can do that. The only thing I have been able to do is either enable or disable the editor globally.

Can someone point out to me how I can get this done?

# Answer
AFAIK, you can only control *access* to the wysywyg editor on a per-user basis, not on a per-node basis. If the user shall be allowed to use the wysywyg editor in general (but be banned from doing it only on *specific* pages, you need to create write PHP-code that prevents the user selecting the wysywyg text format on the pages were this shall not be allowed).

What you can control on a per page/node basis is the *default* editor.

To not make the wysywyg *default* for an existing page, open up the page as Admin, locate the box labeled "Text format" below the main edit area, and select a format (e.g. "Plain text" \*) that has not been set up to use wysywyg.

Save the node. Wysywyg will no longer be default when it is reopend for editing (but it can be selected).

However: If that user has global access to at least one text format tied to wysywyg, he or she can *restore* the wysywyg for that page at will.

To stop the user from doing this, you must prevent the user from changing the text format. You can do this by using `hook_form_alter()` to remove the pull-down menu that changes the text format for the node edit form.

---

\*) If you want something more advanced than "Plain text", and the "Filtered HTML" (for instance) format has been assigned to wysywyg, just clone the text format you want to use, but do not set it up to use wysywyg.
> 0 votes

# Answer
You can solve this problem by preventing CKEditor module from loading CKEditor based on your conditions.

The condition can be anything, permission, page URL or arguments etc....

CKEditor load by adding pre render callback for text format element using hook\_element\_info\_alter.

You just need to do is to take that callback off.

here is example code for disabling the CKEditor module in any page has 'add' as 2nd argument.

```
function example_element_info_alter(&$types) {
  if (arg(1) == 'add') {
    $key = array_search('ckeditor_pre_render_text_format', $types['text_format']['#pre_render']);
    if ($key !== FALSE) {
      unset($types['text_format']['#pre_render'][$key]);
    }
  }
}

```
> 0 votes

---
Tags: 7, wysiwyg
---


title: Block cache not clearing on save?

text:
# Question
Title: Block cache not clearing on save?
I have some custom block types that display in a region in my site. I have noticed that when changing the contents of these blocks, like an image, text, or title, that when you save and visit the page, the block data is cached and doesn't show the new changes. This is problematic because the client keeps reporting this as a bug, but I can't see where or why it won't update.

Is there a way to have it invalidate when saving a block so that a cache clear isn't necessary? I figured this would be normal behavior, but I have to clear it (while logged in as UID 1 even), and I don't *think* I am doing anything weird or have a contrib module installed that would interfere with this.

Edit: I am *not* using Panels or anything - this is core block.

# Answer
> 13 votes
The problem is, that the cache tag `block_content:[id]` does not bubble up and the tag is missing in the cache entry. Without this cache tag the cache entry can't be invalidated when saving a modified custom block.

Here are two workarounds:

**Twig template (Workaround 1)**

If you theme a block template and you render single fields

```
{{ content.field_field1 }}
{{ content.field_field2 }}

```

then you also need to render the rest of `content`:

```
{{ content|without('field_field1', 'field_field2') }}

```

That's because `content` contains the cache tag of the block content entity, which otherwise won't bubble up.

**Preprocess (Workaround 2)**

As an alternative option for rendering `{{ content }}` you can add the cache tag at the top of `variables` in preprocess.

*mytheme.theme*

```
function mytheme_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'block_content') {
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, $variables['content']['#block_content']);
  }
}

```

Then you no longer depend on the twig template to render all of `content`.

You'll find in `Drupal\block\BlockViewBuilder::preRender()` more workarounds for issues with bubbling up data from the content render array. You could use this code, which there is only applied in special circumstances, for all cache data from block content to bubble up to the top level:

```
use Drupal\Core\Cache\CacheableMetadata;

function mytheme_preprocess_block(&$variables) {
  $content = $variables['content'];
  CacheableMetadata::createFromRenderArray($variables)
          ->merge(CacheableMetadata::createFromRenderArray($content))
          ->applyTo($variables);
}

```

But I don't know which side effects that would have in other places. If it would be that easy the block view builder would do this already. So it's better to tackle only that specific problem with the one missing tag and use the first version of the preprocess function.

# Answer
> -1 votes
Setting cache max age to 0 saved my day.

```
function MODULE_NAME_preprocess_block(&$variables) {
    if ($variables['base_plugin_id'] == 'block_content') {
        $variables['#cache']['max-age'] = 0;
    }
}

```

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


# Question
Title: Is there any way to force a custom block in the Custom Block Library to invalidate cache on edit update?
I have created custom blocks in the Custom Block Library and placed instances of the blocks on a page in Block Layout. The blocks get cached for anonymous users.

Editing the custom block and saving does not invalidate the cache for those instances of the blocks. Looking in the "cache\_render" table I see that caches for blocks get created through the Custom Blocks Library are set to never expire as a default with no options I can see available in the admin UI.

I have to actually "Flush All Caches" using the Devel module to have the changes appear, or another way I have found is to go to the Block Layout page and click the "Save Blocks" button without changing anything. The cahces for all the blocks will invalidate.

I don't want to give access to Devel to an average content manager or have to try to explain that they have to do a non-obvious extra step to have their block content changes appear. Am I missing a setting in the UI that will invalidate the cache of those blocks on edit save?

I can cobble together a module that would add an extra submit handler that would invalidate the cache using `\Drupal::service('cache_tags.invalidator')->invalidateTags()` if I can get the cachetags for all instances of the block on save ... but I'm not sure how to get that info, and that just seems like a hack.

I'm hoping I'm just missing something.

# Answer
I came across this question in the related questions sidebar on my question that seems to be the same issue with out-of-the-box core blocks: Block cache not clearing on save?

The accepted answer from @4k4 on that question seems to confirm the issue, but doesn't hook in to the block save to invalidate the cache like I was thinking, but mentions, as one possible workaround, adding this to the theme:

```
function mytheme_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'block_content') {
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, $variables['content']['#block_content']);
  }
}

```

I don't know if this is the best answer, but it's simple and straightforward and seems to work at the moment, though it's a wonder that this would need to be done at all. It's probably less of a hack than what I was thinking.
> 1 votes

# Answer
Setting max age to 0 saved my day

```
function MODULE_NAME_preprocess_block(&$variables) {
    if ($variables['base_plugin_id'] == 'block_content') {
        $variables['#cache']['max-age'] = 0;
    }
}

```
> 1 votes

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


# Question
Title: Config import constantly showing configs to import
Recently after doing a config import via drush (`drush cim sync`), the config files don't seem to import properly, as the files are listed after a supposed successful import. (and doing a `cex sync` shows configs to export, despite nothing being changed in the backend)

The only thing I have done recently is import a copy of a database from one of our live test servers, to get the content.

Is there a UUID I need to change or something?

# Answer
Check that the UUID of the remote and local drupal sites match.

```
drush config-get "system.site" uuid

```

You can also get the id from the remote site, by looking into `system.site.yml` of your config folder you are trying to import.

To set your local UUID use drush

```
drush config-set "system.site" uuid "UUID-GOES-HERE"

```
> 1 votes

---
Tags: 8, drush, configuration
---


title: Path aliases don't work

text:
# Question
Title: Path aliases don't work
We are running Drupal 7 on NGINX. The config has worked fine except that path aliases are ignored. When we navigate there, we get a "file not found" page instead of a redirection to the node.

Clean URLs work fine -- the site navigation using clean URLs works perfectly. It's just the aliases that are not working. We used this config example as the basis for the setup: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/

Any ideas on what we're missing?

# Answer
> 1 votes
If you just add the following snippet under -\> location ~ '.php$|^/update.php' {

```
#Redirect urls with php extension
if ($request_uri ~ .*.php.*) {
        error_page 404 =  @rewrite;
}

```

that should get it to work! It's basically telling nginx how to handle urls with .php extension.

And then restart nginx

```
sudo service nginx restart

```

---
Tags: path-aliases
---


# Question
Title: subtheme preprocess functions inheritance
I'm using Drupal 7 with Boostrap Theme.

I put the main theme inside `sites/all/themes/` And as a recommanded I put sub-theme in `sites/my-site.com/themes/`

It's working fine but my question is about preprocess hook.

The main theme using `bootstrap_preprocess_region()` to add some attributes to regions. In my subtheme, I want to alter attributes of a region already "hooked" by main theme.

So, in my sub-theme `template.php` file I did

```
<?php
mytheme_preprocess_region(&$variables){
$region = $variables['region'];
switch ($region) {
 case 'header':
 $variables['attributes_array']['id'] = 'main-header';
 break;
}
?>

```

But there is no effect in my output ; main theme preprocess function is called *after* my subtheme preprocess function :( (I dumped string inside each preprocess to see which is called first)

Is that normal ? Is there a global workaround ?

# Answer
EDIT : solution (can't answer myself before 8hours after posting)

Ok for those who're interested in the why :

It's a "side effect" of Twitter Bootstrap theme specific loader (\_bootstrap\_theme(), bootstrap\_include ...)

To respect the correct order of hook processing, we have to keep the same filename as the main theme where hook is located in. (directories tree could change)

In my case, bootstrap\_preprocess\_region() was located in `\sites\all\themes\bootstrap\theme\system\region.vars.php`, so to overwrite it the `mytheme_preprocess_region()` should not be in my subtheme `template.php` file (=\> breaking order of processing)

It should live in `\sites\my-site.com\themes\mytheme\(opional folder)\(optional folder 2)\region.vars.php`

Not explicitly written in TBS documentation I think ...

I hope this could help someone one day ! (:
> 1 votes

# Answer
The Drupal 7 Atomium base theme also has this mechanism and some other goodies.
> 0 votes

---
Tags: theming
---


# Question
Title: Which function should I use to update a node through the comment form?
I use this function to synchronize a comment field with the value from a field that exists in the node the comment belongs to.

```
function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
  $node = $comment->getCommentedEntity();
  if ($node && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->hasField('field_example')) {
      $comment->subject->value = $node->field_example->value;
    }
  }
}

```

How could I achieve the opposite? When a comment is submitted with the field *field\_rating*, the *field\_average\_rating* field of the node should be updated.

How could I achieve that?

# Answer
> 0 votes
You could implement the same hook hook\_comment\_create() but just inverse the assignment you do on the comment as in your code, for example:

```
function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
  $node = $comment->getCommentedEntity();
  if ($node && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->hasField('node_field') && $comment->hasField('comment_field') && !empty($comment->comment_field->value)) {
      $node->node_field->value = $comment->comment_field->value;
    }
  }
}

```

---
Tags: comments
---


# Question
Title: Build and update a form based on another form
On the checkout page, I wish to load a form on a modal whose data depends on the uc\_addresses select address drop-down.

I have declared a form through hook\_form and add the form to the checkout page through mymodule\_form\_uc\_cart\_checkout\_form\_alter:

```
  $form['panes']['delivery']['modal'] = drupal_get_form('form_id');

```

My question is: how will I rebuild the form when a different drop-down option is selected? Note that I have tried to add a parameter in hook\_form:drupal\_get\_form('form\_id', 'address\_id') my problem is the form rebuild when the option is changed.

# Answer
You could possibly use the #states API to react upon another option in the dropdown is selected, this will work without submits on the client side.

If you want to change your form after submission has happened only you'd have to add conditions in your custom form function that will change your form dynamically according to what is contained in the $form\_state\['values'\] of that dropdown field.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: How to make a field readonly using hook_form_alter
I am trying to make some of the Drupal profile form fields as read-only in edit mode. I am using the following code in hook\_alter

```
$form[field_organisation_company_name][und][0]['#after_build'][]='_build_element_readonly';

function _build_element_readonly($element, &$form_state) {
    $element['value']['#attributes']['readonly'] = 'readonly';
    return $element;
}

```

In the UI filed is showing as read-only, but still, I can change the value using firebug and save. Is there any way to prevent this behavior?

# Answer
> 6 votes
It sounds like you could accomplish what you need to with Field Permissions. On a field-by-field basis you can set permissions to:

> * Create own value for the field
> * Edit own value for the field
> * Edit anyone's value for the field
> * View own value for the field
> * View anyone's value for the field

So you would easily be able to allow your users to create the value for the field initially, but as soon as they have it only becomes editable by an admin.

# Answer
> 6 votes
When you set a field as `readonly`, browser locks the field and **sends** data back to the server upon submission. Other attribute is `disabled` that locks the field and **does not sends** data back to the server.

For both of cases, you can forcefully set the value to be the same after submission. So, even when the field is set to `readonly` or `disabled`, and the user modified the HTML and sent different data, `$form_state['values']` will remain unchanged.

```
function _build_element_readonly($element, &$form_state) {
    $element['value']['#attributes']['readonly'] = 'readonly';
    $element['value']['#value'] = isset($element['value']['#default_value'])
       ?  $element['value']['#default_value']
       :  '';
    return $element;
}

```

Note that we set `#value` from #default\_value. #default\_value is the usual way to set the default value that loads up when the form is built, and `$form_state['values']` will contain the default\_value or user-input. When you set `#value` explicitly, user-input is ignored and `#value` will be used.

Anyways, I'd recommend to use `'#access' => FALSE,` when hiding form elements. It will remove the element completely, while allowing you to use its values.

# Answer
> 2 votes
I think using `#disabled = true;` is the easiest way to achieve this instead of adding some heavy module to your core, as an example I disable edit of the custom image field in user\_profile\_form when it's filled by the user before.

```
function MY_CUSTOM_MODULE_form_alter(&$form, $form_state, $form_id){

        if($form_id == 'user_profile_form'){
            if($form['field_national_front']['und'][0]['#default_value']['fid']){
                $form['field_national_front']['und']['#disabled'] = true;
             }
          //ym($form);
        }
}

```

Also, you can check the role of user and just disable (readonly field) for not admin users.

```
    function MY_CUSTOM_MODULE_form_alter(&$form, $form_state, $form_id){
       global $user;
       if($form_id == 'user_profile_form'){
           if($form['field_national_front']['und'][0]['#default_value']['fid'] && !in_array('webadmin', $user->roles)){
              $form['field_national_front']['und']['#disabled'] = true;
         }
//ym($form);
    }
}

```

# Answer
> 1 votes
You cannot prevent Firebug from changing readonly fields. But if the textfield is readonly, it's only purpose is to display data. So why not change the input-element against a text-element?

You could use the "disabled" attribute instead, because disabled input-fields are not beeing sent to the server.

You can remove the "disabled" attribute with firebug as well, but the drupal core does not react on changes of disabled input fields!

# Answer
> 1 votes
The safest way to do this is to change the type of the field to be an 'item'. http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#item

# Answer
> 1 votes
You may use Field Permissions \+ Field Readonly.

*Field Permissions* will allow you to make some of your fields non-accessible to certain users.

*Field Readonly* will allow you to display the non-accessible fields as read-only items on edit forms (instead of hiding them).

---
Tags: 7, forms
---


# Question
Title: How to resolve message ' Requires: Commerce_checkout (missing)'?
I have installed the Commerce Checkout Pages module (as the tar.gz file), as shown in this image:

Note the message shown within its description, i.e:

```
Requires: Commerce_checkout (missing)

```

Now I want to enable it, but I don't know how I resolve the `missing` part of the module.

Any help?

# Answer
You need to install the Commerce module.

Commerce Checkout is a submodule thereof.
> 1 votes

# Answer
From the screenprint it looks like you're using the module for which the info file looks like so:

```
name = Checkout Pages
version = 7.x-1.x-dev
description = Allow user to add custom pages to DrupalCommer checkout.
package = "Commerce (contrib)"

core = 7.x
dependencies[] = commerce_checkout

; Information added by drupal.org packaging script on 2011-10-20
version = "7.x-1.0"
core = "7.x"
project = "dc_co_pages"
datestamp = "1319137230"

```

So as per this info file, you need to install "Checkout" first (that's why it shows "missing") ... and which is a submodule of Drupal Commerce.
> 0 votes

---
Tags: 7, commerce
---


title: Force rebuild of aggregated css/js

text:
# Question
Title: Force rebuild of aggregated css/js
I have manually removed all aggregated css and js files from sites/default/files.

I would like Drupal to regenerate these, but it does not. Drupal is still looking for the old files, the ones I have deleted.

Clearing the cache does nothing.

How do I force Drupal to recognize that the files are missing and need to be recreated?

# Answer
> 0 votes
In D7 you might want to clear also the variables drupal\_js\_cache\_files and drupal\_css\_cache\_files:

```
drush vdel drupal_js_cache_files && drush vdel drupal_css_cache_files

```

Other than that, do you have any other cache on top of drupal (varnish?). Your pages could be cached with the reference to the old JS files. Is your site broken (404 on CSS/JS files) or is it just referencing the old ones? Usually drupal regenerates aggregated files if it can't find it.

---
Tags: 8, css-js-aggregation
---


title: Cannot add CSS class to views field

text:
# Question
Title: Cannot add CSS class to views field
I have a view in Drupal 8, and have configured a field in the view to have a custom CSS class.

The field I am adding the class to is an image. Under Style Settings I have chosen "Customize field HTML" and "Create CSS class".

When I inspect the image element on the front end, the class is nowhere to be found, and the styles are not applied.

I also have a view fields template for this view named:
**views-view-fields--home-page-top-three-stories.html.twig**

```
{{ fields.field_story_preview_image.content }}
<div class="story-title-box">
    <h3>{{ fields.title.content}}</h3>
    <h4>{{ fields.field_subtitle.content }}</h4>
</div>

```

"fields.field\_story\_preview\_image.content" is the image field that I would like to apply the CSS class to. Am I missing a configuration step?

Why isn't the CSS class being applied to this image field?

# Answer
1. I hope you cleared cached
2. I hope u added css under \[themename\].library.yml
3. If still not working plz use rewrite result add your custom html.
> 0 votes

# Answer
I think you might have modified the template that actually prints the `preview image field classes`

If you have modified the original `views-view-field.html.twig` in your theme than make sure that the `{{ field.element_attributes }}` is included as it is the one responsible for printing the attributes (which includes the classes)

For reference I am pasting here the original `views-view-field.html.twig`

```
{% for field in fields -%}
  {{ field.separator }}
  {%- if field.wrapper_element -%}
    <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
  {%- endif %}
  {%- if field.label -%}
    {%- if field.label_element -%}
      <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
    {%- else -%}
      {{ field.label }}{{ field.label_suffix }}
    {%- endif %}
  {%- endif %}
  {%- if field.element_type -%}
    <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
  {%- else -%}
    {{ field.content }}
  {%- endif %}
  {%- if field.wrapper_element -%}
    </{{ field.wrapper_element }}>
  {%- endif %}
{%- endfor %}

```
> 0 votes

---
Tags: views
---


# Question
Title: Export block that exists in two or more regions
Does anyone know how to export block that exists in two or more regions into yaml file?

This is the scenario I'm facing. A 'sitebranding' block is placed onto header and footer regions. When I go to admin/config/development/configuration/single/export I can find proper configuration, however when the code is being generated I can see there is a region property and the value is 'header' although in Drupal UI it's placed in footer and header. Is there a was to include both of regions for particular block?

# Answer
The short answer is no.

The simplest way to get what you need is to create two unique blocks and simply export both YAML files. This method will make adding any styling or configuration differences down the line much easier anyway.

Per question #9677 there were some problems with doing this in Drupal 7 but thankfully the block system is pretty robust in Drupal 8.
> 1 votes

# Answer
Drupal 8 block are not exported.. it will show broken block.. You need to do split configuration and ignore configuration.. You need to add again that block into that region.
> 0 votes

---
Tags: 8, blocks, configuration
---


# Question
Title: How to get the File Description programmatically?
In Drupal 8, like Drupal 7, you can enable the file description in the file field setting.

But once my file entity is loaded in my preprocess, I don't know how can I get the description value entered for my file. I've tried (without success) :

```
$myfileentity->toArray();
$myfileentity->get('description');
$myfileentity->get('description_field');
$myfileentity->label();

```

Any Idea ?

Thanks.

# Answer
> 11 votes
The description is stored on the file field, not on the file entity. To access it, use `$node->yourfilefield->description`.

# Answer
> 1 votes
If the field has multiple files you can get the description like so:

```
$values = $field->getValue();
foreach($values as $value){
   $descriptions[] = $value['description'];
}

```

Tested in Drupal 8.4.

# Answer
> 0 votes
If you want to get the value of the field 'description' you can use something like this:

```
$fid = 1; //Your file id
$file = \Drupal\file\Entity\File::load($fid);
$file->get('filename')->value; //here to get the file name

```

To get the list, try `dpm(file->toArray());`

You can check this pages to know about files and fields.

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


# Question
Title: Cache rebuild causes an error with missing plugin
On rebuilding the cache, a Drupal 8 website goes down and displays the message "The website encountered an unexpected error. Please try again later." I used `drush cr` to rebuild the cache, which shows the following error message.

> The "field\_item:boolean" plugin does not exist.

I also tried to rebuild the cache right after installing a new Drupal 8 site without any additional module, and it shows the same error.

How can I get the site back to working?

# Answer
This morning I had similar problem and `drush cr` was actually not clearing the discovery cache but after

```
drush sql-query 'TRUNCATE TABLE cache_discovery;'

```

I was able to get rid of this error
> 2 votes

---
Tags: drush, caching, plugins
---


# Question
Title: Database updates after pulling in code updates for modules
I've updated a bunch of modules in my local development environment and then committed the code changes using git.

On my test site, I've pulled the code and ran `drush updb` but it's showing that nothing needs to be updated and that the modules I updated are now current. In the past, every time I've performed updates, I was under the assumption that there was a database updating component to it and whenever I ran `drush updb` it would take the code that was just implemented with git and run the update. Not sure, why it's different this time, can someone explain? Am I missing a command? If there are no database updates needed, I can go on knowing the updates are truly complete?

If database updates aren't require for all module updates, can someone give an example of when updates do and do not touch the database?

Edit: An example of one such update was to the address fields token or to the Google Static Maps module.

# Answer
What makes you think that, for any of the updated modules, part of the actual updates included some database update to be performed? In other words: there are (plenty) of cases where, if you update some module, there are no related database updates that are included in such module update.

From "Writing .install files (Drupal 7.x)", within the parg "Module updates using hook\_update\_N":

> Updating your module, for example updating your schema, can be done using hook\_update\_N functions. The API page for this is at: function hook\_update\_N.
>
> Suppose you add a new column called 'newcol' to mytable1. First, be sure to update your schema structure in mymodule\_schema() so that newly created tables get the new column. Then, add an update function to mymodule.install ...

Have a look at this part of an .install file about an update of the database for the Rules module, and which looks like so:

```
/**
 * Creates a flag that enables a permission for using components.
 */
function rules_update_7209() {
  // Create a access exposed flag column.
  db_add_field('rules_config', 'access_exposed', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Whether to use a permission to control access for using components.',
  ));
}

```

PS: *It's fair to say that database updates are not required unless a change is made to the schema.*
> 2 votes

---
Tags: 7, updating
---


# Question
Title: '"entity_test" entity type does not exist' on attempted module uninstall
I'm in the process of replacing D8's core Search module with Search API. When I try uninstalling Search, I get this error:

> Drupal\Component\Plugin\Exception\PluginNotFoundException: The "entity\_test" entity type does not exist. in /Applications/MAMP/htdocs/mysite/core/lib/Drupal/Core/Entity/EntityTypeManager.php:133

There is an entity\_test table in the database, along with a number of related tables. I also have `$settings['extension_discovery_scan_tests'] = FALSE;` in the settings.local.php file.

How do I address this error?

# Answer
> 2 votes
Sounds like you installed the entity\_test module accidentally and then disabled test modules afterwards.

Set that flag to TRUE, clear cache, uninstall search and the entity\_test module (look for other enabled \_test modules too) then set that flag to FALSE again.

---
Tags: 8, entities, search
---


# Question
Title: Fresh installation on the same server where another core version was installed gives error
I have my own remote server to play around. I gave Drupal 8 a go but decided today to delete it from my server and install Drupal 7.56 again.

So I deleted all files via FTP and deleted all tables in phpMyAdmin, uploaded the Drupal 7.56 files from a fresh package I downloaded from drupal.org but ran into this issue:

When running through the process of install.php I suddenly get these 2 error:

```
Notice: Undefined variable: app_root in include_once() (line 690 of /var/www/clients/client1/web3/web/sites/default/settings.php).
Notice: Undefined variable: site_path in include_once() (line 690 of /var/www/clients/client1/web3/web/sites/default/settings.php).

```

So, after some Googling I found out it might have to do with the setting.php file of Drupal 8. The thing I don't understand is how this fresh install can search for the settings.php file of the Drupal 8 installation whilst I deleted every single file and table?

I checked my settings.php file of the Drupal 7 installation and there are only 648 lines, so I have no idea where to go searching...

# Answer
> 1 votes
After you install Drupal, automatically Drupal set `sites/default` to `555` and `settings/default/settings.php` to `444` , *So* it means they haven't deleted .

my suggestion is to change the permission for them, them delete `settings.php` (**and make sure you delete it correctly** ), and when you got insure of deleting everything Setup Drupal 7.56 again.

---
Tags: 7
---


title: Cache for logged-in user?

text:
# Question
Title: Cache for logged-in user?
I have created simple form and page to list records on form via Custom Drupal 8 Module. This form is accessible to only logged-in users with some specific role. It looks like screenshot. Whenever I submit new entry it lists record in via theme table for admin user but it does not appear for other logged-in users until I clear cache manually.

Please suggest, Thanks!

To display Records :

```
<?php

namespace Drupal\custom_form\Controller;
use Drupal\Core\Controller\ControllerBase;

class DisplayRecords extends ControllerBase {

  public function DisplayCustomRecords() {

    // Display theme table

    $table_header = [
      'name' => t('Name'),
      'mobilenumber' => t('Phone Number'),
      'email' => t('Email'),
      'age' => t('Age'),
      'gender' => t('Gender')
    ];

    $results = \Drupal::database()->select('custom_for_data')
      ->fields('custom_for_data', [
        'name',
        'mobilenumber',
        'email',
        'age',
        'gender'
      ])
      ->execute()
      ->fetchAll();

    $rows = array();
    foreach ($results as $res) {
      $formatted_age = \Drupal::service('date.formatter')->format(
        $res->age, 'custom', 'Y-m-d'
      );
      $rows[] = [
        'name' => $res->name,
        'mobilenumber' => $res->mobilenumber,
        'email' => $res->email,
        'age' => $formatted_age,
        'gender' => $res->gender
      ];
    }

    $form['table'] = [
      '#type' => 'table',
      '#header' => $table_header,
      '#rows' => $rows,
      '#empty' => t('No users found'),
    ];

    return $form;

  }

}

```

# Answer
> 4 votes
Short version: You need to define a cache tag that you can invalidate when a record is created, updated or deleted.

See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays for a lot of documentation on this.

I'd also recommend to look into using an entity type for this instead of a custom table. A bit of effort at first, but you get a ton of functionality with that, including default cache tags and for example views integration, so you can build searchable, sortable listings like that through views.

# Answer
> 1 votes
I was trying to learn how insert and select queries work with custom form so was using this way . By adding options:no\_cache: TRUE its working now.

```
DisplayRecords:
    path: 'list/custom/records'
    defaults:
      '_title': 'Custom Records List'
      '_controller': 'Drupal\custom_form\Controller\DisplayRecords::DisplayCustomRecords'
    requirements:
       _permission: 'access_custom_records_display'
    options:
      no_cache: TRUE // with this line cache stops on page

```

---
Tags: 8, database, caching
---


# Question
Title: Devel Krumo outputting all variables in a list format and not in an expandable clickable list
When I do a dpm() on an array my devel krumo output is showing a list of the variables. Previously it was in a clickable expanding list where I can hide and show the child arrays. What settings did I miss to fix this?

# Answer
If you are using bootstrap 3, you might encounter this problem. To fix this issue, add the following code to your template.php file.

```
function THE-THEME-NAME_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "<div class=\"messages $type\">\n";
    if (!empty($status_heading[$type])) {
      $output .= '<h2 class="element-invisible">' . $status_heading[$type] . "</h2>\n";
    }
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach ($messages as $message) {
        $output .= '  <li>' . $message . "</li>\n";
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= reset($messages);
    }
    $output .= "</div>\n";
  }
  return $output;
}

```
> 0 votes

---
Tags: 7, debugging
---


# Question
Title: Exposing a type of field operation (flag lists) for search index view
I installed the flag list operations module which gives me the ability to do **operations** on my views results. But this **flag list operations** doesn't show up on my **search index view** as seen below.

I'm sure there is some parameter or variable that is set in the **flag list** module that is preventing this **operation** to show up on the **search index view**.

What should I be looking for in the **flag list** module code to enable this operation to show up in the search index view?

# Answer
Those flag list operations come from a Views handler; they're applied only to the node entity type in `flag_lists_views_data_alter`.

The *Indexed node* isn't a node entity, it's something specific to the search API module (added in `search_api_views_views_data`). It only contains fields that are indexed, plus any extra stuff search API or contrib modules add on.

I haven't tried it, but you may be able to include the `nid` in the index, and add a relationship in the View to *Content*. That would, in theory, give you access to everything that Views knows about for a node.

Failing that, you'll probably have to implement your own Views handler, implement `hook_views_data_alter`, and find the table whose field handler you need to override (it'll be `search_api_index_MACHINE_NAME`). The class in `includes/flag_lists_handler_field_ops.inc` would probably be a good template to start from.
> 1 votes

# Answer
Took me a good 20-30+ hours to figure this one out as this involved knowing how Views Handlers work and reverse engineering the flag list module code.

In the case of the flag\_list module not working with the search api index, it had to do with creating a new handler. The flag list operations handler was extending the class **views\_handler\_field** but you needed **views\_handler\_field\_entity** for the search api view to see it. I'm not sure why, but I followed the views\_bulk\_operations module as an example.

From there I copied all the code from the **original** flag list operations handler code into my new handler that uses the views\_handler\_field\_entity with some modifications in the code that had to do with targeting the **nid** as the **$data** array was different from the **$data** array in the **views\_handler\_field**.

Then, to get the flag list operations **form** to show up, I had to find the form\_alter in the flag\_lists.module file and have it recognize the new handler I had.

In total I had to modify:

* flag\_lists.module
* flag\_lists.views.module
* flag\_lists\_handler\_field\_ops\_xxx.inc (this is my new handler file called xxx)
> 0 votes

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


title: Mapping roles to users while migrating

text:
# Question
Title: Mapping roles to users while migrating
Following \[this\]\[1\], I have done migration for users from Drupal 7 to Drupal 8, but I got stuck with assigning roles to the specified users.

In user.php file, my code for mapping roles to assigned users is the following.

```
public function prepareRow(Row $row) {
    $uid = $row->getSourceProperty('uid');
    // user_role

    $result = $this->getDatabase()->query('
      SELECT
        r.rid, r.name, ur.uid
      FROM
        {role} r, {users_roles} ur
      WHERE
        r.rid = ur.rid
      AND
        ur.uid = :uid
    ', array(':uid' => $uid));
    foreach ($result as $record) {
      $row->setSourceProperty('roles', $record->name );
    }

    // local_market field of type entity_reference
    $result = $this->getDatabase()->query('
      SELECT
        fld.field_local_market_target_id
      FROM
        {field_data_field_local_market} fld
      WHERE
        fld.entity_id = :uid
    ', array(':uid' => $uid));
    foreach ($result as $record) {
      if (!is_null($record->tids)) {
        $row->setSourceProperty('local_market', explode(',', $record->tids) );
      }
    }

    return parent::prepareRow($row);
  }

```

Except `roles` and custom field, `field_local_market`, all users migrated from Drupal 7 to Drupal 8.

```
destination:
  plugin: entity:user

process:
  uid: uid
  name: name
  pass: pass
  mail: mail
  status: status
  created: created
  changed: changed
  access: access
  login: login
  timezone: timezone
  langcode: language
  preferred_langcode: language
  preferred_admin_langcode: language
  init: init
  field_local_market: local_market
  field_user_role: user_role

```

What's the right way to assign roles to the users?

Migration of roles is done from Drupal 7 to Drupal 8 by using `drush migrate_upgrade`; the only task left is assigning/mapping these roles to certain UIDs or users.

# Answer
You can migrate users with roles without migrating roles using migrate **static\_map**

In migrate set

```
  process:
  uid: null
  name: name
  pass: pass
  mail: mail
  status: status
  created: created
  access: access
  login: login
  roles:
    plugin: static_map
    bypass: true
    source: roles
    map:
      5: new_role_name
      3: editor

```

and in the source plugin you have to set the roles in **prepareRow**

```
  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $uid = $row->getSourceProperty('uid');

    $query = $this->select('users_roles', 'r');
    $query->fields('r', ['rid']);
    $query->condition('r.uid', $uid, '=');
    $record = $query->execute()->fetchAllKeyed();
    $row->setSourceProperty('roles', array_keys($record));

    return parent::prepareRow($row);
  }

```
> 7 votes

# Answer
Few things you can try:

1) You need to pass the Role ID instead of the Role name.

2) Ensure you're passing an array and you actually have results in the query result:

```
$roleIds = array_map(function ($record){
  return $record->rid;
}, $result);

// Make sure $roleIds is an array.
$row->setSourceProperty('roles', $roleIds);

```

3) As your roles are migrated in another migration, the mapping should be done by using a special plugin "migration". E.g:

```
roles:
  plugin: migration
  source: roles
  migration: the_migration_name_which_migrated_user_roles

```
> 0 votes

---
Tags: 8, migrations
---


# Question
Title: Specific field tag based naming conventions (overriding views-view-field.html.twig for specific fields)
I've scoured the documentation and I simply cannot find an answer to this question regarding naming convention for twig files given a tagged view with the override of a specific field. Let me create a scenario to explain the problem.

Given **Viewname** with tag **viewtag** with a **block** display and a **fieldname** field.

I can override the theme as follows

Original file --\> Overridden file name

* views-view-unformatted.html.twig --\> views-view-unformatted--viewtag.html.twig
* views-view-field.html.twig --\> views-view-field--fieldname.html.twig
* views-view-field.html.twig --\> views-view-field--viewname--block--fieldname.html.twig
* views-view-field.html.twig --\> views-view-field--block--fieldname.html.twig

I cannot figure out how to override views-view-field for a specific **fieldname** by specifying the **viewtag**. The following names do not work:

* views-view-field--viewtag--fieldname
* views-view-field--viewtag--block--fieldname
* views-view-field--fieldname--viewtag
* views-view-field--block--fieldname--viewtag
* views-view-field--block--viewtag--fieldname

I've run out of possible combinations and yet I'm simply not able to get the viewtags to override the specific field. Surely there has to be a way to do this given that you can use the viewname to override the templates. I'd rather avoid having 50 versions of a view template when 1 could do the same thing.

# Answer
> I am able to use the tag to create template files for everything other than the specific field templates. – John Millnik

Your comment gave me the following thought: When you tag something, you tag the node and not the fields themselves. Fields do not have any tags, which makes me think that what you're trying to do is not possible.
> 1 votes

# Answer
If I'm understanding your question correctly, you are looking to add a `theme suggestion` for a `field` based on a "viewtag".

I can't say I'm 100% sure what you mean by a "viewtag", but I think you are probably looking for `hook_theme_suggestions_HOOK_alter` or more specifically `hook_theme_suggestions_views_view_field_alter()`.

More in for in Adding Theme Suggestions Programmatically For Views (Rows & Fields)
> 1 votes

# Answer
I am pretty sure you cannot target a specific field in a view. Is this view being pulled into a global sidebar or into the content area of a specific content type? If it's being pulled into the content area then you can add the view block as an entity reference field in the content type itself and target the field that way, like targeting a field inside of a field. Let me give an example and explain.

Let's say you want track titles (*field\_track\_title*) and their albums (*field\_album*) to appear on a bio page. (The bio page and the tracks are separate content types, bio page machine name being *bio*.) Create your view block displaying the track titles and albums as normal. Go ahead and place this block in a hidden region under block layout- this **must** be done in order to render it anywhere.

Then, in the bio content type, create a field referencing "other."

On the next screen select Block as the type of item to reference and set allowed number of values to 1.

When you get to the edit field screen you can select your newly created view block as the default (so you don't have to select it each time you create a new content type instance) and save. Make sure to place this field somewhere in your Manage Display screen.

Finally, to answer your question, you now can target this view's field because it renders as a field in the content type.

*field--node--field\_album--bio.html.twig*
> -1 votes

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


# Question
Title: How can I trigger a rule when there's no more scheduled content?
I have a Drupal 7 blog where I write content in advance and publish it using the Scheduler module. I'd like to be able to write a rule to send me an email when the site has published the last scheduled node available. I have a View set up which lists all the scheduled nodes, but I can't figure out how to get the result count of that view into the condition of a rule. I've got Views Bulk Operations and Views Rules installed, but I can't figure out how to use either of those how I need to.

# Answer
> 1 votes
You can make this work also by using Rules in combination with the Views Bulk Operations module, as further detailed below.

### Step 1

Use the Views Bulk Operations module to create a view of all your "nodes to be published" (as in your question), in which you add a VBO field to it. Simply include a field like `nid` for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

### Step 2

Create a Rules Component with a Rules Condition "***Check number of results returned by a VBO view***". And select the VBO view created in the previous step. If the number of results is below 1, then perform a Rules Action (in that Rules Component) to trigger your eMail.

### Step 3

Create a Rule like so:

* Use some relevant **Rules Event** related to those nodes to be published.
* Don't use any **Rules Conditions** (there is no need for them in this rule).
* Perform a **Rules Action** to execute the Rules Component from Step 2.

If you cannot think of any relevant **Rules Event** that would fit for such rule, then just create a Rules Component which has (only) 2 Rules Actions:

* Perform a **Rules Action** to execute the Rules Component from Step 2.
* Reschedule this (extra) Rules Component itself, eg after X mins or hours

Then trigger the very first execution of this Rules Component using the Rules UI.

***Done!***

# Answer
> 0 votes
Since you also have the Views Rules module enabled, you could use a completely different approach like so also:

* Before starting the Views Rules loop (Rules Action) to iterate over all results of the view, define some boolean (or integer) variable which you set (initial value) to FALSE (or 0).
* Within each iteration of your Views Rules loop, set the value of the variable to TRUE (or 1).
* After the Views Rules loop completed, use the Conditional Rules module to check the value of your extra variable: if it is still FALSE (or 0), you know there were no nodes to be processed, so that's when you want to send that eMail.

---
Tags: 7, views, rules
---


# Question
Title: Filters as rewrite results link path parameters
I am currently using this approach to link lists view's rows to detail pages in Drupal 8

I would like to pass the entity title of the row to the receiving page and use that to select view blocks having that title.
In this case something like www.mysite.com/VenuePage?Name="Mikes" This argument would then be used to select blocks with Title "Mikes"

Can someone point me in the correct direction? I'm a bit new to Drupal and may be thinking about this incorrectly.

# Answer
If the entity title of the row is a field on the view you can use the *Override the output of this field as a custom link* option and then create a link yourself using replacement patterns. So long as the field you are referencing the entity title of is beneath the field you are referencing in the field list.
> 0 votes

# Answer
At the bottom of the `Rewrite results` fieldset you should see another fieldset called `Replacement patterns`, in it there will be a list of available patterns (examples from the Files view):

* {{ fid }} ==
* {{ filename }} ==
* {{ filemime }} ==
* {{ filesize }} == File size
* {{ filesize\__value }} == Raw value

**NOTE:** You will only see values from fields above the one you are rewriting. In my example I was rewriting `filesize`, if I had done `mime`, then `filesize` wouldn't be in the list.

For your path, you would have something like `/VenuePage?name={{ field_name_of_field }}`

If the `VenuePage` is a view too, then you can add a `Contextual filter` to it, removing the need for parameters, and then your URL would be:

```
/VenuePage/{{ field_name_of_field }}
/VenuePage/Mikes

```
> 0 votes

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


# Question
Title: Linux Drush install error: Undefined class constant 'MYSQL_ATTR_SSL_CA' in phar:///usr/local/bin/drush/lib/Drush/Sql/Sqlmysql.php, line 56
I tried installing Drush with both methods listed in the drush.org documentation. I think they might be conflicting with each other if that's possible.

When I run `composer global require drush/drush` all the components appear to install correctly. However when I change to a Drupal site (Using XAMPP, /opt/lampp/htdocs/sitefolder) and run `drush status` I get the following error:

> PHP Fatal error: Undefined class constant 'MYSQL\_ATTR\_SSL\_CA' in phar:///usr/local/bin/drush/lib/Drush/Sql/Sqlmysql.php on line 56 Drush command terminated abnormally due to an unrecoverable error.
> \[error\] Error: Undefined class constant 'MYSQL\_ATTR\_SSL\_CA' in phar:///usr/local/bin/drush/lib/Drush/Sql/Sqlmysql.php, line 56

I do have the following line in my ~/.bashrc:

`export PATH="$HOME/.composer/vendor/bin:$PATH"`

Unfortunately I don't know how to troubleshoot from here, as there doesn't seem to be an easy way to uninstall Drush via the main method (http://docs.drush.org/en/master/install/), which didn't seem to work for me. `composer global remove drush/drush` does appear to run successfully.

Thanks in advance.

# Answer
> 22 votes
In my case, not all of the PHP packages made it though the Ubuntu upgrade to 16.04 (which now runs PHP 7 by default). I needed to add the missing one, and then Drush started working again:

```
sudo apt install php-mysql

```

Or for php5 users

```
sudo apt install php5-mysql

```

on very recent Ubuntu/Debian distributions.

For PHP 7.1:

```
sudo apt install php7.1-mysql

```

For PHP 7.2:

```
sudo apt install php7.2-mysql

```

You can search for your version using this:

```
apt-cache search php-mysql

```

# Answer
> 1 votes
Went down a bit of a rabbit hole on this one, but I believe the issue was related to drush connecting to the proper version of mysql. It needs the XAMPP version, not my local linux version. Adding these two lines to ~/.bashrc helped:

```
export DRUSH_PHP=/opt/lampp/bin/php

export PATH=$PATH:/opt/lampp/bin

```

# Answer
> 0 votes
had the same problem on Fedora 25. i had upgraded to php 5.6.32 from 5,60,30 and neglected a switch in the compile of 32.

doing php -m showed that 5.6.32 neglected to have module "pdo\_mysql". So i reverted back to 5.6.30 that has that module compiled in, until i can debug the 5.6.32 compile.

after this change Drush 8 worked just fine.

# Answer
> 0 votes
Make sure you have the most up-to-date extensions for your version of PHP. You can find a list of the basic items you should install in the comments on the PHP documentation site under the upgrade to 7.1.

They recommend running: `sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-fpm php7.1-curl php7.1-gd php7.1-bz2 php7.1-mcrypt php7.1-json php7.1-tidy php7.1-mbstring php-redis php-memcached`

If you don't, you will at very least run into issues with mbstring as this is a core dependency. This is also a potential solution for the all-too-common error "easyrdf/easyrdf 0.9.1 requires ext-mbstring * -\> the requested PHP extension mbstring is missing from your system." when we run `composer install` for the first time. For different versions, just switch it out as appropriate. Most of them are likely the same.

Hope that helps someone.

---
Tags: drush
---


# Question
Title: How to remove "FILE NAME SUGGESTION" from rendered HTML
I'm using D7.

I want to remove "FILE NAME SUGGESTION"(please refer to the uploaded image) from pages.

Honestly, I have no idea why it is displayed nor when it was enabled...

So, I searched the ways to enable that IN ORDER TO DISABLE NOW. I found there are three possible ways to enable it (Sorry if those ways are wrong because of my mis-understanding English):

1. Make `$conf['theme_debug'] = TRUE;` in `settings.php`
2. Implement function like

```
function mytheme_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

```
3. Use Theme developer module

About 1, I checked `settings.php` and found `$conf['theme_debug'] = TRUE;` comment out in that.

About 2, I checked my `template.php` and found I coded the function `mytheme_preprocess_page(&$vars, $hook) {...}`. So, I removed it.

About 3, I installed Theme developer module but it made all pages blank white pages. So I manually updated the module's status from 1 to 0 of the module on system table on the database, and uninstalled.

So, now I don't know why it still output "FILE NAME SUGGESTION". Does anybody have any idea why?

# Answer
> 3 votes
I found the reason why "FILE NAME SUGGESTION" was still output. It is because a following code still remained in template.php in Zen(not sub theme).

```
$GLOBALS['conf']['theme_debug'] = TRUE;

```

I didn't coded it by myself. So, I guess the code was added when I install some module(probably Theme developer?).

Anyways, when I comment out it, "FILE NAME SUGGESTION" disappered.

---
Tags: 7, theming
---


# Question
Title: Geofield Map - Filter attachment result by clicking marker
I'm facing a problem with geofield map and I can't find a solution. So I have a view with a geofield map format. There I show all nodes from one node type as markers. Under my map I have an attachment also with all nodes, but as a list with more details.

Now the problem: I want to filter the attachment when I click on a marker from the map. For example - I have 10 markers on my map. These 10 markers represent 10 nodes which are also shown in the attachment beneath. When I click on one marker on the map I want the attachment to show only one node in the results. It would also be great if the result would be updated via ajax.

I hope somebody can help me. :)

# Answer
So You have 2 views on the Page 1 view is the Map and another view is the "attachment"

You need to look in to how to use Contextual filters look at the Url Arguments in A view (see https://www.youtube.com/watch?v=aVwclF9TfBo | and https://www.youtube.com/watch?v=zbdQghFj0lU)

A Very Quick Way to get this done is, in your Map View add 2 new fields Content id and a Global: Custom text field then in your new custom field view add

```
 <a href="/map?show={{ nid }}" class="use-ajax btn">Quick View</a>

```

where /map is the path to your map page,

Then open your Map FORMAT Settings and scroll until you see

"MAP MARKER AND INFOWINDOW" in Marker Infowindow Content from select your new field

Then save the map view.

Open Your "attachment" view and add a CONTEXTUAL FILTERS

selecting "ID" in the Content Category.

config like

tick Provide default value

Type = Query parameter

Query parameter = show

this will give you

this is not 100% exactly what you want but then you can start to add a custom js file to target the marker click event and auto trigger the window link - good luck !
> 0 votes

---
Tags: views, 8, google-maps
---


title: Modify default drupal 8 search results

text:
# Question
Title: Modify default drupal 8 search results
I am using **Drupal 8** default search and I don't want to use **search api** module. Default search is working fine. But I Want to modify it. I want to categorize search result and get count of that category. Also I want to add class of that category so that On click of that category, I can hide other results.

There was hook `hook_preprocess_search_results()` in `7` but in `8` I think they have removed.

So is there any alternate hook available? Is there any other way around without using search api and facet api?

# Answer
> 2 votes
Perhaps a view with exposed filters may be a quicker solution for this kind of thing.

# Answer
> 0 votes
If you want to add search behavioral and modify the results which it gives you, you can use hook\_node\_search\_result , Else if you want to modify the look and design of your result items you can use search-result.html.twig file to theme the output markup of your result items.

---
Tags: 8, search
---


title: getting the value of a target_id

text:
# Question
Title: getting the value of a target_id
Using either **node\_load\_multiple** or **entity\_metadata\_wrapper**, how do you go about getting the value of a target\_id? Using Views does not seem to work either because of the target\_id value does not get pulled in by the hook\_cron().

for a value, you can use something like

```
$node = node_load($value->nid);
$wrapper = entity_metadata_wrapper('node', $node);
$userId1 = $wrapper->field_name->value();

```

Using noad\_load\_multiple, I get an array like

```
Array
(
[595796] => stdClass Object
(
...
[field_name] => Array
(
[und] => Array
(
[0] => Array
(
[target_id] => 1010101
...

```

The goal is to get the target\_id so that I can create a node with that value, creating the node is not the problem.

I also tried variations of

```
$foo_foo = node_load_multiple(array_keys($foo_foo_result['node']));
$foo = current($foo_foo['node']['field_name']['und'][0]['target_id']);

```

# Answer
I assume You are using drupal 7 if so you result is an object:

```
$foo_foo = node_load_multiple(array_keys($foo_foo_result['node']));
$target_ids = [];
foreach ($foo_foo as $result) {
   $target_id = $result->field_name['und'][0]['target_id'];
   $target_ids[] = $target_id;
}
var_dump($target_id);
die('stop');

```

In Drupal 8 its WAY WAY WAY easier then this.
> 1 votes

---
Tags: views, hooks
---


title: Webform Title Issue

text:
# Question
Title: Webform Title Issue
I'm using Drupal 8 and the Webform module. I have entered a title for my form, but when you view the form the title defaults to "Main page content." I have three forms, including the default Contact form and all of them have this as a title. The correct title does display in the webform admin pages.

Thanks,

Kateva

# Answer
> 0 votes
Mmmm when you installed webform is this a fresh site, or did you upgrade "yaml form" - to webform, if so might be a halfbaked migration.

can you replicate this with a fresh Drupal install and webform install ?

---
Tags: forms
---


# Question
Title: Trigger custom Javascript function from twig template
I just want to trigger a custom javascript function when the site is loaded I have done this with Drupal.behaviors.custom, but it somehow behaviors triggers twice and I see two identical tables. The problem is that I am a beginner and dont know how implement the once() function in my case

custom.js:

```
Drupal.behaviors.startTable = {
        attach: function () {

            var data = function () {
                return Handsontable.helper.createSpreadsheetData(100, 10);
            };

            var container = document.getElementById('example');

            var hot = new Handsontable(container, {
                data: data(),
                minSpareCols: 1,
                minSpareRows: 1,
                rowHeaders: true,
                colHeaders: true,
                contextMenu: true
            });

        }
    }

```

Best solution for me would be If I can trigger a Drupal.AjaxCommands.prototype.custom Command and trigger it with the template

Here is the call for the template:

```
public function handsontable()
{
   return [
      '#theme' => 'mytheme',
      '#attached' => ['library' => ['ajax_example/handsontable']],
         ];
}

```

Iam also able to call the custom js with a CommandInterface but it only works if there is a callback with a Link or button or from.

I am pretty sure that there is a really easy way, but could not find any solution.

twig template:

```
<h2>Handsontable Basic Example (100x10)</h2>
<p>
    Head to <a href="https://handsontable.com" target="_blank">handsontable.com</a> to learn more about Handsontable.
</p>

<div id="example"></div>

```

Maybe it is possible to call the custom js with the twig template?

# Answer
Some thing like this.

```
(function ($, Drupal, once) {
  'use strict';
  Drupal.behaviors.startTable = {
    attach: function () {
      var container = $('#example');
      $(window).once().on('load', function () {
        var data = function () {
          return Handsontable.helper.createSpreadsheetData(100, 10);
        };
        var hot = new Handsontable(container, {
          data: data(),
          minSpareCols: 1,
          minSpareRows: 1,
          rowHeaders: true,
          colHeaders: true,
          contextMenu: true
        });
      });
    }
  }
})(jQuery, Drupal);

```

your library then needs: dependencies: \- core/jquery \- core/drupal
> 1 votes

---
Tags: 8, theming, javascript
---


# Question
Title: Assign new customer with specific user role upon checkout registration
When a new customer is created, in the first checkout steps, its useful to be able to assign him with a specific user role, apart from the default 'authenticated'

A relevant use case would be when there are both customers and different backend user roles (editors e.t.c.) and it is need to create specific permissions to users according to whether they are customers or not.

This has been answered for commerce v1 (drupal 7) in the following Drupal Commerce assign role on account create on checkout

This solution can be applied to Drupal 8 commerce v2. So by utilizing hook\_user\_insert one can get the new account and assign it other roles, upon registration.

However its not clear how/if we can determine in this hook whether this new user is a commerce created user and therefore a customer, or if its a user created by the admin and therefore possibly not a customer.

One not so safe condition would be to check if he already is assigned with any roles, as it would be the case if he was a backend user, but still this does not feel so safe.

So, there are 2 questions

1. Is there a 'by the book' way to assign a specific role to a commerce customer?
2. Is there a safe way to identify who is creating (commerce checkout or backend admin) a user in hook\_user\_insert?

# Answer
> 0 votes
Surely If someone creates the order the the order is associated to that user, so in this case you don't need to wory about user being created, what you can do is look in to:

hook\_ENTITY\_TYPE\_update()

this way your going from the order status being upgraded to paid or whatever I dont know what the entity name for the order is but you could grab that loaded it, get the user id and check the roles , if no role add new role to them and save. as a bonus you have more control over what type of products to restrict it to ect.

---
Tags: commerce
---


# Question
Title: Use existing serial field with same counter across content types
how do I use existing Serial field in other content types with same counter db table? Have 2 CCKs, cck-A has a serial field (auto increment) (ParticipantNumber), added same ParticipantNumber serial field (add existing field) in cck-B. But the serial field value for both CCKs have independent auto incremental value.

How do I make the ParticipantNumber values be incremental (and Unique) across cck A and B? (just like node nid)

# Answer
Instead of Serial type, I added Integer field, and added the same field (add existing field) in other content type as well. And In the **hook\_entity\_presave**, I query for the MAX(field\_value), increment and assign for the current node/entity.
> 0 votes

---
Tags: 7, entities
---


title: Data Entry Form in Drupal

text:
# Question
Title: Data Entry Form in Drupal
I am new to Drupal and somehow managed to create a website with some basic pages I required using views. One of the main functionality that I need is a data entry form where a logged in user can enter details about members of his/her team like name, age, etc and this too for variable number of members. So far I could not find anything related. Has anyone tried anything related to this?

Thanks in advance.

# Answer
Add fields to the existing content types 'Article' or 'Page' or create a content type based on your requirement. Add fields name, age, etc

```
admin >> strucuture >> content types >> Add content type

```

path (/admin/structure/types/add) or manage fields of the existing content type (add or delete) Ex: For Article content type you can manage fields at

> admin/structure/types/manage/article/fields
> 0 votes

---
Tags: forms
---


# Question
Title: How do I get the active theme path in a view?
I need the active theme path in a view to use it in a field rewrite to display that particular image from my theme images folder.

How can I achieve this?

# Answer
You can do by

```
global $base_url;
$theme = \Drupal::theme()->getActiveTheme();
$default_image_url = $base_url.'/'. $theme->getPath() .'/images/image.jpg';

```
> 5 votes

# Answer
You should be able to just reference it.

```
"/themes/mytheme/path/to/images/foo.jpg"

```

Although, IMO this would be a lot simpler by changing the View to show rendered content, and creating a view mode that has all of this in a Twig template instead of fiddle with Views field rewriting.
> 1 votes

---
Tags: views, 8, entities
---


# Question
Title: How to get the URL of a file located in the theme folder?
Is there a way to get the URL of an image located in the theme folder? Or just get the URL of the theme folder?

# Answer
You can use `drupal_get_path()` to get the path to your theme folder:

```
$path = drupal_get_path('theme', 'name_of_theme');

```

From there you can specify a particular file like this:

```
$image_path = $path . '/images/image.jpg';

```

You could also use `path_to_theme()`, but be wary as the return from this can change depending on the context it's called in:

> It can point to the active theme or the module handling a themed implementation. For example, when invoked within the scope of a theming call it will depend on where the theming function is handled. If implemented from a module, it will point to the module. If implemented from the active theme, it will point to the active theme. When called outside the scope of a theming call, it will always point to the active theme.
> 18 votes

# Answer
```
$imgurl = file_create_url(path_to_theme().'/images/blah.png');

```

description: *this line of code uses path\_to\_theme(), to get the path to the theme, and then file\_create\_url(), to create an url for the file, to get the URL of an image located in the theme folder, as requested by the op.*

I got a downvote for not describing it, so there you are :-)

its also the same as the accepted answer, just with comments applied to make it more complete. please note that it refers to the theme folder of the current theme, so its mainly usefull inside a theme template.
> 6 votes

# Answer
In Drupal 8

```
global $base_url;
$theme = \Drupal::theme()->getActiveTheme();
$image_url = $base_url.'/'. $theme->getPath() .'/images/image.jpg';

```
> 0 votes

---
Tags: 7, theming, uri
---


# Question
Title: How to create a view to display only child nodes of a parent term?
Is it possible to create a view which displays only the child nodes of selected taxonomy term?

I have something like this

```
-Fruit
--Apple
---Green
---Red

```

and when I click on fruit (taxonomy/tem/1), I want to display only nodes with term apple, green, red. Now It is displaying nodes from fruit, too, but I dont want it. I have some nodes with term fruit but I dont want to display it when I click on fruit.. only nodes from fruit children terms.

Is it possible to do this?

# Answer
I dont think that this way is possible,but a situation near to this is possible as:- 1. While creating a view,we have a field known as "filter criteria" field,in that add --\**Content: Has taxonomy terms (with depth) (or Unknown) **

1. Go into the settings of this field\**strong text** and choose depth of the field.\**
2. Here **Depth** means-The depth will match nodes tagged with terms in the hierarchy. For example, if you have the term "fruit" and a child term "apple", with a depth of 1 (or higher) then filtering for the term "fruit" will get nodes that are tagged with "apple" as well as "fruit". If negative, the reverse is true; searching for "apple" will also pick up nodes tagged with "fruit" if depth is -1 (or lower).\**
3. this can be of help if u don't mark any node with the **fruit** tag,but mark all nodes with the **some children tags of fruit**.
> 1 votes

# Answer
The Views module has a taxonomy\_term View which can be used. You need to edit the View so that under the Arguments -\> Taxonomy: Term ID (with depth) -\> change the depth depending on your requirement. If you want to exclude the parent item, you can do this by adding a filter to exclude the parent term.

I found a link as well that might help: Display terms only if associated with a node
> 1 votes

# Answer
Add RELATIONSHIPS -\> Taxonomy term: Parent term

**do not forget to check checkbox -\> Require this relationship**
> 0 votes

---
Tags: 7, views, taxonomy-terms
---


# Question
Title: Get path/url/uri of Entity reference field to content in a Twig template?
I have a Entity reference field which links to internal content/node.

I can get the title with {{ node.field\_related\_project\_internal.entity.label }}

But how can I get the raw path/url/uri of the linked content/node? The soloutions for a Link Field to not work here: How to get the valid URL of a Link field from within a Twig template?

# Answer
> 10 votes
The url is not an entity field, so you can't access it directly. Also the entity methods to generate url/links are not accessible in Twig because of the sandbox policies. You can build a path though, if you have the id of the referenced node:

```
{% if not node.field_ref.isempty %}
  {{ path('entity.node.canonical', {'node':  node.field_ref.entity.id}) }}
{% endif %}

```

Reference: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

---
Tags: entities, uri
---


title: Alternatives to themekey?

text:
# Question
Title: Alternatives to themekey?
I need to show my website with a "theme" when in header's requests is present a particular key/value.

In Drupal 7 I do this via themekey, but this module does not exist in Drupal 8.

Are there alternatives, or other ways to do this?

# Answer
You can easily recreate your required feature by implementing a custom theme negotiator. This requires a little custom programming.

First, create an own module (in the following example, we'll call it `mymodule`). Within that module, create a `mymodule.services.yml` file, that lets Drupal know about your theme negotiator service:

```
services:
  mymodule.theme_negotiator:
    class: Drupal\mymodule\Theme\MyModuleThemeNegotiator
    arguments: ['@request_stack']
    tags:
      - { name: theme_negotiator, priority: 1000 }

```

The important parts here are the service tag `theme_negotiator` and a high enough priority, that ensures the negotiator will be called before any other negotiators. If you want to just change the default theme dynamically but let route specific theme negotiators still apply, use a priority \< 0.

As you can see, we also mentioned your custom theme negotiator service class `MyModuleThemeNegotiator` located in the namespace `Drupal\mymodule\Theme`, and as argument the current request stack (as we can use it to get the request headers).

So let's create a folder `src/Theme` in your module and add a `MyModuleThemeNegotiator.php` like this:

```
namespace Drupal\mymodule\Theme;

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Theme\ThemeNegotiatorInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * My Custom Theme Negotiator.
 */
class MyModuleThemeNegotiator implements ThemeNegotiatorInterface {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a MyModuleThemeNegotiator object.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    // This method must return TRUE, if your headers
    // fulfill the desired requirements.
    if (
      $this->requestStack->getCurrentRequest()->headers->has('myheader')
      && $value = $this->requestStack->getCurrentRequest()->headers->get('myheader')
      && $value == 'myvalue'
    ) {
      return TRUE;
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function determineActiveTheme(RouteMatchInterface $route_match) {
    // This method returns the ID of the theme that shall be
    // used, if your theme negotiator applies.
    return 'mytheme';
  }
}

```

Alter the header/values to match your requirements, clear your caches, and your theme should be applied.
> 0 votes

---
Tags: 8, theme-negotiation
---


# Question
Title: Override webform confirmation and email message if token data is missing
I have a webform in which I am using tokens to display data in the form submission confirmation and in a sent email.

Some of this data is pulled from a web service, and sometimes no data is returned by the API. This can result in the confirmation and email not being populated with data.

Form submission confirmation:

```
REPORT COMPLETE
Thank you for your report, which will be forwarded to: .
If you need to contact us about your report, you can do so at:
A confirmation email has been sent to: someone@example.com.

```

Email:

```
Thank you for reporting a problem at: Acme Inc.
Your report has been forwarded to .
Please do not reply to this email.

```

In this event, I'd like to override the confirmation and email message with a different message (that does not rely on data being available).

What is the best way to achieve this? Use `hook_form_alter` to test for missing values and then override the webform's `#confirmation` element? And how to override the email message?

Thanks.

# Answer
The Settings handler allows you conditionally override the confirmation message and any other webform setting.

The Email handler support conditional logic and now also supports custom Twig template which allows you to use if/then (conditional) logic in the email message.
> 2 votes

---
Tags: 8, webforms
---


# Question
Title: How to update license status when deleting recurring order?
Commerce License Billing module has the following function, which automatically deletes corresponding billing cycle if recurring order gets deleted:

```
function commerce_license_billing_commerce_order_delete($order) {
  if ($order->type == 'recurring') {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_wrapper->cl_billing_cycle->delete();
  }
}

```

which is good to keep database clean from zombie billing cycles.

However, the problem is that licenses for the deleted order's products keep the same `Active` status when they were supposed to get `Revoked`. So I tried to write a new function in similar manner:

```
function my_module_entity_delete($entity, $type) {
  if ($type == 'commerce_order') {
    if ($entity->status == 'recurring_open') {
      foreach ($entity->commerce_line_items[LANGUAGE_NONE] as $key => $value) {
        $line_item_id = $value['line_item_id'];
        dpm($line_item_id);
        $line_item = commerce_line_item_load($line_item_id);
        dpm($line_item);
        if (isset($line_item->cl_billing_license[LANGUAGE_NONE][0]['target_id'])) {
          $license_id = $line_item->cl_billing_license[LANGUAGE_NONE][0]['target_id'];
          $license = entity_load('commerce_license', array($license_id));
          $license[$license_id]->status = '4';
          entity_save('commerce_license', $license[$license_id]);
        }
      }
    }
  }
}

```

Unfortunately, while the `dpm($line_item_id)` line correctly returns the line item id, the `dpm($line_item)` line always returns empty. Apparently the corresponding line item already gets deleted by that time, so the function is not able to get to its license.

I've found the proposed patch on https://www.drupal.org/project/entity/issues/1789494, but since it's not yet committed, I wonder is there any other way of changing the status of relevant licenses if recurring order is deleted?

# Answer
I've done it on more granular line-item level:

```
function mymodule_entity_delete($entity, $type) {
  if ($type == 'commerce_line_item') {
    if (isset($entity->cl_billing_license)) { // Means this is recurring order.
      $license_id = $entity->cl_billing_license[LANGUAGE_NONE][0]['target_id'];
      $license = entity_load('commerce_license', array($license_id));
      $license[$license_id]->status = '4';
      entity_save('commerce_license', $license[$license_id]);
    }
  }
}

```
> 0 votes

---
Tags: commerce
---


# Question
Title: Feeds - How to set a blank source value programmatically
I'm triggering a Feeds import in a custom module I made. I need to set a value of a blank source in that code because that value is not in the source file (in this case is a xml). Is it possible to do this?

Below is the code I have.

```
$path = $url . '/path_to_my_file/myfile.xml';
$feeds_source = feeds_source($feeds_importer);
$feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);

$file_exists = get_headers($path, 1);

# check if file exists:
if ($file_exists[0] == 'HTTP/1.1 200 OK') {
    $feeds_config['source'] = $path;

    $config = array(
        'process_in_background' => TRUE,
    );

    $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
    $feeds_source->importer->addConfig($config);
    $feeds_source->save();
    $feeds_source->startImport();

    while (FEEDS_BATCH_COMPLETE != $feeds_source->import());
}

```

**UPDATE:**

Below is a more complete code. I have 3 functions. The first one is the original but one. Notice tha I get the `$VALUETOPASS` variable from the function arguments.

The other 2 functions are the ones rooby suggested. The problem is how to have the `$VALUETOPASS` in the last function. At this moment I only need that.

```
function MYMODULE_CustomImport($VALUETOPASS) {
  $path = $url . '/path_to_my_file/myfile.xml';
  $feeds_source = feeds_source($feeds_importer);
  $feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);

  $file_exists = get_headers($path, 1);

  # check if file exists:
  if ($file_exists[0] == 'HTTP/1.1 200 OK') {
    $feeds_config['source'] = $path;

    $config = array(
        'process_in_background' => TRUE,
    );

    $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
    $feeds_source->importer->addConfig($config);
    $feeds_source->save();
    $feeds_source->startImport();

    while (FEEDS_BATCH_COMPLETE != $feeds_source->import());
  }

function MYMODULE_feeds_processor_targets_alter(array &$targets, $entity_type, $bundle) {
  // Set a custom value setter callback for the my field on my node type.
  if ($entity_type == 'node' && $bundle == 'my_bundle') {
    if (isset($targets['my_field'])) {
      $targets['my_field']['callback'] = 'MYMODULE_set_custom_field_value';
    }
  }
}

function MYMODULE_set_custom_field_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
  $xml = simplexml_load_file($url . $VALUETOPASS . '/api/xml');
  $multijob_array = json_decode(json_encode((array)$xml), TRUE);

  if (isset($multijob_array['action'][2]['cause']['upstreamBuild'])) {
    $multijob_build = $multijob_array['action'][2]['cause']['upstreamBuild'];
  } else {
    $multijob_build = '';
  }

  $entity->{$target}[$entity->language][0]['value'] = $value;
}

```

# Answer
> 2 votes
In the code where you run the importer you can only alter the field mapping.

To modify the field mapping configuration at that point to add custom data (you can also do things like remove fields from the mapping here):

```
// Load the importer.
$importer_id = 'my_importer';
$feeds_source = feeds_source($importer_id);
// Get the current field mappings.
$field_mappings = $feeds_source->importer->processor->getMappings();

foreach ($field_mappings as &$mapping) {
  // Add an arbitrary value to the mapping of my_field for
  // use later in the processor target callback.
  if ($mapping['target'] == 'my_field') {
    // Your logic goes here to populate this.
    $mapping['my_custom_value'] = 'My custom value';
  }
}

// Set the new field mappings.
$feeds_source->importer->processor->addConfig(array('mappings' => $field_mappings));
// Save the new field mappings.
$feeds_source->save();
// The previous call to FeedsProcessor::getMappings() cached
// the mapping, so we need to clear that before we run the import.
drupal_static_reset('FeedsProcessor::getMappings');

// Run the import.
$feeds_source->startImport();
while (FEEDS_BATCH_COMPLETE != $feeds_source->import());

```

Then to change the actual value that goes into the field, you have to do that at import time, when feeds is getting the value from the source and saving it to the target.

To do that you can implement hook\_feeds\_processor\_targets\_alter(), like this:

```
/**
 * Implements hook_feeds_processor_targets_alter().
 */
function my_module_feeds_processor_targets_alter(array &$targets, $entity_type, $bundle) {
  // Set a custom value setter callback for the my field on my node type.
  if ($entity_type == 'node' && $bundle == 'my_node_type') {
    if (isset($targets['my_field'])) {
      $targets['my_field']['callback'] = 'my_module_set_custom_field_value';
    }
  }
}

/**
 * Custom feeds target setter callback.
 */
function my_module_set_custom_field_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
  // Set the field value to our custom value if it's there.
  if (!empty($mapping['my_custom_value'])) {
    $entity->{$target}[$entity->language][0]['value'] = $mapping['my_custom_value'];
  }
}

```

---
Tags: feeds
---


# Question
Title: Checking for User Role in Views Field with Twig
I'm currently building a view, where different Links should be displayed in a field, based on the currently logged in users role.

I've read a bit into Twig, but haven't found anything similar yet (if it is even possible).

# Answer
> 3 votes
First, you should not do security by role. It should be done by checking for a permission.

In general...Twig gets passed a user variable from Drupal that can be used for this. There is a hasPermissions method. Here's a sample code snippet.

```
  {% if user.hasPermission('administer eck entities') %}
      <a href='{{ add_url }}'>Add tab</a>
  {% endif %}

```

If you must use roles, there should be an hasRole() method on the user object that is passed in. (See User Object api docs)

For Views:

Views has limited twig like support in the GUI but does not support all the functions of the underlying twig functions. To check for user permissions in a header, you will either need to use the hook\_preprocess\_views\_view() or create your own view specific template, e.g. views-view--view-name.html.php in your theme. You will need to process the header (or footer) variables in these to get the permission specific info into the view.

If you want to limit specific fields, you can use the field specific hook and templates as well.

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


# Question
Title: How to use picture element as background image?
With the simple image field we are able to set the image style and use that to set the image as a background for a div tag (see example below). HOwever, as Drupal 8 has Responsive Image module, the image field will generate like below. With different breakpoints, different images are fetched by the browser, but this make it difficult to set the image as a background.

The current implementation is flexible because as the text grows so does the height of the div containing the image as a background image.

How would you use the picture tag to set the image as a background? I have not found a way to have Drupal detect what image is being fetched by the browser.

Goal:

1. Have image as a background
2. Overlay text on top of image
3. As the overlay text grows, so does the div containing the text. As such the image as a background should grow as well.

Current implementation without Responsive Images:

```
<div class="wrapper">
    <div class="wrapper_img" style="background-image: url('/sites/default/files/banner_large/name.jpg')"></div>
    <div class="wrapper_content">Authoritatively reinvent magnetic ROI without excellent interfaces. Professionally drive extensive manufactured products through 24/365 leadership. </div>
</div>

```

Responsive image outputs which makes it difficult to set the background image (banner\_large, banner\_medium, banner\_small are image styles)

```
<picture>
<source srcset="/sites/default/files/banner_large/name.jpg 1x" media="all and (min-width:1200px) type="image/png" >
<source srcset="/sites/default/files/banner_medium/name.jpg 1x" media="all and (min-width:768px) type="image/png" >
<source srcset="/sites/default/files/banner_small/name.jpg 1x" media="all and (min-width:320px) type="image/png" >

<img src="/sites/default/files/banner_small/name.jpg" alt="text" typeof="foaf:Image">

</picture>

```

# Answer
Found that we can modify the responsive-image.html.twig to do what we need. We used a combination of the following links:

1. Responsive images
2. Responsive images (MDN Web docs)
> 0 votes

---
Tags: 8, media, theming
---


# Question
Title: Is it possible to have custom, default fields added to all new product types In Commerce 2?
I have multiple custom fields that will need to be on **all** new product types (Commerce 2). The fields are already created on the 'default' product type. But new product types do not inherit the custom fields.

Is there a way to have custom fields automatically added to all new product types?

# Answer
> 2 votes
Nothing that just works.

You could define them as a base field through code by defining them in hook\_entity\_base\_field\_info(), so for example how scheduler module does that. Then they will be non-configurable fields that are always there. If they're not multiple, they will even be added to the product base tables.

Those kind of fields are a bit tricky to uninstall.

The other option is implementing a hook\_commerce\_product\_type\_insert() and then copy the configurable fields you want from the default type and add them to that new bundle as well.

---
Tags: 8, commerce
---


title: How do I add default content?

text:
# Question
Title: How do I add default content?
I am looking for a standardized way to add content such as content types into an installation profile.

Suppose we exported the JSON for REST Content and want to import them during installation. I have created a custom profile, and it works. Now I need to import the default content. For that, I used the *Default Content for D8* module.

So, I created the *content* folder in profile/custom\_module/content/node/my\_file.json.

Also, I am using a minimal profile installation with the following `hook_install()` implementation.

```
function mymodule_profile_install() {
  include_once DRUPAL_ROOT . '/core/profiles/minimal/minimal.install';
  minimal_install();
}

```

In the info.yml file, there is only one module dependency.

```
dependencies:
- default_content

```

When I run install.php, my default content is not installed. Also, when I checked admin/module page, this module is enabled, but the basic core modules aren't, even if they are listed in the minimal.info.yml file.

I don't understand what I am missing.

Why isn't my default content installed?

# Answer
> 1 votes
The issues I see are three:

1. As pointed out from Clive, the YAML file is invalid. The second line needs to be indented.

```
dependencies:
  - default_content

```

You can use the content of minimal.info.yaml as guide to write the .info.yml file of your installation profile.
2. An installation profile doesn't inhered its dependencies from another installation profile.
3. The *Default Content for D8* module doesn't automatically handle the dependencies necessary to create the content entities imported with it.

This means that you need to:

* Fix the indentation of the .info.yml file for the installation profile
* Add all the necessary dependencies

From the question, I take the installation profile is just creating nodes or content types. In that case, the .info.yml file would be fine if it contains the following dependencies.

```
dependencies:
  - node
  - default_content

```

As side note, instead of including the core/profiles/minimal/minimal.install file, I would rather copy the code from `minimal_install()`.

---
Tags: 8, installation-profiles
---


title: Sending smtp email using mail()

text:
# Question
Title: Sending smtp email using mail()
I have installed and configured https://www.drupal.org/project/smtp module sending test email works fine, but when sending email with code nothing is sent and also no log in drupal (I have enabled debugging)

```
    $ownerEmail = 'email@someemail.com';
    $subject = 'update';
    $msg = 'You case has been updates';
    mail($ownerEmail,$subject,$msg);

```

# Answer
> 2 votes
mail() is a PHP function, that will never use SMTP.

You need to use the drupal mail manager and its mail function. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Mail%21MailManager.php/function/MailManager%3A%3Amail/8.4.x and the example code ther.

---
Tags: 8, emails
---


title: Continuing an interrupted batch

text:
# Question
Title: Continuing an interrupted batch
I'm using a batch job in Drupal 8 to scrape pages from another site to import.

I'm using `httpClient`, and I have it wrapped in a try/catch.

```
try {
  $response = \Drupal::httpClient()->get($parts['scheme'] . '://' . $parts['host'] . $parts['path'], [
    'query' => $parts['query'],
    'headers' => array('Accept'=>'text/xml'),
    'verify' => FALSE,
    'connect_timeout' => 6,
    'CURLOPT_SSL_VERIFYPEER' => false,
    'CURLOPT_CERTINFO' => false,
  ]);
  return (string) $response->getBody();
}
catch (Exception $e) {
  watchdog_exception('scrape', $e);
  return FALSE;
}

```

However, from time to time the remote site times out, and the guzzle exception is not caught, which causes the batch job to end.

```
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /batch?id=44&op=do_nojs&op=do
StatusText: Internal Server Error
ResponseText: The website encountered an unexpected error. Please try again later.GuzzleHttp\Exception\ConnectException: cURL error 28: Operation timed out after 30001 milliseconds with 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in GuzzleHttp\Handler\CurlFactory::createRejection() (line 186 of vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php). GuzzleHttp\Handler\CurlFactory::finishError(Object, Object, Object) (Line: 103)

```

This job imports a few thousand pages, so when the error happens in the middle of the batch, it's a major pain.

I am getting ready to write a queue for the batch processor, where the batch pops a set of items off the queue and then marks them as done, so that I can continue the job after an exception.

But then I wondered, is there already a way to tell Drupal to continue a batch from where it left off or was interrupted? I did some googling and didn't find anything indicating that this feature already existed. I don't want to re-invent the wheel if I don't have to.

Can I re-start an incomplete, interrupted batch job?

# Answer
So I think there is no way to tell batch to restart when it's gotten an error response. What you could do is to not return a possible error but rather re-try the request using your own wrapper. So could do

```
try {

  $TestRetry = new TestRetry();
  return $TestRetry->test();
}
// And I think you won't need this but handle the exception in your wrapper class.
catch (Exception $e) {
  watchdog_exception('scrape', $e);
  return FALSE;
}

```

and in your wrapper, you could attempt to retry the request to avoid an error. So your wrapper may look like this:

```
<?php

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

class TestRetry {

  public function test() {
    $handlerStack = HandlerStack::create(new CurlHandler());
    $handlerStack->push(Middleware::retry($this->retryDecider(), $this->retryDelay()));
    $client = new Client(array('handler' => $handlerStack));

    $response = $client->request(
      'GET',
// @todo replace to a real url!!!
      'https://500-error-code-url'
    )->getBody()->getContents();

    return \GuzzleHttp\json_decode($response, TRUE);
  }

  public function retryDecider() {
    return function (
      $retries,
      Request $request,
      Response $response = NULL,
      RequestException $exception = NULL
    ) {
// Limit the number of retries to 5
      if ($retries >= 5) {
        return FALSE;
      }

// Retry connection exceptions
      if ($exception instanceof ConnectException) {
        return TRUE;
      }

      if ($response) {
// Retry on server errors
        if ($response->getStatusCode() >= 500) {
          return TRUE;
        }
      }

      return FALSE;
    };
  }

  /**
   * delay 1s 2s 3s 4s 5s
   *
   * @return Closure
   */
  public function retryDelay() {
    return function ($numberOfRetries) {
      return 1000 * $numberOfRetries;
    };
  }
}

```
> 0 votes

---
Tags: 8, batch-operations
---