# Question
Title: Removing required attribute on user entity fields not working
I have added fields to user entity and make them required and show on registration page. So the user signing up have to fill all the fields. On the admin side these all fields are coming but i don't want to make them required when admin is creating any user. I thought it will be solved if i `hook_form_alter` the user registration form and remove the `#required` attribute. I did this for admin and `dpm($form)`. I set `#required => 0` also `unset #required` but it keep on showing error of required field. I uncheck the required checkbox in field settings from admin panel and it does not show validation errors on both Admin and Frontend.

What i want is when admin create a user he just enter username and password and leave the rest of custom fields blank and it should register the user. But on the frontend users have to fill the whole form.

Below is the code:

```
    // If this is admin creating user
     foreach($form as $key => $value){
                if(strpos($key, 'field_') !== false){
                    $value['und']['#required'] = 0;
                    unset($value['und']['#required']); // This isn't working either
                }
            }
    // Endif

```

Updated Full Code:

```
/**
 * Implements hook_form_alter()
 */
function paypal_signup_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form'){
      global $user;
      if(!in_array('administrator', array_values($user->roles))){
        //Submit handler for redirecting user to Paypal.
        $form['#submit'][] = '_paypal_signup_redirect_paypal';
    } else {
        // Remove validation when admin is creating user.
        foreach (element_children($form) as $key) {
            if (strpos($key, 'field_') !== FALSE) {
              $form[$key][LANGUAGE_NONE][0]['#required'] = FALSE;
              $form[$key][LANGUAGE_NONE]['#required'] = FALSE;
            }
         }
        dpm($form);
    }
  }
}

```

# Answer
> 1 votes
Drupal has `element_children()` to help you safely loop over render arrays. Looping over such arrays manually will inevitably causes problems. Your code should look more like this:

```
foreach (element_children($form) as $key) {
  if (strpos($key, 'field_') !== FALSE) {
    $form[$key][LANGUAGE_NONE]['#required'] = FALSE;
  }
}

```

Incidentally, your current code doesn't work because you're modifying a variable that has only ben declared within that function's private scope.

# Answer
> 0 votes
Before writing any custom code, I think you should try Profile2 Module and in addition Profile2\_regpath Module provides you some Extra Options

# Answer
> 0 votes
I had the same issue with textfield. Drupal put the textfield added through GUI under a container and the rendered arrays look like this:

```
Array
(
    [#type] => container
    [#attributes] => Array
        (
            [class] => Array
                (
                    [0] => field-type-text
                    [1] => field-name-field-first-name
                    [2] => field-widget-text-textfield
                )

        )

    [#weight] => 5
    [#tree] => 1
    [#language] => und
    [und] => Array
        (
            [0] => Array
                (
                    [#entity_type] => user
                    [#entity] => stdClass Object
                        (
                            [uid] => 0
                            [hostname] => 0.0.0.0
                            [roles] => Array
                                (
                                    [1] => anonymous user
                                )

                            [cache] => 0
                        )

                    [#bundle] => user
                    [#field_name] => field_first_name
                    [#language] => und
                    [#field_parents] => Array
                        (
                        )

                    [#columns] => Array
                        (
                            [0] => value
                            [1] => format
                        )

                    [#title] => First Name
                    [#description] =>
                    [#required] => 1
                    [#delta] => 0
                    [#weight] => 0
                    [value] => Array
                        (
                            [#entity_type] => user
                            [#entity] => stdClass Object
                                (
                                    [uid] => 0
                                    [hostname] => 0.0.0.0
                                    [roles] => Array
                                        (
                                            [1] => anonymous user
                                        )

                                    [cache] => 0
                                )

                            [#bundle] => user
                            [#field_name] => field_first_name
                            [#language] => und
                            [#field_parents] => Array
                                (
                                )

                            [#columns] => Array
                                (
                                    [0] => value
                                    [1] => format
                                )

                            [#title] => First Name
                            [#description] =>
                            [#required] => 1
                            [#delta] => 0
                            [#weight] => 0
                            [#type] => textfield
                            [#default_value] =>
                            [#size] => 60
                            [#maxlength] => 255
                            [#attributes] => Array
                                (
                                    [class] => Array
                                        (
                                            [0] => text-full
                                        )

                                )

                        )

                )

            [#theme] => field_multiple_value_form
            [#field_name] => field_first_name
            [#cardinality] => 1
            [#title] => First Name
            [#required] => 1
            [#description] =>
            [#prefix] =>

            [#suffix] =>

            [#max_delta] => 0
            [#after_build] => Array
                (
                    [0] => field_form_element_after_build
                )

            [#language] => und
            [#field_parents] => Array
                (
                )

        )

    [#access] => 1
)

```

The `element_children()` doesn't help as it is not recursive. It loops only the immediate children whereas the textfield is rendered with three/four levels deep of arrays. The solution was to add this:

```
unset($form['field_first_name']['und']['#required']);
unset($form['field_first_name']['und'][0]['#required']);
unset($form['field_first_name']['und'][0]['value']['#required']);

```

---
Tags: users, entities
---


# Question
Title: Render view in code with the proper view mode
I have a view that calls for Show: Content, using a very specific view mode (neither Full content nor Teaser, it's created on purpose and themed according to my needs, basically an e-mail oriented output with very different HTML classes than the usual views displays in Drupal). When used in a page, it renders perfectly. However, when I render it from code to be able to use the resulting HTML directly:

```
$view = Views::getView('view_id');
$view->setDisplay('default');
$view->setArguments($args);
$view->preExecute();
$view->execute();
$render = $view->render();
$html = render($render);

```

I get an otherwise perfect render but not with that view mode, just the usual stuff. Alternative calls do the same:

```
$render = $view->buildRenderable('default', $args);
$html = render($render);

```

How could I force it to render the way I want it?

# Answer
> 1 votes
It was the theme. The rendering took place under cron and ran under the administration theme rather than the usual one, meaning different twigs. The solution will be to sub-theme the admin theme to make sure all the relevant twigs are present there, too.

---
Tags: views, 8
---


# Question
Title: How to add content of nested terms to Taxonomy term View
By default Drupal 8 taxonomy view doesn't show the nodes of child taxonomy terms. I need to include them but don't know to to modify the view *Taxonomy term (Content)*.

I have the following vocabulary:

```
- Europe
  - Portugal
    - Lisbon
    - Porto
  - Spain
    - Barcelona
    - Madrid

```

Showing all the content related to cities works fine (for example Barcelona). But now I want to show a list of content for countries (for example Spain) which should include content tagged as city (Barcelona and Madrid). And the same with continents, a list for Europe should include content tagged as Lisbon, Porto, Barcelona, Madrid, etc.

# Answer
Finally found the answer and it is almost the same than for D7:

1. Edit the existing view **Taxonomy Term** (admin/structure/views/view/taxonomy\_term/edit)
2. In *Advanced*, add the field **Content: Has taxonomy term ID (with depth)** using all the settings from already added *Content: Has taxonomy term ID using the same settings*. You can limit the depth by setting the depth parameter.
3. Remove old field *Content: Has taxonomy term ID using the same settings*
4. Set **Use aggregation** to yes to avoid duplicates
> 0 votes

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


title: Migrate content alone

text:
# Question
Title: Migrate content alone
We are using Drupal 8.5.X. As of today, we dump the complete DB to move from one environment to another. My concern is doing this, there are few sensitive information like user info or audit logs will be migrated to each environment. So I want to see whether we can migrate only contents and not the entire DB.

We use config\_split for migrating the contents. We tried https://www.drupal.org/project/content\_sync.. but looks like it is broken in the new Drupal. Any other modules or suggestions?

# Answer
You might want to take a look at Workspace, which which was added to Drupal core (8.6.0) just a month ago. It's mainly about content moderation and let's you prepare content on one site that then can be published to another site.

So maybe, if you wanna stick to your setup of one live (master) site and multiple dev (slave) sites, then you could let Workspace push just the content from live to dev – if it works this way.

Unfortunately, I can't find any really good documentation about Workspace. And yes, it has been added to core as an *experimental module*. But I'd say, you should give it try and can maybe contribute your experiences back :)
> 0 votes

---
Tags: nodes
---


# Question
Title: What may cause the text of a message created with the Message module to be empty?
I have installed the Message module to log activities, and set it up following these instructions.

All steps look good, and message (admin/content/message) is created after I added new content. But, the message's TEXT field is empty.

Also, `Message: Render message (Get text)` field in related View is also empty, and `SHOW NO RESULTS BEHAVIOR` is triggered.

I enabled message\_example module come with message, same result.

Is there anything wrong with my options?

# Answer
This is a rather typical issue in multi-language sites. A variation (not duplicate) of your question is what is described in "Rules - Set language of message notification".

A possible solution (work-around?) is what you wrote in your own comment below your question, i.e.:

> I checked Message class, and it turns out that I have a wrong language code, 'cause I set administer language to English other than default language. It works now after I set language back to default.

Another solution is to indicate the language in which the message is to be created.
> 0 votes

---
Tags: 7, message-subscribe
---


# Question
Title: Proper way to add external JavaScript file
What is the proper way to add Amazon oneTag code to Drupal 8. Instructions say to add it before the ending body tag.

I think it should be loaded to the /theme.libraries.yml. Here is the code I am trying to add:

`<div id="amzn-assoc-ad-123456789"></div><script async src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=123456789"></script>`

Do I need to create a file onelink.js with this code? Then reference it in libraries?

Thanks

# Answer
It's actually pretty well documented: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme#external

**MYTHEME.libraries.yml** (or MYMODULE.libraries.yml)

```
amazon-onetag:
  js:
    //z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=123456789: { type: external, attributes: { async: true } }

```

**MYTHEME.theme** (or MYMODULE.module)

```
function MYTHEME/MYMODULE_page_attachments_alter(&$page) {
  $page['#attached']['library'][] = 'MYTHEME/amazon-onetag';
}

```

---

Now we could start to discuss what is "the proper way"?

As Amazon wants it directly before the closing body tag (which is irrelevant in my experience) and as they also put a nice container with an ID around the script (which very likely is irrelevant as well) you could also simply copy the whole snippet into your (custom or sub-)theme's `html.html.twig` directly before the closing `<body>` tag.

But that would at the same time take this script a little bit out of Drupal's influence to handle, preprocess and order all scripts according a desired logic. And it can become a little bit more difficult to maintain in the end.
> 8 votes

---
Tags: 8, theming
---


title: head_title drupal

