# Question
Title: How can I stop Drupal from tracking or collecting IP addresses?
Is there a way to stop Drupal from tracking or collecting IP addresses of visitors? The specific need case is for a site that wishes to be able to say no identifying information is kept of visitors (it sounds seedier than it actually is).

I recognize that Apache logs are going to do this, and that will need to be handled separately, but I'm wondering if there's any way to prevent this in Drupal (or if you have suggestions on how to obfuscate incoming visitor IPs, that would be helpful as well)

# Answer
As mentioned in clives comment you could override `$_SERVER['REMOTE_ADDR']` in your settings.php to obfuscate incoming visitor IPs. Drupal's ip\_address() function than would return your obfuscated IP to any module that attempts to log IPs (like dblog).

Just **be aware** that any static or random address would **conflict** with a part of **Drupal's flood control mechanism** (the part that blocks IPs after too many failed login attempts; default: 50 within one hour). A static IP would expose you to the risk of locking every user out of the system. A random IP would render it useless.

Hashing the IP should work. The module cryptolog seems to to what you want and takes care of the flood control issue. From its project page:

> Cryptolog enhances user privacy by logging ephemeral identifiers rather than actual client IP addresses in Drupal's database tables and syslog.
>
> When Cryptolog is enabled, Drupal 8's \Drupal::request()-\>getClientIP() and Drupal 7's ip\_address() output a 128-bit HMAC of the client IP address (in IPv6 notation), using a salt that is stored in memory and regenerated each day.
>
> Because Cryptolog uses the same unique identifier per IP address for a 24-hour period, it is still possible to do some statistical analysis of the logs such as counting unique visitors per day. In addition, unlike other solutions of setting $\_SERVER\['REMOTE\_ADDR'\] to either one static IP address or a completely random IP address, Drupal's flood control mechanisms still function as normal.
> 1 votes

# Answer
Disable Statistics module ( or you have visitor or better\_statistics module disable them too).

Drupal by default don't save visitor IP's without enable or install any module.
> 0 votes

# Answer
I think it is impossible to do not collect visitor IP address without modifying Drupal's core code directly.

Drupal collects the visitor IP address using the function ip\_address().

As you can see in the code of that function, it doesn't invoke any hook or something similar to let you modify the IP before to return it. With one hook there you could think on, for example, remove the last octet of the IP, what would anonymize your visitors.

Drupal uses the IP to register what visitors do. And it stores the IP when the user logs in, in comments, in watchdog and syslog events, in poll votes, etc. And it is only for Drupal itself. But a lot of Drupal contributed modules would use the IP for their own purposes.
> 0 votes

---
Tags: 7, users, security
---


# Question
Title: How to get all parent nodes from a menu item?
Imagine the following menu structure:

* Page 1 *type: article*
* Page 2 *comes from a view*
    + Page 3 *type: desirable* \< want this
        - Page 4 *type: random*
            * **Page 5** *type: random*
* Page 6 *type: article*

Lets say I'm on **Page 5**. I want to know if any parent menu item's node has the content type *desirable*.

I got a menu item id `menu_link_content:uuid` for Page 5. My current approach is the following:

```
<?php

$values['menu_parent'] = 'main:menu_link_content:uuid';
list($menuName, $entityName, $uuid) = explode(':', $values['menu_parent'], 3);
$menuLinkManager = \Drupal::service('plugin.manager.menu.link');
$parents = $menuLinkManager->getParentIds($entityName . ':' . $uuid);

foreach ($parents as $parentPluginId) {

  $mlc_ids = \Drupal::database()
    ->select('menu_tree', 'mt')
    ->fields('mt', ['route_param_key'])
    ->condition('route_name', 'entity.node.canonical')
    ->condition('id', $parentPluginId)
    ->execute()
    ->fetchCol();

  // menu_tree gives back node=nid
  if ($mlc_id && strpos($mlc_id, 'node=') !== false) {
    // split node=nid into separate values
    list($entityString, $nid) = explode("=", $mlc_id, 2);

    // load the respective node and see if it is a project
    $parentNode = \Drupal::entityManager()->getStorage('node')->load($nid);

    if ($parentNode) {
      $parentType = $parentNode->getType();

      // we found the parent project node
      if ('project' == $parentType) {
        $node->set('field_project_ref', $nid);
        $node->save();
        drupal_set_message(
          t("The content was automatically added a project reference due to it's parent menu items."),
          'status'
        );

        break;
      }
    }
  }
}

```

So I would go on and load the node if the database statement found something and check the node type etc. I just wonder if there was a more performant/ better, out of the box way of doing that?

Something like

```
$menuLinkContent->getTargetEntity()->getType()

```

or

```
entityManager()->loadEntityFromMenu()

```

would be nice.

# Answer
I don't think there's anything as simple as $menuLinkContent-\>getTargetEntity()-\>getType(). Though that would be nice and I'd love for someone to correct me on that.

Below I wrote a method that loads the menu, loops through the menulink objects, grabs the url objects from them and loads the nodes based on the path of the url object. Once it has the node it gets the content type from it. I doubt it's better performance wise, but it does take advantage of more of the out of the box stuff and might be a bit easier to read.

```
$menu_tree = \Drupal::menuTree();
$menu = reset(\Drupal::entityTypeManager()->getStorage('menu')->loadByProperties(['uuid' => $uuid]));
$menu_parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu->id());
$menu_tree_elements = $menu_tree->load($menu->id());

foreach($menu_tree_elements as $menu_tree_element){
    $path = $menu_tree_element->link->getUrlObject()->toString();
    $node = self::nodeFromPath($path);
    $contentType = $node->getType();
    foreach($menu_tree_elements->subtree as $subtree_menu_element){
        $path = $subtree_menu_element->link->getUrlObject()->toString();
        $node = self::nodeFromPath($path);
        $contentType = $node->getType();
    }
}

function nodeFromPath($path){
        $path = \Drupal::service('path.alias_manager')
            ->getPathByAlias($path);
        preg_match('/node\/(\d+)/', $path, $matches)) {
        $nid = $matches[1];
        return Node::load($nid);
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Pass along field delta value to a rendered entity in an entity reference field
I have a field on a node type that references another node type. On the display side, I am setting it to a view mode to be rendered.

What I want to do is add a zebra stripe class. Every other node needs an extra class on its wrapper. I figure this should be done at the field twig level, but how do you pass in a value when it is rendered?

`field--field-related-content.html.twig`:

```
{% for item in items %}
  {{ item.content }}
{% endfor %}

```

In the node view mode template:

```
<a class="hl__type-promo" href="{{ path('entity.node.canonical', {'node': node.id() }) }}" title="{{ node.getTitle() }}" style="background-image: url('../../assets/images/fpo_16x9.png')">
  <div class="hl__type-promo__header">
    <div class="hl__type-promo__icon">
      {% include "@mytheme/svg/general/how-to.html.twig" %}
    </div>
    <div class="hl__type-promo__subject">How-To</div>
  </div>
  <div class="hl__type-promo__details"><h3 class="hl__type-promo__title">{{ label }}</h3>
    <div class="hl__type-promo__description">
      DESCRIPTION HERE
    </div>
  </div>
</a>

```

The node is unaware of where it is, so, whats the best way to pass a class? Is that possible? The field.html.twig file in classy wraps the field with a div, but thats not what I need to do here.

I suppose one way to do it is change the field twig to something like:

```
{% for item in items %}
  {% set classes = '...' %}
  <a class="{{ classes }}" href="{{ path('entity.node.canonical', {'node': item.content['#node'].id() }) }}" title="{{ item.content['#node'].getTitle() }}" style="background-image: url('../../assets/images/fpo_16x9.png')">
    {{ item.content }}
  </a>
{% endfor %}

```

But that feels dirty, and doesn't really make it reusable, not to mention I would have to inject the background image url through a field preprocess instead of just handle it in the node rendering.

# Answer
I did something like this in Drupal 7 and did have caching issues as 4k4 mentioned, but I think the cache issues would be easier to avoid in D8. You could do this by creating a new Field Formatter that extends EntityReferenceEntityFormatter.

You should be able to alter just the viewElements() method and add the delta information to the referenced entities. However, this will create an issue with the view mode being cached with your delta info. For example, you may have an entity be the first item the first place it's referenced and the second item the second place it's referenced, but it'll be cached from the first call so your delta alterations won't work how you'd expect. To workaround this issue, you can update the #cache settings for the entities and add a new key for the delta.

I would start by calling `parent::viewElements()` and then make a pass through that result to make the alterations (adding the delta value and updating the cache settings).

I would still alter the field template for the parent EntityReference field and add the class to a wrapping div rather than on the entity itself. You could create your own template file and add your own theme suggestion to make it more reusable, something like `field__zebra`, rather than relying on the default theme suggestion you mentioned above, `field__my_field_name`. I love Display Suite so I would create a Zebra DsFieldTemplate that I could reuse on any field I wanted.
> 2 votes

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


title: Multilingual comments in Drupal 8

text:
# Question
Title: Multilingual comments in Drupal 8
I set up an English/Arabic Drupal 8 website. However, comments are misbehaving. When a user enters a comment in the English version of the article, it appears in the Arabic version, and vice versa. I went through all the different options I can think of, but I ended up with all comments being treated and displayed as Arabic. I don't know what I'm missing, or what how I am supposed to configure it.

Shouldn't it respect languages out of the box?

Please, any help or documentation would be greatly useful. Thanx

# Answer
> 3 votes
At this moment in my team, we have identified 3 bugs around this, and to make this works you need to apply this 3 patches:

https://www.drupal.org/project/drupal/issues/2751269#comment-12559117

https://www.drupal.org/comment/12521645#comment-12521645

https://www.drupal.org/comment/12561153#comment-12561153

---
Tags: 8, i18n-l10n, comments
---


title: Search API cannot search taxonomy terms

text:
# Question
Title: Search API cannot search taxonomy terms
I have built a search page using Search API, specifically the database version. This search page is a simple view and works exactly how I'd expect it to.

However, now I need to update the index so that it will search taxonomy terms associated with each piece of content. For reference, the field in question is field\_author as a piece of content can be associated with several different authors.

From reading online, it seems like I should be able to edit the search index, scroll down to Add Related Fields, add Author, and that makes additional fields show up in the selectable fields to index section.

From there, I check the box beside Author \>\> Name (field\_author:name), click Save Changes, and reindex my field.

However, a search for an author name does not produce any search results and I'm not sure why.

# Answer
> 0 votes
The above steps were correct. Additionally however, you need to add Author \>\> Name to the Fulltext search filter criteria in the view.

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


# Question
Title: Drupal 8 Form Redirect On Failed Validation
I have a form which, upon failed validation, should query a custom/non-Drupal table, and if that query is successful, to redirect the user to a custom page that is only accessible through a logged-in state (so I need to "fake" successful authentication even if the user does not exist in the official Drupal users table).

The query to the custom table essentially checks a secondary user list in non-Drupal format upon failing to authenticate the official way, and if successful, would redirect the user to another page where they could select a Drupal username and password combination in order to register them in the system / make an official account.

This is the relevant code inside my form validation method:

```
if ($this->userAuth->authenticate($form_state->getValue('name'), $password) == FALSE) {
    // other stuff
    $uid = $this->userAuth->authenticate($form_state->getValue('name'), $password);
    $form_state->set('uid', $uid);

    $response = new TrustedRedirectResponse('/path/destination');
    $form_state->setResponse($response);
}

