# Question
Title: How can I save the configuration value in a custom submit form method
I've been wondering if it was possible to use the configuration system instead of playing directly with the database. Here's a simplified version of what I'm trying to achieve:

```
public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $form['action'] = array(
        '#type' => 'submit',
        '#submit' => [[$this, 'myMethod']],
        '#value' => $this->t('Test')
    );
    return $form;
}

public function myMethod($form, FormStateInterface $form_state) {
    $this->setConfigurationValue('my_config', 'my test value!');
    $this->saveConfiguration(); // <---- Is that 'kind of' possible?
}

```

So, I was wondering if it was possible to get the real "config class" by some way and call `$config->save()`. I started to look at the source and I think it's probably possible using the configuration engine.

Any help would be appreciated.

Thanks

# Answer
The blockForm is used to configure a block. The configuration is then used to build the block.

If you want to use the configuration system to store data in the database use one of these methods:

1. Simple Configuration Form
2. Creating a configuration entity type
> 2 votes

---
Tags: forms, 8
---


title: How to use browser caching for images?

text:
# Question
Title: How to use browser caching for images?
I am learning to improve Drupal's performance and I discovered Google's PageSpeed Insights tool. It urges me to use browser caching and presents me a list of all my images at **mytheme/images** and **default/files**. To be honest, I am not too sure about what this means. I assumed that Drupal's default caching could handle this, but apparently that is not the case, since caching is already enabled at **Performance** (both minimal lifetime and expiration time are set to 1 hour).

How can I cache all those images as well? Should I install some extra modules like Varnish or Boost to solve this? As a beginner, I can't really wrap my head around all these performance modules and what they do.

# Answer
After Pierre Buyle's answer, I contacted my server host about this problem and they solved it by adding the following code to my `.htaccess` file:

```
# Cache Control Settings
<FilesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=1333600, public"
</FilesMatch>
<FilesMatch ".(xml|txt)$">
Header set Cache-Control "max-age=1333600, public, must-revalidate"
</FilesMatch>
<FilesMatch ".(html|htm)$">
Header set Cache-Control "max-age=1333600, must-revalidate"
</FilesMatch>

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##

```
> 2 votes

# Answer
Images are directly served by the web server. You need to configure your web server to server images (and other files) with the appropriate headers. On Apache HTTP server, this is usually done with the mod\_expires module.
> 3 votes

---
Tags: 7, caching
---


# Question
Title: Create a filterable, sortable admin view that produces front end block
The goal is to produce a single block to go on the homepage with 5 linked terms from a single taxonomy vocabulary. These terms would be selected and then ordered in an admin interface by a content administrator. The taxonomy vocabulary itself my have 30-50 terms.

I thought I could create an admin view with an exposed form to select the terms and then apply draggable views to the results, but I am having trouble combining the exposed form and draggable views. I am also having trouble turning the results into a block.

Happy to ad more info if this is vague, but all of the views I have set up have been so wrong I did not want to waste anyones time by posting them here.

Would views / exposed filters / draggable views be the right way to go about this or is there a better way? I'd rather not install something huge like panels to make this happen.

# Answer
> 3 votes
Another way to do this would be to install https://www.drupal.org/project/term\_queue

This contrib module gives you all you need.

Here is a screenshot, admin interface to the right, front-end block to the left.

The module provides a block automatically, for each term queue, you simply need to place it.

Good luck!

# Answer
> 1 votes
How about creating a new content type, which has a field with the terms that you select.

Then use views with dragableviews to display the content of the node in a view block.

---

OR... I have not tested this, but you could try using the Bean module, which basically allows you to add fields to your blocks.

So create a block and add a term reference field to it. Looking at the bean module source code it looks to have Views integration. So then you would just display your bean block content in a view block with dragableviews.

This way, you avoid having to create a node that has some url path.

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


# Question
Title: How-To call a module when a user clicks a node title or read more link if($page)
I would like to call a module from node.tpl.php like so (based on node id):

//This is my node--job\_post.tpl.php

```
   <pre>

   <?php
         if ($page):
    $nid = $node->nid;
  switch($nid){
  case 4:  CALL A MODULE FOR NODE ID 4
  case 5:  CALL A MODULE FOR NODE ID 5
  break;
 }
  endif;
  ?>
 </pre>

```

If there is a better way to accomplish this , please let me know. Thank you in advance.

# Answer
That's not how it works in Drupal.

You need to use Hook\_node\_view() **in a custom module `.module` file, NOT in the template.tpl.php file**. Which executes the code inside it whenever a node is viewed.

Ex:

**hello\_world.module**

```
hello_world_node_view($node, $view_mode, $langcode){

  //code to run when node is viewed goes here.

}

```
> 1 votes

---
Tags: 7, theming, nodes
---


# Question
Title: How do I pre-populate the login/sign up form?
I'm working on a project that let any user (anonymous) register for an event. An event is a content type that has duration, name and price and possibly a date. So, when a user browse through different events, they can register for an event by simply clicking on the "Register for this Event" What needs to happen when they click on Register.. is: the info related to that event needs to pre populate to the member login form so that they don't have to fill the event info again.

The user must be a member before they can register for the event but I am trying to give a nice user experience to the user so that he/she can simply click on the Register link and then they will be redirected to the user login/sign up form the event info pre-loaded and they provide the rest of the info. I have already extended the standard Drupal login form to my need and also created the event content type. Thinking to use flag module to make Register link but have NO idea how to pre populate that event info into the login form. Any help or guide will be highly appreciated. Thanks in advance.

# Answer
> 1 votes
> I have already extended the standard Drupal login form

Sounds like you're already using `hook_form_alter()`, so all you have to do is add the `#default_value` attribute to your form array.

Ex:

```
$form['my_field_name'] = array(
    '#type' => 'textfield',
    '#title' => t('something'),
    '#default_value' => t('Hello World'),
);

```

---

OR Use the Profile2 module suggested by @Kevin

> Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)

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


# Question
Title: Dynamically generated radio buttons share name
```
   foreach ($questions as $question_index => $question) {

      $form['questions'][$question_index]['answer'] = [
        '#type' => 'radios',
        '#title' => '',
        '#default_value' => 1,
        '#options' => $options,
      ];

    }

```

I am generating a form like this, but the radio buttons share the same name. I find that weird since I am wrapping it in a dynamic wrapper.

I know that I could add something along: `[$question_index]['answer_' . $question_index]`

But, is it possible to make it rely on the grouping/container instead?

# Answer
> 0 votes
You can try using #tree:

```
$form['#tree'] = TRUE;

```

Or you can add it to only your questions element:

```
$form['questions']['#tree'] = TRUE;

```

---
Tags: forms, 8
---


# Question
Title: Commerce Kickstart: How do I fix a SQL error on string length after using Features Override to save customizations?
After reading the update instructions on Commerce Kickstart (Installing & Upgrading), I attempted to use the Features Override module to save my customizations/configuration prior to updating to the most current version of Commerce Kickstart. I have changed menus, user profiles, etc. and would like to keep those updates intact.

I followed the instructions posted on the project and generated a "Feature.tar" file.

Attempt #1:

1. Selected all items shown in Features Override dropdown (179 items)
2. Downloaded the file
3. Enabled the new feature through "Modules" UI
4. Received this set of error msgs \[truncated for demo purposes\]:

PDOException: SQLSTATE\[22001\]: String data, right truncated: 1406 Data too long for column 'info' at row 1: INSERT INTO {system} (filename, name, type, owner, info) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4); Array ( \[:db\_insert\_placeholder\_0\] =\> sites/all/modules/features\_override\_0916/features\_override\_0916.module \[:db\_insert\_placeholder\_1\] =\> features\_override\_0916 \[:db\_insert\_placeholder\_2\] =\> module \[:db\_insert\_placeholder\_3\] =\> \[:db\_insert\_placeholder\_4\] =\> a:12:{s:4:"name";s:25:"Features Override 09-2016";s:4:"core";s:3:"7.x";s:7:"package";s:8:"Features";s:12:"dependencies";a:2:{i:0;s:18:"commerce\_kickstart";i:1;s:4:"node";}s:8:"features";a:2:{s:12:"features\_api";a:1:{i:0;s:5:"api:2";}s:23:"features\_override\_items";a:153:{i:0;s:61:"facetapi.search\_api@product\_display:block:field\_blog\_category";i:1;s:58:"facetapi.search\_api@product\_display:block:field\_brake\_type";i:2;s:56:"facetapi.search\_api@product\_display:block:field\_hub\_type";i:3;s:64:"facetapi.search\_api@product\_display:block:field\_intended\_use\_alt";i:4;s:59:"facetapi.search\_api@product\_display:block:field\_primary\_use";i:5;s:85:"facetapi.search\_api@product\_display:block:field\_product:commerce\_price:amount\_decimal";i:6;s:71:"facetapi.search\_api@product\_display:block:field\_product:field\_axle\_size";i:7;s:71:"facetapi.search\_api@product\_display:block:field\_product:field\_build\_kit";i:8;s:67:"facetapi.search\_api@product\_display:block:field\_product:field\_color";i:9;s:72:"facetapi.search\_api@product\_display:block:field\_product:field\_frame\_size";i:10;s:86:"facetapi.search\_api@product\_display:block:field\_product:field\_product\_specific\_options";i:11;s:73:"facetapi.search\_api@product\_display:block:field\_product:field\_wheel\_sizes";i:12;s:64:"facetapi.search\_api@product\_display:block:field\_topic\_related\_to";i:13;s:25:"field\_base.commerce\_price";i:14;s:30:"field\_base.field\_blog\_category";i:15;s:23:"field\_base.field\_images";i:16;s:54:"field\_instance.commerce\_product-product-

Attempt #2

1. Same as above
2. Generated the file & saved it directly to the server under "Advanced Options"
3. On refresh, received same error msg as above.

I watched an Acquia tutorial on Features that seemed to show the creation of "Features" as something very straightforward, but I can't seem to get through the process.

It looks like I have a string length issue. Where do I set the max length of a column input? (System \>\> Info).

Any tips? Any tutorials or videos that you recommend?

# Answer
> 0 votes
Great news! Kind of.

After looking at the database more (using the Database Admin module), I found that the "info" column is a BLOB. A BLOB has a max char length of 65,000.

Given the number of changes I made to the default settings, my Feature Override complete set of Feature Overrides well exceeded the 65,000 characters allotted. I opted to split the Feature Overrides into individual packets, grouped by type (variable / facetapi / user). This appears to have done the job. Fairly straightforward after better understanding the db setup and limitations there.

In terms of avoiding extensive overrides, I suspect that I created this snag by starting out with the demo store implemented in Commerce Kickstart. That option seemed like a good plan for me at the time because it provided some basic features already setup. I adapted those for what I need, but it may not be a particularly good foundation from which to grow the site. Any feedback there?

---
Tags: commerce, features
---


# Question
Title: How to create a parent content type which consists of other child content types?
I want to create custom content type (parent) which consists of other custom content types (children). Is this feasible in Drupal 8? Or I should do it programmatically?

Example: I want to have custom content type called ***Task***, and another custom content type called ***Subtask***. When a user creates a task, the user has to complete some fields (id, name), and should then create some *Subtasks* which are children of this *Task*. For the subtask some fields are to be completed also. In the end, each task will have some data such as:

* name = "task\_one".
* description = "this task should do ..".
* subtasks = {"subtask\_one","subtask\_two"}.

# Answer
For Drupal 8, it sounds like you are describing reference fields. You would want to:

1. Create your two content types
2. Add a reference field to one of them. The refence field would be of the type 'content'.
3. (Optional, but probably) Limit the types of content that can be referenced to only the other content type.
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: How to generate XML feed with nested tags using Xpath Parser?
I have a XML file as below

```
<rss>
  <channel>
    <title>Channel Title</title>
    <description>Channel Description</description>
    <owner>
      <owner:name>Owner Name</owner:name>
      <owner:email>Owner Name</owner:email>
    </owner>
    <item>
      <title>Item 1 title</title>
      <author>Item 1 author</author>
    </item>
    <item>
      <title>Item 2 title</title>
      <author>Item 2 author</author>
    </item>
  </channel>
</rss>

```

In my Xpath parser settings, I gave `/rss/channel/item` as context and I am getting only the item title and item author into my node. How it is possible to add title,description and owner details into my node?. And I also want the same structured XML output using Views data export.

# Answer
> 0 votes
You need to move your context 1 level back.

context: `/rss/channel`

title: `title`

description: `description`

owner name: `owner/owner:name`

owner email: `owner/owner:email`

item title: `item/title`

item author: `item/author`

---
Tags: views, feeds
---


# Question
Title: How To Wrap Multiple Content Field Items In Li Tag
I've got an issue with a field called Track Listing. As the title states it is a Text(plain) type with unlimited possible values so that I can input as many as I'd like. The machine name is: track\_listing

As it stands I'm outputting the label and items using: `{{ content.field_track_listing }}` which gives me this:

But I'd like to be able to wrap the field in an **ol** tag in addition to every track with a **li** tag to be able to get a nice ordered numbered list. Using twig templates I've wrapped it accordingly but find it only targets the first value which is in this case the label as seen here:

I feel that I should be using a for/if loop in order to get the right values since removing the label only wraps the first item as well. If anyone has an article I can check out to point myself in the right direction I would appreciate it, thank you.

# Answer
You can easily theme a multiple value field in the field template.

To do this put a field twig in `mytheme/templates`:

**field--field-track-listing.html.twig**

```
<div{{ attributes }}>

  <div{{ title_attributes }}>{{ label }}</div>

  <ol>
  {% for item in items %}
    <li>{{ item.attributes }}>{{ item.content }}</li>
  {% endfor %}
  </ol>

</div>

```

Here you can change the html markup around each field item `{{ item.content }}` the same way as you do this in node around the complete field `{{ content.field_name }}`. This is the concept of nested render elements.
> 3 votes

# Answer
Inside **node--\[content-type-name\].html.twig**

```
<ol>

{% for track in content.field_track_listing['#items'].getValue() %}

  <li>{{ track.value }}</li>

{% endfor %}

</ol>

```

If you need to display the field label, put `{{ content.field_track_listing['#title'] }}` before the `<ol>` tag
> 2 votes

---
Tags: theming, 8
---


# Question
Title: defining node multicolumn layout with twig template
Sometimes I get lost in all the options I have on the drupal platform.

I am currently creating a site for a choir. I want them to be able to add new concerts. There has to be a page for every concert. I want to use a multicolumn layout for those concertpages. This layout I want to define using a twig template. Each concert would get a standard layout at creation.

I want to be able to override that template for each individual concert. Once the grafic design for promotion material is finished the page has to be inline with the grafic design. But it still has to be editable like a normal drupal-page.

I thought about doing that with a content type. But can I theme that in a multicolumn layout using twig? It seems like I only have a {{ content }} variable in twig.

Am I missing something? It seems like a custom entity would be a better solution since I can define a render array and add the fields in different variables wich I can then use in my twig file.

Maybe I got it all wrong, this is my second drupal project and I'm still learning to find the best way of getting things done.

Matt.

# Answer
> 1 votes
Make a copy of node.html.twig and rename the copy to node--\[content-type-name\].html.twig which goes inside your theme's template folder.

Then in node--\[content-type-name\].html.twig find and delete `{{ content }}` and instead in there you put

```
{{ content.title }}
{{ content.body }}
{{ content.field_name }}

```

This is how you can render your fields individually.

Then, you can wrap them inside an id or class divs. Ex:

```
<div class="something">{{ content.field_name }}</div>
<div class="something-else">{{ content.field_name_other }}</div>

```

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


# Question
Title: How to create a list of file fields with checkboxes selector?
We all know that by default drupal allows the users to create Lists consists of (float, integer, decimal and text) field types that can be useful for webforms element, but this kind of list can't be very useful and haven't enough efficiency in content type (of course this is my personal opinion only) However, I think this kind of list can be more flexible and powerful if combine with other types of field like **Link** and especially in the case of **Files**.
Because these kind of fields (Link & File) consists of two components **Title** (can be equal to field label For more convenience) that can be Stable and **Value** that can be Unstable.
for example I have a predefined, stable and limited list of title, **List(text)** and against of it there is a list of unstable and changeable of file fields in my custom content type, for this reason I decide to combine the power of lists (like default drupal list(text)) with file upload fields and create new and more powerful field type like **List(file)** something like below:

## Advantages of this field:

* Not have to change the **Description** (Title or label of the link) of file field eachtime that you want to upload or update a new file
* Not have to change ugly file names like '102-32.exe' to something can be more human readable.(If you want to use generic display format)
* Get rid of any change or add more complexity to template files.

# Answer
> 6 votes
Add 4 file fields to your content type with desired labels (ex. "Win 64bit"), Then you will have this 4 fields in your add content form.

Now it's time to make them optional, first of all using hook\_form\_alter you can add 4 new elements of class "checkbox" to your form like this:

```
$form['dependent']['win64'] = array(
  '#type' => 'checkbox',
  '#title' => t('Win 64bit'),
);

```

and then for your fields add a `#states` like below :

```
$form["win 64 file field"]= array(
  '#states' => array(
    'visible' => array(
      ':input[name="dependent[win64]"]' => array('checked' => TRUE),
  ),
);

```

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


title: Drush 8 installation issues

text:
# Question
Title: Drush 8 installation issues
Few months ago I've tried to uninstall drush 6 in order to put drush 8 instead (for D6 to D8 migration purposes). I absolutely don't know why, but it's been impossible to install drush 8 on my site, whatever the method used (either directly or via composer).

More precisely, at first glance it seemed that drush 8.1 had been properly installed, but a "drush status" command displayed curiously "version 8.0.3 installed", and no drupal site has been recognised when trying to use drush 8 in the drupal directories.

I precise that I'm hosted on a managed VPS with PHP 5.5 installed and that drush 6.7 worked perfectly well.

Here are the details while using composer at the time I tried to do it (no improvement since):

```
[~]# composer global require drush/drush:8.*

Changed current directory to /home/user/.composer

./composer.json has been created

Loading composer repositories with package information

Updating dependencies (including require-dev)

  - Installing pear/console_table (v1.3.0)
    Downloading: 100%

  - Installing symfony/polyfill-mbstring (v1.2.0)
    Downloading: 100%

  - Installing symfony/console (v2.8.6)
    Downloading: 100%

  - Installing symfony/var-dumper (v2.8.6)
    Downloading: 100%

  - Installing symfony/yaml (v2.8.6)
    Downloading: 100%

  - Installing jakub-onderka/php-console-color (0.1)
    Downloading: 100%

  - Installing jakub-onderka/php-console-highlighter (v0.3.2)
    Downloading: 100%

  - Installing dnoegel/php-xdg-base-dir (0.1)
    Downloading: 100%

  - Installing nikic/php-parser (v2.1.0)
    Downloading: 100%

  - Installing psy/psysh (v0.7.2)
    Downloading: 100%

  - Installing psr/log (1.0.0)
    Downloading: 100%

  - Installing drush/drush (8.1.2)
    Downloading: 100%

pear/console_table suggests installing pear/Console_Color2 (>=0.1.2)

symfony/console suggests installing symfony/event-dispatcher ()

symfony/console suggests installing symfony/process ()

symfony/var-dumper suggests installing ext-symfony_debug ()

psy/psysh suggests installing ext-pcntl (Enabling the PCNTL extension makes PsySH a lot happier :))

psy/psysh suggests installing ext-posix (If you have PCNTL, you'll want the POSIX extension as well.)

psy/psysh suggests installing ext-readline (Enables support for arrow-key history navigation, and showing and manipulating command history.)

psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)

drush/drush suggests installing ext-pcntl (*)

drush/drush suggests installing drush/config-extra (Provides configuration workflow commands, such as config-merge.)

Writing lock file

Generating autoload files

[~]# drush status

 PHP executable         :  /usr/bin/php-cli

 PHP configuration      :  /usr/local/lib/php.ini

 PHP OS                 :  Linux

 Drush script           :  /home/user/vendor/drush/drush/drush.php

 Drush version          :  8.0.3

 Drush temp directory   :  /tmp

 Drush configuration    :

 Drush alias files      :

 /home/user/.drush/en.aliases.drushrc.php

 /home/user/.drush/fr.aliases.drushrc.php

 /home/user/.drush/es.aliases.drushrc.php

[~]# drush version

 Drush Version   :  8.0.3

[~]# cd public_html/en/sites/en.mysite.com/

[~/public_html/en/sites/en.mysite.com]# drush cc all

No Drupal site found, only 'drush' cache was cleared.                [warning]

[~/public_html/en/sites/en.mysite.com]# drush ups

Command pm-updatestatus needs a higher bootstrap level to run - you  [error]
will need to invoke drush from a more functional Drupal environment
to run this command.

The drush command 'ups' could not be executed.                       [error]

```

# Answer
> 0 votes
Well, I think I've found where the problem came from at last.

My previous `drush status` displayed erroneously:

```
[~]# drush status
 PHP executable         :  /usr/bin/php-cli
 PHP configuration      :  /usr/local/lib/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/user/vendor/drush/drush/drush.php
 Drush version          :  8.0.3

```

After having uninstalled Drush, I've removed the `/home/user/vendor/drush` directory and other remaining Drush files and directories in order to restart from the cleanest possible situation. I've then reinstalled Drush 8 with composer, and now the `drush status` displays rightly:

```
[~]# drush status
 PHP executable         :  /usr/bin/php-cli
 PHP configuration      :  /usr/local/lib/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/user/.composer/vendor/drush/drush/drush.php
 Drush version          :  8.1.3

```

The curious thing is that this was a problem for Drush 8 only, not for Drush 6. But finally Drush 8 seems to work well for the moment.

# Answer
> 1 votes
This method should work in almost all environments:

Browse https://github.com/drush-ops/drush/releases for the release you want. You can't use drush 9 with php 5.5, so you have to choose drush 8.

Download the selected drush version

```
wget https://github.com/drush-ops/drush/releases/download/8.1.3/drush.phar

```

and try to run this php runtime file:

```
/usr/local/php5.5/bin/php drush.phar status

```

The php path is an example. You only need it, if `php` does not pickup the right php version.

You can keep running drush like this, but it is more convenient to rename it to `drush`, make it executable with `chmod +x drush` and copy it to a location where your shell finds it as executable (a path defined in $PATH). This depends on that your environment allows you to execute phar files.

---
Tags: 8, drush
---


# Question
Title: URLs with trailing slash say site in maintainence mode, others don't, site isn't in maintenance mode
Something very strange has happened and I'm at a complete loss as to how to go about working out the cause.

I used Backup / Migrate module to restore a backup of my live site's database (let's call it *somesite.com*) onto my dev site's database (let's call it *dev.somesite.com*) after copying the files over.

I visited *dev.somesite.com/admin/* and was surprised to be told it was in maintenance mode. I did the usual maintenance mode fixes: `drush vset maintenance_mode 0`, checking that the contents of *variable \> maintenance\_mode* in the database was `i:0;`, but it still showed as maintenance mode.

A little trial and error later, I discovered that *dev.somesite.com/admin* did work, and it seemed **having a trailing slash in the URL would show the maintenance mode page**.

What could possibly be causing such a strange behaviour? My first thought was, since it's a URL formatting issue, there might be a mistake in my `.htaccess` file, but it looks fine and hasn't changed.

---

**Update**: a little more testing seems to show that this only happens for URLs the user doesn't have access to. For example, *dev.somesite.com/admin/* while logged in gives the expected user access error, *dev.somesite.com/about-us/* while not logged in redirects to *dev.somesite.com/about-us* and then works fine, but *dev.somesite.com/admin/* while not logged in gives the maintenance page not the access denied page.

So, it's not as serious a problem as I first thought, but it's still strange and smells like a sign I might have misconfigured something which might in turn have more serious consequences elsewhere - but I don't know what this could be. I've looked at my Global Redirect settings and they look fine.

# Answer
> 0 votes
1. Have you already cleared the cache? Maybe it's just that
2. Try putting this code `$conf['site_offline'] = 0;` into settings.php to see what happens :)

---
Tags: 7, uri, maintenance-mode
---


# Question
Title: Programmatically add a taxonomy term as entity reference in a custom entity
I'm really struggling to add a taxonomy\_term as an entity reference to a custom entity I've created programmatically.

Here is my configuration based on BaseFieldDefinition (the name of the vocabulary is "specialite":

```
$fields['speciality_field'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('speciality'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'taxonomy_term')
  >setSetting('handler_settings', ['target_bundles' => ['specialite' => 'specialite']])
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '10',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

This piece of code doesn't work, would you please help to find what I am missing, or redirect me to a good documentation explaining different values for handler\_settings

Thank you so much.

# Answer
Well thank you, the answer of 4k4 was very useful. My problem was that for my field I wanted to reference to a taxonomy term, I had already created it and dropped it directly in the database. It's seems no to be the right way to do this, so I was having such trouble recreating it. So unisntalled my module (after removing all the data) , and reinstalled it , and then this piece of code worked perfectly to have a reference to a taxonomy term:

```
$fields['speciality'] = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings',
      array(
    'target_bundles' => array(
     'specialite' => 'specialite'
    )))
  ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 3,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '10',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

PS: specialite is my the name of my vocabulary
> 10 votes

# Answer
You can use the handler settings drupal generates, when you add a taxonomy field in ui:

```
settings:
  handler: 'default:taxonomy_term'
  handler_settings:
    target_bundles:
      tags: tags
    sort:
      field: _none
    auto_create: false

```

This is the config of tags in article, so you need to swap tags with your vocabulary.
> 3 votes

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


title: How to style my custom Fivestar field?

text:
# Question
Title: How to style my custom Fivestar field?
After having solved How to calculate the average Fivestar rating correctly?, I have a computed field *Average score* that displays the average score of a node. I sometimes want to display this field in a View as a rating (e.g. 4.2/5) and add some more markup to it. For the moment, I have different templates of the form **views-view-field--MY-VIEW--field-average-score.tpl.php** with the same code:

```
<?php $rating = round(($output/100) * 5, 1); ?>
<span>
  <span class="star"></span><span><?php print $rating . '/5'; ?></span>
</span>

```

Having all these duplicate templates seems silly to me. Is there a way to only have one and somehow point out which *Average score* fields should be styled accordingly? Simply using **views-view-field--field-average-score.tpl.php** is not what I want, since I don't always want to style *Average score* like this.

# Answer
> 2 votes
Then you can do it like this:

Use **view-field--field-average-score.tpl.php** which will affect all views that have this field, but we can add an if statement to target the views you only want the special markup.

Ex: In here we check if it has view\_name with block\_1 OR view\_name\_2 with block\_1

```
<?php if (($view->name == 'view_name' && $view->current_display == 'block_1') || ($view->name == 'view_name_2' && $view->current_display == 'block_1'): ?>
<?php $rating = round(($output/100) * 5, 1); ?>
<span>
  <span class="star"></span><span><?php print $rating . '/5'; ?></span>
</span>
<?php else: ?>
<?php print $output; ?>
<?php endif; ?>

```

In case you are wondering, `current_display` is the machine name

The `$view->current_display` check is optional. This is so it only affects a certain Display of block/page that is inside your view.

So for line 1, you could use this instead:

```
<?php if ($view->name == 'view_name' || $view->name == 'view_name_2'): ?>

```

If you want to affect all blocks/pages that are inside these 2 views.

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


# Question
Title: Separating contextual-links CSS, out of the CSS of menus and other associated markup
The following problem happens when you style menus in Drupal, using CSS. The problem is especially dominant when you edit the `<a>` tags of a menu, but happens in regards to all of the menu markup.

The following images describe problems for two different menus, in which CSS directives I gave to my `#navigation` selector and its `<a>` tags, such as `height: 60px`, `display: inline-block`, and `color: #fff`, are inherited by the contextual links markup and thus destroy its appearance and making it impractical if not nonfunctional.

Thus, the solution I need is to separate the contextual links CSS from the themes', loading it afterwards or hardcoded somehow.

I dedicate this question to experienced themers: How can one load the contextual links with "hardcoded" CSS code, so they won't inherit anything from CSS directives I write in any theme-dependent CSS.

## Code information:

Twig data:

```
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('menu') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

```

Mobile-first responsive CSS:

```
#navigation {height: auto; padding: 10px 0 10px 0; background: #0a97b7}
    #navigation ul {display: none} /*For JS conditioning: if none than...*/
    #navigation li {display: block}
        #navigation a {color: #fff}
            #navigation a:hover {text-decoration: none}
    .navtoggle {display: block; padding: 10px 25px 10px 0; font-size: 24px; background: none !important}

```

Desktop level CSS:

```
@media screen and (min-width: 1080px) {
    #navigation {height: 60px; padding: 0}
        #navigation ul {display: block}
            #navigation li {display: inline-block}
                #navigation a {height: 60px; line-height: 60px; padding: 0 15px 0 15px; display: inline-block}
                /*<a> must be either block/inline-block to have its height changed.*/
                    #navigation a:hover {background: #55cfd6; text-decoration: none}
    #navigation .menu-item {display: inline-block; float: right}
    #navigation .is-active {background: #55cfd6}
    .navtoggle {display: none !important}
}

```

Complete reset of the contextual links class as follows, isn't effective (nor it is adequate) and is overridden by more specific codes:

```
.contextual ul       {background: #fff !important}
.contextual li       {display: block !important}
.contextual a        {color: black !important; height: auto !important; line-height: 1.3em !important; background: #fff !important}
.contextual a:hover  {background: #f4f4f4 !important}

```

**Every in-place menu seems better with this compelete reset, but it still don't cover all menus.**

# Answer
If you do it like that `#id a { ... }` it will affect all the `<a>`'s of all the child divs that are inside the wrapper. Since the contextual links are inside it, they get affected.

Ex: if you do `html a { color: purple;}` since everything is a child of HTML, every single `<a>` gets affected.

In CSS there is no such command to affect all children except some child.

**In CSS you have to affect all children, and then you can override a specific child** by placing `.somediv a { color: green; }` after.

Ex:

```
html a { color: blue; } // all divs become blue.
.somediv a { color green; } // changes somediv to green.

```

If you do the same command:

```
a { color: brown; }
a { color yellow; }

```

It applies the brown first, but then applies the yellow. So the yellow is the actual one that you see. This is why it's called **C**ascading **S**tyle **S**heets. It reads from the top to the bottom.

So in your case you currently have

```
.contextual a{ color: black; } // applies black
#menu-id a{ color: orange; } // since contextual is inside #menu-id the orange gets applied, since this is last, you see orange on your screen.

```

### Solution (In Theory):

You need to load the style sheet that contains the `.contextual` AFTER the style sheet that contains the `#menu-id`

So when your website loads, it will read like this

```
#menu-id a{ color: orange; } // contextual is orange because it's inside menu-id, so it inherits this command.
// bunch of other stuff in between
.contextual a{ color: black; } // contextual is black

```

Since black is last, you see black for contextual

But there is one problem, the **/core/themes/stable/css/contextual/contextual.theme.css** gets loaded before your theme. You would have to hack core so it loads this css file after your theme's .css file.

### Alternative solution:

What you could do is find something that wraps around the tab only rather than something that wraps the entire menu, such as `.menu-item`
> 1 votes

# Answer
All contextual links are wrapped in a `div.contextual`, whereas navigational menu items are usually wrapped in a `li.menu-item`.
> 1 votes

---
Tags: theming, 8, navigation
---


# Question
Title: Why to use hook_drush_help() when we have 'description' in hook_drush_command()?
When you go to create new drush commands you can define the 'description' element inside the `hook_drush_command()`, and if you use `drush help your_command` you will see this description as output.

```
function onlyone_drush_command() {
  $items['onlyone-list'] = array(
    'description' => dt("List the configured content types to have Only One node."),
    'aliases' => array('ol'),
    'examples' => array(
      'drush onlyone-list' => dt("List the configured content types to have Only One node."),
    ),
  );
  return $items;
}

```

Command:

```
drush help ol

```

Output:

```
List the configured content types to have Only One node.

Examples:
 drush onlyone-list  List the configured content types to have Only One node.

Aliases: ol

```

But once you implement the `hook_drush_help()` and you use `drush help your_command` you will see the description defined inside this hook and you'll never see again the description defined inside `hook_drush_command()`.

```
function onlyone_drush_help($section) {
  switch ($section) {
    case 'drush:onlyone-list':
      return dt('This is from help');
  }
}

```

Command:

```
drush help ol

```

Output:

```
This is from help

Examples:
drush onlyone-list  List the configured content types to have Only One node.

Aliases: ol

```

So, why to use `hook_drush_help()` when we have 'description' in `hook_drush_command()`?

# Answer
The answer is *context*.

The command data pulled from `hook_drush_command()` is used when listing of all available drush commands with the command:

```
drush

```

So if a user is curious, "What drush commands do I have, and what do they do?" `hook_drush_command()` would provide that snippet. This could be useful for a short description in a directory of commands.

If a user is curious about a specific command:

```
drush help my_command

```

That's where `hook_drush_help()` would be more applicable as it can provide a detailed description that is only about that command queried.
> 2 votes

---
Tags: drush
---


title: View filter by date not current

text:
# Question
Title: View filter by date not current
I have two blocks on our Drupal 8 front page: one shows a list of events upcoming; the other a list of events past. The blocks are generated from views filtering nodes whose event dates are after and before today's date respectively (using an 'event date' field, not the date authored). The granularity of the event dates is to an hour. The filter is set to compare to 'now'.

But ... the lists are rarely up to date, usually several days out in fact. With 'future' events having event dates of days recently passed. So I'm not looking at caching as the source of the problem (rightly or wrongly) as we have cacheing configured in hours not days.

What can I do to ensure that the lists are correct each day?

# Answer
> Clearing the cache has no immediate effect.

Then it's very likely that is not a caching issue and it's a set up issue.

This should work, is greater than 0 minutes
> 4 votes

---
Tags: views
---


title: How to tag a view?

text:
# Question
Title: How to tag a view?
Views in drupal allow to filter content. A single webpage can have many views. A way to get them sorted is to use a initial letter (as A\_view\_name). Another one is to use tags.

I don't understand if tagging views is out of the box (with drupal 7 or 8), or I have to install some module (as https://www.drupal.org/project/metatag).

# Answer
Click on the `edit view name/description` button

The following pops up, by default, you will see `default` is set as the view tag, I changed it to `example`

Now when you to to `/admin/structure/views`

You can click on the blue TAG header to sort by tag.

---

**PS:** The Metatag module is for SEO purposes.

> **Meta tags** are snippets of text that describe a page's content; the meta tags don't appear on the page itself, but only in the page's code. We all know tags from blog culture, and meta tags are more or less the same thing, little content descriptors that help tell search engines what a web page is about.
>
> source: http://www.wordstream.com/meta-tags
> 5 votes

---
Tags: views
---


# Question
Title: How can I print out a form in a twig template file
I am looking to use bootstrap modal window to show a Drupal form, and the easiest way to do it seems to be to put the bootstrap html into a twig template file, however I have no idea how to render out the form inside this html.

# Answer
Well, I did it, for anyone that needs this:

```
  $myform = \Drupal::formBuilder()->getForm('Drupal\[mymodule]\Form\[myformclass]');
  $build = [
    '#theme' => 'twigTheme'
    '#form' => $myform,
  ];

```

In twig:

```
{{ form }}

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: How can I create an entity bundle programmatically?
Given a custom defined entity 'Foo', how can I make a bundle programmatically?

Such as Node entity has the Article and Basic page bundles (with fields) on install.

# Answer
> 2 votes
Bundles are configuration.

You define a config entity with the name of the bundle of the custom entity:

```
class FooType extends ConfigEntityBundleBase

```

Then you can create a new bundle:

```
$bundle = FooType::create([
  'id' => 'newbundle',
  'label' => 'New Bundle',
  'revision' => FALSE,
]);
$bundle->save();

```

Bundles usually are not created programmatically. Most times modules put bundles in /config/install as yml files.

---
Tags: 8, entities
---


# Question
Title: Allowing unlimited values for a field in programmatically defined form
I am trying to insert a custom form into a page in my Drupal 8 site. This form has 2 fields which need to accept unlimited values (one textfield, one fieldset).

In my current implementation, I have declared this form as a class, defined in the `src` folder of a module, and my `.module` file adds this form to the `$build` array via `hook_node_view_alter()`:

`$build['myform'] = \Drupal::formBuilder()->getForm('Drupal\my_module_hook\Form\MyForm');`

My class constructs the form using `public function buildForm(array $form, FormStateInterface $form_state)`. I am not sure how to set up a field such that it can accept unlimited values.

I'm aware that tutorials and answers on this topic using Ajax exist such as this and this, but all such examples are using `$form_state` as an array, which breaks my code as `$form_state` is an object.

Is building this form as a class the wrong way to do it? If not, how exactly do I accomplish what I'm trying to do without using `$form_state` as an array? If so, how can I insert my form into the page otherwise? I'm not understanding how other answers and tutorials on the subject are accomplishing this since these functions are usually shown out of context.

# Answer
I have set up a module demonstrating how to allow the user to add unlimited values: https://bitbucket.org/scotteuser/drupal-8-demo-form-unlimited-values

Here is the Form itself:

```
<?php

namespace Drupal\demo_form_unlimited_values\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class UnlimitedValuesForm.
 *
 * @package Drupal\demo_form_unlimited_values\Form
 */
class UnlimitedValuesForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'unlimited_values_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // State that the form needs to allow for a hierarchy (ie, multiple
    // names with our names key).
    $form['#tree'] = TRUE;

    // Initial number of names.
    if (!$form_state->get('num_names')) {
      $form_state->set('num_names', 1);
    }

    // Container for our repeating fields.
    $form['names'] = [
      '#type' => 'container',
    ];

    // Add our names fields.
    for ($x = 0; $x < $form_state->get('num_names'); $x++) {
      $form['names'][$x]['first_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('First name @num', ['@num' => ($x + 1)]),
      ];

      $form['names'][$x]['last_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Last name @num', ['@num' => ($x + 1)]),
      ];
    }

    // Button to add more names.
    $form['addname'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add another name'),
    ];

    // Submit button.
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  /**
    * {@inheritdoc}
    */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    // Decide what action to take based on which button the user clicked.
    switch ($values['op']) {
      case 'Add another name':
        $this->addNewFields($form, $form_state);
        break;

      default:
        $this->finalSubmit($form, $form_state);
    }
  }

  /**
   * Handle adding new.
   */
  private function addNewFields(array &$form, FormStateInterface $form_state) {

    // Add 1 to the number of names.
    $num_names = $form_state->get('num_names');
    $form_state->set('num_names', ($num_names + 1));

    // Rebuild the form.
    $form_state->setRebuild();
  }

  /**
   * Handle submit.
   */
  private function finalSubmit(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Do what you want with the final data here'), 'status');
  }

}

```

The critical bits are:

* `$form[#tree]` tells Drupal that the form is hierarchical.
* `$form_state->get()` and `$form_state->set()` are used around the counter `num_names`
* Check the 'op' to see which button the user pressed. If they pressed to add another field, use `$form_state->set()` to increase the count and `$form_state->setRebuild();` to tell Drupal that the form should be rebuilt.

Hope that helps you get it working!
> 2 votes

---
Tags: 8, forms
---


# Question
Title: Status report: Twitter module using unautheticated api
So, I'm getting kind of a strange error in my status report about my twitter module. I get an error that the twitter pull authentication is using an unauthorized api" Below that it says that the Twitter modules doesn't have any authorized accounts, and that I should add an authorized account via the accounts page. The issue is that I have authorized accounts attached.

I'm using twitter module 6.2 and twitter pull version 7-2.0alpha3.

callback url is: twitter/oauth the host is : twitter.com and the api is: https://api.twitter.com

Not sure if this an incompatibility between versions, or what the problem is here. How to fix?

# Answer
Twitter module was misconfigured, not updated.
> 0 votes

---
Tags: social-network
---


# Question
Title: Drush on windows 10 gives an error - Command pm-update needs a higher bootstrap level to run
When I try to use drush to work on my local site I get this error:

Command pm-update needs a higher bootstrap level to run - you will need to invoke drush\[error\] from a more functional Drupal environment to run this command. The drush command 'up' could not be executed. \[error\] Drush was not able to start (bootstrap) the Drupal database.

I have wamp server installed on windows 10. I also have composer and drush installed on windows 10. I have the user environment path set up correctly. I am in the drupal directory. I have my local drupal site set up but I cannot get drush to work. I have been crawling the internet and can only find older solutions.

My user environment path for drush is C:\Users\Name\AppData\Roaming\Composer\vendor\drush\drush

My user environment path for composer is C:\Users\Name\AppData\Roaming\Composer\vendor\bin

When I type drush status I get

```

$ drush status
 Drupal version         :  8.1.8
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  root
 Database name          :  tekopolis
 PHP configuration      :  C:\wamp64\bin\php\php7.0.4\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:\Users\Anthony\AppData\Roaming\Composer\vendor\drush\drush\drush
 Drush version          :  8.1.3
 Drush temp directory   :  C:\Users\Anthony\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  C:\wamp64\www\tekopolis
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default
 Sync config path       :  sites/default/file/config[...]/sync

```

Does anyone know how to get drush working on windows 10 without acquia dev?

# Answer
My experience is that these kind of tools are more easier to install on a Linux based system (ports of this programs to Windows are always limited in their capabilities). Luckily, the Windows 10 Anniversary update includes "**Ubuntu on Bash on Windows 10**", which allows you to natively run terminal-based Linux applications and Bash commands in Windows. Using this feature you can simply follow the native tutorials/install instructions.

To install this Bash shell in Windows 10 (after installing the Anniversary Update), you have to enable the developer mode (go to Settings \> Update and Security \> For developers). Then in the start menu search for the application: "Turn Windows features on or off" and with this application enable the "Windows Subsystem for Linux (Beta)". A reboot of your computer will follow and after this search in the start menu for "Bash" and follow the instructions. Once completed, you can use the program "Bash on Ubuntu on Windows" to start up your Linux shell.

With apt-get you can install php5 (don't forget to use sudo here), from there you can follow the install instructions of Composer and/or Drush.
> 1 votes

---
Tags: drush
---


# Question
Title: Backup and restore DB to remote DB cause blank page
i'm new to drupal 8, i'm trying to backup and restore localhost db to remote db, but when i open home page, it just display a blank page (with source code).

```
<!DOCTYPE html>
<html lang="en" dir="ltr" prefix="content: http://purl.org/rss/1.0/modules/content/  dc: http://purl.org/dc/terms/  foaf: http://xmlns.com/foaf/0.1/  og: http://ogp.me/ns#  rdfs: http://www.w3.org/2000/01/rdf-schema#  schema: http://schema.org/  sioc: http://rdfs.org/sioc/ns#  sioct: http://rdfs.org/sioc/types#  skos: http://www.w3.org/2004/02/skos/core#  xsd: http://www.w3.org/2001/XMLSchema# ">
  <head>
    <meta charset="utf-8" />
<meta name="Generator" content="Drupal 8 (https://www.drupal.org)" />
<meta name="MobileOptimized" content="width" />
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="/core/misc/favicon.ico" type="image/vnd.microsoft.icon" />

    <title>Home | plant testing site</title>
    <style media="all">
@import url("/core/assets/vendor/normalize-css/normalize.css?odbvth");
@import url("/core/themes/stable/css/system/components/ajax-progress.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/align.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/autocomplete-loading.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/fieldgroup.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/container-inline.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/clearfix.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/details.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/hidden.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/item-list.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/js.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/nowrap.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/position-container.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/progress.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/reset-appearance.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/resize.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/sticky-header.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/tabledrag.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/tablesort.module.css?odbvth");
@import url("/core/themes/stable/css/system/components/tree-child.module.css?odbvth");
</style>
<style media="all">
@import url("/themes/bootstrap_business/bootstrap/css/bootstrap.min.css?odbvth");
@import url("/themes/bootstrap_business/css/base/style.css?odbvth");
@import url("/themes/bootstrap_business/css/base/colors.css?odbvth");
@import url("/themes/bootstrap_business/css/base/local.css?odbvth");
@import url("/core/themes/classy/css/components/action-links.css?odbvth");
@import url("/core/themes/classy/css/components/breadcrumb.css?odbvth");
@import url("/core/themes/classy/css/components/button.css?odbvth");
@import url("/core/themes/classy/css/components/collapse-processed.css?odbvth");
@import url("/core/themes/classy/css/components/container-inline.css?odbvth");
@import url("/core/themes/classy/css/components/details.css?odbvth");
@import url("/core/themes/classy/css/components/exposed-filters.css?odbvth");
@import url("/core/themes/classy/css/components/field.css?odbvth");
@import url("/core/themes/classy/css/components/form.css?odbvth");
@import url("/core/themes/classy/css/components/icons.css?odbvth");
@import url("/core/themes/classy/css/components/inline-form.css?odbvth");
@import url("/core/themes/classy/css/components/item-list.css?odbvth");
@import url("/core/themes/classy/css/components/link.css?odbvth");
@import url("/core/themes/classy/css/components/links.css?odbvth");
@import url("/core/themes/classy/css/components/menu.css?odbvth");
@import url("/core/themes/classy/css/components/more-link.css?odbvth");
@import url("/core/themes/classy/css/components/pager.css?odbvth");
@import url("/core/themes/classy/css/components/tabledrag.css?odbvth");
@import url("/core/themes/classy/css/components/tableselect.css?odbvth");
@import url("/core/themes/classy/css/components/tablesort.css?odbvth");
@import url("/core/themes/classy/css/components/tabs.css?odbvth");
@import url("/core/themes/classy/css/components/textarea.css?odbvth");
@import url("/core/themes/classy/css/components/ui-dialog.css?odbvth");
@import url("/themes/bootstrap_business/css/components/primary-menu.css?odbvth");
@import url("/themes/bootstrap_business/css/components/to-top.css?odbvth");
</style>

<!--[if lte IE 8]>
<script src="/core/assets/vendor/html5shiv/html5shiv.min.js?v=3.7.3"></script>
<![endif]-->

  </head>
  <body class="path-frontpage">
        <a href="#main-content" class="visually-hidden focusable skip-link">
      Skip to main content
    </a>

    <script src="/core/assets/vendor/jquery/jquery.min.js?v=2.1.4"></script>
<script src="/themes/bootstrap_business/bootstrap/js/bootstrap.min.js?v=8.1.8"></script>
<script src="/themes/bootstrap_business/js/custom/toggle.js?v=8.1.8"></script>

  </body>
</html>

```

anyone know what is the problem and how to fix it?

# Answer
> 0 votes
run this to clear cache

```
TRUNCATE TABLE `cache_bootstrap`;
TRUNCATE TABLE `cache_config`;
TRUNCATE TABLE `cache_container`;
TRUNCATE TABLE `cache_data`;
TRUNCATE TABLE `cache_default`;
TRUNCATE TABLE `cache_discovery`;
TRUNCATE TABLE `cache_dynamic_page_cache`;
TRUNCATE TABLE `cache_entity`;
TRUNCATE TABLE `cache_menu`;
TRUNCATE TABLE `cache_render`;
TRUNCATE TABLE `cache_toolbar`;
TRUNCATE TABLE `cachetags`;

```

---
Tags: 8, database
---


# Question
Title: Is there a way to restrict access to a calendar page excepting the owner of the content?
I'm pretty new to drupal and I hope to get the solution here. Goes like this: I have a content type named "property" and a calendar attached to each node of this content type. In the permissions section the calendar has "Access bookable item's calendar" which controls who has access to the calendar pages. One of the roles "propertyadmin" has this permission set. Now comes the problem - All users having that role has the same permission and can edit all other calendar pages. I think the problem is here in the calendar module because it doesn't have any conditional logic to check whether the user accessing the calendar is the owner of the referenced node.

Can anyone help? Here is the code:

\` function property\_calendar\_menu() {
$items = array();
$items\['admin/property/items/%property\_item/calendar'\] = array(
'title' =\> t('Calendar'),
'page callback' =\> 'drupal\_get\_form',
'page arguments' =\> array('property\_calendar\_admin\_form', 3, 5, 6),
'access arguments' =\> array('access property\_item calendar'),
'type' =\> MENU\_LOCAL\_TASK,
'context' =\> MENU\_CONTEXT\_PAGE | MENU\_CONTEXT\_INLINE,
'file' =\> 'includes/property\_calendar.admin.inc',
);
$items\['node/%node/calendar'\] = array(
'title' =\> t('Calendar'),
'page callback' =\> 'property\_calendar\_overview',
'page arguments' =\> array(1, 3, 4),
'access callback' =\> 'property\_calendar\_overview\_access',
'access arguments' =\> array(1),
'type' =\> MENU\_LOCAL\_TASK,
'weight' =\> 4,
'context' =\> MENU\_CONTEXT\_PAGE | MENU\_CONTEXT\_INLINE,
'file' =\> 'includes/property\_calendar.admin.inc',
);

$items\['custom\_calendar/ajax'\] = array(
'title' =\> 'AHAH callback',
'page callback' =\> 'custom\_calendar\_status\_ajax',
'page arguments' =\> array(2, 3, 4),
'delivery callback' =\> 'ajax\_deliver',
'access callback' =\> TRUE,
'theme callback' =\> 'ajax\_base\_page\_theme',
'type' =\> MENU\_CALLBACK,
);
return $items;
}
/\** * Access callback for overview form. \*/
function custom\_calendar\_overview\_access($node) {
// Foreach field.
foreach (field\_info\_fields() as $field) {
// If field is entityreference, targets a property\_item
// and it belongs to a node.
if ($field\['type'\] == 'entityreference' and $field\['settings'\]\['target\_type'\] == 'property\_item' and isset($field\['bundles'\]\['node'\])) {
// If current node's type has this field.
if (in\_array($node-\>type, $field\['bundles'\]\['node'\])) {
return user\_access('access property\_item calendar');
}
}
}
return FALSE;
}
\`

# Answer
$items\['node/%node/calendar'\] = array( ...

'access callback' =\> 'node\_access',
'access arguments' =\> array('update', 1),

I manage to solve this part. I still need help for the first URL
> 0 votes

---
Tags: users
---


title: drupal migrate source csv

text:
# Question
Title: drupal migrate source csv
I am trying to use 'migrate source csv' to migrate some content with taxonomy terms in drupal 8. If the field has only one term, I can use the following and it works out fine`process:
 type:
 plugin: default_value
 default_value: adi
 title: title
 field_description: description
 body: note
 field_subject_terms:
 plugin: entity_generate
 source: subject_terms
destination:
 plugin: 'entity:node'`

However, if it has more than one term, and I try with the following code, I get an error about th term is not an integer. I have also tried adding the iterator plugin to the code below, but still the same error.`process:
 type:
 plugin: default_value
 default_value: adi
 title: title
 field_description: description
 body: note
 field_subject_terms:
 plugin: explode
 source: subject_terms
 delimiter: ','
 process:
 plugin: entity_generate
destination:
 plugin: 'entity:node'
migration_dependencies: null`

Any help appreciated. Thanks

# Answer
> 2 votes
'process' is not recursive - you can't simply embed processing within another plugin in the general case (only iterator has that ability). Rather, plugins (generally) need to be executed in sequence:

```
field_subject_terms:
  # First step in the processing pipeline.
  -
    plugin: explode
    source: subject_terms
    delimiter: ','
  # Results of the first step are passed through to the second step.
  -
    plugin: entity_generate

```

---
Tags: migrations
---


# Question
Title: How do I open up a YAML Form in a bootstrap modal window
I have a form made in the YAML Form module and I would like it to open up in a bootstrap modal window.

Can I just put the Bootstrap html into my page.hmtl.twig file and print out the form somehow?

This would be sufficient for my purposes as I want to form to be accessible from all pages on the website.

If this is not the Drupal way could someone please point me in the right direction

# Answer
The drupal way to do this would be to use blocks. The YAML Form module has the feature to put form in blocks. Place the form block in a region, where you want to have it on the page. Then style it in a block template:

**block--my-form.html.twig**

```
<div class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
                {{ content }}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

```
> 1 votes

---
Tags: theming, 8
---


title: Alert 3 months before the ending date

text:
# Question
Title: Alert 3 months before the ending date
I am using the Views and the Views conditional modules to display an alert message 3 months before the ending date is coming, but it does not work. For example the ending date is 12/10/2016(m/d/Y) and I want an alert shows before that 3 months such as 09/10/2016(m/d/Y). So this is my views

This is my Views condition

# Answer
> 0 votes
Looks like you're struggling with the issue about Date comparison not working.

You may want to try the steps explained in Comment # 20, to configure the timestamps.

If that doesn't work, then try what's suggested in Comment # 19, ie:

> Use the Views Date Format SQL module to format the date on the database server, prior to rendering by Views. This will allow for comparisons in Views Conditional.

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


# Question
Title: Is it possible to replace more than one form element (wrappers) triggered by only one #ajax trigger element?
```
function ajax_example_simplest($form, &$form_state) {

  //This is my ajax trigger element
  $form['element_trigger'] = array(
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      'callback' => 'ajax_example_simplest_callback',

      /** Q: Can I somehow declare more than one wrapper? **/
      //Say for instance, something like:
      'wrapper' => array('replace_div_1', 'replace_div_2'),

     ),
  );

  //replace_div_1
  $form['element_to_be_replaced_1'] = array(
    '#type' => 'textfield',
    '#title' => t("My conditional field one"),
    '#prefix' => '<div id="replace_div_1">',
    '#suffix' => '</div>',
  );

 //... more form elements here

  //replace_div_2
  $form['element_to_be_replaced_2'] = array(
    '#type' => 'textfield',
    '#title' => t("My conditional field two"),
    '#prefix' => '<div id="replace_div_2">',
    '#suffix' => '</div>',
  );
  return $form;
}

function ajax_example_simplest_callback($form, $form_state) {

  //... do my stuff here

  //normally I would return only the form bit for replacing a single wrapper
  //declared in the trigger element, like this:
  return $form['element_to_be_replaced_blahblah'];

}

```

Is it possible to return more than one form bit in the callback function telling the AJAX framework that `$form['element_to_be_replaced_1']` should replace `<div id="replace_div_1">` and `$form['element_to_be_replaced_2']` should replace `<div id="replace_div_2">`?

# Answer
Instead of returning the HTML of the single element to update, your ajax callback can return an array of ajax commands. So it can return two ajax\_command\_replace to replace each element.

```
function ajax_example_simplest_callback(&$form, $form_state) {
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#replace_div_1", render($form['element_to_be_replaced_1'])),
      ajax_command_replace("#replace_div_2", render($form['element_to_be_replaced_2']))
    )
  );
}

```
> 75 votes

# Answer
Drupal 8 alternate syntax

```
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

class name extends FormBase{
   function ajax_example_simplest(array $form, FormStateInterface &$form_state) {
       $response = new AjaxResponse();
       $response->addCommand(new ReplaceCommand("#replace_div_1", ($form['element_to_be_replaced_1'])));
       $response->addCommand(new ReplaceCommand("#replace_div_2", ($form['element_to_be_replaced_2'])));
       return $response;
   }
}

```

One diffrence is that the render command is dropped, because AjaxResponse implements Drupal\Core\**Render**\AttachmentsInterface

render($form\['element\_to\_be\_replaced\_1'\])

Adding the render still works, but I had problems when updating a TableSelect Table that way.
> 6 votes

# Answer
Pierre Buyle's answer did not work for me. However, something like the following worked.

```
function ajax_example_simplest_callback(&$form, $form_state) {
    $commands = array();
    $commands[] = ajax_command_replace("#replace_div_1", render($form['element_to_be_replaced_1']));
    $commands[] = ajax_command_replace("#replace_div_2", render($form['element_to_be_replaced_2']));
    $page = array('#type' => 'ajax', '#commands' => $commands);
    ajax_deliver($page);
}

```

Note the call to ajax\_deliver(), rather than returning the array of AJAX commands.
> 4 votes

---
Tags: ajax
---


# Question
Title: Getting xdebug to work with BrowserTestBase functional tests?
I'm having a really difficult time trying to get XDebug working with my functional tests that extend from BrowserTestBase.

Does anyone have a working configuration in place for this?

I'm using PHPStorm (version 2016.2) for debugging and already have a working XDebug setup for standard unit tests. I've been initiating the tests from PHPStorm directly, but would certainly be happy running them from a terminal outside of PHPStorm if it works!

Here's what I've tried for running out outside of PHPStorm in a normal terminal:

```
export SIMPLETEST_BASE_URL=http://drupal8.dd:8083
export XDEBUG_CONFIG="idekey=PHPSTORM"
vendor/bin/phpunit --configuration core/phpunit.xml.dist /Users/bosborne/Projects/drupal8/modules/cas/tests/src/Functional/CasAdminSettingsTest.php

```

The tests run but my breakpoints are ignored.

# Answer
> 7 votes
BrowserTestBase and KernelTestBase use phpunit's 'run in separate process' feature which generates a new temporary php file from a template and then executes that. The output is provided as serialized php object which is then read back into the main thread an unserialized to yield the results.

So at present that makes using Xdebug fairly difficult.

We probably should open an issue to look at shipping our own template that support Xdebug.

In the meantime my suggestion would be to use outputting, you can use the standard approaches like `var_export`, `print_r`, `echo` etc or you can use `$this->htmlOutput($something_you_need_to_debug);` which then shows up amongst the other HTML output.

Then run your tests with `-printer="\Drupal\Tests\Listeners\HtmlOutputPrinter"`

This requires the `BROWSERTEST_OUTPUT_DIRECTORY` environment variable to be set, see core's phpunit.xml.dist for info on how to configure that.

---
Tags: 8, testing
---


# Question
Title: How to override user_picture per comment?
I use the facebook connect plugin. By default it downloads the 50x50 pixel facebook image. It luckily stores it as the profile ID, which I can in turn use to look up the large version of the image. So I need way to:

1. Get the current user\_picture for a comment, and then
2. Override it with a new url.

I have this so far:

```
function capewinefarms_preprocess_comment(&$variables)
{
    $comment = $variables['elements']['#comment'];
    $variables['comment_create_date'] = format_date($comment->created->value, "custom", "d M Y, H:i:s");

    $variables['user_picture'] =  'BLA';
}

```

The above code replaces the user's profile pic with the words "BLA". But I don't want that. So I need a way to see what the variables object looks like, so I can see where to get the current value and to change it. But if I do this:

```
print_r($variables);

```

It just bombs out and shows a blank screen (as if the variable is blank).

How do I change the user picture?

# Answer
> 0 votes
A dump of the `$variables` array is probably causing out-of-memory problems as preprocess variables in D8 can have some heavy depth to them.

Anyway, you can retrieve the image url from `$user_picture` render array which has a reference to the comment's user:

```
  $comment_user = $variables['user_picture']['#user'];
  if ($user_image = $comment_user->user_picture->first()) {
    $user_image_uri = $user_image->entity->uri->value;
  }

```

---
Tags: theming, 8
---


# Question
Title: How do I use jQuery code through a module/theme?
How do I use jQuery through a Drupal 8 module? I'm trying to get some jquery code running on a drupal 8 website. It's a div animation that randomly moves the div within a wrapper. I've added the JS and CSS files and they're both showing in the source. I've then added the Div ID of 'container' to html.html.twig(yes I copied it into my theme folder first) -

```
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    theme.settings.navbar_position ? 'navbar-is-' ~ theme.settings.navbar_position,
    theme.has_glyphicons ? 'has-glyphicons',
    'container',
  ]