text:
# Question
Title: head_title drupal
in html.html.twig in title tags

```
{{ head_title|safe_join(' | ') }}

```
* This code display " home | " how to remove( | ) from display in home page?
* also in other page display " page | Home " i want title in other page display "Home | page " ?

# Answer
> 3 votes
It's easier and better to override this using the Metatag module.

The D8 version UI looks different than the picture below which is from D7.

This video goes over the D8 version.

---
Tags: theming
---


# Question
Title: How to set a contextual filter based on an entity reference field
I am currently working on a radio website.
Here is the basic information to keep it simple.

I have two content types: \[emission\] (programme) and \[podcast\].
The \[emision\] content is merely a general presentation with the broadcasting time. The \[podcast\] content has a field \[field\_emission\] in which I can make a reference to the \[program\] you can hear (it works with entity reference).

I have a View displaying all podcasts.
I have another display of that View, a block, shown only on the \[emission\] pages. I want to restrict to results of the view to all \[podcast\] concerned with the displayed \[emission\]. How should I set the contextual filters.
Here is how I tried so far. Up to now, nothing shows up.

# Answer
> 3 votes
On the View you started (Podcast Views) the **Contextual filter** you need to add is the **Entity reference** field, not the Nid.

Here are the settings for it:
When the filter value is NOT available:
**Provide default value**
**Content Id from URL**
When the filter value IS available or a default is provided (optional)
Specify validation criteria
Validator Content
Emission

Place the block on Emission nodes. The block will take the NID of the Emission node it's on, pass it to the Entity reference contextual filter to match Emission in question, and Views results will be limited to only Podcasts which reference that Emission through the field.

You don't need the Relationship unless you plan on displaying Emission information in this block, which you probably don't.

---

Another approach would be through the opposite side, through Emission Views, where you list Emission content type, but you don't have to display any Fields concerning Emission. Instead you'll display only the Title field of the Podcast that is referencing that Emission.

You do that by adding the Contextual filter ID (it's not the same field as above, but the settings are are the same).

And you have to add the Relationship for the Entity reference field, but the reverse one (Relate each Content with a field\_emission set to the content.)!

Then you add the Title Field, but make it uses the above Relationship. This will make the Title Field show Podcast title, and not Emission title. Set its label to something like "Podcasts referencing this Emission".

Make sure to tick "Hide if empty" under "No results behavior" so nothing is output on Emission pages that have no Podcasts referencing them.

And in the end display that block on Emission pages.

---
Tags: 7, entities, views
---


# Question
Title: How do I download a specific version of a module?
The official documentation for Drupal Console says that the arguments for `drupal module:download` are the following.

```
drupal module:download [arguments] [options]

```

is there an argument or option to specify the dev/beta version of the module?

# Answer
> 0 votes
We can use following code to download latest stable release :

```
drupal mod modulename --latest

```

if we want to select a specific release other than latest then we can go for

```
drupal mod modulename --unstable

```

hope this will help. https://docs.drupalconsole.com/en/commands/module-download.html

---
Tags: console
---


# Question
Title: How do I create an AJAX form with Add and Remove buttons for multi-value form element without submission button?
I would like to create a custom form with a textfield in which I input some data and it gets saved in the variable table.

The form should only contain the *Add*, *Remove*, and *Add more* button to add additional textfields.

When the textfield is empty, there should be an *Add* button; when the textfield is not empty, there should be a *Remove* button.
Clicking on the *Add more* button should create an empty textfield with an *Add* button.

All this need to happen without page reload.

I was able to add the *Add*, *Remove*, *Add more*, and *Submit* buttons. I looked into the available resources and example modules, but I can't find helpful resources.

Can anyone help me to modify the code so that the *Submit* button can be removed?

```
function mymodule_menu() {
    $items = array();
    $items['admin/mymodule'] = array(
        'title' => t('Example form'),
        'type' => MENU_CALLBACK,
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_ajax_example_add_more'),
        'access callback' => TRUE,
    );

    return $items;
}

function mymodule_ajax_example_add_more($form, &$form_state) {
  $mymodule_ajax_events = variable_get('mymodule_ajax_example_content', array());
  $mymodule_ajax_events_count = count($mymodule_ajax_events);
  if ($mymodule_ajax_events_count == 0) {
    $mymodule_ajax_events_count = 1;
  }

  $form = array();
  $form['#tree'] = TRUE;
  $form['mymodule_ajax_events'] = [
    '#type' => 'container',
    '#weight' => 80,
    '#tree' => TRUE,
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '<div id="js-ajax-elements-wrapper">',
    '#suffix' => '</div>',
  ];
  $form_state['field_deltas'] = isset($form_state['field_deltas']) ? $form_state['field_deltas'] : range(0, $mymodule_ajax_events_count-1);

  $field_count = $form_state['field_deltas'];
  foreach ($field_count as $delta) {
    $form['mymodule_ajax_events'][$delta] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['container-inline'],
      ],
      '#tree' => TRUE,
    ];

    $form['mymodule_ajax_events'][$delta]['event_url'] = [
      '#type' => 'textfield',
      '#title' => t('Event URL' . ($delta + 1)),
      '#size' => 40,
      '#default_value' => (isset($mymodule_ajax_events[$delta])) ? $mymodule_ajax_events[$delta] : '',
    ];

    $form['mymodule_ajax_events'][$delta]['remove_event_url'] = array(
      '#type' => 'submit',
      '#value' => t('Remove'),
      '#submit' => ['mymodule_ajax_example_add_more_remove'],
      '#ajax' => [
        'callback' => 'mymodule_ajax_example_add_more_remove_callback',
        'wrapper' => 'js-ajax-elements-wrapper',
      ],
      '#weight' => 50,
      '#attributes' => [
        'class' => ['button-small'],
      ],
      '#name' => 'remove_event_url_' . $delta,
    );
  }

  $form['mymodule_ajax_events']['add_event_url'] = array(
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => ['mymodule_ajax_example_add_more_add_one'],
    '#ajax' => [
      'callback' => 'mymodule_ajax_example_add_more_add_one_callback',
      'wrapper' => 'js-ajax-elements-wrapper',
    ],
    '#weight' => 1,
  );
    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#weight' => 100,
  );

  return $form;
}

function mymodule_ajax_example_add_more_remove($form, &$form_state) {
  $delta_remove = $form_state['triggering_element']['#parents'][1];
  $k = array_search($delta_remove, $form_state['field_deltas']);
  unset($form_state['field_deltas'][$k]);

  $form_state['rebuild'] = TRUE;
  drupal_get_messages();
}

function mymodule_ajax_example_add_more_remove_callback($form, &$form_state) {
  return $form['mymodule_ajax_events'];
}

function mymodule_ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['field_deltas'][] = count($form_state['field_deltas']) > 0 ? max($form_state['field_deltas']) + 1 : 0;
  //mymodule_ajax_example_add_more_validate();
  $form_state['rebuild'] = TRUE;
  // drupal_get_messages();
}

function mymodule_ajax_example_add_more_add_one_callback($form, $form_state) {
  return $form['mymodule_ajax_events'];
}

function mymodule_ajax_example_add_more_validate($form, $form_state) {
    dpm($form_state);
  foreach ($form_state['values']['mymodule_ajax_events'] as $key => $item) {
      //dpm($item);
      dpm($item['event_url']);
   if (!empty($item['event_url'])) {
      if (!preg_match('/https:\/\/example.com.*/i', $item['event_url'])) {
        form_set_error("mymodule_ajax_events][$key][event_url", 'Enter a valid Event URL.' . ($key + 1));
        //
      }else{
       drupal_set_message('URL ' . ($key + 1) . ' Created' );
   }
  }
 }
}

function mymodule_ajax_example_add_more_submit($form, $form_state) {
  $events_content = array();
  $events_count = 0;
  foreach ($form_state['values']['mymodule_ajax_events'] as $key => $item) {
    if (!empty($item['event_url'])) {
      $events_content[] = $item['event_url'];
      $events_count++;
   }
 }
  variable_set('mymodule_ajax_example_content', $events_content);
  variable_set('mymodule_ajax_example_count', $events_count);
}

```

# Answer
If you want to omit the submit button altogether, you need to move the logic of the validate and submit to the ajax callbacks.

First, remove the submit button:

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

```

Now you can take the logic from `mymodule_ajax_example_add_more_validate` and from `mymodule_ajax_example_add_more_submit` to the various ajax callbacks.

Each time the user interacts with the ajax buttons, you must validate the data and if all goes well, rewrite the variable to the database, because as far as we concern, this was the last interaction the user has with this form.
> 0 votes

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


# Question
Title: Use JSON instead HTML for access denied on some custom paths
I create a small API for one project using Bathic Authentication. The API consists of some custom paths defined in routes in a custom module. Using JsonResponse() in the controller we send back a JSON object with data.

But in case the user does not have permissions to access the path the route gives back the 404 HTML page. How can I tell Drupal to return a JSON object for my API paths under every circumstances?

Another example: we defined just to accept GET in the route. Using POST will return a HTML error page - we want Drupal to send back JSON with error information.

# Answer
Drupal returns the 404 in the format requested, so adding the query string `?_format=json` to the request should return a JSON response under any circumstances. If Drupal doesn't detect the format it uses HTML by default. You could either help Drupal detecting the format in a request subscriber or implement an exception subscriber to return JSON exceptions similar to ExceptionJsonSubscriber::on4xx for your API paths.
> 2 votes

---
Tags: routes, 8
---


# Question
Title: what are the disadvantages of adding <script> in tpl file
I want to add in theme template . Are there any disadvantages using scripts inside a drupal template tpl.php file.?

# Answer
It depends:

* Is it your own theme? (sub-theme from contributed theme usually) - If not, you better not hack it. (you changes will be deleted next time you will update the theme)
* Assumes above as yes, do you have many templates files?
* Is it a "root" template? like `html` or `page` or is it more in depth like `node`, `search-result` and so on?

The disadvantages:

* You must copy-paste this script to all overriding template files if template suggestions, suggest another variation of the template. (e.g `page.tpl.php`, `page--front.tpl.php`, `page--node--article.tpl.php`
* You must make sure manually, this script does not appear twice in different places.
* Take into consideration this script will go in any page users can see. (e.g search results page, taxonomy index, node pages, views pages, user login/registration pages.) - If it is not necessary in all pages, this is bad practice.
* Performance wise, the JS aggregation feature will not work for this script, so this means one more request from the client.
> 3 votes

---
Tags: 7, theming
---


title: Drupal Mollie Payment no rules trigger

text:
# Question
Title: Drupal Mollie Payment no rules trigger
We are working on a drupal ecommerce subscription service.

Modules: Commerce, Commerce Mollie, Payment etc..

Everything works 99%.

After finishing the payment the user needs to get the right role + a message.

This works with the default test creditcard payment.

But the commerce mollie integration module, is not triggering any rule after finishing the payment.

This is a real problem for us.

***Screenshots:***

**UPDATE**

https://www.drupal.org/project/mollie\_payment https://www.drupal.org/project/payment\_commerce https://www.drupal.org/project/payment

I would love any help, if there is information missing tell me!

Thank you guys.

# Answer
> 0 votes
You need to use event named `order_paid_in_full`.

the mollie module does not take of that, it just create the transactions. (take a look at `payment` tab in the order)

So you have two options:

* Create you own rule, based on the event above, and grant the user the role.
* Use commerce\_license module - it has a role module, and this is what you need.

---
Tags: 7, commerce, rules, payment-gateways
---


title: Add paragraph domains to media View

text:
# Question
Title: Add paragraph domains to media View
I'm using media and domain modules. Nodes are assigned to multiple domains and there are image fields that link to media images on those nodes. Some content types also use paragraphs and these paragraphs hold their own image fields, referencing media images.

The media view (/admin/content/media) provides some nice information out of the box and I have added a relationship to the image field used on nodes which allows me to add a field for Affiliate domains for the nodes that hold these images. This adds a list of domains for each media image (used on nodes) to the media View.

I need to display the same information for the image fields used in paragraphs. I can add a relationship to these paragraph image fields but that doesn't add an available field that would allow me to display the domains these paragraphs are assigned to. I guess that has to do with config entities not mixing very well with the domain module and Views.

What would the best way to add this field to the media view? A custom field handler seems to be the best bet but it seems that a query is needed to get the domains to which each node (holding a paragraph that holds an image field) is assigned to.

What's the best strategy to get this custom "computed" field into my view?

# Answer
A newly developed module, Media View Addons, provides just that.
> 0 votes

---
Tags: views, 8, media, domain-access, paragraphs
---


# Question
Title: Using template on subsite for certain node type
I am using a custom Theme in a multisite setting. With the help of @leymannx I implemented hook\_theme\_suggestion\_HOOK\_alter to insert a page Template with the following naming convention: page--NAMEOFSUBSITE.html.twig

See here

If I try to do the same for the node of my content type, which is using a template named node--CONTENTTYPENAME.html.twig at the moment, I can insert a name suggestion node--NAMEOFSUBSITE.html.twig, which will then be used for ALL nodes. I'd like to insert a suggestion such as node--CONTENTYPENAME--NAMEOFSUBSITE.html.twig, for only this one nodetype.

How can I do that?

Thanx in advance!!

# Answer
Activate twig debug and use the browser inspector to see the template precise name available for your content-type Do a cache rebuild when the temaplte is created to make it happen.
> 0 votes

# Answer
MYTHEME\_theme\_suggestions\_node\_alter() should look somewhat like this:

```
function MYTHEME_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $site_path = \Drupal::service('site.path');
  $site_path = explode('/', $site_path);
  $site_name = $site_path[1];
  $type = $variables['elements']['#node']->getType();
  $suggestions[] = 'node__'.$type.'__' . $site_name;

}