```

I have also tried this instead of the new TrustedRedirectResponse:

```
    $redirect_path = "/path/destination";
    $url = url::fromUserInput($redirect_path);
    $form_state->setRedirectUrl($url);

```

# Answer
> 1 votes
If you want the redirect to happen immediately, you can do it like this:

```
use Symfony\Component\HttpFoundation\RedirectResponse;

$response = new RedirectResponse('/path/destination');

$response->send();

```

---
Tags: 8, forms, redirection
---


# Question
Title: Why doesn't the view read cookies on AJAX refreshment?
I use views\_extras module to get default argument froom cookies. It works ok.

But if I set a cookie value using javascript and then refresh a view using ajax the view still shows result for previous value. So the new value affects only if I reload page.

Why and how to make ajax requests use current cookie?

Btw, I wrote my own module to read cookie value and use it as default argument: the result is the same with views\_extras module.

# Answer
> 0 votes
I figured out that an ajax view already has argument stored in drupalSettings.views.ajaxViews\["views\_dom\_id:..."\].view\_args

So the view gets this argument and use it instead of default argument from cookie. So we need to change the value of argument as well as cookie.

---
Tags: views, 8, ajax, cookies
---


# Question
Title: Can access arguments only be specified once for all sub-routes?
For example:

I would start off by setting this.

```
$items['admin'] = array(
 'access arguments' => array('administer users'),
 'type' => MENU_NORMAL_ITEM,
);

```

But the anytime after I use admin in my menu hook it would take on the same access arguments. So below would take on the same access argument as the above.

```
$items['admin/users'] = array(
 'page callback' => 'drupal_get_form',
 'page arguments' => array('get_users_page'),
 'title' => 'Users Listing',
 'type' => MENU_NORMAL_ITEM,
);

