# Question
Title: All links point to the old site after migration
I migrated a Drupal 7 site from 1 server to another. Let's call the old site URL http://oldsite.com and the new site url http://newsite.com. I have copied over the code base and the database. The site displays correctly on http://newsite.com, however all the links point to http://oldsite.com. The only way to access the links are to type the URL in the browser (e.g. http://newsite.com/admin).

I have read lot of forums and done the following:

1. Set the $base\_url in settings.php
2. Cleared cache in Config \> Development \> Performance
3. Cleared the cache table in DB
4. Ran update.php
5. Disabled clean urls

Nothing has worked. Someone suggested changing an entry in system table. Don't know which entry they were talking about.

Can anyone suggest the correct steps and perhaps an explanation of why I keep getting the redirects?
I have also referred to Moving a site, links/admin do not work.

# Answer
> 1 votes
For sites being localized, you have to edit every language:
`/admin/config/regional/language`
It's because there's a "domain" field that is left with the wrong URL in the database.
That solved my case of moving from *subdomain* **beta**.mysite.com to **www**.mysite.com

# Answer
> -1 votes
If you are using domain access, be sure to check the table PREFIX\_languages. I had the exact same problem and wasted 2 days before I found the problem. The old domain was hard coded in the PREFIX\_languages table and once I changed it everything worked perfectly.

---
Tags: 7, migrations, configuration
---


# Question
Title: How do I add role permissions to custom module
I have a custom module in Drupal 8 and I have created a role called editor. How do use .permissions.yml in my module to get it to display on the editor's role?

# Answer
> 2 votes
Create a file my\_module.permissions.yml and add

```
my permission:
  title: 'This is my custom permission'
  description: 'A custom permission for your.'

```

Then use your permission in your my\_module.routing.yml:

```
example.name:
  path: '/example/{name}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'my permission'

```

Now you can configure your custom permission on admin/people/permissions

---
Tags: users
---


# Question
Title: How to list all the user's "member for" via "Views"?
In Drupal 8, there is a "member for" in the profile page to show that how long time since this user be a member until now.

I would like to list all the user's "member for" via Views. However there is no such variable in the Views FIELDS.

I was thinking create a user field called "member since" and then every day get the "member for" value (which in the profile already) everyday, and display this "member since" field via Views. However:

1. I don't know how to get the value of existed "member for" variable in Drupal 8 for created user field "member since". (of course I can calculate it by myself, but I don't want to deal the timestamp, formation etc)
2. I don't know how to run this function to get the value of existed "member for" variable one time everyday.

Or is there a better way to do it (Note I need to use Views to display it)?

Thanks!

# Answer
This is quite easy to achieve. Simply add the user's `created` field to your view, then change the field formatter for this to `Time ago`.
> 2 votes

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


# Question
Title: Custom button for CKEditor not showing up in node creation page
I want to add a simple custom button to CKEditor in Drupal 8. So far I followed the Instructions here and here, and my custom button is showing up on the configuration page under *Configuration \> Content authoring \> Text formats and editors*, where I added it to the *Basic HTML* and *Full HTML* presets.

However, when I want to create a new article, the button is not being shown in the editor toolbar.

I can verify by JS console outputs that my plugin **is** being loaded by CKEditor, and the `init` function actually runs. The button just does not appear. I appreciate any pointers. I have seen this question, where somebody seems to have a similar problem, but I don't really understand the accepted answer as it seems to be specific to CKEditor templates. So my question is: why does my button show up in the configuration page, but not in the node creation page, although the corresponding JS is being run?

I have not implemented any hooks in my module.

**info.yml of my module**

```
name: Glossarion
type: module
description: >
  Some description. I'll think about it later.
core: 8.x
version: 0.1
package: CKEditor
dependencies:
  -ckeditor

```

**.php of my Drupal plugin**

```
class Glossarion extends PluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

public function getDependencies(Editor $editor) { return array(); }
public function getLibraries(Editor $editor) { return array(); }
public function isInternal() { return FALSE; }
public function getConfig(Editor $editor) { return array(); }
public function isEnabled(Editor $editor) { return TRUE; }

public function getFile() {
  return drupal_get_path('module', 'glossarion') . '/js/plugins/glossarion/plugin.js';
}

public function getButtons() {
  return [
    'glossarion' => [
      'label' => t('Insert a Word from Glossarion'),
      'image' => drupal_get_path('module', 'glossarion') . '/js/plugins/glossarion/icons/glossarion-editor-icon.png',
      'command' => 'insertTimestamp'
    ]
  ];
}
}

```

**.js of my CKEditor Plugin**

```
'use strict';

CKEDITOR.plugins.add('glossarion',{
  icons: 'glossarion-editor-icon', // %REMOVE_LINE_CORE%
  init : function( editor ) {
    console.log("Glossarion init is being called");
    editor.addCommand( 'insertTimestamp', {
        exec: function( editor ) {
            var now = new Date();
            editor.insertHtml( 'The current date and time is: <em>' + now.toString() + '</em>' );
        }
    });
    // do I have to add the button here again? Seems to have no effect
    editor.ui.addButton( 'Timestamp', {
        label: 'Insert Timestamp',
        command: 'insertTimestamp',
        toolbar: 'basicstyles,0'
    });
    console.debug(editor);
  }
});

```

# Answer
> 3 votes
See the documentation at https://www.drupal.org/developing/api/8/ckeditor.

You can find examples in Drupal 8 core, at:

* `\Drupal\ckeditor_test\Plugin\CKEditorPlugin\Llama`
* `\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaButton`
* `\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaContextual`
* `\Drupal\ckeditor_test\Plugin\CKEditorPlugin\LlamaContextualAndButton`

(This is the exact same answer as I gave at https://drupal.stackexchange.com/a/191869/7632.)

---

To answer specifically why the button is not showing: CKEditor's Advanced Content Filter (ACF).

Please add your button to CKEditor in the "Full HTML" text format. Check if it shows up then. Chances are it does.

Your plugin does not specify ACF metadata. ACF is what ensures CKEditor produces clean markup. In "Full HTML", there are no restrictions, and no guarantees of clean markup.

# Answer
> 2 votes
If your **button is not visible** while editing a node but it is visible in the configuration file, that means that the value you have on the **getButtons()** function doesn't match with the values from **plugin.js**. This got me back and forth for a while.

```
editor.ui.addButton( 'glossarion', {
    label: 'Insert Timestamp',
    command: 'insertTimestamp',
    toolbar: 'basicstyles,0'
});

```

Perhaps you should also define **id** in comment for you plugin before class

```
 /**
 * Defines the "Glossarion" plugin.
 *
 * @CKEditorPlugin(
 *   id = "glossarion",
 *   label = @Translation("Glossarion ")
 * )
 */
class Glossarion extends CKEditorPluginBase {

```

you use this **id** here

```
CKEDITOR.plugins.add('glossarion',{

```

---
Tags: 8, wysiwyg
---


# Question
Title: Block with entities referenced in a field from current node (of different type)
I got 2 different types of content (**Place** & **Event**). When an **Event** is created you can define **Place** (one or more) where this **Event** will happened (**Place** are referenced in a field in **Event**).

With View, I can display a block with the **Event** attached to the current **Place**. But I can't display in a block the **Place** of the current **Event** (on its page).

# Answer
You need to add relationship Entity Reference: Referenced Entity for field which is referencing to Place content type and you will see the Place field in fields.

Hope this will help.
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: Views Contextual Filter by Day and Night
I have a content type with a boolean field, using radio buttons for day and night.

I would like to create a view with a contextual filter, which shows "day content" between 8:00 am - 8:00 pm and "night content" between 8:00 pm and 8:00 am.

Which is the best way for creating the contextual filter or view?

Or if you'd have a better suggestion, I could change my content type and fields too.

# Answer
your approach is correct.

You can do one thing..Just create a view and contextual filter in view for radio field. use hook\_views\_pre\_view() hook to add arguments.

```
function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'myview' && $display_id == 'page_1') {
    $current_time = date('H'); //24hrs format
    if ($current_time >= 8 && $current_time <= 20) {
      $args[] = "value of day radio button";
    }
    else {
      $args[] = "value of night radio button";
    }
  }
}

```

Hope this will help
> 2 votes

# Answer
Interesting idea.

First off however, I think you should use a date(time) field instead of the boolean. You can then use the between operators for your filter. I haven't used the date field as a contextual filter though so I will double check that in a few.

The other option, if necessary, would be to do your check on `time()` in a `hook_views_pre_view` and change your `$view-args` to the corresponding boolean (make sure to change the right element of the array if you have multiple contextual filters).

I would only use the second option if the date contextual filter is not an option for you.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: How to set a default value for Simple hierarchical select?
I tried to implement `hook_form_alter` in order to pass default value to Simple hierarhical select views exposed filter.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $tid = get_tid_from_termalias (arg(1)); // here I get tid
  $form_state['input']['field_sity1_tid'] = (!empty($tid)) ? $tid : 'All';
  $form_state['field_sity1_tid']['#value'] = (!empty($tid)) ? $tid : 'All';
  $form['field_sity1_tid']['#default_value'] = (!empty($tid)) ? $tid : 'All';
  $form['field_sity1_tid']['#value'] = (!empty($tid)) ? $tid : 'All';
}

```

I see that shs.js creates 2 selects, one hidden and one shown. My code changes only the value in the hidden select while second select always remains 'All'. How to change the visible select's default value?

# Answer
> 0 votes
Hmm, That's a challenge to set default with Simple hierarchical select using form alter.

As they are handling options to taxonomy in js.

But we have another way to set default value for the field. Passing in URL. Like : http://localhost/drupal/demo-view?field\_test\_tid=1

Hope this will help. Just trying other way.

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


# Question
Title: why system/connect web services return nothing in drupal 7?
I have Drupal 7 with web services activated, but the `system/connect` resource returns a 404 Controller Not Found response. I was trying the user resource, and it works correctly. I tried using the following URL in my browser window, which does a HTTP GET:

```
https://localhost/drupal/x_login/system/connect