```

I found this kint() inspecting the variables within the hook, then finding the methods defined on \['#node'\].
> 0 votes

---
Tags: theming, hooks, multi-sites
---


# Question
Title: Add state permissions and allow state changes
I'm using Workflow module. I want to give permission to a specific role to edit the content moderation state. I found these on permissions page but it's not working. After I update the role permission, he got "Access Denied"

# Answer
As far as I'm aware, there's no way to give permission to manage a specific state, nor workflow for that matter.

The only permission to cover these is `administer workflows` and it covers all workflows.

You can see this by looking the `content_moderation.routing.yml`

```
content_moderation.workflow_type_edit_form:
path: '/admin/config/workflow/workflows/manage/{workflow}/type/{entity_type_id}'
defaults:
  _form: '\Drupal\content_moderation\Form\ContentModerationConfigureEntityTypesForm'
  _title_callback: '\Drupal\content_moderation\Form\ContentModerationConfigureEntityTypesForm::getTitle'
requirements:
  _permission: 'administer workflows'

```

**EDIT** That is with the default permissions.
> 0 votes

---
Tags: 8, users, workflows, files
---


# Question
Title: How to add an image field to a custom fieldtype?
I see that there is an ImageType field, machine name `'image'`, with a namespace of `Drupal\image\Plugin\Field\FieldType`. However, I can't seem to make use of it when creating a custom field and defining the property in the `FieldType` class.

I tried putting `DataDefinition::create('image')` but this later causes an abort complaining about the field type not existing, and I notice that the namespace is not referenced.

What are the correct types to use for an image field in the property section of the `FieldType`, in the schema of the `FieldType`, and in the `FieldWidget`?

```
Exporting an image field config from a bundle yields:
uuid: eecbe6e5-89d5-4708-b9c9-79f77b3cedf8
langcode: en
status: true
dependencies:
  module:
    - file
    - image
    - node
_core:
  default_config_hash: SkXIPKZYiIMMtnBmfnxk58RYfbZ8cHSw5NZPY_JByME
id: node.field_image
field_name: field_image
entity_type: node
type: image
settings:
  uri_scheme: public
  default_image:
    uuid: null
    alt: ''
    title: ''
    width: null
    height: null
  target_type: file
  display_field: false
  display_default: false
module: image
locked: false
cardinality: 1
translatable: true
indexes:
  target_id:
    - target_id
persist_with_no_fields: false
custom_storage: false

```

and looking at the image module's fielditem:

```
 * @FieldType(
 *   id = "image",
 *   label = @Translation("Image"),
 *   description = @Translation("This field stores the ID of an image file as an integer value."),
 *   category = @Translation("Reference"),
 *   default_widget = "image_image",
 *   default_formatter = "image",
 *   column_groups = {
 *     "file" = {
 *       "label" = @Translation("File"),
 *       "columns" = {
 *         "target_id", "width", "height"
 *       },
 *       "require_all_groups_for_translation" = TRUE
 *     },
 *     "alt" = {
 *       "label" = @Translation("Alt"),
 *       "translatable" = TRUE
 *     },
 *     "title" = {
 *       "label" = @Translation("Title"),
 *       "translatable" = TRUE
 *     },
 *   },
 *   list_class = "\Drupal\file\Plugin\Field\FieldType\FileFieldItemList",
 *   constraints = {"ReferenceAccess" = {}, "FileValidation" = {}}
 * )
 */

```

# Answer
The image field type has no property `image`, the main property is `target_id` inherited from the file field type. The easiest way to define a custom image field would be to extend the three core image field classes another time, now in the namespace of your module.

See how `ImageItem` defines a new compound field by extending `FileItem` overriding `propertyDefinitions()` unsetting two properties and adding four new image specific properties.

An alternative solution would be Paragraphs, more overhead (while a compound field stores the data of all fields in one table, Paragraphs needs a table for each field and also for the paragraph entity itself), but it provides unlimited nesting of field types.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How to change rest export views field alias programmatically
When using REST export view, and Fields format, under Settings I can change alias for each field.

How can I do the same with code?

# Answer
You can create a ViewsField Plugin with the custom module and name whatever you want.
> 0 votes

---
Tags: views, 8
---


# Question
Title: Filter three views blocks by the same filter
Is there a possibility to filter three separate views blocks by one filter form.

Basically the Idea is:

Filter:

Text field

Date field

Search button

And below we show

First views block **Upcoming**

Second views block **Current**

Third views block **Past**

Whatever we select in the filter is affecting these three blocks. And there are corresponding orderings for each block.

Another complication:

Each block can have a grouping by type:

Example:

**Upcoming:**

**type 1:**

data 1

data 2

data 3

**Type 2:**

data 2

data 23

data 24

And the same is for **Current** and **Past**

# Answer
> 0 votes
Views Attachment Displays are the way to go, because they are like Blocks but have special options for accepting contextual or exposed filters from the View they are attached to.

Create a Views Page Display with your Text and Date exposed filters, and show Upcoming information there (through the usual Filters).

In the same Views create a new Display of type Attachment. In the Attachment settings set:
**Attach to** the **Page** from the previos step,
**Attachment position** to **After**
**Inherit exposed filters** to **Yes**
Override the Filters to display Current info, and override fields if they are different from the default

Repeat the procedure for adding another Attachment, only this time for the Past information.

You can override the Fields, Filters and Sorting individually for each of those individual displays, while Exposed filters will be applied to all at the same time.

Format can also be overriden for each display. Just make sure you first set it to "This attachment (override)" and Save, even if you have to save the same Format (Table for example). Then under Format settings select your Grouping fields. Although IIUC the Grouping field will be the same in all displays.

The Page you created will show all 3 views results, one below the other, and all will react to the Exposed filter, assuming your 3 different structures share those same fields you have exposed.

---
Tags: views
---


# Question
Title: How to programmatically get the difference between two entities of same content type?
I need to implement a function that checks if there has been a change from the previous existing node. If yes, send the updated changes.

I understand that Drupal has revision system and through diff we can see the difference between two revisions.

I want similar to that, however as an API call or a logic which can facilitate getting the difference.

# Answer
Either look at:

To easily "see" if changes exist. Or look at Migrates module `track_changes` implementation and implement it in code between revisions. All `track_changes` does is `hash` the fields of a content type together to get a unique ID. Different revisions of a node with changes between the `body` field will of course hash to a different value. Be sure to exclude node fields such as NID, vid, updated\_at and other fields that (may) chnage between revisions.

Sample hash code from class MigrateSource:

```
// When tracking changed data, We want to quietly skip (rather than
// "ignore") rows with changes. The caller needs to make that decision,
// so we need to provide them with the necessary information (before and
// after hashes).
if ($this->trackChanges) {
    $unhashed_row = clone ($row);
    // Remove all map data, otherwise we'll have a false positive on the
    // second import (attempt) on a row.
    foreach ($unhashed_row as $field => $data) {
      if (strpos($field, 'migrate_map_') === 0) {
        unset($unhashed_row->$field);
      }
    }
    $row->migrate_map_original_hash = isset($row->migrate_map_hash) ?
      $row->migrate_map_hash : '';
    $row->migrate_map_hash = $this->hash($unhashed_row);
  }
  else {
    $row->migrate_map_hash = '';
  }