```

EDIT: To put in better words, thanks Jaypan. Can access arguments be inherited from their parent's access arguments?

# Answer
Basing on the documentation for `hook_menu()` access arguments are inherited from the parent route only if the access callback is inherited, and that only happens for `MENU_DEFAULT_LOCAL_TASK` routes.

For the code shown in the question, this would happen only if it would be written as follows.

```
function mymodule_menu() {
  $items['admin'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('get_users_page'),
    'access arguments' => array('administer users'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['admin/users'] = array(
    'title' => 'Users Listing',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  return $items;
}

```

I take the route names are used just as example. Since admin is already defined from `system_menu()`, it is better not to use route names containing admin or admin/.

As side note, the page callback is inherited from the parent route, in any case.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: What is easiest way to debug variables in nodes, views, blocks and page twig templates?
What is easiest way to debug variables in nodes,views,blocks and page template.

Earlier we used devel module in drupal 7 ,by using dpm() function it shows very neat and clean structure ,it was so easy to find out the values of variables.

Also what is the easiest way to get protected variables values.

why debugging became so complex in drupal 8?

# Answer
> What is easiest way to debug variables in nodes,views,blocks and page template.

Straight from the documentation:

> **Far and beyond the best way to deal with printing out variables is to use Xdebug.**
>
> If you use the other non-xdebug methods noted below you will have many recursive things rendering which may result in pages and pages of information that are not useful to you.

So using a proper debugger is the recommended approach. You might be tempted to use `var_dump`, or an extension thereof like the `kint()` tool included with devel, because it’s perceived to have less setup. But to reinforce the official documentation, I’d strongly advise you not to do that.

The hour it takes you to research and implement XDebug will be saved over and over again as you find yourself to be a much more effective debugger. Var dumping is an ok approach to debugging, but it’s pretty old fashioned, and becomes a frankly poor approach when compared to using XDebug in and IDE that knows how to integrate with it properly.

Plus you won’t run into resourcing issues - no more 500 errors when you try to `ksm($vars)` in a page preprocess method. No more waiting 30 seconds for the page to become responsive again after accidentally clicking the wrong part of the output.

> Also what is the easiest way to get protected variables values.

Protected properties are just that: protected. You’re not supposed to be able to get easy access to them unless the author of the class exposed a method for you to do so, or they’re designed to be available via magic methods. If such methods exist, you can use them, or if you’re determined to break convention you can get them via reflection. This isn’t an issue Drupal can or would attempt to solve.

Of course, your debugger will show you the values of protected properties without you having to hunt for them.

> why debugging became so complex in drupal 8?

It actually got easier in my opinion, I guess it depends on your outlook and experience. Yes there’s a small amount of overhead now, you have to set up a debugger, but anyone doing any development should have a debugger ready to go. You only set it up once, then you can use it in every project forever more with a couple of clicks, no extra code, no remembering to remove that debug code when you’re done, no 500 errors when one Twig call to `kint()` slips through to production where the devel module is disabled.

It’s not even a worthy comparison IMO, the debugger beats everything static var dumping can do every time. Once you’ve converted, I promise you won’t think about going back!
> 5 votes

# Answer
> What is easiest way to debug variables in nodes,views,blocks and page template

# Welcome to Kint 101

### Installing

Using Kint with **Devel 8.x-2.1**, which comes with the Devel module.

Using Kint with **Devel 4.0.1**. Kint no longer comes with Devel, you'll need to do
`composer require kint-php/kint` and apply patch.

**Important:** in order to use `kint()` in a twig file you need to enable debugging for twig. If you're not debugging inside a twig/template file, you can skip this part.

If you have Drupal Console installed `drupal site:mode dev`, remember to set it back to `drupal site:mode prod` when your developing is done.

If you don't have Drupal Console, do the following:

> You enable Twig Debugging in `sites/default/services.yml`. (If `services.yml` does not yet exist; copy `default.services.yml` and copy it to `services.yml`.)
>
> Set the debug variable to **true**. And clear cache.
>
> ```
> parameters:
>   twig.config:
>     debug: true
>
> ```

Remember to turn debug back to false after you're done developing.

Source Debugging Twig templates

### Now do the following to prevent issues with Devel 8.x-2.1, skip this part if using Devel 4.0.1

For starters, you are likely to run into this issue when you try a kint dump, specially if you just try
`{{ kint() }}` without passing any parameters

This is due to the array or object being too big for your server resources to handle the default kint settings.

Edit **/modules/devel/kint/kint/config.default.php** and set `$_kintSettings['maxLevels']` to a lower number to reduce recursion and the memory needed for dumping variables. The default is 7, I have mine set to 4. If 4 still doesn't work for you, keep lowering the number.

### Ok, lets use kint

**Note:** If you're trying to dbug when logged out, you'll need to give *Access kint information* permission to the anonymous user role.

For Example, in comments.html.twig we do a `{{ kint(content) }}` and you will see

### Tip #1 Do not click the + button, it's pure Evil

The + button will automatically open every single children and their children.

Instead, click on anywhere on the bar but the + button, for example, click here

Look how nice a tidy our Kint is

> Also what is the easiest way to get protected variables values.

### Getting a value

Lets say we're interested in the User. So click on user, but again **do not click on the + button**. You will see this

The id is protected, how do we get this value?

### Tip #2 click on the **available methods** tab

This will reveal all methods that we can use here

So simply go with the one that makes most since, here being `id()` to get the user id.

`{{ content.user.id() }}`

---

> why debugging became so complex in drupal 8?

It's not, as long as you know how to use Kint

Using all the above tips and tricks, I was able to answer this question Show comment author e-mail in comment.html.twig
> 16 votes

# Answer
You can use twig\_tweak module.

You can use `{{ drupal_dump(var) }}` or its alias `{{ dd(var) }}` to get a variable dump which works even if twig debug mode is disabled.

Here is full list of functionalities : Twig Tweak Cheat Sheet
> 6 votes

---
Tags: 8, debugging
---


# Question
Title: Views contextual filters summary display nodes id instead of title
I have a content type **customers** who has a required entity reference field to a content type **groups**. I have create a view to show all **customers** nodes and I have added a contextual filter over the entity reference field to display a summary of **groups** with a count of customers per group. The view uses fields, and I have added nid, title and reference field from the **customers** content type. It works good and if no group is in the argument, It shows the summary, but instead of display the titles of the group, It display the nid of the group.
Following this answer I have put the title when a group is selected, but the summary shows nids. What should I do to show this nodes titles?

**Edited**:if I do exactly the same with D7, it shows the titles as expected.

# Answer
> 1 votes
I have found how to do it. Firstly, I added the relation between customers and groups in the "relation" section. After this, instead of adding the relation field as contextual filter, I added the title field as contextual filter, but I checked the relation I have created. Then, when the argument is not present, It shows a list of groups (with their names) and the count of record.

---
Tags: 8, views
---


# Question
Title: Rewrite markup of a field in twig template
I want to calculate dynamical a value and give it back in the markup without saving the newValue. I try this with:

```
 {% set content.field_my_field[0]['#markup'] = newValue %}

```

This doesn\`t work! The "newValue" is given from preprocess\_node in the .theme file. Should I rewrite this directly in the preprocess function? How?

Found a solution in preprocess\_node. I tried to manipulate $variables\['node'\] instead of $variables\['content'\]

```
function mytheme_preprocess_node(&$variables) {
    $variables['content']['field_my_field'][0]['#markup'] = $newValue;
}

```

# Answer
> 0 votes
Sorry I couldn't be more verbose earlier, I was typing from a phone.

One way to solve this would be to just create a new template variable. Also, its easier to use the field value instead of parsing the render array - the contents of that array could change without warning. Not saying it happens a lot, but is possible. Just access the field value directly in one of two ways:

`$field_value = $node->get('field_name')->value;`

or

`$field_value = $node->get('field_name')->getValue();`

Note that not all fields will work that way, but most basic ones like text or textlong do. Reference fields for example will work a little differently.

```
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  if ($node->getType() == 'mytype') {
    if (!$node->get('field_my_field')->isEmpty()) {
      $variables['new_variable'] = $node->get('field_my_field')->value;
    }
  }
}

```

Then, in your `node--node-type.html.twig` template of your theme, where you want the field output, do:

`{{ new_variable }}`

Note that if you use `->getValue()` above, you need to dig into that value array to get the actual value as opposed to `->value`.

Always isolate the effort to the node type(s) and templates it should affect. In your question, you say you have this:

```
function mytheme_preprocess_node(&$variables) {
    $variables['content']['field_my_field'][0]['#markup'] = $newValue;
}

```

This code will fire for every node in the system any time it is loaded on that active theme. Unless that field exists on every single node type, it will cause a lot of warnings/notices in your logs. If you moved the field from visible to hidden from the admin UI, this code will fail as well, since the field will be removed from the `content` render array and not exist. I tend to also enforce checking both the node type *and* the view mode of that node being rendered too, but that is all up to what your design requirements are.

---
Tags: 8, theming
---


title: How do I name a theme file for view?

text:
# Question
Title: How do I name a theme file for view?
I am trying to theme a block from my view. I have a view called slides and it is creating a block. I have a template file I want this block to use. I have looked at the documentation for themes and the pattern to follow is

```
views-block--<viewname>.html.twig

```

or

```
block--views-block--<viewname>-displayid.html.twig

```

I can't find displayid for my block so I am trying to get that first option to work, but No matter what I do my block wont seem to take on the template I have written.

my template is named

```
views-block--slideshow.html.twig

```

What am I doing wrong with my names?

# Answer
> 0 votes
```
block--views-block--slideshow-block-1.html.twig

```

This is what it supposed to be. When configuring the block it gives the entire file name and I just needed .html.twig on the end of what the block name is in the configuration page for the block.

# Answer
> 1 votes
In your development.services.yaml file set twig debug to true and disable the cache by setting value to false.

After that you will see theme suggestions by inspecting element in browser.

# Answer
> 0 votes
In Drupal 7 under ADVANCED you just need to click the theme information link and it will show you all the template names.

In Drupal 8, you're are expected to turn on twig debug and see the template file suggestions. See Locating Template Files with Debugging

# Answer
> 0 votes
To quote drupal.org

> Also one more example with Views, if you have a block created by views with a view name "front\_news" and display id "block\_1" then the theme hook suggestion would be: block--views-block--front-news-block-1.html.twig (notice, when you have underscores in a display id or in a view name - you have to transform them in to a single dash)

Well in drupal 7 the "display id" is the **machine name** under "other"

Lets pretend the above picture is your Slides view.

Assuming its the same for 8, then it would be block--views-block--slides-block.html.twig (for the above picture)

If your machine name is block\_1 then it's block--views-block--slides-block-1.html.twig

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


# Question
Title: Expose single filter of combination of two fields in views
I have two user profile fields "Last Name" and "First Name". I also have a user list views. I want to expose "Name" as filter which can search for both Last Name and First Name. How can I do single filter of combination of those two fields? Can I create it from views UI?

One possible way is to create another profile field "Name" which will be hidden in the form. On user save, I would combine the two field values into the "Name" field and then expose it as filter in the views. But this solution is hard coding and it needs to write hooks.

# Answer
> 21 votes
I eventually got a solution from this. I followed the second primary solution offered although the blogger personally used `hook_views_query_alter()`.

1. installed the module Views filters populate.
2. added two filters "First Name" and "Last Name" (both must not be exposed) and added them to a OR filter group (Views 3 supports this). I had to use the operator "Contains any word" for both fields, otherwise the query gave me no desired result.
3. created a filter "Global: populate filters", added the two fields into this and exposed it.

This gave me a quick solution without hard coding.
Here is other helpful reference.

# Answer
> 13 votes
On my installation, D7 with Views 7.x-3.6, you can add a filter that is " Global: Combine fields filter" which will do exactly what you need, allow users to search on multiple fields with a single filter.

# Answer
> 5 votes
Its really easy.

1. Click on Add a filter.
2. select "Global: Combine fields filter"
3. Follow the instructions.

Thanks.

# Answer
> 2 votes
## Works out of the box

The easiest way to go is to use the **'Search Terms'** filter which is Views **core functionality**. It will search through all the fields of the entity and return the result, no extra module necessary!

1. Go to your View
2. Add a new filter to view
3. Select 'Search: Search Terms'

Thats it, nothing else to do (you might want to expose it though)

It performs very well too.

# Answer
> 0 votes
You can use hook\_views\_pre\_execute(&$view) to extend your single condition to multiple fields you wish

```
/**
 * Recursive looks for mentioning of $fname as field of in query QueryConditionInterface::conditions()
 *
 * @param array $cond result of QueryConditionInterface::conditions to search in
 * @param string $fname a name oof field we are looking for
 * @param array $res result array containing a references of conditions having $fname
 * @param integer $rec_lvl level of recursion
 *
 * @return array an array containing $fname mentioned in condition $res[]['field'] == $fname
 */
function dolynskyi_help_func_find_field_condition(&$cond, $fname, &$res = array(), &$rec_lvl = 0) {
    $numeric_keys = array_filter(array_keys($cond), function($k) {return is_int($k) || (substr($k, 0, 1) !== '#');});
    $rec_lvl++;
    foreach($numeric_keys as $numkey) {
        $t = gettype($cond[$numkey]['field']);
        if($t == 'string') {
            if($cond[$numkey]['field'] == $fname) {
                $res[] = &$cond[$numkey];
            }
        } elseif($t == 'object') {
            dolynskyi_help_func_find_field_condition($cond[$numkey]['field']->conditions(), $fname, $res, $rec_lvl);
        }
    }
    $rec_lvl--;
    return $res;
}

function dolynskyi_help_func_views_pre_execute(&$view) {
    if($view->name == 'appraisals_special_global_access') { // view name we wanna extend
        $fname = 'field_data_field_ap2_employee.field_ap2_employee_target_id'; // field we look for to use as source of extending
        $search = &dolynskyi_help_func_find_field_condition($view->build_info['query']->conditions(), $fname);
        foreach($search as &$v) { // looping found field references
            $or = db_or();
            $or->condition($v['field'], $v['value'], $v['operator']); //repeating existing field condition
            $or->condition('field_data_field_ap2_employee.field_ap2_employee_target_id', array('711'), 'IN'); //adding any extra condition
            $v = array('value'=>null, 'operator'=>'IS NULL', 'field'=>$or); // wrapping up simple condition for $fname to multiple with $fname + our extra field via OR logic
            unset($v);
        }
    }
}

```

---
Tags: 7, views
---


# Question
Title: Latest Saved Content keeps appearing on the front-page despite being configured in "content" and "content type"
Latest saved content without the title, always appears on the front page even thought in "Content" and "Content Type" it is configured not to show up on the front-page. The content is also disabled in the blocks, but it still appears on the front page.

# Answer
> 0 votes
By default drupal's frontage shows latest content published on site. In drupal this is a /node path which is a view in drupal 8 and a page in drupal 7. If you are using drupal 8 it will be as easy as justmodifying the view. In drupal 7 you can set a different front page in the system configurations and the latest published won't appear any more.

---
Tags: nodes
---


# Question
Title: How to display Commerce Order Owner role in Views fields?
Using Drupal 7.58 and Views 3.18

I am simply trying to display Commerce Order Owner role on a View. Using the Commerce Order:Owner relationship, I have access to a large set of user fields and properties... except the User role? Did I miss anything here?

EDIT : I am using Aggregation on my View (if you want to replicate this issue)

EDIT#2 : interesting workaround here, simply add the user role field before activate the aggregation... Still, I could not manage to build a chart and only a list of roles counted per user, using Table with aggregation options display

Related question : How to add the "user role field" in View showing users

# Answer
> 0 votes
No clue why it's not showing. The Views module defines a "User: Roles" field, and I see that just fine in my own development environment for a View joining to Users via the "Commerce Order: Owner" relationship.

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


# Question
Title: How to display a contact form as a node block?
I have a content type let’s say "hotels" and there are a bunch of nodes for different hotels. I would like to display a content form either as a block or in the node itself, where users can send an e-mail to the accordant hotel owner.

How can I do this? I have tried using display suite and entity reference but could not get this to work.

Thanks for your help :)

# Answer
> 1 votes
For non coding solution, you can go with

Create the form using **Webform** and utilizing **Webform Blocks** and **Token**

> Webform is the module for making forms and surveys in Drupal. After a submission customizable e-mails can be sent to administrators and/or submitters. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has an extensive API for expanding its features.

---

**Form Block**
> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

Worth mentioning, just might not do for this question's specific use case.

---

Do it programmatically by creating a custom block and fetching the form, you can find an example here Problems to integrate a form into a block

---
Tags: 7, nodes
---


# Question
Title: Can I conditionally hide a route (e.g. action / local task)
Consider an action button on a custom entity's canonical page:

mymodule.actions.yml:

```
entity.item.action:
  route_name: entity.item.action
  title: 'Do something'
  appears_on:
    - entity.item.canonical

```

mymodule.routing.yml:

```
entity.item.action:
  path: '/item/{item}/action'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ItemController::action'
    _title: 'Do something'
  requirements:
    _permission: 'edit items'

```

I would like to show or hide the action button depending on the value of some field of the entity.

How could I achieve this? Would it be wise to add custom access checking for this?

# Answer
> 2 votes
You can add a custom access method on your controller. According to this page you should have access to your `item` argument in the access method so you should be able to restrict access based on a value on that item. The action should be hidden if the user does not have access to the route, i.e. your custom access method denies access.

# Answer
> 2 votes
I was doing a similar task with `hook_menu_local_tasks_alter`. Keep in mind though that you will have to query for the current entity (e.g. node) separately as it is not passed into this hook as a parameter

Something like this:

```
function XXX_menu_local_tasks_alter(&$data, $route_name) {
  $routes = ['entity.node.canonical'];

  if (in_array($route_name, $routes)) {
    foreach ($data['tabs'][0] as $task_name => &$task_array) {
      if ($task_name == 'entity.node.canonical') {

        $node = \Drupal::routeMatch()->getParameter('node');
        if ($node instanceof \Drupal\node\NodeInterface) {

```

# Answer
> 0 votes
Two useful approaches are outlined in the Drupal 8 guide / Providing module defined actions. These are:

1. Derivers that dynamically generate one or multiple actions
2. Custom classes for the actions

I nearly solved the issue with approach 1. However, I'm still struggling with caching. This is my solution so far:

```
namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\mymodule\Entity\ItemInterface;
use Drupal\mymodule\Entity\Item;

/**
* Defines dynamic actions.
*/
class ItemLocalActions extends DeriverBase {

 /**
  * {@inheritdoc}
  */
 public function getDerivativeDefinitions($base_plugin_definition) {
   // Implement dynamic logic to provide values for the same keys as in example.links.task.yml.
   $id = \Drupal::routeMatch()->getRawParameter('item');
   $item = Item::load($id);

   if ($item instanceof ItemInterface) {
     switch($item->getStatus()) {
       case ItemInterface::STATUS_NEW:
         $this->derivatives['entity.item.action'] = $base_plugin_definition;
         $this->derivatives['entity.item.action']['title'] = t('Do something');
         $this->derivatives['entity.item.action']['route_name'] = 'entity.item.action';
         break;

         // add more derivative definitions here, depending on the item's state
     }
   }
   return $this->derivatives;
 }
}

```

and in mymodule.links.action.yml:

```
entity.item.state_actions:
  deriver: '\Drupal\mymodule\Plugin\Derivative\ItemLocalActions'
  cache_tags:
    - item_list
  appears_on:
    - entity.item.canonical

```

As stated above, caching is still a problem. Even though I set the appropriate cache tags, the actions are still rendered from cache.

Related questions:

---
Tags: 8, entities, routes
---


# Question
Title: The node from one content type doesn't appears in Nodequeue
I'm using Drupal 7 and nodequeue module with Royalslider.All other content types are working fine but only one content type which is named as **Real Estate Listing** doesn't show it properly.

Here's even it's available in queue list:

and here's how it's displaying in slider:

All of other content type nodes it displays all queues as:

But for Real Estate content type node it displays only 2 queues as:

What can be wrong?

Thanks in Advance!

# Answer
1. Go to admin/structure/nodequeue/
2. Click 'edit' for the nodequeue in question.
3. Check 'Real estate' under 'types'.
4. Save.
> 1 votes

---
Tags: views, nodes
---


title: Override labels in REST Export view

text:
# Question
Title: Override labels in REST Export view
I have a REST EXPORT view getting fields values of a node. I want to override the labels of these fields in the response returned. For example:- the returned response like this

```
[
    {
        "question_title": "How are you?",
}
]

```

I want the response like this

```
[
    {
        "questionTitle": "How are you?",
}
]

```

I tried to create label from the view but it doesn't affect.

# Answer
In your view's row style options you can rename any exposed field's label. The form labels those fields as **alias**.

This is screenshot from another view I was working on, but should give you an idea.
> 3 votes

---
Tags: views, 8
---


title: Custom username paths?

text:
# Question
Title: Custom username paths?
I want to be able to create paths like this:

```
/guy1
/guy2
/guy3

```

It's easy enough if I want /profile/guy1 ... then I can just do this:

```
gg_profile.viewUserProfile:
  path: '/profile/{username}'
  defaults:
    _controller: '\Drupal\gg_profile\Controller\GGProfileController::viewUserProfile'

```

But I want it to work with the /profile bit. Changing it as follows doesn't work:

```
  path: '/{username}'

```

How do I make it work without having the extra /profile bit?

# Answer
> 3 votes
You cannot: The part of the path after the first slash cannot be dynamic, so you cannot use /{username} as path. This is explicitly stated in Structure of routes, which describes *path* as follows.

> **path (required):** The URL to the route, *with a leading forward slash* (e.g., `path: '/book'`). You can use dynamic properties by including them in curly braces. (e.g., `path: '/node/{node}/outline'`). These will be passed along as arguments via *parameter converters* to the controller/form (see below). Note that the first item of the path must not be dynamic.

You can use /profile/{username}, but /{username} doesn't work.

# Answer
> 2 votes
Perhaps the Pathauto Module could come in handy for this. https://www.drupal.org/project/pathauto

Your use case is kind of vague so I don't know exactly what you want but you can use Pathauto to create 'dynamic' URL endpoints when creating new content/users. You can use tokens within the URL to add variables.

---
Tags: 8, routes
---


# Question
Title: Why is Search API only searching node titles?
I have a Drupal 8 site with a custom content type called "Story". It uses the provided body field with machine name "body". Although I have set up configured Search API, it seems to only search node titles.

Here are the fields I have added under the search index:

How can Search API be configured to search other fields, including the body field? I have tried searching words that are found only in a body field, and no search results are returned.

# Answer
This is probably due to a misconfiguration in your search\_api view. I'm assuming you're using an exposed filter and you'll need to be sure that your Keyword Search filter is configured to also search the body field. Edit the settings for the exposed filter and make sure body is selected in the `Searched fields` field.

It could be helpful to configure a search\_index view mode for your nodes and configure search\_api to index that view mode, then you can set your exposed filter to just search on that one "field". I find that it helps to keep things running smoothly and consistently across content types that don't necessarily share fields.

Also, make sure your content is actually indexed, sometimes it's just queued and hasn't actually been indexed yet. You can do that from your index's "View" tab.
> 1 votes

---
Tags: search
---


title: Lazy Load inline images in Drupal 8

text:
# Question
Title: Lazy Load inline images in Drupal 8
We have nodes with a lot of inline images in them. And we are looking for a solution on how to lazyload inline images in Drupal 8.

We are trying to get the Blazy module to lazyload them but it is not working that smoothly since we have a ton of posts already and can't manually apply the `src-data` attribute and `class` to all existing images.

This is how I am trying to get blazy to lazyload all images, but it is not working. Any ideas on what we are doing wrong? We are open to all recommendations.

Apply lazyload / blazy to all images.

1) In `mytheme.libraries.yml` I added the following:

```
dependencies:
- blazy/load

```

2) In `MYTHEME.info.yml` I added the following

```
libraries:
- 'mytheme/global-styling'
- 'mytheme/local'

```

3) In `MYTHEME.theme` I added the following:

```
/**
* Implements hook_page_attachments_alter()
*/
function MYTHEME_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'blazy/load';
}

```

What is wrong?

Currently getting this error:

> Fatal error: Cannot use assign-op operators with overloaded objects nor string offsets in /core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php on line 138

# Answer
When you need to lazy-load inline-images, I'd recommend doing that so via Filter plugin system.

That way you wouldn't need to alter any of the HTML in the node body/content.

The filter would be responsible of making the necessary markup changes to support lazy loading images.

The filter plugin should be `FilterInterface::TYPE_TRANSFORM_REVERSIBLE` type to avoid making changes to node content. That way in CKEditor the images could be maintained same as before. But when they are viewed in the page they would be lazy-loaded.

Here's the plugin I created for my projects:

```
<?php
// This plug needs to be placed in a custom module:
// `modules/custom/YOURMODULE/src/Plugin/Filter/FilterLazyload.php`

namespace Drupal\YOURMODULE\Plugin\Filter;

use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Provides a filter to lazy-load images.
 *
 * @Filter(
 *   id = "filter_lazyload",
 *   title = @Translation("Lazyload images"),
 *   description = @Translation("Lazy load images via bLazy"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE,
 *   weight = 20
 * )
 */
class FilterLazyload extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    $placeholder_src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';

    $result = new FilterProcessResult($text);
    $html_dom = Html::load($text);
    $images = $html_dom->getElementsByTagName('img');

    foreach ($images as $image) {
      $src = $image->getAttribute('src');
      $image->removeAttribute('src');
      $image->setAttribute('data-src', $src);
      $image->setAttribute('src', $placeholder_src);
      $classes = $image->getAttribute('class');
      $classes = (strlen($classes) > 0) ? explode(' ', $classes) : [];
      $classes[] = 'b-lazy';
      $image->setAttribute('class', implode(' ', $classes));
    }

    $result->setProcessedText(Html::serialize($html_dom));

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function tips($long = FALSE) {
    return $this->t('All inline-images will be lazy-loaded.');
  }

}

```

You still need to attach bLazy library and the initiator js to all pages. But you don't necessarily need the Blazy module to make this plugin work.
> 4 votes

# Answer
The error you get actually sounds as if one of your theme's `*.yml` files has wrong indentation.

You have wrong indentation at least in your question. That's how it's supposed to look like:

```
dependencies:
  - blazy/load

```

---

```
libraries:
  - 'mytheme/global-styling'
  - 'mytheme/local'

```

---

Finally, ensure your theme's `*.theme` file is existent:

```
<?php

/**
 * @file
 * Functions to support theming in the mytheme theme.
 */

```
> 3 votes

# Answer
You can apply class and data-src to existing images with code below in `MYTHEME.theme`.

```
/**
 * Template_preprocess_image().
 */
function mytheme_preprocess_image(&$variables) {
  $variables['attributes']['data-src'] = $variables['attributes']['src'];
  unset($variables['attributes']['src']);
  if (!isset($variables['attributes']['class'])) {
    $variables['attributes']['class'] = [];
  }
  $variables['attributes']['class'] = array_merge($variables['attributes']['class'], ['b-lazy']);
}

```
> 2 votes

---
Tags: media
---


# Question
Title: Using behat to create nodes and testing user owns them
I would like to create a Behat test that confirms a user can only see content they own or are referenced in. The struggle is that I can't figure out how to assign the content to created user.

Starting with something like:

```
Given users:
| name | status |
| test | 1      |
Given "Page" content:
| title | uid |
| A title | ?? |

```

I need to create several nodes to test, and it seems...odd... that I would need to do the entire steps (e.g. Then I go to register, then I go to node/add/page, ....).

How do I know the uid of the user created in the `Given`?

# Answer
In the example in features/api.feature you'll find how to do this:

```
  Scenario: Create nodes with specific authorship
    Given users:
    | name     | mail            | status |
    | Joe User | joe@example.com | 1      |
    And "article" nodes:
    | title          | author   | body             | promote |
    | Article by Joe | Joe User | PLACEHOLDER BODY | 1       |
    When I am logged in as a user with the "administrator" role
    And I am on the homepage
    And I follow "Article by Joe"
    Then I should see the link "Joe User"

```
> 2 votes

---
Tags: 7, testing
---


# Question
Title: How to configure an exposed filter in a view using a date picker?
How can I configure an exposed filter so that users can filter my site content by creation date, preferably using a date picker?

I tried using *Content: Authored on* as filter, but it gets me a text field to enter the date to enter a date/time in the *yyyy-mm-dd hh:mm:ss* format, which makes entering the date more difficult for users and more error prone.

What is the difference between Drupal 8 and Drupal 7 with Views 7.x-3?

# Answer
> 12 votes
You can use the Date Popup module.

> Adds the native HTML 5 date popup widget to all date fields in views filters.

As the Use form element of type date instead textfield when selecting a date in an exposed filter is still in progress.

# Answer
> 3 votes
There is a new patch released a few days ago, I test it in a project and it works fine. Here is the issue:

Use form element of type date instead textfield when selecting a date in an exposed filter

> Problem/Motivation
>
> When adding a datetime exposed filter I cannot simply select a date - I have to manually enter a date which is very bad UX.

And the patch is the number 65

# Answer
> 3 votes
The Better Exposed Filters module integrates with the date type fields, including the date popup. You can use this module to easily add an exposed filter with the date popup.

Its in Beta for now but you can use it.

# Answer
> 2 votes
Add the jquery date picker in for that page as dependency. `your_theme.libraries.yml`

```
date-picker:
  js:
    script/site-datepicker.js : {}
  dependencies:
    - core/jquery
    - core/jquery.ui.datepicker

```

**site-datepicker.js**

```
Drupal.behaviors.customDatepicker = {
  attach: function (context, settings) {
    jQuery(function () {
      jQuery("#datepicker").datepicker({
        dateFormat: "dd-mm-yy",
        altField: "input[data-drupal-selector=edit-created]",
        altFormat: "yy/mm/dd 23:59:59"
      });
    });
  }
};

```

**views-exposed-form--*views-block-name*.html.twig**

```
{% if q is not empty %}
  {#
    This ensures that, if clean URLs are off, the 'q' is added first,
    as a hidden form element, so that it shows up first in the POST URL.
  #}
  {{ q }}
{% endif %}

<input id="datepicker" type="text">
<input data-drupal-selector="edit-created" data-msg-maxlength="This field field has a maximum length of 128." name="created" size="30" maxlength="128" aria-invalid="false" type="hidden">
{{ form|without('created') }}

```

---
Tags: 8, views, datetime
---


# Question
Title: Input field not submitted in form when added through JS
I have a form that is processed first by an external service through JS and afterwards adds an input field to the form:

```
$('#my-form').once('submit').submit(function(e) {
  // some processing
...
  form.append($('<input type="hidden" name="token" />').attr('value', token.id));
  form.unbind();
  form.submit();
});

```

The field is added and also has the correct value. But when it is submitted the field is not present in neither my `public function validateForm(array &$form, FormStateInterface $form_state)` **nor** in `public function submitForm(array &$form, FormStateInterface $form_state)`.

I already tried using a textfield instead of type hidden, and hide it with css, but same result

# Answer
You can add a hidden field in `buildForm()` like below

```
/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
  :
  :
  $form['token'] = [
    '#type' => 'hidden',
    '#default_value' => ''
  ];
  :
  :
}

```

or, if you're not building the form yourself, i.e. you're altering an already existing form, you can add the hidden field via hook\_form\_alter or hook\_form\_FORM\_ID\_alter.

Then update value of it using **JS** if needed
> 1 votes

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


# Question
Title: Define custom twig page template for specific multiple node pages by nid - page--custom.html.twig
I have a page from different content type and I want to define a custom twig page template to these pages by their nid.

Eg. I have pages like **node/2**, **node/4**, **node/20** and **node/40** from the different content type and I want to apply **`page--custom.html.twig`** template only these specific pages by checking their ID.

Anyone know how to do this?

# Answer
This page describes everything about naming conventions, twig template naming conventions.

As described it is possible to do like this: `node--nodeid.html.twig`, e.g `node--2.html.twig`.

The smartest way will be to implement the `hook_theme_suggestions_page_alter()`, like this:

```
/**
 * Implements hook_theme_suggestions_page_alter().
 */
function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $nodes = [2, 4, 20, 40];
    if (in_array($node->id(), $nodes)) {
      $suggestions[] = 'page__custom';
    }
  }
}

```
> 1 votes

# Answer
You can write a `hook_theme_suggestions_page_alter()`

```
/**
 * Implements hook_theme_suggestions_page_alter().
 */
function YOUR_THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node->id() == 2 || $node->id() == 4 || $node->id() == 20 || $node->id() == 40) {
      $suggestions[] = 'page__custom';
    }
  }

```
> 2 votes

---
Tags: 8, theming, hooks
---


# Question
Title: Request body to post a new comment using REST API
I have a comment type and content type with field from type of that comment type. I also using Rest and Rest UI modules. I want to insert new comment on specific node using rest API using POST request.

In the REST config page, I have this service enabled

What I want to do, what is the request body should be to insert new comment successfully through Postman.

# Answer
I've solved it by these below

```
{
    "entity_id": [{
        "target_id": 612
    }],
    "entity_type": [{
        "value": "node"
    }],
    "comment_type": [{
        "target_id": "discussion"
    }],
    "field_name": [{
        "value": "discussion_comments"
    }],
    "subject": [{
        "value": "Goodbye World"
    }],
    "comment_body": [{
        "value": "comment which you want write"
    }]
}

```
> 1 votes

---
Tags: 8
---


# Question
Title: How do I create an instance of an entity with all its fields attached?
I am trying to create an instance of 'commerce\_customer\_profile' entity with all the extra fields of the customers address.

I am doing this inside a FeedsProcessor that will import users and their addresses from Magento.

I don't want to have to create a fake $form\_state array and then use field\_attach\_submit() as it doesn't seem right to me.

The only other way I have found so far is:

```
$billing_profile = commerce_customer_profile_new('billing', $entity->uid);
commerce_customer_profile_save($billing_profile);
$full_billing_profile = commerce_customer_profile_load($billing_profile->profile_id);

```

$entity is the current user being created.

Which will then give me an empty instance of the new entity ready to populate and save but again it doesn't feel right.

Any help appreciated.

# Answer
for nodes we can do below codes to load all fields and display formatters aplyed on them:

```
$node = node_load($nid);
field_attach_prepare_view('node', array($node->nid => $node), 'teaser');
$fields = field_attach_view('node', $node, 'teaser');

```

similar way should be exists for commerce
> 0 votes

# Answer
Th OP is over a year old now, so perhaps it wasn't a mature option back then, but if you've got the entity api module installed, you should be able to programitcally create fields by going:

```
$profile = entity_create('commerce_customer_profile', array('field_firstname' => 'Joe'));
$created = entity_save('commerce_customer_profile', $profile);

```

You may want to have a look into the commerce\_customer\_profile entity class, to see what requirements it has for creating its entities, i.e. it might want a user in drupal to associate with, or something else. Hope that can help.
> 0 votes

# Answer
In D8 you can do this :

```
$data = array(
  'type' => 'article',
  'title' => 'My new title',
  'uid' => 1
);
$node = Drupal::entityTypeManager()
  ->getStorage('node')   // or other entity type name
  ->create($data);

$node->save();

```

Just specify your entity (here is node), and the attributes or fields (here type, title...)

Some entities also provide a functional interface to set fields, and you can also set field values using the field name and the "magic" methods:

```
$storage->setSummary("value");
$storage->field_summary_text->value = "value";

```

\[the exact nature of "-\>value" depends on the field type\].
> 0 votes

---
Tags: entities
---


# Question
Title: How to run custom PHP in a reaction rule in D8?
Have recently installed & then patched the Rules module to get it working in D8. I need to run an action which executes some PHP e.g when an order in Commerce is completed.

In D7 this is done by selecting Add action -\> Execute custom PHP code, but in the D8 version I can't find a similar option. I'm having trouble finding any documentation for this feature.

How can this be accomplished in Drupal 8?

# Answer
When looking at this thread execute custom php code in rules, it seems like it is not possible in Drupal 8.

If you want to `execute php code` in rules, you must create a custom action. Here is a guide how to create a custom rules action, custom rules action.

The code to create a rules action:

```
<?php

/**
 * Implement hook_rules_action_info().
 */
function my_module_rules_action_info() {
  return array(
    'my_module_rules_action_create_hashed_string' => array(
      'label' => t('Create hashed string'),
      'group' => t('Custom'),
      'parameter' => array(
        'string' => array(
          'type' => 'text',
          'label' => t('String to be hashed'),
          'description' => t('Enter a value for a string that will be hashed using the md5 hash-algorithm.'),
        ),
        'length' => array(
          'type' => 'integer',
          'label' => t('The length of the returned string'),
          'description' => t('Enter a number for the length of the hashed string that will be created.'),
        ),
        'algorithm' => array(
          'type' => 'text',
          'label' => t('Algorithm'),
          'description' => t('Select a hash algorithm.'),
          'options list' => 'my_module_algorithm_options',
          'restriction' => 'input',
        ),
      ),
      'provides' => array(
        'hashed_string' => array(
          'type' => 'text',
          'label' => t('Hashed string'),
        ),
      ),
    ),
  );
}

// A helper function to provide us with a list of algorithms
function my_module_algorithm_options() {
  $algorithms = array();

  $algorithms['md4'] = t('md4');
  $algorithms['md5'] = t('md5');

  return $algorithms;
}

// This callback creates the hashed string by using the parameters provided through rules' UI
function my_module_rules_action_create_hashed_string($string, $length, $algorithm) {
  if ($length <= 0) {
    // For anything below or equal zero lets return the default value.
    $string = hash('md5', $string);
  } else {
    $string = substr(hash($algorithm, $string), 0, $length);
  }

  return array(
    'hashed_string' => $string,
  );
}

```
> 2 votes

---
Tags: 8, rules
---


# Question
Title: Allows users to pass from flat to threaded view for forum comments
We've migrated a site from Drupal 5 to Drupal 7, and we were unable to figure out how to allow user to change between flat and threaded view for the forum comments. This was possible in Drupal 5, but in Drupal 7 it's only possible to change the default display mode per content type (as an administrator option).

Is there a way to allow this for the users?

# Answer
> 0 votes
Unfortunately, on Drupal 7 that setting is not per user, but per content type. So you need to go to the content type's comment settings and choose either flat or threaded view.

---
Tags: 7, views, comments
---


# Question
Title: How to set block visibility by role in Drupal 8
In Drupal 7 it was easy to set block visibility by role in "block configuration" page.

How it can be done in Drupal 8?

# Answer
> 1 votes
I found a discussion about this here: https://www.drupal.org/project/drupal/issues/2952962

And solution in 28 worked for me: https://www.drupal.org/project/drupal/issues/2952962#comment-12549257

---
Tags: 8, blocks
---


title: How do I read response headers?

text:
# Question
Title: How do I read response headers?
I have data in custom response headers that I need to read. I have looked in the Drupal API guide and there is a reference to `Response::$headers`, but I'm not sure how to exactly use this to read header data.

Edit - to further elaborate what I am trying to accomplish:

I have a form in a custom module that redirects some data in the headers to another page. Here is the code for that:

```
$response = new RedirectResponse('/path/destination', 302, array(
            "username" => "value"
          ));
$response->send();

```

The redirect is made successfully and the values that I'm pushing to the headers (illustrated by "username" above) are successfully transferred onto the response headers - I can see that with the browser inspector.

What I am now trying to do is read the values of those custom headers, i.e. "username", as a means of pre-populating the username field on my destination page (/path/destination).

As suggested in the answers, I have also done the following:

```
$response = new ResponseHeaderBag();
$response::get("username");

```

I also tried:

```
$response = new ResponseHeaderBag();
$response->get("username", $default = null, $first = true);

```

Even though I have both these inclusions on the top of my file:

```
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

```

I get the following error:

```
Fatal error: Call to undefined method Drupal\module_name\Form\MyClass::all() in ../vendor/symfony/http-foundation/HeaderBag.php on line 113

```

# Answer
`Response::$headers` is a public property, which means you can access it with `$response->headers`, where contains an object of the `ResponseHeaderBag` class or some inherited class of it.

Essentially, it means you can access the headers using either `ResponseHeaderBag::all` or `ResponseHeaderBag::get($key)`.
> 3 votes

# Answer
Headers don't work like that. First, you can't just invent arbitrary headers (or if you do, you should prefix them with X-), but even then, headers just don't work like that.

A header is just metadata about *your* (the server's) response. The browser doesn't do anything with it unless it is a specific header the browser knows about. It does *not* automatically send that header back to you.

Instead, you need to use any of the following, depending on the use case:

* A query argument, so that your path is some/path?username=foo
* A cookie, which is a bit of information sent by the server that the browser *will* then send on every request
* A value in the Drupal/PHP Session (which itself is usually based on a cookie)

Either way, you will need to consider caching, so that Drupal knows about where you get the information from when caching the result.

You should also read up on services in Drupal and request/response handling (for example, Introducing the Symfony Request Object). (There are many other resources about request/response in Drupal, in Symfony, and just in general.) Understanding these concepts will help you understand what you need to use.
> 2 votes

---
Tags: 8
---


# Question
Title: How can I insert one bespoke item first and one last in a views grid?
I have a set of views (in D7.57, views 7.x-3.18). Each view takes a selection of my (drupal commerce) product-displays and places them in a grid, in alphabetical order.

Now I want to add a bespoke item as first item (so in row 1, column 1), 'bumping up' all normal products one place (so product 1 goes to row 1 column 2, etc). Whatever I try (adding global header in views (obviously wrong), changing the `views-grid-xx.tpl`) 'breaks' the rows, displaying my bespoke item in perfect order, but breaking the row.

**Option 1: adapt the views style or row output .tpl**

*Update after @AltaGrade answer*: Thanks for your answer. That's what I tried, I amended both the 'style' and the 'row' templates for the view, but do not get the desired results with either.

The view does display my insert (which is a piece of fixed code, same lay-out etc as the normal grid items), but then treats the normal generated items as a full row, causing breaks where I don't want them, and also repeats my insert each row.

My rows (of three columns each) then look like:

insert - item 1 - item 2

item 3

insert - item 4 - item 5

and so on..

Code of the `views.grid.xxx.tpl` looks like this, where and how would I code my inserts (one to go before the first item in row one; one to go after all items have been listed)?

```
<?php

/**
* @file
* Default simple view template to display a rows in a grid.
*
* - $rows contains a nested array of rows. Each row contains an array    of columns.
*
* @ingroup views_templates
*/
// Match Column numbers to Bootsrap class
$columns_classes = array(1 => 12, 2 => 6, 3 => 4, 4 => 3, 6 => 2, 12 =>     1);
$bootsrap_class = isset($columns_classes[$view->style_plugin-   >options['columns']]) ? $columns_classes[$view->style_plugin-   >options['columns']] : 3;
$delay_attr = '';
?>
<?php foreach ($rows as $row_number => $columns): ?>
  <div class = "row<?php if ($row_classes[$row_number]) { print ' ' .  $row_classes[$row_number];  } ?>" >
    <?php foreach ($columns as $column_number => $item): ?>
      <?php
        if(isset($column_classes[$row_number][$column_number]) &&  strpos($column_classes[$row_number][$column_number], 'animation-delay') !==  FALSE) {
          $delay = isset($delay) ? $delay + 0.1 : 0.1;
          $delay_attr = ' data-wow-delay = "' . $delay . 's" ';
        }
      ?>
      <div class = "col-md-<?php print $bootsrap_class; ?><?php if   ($column_classes[$row_number][$column_number]) { print ' ' .  $column_classes[$row_number][$column_number];  } ?>" <?php print  $delay_attr; ?>>
        <?php print $item; ?>
      </div>

    <?php endforeach; ?>
  </div>
<?php endforeach; ?>

```

**Option 2: Preprocess the view output using `pre_render`.**

One suggestion I found is using hooks (`hook_views_pre_render`, `hook_views_post_render`?), is this the best way? If so, where would I put such a hook? Are these actually written into `views.api.php`? And how do I then write such a hook that it only applies to the view I want? All pointers / help very welcome, hooks 100% new area for me.

In the `views.api.php` I also found a whole section on `views-handlers` which looks similar to the hooks, are these an option too?.

**Option 3: create extra content types**

Create new content types (in this case product types) and let the view render first extra type, then the main products, then the second extra type. So I'd create a new content type for the bespoke items, and then add them to the view's filter. Any explanation how I would do that so it neatly merges into the row would be amazing.

# Answer
Go to `admin/structure/views/view/YOUR-VIEWS-NAME/edit/page`, click on `Theme:Information` and you will see bunch of lines. Choose appropriate one depending what exactly you want to override. It can be the whole views display output, or style output, or specific field output.

Each line will have an active hyperlink, clicking which you can copy the content of the new file. Also each line will have file name suggestions. When you identified the right output, you can choose pick any of the suggested file names on that line: the further to the right, the more specific output.

Create a new template file in your themes template directory, paste the copied content and start modifying the output per your desire.

For example, you could execute your checks just after foreach loop starts:

```
<?php foreach ($rows as $row_number => $columns):
  if ($row_number != 0) {
    // Here goes your custom modifications.
  }
<?php endforeach; ?>

```
> 0 votes

# Answer
As I can't add this much in a comment and can't do mark-up:

@AltaGrade - I need one 'fake' product to go on row 1, column 1, this is the code to be included:

```
<?php
// Here goes my custom modifications:
print "<div class=\"col-md-4 col-lg-4 mb-60 mb-xs-40\">
<div class=\"views-field views-field-field-sale-images\">
<div class=\"field-content\"><a href=\"http://link to another website\">
<img src=\"/sites/default/files/image_of_the_inserted_product.jpg\" width=\"770\" height=\"500\"></a>
</div></div>

<div class=\"views-field views-field-field-series\">
<div class=\"field-content\"><span class=\"mp_brand\">Text</span>
<span class=\"announcement\"> - by text</span>
</div></div></div></div>";
} ?>

```

Then I need to generate the normal products through the view (as in the code in the original question), filling up row 1 (there are three columns) with two more products in column 2 and column 3, then second row with three products in columns 1 to 3, etcetera..

At the end of the generated products I want to generate one more insert, (same code as the row 1, column 1 one), right behind the generated products (so in column 3 if products end at column 2, or in column 2 id the products and at column 1, etc..

Hope this makes sense?
> 0 votes

---
Tags: 7, hooks, views
---


# Question
Title: Reusing existing content types for very similar content
Let's say I have **n** categories of **"means of transport"** I need to display on my site (aircrafts, cars, bikes...). They share a lot of attributes like "name", "weight", "manufacturer" etc. But each of them also has a small number of distinct attributes that they do not share with others (e.g. only an aircraft has an attribute "wingspan").

I've addressed this myself and seen this issue in related questions here, here and here (and many more) and I do understand that opinions vary as there is (probably) no definite right or wrong answer.

However, I'm still wondering if there exist Drupal-based pros and cons (in terms of performance, maintainability) instead of pure personal preferences for planning your content model one or the other way.

**Approach 1**: My first thoughts were similar to the following approach, which does not appear to be the optimal use case for the paragraphs module:

* 1 content type "means\_of\_transport" with a set of basic fields (name, manufacturer, weight...) that are shared by all.
* 1 field that references a taxonomy X with terms "bike", "car", "aircraft"... to tag each piece of content.
* n fields that each reference a different paragraphs type, containing all the fields that are specific to a certain piece of content (e.g. the "wingspan" & "call\_sign" compound field for aircrafts)

This results in 1 content type with n paragraphs types. As Hudri and Kevin already pointed out there does not seem to be much benefit in just shifting the complexity from content types to paragraphs types.

**Approach 2:**

* n content types "bike", "aircraft"... with all the attributes (fields) that are shared between them being reused, so that you don't need to create a new field for "name", "weight" etc. each time, but also each content type having a few unique fields that are specific to it.

Let's say I'll go with approach 2 and **n=50 content types** and each means of transport only has 1 unique attribute, all the other ones are shared and their fields could be reused. To me that seems very inefficient and often you read one should try to reduce the number of content types when planning your site. But maybe that's the Drupal way to do it and by reusing most of the fields you do not create too much overhead anyway.

Is there any other possible solution to **"reuse existing content types with different fields"** as also indicated in this answer by Jaypan?

Again, I'm interested in facts that support one or the other approach (and I'm aware they might not exist at all and it comes down to personal taste).

# Answer
> 1 votes
Nodes are a generic entity, with each bundle (content type) being it's own type (ie - a means of transport). This is too generalized. As such, I would say that this is a case for a custom entity, rather than nodes. Your custom entity would be means of transport. You would then create base fields on the entity type for the fields common to each means of transport. You would then create bundles (which for nodes, are known as 'content types') for each separate means of transport (car, plane, bicycle etc) and add means-specific fields to the bundle.

# Answer
> 1 votes
You could use one content-type and as many fields needed to define all the unique features of each transport type.

Obviously, not all the fields will make sense for all type transports at that point.

Then you can use Conditional Fields module to organize availability of each fields based on the entries on the fields as you enter.

From the module description:

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. A simple use case would be defining a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked, but much more complex options are available.

---
Tags: 8, nodes, paragraphs
---


title: Get menu link siblings

text:
# Question
Title: Get menu link siblings
I'm trying to create a menu in Drupal 8 that is just sibling links of the current page. So if the menu is:

* Home
* Parent 1
    + Sub-parent 1
        - Child 1
    + Sub-parent 2
        - Child 2
        - Child 3
        - Child 4
* Parent 2

When I'm on the "Child 3" page, I want a menu block to link to look like this:

* Child 2
* Child 3
* Child 4

I know how to do this in D7, I think, but I'm having a hard time translating that knowledge to D8. Is this even something that is doable in D8? And if it is, can someone point me in the right direction on how to do it?

Thanks!

Clarification: The child level needs to be variable, so that menu items with different depths can display their siblings. So for instance, in addition to wanting a menu for the children, I'd need a menu for the sub-parents and a menu for the parents and so forth. I also have no control over/knowledge of how deep the menu goes and if it goes that deep on all sections.

# Answer
> 19 votes
So, I ended up figuring out some code that would let me do this, by creating a custom block and, in the build method, outputting the menu with transformers added to it. This is the link I used to figure out how to get the menu in the block and add transformers to it: http://alexrayu.com/blog/drupal-8-display-submenu-block. My `build()` ended up looking like this:

```
$menu_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

// Load the tree based on this set of parameters.
$tree = $menu_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  // Remove all links outside of siblings and active trail
  array('callable' => 'intranet.menu_transformers:removeInactiveTrail'),
);
$tree = $menu_tree->transform($tree, $manipulators);

