# Question
Title: How do I check the content of variables passed to a template file?
I enabled Twig debug and I tried to debug some custom fields. However, if I try this with `debug()` or `kint()`, my application always crashes. My PHP memory size is currently 512MB; I assume that should be enough.

I realise that `node` is a bit too much to debug, so I tried debugging a field as in `node.field_video`, but that didn't work out as well.

How do I check the content of variables passed to a template file?

# Answer
You can follow document.

> To dump only the available variable keys use:

```
{{ dump(_context|keys) }}

```

In this case you can use:

```
{{ kint(node|keys) }}

```

Or you can follow topic

> Create a /modules/contrib/devel/kint/kint/config.php file and add / modify the line $\_kintSettings\['maxLevels'\] = 3; (by @mdrummond on Slack)

**The best way**: install module twig\_tweak and using twig function `{{drupal_dump(node)}}` to dump variables.
> 4 votes

# Answer
Note that if your fields are inside custom blocks, and you're trying to access those fields, the syntax is slightly different. You'll want to access them this way, with a kint statement inside your custom twig file:

```
{{ kint(_context) }}

```

Inside the \_context array, I found my fields were then inside the content array. So in my case, I was looking for the value of field\_caption - and that was available at

```
{{ _context.content.field_caption.0 }}

```

I hope that helps someone else save some time along the way!
> 0 votes

---
Tags: theming, 8, debugging
---


# Question
Title: Can drupal commerce products become cheaper to the customer when they order more?
I would like to set up a shop to sell custom made products, all variations on the same base product. The greater the number of tasks I have to do to get the product ready, the more expensive the product.

Some of these task do not require set up time for an order, but some tasks do.

Can drupal commerce take calculate the cost per item for a variation per product and the costs per order and turn those in to a sell price (the only price) the customer can see, based on the number of products they want to order?

**Example:**

Let's say, the products are cubes.

I can make a cube out of wood or plastic. I can finish them by just sanding them, or paint them, or cover them in fabric.

Just sanding them is the quickest and thus the cheapest. Painting takes more time and is more expensive. Black is more difficult to get right then white, so again, is more expensive.

But also, painting not only takes time for the painting itself, it takes setup time for the whole order AND for every layer.

I would like to configure the products so that I can include most of these price factors in to the price the customer sees in the shop as they are changing the number they may want to order.

Because my typical order quantity is between 1 and 10, those diferences make a big difference in the price.

Can this kind of calculations be done with drupal commerce out of the box or with contributed modules, or would this require coding?

# Answer
> 1 votes
Assuming you're on Drupal 7 yes, I've done this with the Commerce Price Table module: https://www.drupal.org/project/commerce\_price\_table

"This is a contributed module for Drupal Commerce that allows you to use a secondary price field to supply an alternate price for a product based on the quantity of that product on the line item. It also provides a field formatter to display the price/quantity values as a table."

---
Tags: commerce
---


title: Importing 'body' into 'paragraphs'

text:
# Question
Title: Importing 'body' into 'paragraphs'
I need to migrate an ordinary D7 multi-value long text field 'body' into D8 paragraphs . As paragraphs seem to be a reference, the migration will probably be more complex than just direct field mapping. Moreover, my target paragraphs include multiple fields, not only the text body but a title as well. Any idea or link how to accomplish this task?

# Answer
Paragraphs are entities in and of themselves - it's most straightforward to migrate the paragraphs separately, then populate the reference to the migrated paragraphs within the "parent" node migration.
> 0 votes

---
Tags: migrations, paragraphs
---


# Question
Title: Configuration of views with entity reference fields
I've read several guides about this subject but still incapable of achieving what I want.

I have a main content type (aventuras) and then another content type for images. The images are referenced to the main content type via an Entity Reference field.

I want to create a view that shows a list of all the nodes of the main content type (their titles and other fields) along with their images (reference field).

I think I need to add the "Entity Reference: Referenced Entity" relationship and then the image field with that relationship selected, but that is not working (it only shows fields of the main content type, no image).

I've tried several alternatives (contextual filters, adding also the relationship to the filter, using Referencing Entity instead of Referenced...) without any luck.

Maybe this is an annoying noobie question that has been answered before, but I've searched and tried a lot and I can't find the solution for my case.

Any clue would be much appreciated. Thanks!

# Answer
> 0 votes
> The images are referenced to the main content type via an Entity Reference field.

Who has the entity reference field? The Main content type (aventuras)? OR the Images content type?

Based on your question, I will guess the Main content type.

If the Main content type has the entity reference field, then **under Advanced** you need to add a relationship of Referec**ing** and NOT Referenc**ed** Entity (notice the bold endings).

Also, no need to add a relationship in the image field.

---
Tags: entities, views
---


# Question
Title: Substitute "Your Name" field for anonymous shown on posted comments
I am using the 'Corporate Clean' theme. I have allowed anonymous posting of comments for basic pages. When a person posts, there is a an input field called 'Your Name'. However when the comment is posted, Anonymous is showed instead. I would like to know how to substitute the Anonymous for the 'Your Name' field or if not, have the 'Your Name' show in the title line of comment.

thanks in advance.

Update : ok I have loaded a test site with bare minimum modules and tested comments again. It works this time - no issues. I can only assume one of the modules I have installed is causing this as I have not edited any files by hand. What is the best way to troubleshoot this?

# Answer
I found it was the antispam module and created a bug + patch
> 0 votes

---
Tags: comments
---


title: Compound key in database schema

text:
# Question
Title: Compound key in database schema
I'm trying to define a compound key for a custom database table.

My first insert goes through OK but the following inserts fail because the PID value is the same.

What I'm trying to achieve is a state where the uniqueness of each insert is determined by a combination of the **PID**, **QID** and **UID** values of each insertion.

The following is my schema in my install script:

```
function module_schema() {

  $schema = array();

  $schema['module_records'] = array(
    'description' => '',
    'fields' => array(
      'pid' => array(
        'description' => 'PID',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'User ID',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'qid' => array(
        'description' => 'QID',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'first' => array(
        'description' => 'First option',
        'type' => 'text',
        'length' => 255,
        'not null' => FALSE,
      ),
      'second' => array(
        'description' => 'Second option',
        'type' => 'text',
        'length' => 255,
        'not null' => FALSE,
      ),
    ),
    'primary key' => array('pid'),
    'indexes' => array(
      'uid' => array('uid'),
      'qid' => array('qid'),
    );

  return $schema;
}

```

# Answer
> 0 votes
You may define `'type' => 'serial'` if you want to auto increment your primary key.

---
Tags: database
---


# Question
Title: How Can I have Exposed filter for Taxonomy vocabulary in Heirarchical Select?
I use drupal 7 and simple hierarchical select module for filter views module result by taxonomy terms and taxonomy vocabularies.

my views have results only if select both vocabulary and taxonomy term from select list (exposed filter) .if I select only vocabulary from select list I have no any result for views.

So i want to have a exposed filter that can filter views by vocabulary (all its taxonomy terms) and taxonomy term (sub level of vocabulary) . please see this picture.

Is any other way for filter views result by both vocabulary and terms in heirarchically?

thank you beforehand.

# Answer
> 0 votes
I use the Simple hierarchical select module; in the filter fields, I selected *has taxonomy term (with dept) - simple\_hierarchical-select* and set its value to 1.

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


title: views_get_view() Memory Exhuasted

text:
# Question
Title: views_get_view() Memory Exhuasted
Im trying the following to bring up a view that only has 6 product nodes, and I get a WSOD with a Memory Exhausted warning, ive set it to 256MB, it shouldnt be flaking out on such a small request!

```
$view = views_get_view('products');
$view->set_display('Master');
$view->get_title();
$response = $view->preview('block');
dpm($response);

```

Am i doing something wrong?

# Answer
> 1 votes
Views is notoriously heavy with memory, but it does seem odd that a view that only touches 6 nodes would crap out at 256 MB.

I see you've got a `dpm` call there - does removing that and turning off the devel module make a difference? And do you have xdebug enabled or any other profiling enabled by any chance? All that stuff would contribute.

The other thing you might want to double check from phpinfo() is to see if your memory limit really is set to 256MB.

---
Tags: 7, views
---


# Question
Title: How do I write a template file for a specific input field?
I'm currently creating a custom theme for a drupal 8 site and I'm putting a comment section for blog posts like :

```
<section class="comment-section">
    {{ content.comment }}
</section>

```

That puts in the comment section, but now I want to style it. I have twig debug enabled and to customize a page or view I usually look at the inspector/page source and there are comments recommending file names such as page--node--1.html.twig and such. Unfortunately for these fields when I look for the textarea or title input the only suggestions are, for example, ../form/textarea.html.twig. I can't use those because they will effect every other textarea on the site, so how do I figure out what to name my file for these specific inputs?

I'm going to put in a screenshot of my elements console in case it has something to do with that:

# Answer
Checkout the following module: Themable forms

It adds the following theme suggestions:

```
form-element--[form-id]--[element-type].html.twig
form-element--form-id--[form-id].html.twig
form-element--type--[element-type].html.twig
form-element.html.twig

```

Or use theme suggestions hooks to create / alter a theme suggestion. See the following link:

Working With Twig Templates
> 1 votes

# Answer
If you want to add a more specific template name to an input element use a theme name suggestions alter hook:

*mytheme.theme*

```
function mytheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if ($element['#type'] == 'textfield' && strpos($element['#id'], 'edit-subject-') === 0) {
    $suggestions[] = 'input__textfield__subject';
  }
}

function mytheme_theme_suggestions_textarea_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if (strpos($element['#id'], 'edit-comment-body-') === 0) {
    $suggestions[] = 'textarea__comment_body';
  }
}

```

You find more information here hook\_theme\_suggestions\_HOOK\_alter.

If you don't find the data you need in the elements variables, then you have to add it in the form build process, for example in a form alter hook. In this case the form build has already provided the necessary information in the element id.
> 7 votes

---
Tags: theming, 8
---


# Question
Title: Need to redirect the non-existence URL's to 404 page instead of parent url
This is in connection to drupal.org issue #432384.