```
> 1 votes

# Answer
I wanted to know if there were any changes whenever a node gets updated. If yes, trigger the mail. The solution below works well for me (It could be improved though). I didn't try to get the exact difference, which however can be found using `field_get_items()` api.

```
$entity_old = entity_metadata_wrapper('node', $node->original);
$entity_new = entity_metadata_wrapper('node', $node);
// Fields comprising of field names array, whose changes you want to ignore
$ignore_fields_list = ignore_fields_list();
if(!is_object($entity_old)) {
  return;
}

$data = field_info_instances('node' ,$entity_new->getBundle());
$fields_list = array_keys($data);
$diff_list =  array();
foreach ($fields_list as $key => $field_name ) {
// Ignore if field name belong to ignore list
if(in_array($field_name, $ignore_fields_list )) {
  continue;
}

$old_value = $entity_old->{$field_name}->raw();
$new_value = $entity_new->{$field_name}->raw();
// If both are empty - ignore
if(empty($old_value) && empty($new_value)) {
  continue;
}
 // If one of the value is not empty compared to the other
if( (empty($old_value) && !empty($new_value) ) || (empty($new_value) && !empty($old_value))){
  // You can use field_get_items() to get the changed value.
  $diff_list[$field_name] = $data[$field_name]['label'];
  continue;
}

if(!is_array($new_value) && $new_value != $old_value) {
  $diff_list[$field_name] = $data[$field_name]['label'];
  continue;
}

if(is_array($new_value) && is_array($old_value)) {
  $diff = array_merge(array_diff($new_value, $old_value), array_diff($old_value, $new_value));
  if(!empty($diff)) {
    $diff_list[$field_name] = $data[$field_name]['label'];
  }
}
}

return $diff_list;

```
> 0 votes

# Answer
Amit's answer is super helpful, thanks for that. But there *is* one major error:

$diff = array\_diff($new\_value, $old\_value);

PHP's array\_diff will only tell you about values that are in the first param that are not in the second param. So, if we are updating a node and we *delete* (instead of *add*) a new value i na field, array\_diff will not notice this and the node will not be marked by this code as changed (assuming that is the only change).

Instead, that line should be changed to:

$diff = array\_merge(array\_diff($new\_value, $old\_value), array\_diff($old\_value, $new\_value));

I tested this locally, successfully.

I picked up that array\_merge tidbit from https://stackoverflow.com/questions/10077840/difference-between-two-arrays

I don't have enough rep to comment on the post, but I *can* edit it, subject to moderation, so I will do that.
> 0 votes

---
Tags: entities
---


# Question
Title: How to wrap views-view-fields.html.twig with html container element?
I have a block view with an image field.

I know how to theme this field :

```
views-view-fields—my-images.html.twig

```

How can I wrap this loop with an element like : `<div class="slider-article">`

I’ve tried different solutions without success.

Theme the block twig template :

If I use `block--views-block--slider-images.html.twig`

Of course it doesn’t work because there is no possibility to theme the field inside this twig template.

I’ve tried to add my wrapper in the header and footer option in the view but even if it works, it is not perfect since I need to have a better control on the html (I’m doing a slick slider, I know there is a module but I don’t want to use it).

I’m trying to do something I can do in node :

In `node—lorem.html.twig` :

```
{{ content.field_my_images }}

```

In `field--field-my_images.html.twig`

```
<div class="slider-article">

    {% for item in items %}

        <div>

            {{ item.content }}

        </div>

    {% endfor %}

</div>

```

I’ve also checked all the "rewrite results" options in view but didn’t manage to add a wrapper.

I prefer a solution where I can create my custom html strcucture like the above example with a loop.

**EDIT**

Here is the HTML structure I need :

```
<!-- How can I add this wrapper ? -->
<div class="slider-article">
  <!-- views-view-fields--[view-name]--[machine-name].html.twig starts here ! -->
  <div>your content</div>
  <div>your content</div>
  <div>your content</div>
  <!-- END OF views-view-fields--[view-name]--[machine-name].html.twig -->
</div>

```

# Answer
**Option 1**

You can by copying (the entire code) from core **views-view.html** and paste it in your theme's template folder and rename it **views-view--\[view-name\].html.twig** and then add your class to this template file.

replace `{{ rows }}` with

```
<div class="slider-article">
{{ rows }}
</div>

```

**Option 2**

Copy from core views-view-fields and paste it in your theme's template folder, rename it **views-view-fields--\[view-name\].html.twig**

Then add your div with class before `{% for field in fields -%}` and add close tag after `{%- endfor %}`

**Option 3** (maybe)

You can add it via the Views UI by clicking on "None". But this will add the wrapper to the entire view, which you may not want.
> 1 votes

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


title: Using ajaxComplete in view pagination

text:
# Question
Title: Using ajaxComplete in view pagination
I have (drupal 7) **view** where I have **pagination with Ajax** enabled. When any pager item is clicked I want to perform certain thing **after the view is reloaded with ajax**. I am trying the following code:

```
(function($){
Drupal.behaviors.myBehavior = {
    attach: function (context, settings) {
    $(document).ajaxComplete(function( event, request, settings ) {
        console.log("Ajax Completed");
    });
   }
 };

})(jQuery);

```

There is no output form console.log(). What am I doing wrong ?

# Answer
> 0 votes
I found a solution here. Based on @djayp34's answer, this is how I achieved what I wanted.

Basically the idea is: Drupal does not support adding a JS snippet through `drupal_add_js()` or any other function at **AJAX callback**. So what we are doing here is:

**Step 1:** We register/load that particular JS code during normal page load. In template.php:

```
function MYTHEME_preprocess_html(&$vars) {
  drupal_add_js(
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status){
       //The JS code that needs to be called after completion of ajax
      }',
      'inline'
     );
}

```

**Step 2:** We call that JS code when we want it. Here we want it to be called during AJAX callback.

In module file.

```
function MYMODULE_views_ajax_data_alter(&$commands, $view){
  if($view->name == 'MY_VIEW'){
    $commands[] = array("command" => 'myFunction');
  }
}

```

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


# Question
Title: Where is the result of the query is stored?
I have created a view page and a block. I need to get the query from the view block. The query preview can be seen.

The following code was found to fetch the query from view

```
function status_update_views_pre_execute(&$view) {
 if ($view->name == 'project_initiative') {
   $query = (string)$view->build_info['query'];
   echo $query;
 }
}

```

Where is the result of the query stored? How can I fetch it?

OR

the query is as follows

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, 'node' AS field_data_body_node_entity_type, 'node' AS field_data_field_project_name_node_entity_type FROM  {node} node LEFT JOIN {field_data_field_project_name} field_data_field_project_name ON node.nid = field_data_field_project_name.entity_id AND (field_data_field_project_name.entity_type = 'node' AND field_data_field_project_name.deleted = '0') WHERE (( (field_data_field_project_name.field_project_name_target_id = '55' ) )AND(( (node.status = '1') AND (node.type IN  ('status_update')) ))) ORDER BY node_created DESC LIMIT 10 OFFSET 0

```

How can I execute it to get the result in drupal custom module?

# Answer
You could get the nids like this:

```
// load and display view
$view = views_get_view('view_name');
$view->set_display('block_1');
$view->execute();
$nids = [];
// get all nids from the result
foreach ($view->result as $result) {
   $nids[] = $result->nid;
}
// render view
print $view->render();

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Suggestions for storing private user content lists
I have a feature on my Drupal7 site where users can store a list of personal stock symbols (NYSE, NASDAQ, etc) and then do different actions on that list; quote, chart, etc. These lists are private to each user. For the first iteration, using a custom module, I've stored them in a custom table after the user enters them using the Drupal Form API. The form has a text box for list title, and a text area for entering symbols separated by space or comma. They can have multipe lists by clicking a 'add more' button. The data is stored in a flat structure of "-list\_title1 sym1 sym2... -list\_title2 sym1 sym2..." It is then split out for use in the UI. Some users have more than 300 symbols.

For the second iteration I would like to be able to store these symbols so that they can be referenced individually (deleted or added, notes about symbol) and the lists sortable. I would like to be able to utilize Views and features like Draggable\_views so that the symbols could be re-orderd in a list. I would like users to be able to add symbols to their list from other content eg: news, trending symbols, symbol lookup.

There's a reference to $user-\>data in this Drupal8 article but I couldn't find more details on it. https://www.webomelette.com/storing-user-data-such-preferences-drupal-8-using-userdata-service The user\_save api may work but I'm not sure how you would store this two-level data structure. https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_save/7.x

I could not find any contrib modules for storing this data privately other than Profile2 which I don't think would work for this kind of content. I'm looking for Drupal APIs to store this data on a per-user basis.

# Answer
> 2 votes
You could use ECK and link it to the user using Entity Reference. You'll need to some small custom coding to auto fill the entity reference field with the logged in user's id. Better yet, you can use Rules for a no code solution to autofill the entity reference with the logged in user ID.

Here is a video on ECK and for entity reference.

---
Tags: 7, nodes, users, views
---


# Question
Title: How to send comma separated taxonomy term (as link to taxonomy term url ) from preprocess to twig file as single variable?
According to my requirements I have to use views preprocess and views-view.html.twig

```
function MYTHEME_preprocess_views_view(array &$variables) {

  $aliasManager = \Drupal::service('path.alias_manager');

    if (isset($variables['rows'][0]['#rows'])) {
      $nodeValues = [];
      foreach ($variables['rows'][0]['#rows'] as $value) {

        $nodeValue['created'] = $value['#row']->_entity->created->value;
        $nodeValue['external_url'] = $value['#row']->_entity->field_url->uri;
        $nodeValue['title'] = $title = $value['#row']->_entity->title->value;
        $nodeValue['nid'] = $title = $value['#row']->_entity->nid->value;
        $nodeValue['tid'] = $value['#row']->_entity->field_topic->entity->tid->value;

        // section referenced to node
        $nodeValue['section'] = $value['#row']->_entity->field_topic->entity->name->value;

        $topics = "";
        foreach($value['#row']->_entity->field_topic2 as $val){
          $topics != "" && $topics .= ", ";
          $topics .= $val->entity->name->value;
        }

        $nodeValue['topics'] = $topics;

        $nodeValues[] = $nodeValue;

      }

      $variables['node_values'] = $nodeValues;
    }

 }