// Finally, build a renderable array from the transformed tree.
$menu = $menu_tree->build($tree);

return array(
  '#markup' => \Drupal::service('renderer')->render($menu),
  '#cache' => array(
    'contexts' => array('url.path'),
  ),
);

```

The transformer is a service, so I added an `intranet.services.yml` to my intranet module, pointing to the class that I ended up defining. The class had three methods: `removeInactiveTrail()`, which called `getCurrentParent()` to get the parent of the page the user was currently on, and `stripChildren()`, which stripped the menu down to only the children of the current menu item and its siblings (ie: removed all submenus that weren't in the active trail).

This is what that looked like:

```
/**
 * Removes all link trails that are not siblings to the active trail.
 *
 * For a menu such as:
 * Parent 1
 *  - Child 1
 *  -- Child 2
 *  -- Child 3
 *  -- Child 4
 *  - Child 5
 * Parent 2
 *  - Child 6
 * with current page being Child 3, Parent 2, Child 6, and Child 5 would be
 * removed.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu link tree to manipulate.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   The manipulated menu link tree.
 */
public function removeInactiveTrail(array $tree) {
  // Get the current item's parent ID
  $current_item_parent = IntranetMenuTransformers::getCurrentParent($tree);

  // Tree becomes the current item parent's children if the current item
  // parent is not empty. Otherwise, it's already the "parent's" children
  // since they are all top level links.
  if (!empty($current_item_parent)) {
    $tree = $current_item_parent->subtree;
  }

  // Strip children from everything but the current item, and strip children
  // from the current item's children.
  $tree = IntranetMenuTransformers::stripChildren($tree);

  // Return the tree.
  return $tree;
}