That's when I happen to request for page "node/1/aaa/bbbb", I'm served the response for "node/1" (it's parent page).

I can understand, this is the way Drupal menu system has been designed and works for some obvious reasons.

But I'm in a need to change this. Reason we have some aliased urls across the site, links from third party sites are taking (visitors and crawlers) to not existing page for which ideally http 404 response code and page not found to be returned. Instead Drupal showing it's parent page (with http res. code 200). This is leading to duplicate page in Google webmasters and misleading our genuine users.

I have found a patch to this issue. However it is working fine only for 80% of cases, some valid urls (admin/\*, sites/default/files/ * , system/ajax/\*, etc.,) leads to 404 page.

Would like to hear how others are dealing with this duplicate content issue concerning SEO and possible fix!

# Answer
You can always make decisions about what page should be rendered based on the request path when Drupal is initializing.

It is possible using hook\_init().

**Implementation**

For your case you could implement `hook_init()` in a custom module and use drupal\_not\_found() function as following:

```
<?php

/**
 * Implements hook_init().
 */
function YOURMODULE_init() {
    // Extract different variables that Drupal utilizes for routing
    $menu_item = menu_get_item();
    $path = $menu_item['path'];     // node/%
    $href = $menu_item['href'];     // node/1
    $current_path = current_path(); // node/1/broken

    // Check if the actual path ($current_path) is different than the Drupal assumption ($href)
    if ($href != $current_path) {
        // Redirect user to 404 page which will hanlde the HTTP response as well
        drupal_not_found();
    }
}

```

In this code it is assumed we are browsing http://website/node/1/broken that would normally display the content of http://website/node/1.

**Note**

You need to know that hook\_init() implementations would not always be called. (like when the page is cached). But in your case that would not cause any problem as with the same path you will always expect the same behavior.
> 1 votes

# Answer
Considering the comments of the previous answer:

* Only act on 'node' pages (aliased and not).
* Avoid 'page not found' repeating 2 times.

Furthermore removed the unused variable `$path`.

The code below also avoids a 404 for the path *'node/add'*. In case you use the Entity connect module that path might be followed by a dynamic token. The URL could then look like *'node/add/page/entityconnect-form-hmcOTIsupNLNBI-cZ-sSvjsbFISJeOfzT0VBpg0Sbpc'*. Obviously that is a path not "known" by Drupal that would otherwise incorrectly result in a 404.

```
/**
 * Implements hook_init().
 */
function YOURMODULE_init() {
  // Only act on 'node' pages (aliased and not) but not on 'node/add'.
  if (arg(0) === 'node' && arg(1) !== 'add') {
    // Extract different variables that Drupal utilizes for routing.
    $menu_item = menu_get_item();
    $href = $menu_item['href'];     // node/1
    $current_path = current_path(); // node/1/broken

    // Check if the actual path ($current_path) is different than the Drupal assumption ($href).
    if ($href != $current_path) {
      // Redirect user to 404 page which will handle the HTTP response as well.
      drupal_not_found();
      // Avoid 'page not found' repeating 2 times.
      drupal_exit();
    }
  }
}

```

**UPDATE**: There is now a Drupal 7 module Force 404 that solves just this.
> 2 votes

---
Tags: uri, 7
---


# Question
Title: Query condition on entity reference field count
I need to query an article with more than 1 tag (a field entity reference) in drupal entity query.

I tried this :

```
$query = Drupal::entityQuery('node')
                ->condition('type', 'article')
                ->condition('field_tags', 1, '>');
dd($query->execute());

```

But I got more than expected the articles id's and I don't why.

What is the good query to do that ?

# Answer
> 4 votes
Try to use the delta. This is explained here: QueryInterface:

```
$query = Drupal::entityQuery('node')
            ->condition('type', 'article')
            ->condition('field_tags.%delta', 1, '>');
dd($query->execute());

```

---
Tags: 8, database
---


# Question
Title: Action to be triggered on Comment Approval
How can add new rule to trigger when a comment approve, in Drupal 7?

# Answer
Currently there is no rules condition to do this but there is a patch in the rules issue queue. You can try using that, and if you do you can report back to that issue and help it get committed to the rules module. http://drupal.org/node/1421058#comment-6532372
> 2 votes

# Answer
An alternate way, You can use the hook hook\_comment\_publish in your custom module.

```
hook_comment_publish($comment)

```

> The comment is being published by the moderator.

For eg:

```
function YOURMODULENAME_comment_publish($comment) {
   //your codes to do task
}

```
> 0 votes

# Answer
This way you can achieve with rules
> 0 votes

---
Tags: rules, comments, actions
---


title: How to set title for video embed field

text:
# Question
Title: How to set title for video embed field
I've a video embed field, where I've a youtube video link, I've printed the same on the twig.

But it seems not to have the title for the iframe. How can I add one for iframe in drupal 8.

# Answer
> 0 votes
You can use Paragraphs and then add Title and Video Embed Field in the paragraph type, this is something like Field Collection in D7.

Video about How to use paragraphs.

---
Tags: 8, files
---


title: Rebuild the entity field maps

text:
# Question
Title: Rebuild the entity field maps
After deleting some fields and paragraph types, I have stale values in the entity field map - these cause notice-level errors in the /admin/reports/fields page, and seem to occasionally trigger weird exceptions.

I've tracked the stale data to `entity.definitions.bundle_field_map` entries in the {key\_value} table. Unfortunately, neither running cron nor synchronizing the configuration nor clearing the cache seems to update this.

I've deleted the entries from the table entirely, but they just stay gone. Is there a way to completely rebuild the map from the active configuration?

---

**Update**: For future reference, this problem (and similar entity schema corruption) was a likely consequence of mucking around with unalterable internals (type, machine name, etc) of existing fields. Never do that; this system is complex, easy to break, and basically impossible to get back into a consistent state without reinstalling or reverting to backup.

*Any* changes to the storage of a field should be done by **creating a new field, copying data, and deleting the old field**. Even if you want to retain the existing machine name, it is easier to follow these steps *twice* (using a temporary field) than to try to touch the internals.

(Also, some aspects of the schema seem to be updated by cron, so before reusing a deleted field's machine name, make sure to run cron to let it perform cleanup.)

# Answer
> 0 votes
Update: It seems this data is never rebuilt in full, but is only updated by a field definition listener.

One possible solution is to remove all fields and bundles from the site (by deleting the configuration from the sync folder and importing), then re-creating them (by reverting the deletions and importing again). This will obviously delete any content that may have been created.

---
Tags: 8, entities
---


# Question
Title: How to put a custom message in the message module template?
I am using the Message module with Drupal 8 to log information.

I was able to get the date and time in the messages produced by adding a token of the date and time , but I want to add a customized message that is different each time. How can I do this? this is the code I am using:

```
 $message = Message::create(['template' => 'sfbu_progress']);
 $message->save();

```

How can I add a customized message to each message created? For Example I want it to say "This file 444.pdf was successfully uploaded" or "this file 888.pdf was missing ".

# Answer
Checkout the setArguments(), getText() and the processArguments() function in the Message Entity class:

```
$message = Message::create(['template' => 'sfbu_progress']);
$message->setArguments([
   '@my_argument' => 'my_argument_value',
]);
$message->save();

```

And in your Template which you create over the UI write the @my\_argument to the textarea. It should be replaced with your text.

It is also possible to add an callback function as argument. Therefor checkout the declaration of the argument property in MessageTemplate Entity class.
> 2 votes

---
Tags: 8
---


title: List all terms under a parent

text:
# Question
Title: List all terms under a parent
I want to create a taxonomy view, which only displays terms that belong to a certain parent.

However, the "Term ID with depth" filter that appears in a normal view seems to be missing in the Term View type.

Any ideas how I might go about achieveing this?

# Answer
just add a relationship for "Taxonomy term: Parent term" and select "require this relationship". Then add a contextual filter for termID, select "parent" as the relationship and select a fixed value of the parentID.

You can also do it without using relationships. Just add a contextual filter for "Taxonomy term: Parent term" and provide a fixed value for the parent term.
> 3 votes

# Answer
in drupal 8 (maybe also in late versions of drupal 7) there is a regular filter "Filter the results of "Taxonomy: Term" by the parent pid." that will allow you to enter the TID and will filter only children of this term
> 0 votes

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


title: Admin menu hiding my Navbar

text:
# Question
Title: Admin menu hiding my Navbar
In Drupal 8, how can I stop the admin toolbar from hiding my fixed navbar when I am logged in?

# Answer
> 1 votes
You can move your nav a bit below when you have an admin-logged in, try this :

```
body.admin-menu .navbar-fixed-top {
top: 30px; }

```

Better yet, use Adminimal Theme (Admin Theme) which should automatically take care of everything.

---
Tags: 8, toolbar
---


# Question
Title: View / Twig Extension : Display other items with the same field value
I work on a view block which displays a list of parts (content Type : parts), here are simplified examples of parts and fields :

* part\_ref || part\_id
* ABCD || 10
* BCDE || 11
* CDEF || 11
* DEFG || 11
* EFGH || 12

In my View Filters, only one part is displayed, filtered by "part\_ref". What I would like to do is to display other parts with the same "part\_id".

For example, "BCDE" is displayed, I would like to display also "CDEF" and "DEFG".

I have created a Twig Extension in order to do something like : {{ displayRelated(11) }}

But inside my function "displayRelated", Idon't know how to get parts with the passed "part\_id".

Does someone have a link or something to guide me ? I cannot find anything on google.

Or maybe it's not the right approach ?

Thanks in advance.

# Answer
> 0 votes
I finally found a solution with a function in my Twig Extension. I don't know if it's a clean way to do it but it works.

The function is called from the twig file :

`{% set parts = partsSameId(part_id) %}`

This is the simplified code inside the twig extension php file :

```
<?php

public function partsSameId($part_id) {

    // Get nodes with the same part_id
    $nids = \Drupal::entityQuery('node')
      ->condition('type','my_custom_content_type')
      ->condition('my_custom_field_for_part_id',$part_id)
      ->execute();

    // return array
    $html = [];

    // For each node returned, get the title.
    $i = 0;

    foreach ($nids as $the_node){
      $node = \Drupal::entityTypeManager()->getStorage('node')->load($the_node);
      $part_name = $node->getTitle();

      // return array
      $html[$i]['part_name'] = $part_name;

      $i++;
    }

    return $html;
  }

```

---
Tags: views, theming
---


# Question
Title: Is it possible to translate the suffix of an integer field?
Is it possible to translate the suffix of an integer field? The prefix/suffix settings doesn't appear under the translate section for the field. And I tried searching for the string in "Translate interface" with no luck.

The field is being used in a view where all the fields are in a list, any alternative solutions are also welcome. Using Drupal 7.

# Answer
I didn't find a solution to actually translate the suffix. Instead I added a rewrite of the field in the view where it was used, and rewrites show up in the translate settings in the view.

So the solution is, don't use a suffix. Instead add a rewrite option to the field where you use it, and translate that rewrite option instead.
> 3 votes

# Answer
For Drupal 7, patch #56 from https://www.drupal.org/node/1221208 allows the prefix and suffix to be translated through the regular translate interface.
> 1 votes

---
Tags: 7, views, entities, i18n-l10n
---


# Question
Title: 7 mysql workbench get the values of entity reference fields of a content type in a node page
I am using MySQLWorkbench queries to update some values. Those values are entity reference fields of a content type.

```
 foreach ($node->field_media_types['und'] as $mt) {
    $media_types[$mt['field_media_type']['und'][0]['value']] = $mt['field_media_file']['und'][0]['value'];}

```

The code above is how it is access on a script. I want using MySQLWorkbench or just MySQL CLI acces those values on quick queries.

```
select entity_id, field_media_file_value from field_data_field_media_file order by entity_id desc;
(0 rows return)

```

How do I do it? Is it possible?

# Answer
> 0 votes
Yes it is absolutely possible, and your query you posted is written correctly. If you are returning 0 rows that means there are no records inside the table field\_data\_field\_media\_file. Your query literally says to return everything in that table, and 0 things come back.

Review all of the tables in your database and make sure "field\_data\_field\_media\_file" is what the field is actually called. Either you are looking at an old/wrong field OR there is simply no nodes with this entity reference field populated.

for your reference the tables relate like this:

**The parent node that has the reference**

```
{Node}.nid => {field_data_field_media_file}.entity_id

```

**The node that is being referenced**

```
{field_data_field_media_file}.field_media_file_value => {node}.nid

```

---
Tags: 7, entities, database
---


# Question
Title: pass custom variable for image field from preprocess node to twig
I have a content type (`gallery`) with an image field which is unlimited: `field_picture`.
I have a logic which calculates custom css classes to their HTML containers, like: `grid-item--width1`, `grid-item--width2`, `grid-item--height1`, `grid-item--height2`.
I store these in the `grid_class`.
I can't merge these classes with the item class, because I want to style different HTML containers by them.

I tried to add this new variable (grid\_class) to the image elements from the `mytheme_preprocess_node__gallery` and I thought drupal8 will pass them to the twig template.

```
function mytheme_preprocess_node__gallery(&$variables)
{
  foreach (Element::children($variables['elements']['field_picture']) as $key) {
    // here is my logic which calculates the classes for the image elements' containers
    $grid_class = "grid-item--width1 grid-item--height1";
    $variables['elements']['field_picture'][ $key ]['grid_class'] = $grid_class;
  }
}

```

but in my twig template (`themes/custom/mytheme/templates/field/field--node--field-picture--gallery.html.twig`) when I loop through the `items`, the `grid_class` isn't available.

```
{% for key, item in items %}

    {{ (dump(item)) }}

    <div{{ item.attributes }}>
      <div class="grid-item {{ item.grid_class }}">{{ item.content }}</div>
    </div>
{% endfor %}

```

I also tried to add it from `mytheme_preprocess_field()`. I saw the array of the `field_picture` element, but I didn't find the items in there.

any help or hints?

# Answer
> 1 votes
I found that I have to use the `mytheme_preprocess_field` hook.

```
function mytheme_preprocess_field(&$variables) {
  if ($variables['field_name'] == "field_picture") {
    foreach ($variables['items'] as $key => $item) {
      $grid_class = "grid-item--width1 grid-item--height1";
      $variables['items'][ $key ]['grid_class'] = $grid_class;
    }
  }
}

```

---
Tags: 8, theming
---


title: Publish dynamic pages?

text:
# Question
Title: Publish dynamic pages?
I want to create a website with form, where users can insert the information in the form and then on form submit, information goes into a database table and also goes to the third party API.

Administrators can modify the specific record and add more information, and then publish this record as a web page with a unique URL.

Is it possible in Drupal 8?
How can I achieve that? Is there any specific module I need to use?

# Answer
I'm not sure if in D8 webform submissions are useable, fieldable entities yet.

Although I believe the EForm module may work as you expect. Allowing you to define forms the public can fill out and then very easily turn the content into drupal "pages" or reachable content at some url pathauto pattern.

Allowing the public and administrators to modified different fields, or subsequently edit submitted data is a Roles/Permission issue that drupal Core or other modules such as Field Permissions will let you achieve.
> 1 votes

---
Tags: 8
---


# Question
Title: How do I allow iframe embeds to a particular domain?
I see that Drupal now automatically adds the 'X-Frame-Options: SAMEORIGIN' header. However, the client would like to give explicit permission to allow a `iframe` embed to another site.

How do I allow iframe embeds to a particular domain?

# Answer
If I'm understanding you correctly, this is actually an Apache setting. X-Frame-Options by default are SAMEORIGIN for security reasons. This option helps secure your site again various attacks.

To allow a specific domain to access your site (cross origin) you find the X-Frame-Options setting in your Apache configuration file and change it to say:

```
Header always append X-Frame-Options ALLOW-FROM=http://www.example.com

```

You will need access to the site server in order to do this. Also understand you will need to find the proper configuration file to add this to. Depending on the server setup this could be something different than the default httpd.conf or apache2.conf file.
> 2 votes

# Answer
https://www.drupal.org/project/seckit

you can set security level and also set exceptions
> 3 votes

---
Tags: 7
---


# Question
Title: How to configure the existing search system to exclude content types and/or nodes from the search index?
As far as I see, the search api has no effect on the existing search. The video about State of Search Drupal 8 - Basic Usage of Search API indicates that you have to supply an own view for the search results.

Isn't there a way to configure the existing search system to exclude content types and/or nodes from the search index?

# Answer
> 4 votes
There is a new Search Exclude (Node) module

> Exclude content types from node search for Drupal 8.

# Answer
> 4 votes
In D8 you can use the following code to alter the core node search. The following code would restrict the node search results to 'article' content type. You should be able to use any conditions here you like.

```
<?php

/**
 * @file
 * Module that alters search queries.
 */

use Drupal\Core\Database\Query\AlterableInterface;

/**
 * Implements hook_query_TAG_alter(): tag search_$type with $type node_search.
 */
function MYMODULE_query_search_node_search_alter(AlterableInterface $query) {
  // For testing purposes, restrict the query to node type 'article' only.
  $query->condition('n.type', 'article');
}

```

Hope this helps.

Mark

# Answer
> 1 votes
Drupal Custom Search will allow you to prevent Content Types from getting in the default Drupal Search https://www.drupal.org/project/custom\_search

---
Tags: nodes, 8, search
---


# Question
Title: how to get uri of an image field in a views_view_list twig template using drupal 8?
I have a twig template generated from **views-view-list.html.twig**!
Its a view uses ECK entities.

```
Available variables:
- attributes: HTML attributes for the container.
- rows: A list of rows for this list.
  - attributes: The row's HTML attributes.
  - content: The row's contents.
- title: The title of this group of rows. May be empty.
- list: @todo.
  - type: Starting tag will be either a ul or ol.
  - attributes: HTML attributes for the list element.

```

I would need to access the image field of my eck entity (field\_background\_image) in this template, because it is necessary for the slideshow logic to display the thumbnail. I tried a lot of different ways.

This is how my template looks like

```
<div class="slider-container">
  <div class="slider-fullwidth">
    <{{ list.type }}{{ list.attributes }}>

      {% for row in rows %}
      <li{{ row.attributes }}
        data-thumb="{{ row.content['#slider'].field_background_image[0].??? }}"
        data-title="{{ row.content['#slider'].title[0].value }}"
        data-transition="slideup">{{ row.content }}</li>
      {% endfor %}

    </{{ list.type }}>
  </div>
</div>

```

I can access the `title` property this way (is there a better way?):

```
{{ row.content['#slider'].title[0].value }}

```

I would like to access the `field_background_image` property of my entity.

`row.content['#slider'].field_background_image[0]` is a `Drupal\image\Plugin\Field\FieldType\ImageItem`. I would need to get the uri value of the `field_background_image` field so that I can use the ImageStyle on it:

```
ImageStyle::load($imageStyle)->buildUrl($imageField[0]['#item']->entity->uri->value)

```

I don't find this in the tree..

# Answer
Finally this was my solution.

The template:

```
<div class="slider-container">
  <div class="slider-fullwidth">
    <{{ list.type }}{{ list.attributes }}>

      {% for row in rows %}
      <li{{ row.attributes }}
        data-thumb="{{ row.content['#slider'].field_background_image|imagestyleurl2('slider_thumbnail') }}"
        data-title="{{ row.content['#slider'].title[0].value }}"
        data-transition="slideup">{{ row.content }}</li>
      {% endfor %}

    </{{ list.type }}>
  </div>
</div>

```

Twig filter:

class ImageStyleTwig extends \Twig\_Extension {

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

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

/**
 * Get the url of the image by an image style
 */
public static function imageStyleUrl1($imageField, $imageStyle)
{
  return ImageStyle::load($imageStyle)->buildUrl($imageField[0]['#item']->entity->uri->value);
}

public static function imageStyleUrl2($imageField, $imageStyle)
{
  return ImageStyle::load($imageStyle)->buildUrl($imageField->entity->uri->value);
}

```

}
> 1 votes

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


title: What should I pass as --core parameter?

text:
# Question
Title: What should I pass as --core parameter?
I'm having trouble using `Drush` version 8 to pull down an instance of Drupal 7. I've tried variations of `drush qd --core=7 d7_no`, but all seem to fail.

> No release history was found for the requested project (7).
> Could not download requested project(s).

Also `drush qd --core=7.x d7_no` fails.

> No release history was found for the requested project (7.x).
> Could not download requested project(s).

What should I pass as `--core`?

# Answer
> 2 votes
From the qd help output:

```
$ ./drush.phar help qd
Download, install, serve and login to Drupal with minimal configuration and dependencies.

Examples:
 drush qd                                  Download and install stable release of Drupal into a
                                           timestamped directory, start server, and open the
                                           site logged in as admin.
 drush qd --profile=minimal --cache        Fire up dev release of Drupal site with minimal
 --core=drupal-8.0.x --yes                 install profile.
 drush qd testsite devel                   Fire up stable release (using the cache) of Drupal
 --server=:8081/admin --browser=firefox    site called "testsite", download and enable devel
 --cache --yes                             module, start a server on port 8081 and open /admin
                                           in firefox.
 drush qd commercesite                     Download and install the "Commerce Kickstart"
 --core=commerce_kickstart                 distribution/install profile, display watchdog
 --profile=commerce_kickstart --cache      messages on the server console.
 --yes --watchdog
 drush qd --makefile=mysite.make           Create and install a site from a makefile.

```

It should be inferred that `drupal-<Sematic Version Piece>` would be the project name you're downloading from the `--core=drupal-8.0.x` example provided.

So the following should work I believe:

* `drupal-7`
* `drupal-7.x`
* `drupal-7.N.x`

Actually Drupal 7 doesnt follow semantic versioning. So D7 would require either `drupal-7` or `drupal-7.NN`. The above drupal examples would apply to drupal 8 and beyond as of 06-01-2017 due to semvar usage in drupal.

# Answer
> 1 votes
Try `--core=drupal-7` instead of `--core=7`.

---
Tags: drush
---


# Question
Title: "Twig_Error_Loader: Template "file.html.twig" is not defined" for new twig template file
After creating a new paragraph type and its template file in the correct folder location, I am receiving the following error every time I view the page with that houses the new paragraph type.

**Twig\_Error\_Loader: Template "file.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "file.html.twig" in the Drupal theme registry.)**

I have followed the steps here to disable the cache. However I don't believe it worked because I still have to clear my cache through config\>performance for changes to twig files to appear.

Similarly, I tried to enable twig debugging (and turn off caching) here and can not confirm that it has been enabled either.

I found an article: blog.wturrell.co.uk/troubleshooting-drupalcoretemplateloaderthemeregistryloader-unable-to-find-template/ discussing potentially clearing the theme-registry, but I do not have access to drush to run any commands.

I have already tried clearing all the cache from within drupal itself.

# Answer
> 2 votes
Cache is a pretty broad concept, and sometimes mean content caching and sometimes they mean broader things like config settings and the theme registry. Disabling content caching is still a bit confusing to me so I can't help with that part of the question.

But the theme registry has some pretty simple rules. If you add new template file (or change it's name or move it to a different folder) or if you add a new theme callback (in hook\_theme) or override to a theme callback (hook\_preprocess...) then you MUST clear the theme registry before they will be active. To do that, the simplest method (without additional modules or drush) is to 'Clear all caches' under admin-\>config-\>development-\>performance.

Of note, sometimes the theme registry is referred to as the theme cache. While I know it's probably possible, I don't think that disabling the theme registry from caching is a standard practice in development.

---
Tags: theming, 8, drush, caching, debugging
---


# Question
Title: Dynamic form fields using #states array on empty select field
Trying to make the second field only visible when there is a value in the first controller field. If nothing is selected in the initial load of the screen, the second field should be hidden.

Because the controller api\_title is a sub array I'm not sure how to set the comparison value in condition name='api\_title'

```
$form['api_title_filter_widget'] = array('#tree' => true, '#weight' => '10');
$form['api_title_filter_widget']['api_title'] = array(
        '#type' => 'select',
        '#title' => 'API Title',
        '#default_value' => $api,
        '#options' => ["" => "- Select -"] + $published_api_proxies,
        '#ajax' => array(
            'event' => 'change',
            'callback' => 'callback_api_product_filter',
            'method' => 'replace',
            'wrapper' => 'api_products_controlled_by_filter',
        ),
    );

$form['api_product']['#states'] = array(
                                   'visible' => array(
                                        '**select[name="api_title"]' =>**
                                          array('!value' => ''),
                                            ),
                                         );

```

# Answer
Maybe you can try to add an id to your select field

```
$form['api_title_filter_widget']['api_title'] = [
  '#type' => 'select',
  '#title' => 'API Title',
  '#default_value' => $api,
  '#options' => ["" => "- Select -"] + $published_api_proxies,
  '#ajax' => [
    'event' => 'change',
    'callback' => 'callback_api_product_filter',
    'method' => 'replace',
    'wrapper' => 'api_products_controlled_by_filter',
  ],
  '#attributes' => [
    'id' => 'my_api_title'
  ],
];

```

Then you should be able to target it through its id :

```
$form['api_product']['#states'] = [
  'visible' => [
    ':select[id="my_api_title"]' => ['filled' => TRUE],
  ],
];

```
> 1 votes

---
Tags: javascript
---


# Question
Title: Creating new users with Commerce & Rules: ERROR
Commerce has a problem with the Rule to create a new User account for an anonymous order:

```
ERROR: Missing configuration for parameter param_field_[fieldname]

```

According to a drupalcommerce.org comment this is because of fields being required:

> The rule “Create a new account for an anonymous order” will fail if any of the fields it attempts to create are required. That failure will generate the ERROR: Missing configuration for parameter param\_field\_.

Despite this insight, no answer is give for how to take care of the error. It is necessary to my site to require some fields upon user registration. How can I get rid of this error?

# Answer
> 2 votes
During anonymous checkout, an email address is collected from the 'Account information' pane to create a new user (or append the order to an existing user).

You should be able to hook into the form on the 'Account information' pane and add your required fields. You will probably have to modify the rule (Create a new account for an anonymous order) to send along the extra fields for creating a new user with the required fields - when marked required, custom fields added to the user are added to the Create Entity action for user as well.

You can populate these fields using existing variables, or fields added to the Commerce Order or Commerce Billing Profile, or create your own variables (eg via `hook_token_info_alter()` to make variables available through the commerce\_order).

# Answer
> 0 votes
Another option is to use the Commerce User Profile Pane and add the required field(s) to it.

---
Tags: commerce, rules, users
---


# Question
Title: Can I run drush command from composer with custom script
I have a nested root Drupal 8 site. I would like to create an import and deploy script that runs multiple drush commands. Is this possible via custom script?

# Answer
> 1 votes
I was able to do this. Here is a simple example:

First, create a file called import.sh and place it in the scripts folder.

```
#!/bin/bash

# Exit immediately on errors, and echo commands as they are executed.
set -ex

# Run coniguration import.
cd web
echo "Running coniguration import (config split imoprt)"
drush config-split-import -y

# Clear Cache.
drush cr

```

Second update composer.json by adding the script to the scripts folder.

```
"scripts": {
  "import": [
    "./scripts/import.sh"
  ]
},

```

Now you can run `composer import`

---
Tags: 8, composer
---


# Question
Title: How do I create a configuration menu with the selected section name?
I want to create a menu in the admin section that is in the sitename/admin/config path.

As of now, I am doing this.

### Routing file

```
custom_menu.adminmenu_section:
    path: '/admin/config/custommenu'
    defaults:
        _controller: 'Drupal\custom_menu\Controller\CustomMenuController::content'
        _title: 'Custom Menu Configuration'
    requirements:
        _permission: 'administer site configuration'

custom_menu.admin_menu:
    path: '/admin/config/custommenu/customconf'
    defaults:
        _form: 'Drupal\custom_menu\Form\CustomMenuForm'
        _title: Custom Menu creation
    requirements:
        _permission: 'administer site configuration'

```

### links.menu file

```
custom_menu.adminmenu_section:
    title: 'Configuration'
    description: 'Custom Menus Configuration section'
    parent: system.admin
    route_name: custom_menu.adminmenu_section

custom_menu.admin_menu:
    title: 'Custom Menus Conf'
    description: 'Custom Menus Configuration section'
    parent: custom_menu.adminmenu_section
    route_name: custom_menu.admin_menu

```

This code is not creating a section in the `admin/config` path. But when I used **parent: system.admin\_config** that time I will get menu in the admin section but the section name will be `CONFIGURATION`. Because its title given in the `system.admin_config` route, but I don't want that name.

I want to create a section with separate name. How can I achieve that?

# Answer
I tested it with your code and you just have to change two little things in your custom\_menu.adminmenu\_section. The rest is ok. See below:

**module.links.menu.yml**

```
custom_menu.adminmenu_section:
  title: 'Configuration' <= change this to your section name
  description: 'Custom Menus Configuration section'
  parent: system.admin_config  <= change this to system.admin_config
  route_name: custom_menu.adminmenu_section

```
> 1 votes

---
Tags: routes
---


# Question
Title: Why is cache_discovery not rebuilt on cache-rebuild?
In my local dev environment `drush cr` does not rebuild the `cache_discovery` table. I have to manually truncate it. Is it because `expire` is set to `-1` on all rows? If so, did I mess something up in setting up this site?

I *think* I could add `$settings['cache']['bins']['discovery'] = 'cache.backend.null';` in my local settings file, but then I'd have to truncate it in production when making changes like the one that brought this up. This doesn't seem right.

Maybe I'm just missing a setting somewhere, but `drush cr`, `rebuild.php`, and restarting apache all leave `cache_discovery` exactly as it was.

# Answer
> 1 votes
If you truncate the table `cache_discovery` and then do a cache-rebuild the table is filled again with data, what would not be, if this was still a cache-clear. In D8 clearing the cache is more like rebuilding the cache, hence the new name. Some tables are still cleared, like the render cache or the twig cache, because these are filled with new data from the result of each request. But the structural data like discovery, router, config and some more are rebuilt, so that the first request after clearing the cache doesn't take too long.

If you set `$settings['cache']['bins']['discovery'] = 'cache.backend.null';`, then you freeze the table content. It is not touched, even not by a cache rebuild, until you remove this setting.

---
Tags: 8, caching
---


title: Create new menu with a module

text:
# Question
Title: Create new menu with a module
I want to create a new menu in Drupal 8 when I install my module. How can I achieve this?

I don't want to add a link to an existing menu, but create a new one.

# Answer
You can either include the menu in your modules default configuration by adding a file to config/install folder of the module:

system.menu.menu-name.yml:

```
langcode: en
status: true
dependencies: {  }
id: menu-name
label: 'Menu label'
description: 'Menu description'
locked: false

```

You can also create the Menu entity, perhaps in the hook\_install() hook.

```
use Drupal\system\Entity\Menu;

function MY_MODULE_install() {
  $menu = Menu::create([
    'id' => 'menu_id',
    'label' => 'Menu label',
  ])->save();
}

```
> 8 votes

# Answer
Menus are just entities in Drupal 8. Just create it with:

```
\Drupal\menu\Entity\Menu::create([
  'id' => 'my_menu',
  'label' => 'My Menu',
  'description' => 'This is my menu!',
]);

```

Use this in the hook\_install() so the menu is created in the installation process.
> 0 votes

---
Tags: 8, navigation
---


title: Different domain per node

text:
# Question
Title: Different domain per node
I wonder if it is possible to have different domains set for, for instance, per path basis, or view basis, or node id basis?

# Answer
> 0 votes
Domain Access is great module that allows you to different domains set for instance, per path basis, or view basis, or node id basis.

`The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database`.

---
Tags: domain-access
---


# Question
Title: Is it possible to use Apache Solr to search across multiple sites?
I'm completely new to Solr and roughly understand the basic principles of setting up a search engine but not (yet) the specifics.

I'm beginning work on a site which will display search results from the content in the site (Articles), however, we also want to allow visitors to use the same search form to return - in the same page - results from both our own site, and from other external sites which could be indexed in Solr but are not Drupal sites.

Is this even possible or am I wasting my time? Many thanks for any insights.

# Answer
> 2 votes
Solr can be thought of as a document oriented database , it has a schema based, and a schema-less mode.

When used from the drupal module it uses a schema.xml file to specify what it expects to find in the documents (and hence index).

so if you go down that option one way you could search across the external domain and the drupal site is index the external domain to that schema, extending it where necessary

if you've got a title field in both sets of data , then it will index title that way. if your external site has different fields you could add them to the schema you'll want to define a minimal shared set that documents from either site share, to make themeing, and UX easier.

The process I would probably go for is

1. create a schema that covers both sources of data
2. configure Drupal to use that schema and index the site
3. index the external site (Solr 5 has a crawler now, or might just be easier to build a CSV file with curl)

that would get you to a place where you can search across the 2 sites from the Drupal search. It would be a case of getting the theme/markup right to represent offsite vs onsite results.

---
Tags: search
---


title: View with 2 taxonomy term in url

text:
# Question
Title: View with 2 taxonomy term in url
I a new Drupal 8 user :) and I have a problem with my view !

The context: I have a content type Car with Brand (Taxonomy term ) and Color (Taxo term)

I want to know if it's possible to have this url:

```
mywebsite/ => view with all cars

mywebsite/brand => view with all cars for the brand

mywebsite/brand/color => view with all cars for the brand with the color

```

This is my view

I don't know if it's possbile but I try :)

Thx for you help And see you soon

# Answer
> 0 votes
Set the path to:

```
cars/%taxonomy_term/%taxonomy_term

```

Then add two relations in the advanced section:

```
Taxonomy term referenced from field_brand
Taxonomy term referenced from field_color

```

Then add two times the following context filter:

```
Name (Taxonomy Term)

```

Select in the first context filter the relationship `field_brand` and in the second context filter the `field_color`:

now it should work as expected.

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


title: Route, set meta title in controller

text:
# Question
Title: Route, set meta title in controller
I have a route that takes data from APIs, so I would like to set the title in the controller and not in the getTitle function because it would mean calling 2 or more times the same API

# Answer
I don't think you can, not out of the box at least, but there's no reason to. Just use a static var, it will mean the API is contacted only once per request:

```
function getTitle() {
  static $title = '';

  if (!strlen($title)) {
    $title = $this->getTitleFromAPI();
  }

  return $title;
}

```
> 0 votes

---
Tags: 8, routes
---


# Question
Title: How do I get a parent-group alias as token for the Pathauto module?
When a user sets his groups alias to lets say "mynewgroup" you can view the group at www.example.com/mynewgroup.

How to set pathauto presets to create www.example.com/mynewgroup/mynewgroupcontent as a path for a newly created group-content?

I can not find a token for parent's group alias. I can only find \[group\_content:gid:entity:url\] - but this provides full path and not only the alias.

# Answer
> 1 votes
Not possible at the moment (unless you make it yourself), there is an issue in the module's issue queue though that also has a patch that might work:

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

---
Tags: 8, path-aliases, group
---


# Question
Title: Change display order of a content type fields in the view tab
How can i change the **`order of displaying fields`** details of a node of a content type in D8 ? Its neither specified in the **`Manage form display`** or in the **`Manage display`** of the content type management menu .

**`PS`** : I have added existing fields from another content type to this content type . Will that's display order taken in to this ? How can i change this ?

# Answer
> 2 votes
The fields are sorted by weight, which is hidden by default, because you can reorder the rows by dragging. You can switch off dragging and input the weights by hand with *Show row weights*.

Doesn't matter if the fields are used in multiple content types, you can arrange them in each content type individually.

---
Tags: 8, entities, nodes
---


# Question
Title: Webform2PDF doesn't display arabic characters
I'm using webform2pdf with TCPDF library to generate pdf of submissions, I have some arabic words in the submissions, the generetaed pdf doesn't display them.
Is there any config to do to solve this issue?

# Answer
It solved, I just changed the font to 'DejaVu Sans' in Generate-PDF settings.
> 0 votes

---
Tags: webforms, files
---


# Question
Title: field collection items are not in panels
Im trying to use Panels to display a Field collection but it looks like it is not in the overlay (see screenshot). How can I display the field collection in my panels?

# Answer
> 0 votes
I think the method depends on what you are trying to achieve by doing this.

Hope this helps, without your intended use-case in your question it is difficult to provide a meaningful answer.

# Answer
> 0 votes
Panels 7x 3.9 got built in support for field collection items, guess it was a later addition, available now as form and node elemens.

it's not obvious at first, since the collections are listed with "field:..." same as normal fields.

saw it due to the habbit of "prefixing" all field collection items with fc\_ (field\_fc\_name) makes 'em stand out a bit more.

Hope it helps, good luck to all ;)

---
Tags: panels, entities
---


title: Convert a variable to a string

text:
# Question
Title: Convert a variable to a string
Using Drupal 8, I have a media field where someone can upload an SVG file. I have this field display set to output as the URL path to the file.
I'm trying to get this value as a string (currently it's a render array) so I can call it with `{% include var %}` and embed the SVG directly into the DOM.

For example, I have this code. (I'm using twig\_field\_value.)

```
{% set var = content.field_media_name|field_value %}

```

If I render the variable in the template with `{{ var }}`, it spits out a string onto the screen, for example /sites/default/files/pathto/file.svg.

If I manually copy-paste this string into my twig template, e.g. `{% include '/sites/default/files/pathto/file.svg'%}`, it works perfectly, just like I want. However, I want to use `{% include var %}`, which is causing a PHP error because it can't include a template file because the var is actually an array.

This field can only have a single value. What I need is figuring out how to convert this into an actual string so I can use it with `include`.

# Answer
This works:

```
{% include file_url(content.field_media_name|field_target_entity.field_file_upload.entity.uri.value) %}

```
> 0 votes

---
Tags: theming
---


# Question
Title: Importing 'alt' and 'title' fields does not work for custom image migration
I'm doing a D7-\>8 custom migration. While images (even multiple) get imported fine via a separate file migration based on d7\_file, 'alt' and 'title' tags are not migrated at all. The images are imported via

```
field_galerie:
  plugin: iterator
  source: field_galerie
  process:
    target_id:
      plugin: migration
      migration: luxus_files
      source: fid

```

Any help appreciated!

# Answer
You're only mapping the fid there - you need to also map the alt and title for them to come over:

```
field_galerie:
  plugin: iterator
  source: field_galerie
  process:
    target_id:
      plugin: migration
      migration: luxus_files
      source: fid
    alt: alt
    title: title

```
> 0 votes

---
Tags: entities, media, migrations
---


# Question
Title: Views expose filter with ajax showing validation message after reloading page?
I added a date filter that showing select list for `year` and `month`. I created the block type view. When I select the `month` and submit the form it makes the red border outside the `year`. But when I reload the page or go to another page it gives me the error :

```
Please choose a year.

```

How to show error message at the time of form submit?

Any Solution???

# Answer
I ran into this issue too recently. I didn't try the javascript solution posted above, because I found this thread on d.o that seemed to solve the issue for me, so thought I would add it here as another option: https://www.drupal.org/node/1833322#comment-9184301

Specifically, the comment provides this code:

```
function MODULE_views_ajax_data_alter(&$commands, $view) {
  $commands[] = ajax_command_prepend($commands[0]['selector'], theme('status_messages'));
}

```
> 0 votes

# Answer
Disable the **Ajax for exposed filter**, It will show only the message on form submit.
> 0 votes

# Answer
Solved this using custom javascript code.

```
    jQuery(".views-exposed-form #edit-date-filter-value-year").live('change',function(){
    jQuery('#edit-date-filter-value-year').removeClass("error");
    var month=jQuery('#edit-date-filter-value-month').val();
    if(jQuery('#edit-date-filter-value-year').val()==""){
        jQuery('#edit-date-filter-value-year').addClass("error");
        jQuery('input[type="submit"]').attr('disabled','disabled');
        jQuery('input[type="submit"]').css('background', '#dedede');
    }
    else if(month=="") {
        jQuery('#edit-date-filter-value-month').focus();
        jQuery('#edit-date-filter-value-month').addClass("error");
        jQuery('input[type="submit"]').attr('disabled','disabled');
        jQuery('input[type="submit"]').css('background', '#dedede');
    }
    else {
        jQuery('input[type="submit"]').removeAttr('disabled');
        jQuery('input[type="submit"]').css('background', '');
    }
});

jQuery('.views-exposed-form #edit-date-filter-value-month').live('change',function(){
    jQuery('#edit-date-filter-value-month').removeClass("error");
    var year=jQuery('#edit-date-filter-value-year').val();
    if(jQuery('#edit-date-filter-value-month').val()==""){
        jQuery('#edit-date-filter-value-month').addClass("error");
        jQuery('input[type="submit"]').attr('disabled','disabled');
        jQuery('input[type="submit"]').css('background', '#dedede');
    }
    else if(year=="") {
        jQuery('#edit-date-filter-value-year').focus();
        jQuery('#edit-date-filter-value-year').addClass("error");
        jQuery('input[type="submit"]').attr('disabled','disabled');
        jQuery('input[type="submit"]').css('background', '#dedede');
    }
    else{
        jQuery('input[type="submit"]').removeAttr('disabled');
        jQuery('input[type="submit"]').css('background', '');
    }
});

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Rules to create an autoresponder for a Webform submission?
I need to create a Rule to create a autoresponder email for a Webform submission.

This is: the webform has only the "email" field. When the form is submitted the rule should fetch the the 'email account' entered in the email form field and send an email to that account. That's all.

I already enabled the Webform Rules module but I see to way to fetch the email value from the rule I created.

What am I missing here?

# Answer
You do have access to all ***labels*** and all ***values*** of any field of a webform, ie:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name MachineFieldName.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name MachineFieldName

So in your case, you should be able to get it to work using something like `[data:email-id]` (assuming that's what corresponds to the "*email field*" in your case).

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

* the *1st attempt* relates to using "Entity has field" (which doesn't work for Webform)
* the *2nd attempt* explains what to do in case of Webform.

The above is a good start, but not sufficient to achieve your goal (= "*When the form is submitted the rule should fetch the 'email account' entered in the email form field*", as in your question). However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

* Add an extra Rules Action to `Add a variable`, with a value assigned to it equal to your `[data:EmailAccountField-value-raw]` (and with an appropriate data type). I'm assuming your eMail field in your webform has a machine name like `EmailAccountField` (adapt to fit your machine name).
* In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).

PS: I'm assuming this question is about D7.
> 2 votes

---
Tags: rules, webforms
---


# Question
Title: Ctools wizard multistep form: Back button should remember entered data
I am building a multistep form using ctools, basically following this approach. Now I want the following behaviour:

* user is at step 1
* enters data for step 1
* clicks continue and gets to step 2
* enters data for step 2
* clicks *back* and gets to step 1
* **sees the data he entered previously** (works already)
* clicks *continue* and gets to step 2
* **sees the data he entered previously** (works not yet)

To show the previously entered data after clicking *continue*, I simply set `$form[$name]['#default_value']` with values from `$form_state['values']` (with a detour via ctools object cache). So this works already.

The problem is with clicking *back*: After clicking *back*, $form\_state\['values'\] does **not** contain any entered values. So I don't have the values to populate `$form[$name]['#default_value']` and this is my current problem.

So I wonder: How can I send entered values with the *back* button submit?

# Answer
To get ctools wizard to save values when the user presses the back button, you would have to remove it's '#limit\_validation\_errors' property that is set by default in ctools\_wizard\_wrapper(). There is no convenient switch or form\_info property to do this so you have to use a form alter hook similar to this:

```
function test_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form_state['wrapper_callback']) && $form_state['wrapper_callback'] == 'ctools_wizard_wrapper' && $form_state['form_info']['id'] == 'test_wizard') {
    if (isset($form['buttons']['previous'])) {
      unset($form['buttons']['previous']['#limit_validation_errors']);
    }
  }
}

```
> 1 votes

# Answer
As far as I am aware there is not a built in way to achieve this within cTools with the wizard code you are probably playing with (the sub modules that came with cTools inside its plugins folder).

You'll have to use session storage on the server side or localstorage on the client side (javascript) to have the values saved in the manner you describe.

For instant results, install Multi-step forms module and browse to http://your-install.com/mforms/example/session to see a working example of what you describe. The corresponding code is inside of Multi-step forms, which is made for developers to utilize.
> 0 votes

# Answer
I am able to solve the problem. Actually in my case $form\_state\['rebuild'\] = TRUE; is causing the problem. This actually refresh the form and $form\_state\['values'\] is set to null. So I have created an array which will hold $form\_state\['values'\] before it get refreshed and store it in each step storage form. A bit of code to explain you better.

```
function form_user_registration_previous_submit($form, &$form_state) {
    $current_step = &$form_state['step'];
    $formvalue_array=$form_state['values'];
    $form_state['step_information'][$current_step]['stored_values'] = $formvalue_array;
    if ($current_step > 1) {
      $current_step--;
      $form_state['values'] = $form_state['step_information'][$current_step]['stored_values'];
    }
    $form_state['rebuild'] = TRUE;
  }

function form_user_registration_next_submit($form, &$form_state) {
    $current_step = &$form_state['step'];
    $formvalue_array=$form_state['values'];
    $form_state['step_information'][$current_step]['stored_values'] = $formvalue_array;
    if ($current_step < count($form_state['step_information'])) {
      $current_step++;
      if (!empty($form_state['step_information'][$current_step]['stored_values'])) {
        $form_state['values'] = $form_state['step_information'][$current_step]['stored_values'];
      }
      else {
        $form_state['values'] = array();
      }
      $form_state['rebuild'] = TRUE;  // Force rebuild with next step.
      return;
    }
  }

```
> 0 votes

# Answer
I know this question is a bit old, but might help someone in the same situation as I was.

If you end up creating custom submit handlers and having to take care of saving the step values manually then you are not fully taking advantage of what ctools has to offer. The documentation on using and creating multi step forms is quite poor, but following this blog post helped me understand better all the different callbacks that the ctools wizard offers: http://www.grasmash.com/article/building-multistep-registration-form-drupal-7-using-ctools

The only thing missing from the 'next callback' in that tutorial is 'merging' the existing values from the cache with the new ones from your current step (see below).

When you define your '$form\_info' and specify all the ctools steps and options, you have the ability to set callback for 'next', 'finish', 'return', and 'cancel' actions. The way I ended up saving my step data when going back and forward is by setting the 'next callback' and then saving the `$form_state['values']` in the ctools object cache.

```
'next callback' => 'my_module_subtask_next',

```

Then in the actual callback function you basically merge your current cached object with the new $form\_state\['values'\]:

```
function my_module_subtask_next(&$form_state) {
  $values = (array) my_module_get_page_cache('my_module');
  my_module_set_page_cache('my_module', array_merge($values, $form_state['values']));
}

```

Then when setting up your $form fields you can retrieve this ctools cache object and set your `#default_value`:

```
// ctools automatically adds the cache object in your $form_state
$form_values = $form_state['my_module_object'];
$form['example'] = array(
  '#type' => 'texfield',
  '#title' => t('Example field'),
  '#default_value' => (isset($form_values['example'])) ? $form_values['example'] : NULL,,
);

```
> 0 votes

# Answer
Yes this is possible, but you need a workaround due to Back callback : overloading and call

```
/**
 * Callback executed when the 'back' or 'next' button is clicked.
 */
function MODULE_next(&$form_state) {
  if ($form_state['clicked_button']['#value'] == t('Back')) {
    // Do whatever, but use $form_state['input'] instead of $form_state['values']
  }
  else {
    // Use $form_state['values']
  }
}

```
> 0 votes

---
Tags: chaos-tool-suite, forms
---


# Question
Title: How can I pass a value from block to page in a view?
I'm trying to create a search in Drupal 7 using views. I can create the basic search easily, but I'm trying to have the search work like http://leg.colorado.gov/.

I have a view created with a block that has an exposed filter, and a page with multiple exposed filters. I'm trying to get the block to pass the searched term to the page where a user can use more filters to specify what they're looking for. However, all I can seem to do is create a block that performs a search within the block.

Is it possible to set this up using admin configuration in Drupal 7 views, and if so, how? Or would this required coding or other modules?

Thanks

# Answer
> 0 votes
I think this question may have some similarities to How to pass a value from form(block) to the page and show this page?

The trouble with what you are asking is trying to have two distinct parts of your page act on one interaction: the block form submit and then the page search view filter form submit. Each is in fact a separate function which have no relationship in the Drupal backend. To get this to work you could use some jQuery magic to get the value selected in Block filter be cloned into the page search and do a submit on the form. You may have to do some coding using cookies or session values to ensure the values are also reloaded into the block filter criteria if you wish to keep those synchronized.

Since you have several ways of going about this, stick to one that is easiest to work with at first. jQuery is often the most convenient though maybe less elegant in some cases.

---
Tags: views, search
---


# Question
Title: Dynamic Repeating Custom Form Problems - #base #id hook_forms? So close!
On day 3 of trying to get this dang dynamic form to work. Scoured all the internet with only a few instances of someone trying this with a custom form. I am trying to create a dynamic form by building it multiple inside a foreach loop and rendering it to a template. Everything works great until I submit a value. The values to the correct edited form do not pass to the validate or submit handler.

Further more, I've not been able to figure out how to attach an ajax callback to the correctly edited form as well. However I left that snippet out for clarity on the problem.

* Add the theme
* Render the theme to a field on the node being viewed
* Preprocess the theme. Build the forms pass them to template
* Make the form, validate, submit functions
* Hook\_forms to add a callback to the dynamic form

Here is the code

**ec\_task\_credits.module**

```
<?php
//[+] ADD THEME
function ec_task_credits_theme($existing, $type, $theme, $path) {
    return [
        'vocab_list' => [
            'template' => 'vocab-list',
            'variables' => array(),
            'path' => drupal_get_path('module', 'ec_task_credits') . '/theme',
        ],
    ];
}

//[+] RENDER TPL INTO FIELD ON NODE_VIEW
function ec_task_credits_node_view($node, $view_mode, $langcode) {

    if ($node->type == 'ol_todo') {

            //render the template
            $output = theme('vocab_list', array(
                    'task_nid' => $node->nid,
                    'task_list_nid' => $node->field_todo_list_reference[LANGUAGE_NONE][0]['nid'],
                )
            );

            //return the template to a field on node_view
            $node->content['vocab_list_container'] = array(
                '#markup' => $output,
            );
    }
}

//[+] PREPROCESS THE TEMPLATE FILE VARS - BUILD FORMS
function ec_task_credits_preprocess_vocab_list(&$vars) {
    //build all the forms and send them to the template file

    $vocab_insulation = taxonomy_vocabulary_machine_name_load('credit_list_insulation');
    $terms_insulation = entity_load('taxonomy_term', FALSE, array('vid' => $vocab_insulation->vid));
    $vocab_terms = $terms_insulation;   //simple array of terms

    if (!empty($vocab_terms)) {
        $i=0;
        foreach ($vocab_terms as $tid => $term){
            $vars['test_form'][] = drupal_get_form('ec_task_credits_credit_form', $term->tid, $term->name);
            $i++;
        }
    }
}

//[+] CUSTOM FORM CALLED MANY TIMES
function ec_task_credits_credit_form($form, &$form_state, $term_id, $term_name) {
    if (!empty($term_id)) {
        $form_id = '';
        $form['#id'] = 'ec_task_credit_form_'.$term_id; //dynamic ID - works
        $form['#base'] = 'ec_task_credits_credit_form'; //same #base

        $form['term_group'] = array(
            'term_field' => array(
                '#markup' => $term_name,
                '#tid' => $term_id,
                '#id' => 'term_field_'.$term_id,
            ),
            'browse_credit' => array(
                '#type' => 'managed_file',
                '#name' => 'browse_credit_'.$term_id,
                '#title' => t('Block image'),
                '#size' => 40,
                '#id' => 'browse_credit_'.$term_id,
                '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
                '#upload_location' => 'public://'
            ),
            'comment_credit' => array(
                '#type' => 'textarea',
                '#name' => 'comment_credit_'.$term_id,
                '#id' => 'comment_credit_'.$term_id,
                '#title' => t('Comment'),
                '#value' => t('Comment'),
            ),
            'submit' => array(
                '#type' => 'submit',
                '#name' => 'comment_credit_'.$term_id,
                '#id' => 'comment_credit_'.$term_id,
                '#title' => t('Save'),
                '#value' => t('Save'),
            ),
        );

    }
    return $form;
}

//[+] VALIDATE FORM - RUNS ON SUBMIT BUT DOES NOT CONTAIN SUBMITTED $VALUES
function ec_task_credits_credit_form_validate($form, &$form_state) {
    dpm('validate handler is running');
    dpm($form_state);
    dpm($form);
    form_set_error('', t('Force this error to avoid submit for now'));
}

//[+] SUBMIT FORM - NOT DEALING WITH THIS YET
function ec_task_credits_credit_form_submit($form, &$form_state) {

    if (isset($form_state['values']['browse_credit'])) {
        $file = file_load($form_state['values']['browse_credit']);
        $file->status = FILE_STATUS_PERMANENT;
        file_save($file);
    }
}

//[+] HOOK_FORMS()
/*hook_forms does not work - it never prints a form_id of ec_task_credits_credit_form.
* It never sees it and thus cannot work with it
*/
function ec_task_credits_forms($form_id, $args) {

//  $forms['ec_task_credits_credit_form']['callback'] = 'ec_task_credits_credit_form_callback';
//  return $forms;

//$form_id only prints other forms on the page. never my custom form

    $args = func_get_args();
    $form_id = $args[0][0]; //trying to get the damn form_id - doesnt work

    $dynamic_forms = array(
        'ec_task_credits_credit_form',
    );

    $forms = array();
    foreach ($dynamic_forms as $dynform) {
        if (strpos($form_id, $dynform) === 0) {
            $forms[$form_id] = array(
                'callback' => $dynform,
                'callback arguments' => array('testarg'),
            );
        }
    }
    return $forms;
}

```

**theme/vocab-list.tpl.php**

```
<h1>Vocab List</h1>
<div class="credit-list-container">
    <?php print render($test_form);?>
</div>

```

**IMG: The Output Which all appears to be fine and dandy**

https://i.stack.imgur.com/nZDaL.png

**IMG: Then when you submit a value it reloads the page and the value is not in $form\_state**

https://i.stack.imgur.com/E0CIX.png

Does anyone have any idea what I'm doing wrong or how I could set this up differently? How should I be make a dynamic form like this?

# Answer
Alright I figured it out. In case anyone else runs into this problem. This is how you can setup a dynamic form, but don't set a variable #name in the array of your form element. I'm not sure why but this cause the values not to carry over to the submit handler.

In conclusion, in order to make a dynamic form:

* create a custom form
* call that form many times, along with a variable argument, such as a ticker or other unique number
* set the $form\['#id'\] to 'form\_name\_'.$your\_ticker
* set the $form\['#base'\] as just 'your\_form\_name';

This will allow many similar forms to be made all using the same your\_form\_name\_submit handler.

I did not need to use hook\_forms or rather I could not figure out how to, but this still works.

Here is the fixed code:

```
<?php
//[+] ADD THEME
function ec_task_credits_theme($existing, $type, $theme, $path) {
    return [
        'vocab_list' => [
            'template' => 'vocab-list',
            'variables' => array(),
            'path' => drupal_get_path('module', 'ec_task_credits') . '/theme',
        ],
    ];
}

//[+] RENDER TPL INTO FIELD ON NODE_VIEW
function ec_task_credits_node_view($node, $view_mode, $langcode) {

    if ($node->type == 'ol_todo') {

        //render the template
        $output = theme('vocab_list', array(
                'task_nid' => $node->nid,
                'task_list_nid' => $node->field_todo_list_reference[LANGUAGE_NONE][0]['nid'],
            )
        );

        //return the template to a field on node_view
        $node->content['vocab_list_container'] = array(
            '#markup' => $output,
        );
    }
}

//[+] PREPROCESS THE TEMPLATE FILE VARS - BUILD FORMS
function ec_task_credits_preprocess_vocab_list(&$vars) {
    //build all the forms and send them to the template file

    $vocab_insulation = taxonomy_vocabulary_machine_name_load('credit_list_insulation');
    $terms_insulation = entity_load('taxonomy_term', FALSE, array('vid' => $vocab_insulation->vid));
    $vocab_terms = $terms_insulation;   //simple array of terms

    if (!empty($vocab_terms)) {
        $i=0;
        foreach ($vocab_terms as $tid => $term){
            $vars['test_form'][] = drupal_get_form('ec_task_credits_credit_form', $term->tid, $term->name);
            $i++;
        }
    }
}

//[+] CUSTOM FORM CALLED MANY TIMES
function ec_task_credits_credit_form($form, &$form_state, $term_id, $term_name) {
    if (!empty($term_id)) {
        $form_id = '';
        $form['#id'] = 'ec_task_credit_form_'.$term_id; //dynamic ID
        $form['#base'] = 'ec_task_credits_credit_form'; //same #base

        $form['term_group'] = array(
            'term_field' => array(
                '#markup' => $term_name,
                '#tid' => $term_id,
                '#id' => 'term_field_'.$term_id,
            ),
            'browse_credit' => array(
                '#type' => 'managed_file',
                '#title' => t('Block image'),
                '#size' => 40,
                '#id' => 'browse_credit_'.$term_id,
                '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
                '#upload_location' => 'public://'
            ),
            'comment_credit' => array(
                '#type' => 'textarea',
                '#id' => 'comment_credit_'.$term_id,
                '#title' => t('Comment'),
            ),
            'submit' => array(
                '#type' => 'submit',
                '#id' => 'submit_credit_'.$term_id,
                '#title' => t('Save'),
                '#value' => t('Save'),
            ),
        );

    }
    return $form;
}

//[+] VALIDATE FORM
function ec_task_credits_credit_form_validate($form, &$form_state) {
    dpm($form_state['values']);
}

//[+] SUBMIT FORM
function ec_task_credits_credit_form_submit($form, &$form_state) {
//do stuff with submitted values
    if (isset($form_state['values']['browse_credit'])) {
        $file = file_load($form_state['values']['browse_credit']);
        $file->status = FILE_STATUS_PERMANENT;
        file_save($file);
    }
}

```

This also shows how to work with submitting a file or image on a custom form. Using managed\_file
> 0 votes

---
Tags: 7, forms, hooks
---


# Question
Title: Add roles to user during create and save account
I want to add a custom role to a user during hook\_user\_create() and hook\_user\_update(). All goes well during user create, as long as I do $user-\>save() in the end. The site crashes during hook\_user\_update() if I do $user-\>save(). No role is added if I simply add the role with $user-\>addRole('role\_name'), but don't save it.

This is for Drupal 8.

What am I doing wrong?

# Answer
Found the answer: hook\_user\_presave() will do the trick.

I.e you add what you want to the user object (and don't save). Drupal will do the rest.
> 1 votes

---
Tags: 8, users, hooks
---


title: Search nodes with paragraph

text:
# Question
Title: Search nodes with paragraph
I have the following query:

```
$query = \Drupal::entityQuery('node')
            ->condition('type', 'case_study')
            ->condition('status', '1')
            ->sort('changed', 'DESC')
            ->pager(4);

$query->condition('title', "%QUERY%", "LIKE");

$nids = $query->execute();

```

This works fine, however it obviously only searches on the title of the node. My case study nodes' fields are structured like this

```
- Case Study
    - title
    - field_page_banner
    - ...
    - field_rows <-- this is my paragraphs field

```

The paragraphs can contain multiple types and are chosen by the user when creating the content.

I want to be able to alter my query so that it searches the content of the paragraphs. For example, if the user adds a 'Rich Text' paragraph type, it will search the text.

This works fine for the built in search functionality, I just want to create a page of case studies with search functionality.

I am using Drupal 8.2.4 and Paragraphs 8.x-1.0.

# Answer
The \Drupal::entityQuery object doesnt support JOINs I believe: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/interface/QueryInterface/8.2.x

If it did you could Join onto the Paragraph bundle and LIKE across that all you want.

I recommend the following approach with Views, a small chance exists it may not work:

* Create a View of your case study Nodes
* add a relationship to the Paragraph bundle (if needed)
* assure the field list for the View includes `title` and `field_rows` (you can Exclude field\_rows from showing in your view if you want).
* add a `Grouped Filter` and `Expose` it and select it to use your `title` and `field_rows` values.

That should do the trick...
> 1 votes

# Answer
After keep on testing and write the query i found out it do support join for paragraph. Below is my query

`$query = \Drupal::entityQuery('node');
$query->condition('field_content_type_paragraph_name.entity.field_paragraph_field_machine_name.target_id',"NODE ID HERE");
$entity_ids = $query->execute();`

Here is the generated query

```
[node__field_content_type_paragraph_name] => Array
                    (
                        [join type] => INNER
                        [table] => node__field_content_type_paragraph_name
                        [alias] => node__field_content_type_paragraph_name
                        [condition] => node__field_content_type_paragraph_name.entity_id = base_table.nid
                        [arguments] => Array
                            (
                            )
                    )

                [paragraphs_item] => Array
                    (
                        [join type] => LEFT OUTER
                        [table] => paragraphs_item
                        [alias] => paragraphs_item
                        [condition] => paragraphs_item.id = node__field_content_type_paragraph_name.field_content_type_paragraph_name_target_id
                        [arguments] => Array
                            (
                            )
                    )

                [paragraph__field_paragraph_field_machine_name] => Array
                    (
                        [join type] => INNER
                        [table] => paragraph__field_paragraph_field_machine_name
                        [alias] => paragraph__field_paragraph_field_machine_name
                        [condition] => paragraph__field_paragraph_field_machine_name.entity_id = paragraphs_item.id
                        [arguments] => Array
                            (
                            )

                    )

```
> 1 votes

---
Tags: 8, search, paragraphs
---


title: Print a PNG icon instead of field label

text:
# Question
Title: Print a PNG icon instead of field label
I needed to print a png icon instead of field label in views, so i'm posting this question and it's propper detail answer as well, in my case i need to print whatsapp icon as a label in a field in views, this answer is based on this post, this question is flaged as closed being off-topic, but I think it may be usefull to others. this is working in D7, it may work on D8.

# Answer
> 1 votes
First, you need a png image (my case 17x17 px whatsapp.png), place it under sub-theme/images folder, then, place this css under sub-theme/css/custom.css file

```
.whatsappwrapper {background-
 image:url("../images/whatsapp.png");background-repeat:no-repeat;}
.whatsapplabel {display: none;}
.whatsappnumber {margin-left: 20px;}

```

then, set your views field styles as shown in picture first part of image is the result of this settings. note: telephone icon is a html symbol.

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


# Question
Title: Changing the initial value of an exposed view filter
I'm trying to programmatically set the starting value of an exposed view filter (so that it initially loads the view with data matching that value).

I've managed to change the filter field value with this code in a views\_pre\_build hook (doesn't work in pre\_execute or pre\_render):

```
$view->display[$view->current_display]->handler->handlers['filter']['field_year_value']->value['value'] = $year;

```

But the view still loads with the value from the view filter's config value. How can I get my change reflected in the view when it loads?

# Answer
For some reason a site I was adding a feature to had a years taxonomy vocabulary, with a number of terms, one for each year in a range. So I wanted to auto set the exposed filter to the current year, but to do so needed to set the filter value with the tid of the right term.

I implement hook\_views\_query\_alter().

check if the view is the right name and if the view doesn't have any user selected input (this view only had one filter).

You have to alter the value for the filter's query value

You have to unset the exposed filter area markup and regenerate it.

```
 function mymodule_views_query_alter(&$view, &$query) {

      if($view->name == 'executive_committee' && empty($view->exposed_input)) {
        $current_year = date('Y');
        // find year term id
        $term_query = new EntityFieldQuery();
        $tids = $term_query->entityCondition('entity_type', 'taxonomy_term')
          ->propertyCondition('name', $current_year)
          ->propertyCondition('vid', 3)
          ->execute();

        if(!empty($tids['taxonomy_term'])) {
          $tids = array_keys($tids['taxonomy_term']);
          $current_year_tid = reset($tids);

          // set values to the views object and query objet
          $view->exposed_data['field_year_tid'] = $current_year_tid;
          unset($view->exposed_widgets);
          $view->exposed_raw_input['field_year_tid'] = $current_year_tid;
          $query->where[1]['conditions'][2]['value'] = $current_year_tid;
          // rebuild the exposed form
          $form_state = array(
            'view' => $view,
            'display' => $view->display_handler->display,
            'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
            'method' => 'get',
            'rerender' => TRUE,
            'no_redirect' => TRUE,
            'always_process' => TRUE, // This is important for handle the form status.
          );
          $form = drupal_build_form('views_exposed_form', $form_state);
          $form['field_year_tid']['#value'] = $current_year_tid;
          $view->exposed_widgets = drupal_render($form);

        }

      }
    }

```
> 1 votes

---
Tags: views
---


# Question
Title: Class Term missing sometimes when used in myTheme.theme
Using my theme file, I created a theme/template suggestion for taxonomies. I load a term object so I can know its vid. This was working and still works most the time. However, occasionally I get fatal errors. Which is a big deal. Similar to:

> Fatal error: Class 'Term' not found in myTheme.theme on line 4.

I am not sure why the term class isn't found, and only sometimes? Any suggestions on how to prevent this error?

Most of the time rebuilding the cache would fix this but not always.

myTheme.theme

```
<?php
function myTheme_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

```

# Answer
> 1 votes
The error is caused from the fact you didn't fully qualified the class name, which means you forgot the namespace of that class.

Or you use `\Drupal\taxonomy\Entity\Term::load($tid);` or you add a `use \Drupal\taxonomy\Entity\Term;` line at the top of the file. In this way, PHP knows where to find the class you reference.

---
Tags: theming
---


title: Add combined fields to Content type

text:
# Question
Title: Add combined fields to Content type
I'm creating a website with a Project content type. In that content type there are common fields and a few group fields. Group fields are fields that need to stay together and can be added multiple times. So in my Group fields there will be a date field and a text field that can be added multiple times.

Do I need to create a new content type or taxanomy type for this or is there a module for Drupal 8 that provides this behaviour.

# Answer
Try the module field\_collection.

Add a field of type field\_collection to your content type and allow multiple values. Then go to structure =\> Field collections and choose your field to add your date and text field.

**Update: field\_collection is on its way to be deprecated**

Use paragraphs module instead.

Notice these meta data issues for paragraphs.
> 1 votes

---
Tags: 8
---


# Question
Title: Instructive message when a module is disabled accidentally
Site breaks without a warning when code of a non-enabled module is called. (In my project I disabled accidentally a module, while the code is executed by another module.)

The correct way is to add dependencies, but sometimes that is forgotten (and rather old-fashioned). PHP Storm does not check whether a module is active or not; it just validates the call.

Is there a way to get a message when code of a non-enabled module is called?

# Answer
Absolutely. In the module that calls the function, use one of the following

Drupal 7:

```
if (module_exists('foo')) {
  // Use a function provided by the module
}
else {
  drupal_set_message('Something is wrong');
}

```

Drupal 8:

```
$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('foo')){
  // Use function provided by the module
}
else {
  drupal_set_message('Something is wrong');
}

```

If your code runs in a context that can use DI, inject the module handler service rather than getting it from `\Drupal`.

You're right, though, dependencies should be used and then this extra wrapping code isn't necessary.

Dependency management is definitely not "old fashioned", by any stretch of the imagination; not in Drupal, and not in the greater world of programming/frameworks. It's a thriving, constantly-improving area of work.

I'm not sure where you got that idea from, but if that's what's stopping you using the proper methods to solve your problem, you should probably think about reevaluating your opinion, as (and no offence meant by this), it's quite frankly just wrong at the moment.
> 0 votes

---
Tags: debugging
---


# Question
Title: I s there a way I can show node teasers but don't allow access to full content?
I need anonymous users to to be able to se the node teaser but don't allow access to the full content is there a way to do this?

# Answer
To prevent users from access the node you can disable the "View published Content" permission but that will disable it for all node types. If you like to disable it just for one node type you can checkout the content\_access module.

You can use a view of content to display the teasers.

In the format section use the format "Unformatted list" and choose your content display Teaser.

If you use a page for the view, you should also check the page access in the page settings section of the view.

I'm not sure if you need the following (It depends on how you prevent the node access):

In the advanced section under query settings you can disable sql-rewriting. This allows you to disable the node\_access check. But take attention to this:

"*Disabling SQL rewriting will omit all query tags, i. e. disable node access checks as well as override hook\_query\_alter() implementations in other modules.*"
> 0 votes

---
Tags: nodes
---


# Question
Title: How do I port my hook_alter module to D8?
This is my D7 module (module name is ckeditor\_show\_blocks):

```
<?php

/**
 * Implements hook_ckeditor_editor_settings_alter().
 */
function ckeditor_show_blocks_ckeditor_settings_alter(&$settings) {
    $settings['startupOutlineBlocks'] = TRUE;
  }

```

All it does, it toggles Show Blocks by default on page load in the CKEditor when editing the page/node:

I'm trying to achieve same on D8. I did read some on hooks documentation, and it looked like same, so I didn't change anything, but the module won't apply when in editing mode, what I'm missing? Is hook format different? Does it have something to do with the fact that CKEditor is built-in feature in D8?

There is normal documentation on D7 on how to implement a simple hook module, but not so much about D8.

# Answer
Considering that the Editor module in Drupal core is the equivalent of the Wysiwyg module for Drupal 7, and the core CkEditor module is the equivalent of the Drupal 7 module with the same name, I would say that the hook you are looking for is `hook_editor_js_settings_alter()` that, for a module whose machine name is ckeditor\_show\_blocks, it is implemented from the `ckeditor_show_blocks_editor_js_settings_alter()` function.

If you need to know the ID of the editor plugin used for a input format, you can get that from `$settings['editor']['formats'][$format_id]['editor']`; that is the case, for example, when you need to change settings if the used editor is the one implemented by the CkEditor module.

To make it clearer, the Editor module is the module that associate editors to the input formats used from a Drupal 8 site, while the CkEditor module in core contains an implementation of editor.
> 0 votes

---
Tags: 8, hooks, wysiwyg
---