%}

```

Also added a div to use for this. Again in html.html.twig

```
<js-bottom-placeholder token="{{ placeholder_token|raw }}"> //**Not part of my code just adding it for comparison.
   <div class='fly'>TEST DIV, IF I MOVE I'M WORKING!</div>

```

So the files show up in the source and the source also shows that the div ID of container has been added.

Here's the jQuery code, keep in mind that I've adjusted it to work with Drupal 8 so there's probably a syntax error or two.

```
$.extend(Drupal.theme, {
  animateDiv: (function() {
    ($('.fly')); }),

```

* Almost certain the problem is here ^^^

```
  makeNewPosition: function ($container) {
    // Get viewport dimensions (remove the dimension of the div)
    var h = $container.height() - 10;
    var w = $container.width() - 10;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];
},

animateDiv: function ($target) {
    var newq = makeNewPosition($target.parent());
    var oldq = $target.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $target.animate({
        top: newq[0],
        left: newq[1]
    }, speed, function() {
        animateDiv($target);
    });

},

calcSpeed: function (prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = 0.23;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}

});

```

Here's the CSS code

```
.fly {
width: 50px;
height:50px;
background-color: red;
position:fixed;

}

```

That's what I've tried and yet there's still no jQuery activity, I've also tried using different types for class names(.div instead of #div etc) which I think is where the problem is. The flying div shows but isn't being styled and there's no jQuery. What am I doing wrong?

Update: After playing with the code for awhile I've managed to at least get the style to show on the div. jQuery still a no show though..

This isn't the same jquery code but it's similar and it's what I would like, the div floats around the entire page, I've tried using this code as well but I still get the same problem as above. http://jsfiddle.net/Xw29r/15/

# Answer
> 3 votes
In Drupal 7 and 8 your JS code needs to be wrapped like this:

```
(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

    //custom code goes here

  }
};
})(jQuery);