/**
 * Get the parent of the current active menu link, or return NULL if the
 * current active menu link is a top-level link.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The tree to pull the parent link out of.
 * @param \Drupal\Core\Menu\MenuLinkTreeElement|null $prev_parent
 *   The previous parent's parent, or NULL if no previous parent exists.
 * @param \Drupal\Core\Menu\MenuLinkTreeElement|null $parent
 *   The parent of the current active link, or NULL if not parent exists.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement|null
 *   The parent of the current active menu link, or NULL if no parent exists.
 */
private function getCurrentParent($tree, $prev_parent = NULL, $parent = NULL) {
  // Get active item
  foreach ($tree as $leaf) {
    if ($leaf->inActiveTrail) {
      $active_item = $leaf;
      break;
    }
  }

  // If the active item is set and has children
  if (!empty($active_item) && !empty($active_item->subtree)) {
    // run getCurrentParent with the parent ID as the $active_item ID.
    return IntranetMenuTransformers::getCurrentParent($active_item->subtree, $parent, $active_item);
  }

  // If the active item is not set, we know there was no active item on this
  // level therefore the active item parent is the previous level's parent
  if (empty($active_item)) {
    return $prev_parent;
  }

  // Otherwise, the current active item has no children to check, so it is
  // the bottommost and its parent is the correct parent.
  return $parent;
}

