# Question
Title: Add .active class to a menu link when other menu link is clicked
I have following scenario: Drupal 8.5.6, with a bootstrap subtheme. There are 2 menus (I'll call them main menu and secondary menu).

The links in the main menu are geographic areas, I've managed to add the .active class to the link, based on the url with the help of this answer: https://drupal.stackexchange.com/a/191861/60589 with a preprocess function and tweaking the twig code.

The links in the secondary menu are related to each one of the links in the main menu, so when I click *Area 1* in the main menu, a custom secondary menu will appear in this page.

The problem: I want the main menu link to stay highlihted, when I click on a link of the secondary menu The URLs look like this:

mysite/areas/area1 ==\> the Area1 link in the main menu gets the active class

mysite/areas/area1/otherlink ==\> the links in the secondary menu have this structure, I want the Area1 link in the main menu to keep the .active class.

# Answer
The cited solution appears a little buggy, as it replaces all potentially existing classes of the menu items. But what makes it not suitable for your use case is, that it is intended to add the `active` class only, if the current path matches the menu link's URL path.

What you are looking for instead, is the menu items' "active trail". It is a flag set by the menu module on every menu item found when traversing the menu tree upwards, starting from the current active item up to the menu root.

With this information at hand, have a check for the default menu template. It features the menu item specific property `in_active_trail`:

> in\_active\_trail: TRUE if the link is in the active trail.

So you can easily add the `active` class to your currently active menu item and all its parents by using the following in your theme's `menu.html.twig`:

```
{%
  set link_classes = [
    item.in_active_trail ? 'active',
  ]
%}
{{ link(item.title, item.url, {'class': link_classes}) }}

```

A more complete example for a Bootstrap 4 navigation with `menu.html.twig`:

```
{#
/**
 * @file
 * Theme override to display a Bootstrap 4 menu.
 */
#}
{% import _self as menus %}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('nav') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'nav-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {%
          set link_classes = [
            'nav-link',
            item.in_active_trail ? 'active',
          ]
        %}
        {{ link(item.title, item.url, {'class': link_classes}) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

```
> 3 votes

---
Tags: 8, theming, navigation, bootstrap-theme
---


# Question
Title: Hide a block when viewing own profile page - Show when viewing other people's profile?
I have a "Feedback" form implemented on a block. This block displays only when viewing the user profile page.

To stop people rating themselves, I would like to hide this block when the logged in user is viewing their own profile page.

This block should only show when viewing other people's profile pages.

I am using Drupal 8.

How can I do this please?

Here is the code I am currently using:

The issue is a person should not see the block when viewing their own profile page. They should see the block only when viewing another person's profile.

```
/**
 * Hide feedback form to prevent self voting.
 */
 use \Drupal\block\Entity\Block;
 use \Drupal\Core\Session\AccountInterface;

function zup_hide_feedback_form_block_access($block, $account) {

    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $uid= $user->get('uid')->value;

    if ($operation == 'view' && $block->getPluginId() == 'block-webform-3') {
        if($account->id() != $uid){
            return \Drupal\Core\Access\AccessResult::forbiddenIf($block->getRegion())
            ->addCacheableDependency($block);
        }
    }
      // No opinion.
      return \Drupal\Core\Access\AccessResult::neutral();
}

```

# Answer
> 2 votes
You can use `hook_block_access()`

```
/**
 * Implements hook_block_access().
 */
 function mymodule_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account) {
  if($operation == 'view' && $block->getPluginId() == 'block_id') {
    $uid_from_url = Drupal::requestStack()->getCurrentRequest()->get('user')->id();
    if($account->id() == $uid_from_url) {
      return \Drupal\Core\Access\AccessResult::forbiddenIf($block->getRegion())
        ->addCacheableDependency($block);
    }
  }
  // No opinion.
  return \Drupal\Core\Access\AccessResult::neutral();
}

```

See more document function hook\_block\_access

---
Tags: 8
---


title: How can I import a specific type block?

text:
# Question
Title: How can I import a specific type block?
I have created some blocks of a specific type, in Drupal 8, and I want to import them into the cloned instance.

There is no core import feature available. How can I achieve the task?

They don't get imported by the configuration synchronization; if you try, you will get the error

> This block is broken or missing. You may be missing content or you might need to enable the original module.

and no listing in custom block library.

# Answer
> 0 votes
As per my further research I found that there is a module named **Content Synchronization** which works well with the same issue. As in Drupal 8 blocks as served as content now and block types as entity types.

---
Tags: 8, blocks
---


# Question
Title: Show taxonomy term for administrators only in node creation form
I have a content type Topic. The topic has the taxonomy terms -health -fitness and -news. I only want certain roles like administrators to be able to see and use the taxonomy term - news when creating topics. I need all other users to only see and use the other two.

How do I go about this? Would hook form alter be the right direction?

# Answer
You can do hook\_form\_FORM\_ID\_alter() and alter the options values based on role.

```
use Drupal\Core\Form\FormStateInterface;
/**
 * implements hook_form_alter().
 */
function chad_form_node_topic_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    $current_user = \Drupal::currentUser();
    $roles = $current_user->getRoles();
    if (!in_array('administrator', $roles)) {
      // You can uset values like below.
      unset($form['topic_types']['widget']['#options'][3]);
    }
}

```
> 0 votes

# Answer
**If you like to hide the whole field**, you probably are looking for the Field Permissions module:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

**If you like to hide certain terms only**, you could use Views as reference method and filter your terms accordingly:

1. Create a new view for your taxonomy terms.
2. Create a Filter criteria "Term ID" to filter out all terms that shouldn't be available to non-privileged users, add a "Entity reference" display to that view and configure its Term name in the format settings.
3. Implement hook\_views\_query\_alter() in a custom module and remove the filter criteria, if the users have the elevated roles:

**mymodule.module:**

```
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter()
 */
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() != 'my_taxonomy_reference_view') {
    return;
  }

  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();

  if (in_array('USER_ROLE', $roles)) {
    unset($query->where[1]['conditions']['key_of_condition']);
  }
}

```
4. Head to your taxonomy term field settings and choose your view as reference type.

You might have to fiddle a little with the conditions, as the above example is just an outline for how you could do it. I actually didn't try it myself. But it should get you going.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Embed unique custom form in all rows of a view
I want to create a custom form that will be embedded on each row for visitor to submit an email for that specific row.

I suppose I have to create a custom form (which I have done before) but **how do I embed it on each row** ? `hook_views_data_alter(array &$data)` is the right way ?

Other questions (but not that important) are how do I make it unique (know which row the user has submitted) ? Another requirement is to be submitted without reload of whole page (ajaxy form).

# Answer
That's a lot questions in one post. Two things may help you:

First, if you have more than one instance of a form on one page, you need different formIds. So implement the getFormId with a variable, like so:

```
public function getFormId() {
    return "mysuper_form-".$this->whatEverCounter;
}

```

Then, you will need to create your form yourself with the constructor (cause you need your state to be set from outside) and pass that instance to the formBuilder, for example like so

```
$idForm = new myForm($whatEverCounter);
$form = \Drupal::formBuilder()->getForm($idForm);

```

Second, for the "each row" topic: If you really have one form per row, you will have one submit per row also - no problem. Or, you have one form with one element per row. Then just enumerate your elements like so:

```
public function buildForm(array $form, FormStateInterface $form_state) {
    foreach ($ems as $e) {
       $form['toggle'.$e] = []
    ]

```

If you need an ajax submit callback, use the '#ajax' attribute, like so:

```
'#ajax' => array(
        // Function to call when event on form element triggered.
        'callback' => [$this, 'toggleButtonPress'],
        // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
        'effect' => 'fade',
        // Javascript event to trigger Ajax.
        'event' => 'click',
        'progress' => array(
        // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
        'type' => 'throbber',
        // Message to show along progress graphic. Default: 'Please wait...'.
        'message' => NULL,
        ),

```
> 2 votes

---
Tags: views, 8, forms, ajax
---


# Question
Title: Add JavaScript and css to page with nodes only if there is no tag in any of the nodes
I wrote a module that adds javascript and css to a page with nodes of type 'rower', now I need to add javascript and css to the page only if there is no tag with id == 1503 in any of the nodes. I tried to do it myself but it does not work because the variable $containsOutletTag == TRUE only at last node. Can you please tell me how I can do this? Here's what I have for now:

```
<?php
function countdown_preprocess_node(&$vars)
{
  if ($vars['type'] === 'rower') {
    $containsOutletTag = false;

    foreach ($vars['field_product_tags']['und'] as $tag) {
      if ($tag['tid'] == 1503) {
        $containsOutletTag = true;
      }
    }

    if (!$containsOutletTag) {
      drupal_add_css(drupal_get_path('module', 'countdown') . '/src/countdown.css');
      drupal_add_js(drupal_get_path('module', 'countdown') . '/src/countdown.js');
    }
  }
}

```

# Answer
you shouldn't have use hook\_preprocess\_node as it gets fired on each node separately, so if only one of the node doesn't have that specific tag the css and javascript will be added to the page unless other nodes have, so rather than hook\_preprocess\_node use hook\_preprocess\_page and there you can find an array of nodes (use dsm function with devel module enabled to see variable structure) and you can iterate over that array and check for condition
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: Keep the destination argument in when user switch from user login to register?
I have a link for users to click so that they can add a specific node type, and I use a link like below so that if the user isn't logged in, he/she can login and then be redirected to the node form, and if already is, directly goes to that form.

Now, if the user isn't registered yet, and clicks the register tab instead when coming to /user (or /user/login), the destination argument disappears, and when the user has filled out the form and is all set, he/she will be forwarded to the start page, and not the node form, that I wanted.

What would I have to do to keep this destination argument if the users registers in the process?

I tried Rules - nothing. And now I'm trying to use form/menu alter to either add the destination argument to the link, or create a completely new tab for this, and hide the other one.

Help!

Url example: example.org/user/login?destination=/node/add/help

# Answer
I'll use JavaScript (jQuery) and set a cookie instead.
> 0 votes

# Answer
I found for Drupal 7 there is no need to override the theme function, just adding a preprocess hook is enough.

```
/**
 * Add destination param to user tabs if set.
 * Implements HOOK_preprocess_menu_local_task()
 */
function THEME_preprocess_menu_local_task(&$variables) {
    $link = &$variables['element']['#link'];
    // check for $_GET['destination'] because drupal_get_destination() always contains at least the current page
    if ($link['tab_root'] === 'user' && !empty($_GET['destination'])) {
      $link['localized_options']['query'] = drupal_get_destination();
    }
}

```

Replace THEME with the name of your theme or module.
> 2 votes

# Answer
If you know how to do a little bit of theming or are happy editing a php file then you can do this by theming your menu links. I wrote a solution for Drupal 6 here http://tappetyclick.com/blog/2013/04/11/maintain-destination-drupal-user-account-menu#.UWbt8hcmdIE because I found it so hard to find a solution myself.

Hope that helps someone
> 1 votes

# Answer
For Drupal 7:

```
/**
 * THEME_menu_local_task override.
 * Add destination param to user tabs if set.
 */
function THEME_menu_local_task(array $variables) {
  $link = $variables['link']['#link'];

  if ($link['tab_root'] == 'user' && !empty($_GET['destination'])) {
      $link['localized_options']['query'] = drupal_get_destination();
    }
      $output = l($link['title'], $link['href'], $link['localized_options']);
      return '<li' . (!empty($variables['link']['#active']) ? ' class="active"' : '') . '>' . l($link['title'], $link['href'], $link['localized_options']) . "</li>\n";
}

```

Place in your template.php or a custom module. Replace THEME with your theme name.
> 0 votes

# Answer
For Drupal 8 there is a tiny module just doing that:
https://www.drupal.org/project/user\_login\_persistent\_destination
> 0 votes

---
Tags: redirection, routes, forms
---


# Question
Title: Why can't I change textfield #default_value based on checkboxes' values after an AJAX response?
I have been trying to learn Drupal forms with AJAX recently and from my current understanding of it I thought I should be able to do something like presented below (I wanted to store all selected values as a string in another hidden field to grab it later in my JS and do some stuff, but that does not matter here, what matters is what I do not get about AJAX).

So the idea is that selecting checkboxes will update the value in the input field with checkboxes' values.

Unfortunately, the #default\_value on my textfield is not being set on my page, even though I can see it being set in my $form array when debugging with xdebug.

The form is used to filter some results with an AjaxResponse() ReplaceCommand.

Here is the simplified code, stripped from most unrelated things:

```
public function buildForm(array $form, FormStateInterface $formState)  {
  $values = $formState->getValues();
  $defaultCountry = implode(':', array_filter($values['countryId']));
  $form['countryId'] = [
    '#type' => 'checkboxes',
    '#title' => $this->t('Country'),
    '#options' => [
      '1' => 'Aaa',
      '2' => 'Bbb',
      '3' => 'Ccc',
    ],
    '#ajax' => [
      'callback' => '::ajaxResponse',
      'event' => 'change',
      'wrapper' => 'some-wrapper-for-filters-form-and-results',
      'progress' => array(
        'type' => 'throbber',
        'message' => NULL,
      ),
    ],
  ];
  $form['defaultCountry'] = [
    '#type' => 'textfield',
    '#title' => $this->t('TEST'),
    '#default_value' => $defaultCountry,
  ];
  return $form;
}

public function ajaxResponse(array &$form, FormStateInterface $formState) {
  $result = 'some processing logic';
  $response = new AjaxResponse();
  $response
    ->addCommand(new ReplaceCommand('.filtered-offers > div', $result));
  return $response;
}

```

What do I miss here?

# Answer
> 0 votes
While I'm not sure why it doesn't work, the fix I've found in the past is to set the default value as #value in the AJAX callback. While this generally goes against the principle of #AJAX in Drupal (ie - changes should be made in the form definition), it works.

---
Tags: 8, forms, ajax
---


# Question
Title: How do I pass the language through ajax request
I have an ajax function in the javascript file that calls for the data in a custom module. But the problem is it always get the data for the default language. In my case it is 'en'. How do I get the data for another language.

```
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

```

This method always returns the default language for ajax requests. How do I get the data for the language that is mentioned in the url.

**ajax**:

```
$.ajax({
    url: "/gallery/view",
    method :'POST',
    data: {
        category : category,
        propertyId : propertyId,
        isCorporate : isCorporate,
        brandId : brandId,
    },
    success: function(result){}
});

```

**routing** :

```
eme_gallery.view:
  path: '/gallery/view'
  defaults:
      _controller: 'Drupal\eme_gallery\Controller\ViewGalleryImage::view'
      _title: 'Image Gallery'
  requirements:
      _permission: 'access content'

```

# Answer
You will need to change the URL of your AJAX call to include the language prefix. So this:

```
url: "/gallery/view",

```

Will be this:

```
url: "/ja/gallery/view",

```
> 1 votes

---
Tags: ajax, i18n-l10n
---


# Question
Title: How to force the canonical URL to use http?
On our page we use the Metatag module to show a canonical meta tag. In the configuration we use the `[current-page:url:absolute]` token. This works fine, but the problem is, that whether the page gets accessed by HTTP or HTTPS this protocol is used in the canonical URL.

For SEO purposes we want the canonical URL to be the same and use HTTP for both protocols.

How can we achieve this?

# Answer
### Drupal 7

You can implement `hook_html_head_alter()` to change head tags; the following is untested but should do the trick:

```
function MYMODULE_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => &$tag) {
    if (strpos($key, 'drupal_add_html_head_link:canonical:') === 0) {
      if (strpos('https://', $tag['#attributes']['href']) === 0) {
        $tag['#attributes']['href'] = str_replace('https://', 'http://', $tag['#attributes']['href']);
      }
    }
  }
}

```
> 8 votes

# Answer
With the metatag module you can use the \[current-page:url:relative\] token instead of the \[current-page:url:absolute\] token.

so your canonical tag would become something like: http://www.mywebsite\[current-page:url:relative\]
> 2 votes

# Answer
### Drupal 8

For nodes you have to use `hook_ENTITY_TYPE_view_alter` as that's the place where they got added to initially from `NodeViewController::view()`.

And let me note that you are probably better off by simply redirecting all your incoming traffic to SSL by default: How to simply make the whole site HTTPS?

```
/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function MYMODULE_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if (isset($build['#attached']['html_head_link'])) {
    foreach ($build['#attached']['html_head_link'] as $key => $head) {
      if ((isset($head[0]['rel']) ? $head[0]['rel'] : FALSE) == 'canonical') {

        $url = \Drupal\Core\Url::fromRoute('<current>', [], ['absolute' => 'true'])
          ->toString();

        $url = str_replace('https://', 'http://', $url);

        $build['#attached']['html_head_link'][$key][0]['href'] = $url;
      }
    }
  };
}

```

---

I just found out, that in the end we'll find all the head tags in `hook_preprocess_html` in the `$variables['page']['#attached']` array to be altered.
> 0 votes

# Answer
Call me crazy and please correct me if I'm wrong, but can't you just hard-code the URL with the HTTP?

I'm sure there's something I'm missing, but if you drop in the full URL instead of using the token, you'll end up with that particular URL as the canonical for every variation of the page Drupal creates.

The caveat is that it creates an update nightmare as you have to remember to change the canonical if the alias of the page ever changes.
> -3 votes

---
Tags: uri, meta-tags
---


title: How to resolve lazy_builder error?

text:
# Question
Title: How to resolve lazy_builder error?
We have a field that is an Entity Reference to Blocks. In our situation, this field is referencing a View block. We are able to add this field on the content type and node properly, but when the page renders there is the following error message. We set this up using steps from Drupal 8: How to Reference a Views' Block Display from a Field.

> Uncaught PHP Exception DomainException: "When a #lazy\_builder callback is specified, no properties can exist; all properties must be generated by the #lazy\_builder callback. You specified the following properties: #attached." at /mnt/www/html/netscout/docroot/core/lib/Drupal/Core/Render/Renderer.php line 333

How would we resolve this issue?

What we have tried:

1. DomainException with #lazy\_builder and \['#cache'\]\['keys'\], but this did not have anything that helped because we do not load the block by using `#lazy_builder`
2. We tried updating our modules, but still get the error message
3. Tried removing the removing the block reference, but then we were not able to add the view block to the page.

We are using Drupal v8.5.3.

# Answer
Rather than using Entity Reference to Block, we went with using Viewfield module. It has worked as expected with and without exposed filters.
> 0 votes

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


# Question
Title: How to delete a database field named as a reserved word?
I want to drop a field from db table which is named as read. I tried like;

```
db_drop_field('my_table', 'read');
db_drop_field('my_table', '`read`');
db_drop_field('my_table', `read`);

```

None of these work.

# Answer
> 0 votes
Just run a custom query:

```
db_query('ALTER TABLE my_table DROP COLUMN `read`');

```

The API functions don't cover every possible edge case, and dropping fields named as reserved words happens to be one of them.

When that fails, executing a standard SQL query is the best option.

# Answer
> 0 votes
Read is a reserved word, but your problem has an easy solution (I test it and works)

Change your field name to **reading**

And then use:

```
db_drop_field('your_table', 'reading');

```

---
Tags: 7, database
---


# Question
Title: How to create user with role(s) through REST service?
I could able to create a new user by the following JSON format.(Using POSTER add-on to post this data to REST service.)

```
{
   "name":"user34",
   "pass":"3323",
   "mail":"sample@example.com",
   "status":"1"
}

```

My question is how to create a user with specific role. I tried with the following JSON format.

```
{
   "name":"user35",
   "pass":"pwds3",
   "mail":"sample2@example.com",
   "status":"1",
   "roles":{
      "2":"authenticated user",
      "4":"moderator"
   }
}

```

but the response gives the following error

> \["An illegal choice has been detected. Please contact the site administrator."\]

# Answer
> 16 votes
After many trials, I was able to resolve my issue

Here is the JSON format to create user with role.

```
{
   "name":"user343",
   "pass":"kes35@r4",
   "mail":"user343@sample.com",
   "status":"1",
   "roles":[
      "4"
   ]
}

```

To assign multiple roles,

```
{
   "name":"user344",
   "pass":"kes344@r4",
   "mail":"user344@sample.com",
   "status":"1",
   "roles":[
      "3",
      "4"
   ]
}

```

I hope this helps someone.

# Answer
> 0 votes
This helped!

I used the request URL `endpoint/user/register` and passed headers `content-type` as **application/json** and X-CSRF-TOKEN which I got by login to the system.

Thanks.

---
Tags: 7, users, services
---


title: Token for Total Flag Count

text:
# Question
Title: Token for Total Flag Count
I have created a flag for my comments named HELPFUL. If users find a comment helpful they vote it as such.

The challenge that I have is how do I show the total votes for the flag next to the button? If a comment was voted as helpful 5 times for example, show that next to the helpful button.

If there are no helpful votes for a particular comment show nothing (do not display 0) but only the HELPFUL rate button (flag)

I have tried to add \[flag-action:count\] and \[flag-helpful-count\] as the token under the flag setting (/admin/structure/flags/manage/helpful \>\>edit\>\> Flag link text) but it does not work.

Looked at COMMENT tokes and I see this available: \[comment:flag-helpful-count\] It still won't work. It shows this text \[comment:flag-helpful-count\] instead of a total number.

Any help would be greatly appreciated.

# Answer
You try code:

```
/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if($type == 'comment' && !empty($data['comment'])) {

    foreach($tokens as $name => $original) {
      switch($name) {
        case 'flag-helpful-count':
          //$comment = \Drupal\comment\Entity\Comment::load($data['comment']->get('cid')->value);
          //$count_flag = \Drupal::service('flag.count')->getEntityFlagCounts($comment);
          $replacements[$original] = 10;
          break;
      }
    }
  }
  return $replacements;
}

function mymodule_preprocess_comment(&$variables) {
  $token_service = \Drupal::token();
  $token_count_flag = $token_service->replace('[comment:flag-helpful-count]', array('comment' =>
    $variables['elements']['#entity']));

}

```
> 1 votes

---
Tags: 8, theming, tokens, flags
---


# Question
Title: Disable /Enable a multivalued paragraph field on Ajax calls
I have 2 fields in a form. One select list and another entity reference field referring to a Paragraph type (multivalued). The on-change event should trigger an ajax callback which will disable some of the fields in the paragraph type. I managed to achieve this on ajax callback. Now, the problem is when I add more values to the paragraph the previous disabled field goes back to the default state. Any suggestions /examples will be helpful. Below is my code. Thanks.

```
    function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      //Ajax callback on change event
      if (isset($form['field_link_type'])) {
        $form['field_select_sample']['widget']['#ajax'] = array(
        'callback' => '_my_ajaxcallback',
        'event' => 'change',
       );
      }
     }

    function _my_ajaxcallback(array $form, FormStateInterface $form_state) {

      $response = new \Drupal\Core\Ajax\AjaxResponse();

      //disable field_htext of paragraph field
      $response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.field--name-field-htext input', 'attr', array('disabled', 'disabled')));

      return $response;
    }

```

Updated code - In my callback -

```
    echo 'disabled - ' . $form_state->get('field_header_disabled');`
    $form_state->set('field_header_disabled', TRUE);`
    echo $form_state->get('field_header_disabled');
    return $response;

```

The output is something like - **disabled - 1** on both first and second callbacks. On second callback I'm expecting the output to be something like **disabled - 11**

# Answer
Your issue arises, as the paragraphs widget(s) itself do a lot of Ajax calls and you disable the field(s) in your browser only. So your paragraph form will be reloaded and re-rendered without knowing that the field has been disabled before.

To have the field(s) disabled on consecutive reloads, you need to make your changes more permanent.

You could e.g., save a flag to the `$form_state` using the FormStateInterface::set() method:

> **FormStateInterface**
> \[...\] it may be used to store information related to the processed data in the form, which will persist across page requests when the 'cache' or 'rebuild' flag is set.

This means, after you stored a custom flag in the `$form_state` and an ajax request to reload this form is made, it will be available within the `$form_state` of your `hook_form_alter()` implementation as well.

So all we have to do now, is checking for this flag in `hook_form_alter()` using the FormStateInterface::get() method and ensure the field will be disabled, if it has been set before.

A less abstract example:

```
/**
 * Callback for disabling field_htext.
 */
function _my_ajaxcallback(array $form, FormStateInterface $form_state) {
  $response = new \Drupal\Core\Ajax\AjaxResponse();

  // Disable field_htext of paragraph field.
  $response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.field--name-field-htext input', 'attr', array('disabled', 'disabled')));

  // Set a 'disabled' flag in form state.
  $form_state->set('field_htext_disabled', TRUE);

  return $response;
}

```

And in your form alter:

```
/**
 * Implements hook_form_alter().
 */
function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Better use the form ID here and check, if you are at
  // your form in question, or even use a more specific hook as
  // hook_form_BASE_ID_alter() or hook_form_FORM_ID_alter().

  // Check our custom disabled flag.
  if (
    !empty($form_state->get('field_htext_disabled'))
    && isset($form['field_htext'])
  ) {
    // Set the 'disabled' attribute.
    $form['field_htext']['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
  }

  // Add ajax callback on change event.
  if (isset($form['field_link_type'])) {
    $form['field_select_sample']['widget']['#ajax'] = array(
    'callback' => '_my_ajaxcallback',
    'event' => 'change',
   );
  }
 }

```
> 3 votes

---
Tags: 8, forms, ajax, paragraphs
---


# Question
Title: How to make Dynamic Term Link based on content type?
My web site has three content types ( Event, Course, Video) and 2 taxonomies(city and schools) All of them have same taxonomy referenced field. Eg:New York City events or New York City courses will be listed seperately.

**Problem:** How can I make term links dynamic based on content type .

All new york city contents are listing(3 content type contents) if I clicked newyork city term on event content.

I need only event type contents to be listed if I came from an event type content. It should be changed according to event,course or video content type. Any help with this would be awesome . Thanks

# Answer
The easiest way to achieve this is by using Views.

The links rendered in Taxonomy fields (Entity reference fields) are set to go to Taxonomy term pages. The links are constructed with Taxonomy term ID in the URL: `taxonomy/term/[TID]`.

Taxonomy term pages are created using Views, so you can easily Edit the relevant Views to adjust it to your needs. The modification you're after is adding a Contextual filter that filters out only one content type.

With that modification you could type, for example, `taxonomy/term/10/article` in the browser address bar, and the usual Term page for term 10 would list only results of the Article Content Type.

The other part of your question is how to make the Taxonomy reference link on the node View be sensitive to the Content type it's on, so when it's clicked it goes to the filtered list, and not the general term page that shows all results.

The easiest way to do that is to hide that field from displaying and replace it with a Views Block that would output a similar link, only Contextually sensitive to the term, and to the Content type.

Here are the steps on how to achieve this:

## Make term pages sensitive to Content types

1. Duplicate the `Taxonomy term` View (it's better to keep the default ones as they are, so you don't mess up the original features and it makes updates more straightforward). Rename it to make sense (Taxonomy term-Content type)
2. Add a new Contextual Filter **Content type** from the `Content` Category (keep the one sensitive to the taxonomy term that is already there, we need it) and configure it with these options:
`When the filter value is NOT in the URL`
**Display all results for the specified field**
`When the filter value IS in the URL or a default is provided`
**Override title**
**Content tagged with {{ arguments.tid }} of type {{ arguments.type }}** **Specify validation criteria**
`Validator` **Content type**
**Validate user has access to the Content type**
`More`
**Transform spaces to dashes in URL**
3. Edit the `Path` to add another `%` to react to the Contextual filter we just added, so you end up with the Path: `taxonomy/term/%/%`
4. Go to the other Display in the same View called `Feed` and edit the Path there to read `taxonomy/term/%/%/feed`
5. Save the View. You can test it by entering the relevant arguments into Preview inside Views (for example `10/article`) or by typing the URL into your browser addressbar (`example.com/taxonomy/term/10/article`).
6. Optional but good UX: add **No results behavior** **Text area** `No content of type {{ arguments.type }} tagged with {{ arguments.tid }} has been found.` on your Page display and override for that Display only **This page (override)**.

## Create taxonomy links on Nodes sensitive to CT

To create links sensitive to the context we need Views Display **Block** of type Content. We can add it to the Views we created above (because that View is of type Content), or create a completely new View for this. Since this Block Views will be sufficiently different it's better to create a new View for this. Here are the steps for adding a new Views to accomplish this:

1. Create a new Views of type Content showing Fields, add a Block Display to the View, change its name to something meaningful you can recognize later on Blocks page: `Taxonomy term link sensitive to CT`
2. Add a Filter to limit to your desired Content types (event, course, video)
3. Under `Format` option `Show` settings choose to **Hide empty fields**
4. Add a new Field **City** (or whatever your field is called), **Exclude from display**, and **don't** tick `Link label to the referenced entity`
5. Add a new Field `Content type`, **Exclude from display** and set `Formatter` to **Entity ID** (so you get CT machine name so the contextual filter later works correctly)
6. Add a new Relationship **Taxonomy term referenced from field\_city** and **Require this relationship**
7. Add a new Field **Term ID** (it will use the Relationship from previous step), **Exclude from display** and set `Formatter` to **Unformatted**
8. Add a new Field **Custom text** from `Global` Category and configure it:
**Create a label** just tomake it easier to build, enter `Taxonomy link sensitive to CT`
In **Text** area enter `{{ field_city }} (type { type }})`
`Rewrite results`
**Output this field as a custom link**
**Link path**: `taxonomy/term/{{ tid }}/{{ type }}`
**Replace spaces with dashes**
`No results behavior`
**Hide if empty**
9. Add a new Contextual filter **ID** from `Content` Category and configure:
`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`
**Specify validation criteria**
**Content**
\[your CTs video course event\]

Now when you enter a node ID into Preview it will show the link to taxonomy term page that has content type argument added to it at the end.
10. Set `Pager` to **Display a specified number of items** to `1` item
11. Remove the Title field so you end up with only the Custom text visible and Save the View
12. Place the Block in `Content` region, don't `Display title`, set `Content ID` to **Node from URL**, limit which Content type to show the Block on
13. Edit your Content types (all three) `Manage Display` to hide the City Taxonomy Field (drag to **Disabled**)

And now you have the relavant Taxonomy term link that has the added Content type at the end to call on Views term page that will filter out only that content type.
> 1 votes

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


title: Multi-layer views results

text:
# Question
Title: Multi-layer views results
I'm not quite sure how to explain this but here goes. I want to have a link to a view that displays a collection of categories i.e. t-shirts, jeans, socks, sunglasses etc. I then want to (for example) click on t-shirts and be prestented with a list of all links to items/nodes that are t-shirts. Is views able to do this 2 tier result?

# Answer
Yes, you can do this with a Contextual filter in Views.

Create a Content View of your desired nodes, then add a Contextual Filter (I'm assuming your categories are actually Taxonomy terms referenced from nodes) for the Field with that Taxonomy reference.

Configure it with these options:
`When the filter value is NOT available`
**Display a summary**
`Format` **List**
`Base path` (you *must* enter the Page path if this isn't the first Page Display in your Views)
**Display record count with link**
`More`
**Transform spaces to dashes in URL**

This way you get a list of term IDs that link through to a list of nodes tagged with those terms.

You probably want the term name to be displayed instead of the term ID. In that case remove the Contextual filter, we'll add the one for Taxonomy term Name, but we need a Relationship first for that information to become available.

So add a Relationship **Taxonomy term referenced from field\_category** (or whatever the field is called in your case), require it if you don't want summary results without a category.

Then add a Contextual filter **Name** from `Taxonomy term` Category, it will use the Relationship we created, and configure it like above.
> 0 votes

---
Tags: views
---


# Question
Title: How to disable one specific translation page?
How can I disable only one page in English on a Drupal 7 site, without disabling the Danish page?

I'm using Multilingual - Internationalization module.

# Answer
> 0 votes
Since translations in D7 are new nodes, you can simply Unpublish the English node, while keeping the Danish one Published.

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


# Question
Title: 'Failed to get available update data" behind a proxy
I am running Drupal 8.1.2 behind proxy in Ubuntu 16.04. There is an error:

```
Failed to get available update data for one project.

```

even the following is added in `settings.ini`:

```
$settings['http_client_config']['proxy']['http'] = '192.168.1.8:3128';
$settings['http_client_config']['proxy']['https'] = '192.168.1.8:3128';
$settings['http_client_config']['proxy']['no'] = ['127.0.0.1', 'localhost'];

```

I tried both `192.168.1.8:3128` and `http://192.168.1.8:3128/` and neither works.

Both `http_proxy` and `https_proxy` work well in bash though.

How can I fix the error?

Update, with screenshot:

# Answer
> 1 votes
I solved the problem on Ubuntu 14.04.5 with Drupal 8.5.6. This should also work for Ubuntu 16.04.4. Install php7.0-curl (or php-curl or php5-curl or php7.2-curl) and write `http://` before your proxy name (otherwise GuzzleHttp uses `tcp://`, I think).

# Console/SSH

```
sudo apt update
# Use php --version to find out what version of PHP you're on
sudo apt install php7.0-curl
sudo service apache2 restart

```

# Config

`/var/www/html/<DRUPALFOLDER>/sites/default/settings.php`

```
$settings['http_client_config']['proxy']['http'] = 'http://192.168.1.8:3128';
$settings['http_client_config']['proxy']['https'] = 'http://192.168.1.8:3128';
$settings['http_client_config']['proxy']['no'] = ['127.0.0.1', 'localhost'];

```

## Optional

The old syntax is no longer necessary (but would not hurt either):

```
$settings['proxy_server'] = '192.168.1.8';  // HERE WITHOUT http:// !!!
$settings['proxy_port'] = 3128;
$settings['proxy_username'] = '';
$settings['proxy_password'] = '';
$settings['proxy_user_agent'] = '';
$settings['proxy_exceptions'] = array('127.0.0.1', 'localhost');

```

# Console/SSH (again)

```
sudo service apache2 restart

```

# For the Googlers: errors on my way

Show logs with

```
drush ws --count=100 --extended --tail
# or cd into `<DRUPALFOLDER>` and do
php drush.phar ws --count=100 --extended --tail

```

►►►

```
 *****  24/Aug **:**  update    error     GuzzleHttp\Exception\RequestException: Error creating resource: [message]
                                          fopen(http://updates.drupal.org/release-history/drupal/8.x?site_key=****************************
                                          ***************&version=8.5.6&list=**********************************************************...
                                          ...*************************************************************************): failed to open
                                          stream: Connection timed out
                                          [file] /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
                                          [line] 324 in GuzzleHttp\Exception\RequestException::wrapException() (line 52 of
                                          /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php).
 *****  24/Aug **:**  update    error     GuzzleHttp\Exception\RequestException: Error creating resource: [message]
                                          fopen(http://updates.drupal.org/release-history/admin_toolbar/8.x?site_key=*********************
                                          ***************************************&list=admin_toolbar%2Cadmin_toolbar_tools): failed to
                                          open stream: Connection timed out
                                          [file] /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
                                          [line] 324 in GuzzleHttp\Exception\RequestException::wrapException() (line 52 of
                                          /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php).

```

►►►

```
 *****  24/Aug **:**  notic  user  Session opened for ***.
                      e
 *****  24/Aug **:**  error  upda  GuzzleHttp\Exception\ClientException: Client error: `GET
                             te    http://updates.drupal.org/release-history/admin_toolbar/8.x?site_key=**********************************
                                   *********&version=8.x-1.24&list=admin_toolbar%2Cadmin_toolbar_tools` resulted in a `400 Bad Request`
                                   response:

 *****  24/Aug **:**  error  upda  GuzzleHttp\Exception\ClientException: Client error: `GET
                             te    http://updates.drupal.org/release-history/drupal/8.x?site_key=*****************************************
                                   **&version=8.5.6&list=******************************************************************************...
                                   ...***************************` resulted in a `400 Bad Request` response:

```

---
Tags: 8
---


# Question
Title: How to add an ID to the table generated by a view?
In a site I'm building with Drupal 8.5.3, I designed a view that displays the content of a custom content entity: Members (Adhérents in french).
This view (system name = members) displays a page (system name = page\_1) that uses table format to output the data.
As expected, the generated html is something like:

```
<table class="views-table views-view-table cols-8 sticky-enabled">
    <thead>
        <tr>...</tr>
    </thead>
    <tbody>
        <tr class="odd">...</tr>
        <tr class="even">...</tr>
        <tr class="odd">...</tr>
        <tr class="odd">...</tr>
        ...
    </tbody>
</table>

```

I need this table to have an id, i.e. `<table class="views-table views-view-table cols-8 sticky-enabled" id="ListOfMembers">`.

How can I do that using either standard Views UI or anything Drupal-like?

# Answer
Finally, I found a solution: I duplicated `views-view-table.html.twig` into `views-view-table--members--page_1.html.twig` and changed

```
<table{{ attributes.addClass(classes) }}>

```

into

```
<table{{ attributes.addClass(classes) }} ID="ListOfMembers">

```

and the result is what I wanted:
> 0 votes

---
Tags: views, 8
---


title: Is it allowed to call t($variable)?

text:
# Question
Title: Is it allowed to call t($variable)?
In Drupal 7 t() this warning was present:

> You should never use t() to translate variables

In Drupal 8, well, it's Drupal 8, who knows where to even look?

I tried

and haven't found a similar warning. But absence of evidence is not evidence of absence. Is it OK now to use a variable?

# Answer
The advice is the same, it's just moved. The docs for `t()` say:

> See `\Drupal\Core\StringTranslation\TranslatableMarkup::__construct()`for important security information and usage guidelines.

On that page you'll find familiar advice:

> Translating Variables $string should always be an English literal string.
>
> `$string` should never contain a variable, such as:
>
> `new TranslatableMarkup($text);`
>
> ...

So generally speaking no, it's not OK to pass a variable as the first argument to `t()` in Drupal 8. Always use a literal string.

If you need to use variables for `t()`, pass a literal string containing placeholders, and a second argument containing their replacements. For example:

```
new TranslatableMarkup("@name's blog", [
  '@name' => $account
    ->getDisplayName(),
]);

```
> 10 votes

# Answer
Same as in Drupal 7. Drupal will always record a new `t()` source string dynamically when it encounters it. So this will of course work:

```
$string = 'Source string';
t($string);

```

The reason we **advise against this strongly** is:

1. Often you end up translating twice, so `t($var)` and then some bunch of code and then `t($whole_string)` that contains `t($var)` output, etc. Can pollute the source string database.
2. Often people ended up with `$string = $count . ' apples'; t($string)` which could grow your locale sources indefinitely and consequently make your locale cache unusable.
3. Similar problem for `t($userinput)` which could also quickly become a security issue.

Telling people they should trace their code so the variable is surely not user input and does not contain dynamic portions and is surely not translated already is not a simple advice. **But basically you could use dynamic strings as long as they are actually static strings.**

And then when people want to publish this same code on drupal.org none of the clever dynamic static techniques you used would work since localize.drupal.org would need to parse the source code without running it, so it would need to be statically analysable or it is not translatable.

Applying that best practice regardless of who you are developing for is most consistent to document. Then you don't grow bad habits when developing in-house code and will not submit wrong patches or modules to drupal.org.
> 6 votes

---
Tags: 8
---


# Question
Title: How to pass variable from WidgetBase to .module
In Drupal 8 my module looks like this.

```
<?php

function signature_field_theme() {

  $theme = [];
  $theme['signature'] = [
    'render element' => 'element',
    'variables' => array(
      'sign_src' => NULL,
      'text_area_id' => NULL,
      ),
  ];
  return $theme;
}

function signature_field_page_attachments_alter(&$page) {
  $page['#attached']['drupalSettings']['signature_field']['sign']['id'] = 'id';
}

```

My SignatureWidget.php file looks like this...

```
<?php

namespace Drupal\signature_field\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\ElementInfoManagerInterface;

/**
 * Plugin implementation of the 'field_signature_field_widget' widget.
 *
 * @FieldWidget(
 *   id = "field_signature_field_widget",
 *   module = "signature_field",
 *   label = @Translation("Signature Data"),
 *   field_types = {
 *     "field_signature"
 *   }
 * )
 */
class SignatureWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

     //
     //$sign_thumb = array( '#type'   => 'html_tag',
     //                     '#tag' => 'img',
     //                     '#attributes' => array('src' => '', 'id' => 'signature_thumb_test', 'class'=>array('align-right'), 'width' =>'120px', 'height' => '60px' ));

    $field_name = $items->getName();

    /*function getFieldName() {
      return $field_name;
    }*/

    $text_area_id = 'signature_field_' . $field_name;

    $file_upload_help = array(
      '#theme' => 'signature',
      '#sign_src' => $value,
      '#text_area_id' => $text_area_id,
    );

    $element += array(
      '#type' => 'textarea',
      '#default_value' => $value,
      '#attributes' => array(
        'id' => array($text_area_id),
                        ),
      '#attached' => array(
        'library' => array('signature_field/signature_pad'),
                        ),
    );
    $element['#attached']['library'][] = 'signature_field/signature_pad';
    $element['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help);
    //$element['#suffix'] = \Drupal::service('renderer')->renderPlain($sign_thumb);

    return array('value' => $element);
  }

}

```

How can I pass $text\_area\_id from the widget to the module in order to use it as a variable in `function signature_field_page_attachments_alter`

# Answer
> 0 votes
Just incase someone stumbles upon this and struggles to follow the thread above this is how to pass the variable.

```
$element['#attached']['drupalSettings']['signature_field']['sign']['id'] = $text_area_id;

```

Here is the full widget code.

```
<?php

namespace Drupal\signature_field\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\ElementInfoManagerInterface;

/**
 * Plugin implementation of the 'field_signature_field_widget' widget.
 *
 * @FieldWidget(
 *   id = "field_signature_field_widget",
 *   module = "signature_field",
 *   label = @Translation("Signature Data"),
 *   field_types = {
 *     "field_signature"
 *   }
 * )
 */
class SignatureWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

     //
     //$sign_thumb = array( '#type'   => 'html_tag',
     //                     '#tag' => 'img',
     //                     '#attributes' => array('src' => '', 'id' => 'signature_thumb_test', 'class'=>array('align-right'), 'width' =>'120px', 'height' => '60px' ));

    $field_name = $items->getName();

    /*function getFieldName() {
      return $field_name;
    }*/

    $text_area_id = 'signature_field_' . $field_name;

    $file_upload_help = array(
      '#theme' => 'signature',
      '#sign_src' => $value,
      '#text_area_id' => $text_area_id,
    );

    $element += array(
      '#type' => 'textarea',
      '#default_value' => $value,
      '#attributes' => array(
        'id' => array($text_area_id),
                        ),
      '#attached' => array(
        'library' => array('signature_field/signature_pad'),
                        ),
    );
    $element['#attached']['library'][] = 'signature_field/signature_pad';
    $element['#description'] = \Drupal::service('renderer')->renderPlain($file_upload_help);
    $element['#attached']['drupalSettings']['signature_field']['sign']['id'] = $text_area_id;

    return array('value' => $element);
  }

}

```

It is then available in your JS as follows.

```
var canvasId = drupalSettings.signature_field.sign.id;
            console.log(canvasId);

```

---
Tags: 8, hooks
---


# Question
Title: security kit module settings are blocking own site jQuery calls
I am using Security kit module to enhance security for my website. In that I have enabled `Enable JavaScript + CSS + Noscript protection` option. This setting is blocking one of Jquery call that is `.load` functionality. The description of this option is here:

> Enable protection via JavaScript, CSS and Noscript tag. This is the most efficient Clickjacking prevention technique. If webiste is not being framed, seckit.document\_write.js starts commenting with document.write() and stops when reaches stop SecKit protection. Thus seckit.no\_body.css, which sets body display to none, is ignored. If particularly this JavaScript file is being blocked (with XSS filter of Internet Explorer 8 or Safari), seckit.no\_body.css sets display: none to body. If JavaScript is disabled within browser, it shows a special message.

This is the JavaScript code.

```
$("[name='dest-target']").click(function(e){
  jQuery("#test_file_download").load(Drupal.settings.basePath + Drupal.settings.pathPrefix + "node/hit/ajax", {'path': filenodeurl});
  return false;
});

```

Please suggest me any alternatives I can use for this.

# Answer
If this code inline, then try with this:

'unsafe-inline'

Allows the use of inline resources, such as inline elements, javascript: URLs, inline event handlers, and inline elements. You must include the single quotes.

'unsafe-eval'

Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes.

Howewer, the proper way to set up this module you can find this.
> 0 votes

---
Tags: 7, javascript, ajax
---


title: Sub-Website within a bigger website

text:
# Question
Title: Sub-Website within a bigger website
I want to create an entirely new website within a drupal7 website.
For example:
**www.school.edu** will have theme A (not sure if theme's the right word, basically, different looking webpage). And all its subpages and paths will have the same thing. (i.e. www.school.edu/**news**, wwww.school.edu/**about**, www.school.edu/**contact** ... etc).

### **And, I want a new website within www.school.edu to exist. And that new website should have a different theme.**

for example:
**www.school.edu/compsci** will have theme B. And all the subpages that follows under **compsci**/ should all have the same themes; by having a different theme, I mean they will have different headers, different logos, different main menus, different everything, basically entirely new website. (i.e. www.school.edu/**compsci/news**, www.school.edu/**compsci/about**, www.school.edu/**compsci/contact**

I have looked around for answers; it's just that I haven't been able to phrase my question well and I thought if I explained it as such, I would be able to get more accurate answers.

With the code below, I have been able to make each subpage that exist under /compsci to go to page\__layout\_1 ...

```
function theme_preprocess_page(&$vars, $hook) {
    $path = drupal_get_path_alias($_GET['q']);
    $current_page_path = explode('/', request_path());

    if ($current_page_path[0] == 'compsci') {
      $vars['theme_hook_suggestions'][] = 'page__layout_1';
    }
}

```

Now, the question is, how I would be able to define different main-menus, different nav-bars, so on. I am quite new to drupal so some terms I am still unfamiliar with -- do I create custom themes or custom modules -- what's the best approach to this?

# Answer
You can set different themes using hook\_custom\_theme()

```
function HOOK_custom_theme() {
  if(arg(0, drupal_get_path_alias()) == 'compsci') {
    return 'theme_machine_name';
  }
}

```

When you create menus, they will create a block. You can enable the menu blocks on a per-theme basis.
> 1 votes

---
Tags: theming
---


title: Developing coding skills

text:
# Question
Title: Developing coding skills
I am finally retired and have a bit more time on my hands. I'm pretty good with CSS and building a site from Drupal 8 using it "out of the box". But I'm hopeless when it comes to additional PHP coding, and adding patches etc.

Lots of the advice I see on Drupal Answers goes over my head - can anyone point me in the direction of lessons in simple coding for Drupal?

# Answer
> 2 votes
Welcome to the community! It's nice to see interest from people who come from other angles :)

Although this type of question isn't suitable for this platform, I'll try to answer anyway. If you want more help I recommend you try chatting on IRC with other Drupal developers and see what they recommend.

Unfortunately no one has managed to write a programming book for non-programmers, at least I'm not aware of any. If that were possible then no one would write programming books for programmers ;)

You'll probably need some PHP intro course if you want to start with Drupal, then pick up any Drupal development book that is beginner friendly.

You could probably also get by by using code snippets available online in tutorials and on drupal.org. There's plently already available if you're trying to solve common problems.

But the Drupal projects don't include only the engine part, there's the database side of things. You can try to learn basic SQL. There are excellent books you can find, and plenty of freely available intros online too.

You mentioned patches, that is a workflow side of things, versioning code, you need to learn Git for that. Also a lot of free online help in that department.

It's a long way to go if you're a newbie but want to get to a point where you can solve most Drupal problems yourself. If you're not doing it for your own pleasure, if you want to build projects for others, maybe honing your existing skills would be better, in partnership with someone else who complements you. There are plenty of Drupal programmers who can't CSS and don't have the breadth and depth of knowledge about existing Drupal modules, how to configure Views for common cases etc.

# Answer
> 2 votes
I'm not sure how long your question will be open, usually broad question are closed quickly.

But I can recommend to take a look at drupalize.me or buildamodule.com. Many aspects of Drupal are explained clearly, even when you're just starting with Drupal.

---
Tags: 8
---


title: Show what views a node is in

text:
# Question
Title: Show what views a node is in
I have created views called 'Awards' and in these award views they reference 'food item' nodes. Within the view a food item can be 1st, 2nd, 3rd, depending on certain filters/reasoning to create this list.

So, if a food item is 1st in an Awards view, how can I automatically put this on a 'food item' node to show that this food item has won an award?

**More info on the views**

They are created and sorted/filtered by specific things, one view might be 'Most calorific meal' and then it just lists meals by calories in them. Then I get a 1st, 2nd, 3rd. So if hamburger comes up as 1st, I want to put a badge on the hamburger food item node saying it's 1st in the Awards section for: Most calorific food item.

# Answer
> 0 votes
You could probably do that with Views, clone your Views into three Block Displays, one for each prize (1st, 2nd, 3rd).

Limit the Pager to show only one result, but for 2nd and 3rd set the Offset value to 1 and 2 respectively.

Use Contextual filters to pull node info into the View (node that the Block will be displayed on, basically all food item nodes). Set the Contextual filter settings to Hide View if there's nothing to see, in other places possibly as well.

Then display all 3 Blocks on food item nodes. If there's a "hit" for any prizes the relevant Block will be displayed on that node. If not, then the hiding should take care of it.

I don't think there's a contextual filter for Views counter, that goes a bit reverse, context from Views. It might be useful here, but alas no go.

---

All that said, depending on your project structure, there are probably better ways of solving this. Flag and Rules modules come to mind. You could create 3 flags, and use Rules to programmatically assign flags based on criteria (they wouldn't be flags that users use).

---
Tags: views
---


title: using twig | replace filter in a view

text:
# Question
Title: using twig | replace filter in a view
I'm using textbox replace in a view for an ICAL and I need to get the special characters to render. Right now calendars like Google Calendar just shows the encoded characters instead of the decoded characters. I want ' instead of this ' .

right now it's not doing anything. I've tried multiple ways to pull this off using |render or using replace | but nothing works. It still just shows up with the encoded characters. example below

```
{% set special_1 = ''' %}
{% set result_1 = "'" %}
{% set special_2 = '&' %}
{% set result_2 = '&' %}

{{ title_1|replace({ (special_1): result_1, (special_2): result_2 }) }} - {{ field_sport|replace({ (special_1): result_1, (special_2): result_2 }) }}

```

# Answer
You can write try custom Twig\_Extention

In `yourmodule` create service

yourmodule.service.yml

```
services:
  custom_replace:
    class: Drupal\yourmodule\TwigExtension\Custom_Replace
    arguments: ['@renderer']
    tags:
      - { name: twig.extension }

```

src/TwigExtension/Custom\_Replace.php

```
<?php

namespace Drupal\yourmodule\TwigExtension;

/**
 * Class Custom_Replace.
 */
class Custom_Replace extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'custom_replace';
  }

  public function getFunctions() {
    return [
      new \Twig_SimpleFunction(
        'custom_replace',
        [$this, 'custom_replace'],
        ['is_safe' => ['html']]
      ),
    ];
  }

  /**
   * {@inheritdoc}
   * @param $search can a array [`word1`,`work2`] or string `word`
   */
  public function custom_replace($string, $search, $replace = '') {
    return str_ireplace($search, $replace, $string);
  }
}

```

In template `yourpage.html.twig`

```
{{ custom_replace('word','',string) }}

```
> 2 votes

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


# Question
Title: Manage Display Field Label not changing: inline does not work
I have the same problem as question 212176 and discovered it has to do with CSS. I have 2 (local) sites both with module ds enabled. I configured in both a field where I want the label and the value in one line: inline

With the classy-theme, this works fine. With the IceMagic theme it does not.

I have "inspect element"-screenshots of both. As there is no float:left with IceMagic, I believe this is the reason the label stays above.

Where and how to fix this?

# Answer
> 0 votes
Solved!

I used Firefox Developer Edition tools to find the relevant css code in a working theme. I copy/pasted this piece of code into the styles.css file of the theme of my choice and adjusted the class-names (single dash instead of double-dash and double-underscore).

To tidy up I should make a subtheme with my adjustments and leave the theme as it is.

I made even a little improvement to the original code: label will be aligned to left of the column and content to the right (I am using Display Suite to divide the content into a column view)

```
.field-label {
  font-weight: bold;
}
.field-label-inline .field-label {
  float: left; /* LTR */
}
.field-label-inline .field-items {
  float: right; /* LTR */
}
.field-label-inline .field-label,
.field-label-inline > .field-item,
.field-label-inline .field-items {
  padding-right: 0.5em;
}
[dir="rtl"] .field-label-inline .field-label,
[dir="rtl"] .field-label-inline .field-items {
  padding-left: 0.5em;
  padding-right: 0;
}
.field-label-inline .field-label::after {
  content: ':';
}

```

---
Tags: 8, theming, display-suite
---


# Question
Title: Problems moving whole project from one directory to another
I have Xampp Portable installed on Windows 10.

I run about a dozen Drupal, Wordpress and other CMS on there. I can move the whole stack to different drives and machines and it all works perfectly, only one that can't work is D7/CIVICrm install.

When I move it to another directory I get this error:

```
 Fatal error: Cannot redeclare class CRM_Core_ClassLoader in C:\Core\XAMPP_2018\htdocs\crm4\sites\all\modules\civicrm\CRM\Core\ClassLoader.php on line 36

```

I can see that the path in the error is the wrong path.

The correct new path is:

```
G:\XAMPP_2018\htdocs\crm4

```

And not:

```
C:\Core\XAMPP_2018\htdocs\crm4\

```

As stated in error, where should I go change that setting? In what file/directory?

# Answer
> 0 votes
Had to change the path name in civicrm.settings.php from:

```
G:\XAMPP_2018\htdocs\crm4

```

To

```
C:\Core\XAMPP_2018\htdocs\crm4\

```

This is around LINE 180:

Code looks like this:

$civicrm\_root = 'G:/August25/XAMPP\_2018/htdocs/crm4/sites/all/modules/civicrm'; if (!defined('CIVICRM\_TEMPLATE\_COMPILEDIR')) { define( 'CIVICRM\_TEMPLATE\_COMPILEDIR', 'G:/August25/XAMPP\_2018/htdocs/crm4\sites\default\files\civicrm\templates\_c\\'); }

But the slashes also have to be forward like this "/", I searched from Windows path, that's why I couldn't find the code using find and replace!

---
Tags: civicrm
---


title: Custom Jquery for Entity reference form

text:
# Question
Title: Custom Jquery for Entity reference form
How do I add Custom Jquery On-click event on a checkbox which is inside an Entity reference form?

In the below screenshot, "Study" is the Parent node. "Demographics", "Biological collections", etc. are entity reference fields.

Biological collections is a "multiple inline entity form", and is rendered only after clicking Add new Collection button (not shown in screenshot, but something like "Add new node" button)

"blood\_fs" is also an entity ref field within Biological Collection content type.

What I am trying to achieve: When I click on "Blood" checkbox, I want to trigger "Add new node" button. (Add new node button should not be displayed to the user, it should be hidden all the time!)

JQuery code:

```
(function ($) {
    $(document).ready(function(){
        $(".blood-div input.form-checkbox").click(function() {
            alert(123);
        })
    });
})(jQuery);

```

This code does not work within the inline entity form, but if I open the entity node separately in a different tab, jquery works.

Below is the code with Drupal.behaviours:

```
Drupal.behaviors.someArbitraryButUniqueKey = {
  attach: function (context) {
    addMyEvent();
  }
};

function addMyEvent(context) {
  $(".blood-div input.form-checkbox").once("add-my-event", function() {
    $(this).click(function() {
      alert("123");
    });
  });
}

```

# Answer
> 1 votes
In Drupal, we don't use $(document).ready(). Instead, Drupal.behaviors is used, in combination with $.once(). I actually wrote a fairly detailed explanation just the other day here: on('load') is not working with jQuery 3?

You'll need to wrap your code in an anonymous function like you did in the original code:

```
(function ($, Drupal) {
  // Code goes here
}(jQuery, Drupal));

```

---
Tags: 7, entities, javascript
---


# Question
Title: Custom entity form submit handler not being invoked
I'm trying to attach a submit handler to an entity form (language\_delete\_form) provided by the ConfigurableLanguage config entity. On the form alter function for that form, the top-level submit handler value looks like `$form['#submit'] = ['::submitForm']`.

I want to add an additional submission handler, so it looks like `$form['#submit'] = ['::submitForm', 'locale_delete_language_submit']`. However, locale\_delete\_language\_submit is not being called during the submission process (I would expect it to be invoked after LanguageDeleteForm::submitForm is invoked). What am I missing here?

Based on Berdir's comment here (https://www.drupal.org/project/drupal/issues/2252165#comment-9437863) I would have expected the function to be invoked.

Here's my code:

```
/**
 * Implements hook_form_FORM_ID_alter() for language_delete_form().
 */
function locale_form_language_delete_form_alter(&$form, FormStateInterface $form_state) {
  $x = 5;
  $form['#submit'][] = 'locale_delete_language_submit';
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function locale_delete_language_submit($form, FormStateInterface $form_state) {
  $defined_value = 'fifty';
}

```

# Answer
> 1 votes
As discussed in slack, you misunderstood my comment. You should add it to the form-level submit callbacks if and only if that form has no button-level submit callbacks.

If it has, then you need to add yours there as well.

---
Tags: 8, entities
---


# Question
Title: How can I get exposed filter for content type from the view programmatically?
I want to customize an exposed filter for content types, how can I get the exposed filter for a view in the code? And to know exactly which content types need to be dispalyed?

```
$route = explode('.', \Drupal::routeMatch()->getRouteName());
if (!empty($route) && $route[0] == 'view') {

  if ($view = Views::getView($route[1])) {
       $filters = $view->getHandlers('filter');

  }
}

```

# Answer
It might be easier to get the display settings from the View storage (the configuration of the view):

```
$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
$display = &$storage->getDisplay('page_1');
$display['display_options']['filters']['nid']['value']['value'] = 123;
$storage->save();

```

Here you should be able to find all options configured in the Views UI.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to show tooltips using a bootstrap sub-theme in a views filter?
I am using the bootstrap Tweme theme and would like to **show tooltips when hovering over exposed filters** (e.g. haslanguagecertificate) in a view. When hovering over profile edit fields the help text is shown properly.

I have also added the snippet in html.tpl.php before the closing \< / body\>.

```
(function($) {
   $(document).ready(function() {
   $('[data-toggle=tooltip]').tooltip();
   });
})(jQuery);

```

This has How to show tooltips on form labels based on view filter descriptions in a Bootstrap sub-theme? that helped, but the tooltips are not showing up. Devel does not show \['title'\]\['#attributes'\] - what do i have to write here?

```
/**
 * Implements hook_form_FORM_ID_alter().
*/

function customisations_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
dpm($form);
// $field_name = 'filter-title';
$field_name = 'filter-field_haslanguagecertificate_value';
$form['title']['#attributes'] = array(
  'data-toggle' => 'tooltip',
  'data-original-title' => $form['#info'][$field_name]['description']
  );
 $form['#info'][$field_name]['description'] = '';
}

```

# Answer
form\['title'\] needed to be replaced with the fieldname without "filter-".

```
function customisations_form_views_exposed_form_alter(&$form) {
  //drupal_set_message("setting exposed filter tooltips", 'status');
  //dpm($form);
  $allFilter = array();
  $filtersList = array_keys($form['#info']);

for ($i =0; $i<count($filtersList); $i++) {
    //drupal_set_message("filter " . $filtersList[$i], 'status');
    array_push($allFilter,$filtersList[$i]);
  }

  foreach ($allFilter as $field_name) {
    $fieldTitle = substr($field_name,7); //removes the filter-
    $form[$fieldTitle]['#attributes'] = array(
    'data-toggle' => 'tooltip',
    'data-original-title' => $form['#info'][$field_name]['description']
  );
  $form['#info'][$field_name]['description'] = '';
}
}

```
> 0 votes

---
Tags: 7, views, bootstrap-theme, tooltips
---


# Question
Title: How can I prevent the display of CAPTCHA for other forms except the login form?
I have Drupal 7.59 installed and CAPTCHA is visible for several forms. I want it visible only for the login form.

In this section: admin/config/people/captcha, I set the 'No Challenge' for other form-ID and login-form set on 'default challenge type' but the CAPTCHA gets displayed on all forms: by this text : "CAPTCHA: NO CHALLENGE ENABLED".

How can I prevent the display of CAPTCHA for other forms except the login form?

# Answer
> 1 votes
The message "*CAPTCHA: no challenge enabled*" indicates, that the form in question is not protected by a captcha.

This message is shown to site administrators and users with the "*Administer CAPTCHA settings*" permission only. It is intended to ease administering captchas on the form. You could, e.g. click the message to open a link that allows you to enable a captcha for this form.

If you don't require these administrative links, you can disable them within the captcha module settings. In your administrative back-end navigate to *Configuration \> People \> CAPTCHA*.

Locate the option "*Add CAPTCHA administration links to forms*", uncheck it and save the settings. The administration links should be gone.

---
Tags: 7, captcha
---


# Question
Title: How to make 'Views' consider contextual filter value to be 'all' automatically?
What I am trying achieve here(d7) is a bit cleaner URLs which is looking odd due to **8-12 contextual filters.** Except 1 or 2 filters others will be `/all` most of the times.

Suppose I have 5 contextual filters. When only the first one has value, the URL becomes `example.com/24/all/all/all/all`. Is there a way we can avoid "`/all/all/all/all`" ?

I have also tried using query parameters through PHP CODE.

If I choose *'Provide default value' -\> 'PHP code' and use*

```
$query= $_GET['clr'];
return $query;

```

Is there a way we can tell views to consider "`query=all`" for other queries automatically if that part is omitted in URL?

For ex: If URL is

> example.com?clr=1234

the view should assume it to be

> example.com?q1=all&q2=all&q3=all&q4=all&clr=1234

# Answer
> 0 votes
I don't know if it clashes with your configuration, but usually you use the option **Display all results for the specified field** under `When the filter value is NOT available`.

---

There is also the option under `When the filter value IS available or a default is provided` \> `Specify validation criteria`:

**Action to take if filter value does not validate**

where you can choose to `Display all results for the specified field`. Maybe you can combine it with some Validation conditions to achieve what you want.

# Answer
> 0 votes
I didn't find solution for contextual filter. But the behavior I wanted is achieve is possible by using

`Filter Criteria (Exposed)` instead of `Contextual filter`.

Here instead of using `Exposed Filter form`, I am providing `Links` which is working fine.

---
Tags: views
---


title: Image File field not getting updated

text:
# Question
Title: Image File field not getting updated
Form function:

```
$form['upload_photo'] = array(
        '#type' => 'file',
        '#title' => t('Upload Your Photo'),
        '#title_display' => 'before',
        '#states' => array(
            'visible' => array(
                ':input[name="testimonial_type"]' => array('value' => 'Text'),
            ),
        ),
        '#prefix' => '<tr><td>',
        '#suffix' => '</td></tr>',
    );

```

Submit function:

```
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_text_testimonial_info'));
$file_d = $form_state['values']['upload_photo'];
                $file = file_load($file_d);
                $file->status = FILE_STATUS_PERMANENT;
                file_save($file);
                file_usage_add($file, 'user', 'TYPE', $file->fid);
                $file_info = image_get_info($file->uri);
                $file_arr = array(
                'fid' => $file->fid,
                );
                $field_collection_item->field_client_image[LANGUAGE_NONE][0] = $file_arr;
                $field_collection_item->setHostEntity('user', $user);
                $field_collection_item->save();

```

After submit I am getting below error:

* Notice: Undefined property: stdClass::$uri in file\_save() (line 614 of /public\_html/includes/file.inc).
* Notice: Undefined property: stdClass::$filename in views\_data\_export\_file\_presave() (line 278 of /public\_html/sites/all/modules/contrib/views\_data\_export/views\_data\_export.module).
* PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file\_managed} (filesize, status, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> 1 \[:db\_insert\_placeholder\_2\] =\> 1535026403 ) in drupal\_write\_record() (line 7386 of /public\_html/includes/common.inc).

Kindly help me to solve it out

# Answer
Maybe this can help How to upload file in drupal8 forms with form element type file?

I see for your use case it makes more sense to use Managed file type.

A couple of observations, something you should look at,

* It seems you are getting SQL errors due to trying to upload a file which is already present in the table, you should check why this happens and perhaps programmatically change the name of the file if it already exists. See file\_save\_data
* Errors from views, not sure where you are trying to submit this form, but it is clearly breaking something in views\_data\_export or it maybe because of the next point.
* Lastly, check the link above for how to properly handle file uploads in form, it looks like `file_save($file);` is breaking for you due to missing `uri`
> 0 votes

---
Tags: forms
---


# Question
Title: Edit existing 'if' condition to add a class to a div and display / hide divs
I am using a template which has an 'if' argument to alter the output of a div containing an image field. I need to add my own condition (within comments) to it. Currently the output is creating the image twice (see attached screenshot).

```
<!-- added for publication image formatting -->
  {% if content.field_download_resource|render %}
  <div{{ attributes.addClass('pub-img') }}> {{ content.field_image }}
  {% endif %}
  </div>
<!-- end add for publication image formatting -->

<div class="post-thumbnail post-{{ post_format }}">
  {% if post_format == 'video' or post_format == 'audio' and gva_iframe %}
    {{ gva_iframe|raw }}
  {% elseif post_format == 'gallery' and content.field_post_gallery %}
    {{ content.field_post_gallery }}
  {% else %}
    {{ content.field_image }}
  {% endif %}
</div>

```

The first 'if' argument confirms if there is a value for the field download\_resource, and if there is a value, it adds the class '.pub-img' to the div containing the output of field\_image. The second 'if' argument acts on the same div but displays the content of different fields, **OR** the same field\_image with a different class applied to it, depending on different conditions. Right now my page output is displaying **BOTH** images, as below:

I don't want that to happen. What I need to do is **ONLY** display the output of the first 'if' argument in the div (and remove the display of the larger image) if there is a value for the field\_download\_resource, **OR ELSE** display **ONLY** the larger image and not the smaller image (output of the first 'if' argument).

I have tried various methods to combine the two 'if' arguments into one, but nothing seems to work. I get the "unexpected error" message. I have reached the limit of my knowledge of drupl 8 Twig theming, and am now appealing to the experts to lend a hand.

# Answer
> 0 votes
So here's the correct code, which I figured out after a lot of trial and error. Posting it here so that it helps someone else in the same predicament.

```
<!-- added for publication image formatting -->
  {% if content.field_download_resource|render %}
  <div class="pub-img"> {{ content.field_image }} </div>
<!-- end add for publication image formatting -->

{% elseif content.field_download_resource|render is empty %}

<div class="post-thumbnail post-{{ post_format }}">
  {% if post_format == 'video' or post_format == 'audio' and gva_iframe %}
    {{ gva_iframe|raw }}
  {% elseif post_format == 'gallery' and content.field_post_gallery %}
    {{ content.field_post_gallery }}
  {% else %}
    {{ content.field_image }}
  {% endif %}
</div>

{% endif %}

```

Thanks...

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


# Question
Title: How to remove (not verified) status in anonymous comments?
If I allow users to comment while they are not logged in (anonymous authors), they will have a 'not verified' tag next to their name in the comments of my site. How can I remove it?

# Answer
> 5 votes
You can implement `hook_preprocess_username` and remove the `extra` variable:

```
function THEME_preprocess_username(&$variables) {
  $variables['extra'] = '';
}

```

# Answer
> 5 votes
It's also possible to change that in the backend.

`Appearance` » `Settings` » *uncheck* `User verification status in comments` in the `Page Element Display` section

---
Tags: 8, theming, users, comments
---


title: How do I insert a block into a node?

text:
# Question
Title: How do I insert a block into a node?
I can't insert a block into an article on Drupal 8.

I installed the module, created a custom block, created an article using the *Full HTML* input format, inserted `[block:block=1]` into the article body, and saved it.
Nothing happened. `[block:block=1]` appears in the text instead of the desired block. I tried to find something in admin/config/content/formats/manage/full\_html to make Drupal recognize the inserted blocks, but I found nothing.

Am I doing something wrong?

# Answer
The insert block module implements an "input filter" via the core Filter module. A text format is a collection of enabled input filters. So when enabling a module that provides an input filter, the next step would be to configure the text format to *use* the input filter.

The Full HTML text format does not have that input filter enabled by default.

In addition the module has a Drupal 8 development release, but the code underneath still seems to use PSR-0 for its class loading and has not been updated in *3 years*. It may be broken for other reasons as well.
> 2 votes

# Answer
There is a new patch (https://www.drupal.org/files/issues/2018-06-08/2648496-46.patch) for `insert_block` and now the module works very well. I've tested it on a new Drupal 8.5.5 install.

See this issue for more information : https://www.drupal.org/project/insert\_block/issues/2648496#comment-12644966
> 1 votes

# Answer
You need to use hook\_preprocess\_page, put the block into a variable and then you print that variable in your template file (like this: {{ variable\_with\_the\_block }} ).
> 0 votes

---
Tags: nodes, blocks
---


# Question
Title: Why do users with permission to post commenst get "You do not have permission to post a comment"?
I have some users with roles administrator, authenticated etc. All such user roles have permission to post a comment.

But when posting a comment it is showing error "You do not have permission to post a comment." along with "Your comment has been queued for review by site administrators and will be published after approval."

How can I solve this issue?

# Answer
> 0 votes
Go to the admin/people/permission check for comment section in permission page where you can see **skip comment approval** you need to give appropriate permission for the user.

Like below screenshot.

---
Tags: 8, comments
---


# Question
Title: How can I print current user role in Twig?
I'm trying to get my user role thanks to a function in my theme.theme file.

```
function theme_get_user_role(){
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
}

```

then in my view :

```
{% set roles = theme_get_user_role() %}
{{ dump(roles) }}

```

But I have this error :

> Twig\_Error\_Syntax : Unknown "theme\_get\_user\_role" function. dans Twig\_ExpressionParser-\>getFunctionNodeClass()

What do I miss ?

# Answer
You can use below without any function. Because the User module provides the variable in preprocess for all templates: :

```
{% set roles = user.getroles(TRUE) %}
{{ dump(roles) }}

```

If you want to do anything only for the particular role then do this:

```
{% if 'ROLENAME' in user.getroles(TRUE)  %}
  <p>The user has the role "ABC".</p>
{% endif %}

```
> 17 votes

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


# Question
Title: Save and set an external link image programatically
I have a field that will accept an image link coming from the external source. But of course, to set that image I have to save it in Drupal first. I'm wondering how do Drupal save the image from an external link. I use the following code.

```
$imageUri = 'https://api.statvoo.com/favicon/?url=google.com'; // this is a favicon

$file = File::create([
          'uri' => $imageUri,
          'status' => 1,
        ]);
$file->save();

$user_profile->field_profile_image[] = [
        'target_id' => $file->id(),
        'alt' => 'Alt text',
        'title' => 'Title',
        'width' => 200,
        'height' => 200,
      ];

$user_profile->save();

```

I notice that the following values and the external image URL were added in the image field, but the image is not displayed on the page. Thanks in advance!

# Answer
Well, I think it is supported. I found an exact solution I need to be able to save and set an external image source inside Drupal according to Programmatically update node image field (using URI of the image) and get URL in twig.

I use this method system\_retrieve\_file.
> 0 votes

---
Tags: 8, media, files
---


# Question
Title: How do I disable the required address fields in the checkout page?
In Drupal 8, the Commerce Core module has a step after the customer selects checkout.

Left in the screen there is the payment information which contains a form with:

* Country
* Company
* First and last name
* Street address
* Postal code
* City

We only want:

* Country
* First and last name

I implemented `hook_form_alter()` but the form retrospection gives me no clue on which field I can adjust.

I also checked in the profile if there is any option, but I could not find them.

Do you have any suggestion?

# Answer
You need to edit the address field on the *Customer* profile type.

See `admin/config/people/profiles/manage/customer/fields/profile.customer.address`

In more recent versions of Commerce this can be found under `admin/config/people/profile-types/manage/customer/fields/profile.customer.address`
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: How to change the existing images embedded in Views Twig template to S3 bucket URL
I have embedded the images using views twig template,

```
file_url(row['content']['#row']._entity.field_future_program_image.entity.fileuri) %}

```

The output is `public://2018-07/10a_0_0.JPG`

Instead, I need the image URL from the s3 bucket: https://s3.bucketname/2018-07/10a\_0\_0.JPG

Note: I have configured amazon s3 and moved the local files to s3

# Answer
> 1 votes
Try adding

```
$settings['s3fs.use_s3_for_public'] = TRUE;

```

After that clear cache, now your site images will render form Amazon S3 bucket.

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


title: Get Role Label instead of Machine Name

text:
# Question
Title: Get Role Label instead of Machine Name
I want to know how to show role label in twig view.

I have this

```
{% set roles = user.getroles(TRUE) %}
{{ dump(roles) }}

```

It's giving me my role, but instead of showing **"Directeur (CR)"**, it's showing **"directeur\_cr\_"** (the machine name or database value).

How can I display "Directeur (CR)"?

# Answer
You can try like below:

```
function MYMODULE_field_template_preprocess_default_variables_alter(&$variables) {
  $variables['user_roles'] = user_role_names();
}

```

and in .twig file you can use as `{{user_roles['ROLE_NAME']}}`
> 0 votes

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


# Question
Title: How can I access the raw value of a view in a template?
I am looking for a way to get the url of an image dynamically to put it as a background. So I created a view that get the image field of the node or taxonomy term, which is supposed to output the url only (I have tried only with the node so far). I have been cleaning as much as possible everything inside the view and also the template of the view looks basically like {{rows}} and that's it. But there is still a wrapper div that I can't trim:

```
<div class="views-element-container form-group">
      <div>/sites/default/files/2018-08/bg_image.jpg</div>

</div>

```

**How can I trim the twig variable created in the theme to get rid of the html tags ?**

When I try strip\_tags() function in the theme preprocess or |striptags or |trim directly in the template, it's not working and I have a lot of errors starting with `Warning: strip_tags() expects parameter 1 to be string, array given in __TwigTemplate` for example

# Answer
> 0 votes
I found a solution. I was looking at the problem the wrong way. It is possible to get the raw url value of an image field in a page template by using native twig-drupal functions instead of using a view =\> https://drupal.stackexchange.com/a/224311/16146

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


# Question
Title: how to get values from two content types using one entity reference
I'm using Drupal 7 and have 3 content types -

1. Product
2. Purchase
3. Sales

In **sales** content type, I'm using entity reference I want to fetch and display "product name" from **Product** content type and "MRP" from **Purchase** content type. How can I achieve this by configuration?

# Answer
> 0 votes
If all 3 Content types need to be interrelated then it makes sense to use the *same* Entity Reference Field to connect them (two CTs both use the same Field to reference the third CT).

But this isn't a requirement, it just makes some things easier if using Views to display information from one CT node on related CT nodes. While this can be solved using Views there is an easier way.

## Use Content view modes to control ER Field display

The easiest way to control which Fields from the referenced node an Entity reference Field should display is to use Content type Fields **view modes** (not related to Views module).

You can see available view modes on the `Manage display` page of a Content type, at the bottom under `Custom display settings`.

You need to enable an existing view mode or create a new one on your `Product` and `Purchase` Content types, so they can be used for ER Field on Sales CT.

Select the view mode you want to use (Manage display page) for this purpose and on `Product` CT hide all the Fields except the `product name`.

Similarly, on the `Purchase` CT view mode you selected for this purpose hide all the Fields except `MRP`.

Then on `Sales` CT Manage display page (I'm assuming you have two different ER Fields, one for each CT referenced) select **Rendered entity** as your ER Field Format for both Fields, and change its configuration to use the view mode you configured in previous steps.

This way when you visit a Sales node it will show `product name` and `MRP` Fields from the referenced nodes instead of their node titles.

## Create new Content view modes in D7

You might need to create a new view mode for this purpose. In D7 it doesn't come out of the box (as it does in D8), but you can create new modes with the help of an additional module or a very simple custom module. Read all about it in this article: 3 Easy Ways to Create View Modes in Drupal 7.

## Display information from another node

To display one node information on a different page (in your case you want to display MRP field from a Purchase node on Service pages) you can use Views module (this is different from view modes mentioned above).

You use Views to create a Block Display, filter out the node you need, and show only the MRP Field. The place that Block in a region in your theme (maybe Content region) and configure it so it shows only on Service CT nodes.

1. Create a new View of showing `Content` of type `All`, `Create a Block` of `fields`, showing `0` item (this means unlimited, for performance reasons)
2. Add a new Filter `Content: Nid`, keep the Operator `Is equal to` and enter your Purchase node ID number in the `Value` field (you can see the NID number on that node Edit page in the link)

If you have Views preview enabled you can now see that exact Purchase node title in the Preview results
3. Rearrange the Filters so that `Content: Nid` Filter is above the `Content: Published (Yes)` Filter (this is for performance reasons)
4. Remove the `Content: Title` from Fields
5. Add a new Field `Content: MRP` (or whatever that field is called in your case), configure how you want that Field to appear on Service nodes
6. Save the View and place your Block in a region of your theme, but limit it to show only on `Service` CT

To test it visit one Service node and see if the Purchase MRP is showing there, and if you visit any other page then it shouldn't show.

---
Tags: 7, entities
---


# Question
Title: How do I count the number of unique visitors to Pages
How do I get the number of Unique visitors to the page? I need to get Unique visitors on each page or at the content level, how can I get it?

# Answer
> 0 votes
You can not with only a Drupal instance, it's an architecture issue. But you can use Matomo (former Piwik) for such needs.

If it is a simple scenario, you could get along with setting your own visit-cookie - but you need to program a module for this. And the result will be fuzzy cause of numerous caching steps.

# Answer
> 0 votes
You can take Node View Count module as a base and add the IP condition to be used.

Another solution is to have Google Analytics installed and request the data through some API.

---
Tags: nodes
---


title: Filter for field of current node

text:
# Question
Title: Filter for field of current node
I want to list (in a views block) only teasers of articles that are younger than the current node.

Somehow I have to use the current node from url-\>field\_date for filtering. Is this possible with views via the UI (Contextual Settings)?

Or do I have to create a module for that? If so... which hook should I use.. how to tell the view to filter?

# Answer
> 1 votes
Don't think its possible with just configuration and/or contrib modules.

I believe you have to override `hook_views_query_alter(&$view, &$query)` and add `$query->addWhereExpression` based on the current nodes date field.

Dig in `core/modules/datetime/src/Plugin/views/filter/Date.php function opSimple($field)` and perhaps core/modules/views/src/Plugin/views/filter/Date.php function opSimple($field) to see how they properly use the `addWhereExpression`

---
Tags: views, 8
---