```

In twig file :

```
{% for value in node_values %}
        <div class="link_full">
            <div class="title"><a href="{{ value.external_url }}"> {{ value.title }} </a>
            </div>
            {% if logged_in %}
                {% if 'premium' in user.getroles %}
                    <div class="link_details">
                        <div class="timestamp"><a href="{{ path('entity.node.canonical', {'node': value.nid}) }}">{{ value.created|date(format='y-m-d H:i') }}</a>
                        </div>
                        <div class="topics">{{ value.topics }}</div>
                    </div>
                {% endif %}
            {% endif %}
        </div>
    {% endfor %}

```

Out put is like below :

Everything is working fine but I need to create Links of terms in above screenshot. And in code its TOPICS in preprocess function.

I have tried various ways to create it as link but that does not work as it just print a tags as html but not links. Please suggest.

Thanks!

# Answer
> 0 votes
I have solved this like below :

It was always considered as string so I have to send topics in from of array like below:

```
$topics = array();
foreach($value['#row']->_entity->field_topic2 as $val){
  $topics[$val->entity->tid->value]= $val->entity->name->value;
}

```

And then in Twig I made links from them and it worked.

```
<div class="topics">
    {% for key,item in value.topics %}
        <a href="{{ path('entity.taxonomy_term.canonical', {'taxonomy_term': key}) }}">{{item}}</a>
        {% if not loop.last %},{% endif %} # for adding commas after each term
    {% endfor %}
</div>

```

---
Tags: 8, theming, uri
---


# Question
Title: What is the proper way to cache a http header tag?
I find examples of adding a header meta tag, such as using an event subscriber or using hook\_page\_attachments.

The problem I have is that both of these methods add the tag only in the case of an authenticated user request. The anonymous cache work is done way before either of these methods fire, and even if I could force my change to a higher priority, I don't know that I would want that to happen on every anonymous page request.

In detail, when I subscribe to the response event, and set the header tag, it appears on the rendered page for an authenticated user. However, that tag is apparently not added to cache, because any subsequent anonymous requests do not include that tag. I'm assuming, then, that I need to trigger some mechanism to have the tag added to cache and not simply injected in the header during rendering.

What I want to do is persist a header meta tag in cache so that is included in anonymous requests. The tag value is based on a node field that only needs to be cached when it changes, so the node save event would be the ideal time.

What is the proper way of getting a custom header meta tag into the cache for a specific node?

Here is the code of my subscription, which fires for authenticated traffic, but is not persisted in cache:

```
namespace Drupal\my_http_injector\EventSubscriber;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Url;class MyHttpInjector implements EventSubscriberInterface {

    /**
     * Trigger pulled
     */
    public function onRespond(FilterResponseEvent $event) {
        $response = $event->getResponse();
        // Get the response attachments

        if (is_object($response)) {
            if (method_exists($response, 'getAttachments')) {
                $attachments = $response->getAttachments();
                if (is_array($attachments) &&
                    isset($attachments['drupalSettings']) &&
                    isset($attachments['drupalSettings']['path']) &&
                    isset($attachments['drupalSettings']['path']['currentPath'])) {
                    // Get the requested path
                    $path = '/' . $attachments['drupalSettings']['path']['currentPath'];
                    $params = Url::fromUri("internal:" . $path)->getRouteParameters();
                    $entity_type = key($params);
                    if ($entity_type == 'node') {
                        $node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);
                        if (is_object($node)) {
                            $date = gmdate(DATE_RFC1123, $node->getChangedTime());
                            $response->headers->set('Last-Modified', $date);
                        }
                    }
                }
            }
        }
                                                                                }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        $events[KernelEvents::RESPONSE][] = ['onRespond'];
        return $events;
    }

```

# Answer
> 1 votes
Add the header in an event subscriber

```
  public function onKernelResponse(FilterResponseEvent $event) {
    $response = $event->getResponse();
    $node = $this->routeMatch->getParameter('node');
    // if you don't have injected $this->routeMatch use \Drupal::routeMatch()
    if ($node && $node instanceof NodeInterface) {
      $date = gmdate(DATE_RFC1123, $node->getChangedTime());
      $response->headers->set('Last-Modified', $date);
    }
  }

```

and it will get cached for authenticated and anonymous requests.

If you use additional dependencies add them to the response as well:

```
  if ($response instanceof CacheableResponseInterface) {
    $response->addCacheableDependency($entity);
  }

```

This is not necessary in this case because the rendering of the node has already added the cache data.

---
Tags: meta-tags
---


title: How to link to login page?

text:
# Question
Title: How to link to login page?
I am trying to do something a priori simple.

I wish in a template to add a link to the login page.

I found this documentation, so I know how to link to a node etc. but to a url type "/ login", I did not find.

Do you know how to do it ?

# Answer
> 3 votes
You can use the `link` function and the route for the login page (`user.login`), e.g.

```
{{ link('Login', 'route:user.login') }}

```

---
Tags: 8, theming
---


# Question
Title: adding ckeditor color button and font size
I am new to drupal. I am using drupal 8.2.5, bartik theme and i would like to add font size&family and colour buttons to the ckeditor.

i installed the "CKEditor Font Size and Family" module, enabled it and then at "admin-configuration-content authoring-text formats and editors" i configured "Basic HTML" and "Full HTML" and drag the new available buttons of fonts and size to the toolbar. I saved it and then when i tried to add new content (article or basic page), the editor was completely gone, there was only the field of "summary" available to write something! When i disabled the module, the text editor was back to normal.

Later, I noticed at the module page that the installation process was the following:

1. Download the plugin from http://ckeditor.com/addon/font.
2. Place the plugin in the root libraries folder (/libraries).
3. Enable CKEditor Font in the Drupal admin.
4. Configure your WYSIWYG toolbar to include the buttons.

So I realised i hadn't followed step 2. I don't know where the libraries folder is, although i searched and have no experience how to create it correctly and how to place this plugin there. I read various posts on the internet but couldn't find a solution and then i ended up here. Thank you.

# Answer
> 1 votes
You have to create the folder yourself as the docs say.

You can do this with command line with `mkdir libraries` in the webroot (where the /core folder is), or with a window and New Directory (New Folder) in either Windows / OSX.

Your application structure will then look like...

```
/core
/libraries
/modules
/themes

```

and so on.

All thats left is to download the JS plugin from ckeditor.com (v 4.5.x), unzip it, and place it in the libraries directory.

# Answer
> 0 votes
Check the console in your browser for any errors. In my case I hadn't added the panelbutton addon at the /libraries folder

# Answer
> 0 votes
1. So you have created the Drupal/libraries folder. Ensure that you have downloaded and placed the library inside the library folder and the corresponding module in the Drupal/modules folder. (i had once copied module to library and viceversa). Try clearing the cache (Configuration-\>Performance-\>Cache) and run Configuration-\>Cron once.
2. You have mentioned that the editor is gone. This happens when there is a bug in the module. It happened with me for the 'color button' module. Search Configuration-\>reports to find the exact error. Once you get the error, you can search in this forum and I am sure a patch will be available for it.

# Answer
> 0 votes
a.Download the plugin from http://ckeditor.com/addon/font. b. enable that plugin. c. Enable CKEditor Font in the Drupal admin. d. Configure your WYSIWYG toolbar to include the buttons.

---
Tags: 8, wysiwyg, theming
---


title: See Which User Created/Edited Block?

text:
# Question
Title: See Which User Created/Edited Block?
Is there any way in Drupal 7 to view which user last made edits to a particular block, or who created the block?

# Answer
> 1 votes
STEPS: 1. Start creating a new view by clicking "Add new view" link under Admin \> Structure \> Views.

2. a) Type "Other Contents by Author" in "View name" text box. b) \[Optional step.\] You can check "Description" checkbox and write a description for view. If you wish, check and write "A list which contains other content by author."

3. Select "Content" from the "Show" select list.
4. Uncheck "Create a page".
5. Check "Create a block". You can enter any block title you wish. To limit the items shown in block, type a number in the "Items per page" text box. (You can change it later.)
6. Click "Continue & edit". At this stage, it is a good idea to click the "Save" button after each alteration/change to save the View.

7. a) Click the "Advanced" link in right side of the page (if the pane is not open). b) Click the "add" link in CONTEXTUAL FILTERS row. c) Check the "Content: Author uid" checkbox from the "Add contextual filters" popup. d) Click "Apply..." button. e) Check "Provide default value" option in the WHEN THE FILTER VALUE IS NOT AVAILABLE section. f) Select "User ID from URL" from the "Type" select list. g) Check "Also look for a node and use the node author" checkbox. h) Click "Apply..." button.

8. a) Click "add" link again in the CONTEXTUAL FILTERS row. b) Check "Content: Nid" checkbox from the "Add contextual filters" popup. c) Click the "Apply..." button. d) Check "Provide default value" option in the WHEN THE FILTER VALUE IS NOT AVAILABLE section. e) Select "Content ID from URL" from the "Type" select list. f) Scroll down to the MORE section and check the "Exclude" checkbox. g) Click the "Apply..." button.

9. Click the "Save" button and save the view.

You can add different fields and filters and make changes to create solutions for different needs.

---
Tags: 7, users, blocks
---


# Question
Title: Concatenation with %keyword in mini-panels
Someone posted another question How does one concatenate fields in title field in Panels (Pages)? but its not working for me.

I need to concatenate a custom text as prefix with %node:field\_city\_title keyword while adding a node field in min-panels.

I tried with `Event in %node:field_city_title` , `Event in%node:field_city_title` and searched a lot but nothing works for me.

If you any idea, let me know

# Answer
> 2 votes
I've figured out but not sure either it's a standard way or not but I believe override title field is not accepted "prefix or postfix" for `%keyword` like mentioned in the question.

**Solution**

1) Removed tag h1 from the attached image in the question.

2) Created new tpl named as `panels-pane--event-node-title.tpl.php` and added some code in it

```
<div class="pane-content">
  <?php if ($title): ?>
  <h1> <?php print $title; ?> </h1>
  <?php else : ?>
    // Here we can set any prefix or postfix within the tag
    <h1> Event in <?php print render($content); ?> </h1>
  <?php endif; ?>
</div>