/**
 * Remove the children from all MenuLinkTreeElements that aren't active. If
 * it is active, remove its children's children.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu links to strip children from non-active leafs.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   A menu tree with no children of non-active leafs.
 */
private function stripChildren($tree) {
  // For each item in the tree, if the item isn't active, strip its children
  // and return the tree.
  foreach ($tree as &$leaf) {
    // Check if active and if has children
    if ($leaf->inActiveTrail && !empty($leaf->subtree)) {
      // Then recurse on the children.
      $leaf->subtree = IntranetMenuTransformers::stripChildren($leaf->subtree);
    }
    // Otherwise, if not the active menu
    elseif (!$leaf->inActiveTrail) {
      // Otherwise, it's not active, so we don't want to display any children
      // so strip them.
      $leaf->subtree = array();
    }
  }

  return $tree;
}

```

Is this the best way to do it? Probably not. But it at least provides a starting place for people who need to do something similar.

# Answer
> 7 votes
## Siblings Menu Block

With the help of @Icubes answer and `MenuLinkTreeInterface::getCurrentRouteMenuTreeParameters` we can simply get the current route's active menu trail. Having that we also have the parent menu item. Setting that as starting point via `MenuTreeParameters::setRoot` to build a new tree gives you the desired siblings menu.

```
$menu_name = 'main';
$menu_tree = \Drupal::menuTree();