```

To test, put the following code inside your JS file.

```
(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

    //code starts
    $("body").click(function() {
      alert("Hello World");
    });
    //code ends

  }
};
})(jQuery);

```

Now when you click in the body, you should get an alert saying hello world.

For more info read the JavaScript API in Drupal 8

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


# Question
Title: How to add a subtitle field to a block view?
I want to add an additional subtitle to a block view in Drupal 8. For example my View would be showing News on the site. So I want the title to be 'News' and then a subtitle underneath 'My Subtitle'. Then the list of news would follow. How would I do this? Can i add additional fields just like with custom blocks?

In the end it should look something like that:

```
    <div class="content-section-heading">
       <h2 class="content-section-subtitle"> Subheadline </h2>
       <h1 class="content-section-title"> Headline </h1>
    </div>
   <div>
      Block Content
   </div>

```

# Answer
The easiest solution is to add a `Global: Text area` in the **`HEADER`** and type your Subtitle there.

You can use FULL HTML and wrap it in a div class or ID so you can do some CSS work on it.

> Can i add additional fields just like with custom blocks?

You can add fields to your view

or attach another view that contains fields in the **`FOOTER`**, but fields in views and fields in custom blocks are totally different.
> 3 votes

---
Tags: views, 8, blocks
---


title: How do I create a new variable?

text:
# Question
Title: How do I create a new variable?
I want to use a new variable in a view using global PHP. Between the available variables, I have `$row->my_field`, and I want to put its value in a new variable.

```
$new = $row->my_field;
echo $new