```

**$content** variable will get content of the field along with its all settings (ID, class, tag etc.)

I hope this will help someone.

---
Tags: 7, panels
---


# Question
Title: How to call the implemented hook_profile2_access() function?
I'm rather inexperienced in module development, sometimes I have really basic issues: I'd like to grant custom access to user profiles. I think I can do it with the implementation of hook\_profile2\_access() (profile2 and profile2\_og\_access submodule use such implementations)

I added the `mymodule_profile2_access()` to my module but I don't know how/when it would be called?

# Answer
Well, it was a typical user error: The implemented `mymodule_profile2_access()` function is called only for non-admin users and I checked it with administrator. So simple...
> 0 votes

---
Tags: hooks
---


# Question
Title: How to change filed type from integer to string
using D8. I have a field `field_number` just in one bundle (a node content type that I called `law`). Now I found that I need to change the field type; it needs to be of type `string` and not `integer`.

I wonder if there is a quick/easy way of using migrate or something similar

I remember that time ago I used VBO in D7 but seems that the PHP option is not available in the D8 version of the module. Like in this case: https://drupal.stackexchange.com/a/28349/5422

I'll like to try using a `hook_update_n` on a custom module like in this example: How do I change a field type? but not sure if the the new field (as is created programatically) will be easily available for views and other modules and I don't want to end with a mess.

# Answer
> 0 votes
I ended up following this path. The reason I opened a new question was to see if there were any module or alternative to custom code.

My main concern was that the example was converting text to text and not number to text, but after executing some code using devel + webprofiler + kint (locally) I was able to see that even that same code was going to do the trick as the schema is affected only when needed.

For anyone looking at this same issue: take in mind that after running the custom code via the update process you will need some manual steps: recreate some views (when the field is used) and reconfigure the form display, presentation and so on of the bundles that are using the field.

As I have configuration of the site in git, my path was running the code locally, reconfigure the corresponding views, form displays, etc and then export the configuration, commit and push; then on production ran the upgrade and then import the config; it was pretty clean except that some views that have menu links assigned I had to manually edit its ordering.

---
Tags: 8, entities, hooks
---


# Question
Title: Feeds importing unique nodes over and over
I'm trying to import events to a calendar from an external ics.. I installed the Calendar module with the Feeds module. Unfortunately it creates the whole time new nodes. Even if the UID is unique (mapped to field field\_gimme\_uid) in the node. Update nodes is setted 'on'. I have checked everything but everything seems alright. The unique field is correctly imported (and the same for multiple nodes)..

I have a **contenttype "Evenement"** with the following fields:

* Evenement (title)
* Datum (field\_event\_date) Date
* Gimme-UID (field\_gimme\_uid) Text

I have a **feed** that maps the ics import to the nodes

```
$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'ics_importer';
$feeds_importer->config = array(
  'name' => 'Gimme Agenda',
  'description' => 'Gimme agenda importeren van het account website',
  'fetcher' => array(
    'plugin_key' => 'FeedsHTTPFetcher',
    'config' => array(
      'auto_detect_feeds' => 0,
      'use_pubsubhubbub' => 0,
      'designated_hub' => '',
      'request_timeout' => '',
      'auto_scheme' => '',
      'accept_invalid_cert' => 0,
      'cache_http_result' => 1,
    ),
  ),
  'parser' => array(
    'plugin_key' => 'DateiCalFeedsParser',
    'config' => array(
      'indefinite_count' => '52',
      'indefinite_message_display' => TRUE,
      'until_not_utc' => FALSE,
      'skip_days' => NULL,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => '1',
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'SUMMARY',
          'target' => 'title',
          'unique' => 0,
          'language' => 'und',
        ),
        1 => array(
          'source' => 'DTSTART',
          'target' => 'field_event_date:start',
          'unique' => FALSE,
          'language' => 'und',
        ),
        2 => array(
          'source' => 'DTEND',
          'target' => 'field_event_date:end',
          'unique' => FALSE,
          'language' => 'und',
        ),
        3 => array(
          'source' => 'UID',
          'target' => 'field_gimme_uid',
          'unique' => TRUE,
          'language' => 'und',
        ),
      ),
      'insert_new' => '1',
      'update_existing' => '1',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 0,
      'bundle' => 'evenement',
      'language' => 'und',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '900',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 1,
);

```

**My modules**:

* Drupal 7.56
* Calendar module 7.x-3.5
* Date 7.x-2.10
* Date iCal 7.x-3.9
* Feeds 7.x-2.0-beta4

**My ICS** that I use to import can you find here

**Why is it importing the whole time the same nodes?**

# Answer
My bad! The **"Unique" option** in the feeds module isn't working without the **module "Field Validation"**. I added an unique rule to the contenttype "evenement" and now it works like a charm!
> 0 votes

# Answer
The "Unique" option in the feeds module is working out-of-the-box only with title field. If you're using another field - you need "field validation" module
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: How to force Feeds to import content? (Feeds too lazy to import every minute)
I've setup Feeds to import content every minutes. All settings was fine. Feed source contains only 1 rss item, and it changed every 1 or 2 minutes.

When I manually click "Import" tab, it will import nicely. But in many times, Feeds too lazy to import it.

By using cron, Is there any way I can force Feeds to import?

# Answer
> 2 votes
Check the minimum refresh period in your feeds setting; feeds will not import anything if the last import is more recent than that setting.

# Answer
> 1 votes
In the Feeds settings page, in the settings section, check the option 'Skip hash check' -Force update of items even if item source data did not change.

This will prevent the importer from checking for any change, and import every time.

I would also check that the import task is quick enough to happen every minute. Imports can take several minutes, and re-calling the import by the cron every minute may disrupt this.

# Answer
> 0 votes
Create drush command and add it in your crontab file on the server.

---
Tags: feeds
---


# Question
Title: How to hide webform block after submission for anonymous users?
I can not hide webform block by Per user submission limit.

I choose Per user submission limit = 1- \> ever, but block is shown.

How can I hide the block, if it was submitted?

# Answer
When a visitor submit a form, cookie with a name "webform-123" (123 - webform ID) save in his browser. In the block visibility settings use the cookie existence check with PHP:

```
<?php
$match = FALSE;
if(!isset($_COOKIE['webform-123'])) {
$match = TRUE;
}
return $match;
?>

```

If the cookie does not exist, the condition will return the TRUE and the block will be displayed.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: how can i make a twig node path variable multilingual compatible in a view template?
I have not found the path field in a view so i have added in my template for views\_view\_fields.

```
 <div class="cell small-12 event__link">
     {{ fields.view_node.content }}
 </div>

```

This provide the path to the content of the default language.

How can i make a twig variable node path multilingual compatible in a view template?

# Answer
how simple is that ?

```
  <div class="cell small-12 event__link">
      <a href="{{ path('entity.node.canonical', {'node': fields.nid.content|striptags|trim}) }}">
        {% trans %}Read more{% endtrans %}
      </a>
   </div>

```
> 0 votes

---
Tags: views, 8, i18n-l10n
---


# Question
Title: Node Access - Change ownership of node before loading
I'd like to change the ownership of a node before it loads on the edit page to essentially transfer ownership of a node from one person to another. My goal is to give multiple users access to a single node.

I was looking through the Node API hooks and I was hoping that I could use either hook\_load or hook\_node\_load and alter the `$node->uid` but both say this in the description:

> This hook should be used to add information that is not in the node or node revisions table, **not to replace information that is in these tables** (which could interfere with the entity cache).

So unfortunately I can't use those hooks.

I noticed that hook\_node\_prepare allows you to "act on a node about to be shown on the add/edit form", however, it looks like the node access hook already runs before that hook does, because I run into an "access denied" message.

My goal was to avoid having to control access to the node, and instead, just transfer ownership so that it can defer access control to the currently installed node access module (Taxonomy Access) and the "Edit Own Content" permission. I didn't want to add more custom logic or additional node access modules on top of our existing access modules because it's already complex as it is and not recommended.

Is this the right approach or should I just cave and use hook\_node\_access (or some other access hook)? I'm worried about the implications of adding another layer of node access to our already complex system, but if it's the best way to do it, I will.

# Answer
> 0 votes
One possible solution might be to add a User Reference field to the node and add the Users you want to grant access to. Then in `hook_node_access`, check for that field, and return the proper access for view/edit/delete. Don't forget the value of the author field too, to preserve the original functionality. Basically, if the current UID is in the list of referenced users, return TRUE.

I feel like I have done this in the past in 7, but can't locate any code examples at the moment.

---
Tags: 7
---


title: Rendering semantic HTML5 caption

text:
# Question
Title: Rendering semantic HTML5 caption
Is there a way to render HTML5 captions in Drupal 8? I've tried with embedding images and embedding media in the WYSIWYG, and I've also tried with media migrated from D7 to D8, but nothing works.

An image with a source like this in the WYSIWYG:

```
<img alt="mermaid" data-caption="actual photo of a mermaid" data-entity-type="file" data-entity-uuid="5b148b62-6890-4b90-98e6-63a2cad3fe70" src="/sites/default/files/inline-images/mermaid.gif" />

```

renders on the page like this:

```
<p>
  <img alt="mermaid" data-entity-type="file" data-entity-uuid="5b148b62-6890-4b90-98e6-63a2cad3fe70" src="/sites/default/files/inline-images/mermaid.gif" />
  actual photo of a mermaid
</p>

```

and a media entity with a source like this on the WYSIWYG:

```
<drupal-entity data-caption="this is the caption" data-embed-button="media" data-entity-embed-display="view_mode:media.large_480x480" data-entity-type="media" data-entity-uuid="7012b662-1430-4610-8fa3-65eede89f7ba"></drupal-entity>

```

renders on the page like this:

```
<div class="contextual-region row bs-1col media media--type-image media--view-mode-large-480x480">
  <div></div>
  <div class="col-sm-12 bs-region bs-region--main">
    <div>
      <a href="example.com/sites/default/files/field/image/groundhog_480x480.jpg">
        <img src="/sites/default/files/styles/large/public/field/image/groundhog_480x480.jpg?itok=1DapCxP0" alt="Photo of a groundhog" />
      </a>
    </div>
  </div>
</div>
this is the caption

```

with random `<div>` tags that hold nothing and the caption pulled entirely out of the relevant tag so its parent is actually the body field. Neither of these use HTML5 with a wrapping `<figure>` tag or even a `<figcaption>` or `<caption>` tag.

I found a suggested hack that uses the image's title tag as a caption, and the sandboxed Image Caption module uses jQuery to produce similar results, but my site is migrating hundreds of articles where the content team has used captions for image credits and we're legally required to display those, so we can't pretend the image title is the caption. Also, the way captions are currently being rendered doesn't allow us to style the them in a way that ties them to the image or separates them from the surrounding paragraphs, so they just blend in with the rest of the text.

I tried to dump the image's variables to the page, but there is no caption:

```
array:8 [
  "#theme" => "image_style"
  "#style_name" => "large"
  "#attributes" => []
  "#title" =>null
  "#uri" => "public://field/image/groundhog_480x480.jpg"
  "#width" => "480"
  "#height" => "480"
  "#alt" => "Photo of a groundhog"
]