// This one will give us the active trail in *reverse order*.
// Our current active link always will be the first array element.
$parameters   = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
$active_trail = array_keys($parameters->activeTrail);

// But actually we need its parent.
// Except for <front>. Which has no parent.
$parent_link_id = isset($active_trail[1]) ? $active_trail[1] : $active_trail[0];

// Having the parent now we set it as starting point to build our custom
// tree.
$parameters->setRoot($parent_link_id);
$parameters->setMaxDepth(1);
$parameters->excludeRoot();
$tree = $menu_tree->load($menu_name, $parameters);

// Optional: Native sort and access checks.
$manipulators = [
  ['callable' => 'menu.default_tree_manipulators:checkNodeAccess'],
  ['callable' => 'menu.default_tree_manipulators:checkAccess'],
  ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
];
$tree = $menu_tree->transform($tree, $manipulators);

// Finally, build a renderable array and enable proper caching.
$menu = $menu_tree->build($tree);

$build = [
  '#markup' => \Drupal::service('renderer')->render($menu),
  '#cache' => [
    'contexts' => ['url'], // For .active classes.
    'tags' => ['config:system.menu.' . $menu_name], // For menu changes.
  ],
];

return $build;

```

# Answer
> 4 votes
Drupal 8 has Menu Block functionality built in the core only thing you have do is to create a new menu block in the Block Ui and configure that.

That happens by:

* Placing a new block and then selecting the menu you want to create a block for.
* In the block configuration you have to select the "Initial menu level" to be 3.
* You might also want to set the "Maximum number of menu levels to display" to 1 in case you only want to print menu items from the third level.

# Answer
> 4 votes
Setting the root on the current link might do the tricks :

```
$menu_tree = \Drupal::menuTree();
$menu_name = 'main';