```

I'm using this code in *Output Code*. I get the following error:

> Syntax error, unexpected 'echo' (T\_ECHO) ...

I cannot even use `array_unique()`.

Is it possible to add a new variable? and Is it possible to use a function like `array_unique()`?

# Answer
> Is it possible to add a new variable?

YES

> Is it possible to use a function like `array_unique()`?

Yes, as long as you have an array to pass as a parameter.

**PS:** You shouldn't be using Views PHP to begin with; you should create a template file for your view and add the PHP code there.

What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?
> 0 votes

---
Tags: 7, views
---


title: ThemeKey rule; how to target IMCE pages

text:
# Question
Title: ThemeKey rule; how to target IMCE pages
On my Drupal 7 site, I noticed that the IMCE popup loses its action buttons and all functionality when I'm using Adminimal as the admin theme:

In the *Known Issues* section of the IMCE project page, it mentions using the ThemeKey module if there is a conflict with your custom theme. Here are the ThemeKey rules it says to write:

```
drupal:path = %token
drupal:path:wildcard token * imce

```

When I do this, the IMCE buttons are, in fact, back in place (yay!)... *BUT* the entire site, both public pages and administration pages, are also displayed in Garland (boo!).

How can I force *just* the IMCE popup window to render in Garland?

# Answer
As is my nature, I was totally overthinking this. Here's what I had to do in ThemeKey:

First, for the File field:

```
drupal:path = imce-filefield/%