```

so somewhere in the rendering process the caption is being removed from the image and rendered separately.

# Answer
Did you double-check that your Text Format (under /admin/config/content/formats) was set to allow the HTML5 tags for this? (See below) If you haven't then the filtering will remove those tags and replace them with `<div>` tags.

```
<figure>
<figcaption>

```
> 1 votes

# Answer
I am not sure if you are using the core Media module and Entity Embed / Media Embed for CKEditor, if you are, the way I do it is add the caption field to the media type (Image). I don't use any of the other core stuff (Image2 plugin?), as I prefer the Media/entity way.

In the theme (or module), I add a `hook_preprocess_field`:

```
  if ($variables['field_name'] == 'field_mymedia_image_field') {
    foreach ($variables['items'] as $key => $item) {
      $variables['items'][$key]['content']['#options']['attributes']['class'][] = 'custom_class_foo';
      $variables['items'][$key]['content']['#options']['attributes']['class'][] = 'custom_class_bar';
      $variables['items'][$key]['content']['#options']['attributes']['data-caption'] = 'Field value from Caption field';
    }
  }

```

^ This will add attributes to the image tag when the image field is rendered. I added two css classes as an example, and a `data-caption` attribute. You can't do this if you just have raw image tags in the WYSIWYG source. In that case you'd have to add the attributes manually in the source.

Note that your `$variables` structure may be slightly different than mine depending on your setup.

For the figure/figcaption part, using Media grants you twig templates (and you can add more suggestions as needed), but I also solve it there too (example, media--image.html.twig):

```
{% if content %}
    <figure{{ attributes.addClass(classes) }}>
      {{ content.image }}

      {% if media.field_credit is not empty or media.field_caption is not empty %}
        <figcaption class="hl__figure__figcaption">
          {% if media.field_caption is not empty %}
            <div class="hl__figure__text-caption">
              {{ content.field_caption }}
              {% if media.field_caption_link is not empty %}
                {{ content.field_caption_link }}
              {% endif %}
            </div>
          {% endif %}

          {% if media.field_credit is not empty %}
            <div class="hl__figure__text-credit">
              {% include "@mytheme/svg/media/caption_icon.html.twig" %}
              {{ content.field_credit }}
            </div>
          {% endif %}
        </figcaption>
      {% endif %}
    </figure>
  {% endif %}

```

I think there is some stripping going on during the processing of your data - which is why I think Media is the better route (entity render pipeline).

If you could adjust your Media migration to read attributes into field data, I think this is a good shot. It's been a while since I have done that, and can't find an example offhand.
> 0 votes

# Answer
This looks a lot like something you can control in the theme layer.

Turn on twig debug in your `service.yml` (sites/default/…) and it will tell you the template being used to generate that output, and the paterns needed to override it.

```
twig.config:
  # Twig debugging:
  #
  # When debugging is enabled:
  # - The markup of each Twig template is surrounded by HTML comments that
  #   contain theming information, such as template file name suggestions.
  # - Note that this debugging markup will cause automated tests that directly
  #   check rendered HTML to fail. When running automated tests, 'debug'
  #   should be set to FALSE.
  # - The dump() function can be used in Twig templates to output information
  #   about template variables.
  # - Twig templates are automatically recompiled whenever the source code
  #   changes (see auto_reload below).
  #
  # For more information about debugging Twig templates, see
  # https://www.drupal.org/node/1906392.
  #
  # Not recommended in production environments
  # @default false
  debug: true

```

Example output:

```
 <!-- THEME DEBUG -->
 <!-- THEME HOOK: 'image' -->
 <!-- BEGIN OUTPUT from 'core/themes/classy/templates/field/image.html.twig' -->
 <img src="…">
 <!-- END OUTPUT from 'core/themes/classy/templates/field/image.html.twig' -->

```
> 0 votes

---
Tags: theming, media
---


# Question
Title: Sorting in views not working for drupal commerce products
In the product views of my drupal commerce site, I want to list the products sorted by amount(price).

The product has 4 categories. They are added as relationships in the view:

Now to sort them by price, I am doing the following:

This is working perfectly fine in another view where I am using Contextual filters(Product category).

But in this view, where I am **displaying products of all categories**, the sorting is not working. What is happening in this case is:

* First all the **Poultry items** are coming in sorted(by price) order.
* Then all the **Fish items** in sorted(by price) order.
* And so on.

What I want is :

All Items should be collectively sorted by price.

# Answer
> 2 votes
This isn't working as configured because you're using separate product reference fields per content type. This instructs the query to attempt a sort based on non-existent values for those rows where the content type does not have the expected reference field. To sort this View properly, you'd need the base table to be the Products and then some sort of a reverse reference to content referencing those products.

# Answer
> 0 votes
I sorted my view using **hook\_views\_pre\_render()** and **array\_multisort()**.

```
function MY_MODULE_views_pre_render(&$view) {
      if($view->name == 'MY_VIEW'){
        $price_array = array();
        foreach($view->result as $key => $row) {
          $price = '0';
          if(isset($row->field_commerce_price[0])){
            $price = $row->field_commerce_price[0]['raw']['amount'];
          } elseif (isset($row->field_commerce_price_1[0])) {
            $price = $row->field_commerce_price_1[0]['raw']['amount'];
          } elseif (isset($row->field_commerce_price_2[0])) {
            $price = $row->field_commerce_price_2[0]['raw']['amount'];
          } elseif (isset($row->field_commerce_price_3[0])) {
            $price = $row->field_commerce_price_3[0]['raw']['amount'];
          }
          $price_array[$key] = $price;
        }
        array_multisort($price_array, SORT_ASC, $view->result);
      }
    }

```

---
Tags: commerce, views
---


# Question
Title: How do I troubleshoot unit tests using xdebug?
I have xdebug in a Vagrant box, based on VDD, set up and working correctly. Breakpoints trigger phpstorm and mostly works just fine. But when I enable the testing module and try to run a single test on `admin/config/development/testing` where a breakpoint in the test source code has been setup, nothing gets triggered. I am assuming that's because PHPUnit is using a separate process. I went though this but it's not helping much.

# Answer
I was unable to figure out why the debugger would not **initially** trigger for tests while it's triggered for other normal requests. Then I changed the `xdebug.remote_autostart = 0` to `xdebug.remote_autostart = 1` and it started working. I even changed it back to `xdebug.remote_autostart = 0` and it kept working.

I also found out that one can also temporarily enable the phpstorm `break at first line` by xdebug settings:

I presume there is not one answer fit all but hope this helps others.
> 0 votes

---
Tags: 8, testing
---


# Question
Title: How to programmatically truncate table in Drupal8
I'm wondering how to programmatically truncate a table in drupal8.

Like:

```
db_truncate('some_table');

```

Is this possible?

# Answer
> 14 votes
Sure, the function still exists: https://api.drupal.org/api/drupal/core%21includes%21database.inc/function/db\_truncate/8.5.x.

It's deprecated, though, with the advice:

> Instead, get a database connection injected into your service from the container and call `truncate()` on it. For example, `$injected_database->truncate($table, $options);`

If you're not in a context where injection is possible, get it from `\Drupal`:

```
\Drupal::database()->truncate('foo')->execute();

```

---
Tags: 8, hooks
---


# Question
Title: view content filtered by taxonomy children
I\`m having a view block displayed on node page. In this block i want to show only other nodes that have the same child taxonomy selected.

I tried with contextual Content: Has taxonomy term ID (with depth)

and those settings and is not working https://www.screencast.com/t/b8GJftJSanwA

The taxonomy looks like this

```
parent term1
- term1
- term2

parent term2
- term3
- term4

```

And on node are selects both parent and child.

Any ideas?

# Answer
> 0 votes
There are two parts to your question, showing only nodes that have child terms, and getting the Contextual filter to work.

## List only nodes that have child terms

This part of the question can be solved by using a regular Filter `Has taxonomy term` and then select only the 2nd level from the list with the Operator set to `is one of`.

The same applies if you add a filter `Content: YourTaxonomyField` instead of the `Has taxonomy term`.

## Contextual taxonomy filter

With the main filter taking care of the depth, you don't need the Depth one as the Contextual filter.

Add `Content: Has taxonomy term ID` as the Contextual filter. Your example didn't have it set up correctly. It should be:
When the filter value is NOT available
**Provide default value**
**Taxonomy term ID from URL**
Only tick **Load default filter from node page, that's good for related taxonomy blocks**
**Filter to items that share any term**
Under **More**
**Allow multiple values** if your nodes can be tagged with more than one term at a time.

Don't forget to place your Block and adjust Block settings for the Contextual filter.

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


# Question
Title: Views: Show only "Grouping Field" headings
I'm working on customizing a view that is displaying a content type. I need to build an attachment that shows available taxonomy terms on this content type.

In this attachment, I currently have the taxonomy term name displaying as a field for each returned instance of the content type.

Grouping the results by the taxonomy name field produces one instance of each term as an `<h3>` followed by one instance for each node that was returned:

```
TAXONOMY TERM 1 (Grouping Title, H3)
    taxonomy term 1 (term on node)
    taxonomy term 1 (term on node)
    taxonomy term 1 (term on node)
TAXONOMY TERM 2 (Grouping Title, H3)
    taxonomy term 2 (term on node)
    taxonomy term 2 (term on node)
    taxonomy term 2 (term on node)

```

Is there a way to just show the grouping without outputting the additional content? Something like:

```
TAXONOMY TERM 1 (Grouping Title, H3)
TAXONOMY TERM 2 (Grouping Title, H3)