```

where x\_login is the endpoint.

# Answer
> 0 votes
The services module allows a resource to define the following "things":

1. Operations: provide 5 different verbs
    * retrieve: Make a GET request based on the resource name and an identifier i.e. `GET /endpoint/user/ID`
    * index: Make a GET request based on the resource name to get a list of resources i.e. `GET /endpoint/user`
    * update: Make a PUT request to a resource name and an identifier i.e. `PUT /endpoint/user/ID`
    * create: Make an idempotent POST request to a resource name to create a new resource i.e. `POST /endpoint/user`
    * delete: Make a DELETE request to remove a resource by identifier i.e. `DELETE /endpoint/user/ID`
2. Actions: Allows to make a custom POST request to a resource. This is used for login, logout, etc... These are *never* GET.
3. Targeted Actions: Allows to make a custom POST request to a resource + identifier. This is used for making hierarchical resources.
4. Relationships: Allows to make a custom GET request to a resource + identifier. This is used for make hierarchical requests for things like group membership.

The `system/connect` resource is defined as an "action" above. This means that you must make a POST request instead of a GET request. And it may require a CSRF Token.

```
POST /login_x/system/connect HTTP/1.1
Content-type: application/json
Accept: application/json
X-CSRF-Token: 'TOKEN'

```

---
Tags: services, 8
---


# Question
Title: determine custom templates in custom module hook_preprocess_page function
I'd like to create a module that use a set of custom templates depending on http status code

Very well inspired by Custom template for 404 error pages

Here is where i am so far

```
function my_module_preprocess_page(&$vars) {
  $header = drupal_get_http_header('status');
    if ($header == '404 Not Found') {
      //this
      $vars['template_files'][] = 'page__404';
      //or that
      $vars['theme_hook_suggestions'][] = 'page__404';
    }
}

```

in my module templates folder , i have created a

```
page--404.tpl.php

```

this template is not overtaken !?

EDIT : i have also tried what's in there

```
function my_module_preprocess_page(&$vars) {
$header = drupal_get_http_header('status');
if ($header == '404 Not Found') {
  $vars['theme_hook_suggestions'][] = 'page__404';
}
}

function my_module_theme() {
  return array(
    'page__404' => array(
      'template' => 'page__404',
      'variables' => array('xxx' => null),
      'path' => drupal_get_path('module', 'my_module')
    ),
  );
}

```

# Answer
```
function my_module_preprocess_page(&$vars) {
$header = drupal_get_http_header('status');
if ($header == '404 Not Found') {
  $vars['theme_hook_suggestions'][] = 'page__404';
}
}

function my_module_theme() {
  return array(
    'page__404' => array(
      'template' => 'page__404',
      'variables' => array('xxx' => null),
      'path' => drupal_get_path('module', 'my_module')
    ),
  );
}

```

thanks to sareed, drush vset theme\_debug 1 allowed me to see :

```
<!-- THEME DEBUG -->
<!-- CALL: theme('page') -->
<!-- FILE NAME SUGGESTIONS:
   * page--404.tpl.php
   * page--psnmssss.tpl.php
   * page.tpl.php
-->
<!-- BEGIN OUTPUT from 'my_module/page__404.tpl.php' -->

<!-- END OUTPUT from 'my_module/page__404.tpl.php' -->

```

so i changed page--404 to page\__404 and it worked

how could i restrict the template suggestion only for the content region of the page ?
> 0 votes

---
Tags: theming
---


# Question
Title: How to set page variable from custom module
In Drupal 8:

I have custom module code that declares its own theme can twig template. How do I make module variables available to my Drupal theme's page.html.twig?

I have tried various preprocess\_page\* functions; however, those functions don't see the variables the module is passing to it's own themed twig templates.

Can the module's controller inject something into the page variables?

Can a Drupal theme's preprocess functions access some variables flowing from a custom module to the module's twig templates?

The controller file:

```
class PromtController extends ControllerBase
{
    public function program($id)
    {
        $program = PromtService::program((int)$id);

        return [
            '#theme'   => 'promt_program',
            '#program' => $program,
            '#title'   => $program['title']
        ];
    }
}

```

The module code:

```
function promt_theme()
{
    return [
        'promt_program' => [
            'template' => 'promt_program',
            'variables' => [
                'program' => null
            ]
        ]
    ];
}

```

# Answer
> 1 votes
As far as I can tell, this should be handled in the custom theme, not in the custom module. This is because the module really has no idea how a custom theme wants to render stuff.

In any case, in the custom theme, the only way I can figure out how to make the data available is to register a hook\_preprocess() function in the theme, check the hook that's called, and declare a static variable that sticks around until it can be injected later on.

The custom module's "promt\_program" hook will be called earlier than the theme's "page" hook. I'm pretty sure that will always be true. So, we grab the location\_id and then inject it later on.

This preprocess function will get called many, many times, so it seems important to make it thin.

```
function cob_preprocess(&$vars, $hook)
{
    static $location_id = null;

    switch ($hook) {
        case 'promt_program':
            if (!empty($vars['program']['location_id'])) { $location_id = $vars['program']['location_id']; }
        break;

        case 'page':
            if ($location_id) {
                $query = \Drupal::entityQuery('node')
                    ->condition('status', 1)
                    ->condition('type', 'location')
                    ->condition('field_promt_id', $location_id);
                $nids  = $query->execute();
                if ($nids) {
                    $vars['node'] = \Drupal::entityTypeManager()->getStorage('node')->load(current($nids));
                }
            }
        break;
    }
}

```

---
Tags: theming, 8
---


title: how to debug a controller not being run

text:
# Question
Title: how to debug a controller not being run
my code below results in a page not found when I browse to the path. How can I debug what is going wrong? I dont see any errors and I have cleared the cache.

```
mymodule.content:
  path: '/admin/viewfiles'
  defaults:
    _controller: '\Drupal\mymodule\Controller\FileView::content'
    _title: 'File Operations Module Description'
  requirements:
    _permission: 'access administration pages'

```

# Answer
> 1 votes
thanks i had a misspelling in the router name. thank you all

---
Tags: 8, routes, page-controller
---


# Question
Title: Why would some features still show Overridden after a revert all --force?
Why would some features still show as "Overridden" even after running a full features revert with the force switch? Below are the commands I am running, for the sake of clarity.

```
drush fr-all --force -y
drush fl

```

# Answer
A feature or features may not revert for the following reasons as cited by some developers in the issue queue #744450:

* If your feature includes a view views cache could cause it to remain changed; especially, the migrate module (#1)
* Other features can cause your feature to be overridden (#10)
* Adding a line in your info file (#24)
* There are hooks overriding or altering your view (#36)
* A view won't revert. So revert the view using the UI (#62)
* When Views UI is disabled, it may cause your view to be overriden (#64)
* A feature is missing an include file (#82)
> 16 votes

# Answer
One way of that happening, that I've tried myself, is to have two seperatere features define content types that use the same CCK field. Doing that it's possible to have different settings for the same field for. That way one them will always be overridden.
> 7 votes

# Answer
There is more documentation related (https://www.drupal.org/node/986932), including a description of a *silver bullet* solution (Disable and re-enable. be careful and test first).
> 2 votes

# Answer
Here's a known issue, http://drupal.org/node/860974

I am battling that one myself.

It does depend on what you are trying to override. The output of drush features-diff could be helpful for others to give you a more precise reason.
> 1 votes

# Answer
This may seem stupid, but make sure you have all the files for the feature. One of my files didn't make it to git so it kept showing overridden.
> 1 votes

---
Tags: drush, features
---


# Question
Title: How do I get when an entity was last updated?
I found from the documentation that to get the created date I can use the `getCreatedTime()` method.

How do I get when an entity was last updated?

# Answer
For an entity class that implements `EntityChangedInterface`, `EntityChangedInterface::getChangedTime()` returns the the timestamp of the last entity change for the current translation.
> 5 votes

---
Tags: 8, entities
---


# Question
Title: How do I get the path for the private filesystem?
I just trying to get the real path of my private filesystem but I just obtain an empty string if I use:

```
\Drupal::service('file_system')->realpath("private://");

```

There one user in Get the public path directory that says that this is the correct way, but this is not working for me.

My private filesystem is configured as:

```
$settings['file_private_path'] = '/User/adriancid/private-drupal-folder';

```

If I use `file_default_scheme()` I see:

> private

# Answer
The problem is solved.

I had a problem with the path, so the correct path is

```
$settings['file_private_path'] = '/Users/adriancid/private-drupal-folder';

```

And I give permissions to write in the folder to the webserver.
> 5 votes

---
Tags: 8, files
---


# Question
Title: How to add css class to specific rows base on fields in order commerce view page
I would like to add a class based on the field value I used in commerce order view. I have tried a solution from here I have installed "devel" module and already enabled it. However, I cannot find the dpm() result from my admin order page. I don't know if it is because of my code or dpm() function.

Here is my code and put them in my theme's template.php file::

```
function MYTHEME_preprocess_views_view_list(&$vars) {
    if ($vars['view']->name == 'commerce_backoffice_orders' && $vars['view']->current_display == "Admin Page") {
        dpm($vars); //uncomment to see variables
        foreach($vars['view']->result as $key => $value){
             $timestamp = $value->node_created;
             if ($timestamp) { // add whatever conditional logic you need here
             $vars['classes_array'][$key] .= ' hello'; // note the space in front of class
             }
         }
     }
}