```

Basically, this is matching the first section of the URL path with `imce-filefield` and then whatever else comes after it is matched with `/%`.

This solves the problem for file/image uploads. The IMCE file browser used in the WYSIWYG editor (in my case, CKEditor) has a different URL path, so its interface is still broken. That one is simply:

```
drupal:path = imce

```

So far so good...
> 0 votes

---
Tags: files, theme-negotiation
---


title: How import Feeds into entityforms

text:
# Question
Title: How import Feeds into entityforms
Does anyone know if there is a way to use `Feeds` to import into `Entityforms`?
I have a `CSV` file of usernames and spent some hours at a specific event and would like to import it into it's corresponding form rather than entering it in all by hand.
**How can I import Data from `CSV` file into EntityForm\`?**

# Answer
> 1 votes
Other than Migrate (which I have not tried yet), the only thing I have found was to use Feeds Import with the contributed patch for a Generic Entity Processor to import Entityforms.

https://drupal.org/node/1033202#comment-7710367

I currently have Drupal 7.23 and Feeds 7.x-2.x-dev (7/6/13) and I patched the feeds module successfully with the patch at comment #217. This then gives you the option of having an entityform as a bundle.

I created a test entityform, a small test csv, and a new test feeds import. The import completes successfully, but there's no content in the submissions. Maybe you'll have better luck than I. My next step is to checkout the latest from git and try again. If that doesn't work, I guess I'm going to have to learn how to write a migrate module.

FYI, I have successfully used the Feeds Import module using the node processor that comes with the module for custom content types if you don't need it as an entityform. There are several good Feeds videos out there is you're not familiar with the module.

Please reply if you find something else that works.

# Answer
> 1 votes
Both in D8 and 7 you can also use RESTful-interface: https://www.drupal.org/node/2405657

You can POST to /entity/taxonomy\_vocabulary etc

# Answer
> 1 votes
To get around this, I set up an extra content type that and used Form Block.

It depends on your needs but for me, it offered the same functionality.

---
Tags: feeds, entities, importing-exporting
---


# Question
Title: AJAXifying content and pagination problems
I am using the Ajax links API module that allows to load a node inside a `<div>` tag by using `<a class="ajax-link" href="node/add/page" rel="#content">Add page</a>`.

However, I have a problem: If I use a pager, and I click on the link to see another page, I will be redirected to that page, instead of loading it inside the `<div>` tag.

I solved partially by using the Views Infinite Scroll module, but if I have several `<div>` tags, the module doesn't load the correct view in the correct `<div>`.

It seems I cannot use the pagination because the URL is not re-written to accommodate to the container, and it is not scrolling because this limitation.

Is there some way of creating simple AJAX calls loading content in different `<div>` tags on the same page, and with pagination (or load more button, infinite scrolling, etc.)?

# Answer
> 2 votes
Try this below solution with views pager ajax enable.

jQuery 1.7+ Version

```
function runthiscode() {
  $(".pager a").each(function(){
    $(".pager a").addClass("ajax-link");
    $(".pager a").attr('rel', '#content')
  });
}