```

This would produce exactly what I need but I can't figure out a good way to do this.

I've tried aggregation but this makes exposed filter inheritance for the attachment messy and unreliable.

Thank you!

# Answer
> 1 votes
Since you want to display all the terms possible, and not only those assigned to nodes, it doesn't make sense to build it through a Node View.

You can create a new View of type Taxonomy terms, create a block displaying Taxonomy terms, then place the Block in the Content region on your Views page (or any other region).

Alternatively you could also use a module to create the block listing Taxonomy terms: Taxonomy menu and again place the Block in a region and restrict it to show only on your node View page.

---
Tags: views, 8
---


title: Add a Block ABOVE view

text:
# Question
Title: Add a Block ABOVE view
I need to add short descriptions for some 20+ views and display them above the views. I know I have an option to add a header to a view, but that's not what I want. I have a sidebar on the left and the main content on the right which displays views on the views pages. I need to add different descriptions for my views ABOVE both sidebar and main content.

How do I achieve it?

# Answer
> 0 votes
> Yes. The thing is, I need different content in this block depending on the current view. So I'd need to create 20+ different blocks for each of my views which seems redundant. I'm sure there must be more elegant solution.

Create a block and use template\_preprocess\_block to alter the content based on the path. In your theme's **template.php** add:

```
mytheme_preprocess_block(&$vars) {
  if ($vars['block']->bid === 'target_block_id') {
    $path = current_path(); // gets the current page path.

    switch($path) {
      case path1:
         $vars['content'] = "Hello World";
         break;
      case path2:
         $vars['content'] = "Hello Kitty";
         break;
       // ... and so on and so forth.
    }

  }
}

```

<sub>**Note:** replace `mytheme` with your actual theme name, same for `'target_block_id'`. </sub>

---

Another possible option, would be to add a header to your views, and then just use CSS with absolute position to move it, this would mean you'll need to add some `padding-top:` or `padding-bottom` on some other div to create a space for it.

---
Tags: 7, views, blocks
---


title: Drupal alternative to PHP's strip_tags?

text:
# Question
Title: Drupal alternative to PHP's strip_tags?
Is there a Drupal 7 function that is equivalent to PHP strip\_tags?

# Answer
> 3 votes
Drupal 7 uses `strip_tags` directly in plenty of places (theme.inc, common.inc, etc.).

If there was an equivalent, core would use that instead, so you can safely assume that you should use `strip_tags` when you need the functionality it provides, not a Drupal-specific method.

# Answer
> 0 votes
AsciiDoc filter will work like strip\_tags https://www.drupal.org/project/asciidoc

Not Exactly, but many cases it will work like strip\_tags.

---
Tags: 7
---


title: Drupal 8 Page Cache

text:
# Question
Title: Drupal 8 Page Cache
I am using dynamic tokens in page title, which is always being cached. I want to stop that.

I have try by disabling page cache using

```
function hook_preprocess_page(&$vars) {
  $vars['#cache']['max-age'] = 0;
  \Drupal::service("page_cache_kill_switch")->trigger();
}

```

But they didn't help me, Is there a way so i can only disable or refresh page title cache of a specific page.

My title looks like " lorem ipsum \[mydynamictoken:subtoken\] "

# Answer
This code works, but you need to place it in the title block.

I wouldn't use the page cache kill switch though, uninstall the module *Internal Page Cache* instead and then the dynamic page cache can still cache pages where uncacheable blocks are placeholdered.
> 1 votes

# Answer
Disable cache for a custom page from route declaration. If you want to disable cache for a custom controller (Custom module), You have no\_cache option (YOUR\_MODULE.routing.yml). Example : File : mymodule.routing.yml

```
mymodule.myroute:
  path: '/mymodule/mypage'
  defaults:
    _controller: '\Drupal\mymodule\Controller\Pages::mypage'
    _title: 'No cache page'
  requirements:
    _access: 'TRUE'
  options:
    no_cache: 'TRUE'

```
> -1 votes

---
Tags: 8, caching, tokens
---


# Question
Title: Use CKEditor on textarea in custom module's controller response
I am trying to figure out how to use Drupal 8's CKEditor on `<textarea></textarea>` tags that are part of a controllers markup and not generated from a Drupal form.

Has anyone done this or can Drupal 8's integrated CKEditor only be used with Drupal Forms?

When I try to use ckeditor with the standard way of `CKEDITOR.replace('element');` I get the error that `config.js` and `styles.js` are missing. Which should be the case because Drupal has consciously excluded them from their integrated CKEditor. https://www.drupal.org/project/drupal/issues/2604052

After digging around I found the javascript call `Drupal.editors.ckeditor.attach(element, format)` but I can't figure out what to pass in for the `format` parameter. Looking at other javascript code it appears they they use the `drupalSettings` global variable in javascript to pass it in but it's not there.

Any help on this would be greatly appreciated.

My code is below.

**my\_module.routing.yml**

```
my_module.myroute:
  path: '/my-route'
  defaults:
    _title: 'Test Module'
    _controller: '\Drupal\my_module\Controller\HomeController::view'
  requirements:
    _access: 'TRUE'

```

**my\_module.libraries.yml**

```
scripts:
  js:
    my_script.js: {}
  dependencies:
    - ckeditor/drupal.ckeditor

```

**my\_script.js**

```
window.onload = function () {
    let element = jQuery("#testelement");
    let format = "filtered_html";
    Drupal.editors.ckeditor.attach(element, format);
};

```

**HomeController.php**

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\Markup;

class HomeController extends ControllerBase
{

    function view()
    {
        return [
            "#attached" => [
                "library" => ["my_module/scripts"]
            ],
            "#markup" => Markup::create("
                <textarea name='testelement' id='testelement'></textarea>
            ")
        ];
    }
}

```

# Answer
I'd imagine you just return the same element you'd build into a form, and use a format that's configured to use a WYSIWYG:

```
return [
  '#attached' => ...,
  '#type' => 'text_format',
  '#title' => 'Foo',
  '#format' => 'full_html',
];

```

See the `TextFormat` class for more options.
> 2 votes

# Answer
Missed the format

```
return [

  '#type' => 'text_format',
   '#title' => t('Text'),
   '#required' => TRUE,
   '#format' => 'full_html',
   "#attached" => [
   "library" => ["my_module/scripts"]
            ]
  ];

```

Go to /admin/config/content/formats and check the CKeditor is enabled for FULL HTML. Also, could be a role issue, by default Full HTML is for admins only.
> 0 votes

---
Tags: 8, wysiwyg
---


# Question
Title: Site appears garbled after installing a SSL certificate on the server
I installed a SSL certificate on the server. However, the site appears garbled under https://, which I need for several reason.

# Answer
> 0 votes
This is kind of a duplicate of issues like Is there any way to force https:// to be used for assets and still be able to define a theme CSS files in its .info file?

@bharate is correct about the issue being caused by your assets not being loaded over https://.

It's likely caused by the `$base_url` in the *settings.php* file. Check to see if it includes the http:// as protocol and replace it with something like `$base_url = (drupal_is_https() ? 'https' : 'http') . '://www.example.org';` or `$base_url = '//demoflorida.com';`.

Using just *//* is protocol agnostic, so it will use whatever is asked for without any logic needed.

# Answer
> -1 votes
Actually this is a problem of trying to load resources via http over https. You can check the link below for your website and you will see which elements/css are loaded via http You will have to call them with https and your page should be fine.

https://www.whynopadlock.com/results/09ff9e5c-52d1-4299-80e5-3db45fe3aafd

---
Tags: 7, ssl
---


# Question
Title: How do I add custom meta tags to a view page?
There doesn't seem to be an answer for Drupal 8 yet. I have the metatag module installed, it's a great module, but doesn't seem to address views at all. This post for Drupal 7 says that it comes with a 'metatag views' module, but, this doesn't seem to be true for Drupal 8. I've also tried to install metatag quick, but, that fails to do anything at all. So I'm stuck. Is there a way to do this programmatically in D8? How can I get this done?

# Answer
> 3 votes
I actually believe my comment provides an answer to this question; it cannot be done yet...

But looking at the issue, it seems to be pretty active at the moment and it is planned for the first release candidate. There is a patch available and cgmonroe claimed it worked in his beta 11 version of the module.

So you can wait until RC1 is released, which will very likely contain the Views integration, or you can try to apply the patch.

# Answer
> 15 votes
Current version of Metatag module includes a submodule "Metatag: Views". Enabling this, you get a new section in your views editor to set all metatags available (specific tags are available in other submodules in a very drupal way).

# Answer
> 3 votes
While we wait for the metatag module to catch up, I'm using something like this in my theme's `.theme` file:

```
<?php

function THEMENAME_preprocess_html(&$variables) {
    // Set up the tag structure that's always the same no matter what page you're on
    $tag = array(
        '#tag' => 'meta',
        '#attributes' => array(
            'name' => 'description',
            'content' => FALSE,
        ),
    );

    // Switch on the current page path. Apparently Drupal 8 paths have leading slashes now
    switch(\Drupal::service('path.current')->getPath()) {
        case '/your/view/path':
            $tag['#attributes']['content'] = 'Your view’s description';
            break;
        case '/another/view/path':
            $tag['#attributes']['content'] = 'Another view’s description';
            break;
    }

    // Only add the tag if an option matched the current path
    if($tag['#attributes']['content']) {
        // 'THEMENAME_meta_description' is my best guess for a good identifier.
        // Maybe there's something better?
        $variables['page']['#attached']['html_head'][] = array($tag, 'THEMENAME_meta_description');
    }
}

```

# Answer
> 2 votes
I ended up turning all my View pages into blocks and then adding the block to a basic page. From there I can edit and add meta tags at will. Not an ideal solution, but should get us by until the new module is released. Thanks @Neograph734 for shedding some light on the issue.

# Answer
> 2 votes
Please do following steps:
1) Install metatag module
2) Enable it 3) Now enable "Metatag: Views" module which is the child module of Metatag
4) Now clear the cache
5) Now go to views page
6) You can see the "META TAGS" option below the "LANGUAGE"
7) Now either you left the "Using defaults" option or just click it and change the meta title of the page
8) This title will set for default language content
9) For other language content, you need to go to translate a page of same views
10) First, translate the views
11) Edit the translated view
12) Now search the "Page title" under "PAGE DISPLAY SETTINGS"
13) Change the title accordingly
14) Save it
15) See the meta title of other language page it will changed now
16) Please do cache clear if that it not reflect

---
Tags: 8, meta-tags
---


# Question
Title: D8 Widget Column is missing on manage field page
I haven't worked with Drupal for a long time and particularly I never worked with D8. Looks like the manage fields screen doesn't have widget column. Specifically I would like to use https://www.drupal.org/project/inline\_entity\_form widget for entity reference field, but I couldn't figure out where do I go to change widget type for the reference field.

See screenshot: https://screencast.com/t/eZvspoNHTDQv

# Answer
> 2 votes
I'm sorry for a stupid question. I figured it out. It was under "Manage form display" screen. What got me confused was while googling for answer, I stumbled upon a few screenshots from an early D8 build which still had Widget Type column on Manage Fields screen and it lead me into thinking that something was wrong with my installation.

---
Tags: 8, entities
---