```

Here is a screenshot:

Does anyone have any idea about my issue? Thank you for anyone's help~~~~

# Answer
> 0 votes
I found the solution by using JS injector Module. If someone wants to get any idea from my question, you can check it from here.

# Answer
> 0 votes
Try this hook instead: MYTHEME\_preprocess\_views\_view\_table. Your view uses the Megarow table format. The hook you used is called for the list format.

---
Tags: 7, views, commerce
---


# Question
Title: How to set node default language (or avoid language neutral) without Content translation module
I both have nodes that need to be translated (using Entity Translation), and nodes that need to have a single language (which we are discussing here).

Because of some incompatibility between Entity and Content translation, I cannot enable "Content translation" and "Multilingual content".

Also, even if it was possible, all I really want is not linking translations of different nodes and the other features that come with Content translation.

I just want to let users select the node language when creating/editing a node without having the "Language neutral" option, or select language by default (based on current page language).

# Answer
You can enable i18n\_node module that is included in i18n module. Then:

1. Go to edit the content type (admin/structure/types/manage/page).
2. Open the 'Multilingual settings' tab.
3. Check the 'Require language' checkbox.

Done.
> 3 votes

# Answer
Seems like there might be 3 different paths to solve this problem;

1. The simplest (and least recommended way) is probably JS hack-ery that hides the specific option in the drop-down. There are MANY drawbacks to this option as well as a few different ways to get it done. I wouldn't suggest any of them under normal circumstances.
2. Unset the "Language neutral" option on the form using a custom module hook form alter. This could lead to unknown problems and incompatibility with contrib modules in the future.
3. Select the language by default, based on current page language, again using a custom module. This would require some error handling as well and seems most in line with what you really want. It requires the most development but with some effort is definitely the best option.

I can't point to all of the right resources, since you have not posted the version of Drupal you're using. However, key among the things you'll need is the Drupal API documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook\_form\_alter/8.3.x

hth
> 0 votes

---
Tags: 7, nodes, i18n-l10n
---


# Question
Title: All Blocks in One Theme Automatically Disabled
On a Drupal 7 site that I help maintain, the blocks in one of the themes were all disabled automatically. I manually added all of the blocks back of course, but can't promise this won't happen again. To try to find out what happened, I queried the block table and discovered that the tracking columns are not provided (e.g. created, changed, uid). So then I went on to see if MySQL could tell me the last time that these rows were modified, but there is no such native function.

Has anyone seen this problem?

# Answer
I haven't run into this specific problem, but I would advise getting as much of this as you can into Features - that way you can easily revert it all back, should this problem recur, and you wouldn't have to do it manually.
> 1 votes

# Answer
I have seen this happen many times during migrations in D7. Most commonly, when a region is not defined in a new or alternate theme... then the block gets disabled. There are also contrib (and definitely custom) modules that can have the same impact. Last but not least, install profile use - and subsequent misuse - can readily cause this behavior. Especially when there is a theme in the profile. In most cases I've seen, the issue is a result of many hands over time maintaining code in different (and sometimes conflicting) ways.

On the second question, D8 has significant changes and vastly improved blocks. In fact, new in Drupal 8 are the Block Plugin API, which is a stand-alone reusable API and the Block Entity API which is used for block placement and visibility control.

If you're curious what revision fields are present in D8 (and this might have changed in more recent versions) 2 of the relevant tables are:

```
mysql> describe block_content;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| revision_id | int(10) unsigned | YES  | UNI | NULL    |                |
| type        | varchar(32)      | NO   | MUL | NULL    |                |
| uuid        | varchar(128)     | NO   | UNI | NULL    |                |
| langcode    | varchar(12)      | NO   |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

```

and:

```
mysql> describe block_content_revision;
+--------------+------------------+------+-----+---------+----------------+
| Field        | Type             | Null | Key | Default | Extra          |
+--------------+------------------+------+-----+---------+----------------+
| id           | int(10) unsigned | NO   | MUL | NULL    |                |
| revision_id  | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| langcode     | varchar(12)      | NO   |     | NULL    |                |
| revision_log | longtext         | YES  |     | NULL    |                |
+--------------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

```

You will note that even though entities are now being used and therefore revision goodness is present... the fields you were looking for (created, changed) are not available in D8 for these tables.
> 0 votes

---
Tags: database, blocks
---


# Question
Title: Taxonomy hierarchy via separate dropdowns
I am building a view that requires users to select from a drop down menu containing a list of taxonomy terms, which will then filter the view results based on those terms. So far, so good.

I want to make the dropdown menu with only all of parent taxonomy terms of a specific vocabulary so that when one of the parent terms is selected, a second drop down menu shows all of the children of the selected term.

How can I accomplish this, preferably without an extra module? I will consider any means to accomplish this goal.

More specifically, I am building a view based on states and counties, and want users to first select a state and then select from the list of counties for that state.

# Answer
You probably won't be able to do that without some custom code.

An existing module for the purpose is Simple hierarchical select:

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy. The widget is available in node forms and as Views exposed filter.

https://www.drupal.org/project/shs

There is also the more full featured module Hierarchical select
> 1 votes

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


# Question
Title: Change the submit function for user login
I'm building a site for a client that already has a website through another CMS that they do not wish to move away from despite my best efforts to convince them otherwise.

This CMS does offer an api that allows for implementation for single sign on so I'm trying to set that up.

I've gotten as far as

```
    function mymodule_form_alter(&$form, &$form_state, $form_id)
    {
        if ($form_id == 'user_login') {
            $form['#submit'] = ['mymodule_login'];
        }
    }

    function mymodule_login($form, &$form_state)
    {
        exit('SUCCESS');
    }

```

But the success message is never shown.

Oh, I tried searching to see if there was already a module that implemented this but no such luck.

# Answer
> 0 votes
The issue was that I was inputting an incorrect username and password and it was not reaching any of the submit hooks because it was failing on the validate hooks. It seems that my logic needs to go there if it wants to supercede the default validation logic.

# Answer
> 0 votes
Is you module named mymodule? The prefix of the hooks has to be the same as the machine readable name of your module. After checking that, try clearing the cache. After that, is should work because the code looks all right.

# Answer
> 0 votes
Have a look at `user_external_login_register`

> Helper function for authentication modules. Either logs in or registers the current user, based on username. Either way, the global $user object is populated and login tasks are performed.

There is a good comment there about how to implement that type of external login flow. https://api.drupal.org/comment/13434#comment-13434

---
Tags: users
---


# Question
Title: How to programmatically link commerce products to taxonomy terms
I'm trying to link existing commerce products to an existing taxonomy term in Drupal 7:

```
$products = commerce_product_load_multiple($pids);
foreach($products as $product){
    $product->field_some_option[LANGUAGE_NONE][0]=$tid; //the taxonomy term id
    commerce_product_save($product);
}

```

This doesn't work.

Typically when I assign the taxonomy term to the product via the admin pages it adds an entry to a database table called *field\_data\_field\_some\_option*, which contains the product and term id. When I use the above code, a new entry is again made in the table, but the term id is set as NULL.

Note that I'm trying to link commerce products, not product displays, which as far as I understand means I can't use the typical node-taxonomy linking approach.

Anyone know how to get this working, short of bypassing Drupal APIs and editing the database directly?

# Answer
> 0 votes
You're close, but need to tweak setting the field value to:

```
$product->field_some_option[LANGUAGE_NONE][0]['tid'] = $tid;

```

For the taxonomy term reference field uses the 'tid' key there.

You could also do it with a metadata wrapper like:

```
$wrapper = entity_metadata_wrapper('commerce_product', $product);
// Append to existing field value
$values = $wrapper->field_some_option->raw();
$values[] = $tid;
// Set field values
$wrapper->field_some_option->set($values);
$wrapper->save();

```

---
Tags: 7, commerce
---


# Question
Title: A post var error upon webform submitting programmatically
I need to update a webform submission using function drupal\_form\_submit.

And upon updating an error is displayed.

> This form could not be submitted because $\_POST was truncated to 5 input vars. PHP max\_input\_vars is 10000 and needs to be increased

I tried to increase max\_input\_vars value even up to billion, but it doesn't helps.

The webform is very big and complicated.

Here I can't use function webform\_submission\_update, because some form alter and form validation functions must be executed upon the webform submission updated.

# Answer
According to this post:

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

If it's a custom webform template, you may need to add, at the end of the form:

```
<?php print drupal_render_children($form); ?>

```

See also this related issue here: https://www.drupal.org/node/2417757
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: Extending the Year range in Popup Calendar
I am trying to extend a year range of a popup calendar in drupal 7 but have been unable to see where I can do this.

After doing more research, I discovered that I can change it through the 'More settings & values' option in the field settings which I have seen in other people's screen shots except that I don't seem to have this option at all when I go into my field settings.

I am using the date field and having it display as a popup calendar but cant find the year range setting anywhere - is there something else I need to enable to find this or has anybody else had a similar issue?

I'd be happy to even change some code in one of the files, but I havent been able to find the right one.

Many Thanks

# Answer
* Step 1 : Edit the file **date\_year\_range.js** located in this path : sites\all\modules\date\date\_api\
* Step 2 : Locate this line : Line 67 start = Math.min(this.getOriginal('int'), -**n**) **n** is the number you specified in your Drupal
* Step 3 : Replace **n** with the value you want, for example for the field date of birth i want 60 years besfore today
* Step 4 : Go back to your web site, edit the content type, then manage fields and change more settings and values of your date field.
> 1 votes

# Answer
Ensure that the widget type is "Select list" - then the range and increment settings appear when editing the field.
> 0 votes

---
Tags: datetime
---


title: View bulk errors

text:
# Question
Title: View bulk errors
I create a rules component with 2 parameters to grant userpoints to user. I create a view and add bulk operation then I add my view on dashboard. All work great, but after bulk operation is complete I get errors:

> ```
> Notice: Undefined index: operation in views_bulk_operations_form_submit() (line 712 of C:\Sites\a\sites\all\modules\views_bulk_operations\views_bulk_operations.module).
> Notice: Undefined index: operation in views_bulk_operations_form_submit() (line 713 of C:\Sites\a\sites\all\modules\views_bulk_operations\views_bulk_operations.module).
> Notice: Undefined index: list callback in views_bulk_operations_get_operation() (line 229 of C:\Sites\a\sites\all\modules\views_bulk_operations\views_bulk_operations.module).
>
> ```

I tried use dev version of bulk module, but it also get errors. What should I do for fix it?

# Answer
> 0 votes
Ok, I found solution.

I created a panel and add my view block with bulk on it instead dashboard. and all work fine, without error. I hope somebody will find it useful.

---
Tags: 7, views
---


# Question
Title: Is there any template debugging technique similar to Twig debugging?
David Rothstein pointed out in the comments that as of Drupal 7.33, this functionality has been back-ported to Drupal 7.

Is there any template debugging technique similar to Twig debugging?

# Answer
> 3 votes
As reported in Working with template suggestions, yes.

> As of Drupal 7.33, Drupal core has a theme debug mode that can be enabled and disabled via the theme\_debug variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments). To enable it, add this line to your settings.php:
>
> ```
> $conf['theme_debug'] = TRUE;
>
> ```

As said in that page, you can use Drush to enable/disable it, respectively with `drush vset theme_debug 1` and `drush vset theme_debug 0`.

After you set *theme\_debug* to `TRUE`, the source of the page will appear as follows.

```
<!-- THEME DEBUG -->
<!-- CALL: theme('page') -->
<!-- FILE NAME SUGGESTIONS:
   * page--front.tpl.php
   * page--node.tpl.php
   x page.tpl.php