$(document ).ready(function() {
  runthiscode();
});

$(document ).ajaxComplete(function() {
  runthiscode();
});

```

# Answer
> 1 votes
It seems your problem is similar to Ajax pager does not work as expected for nested views, I had this problem before and patch #15 help me to resolve.

take a look and try that if it not work tell me I suggest you another solution

# Answer
> 0 votes
Try this with below jquery solution.

jQuery 1.7+ Version

```
function runthiscode() {
  $(".pager a").each(function(){
    var a_href = $(this).find('a').attr('href');
    $('.pager a').on('click', function(event){
      $("#content").load(a_href+" #content");
    });
  });
}

$(document ).ready(function() {
  runthiscode();
});

$(document ).ajaxComplete(function() {
  runthiscode();
});

```

---
Tags: 7, views, ajax, paging
---


# Question
Title: View filtered by taxonomy term - is there a better way?
I am using Drupal 7.14 and I'm wrestling with filtering my content type based on taxonomy terms. I have a solution but I'm sure there must be a better way!

I have a content type called News. It has a taxonomy field so I can categorize the postings to it. I currently have 4 different taxonomy terms.

I also have a view that shows a page with all the News item teasers and links to the full article.

I have a menu on the side of the News page with links to each of the categories. Clicking on one of these links will show a page of teasers for that particular taxonomy term.

I have implemented the above as follows: In my News view I have added a display page for each of the taxonomy terms. On the same form I changed the "Page Settings" to set the path to the path of the taxonomy term (this overrides the default taxonomy view for the term). I also change the "Filter Criteria" and add a filter for the particular taxonomy term.

I then built a menu using the taxonomy term paths and made it appear on the News content type pages. Each item in the menu points at its taxonomy term path. When the user clicks on a menu item it correctly shows the view filtered for that category. Note: it does not show the default taxonomy term page because I set the path to the taxonomy term in my view and this takes priority.

I have also overridden the template for my view by adding a custom template file called views-view-fields--news.tpl.php. This template is used for the full view and each of the filtered views.

The above does work but is there a better cleaner way? It is quite tedious to add a new category as I need to manually update the view to add a new display for the new category and I then need to update the menu of categories.

Many Thanks.

# Answer
> 1 votes
1. Create a view with an **exposed** filter for each News category.
2. Under its settings, in **Admin**, there is a `Filter identifier` which can be changed. This goes after `?` in the URL.
3. Build your menu to link to the new view and add the category after the filter identifier.

The benefit of this is you can do it with any view so your tpl will work. And users can change category quickly using the dropdown menu. Or you can hide the exposed filter with CSS and make them use the menu.

# Answer
> 0 votes
You could also go ahead and let it link to the taxonomy term page, and then customize that view. I believe that would eliminate the need for manually entering categories.

Additionally, you could use contextual filters and set it to display a list of all terms when filter is not in URL.

# Answer
> 0 votes
When you add a new category your view is able to pick that up and dynamically create all the things you need here. Let views do the heavy lifting.

I am not familiar with your view but it sounds like it just needs tweaking to select all categories instead of the four you currently have.

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


# Question
Title: Address field tokens and country display
I have some user profiles with address fields attached. I created a view of these profiles, with the country as a contextual filter. I'm showing a summary of the results in one of my Views displays, so I can show the countries represented in my data set, with the number of matches for each: US (12) CA (6) DE (3) and so forth. I'd prefer to be able to show these as country names rather than 2-letter codes (though the 2-letter code is useful for linking to another part of my view...)

Is there a way to get Views to output the country names in this scenario? It does just fine when displaying them in fields or full content modes, but not in the result summary.

Any advice appreciated.

# Answer
> 0 votes
The addressfield\_tokens module extends the addressfield module by adding full token support. It also adds some convenient addressfield formatters and provides a webform addressfield integration.

Addressfield Token Module

---
Tags: views, tokens, entities
---


# Question
Title: How do you create a custom permission to administer a custom module?
I just finished the Hello World module tutorial for Drupal 8. The tutorial takes you through the process of creating an administration page to configure the module so that you can change via settings to whom the page says hello.

By default, the config page only requires the 'access content' user permission to view. I realize I can change the value to require any other already defined permission if I want, but how can I define a new permission specifically to administer just this module and nothing else? I found this similar question by searching, but it's for Drupal 7 instead of 8, and the solution leaves a lot to be desired; I would like my module to be self-contained, and requiring that the user download a non-core third-party module is not something I am prepared to do.

# Answer
Permissions can be added in the mymodule.permissions.yml file of the custom module.

You can also define permissions with a callback, if they depend on other items in the application.

See: https://kevinquillen.com/drupal/2016/02/21/dynamic-permissions-in-drupal-8
> 15 votes

---
Tags: 8, users
---


# Question
Title: How to integrate the drush help --filter option with your custom module?
You can use the `drush help --filter` command to present a list of command categories to view. When you run the command: `drush --filter=devel_generate` you can see the following output:

```
All commands in devel_generate: (devel_generate)
 generate-content  Create content.
 (genc)
 generate-menus    Create menus and menu items.
 (genm)
 generate-terms    Create terms in specified vocabulary.
 (gent)
 generate-users    Create users.
 (genu)
 generate-vocabs   Create vocabularies.
 (genv)