$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
$currentLinkId = reset($parameters->activeTrail);
$parameters->setRoot($currentLinkId);
$tree = $menu_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_tree->transform($tree, $manipulators);

```

---
Tags: 8
---


# Question
Title: How to debug invalid plugins derived by the GraphQL module?
I'm currently using the GraphQL module in combination with the Brightcove module.

When I visit /graphql/explorer, all I'm getting is a totally white screen. When I visit /graphql/voyager, I end up with an "invalid syntax" error. My supposition is that one of the derived Brightcove plugins has invalid definitions. Unfortunately, GraphQL doesn't seem to throw any sort of error message.

Any ideas on how I can debug GraphQL?

# Answer
> 0 votes
I am a little late but you can enable dblog core module and see if any errors are printed to the watchdog table by running `drush wd-show` after an attempt to access the explorer page.

---
Tags: 8, debugging
---


# Question
Title: How can I display content from tab that was active on save?
I'm using Drupal 8, including paragraphs.

I have a content type *with a paragraph field*, and this paragraph contains a fieldgroup of two fields that display in horizontal tabs.

When adding content, on save only the content in the active tab should be set to display on the page. In other words, you choose one tab or the other, add content into its designated field and save. The content in that active tab is the content that will display when viewing the page (even if there is content in the other tab).

How can I display the content from only the tab that was active on save?

# Answer
Add a text field OR boolean field to your content type, let's call it "Active Tab".

Using jQuery you can make it when tab x gets clicked, it auto fills the text field OR auto checkmarks the x boolean box. (You can hide this field with CSS if you want).

Use a template file to control the display/output. So simply in your twig template file perform an conditional statement

```
{% if content.field_active_tab.0 == 'x' %}
  {{ content.field_something }}
  {{ content.field_something_else }}
{% endif %}

{% if content.field_active_tab.0 == 'y' %}
  {{ content.field_something2 }}
  {{ content.field_something_else2 }}
{% endif %}

```
> 2 votes

---
Tags: 8, theming, entities, paragraphs
---


# Question
Title: Single quote in in filter return exception querySelectorAll
I face a problem when filter with single quote in field. Anyone know why? And how to disable this exception?

# Answer
I found a solution for this by using patch. https://www.drupal.org/project/drupal/issues/2902769 Because this is a core funtion patch, I marked it as can-solve but not plan to use it myself, because the filter works still only some annoying console log.
> 1 votes

---
Tags: 8, views
---


# Question
Title: Redirect to external url adds external url to current url instead
I'm using wampserver and I'm trying to redirect a visitor to an external url (which in turn will eventually send them back to another page on my drupal-site).

My site on wampserver is called localhost/testing and I use

```
drupal_goto(www.example.com, array(
  'external' => TRUE,
  'absolute' => TRUE,
  ));

```

However, the url I get redirected to is localhost/testing/www.example.com instead of www.example.com

# Answer
You need whole URL like http(s)://www.example.com
> 2 votes

# Answer
Dont use file path like localhost/example.com/

please user localhost/examplecom/ or localhost/example-com/

rename the folder name example.com to example-com or examplecom
> 0 votes

---
Tags: 7, redirection
---


# Question
Title: Adding RewriteCode in https does not work for links other than base url
```
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.com*
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

```

With this I swap from http:// to https://www in one single redirect step.

Unfortunately this does not work for sub-pages. So http://example.com/categorypage will get redirected to https://example.com.

How do I fix it? What should be added in .htaccess to fix the redirection from http to https for sub-pages?

# Answer
> 1 votes
Adding these lines to the default `.htaceess` file worked for me

```
# Force HTTPS across the Drupal site
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]
</IfModule>

```

Also enable clean URLs for that site

---
Tags: redirection, ssl
---


# Question
Title: How can I expose a view with date filter?
I have a view and am listing a bunch of data from different content type .

What i need is , i have to list the data according to the date field given . That

is i have to filter the date in between two dates , Is this possible ?

**WHAT I HAVE TRIED**

---

I used the exposed filter as follows :

The problem of this filter is i have to manually enter the date in date field . can i have data field which can select the date as in datepicker ?

# Answer
> 2 votes
I had a similar problem and the solution I did was to add a date Picker to that `page` or `view` or `exposed form` and hide the current field in the twig file and add another with datepicker added to it

You can add a library to that view

```
function YOUR_THEME_NAME_preprocess_views_view(array &$variables) {
  if (isset($variables['view'])) {
    if ($variables['view']->id() == "VIEW_ID") {
      if ($variables['view']->getDisplay()->display['id'] == "VIEW_DISPLAY_ID") {
        $variables['#attached']['library'][] = 'YOUR_THEME_NAME/date-picker';
      }
    }
  }
}

```

It is explained in this answer: How to configure an exposed filter in a view using a date picker?

# Answer
> 1 votes
In 7 you can do this with Better Exposed Filters by selecting the jQuery UI datepicker option in the screen of your screenshot. There is an alpha out for 8.

> The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience.
>
> Views Filters is a powerful tool to refine the results returned by a given view. When you expose a filter, you allow the user to interact with the view making it easy to build a customized, advanced search. For example, exposing the node type field as a filter lets your site visitor limit their search queries to just blog entries. Better Exposed Filters gives you greater control over the rendering of exposed filters.

---
Tags: views, 8, datetime
---


# Question
Title: How to create user input dependent form elements?
I have created a form and it has multiple elements. Is there a way to show specific form elements depend on a slelect box selected value. For an example my select box has 2 options. if i select option 1, form will show a text box after the select box. if the selected option is 2, form will show a another select box after the first select box.

# Answer
Yes it is possible and quite easy. Read up on the #states value in the drupal form api documentation. I am assuming this is for Drupal 7...
> 1 votes

# Answer
http://www.deckfifty.com/blog/2012-11/drupal-form-api-conditional-fields this link has the answer i want
> 1 votes

# Answer
Assuming you created the form or fields using webform builder, you can use the conditional\_fields module which is quite easy to configure and very flexible.
> 0 votes

---
Tags: forms
---


# Question
Title: What is the replacement pattern in rewrite ouput for current user id?
I have a custom content entity listed with Views.
I want to conditionally display some information depending on the fact that the row is related to the current user.
I tried {{ user:uid }} with no success.
Any idea?

With help from @4k4, I could use 'Custom text' to add on each row of my Views output two 'buttons' (Edit, Delete) depending on the current user:

```
{% if user_id_1=="[current-user:uid]"  %}
<a href="/sel/service/{{ id }}/edit"><img src="/sites/default/files/images/document-edit.gif" alt="" title="Modifier" width="11" height="13"></a>
<a href="/sel/service/{{ id }}/delete"><img src="/sites/default/files/images/trash.gif" alt="" title="Supprimer" width="11" height="13"></a>
{% endif %}

```

As you can see, there is also a button in the header (Add).
I'd like to have this button displayed only if the user is not anonymous.
I tried (in either Text area or Unfiltered text):

```
{% if "0"=="[current-user:uid]"  %}
<a href="/sel/service/add" class="form-submit hiddenforuser[current-user:uid]">Ajouter</a>
{% endif %}

```

but it doesn't work:
Any idea why?

# Answer
The twig variables in `{{ }}` are replacement patterns for fields. Globally available tokens are accessed by their usual square brackets syntax:

```
[current-user:uid]

```

# Custom text field

This token works in a global text area, but not a custom text field, because this plugin *Drupal\views\Plugin\views\field\Custom* doesn't have global token replacement. You need to extend it and override renderAltered():

*/src/Plugin/views/field/CustomToken.php*

```
<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\views\Plugin\views\field\Custom;

/**
 * A handler to provide a field extending custom by global token replacement.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("custom")
 */
class CustomToken extends Custom {

  /**
   * {@inheritdoc}
   */
protected function renderAltered($alter, $tokens) {
    return $this->viewsTokenReplace($this->globalTokenReplace($alter['text']), $tokens);
  }
}

```

and tell the plugin manager about the new class:

*mymodule.module:*

```
function mymodule_views_plugins_field_alter(array &$plugins) {
  $plugins['custom']['class'] = 'Drupal\mymodule\Plugin\views\field\CustomToken';
}

```

This applies the function `globalTokenReplace()` before the twig patterns are replaced.

Then you can use

```
{% if anotherfield_id == '[current-user:uid]' %} YES {% else %} NO {% endif %}

```

You have to enclose the token in single quotes so that you get a valid twig syntax after the global tokens are replaced.

# Global text area

A global text area in header/footer is exactly the opposite, it supports global tokens but not Twig.

You could do the same as before and add Twig support in a custom plugin. But there is an easier solution. Install the module Twig input filter and go to "Text formats and editors" in Configuration and enable the Twig filter for the text format you use in the text area.
> 3 votes

---
Tags: views, 8
---


# Question
Title: Custom Rules Actions to set content to unpublished
Is there a way to write a custom Rules Action with this conditions.

> **Default**: Content Type X is set to create unpublished content.

**RULES**

> **Event**: After saving new content
>
> **Condition**: when a content of type X is created
>
> **Action**: ***Set status to published***

# Answer
Even though your Rules question could be like an exercise for a training session like "Getting started with Rules in D7", the most recent release of Rules for D8 (= Alfa 3) does not support this yet.

However, as a work-around, you could implement the very same logic if you'd adapt the configuration of your content type X so that the default is that newly created content is published right away.

**Note**: if your goal is to "*let anonymous users access unpublished contents*" (as in your comment below this answer), then the view\_unpublished module could be a possible alternative. As per its project page: it allows you to grant access for specific user roles to view unpublished nodes of a specific type.
> 2 votes

---
Tags: 8, rules
---