-->
<!-- BEGIN OUTPUT from 'modules/system/page.tpl.php' -->

<!-- END OUTPUT from 'modules/system/page.tpl.php' -->

```

# Answer
> 1 votes
To enable debug mode

## option #1. settings.php

add the following line:

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

## option #2. drush

**enable**

`drush vset theme_debug 1`

**disable**

`drush vset theme_debug 0`

Source

---
Tags: 7, debugging
---


# Question
Title: Restrict Menu options when building Nodes
Drupal 7, when creating a basic page I want the users to be able to add a menu item as a sub item only under local menu items, not under items that link off site. How can I restrict the list of menu Parent item to only ones that point to node/# and not display any that are absolute urls?

# Answer
What I ended up doing was using TEMPLATE\_form\_node\_alter() and creating my own duplicated versions of menu\_parent\_options(), \_menu\_get\_options() and \_menu\_parents\_recurse() so I could call them instead of the default drupal functions to build my menu. And in \_menu\_parents\_recurse() you can access the link information like link\_path, and just set the menu links I wanted to exclude.

```
function _my_menu_parents_recurse($tree, $menu_name, $indent, &$options, $exclude, $depth_limit) {
  foreach ($tree as $data) {
    if ($data['link']['depth'] > $depth_limit) {
      // Don't iterate through any links on this level.
      break;
    }
    // Exclude menus that are absolute/external
    if (stripos($data['link']['link_path'], 'http') !== false) {
        $data['link']['mlid'] = $exclude;
    }
    if ($data['link']['mlid'] != $exclude && $data['link']['hidden'] >= 0) {
      $title = $indent . ' ' . truncate_utf8($data['link']['title'], 30, TRUE, FALSE);
      if ($data['link']['hidden']) {
        $title .= ' (' . t('disabled') . ')';
      }
      $options[$menu_name . ':' . $data['link']['mlid']] = $title;
      if ($data['below']) {
        _my_menu_parents_recurse($data['below'], $menu_name, $indent . '--', $options, $exclude, $depth_limit);
      }
    }
  }
}

```

I was hoping for a more "correct" method (hook\_preprocess\_link maybe, but it doesn't exist in D7, only 6 and 8) but this one works.
> 0 votes

---
Tags: navigation
---


# Question
Title: Remember View results on a browser back button click
I have a view with some exposed filters that show some links. When I select a filter option, an ajax search is done and it shows the results. I click in one link and then I click in the browswer back button to go back to the view page.

Now, all results are shown and not the filter option ones.

How can I get that the view remembers the ajax search?

# Answer
> 3 votes
The answer to this question should include a "non-Drupal" part since what happens when you click the "Back" button is browser-related.

---

## What happens on the browser

I'm not an expert on the subject, but basically all browsers add the last request that you did in a "history cache" and pressing the "Back" and "Forward" buttons moves you backward or forward in this "cache".

In general, AJAX requests are not included in this cache but this is browser specific (I think that I have read somewhere that Safari in some cases does store AJAX requests). You can find various resources on how this works for different browsers if you look it up on google (keywords could be: "back button ajax calls", along with the name of the browser that you are looking for).

---

## Views' "Remember last selection" setting

For your specific question there are 2 things that you should notice:

1. Views **do allow you** to store the last selection by the user in the Exposed Filters' settings. The setting's name is: "**Remember the last selection**". This setting also allows you to limit the roles for which the last selection will be remembered.
2. **The browser does not** really **care** what Views do and, at least in the case of Chrome (probably other browsers do the same too), returns its cached version of the page (aka minus ajax calls).

You can test the above-mentioned assertion by setting the last selection option, hitting the back button (you will see the browser-cached version of the page) and then hitting the refresh button (browser will request the page again and views will kick-in and enforce the application of the last used filters).

---

## Solution

The google search "back button ajax calls" could give you a lot of relevant results but if you want to test the famous Drupal notion: "There is a module for that", there actually is and its name is "Views AJAX History". It depends on the history.js javascript library and the Libraries API module.

---

## Proof of concept

I have quickly created a dev site that I can use for my answers here and added 50 nodes with devel generate. You can see a sample view here that has AJAX enabled. After you have filtered the view using the "Body contains" exposed filter with a sample string like "oppeto" you will instantly see what Views AJAX History does: the call is being made through AJAX but the URL on your browser changes to include the exposed filters' values and is stored in your browser's history cache.

Now, when you click on a node link and then hit the "Back" browser button, you get returned to the correct, filtered version of the view (tested it on Chrome but you can test it on any browser that you want to make sure that it works as expected).

---

## Important Warnings

I have used this module on a couple of sites that I have built and the thing that bothered me the most is the fact that it has a known, unsolved conflict with the core Overlay module. It was not a very big deal for me since I could afford to disable Overlay at these specific cases but you should definitely consider this if you rely heavily on Overlay. For example, if you rely on Overlay Paths to show colorbox-like popups, you will find yourself in a world of hurt.

I am considering using Views AJAX History on one of my core projects but in order to do this, I will have to take a stab at the issue that I mentioned before. In any case, you can monitor the progress of the specific issue or even try to create a patch yourself.

# Answer
> 0 votes
It seems to work if your view display is a *page*, and the exposed filters are displayed through a block (configure the *Exposed form* of that page view display to do so). (I'm using BEF, but I guess that's not related.)

---
Tags: 7, views, ajax, search
---


title: Increase Placeholder Length

text:
# Question
Title: Increase Placeholder Length
I have a `webform` that has a `textarea` `input`. I am trying to update the `placeholder` text. It seems to have a limit of `128 chars`. Is it possible to update this to allow for a longer placeholder?

# Answer
> 0 votes
I created a ticket for this issue in the Webform module's issue queue and fixed the problem.

The best solution was to convert the placeholder input from a text field to a textarea so that you can now enter multiple lines of text as the textarea's placeholder.

---
Tags: webforms, input-formats
---


# Question
Title: How to show the webform submission page as pop up?
I have created the webform with two fields. When I submit the webform, its redirecting to the submission page.

Now, I want to display the webform submission page as pop up.

Thank you message and the "Back to form" should display in the pop up.

I have tried up with the NG lightbox to display the message. But its redirecting to the page with the pop up function.

How to achieve this thing, Please guide me.

# Answer
> 0 votes
It is very difficult (but not impossible) to target a lightbox/modal when submitting a form because the posted database has to be sent to the server.

I recommend following the below ticket on Drupal.org which could help you solve your problem using Ajax.

Allow Webforms to be submitted using AJAX

---
Tags: 8, webforms, javascript
---


title: Get Views field value in Twig template

text:
# Question
Title: Get Views field value in Twig template
I'm trying to get the value of a field and use it as a class for a wrapper of another field within a Views display. So essentially what I need is to be able to get a string representation of the first field. The field already is a text field but when I try getting the content it doesn't just give me a string, which is what I need to be able to use is as a class for my second field.

I've tried using `{{ fields.[field_name].content }}` but that renders the twig template recommendation along with the data. I tried using the `getValue()` function, but that doesn't return anything. I tried passing the data through the `raw` twig filter but that doesn't return anything. I tried rendering the array using dpm and kint but they both give me way too much information and I can't narrow it down to what array item or object I need to use. I'm new to Drupal so maybe I'm not using Devel and Kint correctly to find what I'm looking for.

Is there a function I have to use to get the content data as a string or just raw, or is there some other way I can accomplish this?

I am using Drupal 8.1.

# Answer
> 3 votes
`field.content` is the rendered field. And in views that means it is no longer a render array, but the finally rendered markup. So this is very problematic to use it as a class name, not only because of twig debug.

Better use the row data, where you find the entity object with the field data from the database. Use clean\_class to escape it for using it as a class name:

```
{{ row._entity.field_myfield.value|clean_class }}

```

# Answer
> 0 votes
> I've tried using `{{ fields.[field_name].content }}` but that renders the twig template recommendation along with the data.

That is because you have twig debug turned on. If you turn off twig debug the recommendation will go away.

# Answer
> 0 votes
{{ fields.\[field\_name\].content|striptags|trim }}
this helped me printing path and image url fields

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


title: Removing all validation on submit

text:
# Question
Title: Removing all validation on submit
I have a multistep form with two submit handlers (save/submit), when "Save" is clicked I want to remove any validation applied to the node and have it's contents saved.

In my custom validation hook I am checking both the triggering\_element and clicked\_button for the correct button, I'm then removing limit\_validation\_errors however this doesn't work. According to the api documentation it should though.

```
function test_workflow_form_validate($form, &$form_state) {
  if ($form['#form_id'] != 'test_application_assessment_form') {
    if ($form_state['triggering_element']['#value'] == 'Save') {
      $form_state['triggering_element']['#limit_validation_errors'] = array();
      $form_state['clicked_button']['#limit_validation_errors'] = array();

      $form_state['buttons'][1]['#limit_validation_errors'] = array();
      // Remove validation.
    }
    else {
      // Add in default validation.
      //$node = (object) $form_state['values'];
      //node_validate($node, $form, $form_state);
      //entity_form_field_validate('node', $form, $form_state);
    }
  }
}

```

I've removed the default node validation so my custom one is the only one present. Is there something else I'm missing?

# Answer
Your `'#limit_validation_errors'` may be set when the form gets built, not when it's processed.

Hence in your custom `*_form()` function or a `hook_form_alter()`; not in `*_validation()` or `*_submit()`.
> 2 votes

# Answer
Use `#limit_validation_errors` property. You use it to set:

> Values: array indicating sections of the $form\_state\['values'\] which should be validated.

So for a button that's not supposed to trigger any validation, set it to empty `array()`.

Note that this does not prevent validation hooks to be called. They will be called and you cannot do a thing about it. It just tells them to not set errors, but they are able to ignore it, and they will invoke side effects.

Also, setting it when there is already `$form_state['triggering_element']` set is too late. It means that user has clicked a button that is supposed to validate everything, as at the moment of clicking there was no `#limit_validation_errors` set. You need to apply it before user clicks.
> 1 votes

# Answer
For node edit form, to remove validation on **delete** submit button just need to write the below code in your custom module for **article** content type node edit form.

```
function module_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    if (!empty($form['nid']['#value'])) {
      // The nid is required for the delete confirmation form.
      $form['actions']['delete']['#limit_validation_errors'] = array(array('nid'));
    }
  }
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Moving site from one environment to another
I have a Drupal 8 site installed on a staging server. When moving on the production server, I do a `git pull`, import the database and the site is there and working. I do the same after some configuration is changed,I do a `git pull` and the usual `drush cim`, but I get:

> Cannot change the install profile from to standard once Drupal is installed.

How do I get around this?

# Answer
Check your settings.local.php (or settings.php if you don't have one) for 'install\_profile' and make sure this is set and matches your staging environment:

https://github.com/drupal/drupal/blob/2e8b29651cfb08309098c239ce9d03e724d747b3/sites/default/default.settings.php#L279

If that doesn't work you can take a look at https://www.drupal.org/node/2870028 as @jaypan said
> 1 votes

---
Tags: migrations
---


# Question
Title: How to hide specific term/field value on the node?
Is there a way to hide a specific taxonomy terms (specific field values) on the node? (not hiding field/vocabulary altogether, just some values).

For instance, there is vocabulary "Location" with a stucture like:

* Europe
    + England
    + - London
    + France
    + - Paris

On the **node** view I need to hide terms "Europe", "England" and "France" and display "London" and "Paris" only.

# Answer
> 0 votes
Each term has a level. So if you want to show only the terms from level 2 (London, Paris) you could loop over your terms, check the level and hide if its not 2. If you need to have individual rules for hide / show, then you could add a field to the term where you can save a value to show or hide and use this in your loop.

# Answer
> 0 votes
Below is the code I have tried in D7. I am doing it while node (Node No 1/Node No 2) is being created or, edited. So, changes will get reflected in node view as well. (There can be other approaches like using 'Hierarchical Select'). Here is the code :

```

/**
 * Implements hook_node_validate()
 * @param $node
 * @param $form
 * @param $form_state
 * @return unknown_type
 */

function common_operations_node_validate($node, $form, &$form_state) {
  if ($node->type == 'node_no') { // If node is of type 'node_no'
    if (isset($node->field_region_and_state[$node->language])) {
      if (count($node->field_region_and_state[$node->language]) > 1) { // Multiple terms are associated
        foreach ($node->field_region_and_state[$node->language] as $key => $val) {
          $vid = 0; $children = array(); // Variable Declaration & Initialization
          // Helper function call to get 'VID' for a 'TID'
          $vid = common_operations_get_term_vid($val['tid']);
          // Get all children for a 'TID'
          $children = taxonomy_get_children($val['tid'], $vid);

          if (count($children)) { // Restricting user to select only last level term in the hierarchy
            form_set_error('field_region_and_state', 'Some Message.');
          }
        }
      }
      else { // Only a single term is associated
        $vid = 0; $children = array(); // Variable Declaration & Initialization

        // Helper function call to get 'VID' for a 'TID'
        $vid = common_operations_get_term_vid($node->field_region_and_state[$node->language][0]['tid']);
        // Get all children for a 'TID'
        $children = taxonomy_get_children($node->field_region_and_state[$node->language][0]['tid'], $vid);

        if (count($children)) { // Restricting user to select only last level term in the hierarchy
          form_set_error('field_region_and_state', 'Some Message.');
        }
      }
    }
  }
}

/**
 * Helper function to get 'VID' for a 'TID'
 * @param $tid
 * @return unknown_type
 */

function common_operations_get_term_vid($tid) {
  $vid = 0; // Variable Declaration & Initialization

  $query = db_select ('taxonomy_term_data', 'ttd' );
  $query->fields ('ttd', array ('vid'));
  $query->condition ('ttd.tid', $tid, '=');
  $vid = $query->execute ()->fetchField ();

  return $vid;
}

```

1) 'common\_operations' is name of module

2) 'node\_no' is type of node

3) Structure -

```

   Europe
     England
          London
            Node No 1
   France
     Paris
            Node No 2

Here, 'Node No 1' is a node of type 'node_no' associated with immediate parent in the hierarchy 'London'
      'Node No 2' is a node of type 'node_no' associated with immediate parent in the hierarchy 'Paris'

```

4) field\_region\_and\_state is the 'Term Reference' field in content of type 'node\_no'

So, when you try to create/edit the node you can associate the node only with the last level of the hierarchy.

Hope it helps.

# Answer
> 0 votes
If some the terms are not displayed on the site at all you want to think of it in a wider scope. One solution would be to answer Taxonomy Permissions disallow authenticated users from viewing it.

---
Tags: entities, taxonomy-terms, nodes
---


# Question
Title: Where can I find where this content is being loaded from?
Helping out a friend with a Drupal based site. On one page, he has a series of images with a lightbox displaying info once clicked.

This however doesn't function, and instead shows as an image title.

I was just wondering where I'd find the file with the descriptions?

Thanks

# Answer
> 0 votes
That's not a simple question, it depends on the site. For your case you will first want to check Nodes (Content items) as that could be a WYSIWYG field. Otherwise if it's hard-coded it would most likely be in the theme folder that's currently enabled.

You can also check Views for the page that's showing all of them as a series of images. That could give you information on what type of Content they are.

---
Tags: theming
---


# Question
Title: How to hide paragraph items based on permission
I am trying to limit access to each item in a paragraph field. My goal is to only let the creator of each item change the specific item. I installed and enabled the `Field Permission` module and this is almost exactly what I am looking for. I have configure custom permissions for each field in the paragraph. The only problem right now is that each paragraph item is still visible even though none of the fields are showned:

Is there a way to hide or disable a paragraph item for all users except the owner?

# Answer
Field permissions is not what you want, that only does permissions for fields, not for the entire entity like you want.

There's a hook called hook\_ENTITY\_TYPE\_access, you can use it as hook\_paragraphs\_item\_access(), that would let you alter permissions (Look at the paragraph\_bundle\_permissions submodule for an example).

As others have said paragraph items don't actually have the owner on them - neither does field collection. They aren't really mean't to be separated like this. You can add the property yourself if you want to.

I recommend changing the Paragraphs to not be paragraphs and be something like Nodes instead. If they have permissions and are owned by someone, paragraphs aren't really the right thing. You can use Inline Entity Form if you want to embed a form for it. Since they are nodes you should be able to have more control on permissions.
> 2 votes

# Answer
Each paragraph entity has a user reference base field which if not set to something else defaults to the current user logged in.

So the only thing you have to do is implement a hook to control the entity access; something like

```
/**
 * Implements hook_ENTITY_TYPE_access().
 */
function custom_mod_paragraph_access(EntityInterface $entity, $operation, AccountInterface $account) {

  if ($operation !== 'update') {
    return AccessResult::neutral();
  }

  if ($entity->getOwnerId() !== $account->id()) {
    return AccessResult::forbidden();
  }

  return AccessResult::neutral();
}

```

And the result will like this:

As you can see, the User would still be able to delete the paragraph but not edit it. So you'd probably want to update the code above to forbid the delete operation as well.

This does also only *"disable"* the paragraph and not hide it.

To actually hide them, I suppose you would need to make a form alter and then set them to have #access = false.
> 2 votes

---
Tags: 8, users, paragraphs
---


title: What plugin control html_attributes?

text:
# Question
Title: What plugin control html_attributes?
The html.html.twig template contains the following line.

```
<html{{ html_attributes }}>

```

On my site, it outputs the following markup.

```
<html lang="ru" dir="ltr" xmlns:article="http://ogp.me/ns/article#" xmlns:book="http://ogp.me/ns/book#" xmlns:product="http://ogp.me/ns/product#" xmlns:profile="http://ogp.me/ns/profile#" xmlns:video="http://ogp.me/ns/video#" 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# ">

```

What plugin or core function controls it?

# Answer
They're added in `template_preprocess_html`:

```
$variables['html_attributes'] = new Attribute();