```

You can read in the Drush Command page:

> ***help***
>
> Options: --filter=\[category\] Restrict command list to those commands defined in the specified file. Omit value to choose from a list of names.

I create the onlyone.drush.inc file with the following code:

```
<?php
/**
 * @file
 * Drush commands related to OnlyOne.
 */

/**
* Implements hook_drush_command().
*/
function onlyone_drush_command() {
  $items['onlyone-list'] = array(
    'description' => dt("List the configured content types to have Only One node."),
    'aliases' => array('ol'),
    'examples' => array(
      'drush onlyone-list' => dt("List the configured content types to have Only One node."),
    ),
  );
  return $items;
}

/**
 * Callback for the onlyone-list command.
 */
function drush_onlyone_list() {
  $onlyone_content_types = variable_get('onlyone_node_types');

  if (count($onlyone_content_types)) {
    drush_print(dt("Content types configured to have only one node:"));
    drush_print(implode("\n", $onlyone_content_types));
  }
  else {
    drush_print(dt("There is not content types configured to have only one node."));
  }
}

```

I clean the cache with `drush cc drush` but when I use `drush help --filter=onlyone` I get this output:

```
 [error]  The specified command category onlyone does not exist.

```

So, how can I obtain the list of the commands defined in my module?

# Answer
Here is the explanation found in the `help` hook (sandwich\_drush\_help) of the example sandwich command (examples/sandwich.drush.inc):

```
// The 'title' meta item is used to name a group of
// commands in `drush help`.  If a title is not defined,
// the default is "All commands in ___", with the
// specific name of the commandfile (e.g. sandwich).
// Command files with less than four commands will
// be placed in the "Other commands" section, _unless_
// they define a title.  It is therefore preferable
// to not define a title unless the file defines a lot
// of commands.
case 'meta:sandwich:title':
  return dt("Sandwich commands");

```

This explanation is admittedly a little obtuse. The general idea is that Drush thinks that a commandfile that defines a 'meta:MODULENAME:title' help item is important / distinct enough to get its own section in Drush help; untitled commandfiles are all grouped into the "other" section, unless they have so many commands that they would tend to make the "other" section too long, in which case they are given their own section with an arbitrary title.

The number 4 is completely arbitrary.

The --filter feature was designed to show just part of the help index; it was not really considered to be a feature to show all of the Drush commands available for a given module. There is no other good way to do that, though; it might be an improvement to simply abolish the "other" section, and put all of the commands for each commandfile into its own section. If that was done, then --filter would behave as you expected it to.
> 3 votes

# Answer
I found the answer searching in the code of the drush project:

If the module have less than 4 commands you can't use the `drush --filter=MODULE_NAME` because your commands are classified as other:

See the function drush\_commands\_categorize(), and at line 1125 you can see this comment:

```
  // Post-process the categories that have no title.
  // Any that have fewer than 4 commands go into a section called "other".

```

I create 3 more commands and now the `drush --filter=onlyone` command works.
> 5 votes

---
Tags: drush
---


# Question
Title: $form_state->setErrorByName() for a form in a block doesn't work properly
I created a very simple module 'testform'. In this module, I generate a form and a block. (via the drush console)

The form contains a textfield ("housename") and a submit button.

In the form Class, I add a condition in the validate handler for display an error when the user submit the form without any data in the textfield.

### The form from the form page (no problem)

1. I load the form page (url path found in the testform.routing.yml)
2. I click to the submit button without enter any data in the housename textfield
3. The next page load, the empty housename field is red and **there is an error message "the housename field is empty"** =\> By this way, all is ok

### The form from the block (there is the problem)

1. I load a page where is displayed the form block
2. In the block, I click to the sumbit button without enter any data in the textfield
3. The next page load, the empty housename field is red and **there *isn't* any error message**

4. If I reload the page, the setError message appears

I don't understand why when the form is displayed in a block, the error message doesn't work properly.

This is the code I am using.

### The modules/custom/testform/src/Form/DefaultForm.php file

```
<?php

namespace Drupal\testform\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class DefaultForm.
 *
 * @package Drupal\testform\Form
 */
class DefaultForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'default_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['housename'] = [
      '#type' => 'textfield',
      '#title' => $this->t('housename'),
      '#maxlength' => 64,
      '#size' => 64,
    ];

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

    return $form;
  }

  /**
    * {@inheritdoc}
    */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $housename = $form_state->getValue('housename');
    if(empty($housename)){
      $form_state->setErrorByName("housename","The housename field is empty");
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
    ksm("Work...");

  }

}

```

### The modules/custom/testform/src/Plugin/Block/DefaultBlock.php file

```
<?php

namespace Drupal\testform\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Default block"),
 * )
 */
class DefaultBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\testform\Form\DefaultForm');

  }

}

```

# Answer
> 3 votes
This is a known bug. You can see the same problem with the core user login block upon submitting bad credentials. The comments in that issue note that it's a side effect of another issue which has a fix committed to the 8.2.x branch.

---
Tags: forms, 8, blocks
---


# Question
Title: How do you programmatically enable a payment method?
I have enabled the payment method module I want to use. I am using Authorize.net.

However, by default it is disabled in the Payment methods listing.

In my module, I want to enable the payment method module for use when my module is installed.

# Answer
I presume this is for Drupal Commerce? Payment methods are set and enabled by Rules. I would create a custom module that will make a condition for the Rule, based on a variable that is set elsewhere (as in a custom Admin UI for the site).
> 2 votes

# Answer
Just update the rules\_config entity.

```
$config = rules_config_load('name_of_your_rules_config');
$config->active = 1;
$config->save();

```

If you are not sure what the name of your rules config entity is run:

```
$configs = entity_load('rules_config');
foreach($configs as $config) {
  dpm($config, $config->name);
}

```

This will list all rule config entities that you have.
> 3 votes

---
Tags: commerce
---