```

To alter them, you can implement `hook_preprocess_html` in your theme or module.
> 1 votes

# Answer
Drupal core provides theme "html" https://api.drupal.org/api/drupal/core%21includes%21theme.inc/8.2.x See drupal\_common\_themes().

This is sent thru a preprocess function: hook\_preprocess\_html() https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template\_preprocess\_html/8.2.x

In the preprocess function, the "html\_attributues" variable is added by using the Attribute class; https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Template%21Attribute.php/class/Attribute/8.2.x

Theming is a huge part of Drupal, here's a good starting point https://www.drupal.org/docs/8/theming

More info on preprocess functions https://www.drupal.org/docs/8/theming/twig/twig-best-practices-preprocess-functions-and-templates

More info on using attributes https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
> 0 votes

# Answer
I think it is a result of working "Metatag" module (your attributes contain some w3c validation errors). I used this patch to change depreciated metatags.
> -2 votes

---
Tags: theming
---


# Question
Title: Why are there so many attempts by an anonymous user to access /wp-login.php?
I looked at `/admin/reports/dblog` today. There were five request in two minutes by an anonymous user to view `/wp-login.php`. These requests have been happening for an hour at least and continue 2-3 times per minute.

1. What are the possible explanations for this strange behavior?
2. What can/should I do about it, if anything?

# Answer
As kiamlaluno said:

> It's just bots scanning for exploits. You don't need to do anything, except serving a faster 404 response for those pages, as described in drupal.stackexchange.com/a/152732/199.
> 3 votes

# Answer
For D8 you could use Drupal Perimeter Defence

> Basic perimeter defence for a Drupal site. This module bans the IPs who send suspicious requests to the site. The concept is: if you have no business here, go away.
>
> Use the perimeter module if you get a lot of requests to '**wp-admin**' or to **.aspx** urls on a linux server, or other similar requests.
>
> Currently, the module bans users who generate "page not found" events for requesting any of the following url patterns:
>
> ```
>   private $bannedPatterns = [
>     '/.*\.aspx/',
>     '/.*\.asp/',
>     '/.*\.jsp/',
>     '/\/blog_edit\.php/',
>     '/\/blogs\.php/',
>     '/\/wp-admin.*/',
>     '/\/my_blogs/',
>     '/\/system\/.*\.php/',
>     '/.*systopice.*/',
>   ];
>
> ```
>
> The module is optimized for performance and designed to be activated when a Drupal site is targeted by hackers or bots.
> 0 votes

---
Tags: security
---


title: Not Letting Me Turn On Registration

text:
# Question
Title: Not Letting Me Turn On Registration
When I try to change my ACCOUNT settings at admin/config/people/accounts

The new state (visitors) doesn't stay checked at Who can register accounts. It reverts just back to admin.

Does anyone know why?

**Note**: I had a look in settings and all the files around it (D8). But I cannot see anything similar.

# Answer
The config variable might be hard-coded in your codebase.

You could look for the string:

`$conf[` or `$conf['user_register'] = 0`

For example, in *settings.php* or elsewhere.

The exact string may vary depending on your codebase, e.g quotes, spaces etc..

That would override the variable configuration setting in the UI.
> 0 votes

---
Tags: users
---


# Question
Title: How to find orphaned files and images which are not linked from any css stylesheet or from any node?
Is there a way to list all unused files which reside inside public file system and inside a theme directory and list them, or maybe even have an option to delete them automatically?

I mean files which are currently not linked from any css stylesheet or from any node.

# Answer
You can find orphaned files by running the following MySQL query:

```
SELECT fm.*
FROM file_managed AS fm
LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
WHERE fu.type = 'node' AND n.nid IS NULL

```

This returns all files which have no associated node. I'm not sure if it's safe to delete the returned rows and files, probably also depends on your module setup. Only use at your own risk!

Source: http://drupal.org/node/733258#comment-5582764
> 14 votes

# Answer
For those coming to this post three years later, there's a little module you can use to do this called Fancy File Delete.

At the time of this post, it's in beta, so use it at your own risk. As always, cleaning up orphaned anything through DB queries can be sketchy and its success depends heavily on your particular module setup.
> 5 votes

# Answer
Something that may help to identify "*files that are no longer attached to nodes or files and directory that are not in the file managed table*" (as in the duplicate question about "How to do delete unused files?"), is to use the File Checker module. Some details about it, from its project page:

> In a perfect Drupal world your server filesystem and its correspoding entries in Drupal's files table are 100% synchronized. But what if parts of your file system have been corrupted due to some disk failure? Or one of your modules messed up your database and files? Or your deploy script went beserk? Well, then this module will help you to monitor and find out which files are out of sync.
>
> Out of the box the files table has two kind of statuses: Temporary (0) and Permanent (1). The file checker introduces an additional status Missing (2). In scope of the verification process which can be triggered in various ways the status column of the files table is updated.
>
> **Features**
>
> * Run verification process: on demand, via cron, via drush (in planning)
> * File list overview page with filters
> * Views integration
> * Drush command for file checking
>
> If you want to export the results of a view it's recommended to use views\_data\_export module.

So what you could do is like so:

* Clone (copy) your site to some dev environment, but don't copy any of the files in the directory you want to check. As a variation (if this question is about a non-production status site), just temporary move all files out of that directory.
* Use the File Checker module to find out what files are "missing": these are the files that are obviously **not** unused. But any file that this module does not argue about is ... unused!
* By copying all missing files to the correct location of the directory you want to check, you then step-by-step recreate a perfect content of your directory.

**Note**: even though this question is about D7, the is an (alfa) version of it also for D8.
> 3 votes

# Answer
there is one module that removes unwanted files fancy file delete.

> View of all managed files with an option to force delete them via VBO custom actions Manually deleting managed files by FID (and an option to force the delete if you really want to). Deleting unused files from the default files directory that are not in the file managed table. AKA deleting all the unmanaged files. Deleting unused files from the whole install that are no longer attached to nodes & the file usage table. AKA deleting all the orphaned files.
> 2 votes

# Answer
You can delete unused file by

1. Delete manually from the **file\_managed** table, by some query like

`$this->database
 ->delete('file_managed')
 ->condition('fid', $fid, '=')
 ->execute();`
2. Setting the status of a file **0**, to mark is as temporary file, so the cron will delete it after certain time.
`$file = File::load ($fid);
 $file->setTemporary();`
> 0 votes

# Answer
The *fancy file delete* module did not work at all for me. Here is a more manual alternative.

To delete files from a folder that are not in the managed file table you can:

1) Create a list of all the managed files:

```
mysql whateverdb -e "select filename from file_managed" > ~/managed-files.txt

```

2) Delete all files from a directory that are not in that list. To do this I used a small bash script:

```
#!/bin/bash

IMG_FOLDER='/var/www/html/yoursite/docroot/sites/default/files/certain-images'
EXCLUDES='/home/yourhomeuser/managed-files.txt'

for FILE in $IMG_FOLDER/*; do
  if ! grep "$FILE" "$EXCLUDES"; then
        echo "Deleting $FILE"
        rm -f "$FILE"
  fi
done

```

Just change the `IMG_FOLDER` variable to the path of whatever folder you want to delete files from (and update the path to your excludes file)
> 0 votes

---
Tags: 7, files
---


title: Views for specific user profiles

text:
# Question
Title: Views for specific user profiles
I have view that displays a users nodes. When you view "my account" it displays all the nodes you created in a view. However when viewing another user's profile, you don't see the node's that they added, instead you still see your nodes. Is this something I would need to set up with views and rules?

tl;dr How can I create a view that displays user specific content on their own profiles.

X user's content on X user's profile
Y user's content on Y user's profle

EDIT Answer: Drupal 7 views, filter by owner

# Answer
> 1 votes
To list content owned by a user you can:

1. Create a View that lists content
2. Create a Page Display within that view
3. Configure a "Contextual filter" for "Content: Author UID" and set its "When the filter value is NOT in the URL" setting to "Provide a default value", then select "User ID from URL" for the "Type".

# Answer
> 0 votes
If you only want to limit a certain user, you can select the filter criteria of User: Name, or User: The User ID, whatever suits you.

---
Tags: views
---


# Question
Title: view of unformatted list invalidating cache issues
I have a view that shows the title of a single content type as an unformatted list. I have an argument for a nid-contextual filter that I pass to the view in

```
function modulename_views_pre_view($view, $display_id, array &$args) {
 ....
 $args[0] = $filter_value;
 }

```

The value for the contextual filter is a value the user can select and is set in `\Drupal::service('user.private_tempstore')`. Every time the user selects a different value from a select form element, the view should show different results. However, it caches the output and only if I clear all caches it shows the correct output. But if I format the view output as a table, then everything works totally fine and the new results are shown immediately.

The cache tags for this view are given as follows:

```
print_r($view->getCacheTags());
Array ( [0] => config:views.view.users_in_class [1] => node_list )

```

Do I have to specifically invalidate something here or am I missing something else ? I thought that the cache tag `node_list` would already be enough. And why are results being cached when having the format as an unformatted list?

# Answer
> 1 votes
The cache tag `node_list` only works for database changes in the node table, but this is not happening when the user selects a filter value.

This is from the point of the View a cache context. So if you don't find a way to configure the View to handle this correctly, you could assign a custom cache context for the filter value.

The whole picture, which the View can't know because you provide only the filter value to it, is a mix of tag and context. You would need a cache tag for the private tempstore and a context for the current user to get the caching right:

```
function modulename_views_pre_view($view, $display_id, array &$args) {
  ...
  $uid = \Drupal::currentUser()->id();
  $view->element['#cache']['tags'][] = 'users_in_class.' . $uid;
  $view->element['#cache']['contexts'][] = 'user';
}

```

and then invalidate the tag when changing the private tempstore of a user $uid:

```
Cache::invalidateTags(['users_in_class.' . $uid']);

```

---
Tags: views, 8, caching
---


title: problem with authenticated users

text:
# Question
Title: problem with authenticated users
I'm on drupal 8.3, I have do the same for the view block and it's ok just for the admin user, but for authenticated users, the block does not appear, what should I do?

# Answer
Navigate to

> admin/people/permissions

and check if u have permissions for authenticated user.

Do you using the field permissions module?
> 0 votes

# Answer
it's solved, i have to check view user information on admin/people/permissions for authenticated users
> 0 votes

---
Tags: views, blocks, users
---


# Question
Title: Include Drupal modules inside composer.json file
I am doing a custom code of OpenSocial template/site.

In OpenSocial or other composer file, there are some modules that are added in the `"require": {}` section and they are installed properly when running the file.

Ex.

```
   "drupal/entity": "1.0-alpha4",
   "drupal/features": "3.5",

```

My question is how can I install module that requires to run composer for it to be properly working?

My goal is to include Simple Oauth in the composer file. I can just do this, but is there any additional input outside the file?

```
"drupal/simple_oauth": "2.0-rc1",

```

Also I noticed that when adding the Address module in the require section, there is some lines added here, for example.

I am new to this method and I really appreciate your help! Thanks!

# Answer
There are general two kind of dependencies you can make in a composer file.

1. Other Drupal modules
2. PHP/JS/FOO libraries

If your module depends on a specific library, you should do like the address module and make sure that the library is present when it's being installed, so you can prevent installation if the library is not available. It's a clever way of making sure you don't install the module in a broken setup, which could cause fatal errors etc.

IF you simply depend on other drupal modules, you should also add the dependency in the info file which should be enough.
> 2 votes

---
Tags: 8, composer
---


# Question
Title: How to port active configuration to module configuration
**Scenario**: I have a website which was initially developed with a single site (A) in mind. Now, because reasons, I need to make this a multi-site setup (A & B). So, I have functionality in A I want to share with B. We built A with all config exported to it's config sync folder, which means all config is intertwined.

**Problem**: How would I go about converting all sharable configuration to modules, which would allow me to maintain the modules from one codebase in both A & B? Putting everything into `module_foobar/config/install/` will not work that easily for A, since it already has that config in it's active config.

# Answer
> 1 votes
Use Features: It basically does exactly what you want, it turns your existing configuration into a `module_foobar/config/install/`

Be aware though that Features merges config (it does add and update existing config, but it does not remove/delete unused config like core configuration management).

---
Tags: 8, configuration
---


# Question
Title: How to send out email based on matching taxonomy terms in user profiles?
I'm using profiles 2 and have (one or many) taxonomy terms that can be selected by a specific profile type. I have a webform that also has this taxonomy term in the select list. When the webform is submitted, if it matches one of many taxonomy terms in any of these profiles I want an email sent to those profiles. I can't figure out how to get Rules to do this. Any help is appreciated.

This is what I have so far. I just have it posting a message right now to test, but I want it to email, but I can't find the data I need to compare in the Rules.

```
{ "rules_webform_email" : {
"LABEL" : "Webform Email",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "webform_rules", "rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "webform_has_id" : {
      "form_id" : [ "form_id" ],
      "selected_webform" : { "value" : { "webform-client-form-3" : "webform-client-form-3" } }
    }
  },
  { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "webform" : "webform" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Test submit webform\r\n[data:project_type-value]\r\n[data:project_description-value]" } }
]
}
}

```

The project\_type is the taxonomy term in the webform. I need to compare it with the field\_service\_provided (Term Reference field to the same taxonomy vocabulary) in the Profile.

# Answer
Even though your question doesn't say so, from the format of your exported rule it's clear it is about D7. A possible answer to your question is by replacing the Rules Action in the rule you already have, and by also using the Views Rules module, as further detailed below.

### 1. About the Views Rules module

The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

> ... provides two types of elements in Rules, configured with a "Rules" view display:
>
> * **Views loop**: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.
> * **Collect view result rows (action)**: This action collects each variable in all view result rows into list variables for use in Rules.
>
> ***Tip***: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

### 2. Create a view of display type 'Rules'

After you enable the Views Rules module, you can use Views to create a view of those users that you want to send an eMail to. Add of view of display type ***`Rules`*** (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

### 3. Create a rule using the view of display type 'Rules'

Replace the Rules Action in your current rule, using these guidelines:

* Use the link that says `Add view loop` to add a Views loop, and select the "Rules" display created in the previous step.
* Configure the parameters and variable names.
* For each user contained in your Views loop, perform a Rules Action "Send an eMail", using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the *Rules row variables* as suggested in the previous step, your actual eMail can use tokens such as `[usermail:value]`, `[username:value]`, etc.
> 2 votes

---
Tags: taxonomy-terms, rules, webforms, emails
---


title: Get node path for different domain

text:
# Question
Title: Get node path for different domain
I have a series of nodes which are published on up to 7 different domains on the same single Drupal 7 install. Whilst I can use `url('node/12345');` for nodes published to the current domain, I would like to create href links to the these nodes and have them link to the correct domain path.

At the moment, nodes that are not published to the current domain are just giving me `href="/12345"`.

How do I get the URL for nodes that aren't in the current domain?

# Answer
You could try `drupal_get_path_alias('node/12345')` (see docs) and then exchange the domain name.
> 0 votes

---
Tags: 7, domain-access
---


# Question
Title: Output from preprocess_views_view_field in Drupal 8
I tried to alter the Output of an View-field with function in Drupal 8:

```
function mytheme_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];

  if ($view->storage->id() == 'myview' && $variables['field']->realField == 'field_sterne_value') {

    $string = "";
    $sterne = intval($variables['field']->getValue($variables['row']));

    for ($i=1;$i < $sterne;$i++){
      $string .= "<img src='/themes/mytheme/img/stern.png'>";
    }

    $variables['mystar'] = $string;
  }
}

```

The output should show the stars as Images, but shows the html-Code in Frontend. I tried different encoding with htmlentities and html\_entity\_decode. But it does not work or I did encoding in a false way.

In my custom twig-template I use {{mystar}}. But the same problem exists when I use the original template with {{output}}.

Where is my error?

# Answer
> 3 votes
You can use the original template with `{{ output }}`, if you put the string in a markup object:

```
$variables['output'] = \Drupal\Core\Render\Markup::create($string);

```

---
Tags: 8, theming
---


# Question
Title: how to get the size and last modified date of file with fid
Hi I have the filename and fid of the uploaded file in a media entity, how can I programatically get the size and last uploaded date in my module? This is with D8 thanks

# Answer
> 1 votes
This is the code to get the size:

```
 $tid=$fileupload[0]['target_id'];
 $file = File::load($tid);
 $size = $file->getSize();

```

---
Tags: 8, files
---


# Question
Title: How to define a custom menu and show it like an admin menu in Drupal 8?
**Question**: How to define a custom menu and show it like an admin menu in Drupal 8 ?

**Goal**:

First of all, we have a custom administration theme where we are looking for a custom toolbar solution that stays visible for an "simple" user on the front and backend when logged in.

There is a need for a toolbar at top of page similar like the toolbar module in Drupal 8 core.

We want the following links shows to a user :

* Back to site
* User with possibility to view and edit their profile
* Logout
* The Edit option for edit content from the front of the site

**Screenshot of the goal** :

**Research**:

I have found there are several solutions for Drupal 7 with modules like Admin menu source, Webmaster menu and with Block Class styles module. But none of them is compatible for using in Drupal 8.

**Expected solution**:

This custom toolbar should only be for specific user roles("user") showed. I will do this by creating an custom module but I'm not really sure if I need to inherit from the toolbar core module in Drupal 8.

* A complete new toolbar

OR
* I can work further on the default toolbar module in Drupal 8 but there is a need for 2 things: add item "boutique" as example that is decribed as an answer but also remove an item from the default toolbar like Devel or Manage tab included the sub links from these items.

Are the two things together not possible then I prefer for creating a completely new toolbar module from scratch for Drupal 8.

**Recap:**

* Not hide or show items based on permissions
* Not just adding items to the default drupal 8 toolbar module

Is that possible ? Are they better/other methods for achieving this goal ?

# Answer
> 1 votes
This is how i add custom menu :

In a custom module :

> xxxx.module :

```
/**
 * Implements hook_toolbar().
 */
function xxxx_toolbar() {
    $items = [];

    $items['Boutique'] = [
        '#cache' => [
            'contexts' => ['user.permissions'],
        ],
    ];

    if (!\Drupal::currentUser()->hasPermission('Access the Commande overview page')) {
        return $items;
    }

    $items['Boutique'] += [
        '#type' => 'toolbar_item',
        '#weight' => 1,
        'tab' => [
            '#type' => 'link',
            '#title' => 'Boutique',
            '#url' => \Drupal\Core\Url::fromUri("internal:/admin/boutique/commandes"),
            '#attributes' => [
                'title' => 'Boutique menu',
                'class' => ['toolbar-icon', 'toolbar-icon-boutique'],
            ],
        ],
        'tray' => [

            'configuration' => [
                '#type' => 'link',
                '#title' => 'Commandes',
                '#url' => \Drupal\Core\Url::fromUri("internal:/admin/boutique/commandes"),

            ],[
                '#type' => 'link',
                '#title' => 'Livraison',
                '#url' => \Drupal\Core\Url::fromUri("internal:/admin/boutique/livraison"),

            ],
            [
                '#type' => 'link',
                '#title' => 'Configuration',
                '#url' => \Drupal\Core\Url::fromUri("internal:/admin/boutique/configuration"),

            ],

        ],
        '#attached' => array(
            'library' => array(
                'boutique/admin',
            ),
        ),

    ];
    return $items;
}

```

And the result :

You can manage access with :

> if (!\Drupal::currentUser()-\>hasPermission('Access the Commande overview page')) { return $items; }

in the xxxx.module like me.

# Answer
> 0 votes
I think that u can do this by adding permission for Toolbar on specific roles and ofc permissions for editing content.

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


# Question
Title: RedirectResponse not able to redirect in hook_entity_view drupal 8
I am trying to redirect users to a page on entity view. I am using RedirectResponse in hook\_entity\_view. But it is not redirecting to the desired page.

This is how I implemented this. After fetching my redirect url, I have passed it to RedirectResponse.

return new RedirectResponse($redirect\_url);

Thank you

# Answer
Thank you, I got it working. Don't need to return the object of RedirectResponse. It works like this.

$response = new RedirectResponse($redirect\_url);

$response-\>send();

It works this way.
> 6 votes

# Answer
After filling in the prompts with Drupal Console after executing `drupal generate:event:subscriber`, and entering `kernel.request` when prompted for the event name, it's possible to add something like the following to the callback function that handles the event:

```
use Symfony\Component\HttpFoundation\RedirectResponse;
...
 /**
   * This method is called whenever the kernel.request event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function kernelRequest(GetResponseEvent $event) {
    $request = $event->getRequest();
    $route_name = $request->attributes->get('_route');

    if ($route_name == 'entity.checkout.canonical') {

     // Create the destination URL, such as:
      $url = Url::fromRoute('user.register')->toString();

      // create redirect:
      $response = new RedirectResponse($url);
      $response->send();
    }
  }

```
> 4 votes

---
Tags: 8, hooks
---


# Question
Title: How to hide the 'Format Options' / 'Help Text' Guideliness from the bottom of comments textarea?
How can I remove or hide **Format Options / Guideliness** under the comments textarea in my theme?

# Answer
If you're looking for a code-less way to do this in your theme. Adding a simple style rule to your theme's CSS can hide this element from display:

```
#edit-comment-body-wrapper .filter-wrapper { display: none; }

```
> 2 votes

# Answer
The best is to add to your CSS file

```
.filter-wrapper
{
display: none;
}

```

There you go, disappeared!
> 4 votes

# Answer
Unfortunately this https://www.drupal.org/node/2599958 most likely won't get commited in any shape or form so you have to a) deny access to the route(if you want to) and add process handler for text\_format via hook\_element\_info\_alter.

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

/**
 * Implements hook_element_info_alter().
 */
function MODULENAME_element_info_alter(array &$types) {
  // Add process handler for text format so that we can remove
  // formatting tips.
  $types['text_format']['#process'][] = 'MODULENAME_process_text_format_element';
}

/**
 * Text input element process handler that will remove
 * the formatting tips.
 */
function MODULENAME_process_text_format_element(&$element, FormStateInterface $form_state, &$complete_form) {
  $element['format']['guidelines']['#access'] = FALSE;
  $element['format']['help']['#access'] = FALSE;
  return $element;
}

```
> 3 votes

# Answer
Check out the Better formats module. It allows you to hide the format options and tips link per user roles and fields.
> 3 votes

# Answer
This is Another solution that i found in:
How to hide Input Format Options and help text under a textarea?

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function CUSTOM_MODULE_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#after_build'][] ='CUSTOM_MODULE_eform_application_after_build';
}

function CUSTOM_MODULE_eform_application_after_build ($form) {
    unset($form['field_experience']['widget'][0]['format']);
    unset($form['field_miscellaneous']['widget'][0]['format']);
    return ($form);
}

```
> 2 votes

# Answer
This is the method that I use:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_FORM_ID_alter(array &$form, FormStateInterface $form_state, $form_id) {
  // Here we only delete the format if the user is anonymous,
  // you can eliminate the if() for all the users.
  if (\Drupal::currentUser()->isAnonymous()) {
    $form['field_description']['widget']['#after_build'][] = '_mymodule_allowed_formats_remove_textarea_help';
  }
}

/**
 * Remove the textarea help message.
 *
 * @param array $form_element
 *   The form element.
 * @param FormStateInterface $form_state
 *   The form state.
 *
 * @return array
 *   Images URL Array.
 */
function _mymodule_allowed_formats_remove_textarea_help(array $form_element, FormStateInterface $form_state) {
  if (isset($form_element[0]['format'])) {
    // All this stuff is needed to hide the help text.
    unset($form_element[0]['format']['guidelines']);
    unset($form_element[0]['format']['help']);
    unset($form_element[0]['format']['#type']);
    unset($form_element[0]['format']['#theme_wrappers']);
    $form_element[0]['format']['format']['#access'] = FALSE;
  }

  return $form_element;
}

```
> 1 votes

---
Tags: theming, 8, comments, wysiwyg, input-formats
---


# Question
Title: How to View of commerce products with image from product_variation
Drupal 8, commerce 2: I would like to make a a view of commerce products and show a) the title of the product b) the image of one of the product\_variations, e.g. at delta 0. What I have done: * view of products

* add relationship to product\_variations
* add the variation image field for display

-- this gets me a list of products and images, but it is in essence a list of variations, with the product title repeated over the different images, so

* I turn on aggregation and

-- I get this error: Table 'mytable.commerce\_product\_variation\__field\_variation\_image' doesn't exist:

WITHOUT the product\_variation image field and aggregation on, I have the correct list of product titles.

This seems like a pretty basic need for a view of products, without we put an image field directly on the product.

One alternative I have explored is to do a rendered entity of the Product and make simplified view modes for the product\_variation and product, then set the display mode for the entity in the view, but I will have to customize the field display for every type of product\_variation and product I have, and in my one test its still not right, giving me duplicate variation images stacked under the product title, and there is no way to specify "link to content" when using the rendered entity, or do any custom buttons as you might do using fields. I suppose its possible to get this way to work using twig templates, but it seems a lot tougher than if we could have a working aggregation while using a relationship.

# Answer
> 1 votes
Here's how I did mine :

* View of products
* Add relationsip: variation image
* Add that relation in the fields displayed (You'll now get all the images for the product
* Add a field Product variation delta
* Add a filter with the delta which equals to 0 (which will show the image of the first variation).

It's not perfect as if the first variation as no images, it think it won't show up... But it should fits quite some cases.

---
Tags: views, 8, commerce
---


# Question
Title: Why would enabling a new module result in the majority of modules disabling?
On my Drupal Commerce site, I was attempting to add a Commerce Discount-related module that would allow me to specify a discount based on taxonomy term/product category. When I enabled the module however, my site showed that my enabled module count dropped by ~50 modules. Yikes! This included key features of the site, including payment methods (Paypal, FirstData), as well as XML sitemap-related modules. I also received some exception errors related to existing Rules on the site that were related to shipping rules.

I was able to revive through a backup, but had never seen this type of response before. Any ideas?

# Answer
> 1 votes
It appears you're being affected by a known issue that has been resolved in Drupal 8 but still needs to be back ported to Drupal 7. The PHP extension Suhosin causes modules with parentheses in the package name to be disabled. You can edit your Suhosin configuration to remove parentheses from the array index blacklist or, if you're unable to do that in a pinch, you can edit the relevant module files to remove the parentheses from their package names.

More info in the core issue: https://www.drupal.org/node/2665152

---
Tags: commerce, installation
---


# Question
Title: Rules Add an item to a List overwrites existing data
I have created a rule to add terms to an existing Term Field. The rule fires correctly, it's adding the Term to the Field. However, it's overwriting all the existing terms within the field.

I have tried to follow the steps from this similar question as well as this Tutorial, however, it's still a no go for me.

More details about my setup:

* Vocabulary: Emails (machine name: `emails`)
* Email Field: Email Field (machine\_name: `field_primary_email`), which is a single value field.
* Term Reference: Email Term Reference (machine\_name: `field_email_term_reference`)

The requirement is to display Email communication basis of the Email address present in the node \[ Contact Content Type\].

I have a rule which picks up the primary email & creates a taxonomy term from it. The second rule, assigns the relevant terms basis of the email present in the node. The email address in the node may change, however, the terms are to remain to display the past communication. When the new email is updated in the node, the first rule creates a new taxonomy term basis of the updated email address. When the new term is created, the second rule picks up the term & assigns it to the Term reference field along with the existing ones. It is not to overwrite the terms already present in the field. Basis of the terms present in the node, I can display the email communication.

My rule I created so far (in Rules export format):

```
{ "rules_update_email_term_reference" : {
"LABEL" : "Update Email Term Reference",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_view" : [] },
"IF" : [
  { "entity_is_of_bundle" : {
      "entity" : [ "node" ],
      "type" : "node",
      "bundle" : { "value" : { "candidates" : "candidates", "clients" : "clients" } }
    }
  },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_email_term_reference" } }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "node:field-email-term-reference" ] },
      "ITEM" : { "current_term" : "Current Term" },
      "DO" : []
    }
  },
  { "entity_query" : {
      "USING" : {
        "type" : "taxonomy_term",
        "property" : "name",
        "value" : [ "node:field-primary-email" ]
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "list_add" : {
      "list" : [ "node:field-email-term-reference" ],
      "item" : [ "entity-fetched:0" ],
      "unique" : "1"
    }
  }
]

```

} }

# Answer
Your rule in your question seems to have "a few" (not just one) issues that need to be addressed. So I'll build a list of these issues here (and will add more of them later on if needed) ...

### Issue 1:

Think about this: "Why have that 1st Rules action (a loop), if inside that loop there is nothing happening (as per the `"DO" : []` in it)?". Either the loop is just redundant, or there is some Rules action(s) still missing inside that loop (more research needed).

If it was me to decide, for now I'd delete that Rules Action. And if needed I'd restore it later on if I have a real reason to do so (i.e. if there is at least 1 Rules Action that I know I'd need, as part of that loop.

### Issue 2:

At the core of your question, there is your "*It is not to overwrite the terms already present in the field*". The typical mistake in using Rules is that someone incorrectly uses a Rules Action like "Set a data value" (for a multi value field), and that will remove all existing values for that field. The correct way is to use a Rules Action "Add to list" (that will preserve existing values). Your last Rules Action does indeed perform a "Add to list" (as it should be done to achieve your goal), but what is suspicious in that Rules Action is that you use `entity-fetched:0` ... That is a single value (as per the `...:0` part of it, but `entity-fetched` is a multi value list (it has to be like that, otherwise you wouldn't use that `...:0` part in it). But nowhere there is an indication why "the first value" in the multi value list (stored in `entity-fetched`), is the actual value you want to add to your list.

### Issue 3:

The rules event your using (= `node_view`), combined also with the Rules Condition, is rather suspicious also. For 2 reasons: (a) what if the event and/or condition are not satisfied (in that case none of the Rules actions get executed) and (b) if you're sure the Rules event and Rules condition is "always" satisfied, then you might be doing those Rules Actions over and over again.

Though there is possibly only reasons to do so in 1 specific scenario. I.e. for those situations related to your "*I have a rule which picks up the primary email & creates a taxonomy term from it*" (let's call that your 1st rule, as compared to your 2nd rule shown in your question). It seems to me that your 2nd rule (as in your question) should be reworked like so:

* Create a new Rules Component, with Rules Conditions and Rules Actions as you already have in your 2nd rule here.
* Add and extra Rules Action to your 1st rule, which is simply/only to perform (= trigger the execution) of your 2nd rule.
* In doing this redesign, you may have relevant / interesting data available in your 1st rule (like node id, user id, eMail id, term value, etc), which you can pass on to the Rules Component as a so called "Parameter" for that component.
* And by having such parameters available in your Rules Component, you might possibly simplify the set of required Rules Actions needed to achieve your goal.
* Don't forget to at least disable (or even delete) your current 2nd rule, after you reworked it to such Rules Component.

### Possible other issues to be resolved

The above issues are, for now, only some suggestions to help you come closer to your goal. It's well possible (actually I'm about sure ...) you'll need other issues to be resolved also. But pretty sure the above issues will help you come closer. Btw, debugging is the art of taking away all possible reasons why it doesn't work ... as you want it to work.
> 2 votes

---
Tags: 7, taxonomy-terms, rules
---