# Question
Title: Automatically add class to <ul> to WYSIWYG
Is it possible to automatically add a class to each `<ul>` element added to the CKEditor WYSIWYG?

In my project, I decided to not style `ul > li` in order to not have to rewrite CSS for each `ul` Drupal can display (i.e. menus or contextual links). So, I have only one CSS rule for my unordered lists: `ul.my_custom_class li`. I used to add a custom style in CKEditor's Styles dropdown that add this class, but it's not a perfect solution, as some administrators forget to use it (or sometimes, CKEditor does not recognize `ul` ou `a` since Drupal 8.4.x, see this thread).

The perfect solution would be that, each time you add an unordered list into the WYSIWYG, instead of having `ul li`, you'd have `ul.my_custom_class li`. I know I can use an other CSS rules like `.ckeditor ul` to make it work, but I want to be able to use this specific class anywhere in the website.

I've found some methods in the CKEditor docs but I don't really know where to use them on Drupal 8.

# Answer
According to your description, you want to automatically add the class to all lists within the CKEditor content for better theming.

I suggest not doing so within the CKEditor. Use a custom text filter instead. This avoids users accidentially forgetting to add the class manually and keeps your database stored contents cleaner.

The custom filter could parse the content and automatically add the classes when the text format is rendered. A good guide on getting started with creating custom text filters is this one: https://www.lullabot.com/articles/creating-a-custom-filter-in-drupal-8

In your process method you should use a simple DOM parser to add classes to all `ul` tags (not tested though, just for illustration):

```
namespace Drupal\my_module\Plugin\Filter;

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

/**
 * Drupal 8 filter to automatically add class to unnumbered lists.
 *
 * @Filter(
 *   id = "my_lists_filter",
 *   title = @Translation("My lists filter"),
 *   description = @Translation("Automatically adds my_class to unnumbered lists."),
 *   type = \Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 * )
 */
class MyListsFilter extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    // Create DOM document.
    $dom = Html::load($text);

    // Get all UL tags.
    $lists_query = '//ul';

    // Get DOM nodes from XPath query.
    $xpath = new \DOMXPath($dom);
    $nodes = $xpath->query($lists_query);
    // Whether we have results.
    if ($nodes->length > 0) {
      // Iterate over list elements and add our class.
      foreach ($nodes as $node) {
        $classes = explode(' ', $node->getAttribute('class'));
        $classes[] = 'my_class';
        $node->setAttribute('class', join(' ', array_unique($classes)));
      }
    }

    return new FilterProcessResult(Html::serialize($dom));
  }

}

```
> 3 votes

---
Tags: 8, wysiwyg
---


# Question
Title: How to utilise watchdog or how to debug webform error
I have a webform that integrates into CiviCRM such that the webform is used to save data into the Civi system. The following error is generated when hitting submit (although data is saved in the results tab of the form):

The lease helpful error message in the word - unless you only have one field =/

Any ideas as to how I can decipher which field is causing the issue e.g. use Watchdog or something to see what the query is or why the error is appearing. I don't have access to the mySQL server logs.

# Answer
> 0 votes
Thanks for taking the time to looking into the issue Jay Chand and Ziftman.

Turns out that if you go into the admin panel in CiviCRM there is a debugging option where you can turn on callback on errors and thus gain more insight into error messages such as the one I mention above.

---
Tags: 7, debugging, civicrm, webforms
---


# Question
Title: Installing entity form/view display config in custom module using options_select plugin
I am trying to provide a default content type, entity form display, entity view display and a list (text) field on module installation. Installation errors out (though the module is installed) because of a plugin not found exception for "options\_select" which is a core plugin.

```
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "options_select" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of /var/www/tx-sampling.zaner-bloser.com/webroot/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

```

This is caused by EntityViewBuilder not finding options\_select in its object `$definitions` property, but why? `options_select` is a *core* plugin, and should be loaded? There is no dependency to add in config as the dependencies schema type does not have a "core" option.

This is probably due to something I am not understanding correctly with the YAML configuration I am providing given the following configuration in `module_name/config/install`:

`config_fail/config/install/node.type.config_fail.yml`:

```
langcode: en
status: true
dependencies:
  module:
    - menu_ui
    - config_fail
  enforced:
    module:
      - config_fail
third_party_settings:
  menu_ui:
    available_menus: {  }
    parent: ''
name: 'Config Fail'
type: config_fail
description: 'A content type installed by this module.'
help: ''
new_revision: true
preview_mode: 0
display_submitted: false

```

`config_fail/config/install/field.storage.node.field_blah.yml`:

```
    langcode: en
    status: true
    dependencies:
      module:
        - node
        - options
        - config_fail
      enforced:
        module:
          - config_fail
    id: node.field_blah
    field_name: field_blah
    entity_type: node
    type: list_string
    settings:
      allowed_values:
        -
          value: 'a'
          label: 'Option A'
        -
          value: 'b'
          label: 'Option B'
      allowed_values_function: ''
    module: options
    locked: true
    cardinality: 1
    translatable: true
    indexes: {  }
    persist_with_no_fields: false
    custom_storage: false

```

`config_fail/config/install/field.field.node.config_fail.field_blah.yml`:

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_blah
    - node.type.config_fail
  module:
    - options
id: node.config_fail.field_blah
field_name: field_blah
entity_type: node
bundle: config_fail
label: 'Some Field'
description: 'Choose some option'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: list_string

```

`config_fail/config/install/core.entity_form_display.node.config_fail.default.yml`

```
langcode: en
status: true
dependencies:
  config:
    - field.field.node.config_fail.field_blah
    - node.type.config_fail
  module:
    - path
    - options
id: node.config_fail.default
targetEntityType: node
bundle: config_fail
mode: default
content:
  created:
    type: datetime_timestamp
    weight: 8
    region: content
    settings: {  }
    third_party_settings: {  }
  field_blah:
    weight: 0
    settings: {  }
    third_party_settings: {  }
    type: options_select
    region: content
  path:
    type: path
    weight: 10
    region: content
    settings: {  }
    third_party_settings: {  }
  promote:
    type: boolean_checkbox
    weight: 9
    region: content
    settings:
      display_label: true
    third_party_settings: {  }
  status:
    type: boolean_checkbox
    settings:
      display_label: true
    weight: 6
    region: content
    third_party_settings: {  }
  sticky:
    type: boolean_checkbox
    settings:
      display_label: true
    weight: 11
    region: content
    third_party_settings: {  }
  title:
    type: string_textfield
    weight: 0
    region: content
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  uid:
    type: entity_reference_autocomplete
    weight: 7
    region: content
    settings:
      match_operator: CONTAINS
      size: 60
      placeholder: ''
    third_party_settings: {  }
hidden: {  }

```

`config_fail/config/install/core.entity_view_display.node.config_fail.default.yml`

```
langcode: en
status: true
dependencies:
  config:
    - field.field.node.config_fail.field_blah
    - node.type.config_fail
  module:
    - path
    - options
id: node.config_fail.default
targetEntityType: node
bundle: config_fail
mode: default
content:
  created:
    type: datetime_timestamp
    weight: 8
    region: content
    settings: {  }
    third_party_settings: {  }
  field_blah:
    weight: 0
    settings: {  }
    third_party_settings: {  }
    type: options_select
    region: content
  path:
    type: path
    weight: 10
    region: content
    settings: {  }
    third_party_settings: {  }
  promote:
    type: boolean_checkbox
    weight: 9
    region: content
    settings:
      display_label: true
    third_party_settings: {  }
  status:
    type: boolean_checkbox
    settings:
      display_label: true
    weight: 6
    region: content
    third_party_settings: {  }
  sticky:
    type: boolean_checkbox
    settings:
      display_label: true
    weight: 11
    region: content
    third_party_settings: {  }
  title:
    type: string_textfield
    weight: 0
    region: content
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  uid:
    type: entity_reference_autocomplete
    weight: 7
    region: content
    settings:
      match_operator: CONTAINS
      size: 60
      placeholder: ''
    third_party_settings: {  }
hidden: {  }

```

`config_fail/config_fail.info.yml`:

```
name: 'Config Install fail'
type: module
core: 8.x
dependencies:
  - options

```

# Answer
> 2 votes
Unfortunately the error message doesn't say which plugin type is missing.

But I think it is a field formatter plugin. You install a field type `list_string`:

```
 * @FieldType(
 *   id = "list_string",
 *   label = @Translation("List (text)"),
 *   description = @Translation("This field stores text values from a list of allowed 'value => label' pairs, i.e. 'US States': IL => Illinois, IA => Iowa, IN => Indiana."),
 *   category = @Translation("Text"),
 *   default_widget = "options_select",
 *   default_formatter = "list_default",
 * )
 */

```

The widget `options_select` is correct for the form mode, but not for the view mode. Here you can use the field formatter `list_default`.

---
Tags: configuration
---


# Question
Title: How to add metatag module data to the Search API indexes
I am in the process of building a new site that will have some content in the form of videos and PDFs. To make those more searchable I added the metatag module. We are also using the Search API to hook into Solr and do our search operations.

I have found the hooks I need to insert, update, and delete metatag info from the metatag fields. That part is fairly straight forward.

However, I am stuck on the part where I tell the Search API about the fields so that they can be indexed. I think I will be able to figure out how to push the data to the index with the hooks. I just don't know how to tell the Search API that the fields are there and that they contain strings.

I was looking, originally, at the hook\_search\_api\_item\_type\_info(). However, after reading the description in the API documentation (in the code) I realize that it is only for new entity types. These metatag fields are mainly attached to nodes. And the documentation specifically says that it should not be used for existing entity types (i.e. nodes) because this hook simply tells about the data controller classes.

Should I use hook\_search\_api\_alter\_callback\_info() to do this? That seems like a good candidate, but I am just not quite following how this works in the SearchAPI.

How do I tell the Search API that the metatag fields exist and I want to be able to index them?

This is in Drupal 7.

# Answer
> 1 votes
I do it like this: First

```
  function HOOK_search_api_alter_callback_info() {
  $callbacks['search_api_alter_add_keywords_field'] = array(
    'name' => t('Keywords field from metatag module'),
    'description' => t("Adds Keyword field from metatag module to indexed data."),
    'class' => 'SearchApiAddKeywordField',
  );
  return $callbacks;
}

```

Second

```
class SearchApiAddKeywordField extends SearchApiAbstractAlterCallback {
  public function alterItems(array &$items) {
  foreach ($items as $id => &$item) {
      if (!isset($item->metatags[$item->language]['keywords']['value'])) {

        $item->search_api_keyword = NULL;
        continue;
      }
      $item->search_api_keyword = strtolower ($item->metatags[$item->language]['keywords']['value']);
    }
  }

  public function propertyInfo() {
    return array(
      'search_api_keyword' => array(
        'label' => t('Keyword field'),
        'description' => t('Add keyword field to index.'),
        'type' => 'text',
      ),
    );
  }

}

```
* After Clear cache go to you index filters and check: Keywords field from metatag module
* If Boost settings need to be changed (to give more importance to the field) do it now.
* Index Again
* Go to the search results view - the view you created to list indexed content.
* Assuming that you have fulltext search filter in "Searched fields" select the new "field" Keyword field
* Test the things out.

# Answer
> 0 votes
The "Meta tag" module has the integration with "Search API" ready to be used for indexing your metadata.

From README.txt

> Search API integration
>
> Entity meta tag values can be made searchable using the Search API module (https://www.drupal.org/project/search\_api).
>
> 1. Select "Meta tags" under "Data alterations" in the filters for the index: admin/config/search/search\_api/index/INDEX NAME/workflow
> 2. Meta tag fields will now appear under "Fields" and can be enabled there: admin/config/search/search\_api/index/INDEX NAME/fields

---
Tags: 7, entities, hooks, search, meta-tags
---


# Question
Title: Views PHP Filter buggy for Taxonomy name
I'm trying to show specific contents for specific users based on the taxonomy term.

**Variables explanation:**

```
webauth variable

```

I am using these variables to setup my PHP filter. `$_SESSION['company'];` This will return the company name of the user. This is tested works as required.

```
taxonomy variable

```

I'm trying to get the taxonomy name based on the array format from `print_r($data);` which looks like, `$data->field_field_company[0]['rendered']['#markup']` this prints the taxonomy term present in the `array[0]`. I'm using a for loop to print all the taxonomy terms (*which has a purpose*).

**What I'm trying to achieve?**

When the `SESSION` variable matches with the `Taxonomy` variable, show specified user related taxonomy term content.

So that user having `XYZ` company can see the content, having taxonomy entity with `XYZ` term.

**How am I trying to achieve it?**

In **view** add `PHP global Filter` and in `filter code` I'm trying to add this code:

```
$length = count($data->field_field_company);
  for ($i=0; $i < $length; $i++) {
  /** as I'm having multiple arrays I'm checking every array **/
    if(($_SESSION['company']) == ($data->field_field_company[$i]['rendered']['#markup'])) {
    /** above should be like if(xyz == xyz) **/
      return FALSE;
    }
  }
  return TRUE;

```

If this same code is written in `Fields` `Global PHP` It works fine.

```
<?php
  $length = count($data->field_field_company);
  for ($i=0; $i < $length; $i++) {
    if(($_SESSION['company']) == ($data->field_field_company[$i]['rendered']['#markup']))
    echo "hi";
    }
?>

```

Why it doesn't work at all in the **Filter criteria?**

# Answer
> 0 votes
Found out that there is a `dev version` for the above issue, you may need to update if you are using the old module version.

look at the comment #38 in link below. https://www.drupal.org/project/views\_php/issues/1222448#comment-9852925

Where you can get the `updated version` of this module. https://www.drupal.org/project/views\_php

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


title: Schema for group module

text:
# Question
Title: Schema for group module
I have installed this module and I assume that this works not only in the regular content type but also in the group module. I was expecting that after enabling the module there is an option to map my group type fields in the manage fields section but none even in the edit setting of the group type.

See RDF Mappings in the Basic Page content type:

**Notice this from the module:**

> Features
>
> RDF UI Map Content Types to Schema.org Types. Map Fields to Schema.org properties.

Does the group module supports schema integration? If yes, is there any documentation provided?

# Answer
The RDF UI module only provides the 'RDF Mapping' local task for nodes at the moment (so not Group entities). See the `if` statement in this snippet from `Drupal\rdfui\Plugin\Derivative\RdfUiLocalTask::getDerivativeDefinitions()`:

```
foreach ($this->entityManager->getDefinitions() as $entity_type_id => $entity_type) {
  if ($entity_type->get('field_ui_base_route') && $entity_type_id === "node") {

    $this->derivatives["overview_$entity_type_id"] = array(
      'route_name' => "entity.$entity_type_id.field_ui_fields",
      'title' => $this->t('Fields'),
      'parent_id' => "field_ui.fields:overview_$entity_type_id",
    );

    $this->derivatives["rdf_$entity_type_id"] = array(
      'route_name' => "entity.$entity_type_id.rdf_ui_fields",
      'weight' => 2,
      'title' => $this->t('RDF Mappings'),
      'parent_id' => "field_ui.fields:overview_$entity_type_id",
    );

  }
}

```
> 0 votes

---
Tags: 8, database, group
---


# Question
Title: Banned IP address is still able to access the site
I've blocked the IP address at admin/config/people/ip-blocking and I can see it also in the flood control logs as a blocked IP, but the IP is still accessing the site and I can see errors in the watchdog with their IP address after the block...

I'm at a complete loss as to how this could be... google and SE search has brought nothing. Why isn't Drupal blocking this IP?

Edit: I tested it with a firend's IP and it's not blocking him either, so I guess my IP blocking is not working at all...

# Answer
Turns out my host has me on a load balancer so the IP was masked by the load balancer. I had to look at the values inside the `$_SERVER['HTTP_X_FORWARDED_FOR']` variable instead of `$_SERVER['REMOTE_ADDR']`

See more info here too: https://www.drupal.org/project/smart\_ip/issues/1820048
> 2 votes

---
Tags: 7, users
---


# Question
Title: How to get node url from Entity Reference field?
We have an ECK Bundle that has an Entity Reference to Article and Basic Page content type. In the twig template we are using the following line below to get the node's nid value and then using that in the twig template to create a link to that node. However, we are getting the following error message while logged out (for logged in users it works fine).

How can we get the node's url for both anonymous and logged in users?

Twig template (eck-entity--component--eck-ref-node--default.html.twig where eck-ref-node is the eck bundle name):

```
{% set field = entity.field_eck_ref %}
{% set ref_node = field.0['#node'] %}
{% set nodeId = ref_node.nid.value %}
{% set nodeURL = path('entity.node.canonical', {'node': nodeId}) %}

<a href={{ nodeUrl }}>
...
</a>

```

Error:

> Uncaught PHP Exception Symfony\Component\Routing\Exception\InvalidParameterException: "Parameter "node" for route "entity.node.canonical" must match "\d+" ("" given) to generate a corresponding URL."

# Answer
I ended up using template\_preprocess\_eck\_entity() with the following lines of code to get the node URL and passed it into the Twig template. I ended up calling Entity::url to get the canonical URL.

```
template_preprocess_eck_entity(&$vars) {
$eck = $vars['entity']['#component'];
if($eck->bundle() == 'eck_bundle_name') {
    if($eck->hasField('field_eck_bundle')) {
         $ref = $eck->get('fiedl_eck_bundle'));
         $entRef = $ref->offsetGet(0)->get('entity');
         $node = $entRef->getTarget()->getValue();
         $node_url = $node->url();
         $vars['field_eck_bundle']['node_url'] = $node_url;
    }
}

}//end template_preprocess_eck_entity()

```

eck-entity--component--eck-ref-node--default.html.twig

```
{{ field_eck_bundle.node_url }} {# this works #}

```
> 0 votes

# Answer
`#node` is usually part of a render array. Don't know why you named this `entity`. If it were a real entity object, then you could get the node id directly with `.target_id` instead of `['#node']`.

The problem with keys in render arrays like `#node` is, they are only included if needed for rendering, so it's not a good idea to write code which fails if it does not exist.

You have to look for the entity object. According to the template doc the entity is named `eck_entity`:

```
{#
/**
 * @file
 * Default theme implementation to display an ECK entity.
 *
 * Available variables:
 * - eck_entity: The full ECK entity with limited access to object properties
 *   and methods. Only "getter" methods (method names starting with "get",
 *   "has", or "is") and a few common methods such as "id" and "label" are
 *   available. Calling other methods (such as node.delete) will result in an
 *   exception.
 * - content: All ECK entity items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - attributes: HTML attributes for the containing element.
 *
 * @see template_preprocess_eck_entity()
 *
 * @ingroup themeable
 */
#}

```

If this is the template you use, then try something like this to access the field object and the target id of the node:

```
{% set field = eck_entity.field_eck_ref %}
{% set nodeId = field.0.target_id %}

```

This works independently of user permissions.

And only build the url when you are sure you have a node id, because otherwise your code still fails if the field is empty.
> 0 votes

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


# Question
Title: How to show text fields from a User object to anonymous users without "View User Profile" permission?
I have a few basic fields on the user object to display "Author Bio" cards at the bottom of articles. It seems that anonymous users cannot see any of this information.

All I want to do is show first name, last name, phone number and email address. Is this hidden away because it requires "View User Profile" permission? How can I get around enabling that? I don't want to enable that if I don't have to. Conversely, how I can prevent anyone from getting to user/\* pages?

Is there something I can change in the render array to change the access check?

# Answer
> 1 votes
> Conversely, how I can prevent anyone from getting to user/\* pages?

Getting technical here, you wouldn't want to block all `/user/*`; otherwise, you wouldn't be able to `/user/login` or `/user/logout` and also you would still want admins to access those `/user/{uid}` pages.

If you inspect core/modules/user/**user.routing.yml** you can see most of the user routes. But what you expect, the `/user/{uid}` is not defined here.

It's actually defined in **UserRouteProvider.php** as `/user/{user}`

You can easily find the route name by enabling WebProfiler module that comes with Devel and going to `/user/1`

Now all you gotta do is override the route's access by giving it a role of administrator.

**mymodule/src/Routing/RouteSubscriber.php**

```
namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Allow only admins to access '/user/{user}'.
    if ($route = $collection->get('entity.user.canonical')) {
        $route->setRequirement('_role', 'administrator');
    }
  }

}

```

Alternatively, in your custom module, you could create a new permission and use that for the Route's `setRequirement` instead and then assign the new permission to the roles that you want to have access.

**mymodule/mymodule.services.yml**

```
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

For more in depth information about altering routes, see: Altering existing routes and adding new routes based on dynamic ones.

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


# Question
Title: Add image field or other fields from node to a custom Block in Drupal 8
I am new to Drupal and I am learning pretty fast. However I am stuck on an issue.

I need to make a custom Block for my content (node) images.

There is a system-made content block which pulls from the node form of content type "Basic Page". I've added a "Image upload field" to that so I can upload images within my content.

I am able to render the field on the page after adding the content block to the content region, However, I need to show just that image of that node in some other region.

How can I do this?

# Answer
Use Views module for this. In D8 the views module is part of the core, in D7 you need to install it

1) Go to Structure \> view

2) Add a view which shows content of type Basic page. Check on create a block.

3) Select the fields to be shown as image (as you want)

4) Under **Advanced** (on the right side of the view, click on it to expand)

**CONTEXTUAL FILTERS** click `add`, and select ID (D8) or Nid (D7) and then choose "Provide Default Value" and Under type select "Content ID From URL". click on Apply and save the view.

5) In structure \>blocks, place the block in the region you want to on the content type you wish (In your case Basic Page).

6) Go to your basic page content and you will be able to see the image which belongs to that node only in the view block you have placed.
> 3 votes

# Answer
You can use Field as Block module for that scenario.

I often use it to place the node content in one region, and node image in another -as a dynamic block.
> 0 votes

---
Tags: nodes, blocks, media, theming
---


title: Importing Taxonomy from CSV

text:
# Question
Title: Importing Taxonomy from CSV
I know that there are a couple of modules to import taxonomy from CSV but my taxonomy has many term references inside it.

Attached is a screenshot of my taxonomy, how can I import the excel sheet into it? Please help

excel sheet.

# Answer
Programmatically speaking, for term references you need to use the Term ID rather than the actual term name.

Luckily, the D7 Feeds module comes with a feature where it fetches the Term ID automatically for you based on the Term Name.

Here is an example of one of my mappings:
> 0 votes

---
Tags: taxonomy-terms, importing-exporting
---


# Question
Title: How do I add custom keywords in the URL?
For a sake of SEO, I need to be able to dynamically pass random keywords to the URL. For example, instead of the classic *variable=value* couples in a query (e.g. /my-node-title?selected=random-seo-keyword), I need to use a good-looking path like /my-node-title/random-seo-keyword, where *my-node-title* is a URL / path alias of node/xxx but *random-seo-keyword* does not exist in the structure and may not be predefined.

Then, on the server I handle and split the URL parts with a script. The only problem is that currently Drupal 7 returns a 404 error in such cases.

# Answer
> 1 votes
You can alter your paths by using `hook_url_*_alter()` hooks. Have a look at `hook_url_inbound_alter()` and `hook_url_outbound_alter()`.

# Answer
> 0 votes
I found this module https://www.drupal.org/project/subpathauto thanks to Paul Jones answer in this post Passing an argument to a node causes 404

This module correctly recognizes Drupal paths in links and avoids 404 errors.

---
Tags: uri
---


# Question
Title: How to access a custom field in a field twig loop?
I have a content type article which have a field repeatable "related content"

I use a field twig where I have this loop

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

```

It works very well : it displays title of the article and a link to the content.

I would like also to display some subfields associated with this content but I'm not successful.

I’ve tried things like :

```
{{ item.content.field_date_mise_a_jour_article.value }}

```

but obviously it doesn’t work. `item.content` only contains url and title.

How can I do that ?

In `node--article.html.twig`, i can access the related content subfield like that :

```
{{ node.field_suggestion_articles.entity.field_date_mise_a_jour_article.value }}

```

How can I do the same in

```
field--field-suggestion-articles.html.twig

```

# Answer
As you are creating the twig template for a field and try to access the fields / data that is not available, you can write your custom code in preprocess function and you should use the template\_preproces\_field and create custom variable with desired data and use that variable in custom twig template.

In preprocess function

```
$variables['myVariable'] = 'My Desired Data';

```

In Twig use the variable which will print 'My Desired Data'

```
{{ myVariable }}

```
> 1 votes

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


# Question
Title: How can I use a custom function in a field widget class?
I have created custom fields using field,field widget and field formatters. One of the field I have created is a button. What I need is to write the submit handler for that button.

This is my CertfieldDefaultWidget.php.

```
namespace Drupal\certfield\Plugin\Field\FieldWidget;

use Drupal;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
 * Plugin implementation of the 'CertfieldDefaultWidget' widget.
 *
 * @FieldWidget(
 *   id = "CertfieldDefaultWidget",
 *   label = @Translation("Certfield select"),
 *   field_types = {
 *     "Certfield"
 *   }
 * )
 */
class CertfieldDefaultWidget extends WidgetBase {
  /**
   * Define the form for the field type.
   *
   * Inside this method we can define the form used to edit the field type.
   *
   * Here there is a list of allowed element types: https://goo.gl/XVd4tA
   */
  public function formElement(
    FieldItemListInterface $items,
    $delta,
    Array $element,
    Array &$form,
    FormStateInterface $formState
  ) {
      //print_r($items[$delta]->cert_fqdn);
      //exit();

 $element['cert_fqdn'] = [
      '#type' => 'textfield',
      '#title' => t('Fully qualified Domain Name'),
      '#value' => isset($items[$delta]->cert_fqdn) ?
          $items[$delta]->cert_fqdn : null,
      '#empty_value' => '',
      '#placeholder' => t('Fully qualified Domain Name'),
    ];
    $element['privatekey'] = [
      '#type' => 'textfield',
      '#title' => t('Private Key'),

      // Set here the current value for this field, or a default value (or
      // null) if there is no a value
      '#default_value' => isset($items[$delta]->cert_key) ?
          $items[$delta]->cert_key : null,

      '#empty_value' => '',
      '#placeholder' => t('PrivateKey'),
    ];

    // City

    $element['csr'] = [
      '#type' => 'textfield',
      '#title' => t('Certificate Signing Request'),
      '#default_value' => isset($items[$delta]->cert_csr) ?
          $items[$delta]->cert_csr : null,
      '#empty_value' => '',
      '#placeholder' => t('Certificate Signing Request'),
    ];
    $element['cert_crt'] = [
      '#type' => 'textfield',
      '#title' => t('Server Certificate'),
      '#placeholder' => t('Server Certificate'),
    ];
    $element['create_cert_btn'] = [
      '#type' => 'submit',
      '#title' => t('Server Certificate'),
      '#placeholder' => t('Server Certificate'),
    ];

$element['create_cert_btn'] = array(
    //'#name' => implode('_', $element['#parents']) .'_create_cert_btn',
    '#type' => 'submit',
    '#value' => t('Create/Renew Cert'),
    '#callback' => '_certfield_button_action'
        );

    return $element;
  }

} // class

```

In the certfield.module or CertfieldDefaultWidget.php file, I have a `_certfield_button_action(&$element, $form_state, $button)` function, but it's not called when the button is clicked.

# Answer
Because this is your custom widget, you don't need to create a custom submit function.

Just add `WidgetBase::massageFormValues` method to your class:

```
class CertfieldDefaultWidget extends WidgetBase {
  ....
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    // manipulate with $values where $values is an array of your fields defined in your formElement.
    return $values;
  }
  ....
}

```
> 2 votes

# Answer
In your widget, replace

```
'#callback' => '_certfield_button_action'

```

by

```
'#submit' => [[get_class($this), 'certfieldButtonAction']]

```

and implement

```
public static function certfieldButtonAction(array $form, FormStateInterface $form_state)

```
> -1 votes

---
Tags: 8
---


# Question
Title: Check if a field group's subfields have values
Is it possible to check if a fieldset's subfields have values? If none of the fieldset's fields have values it would return null.

```
$field = field_get_items('node', $node, 'group_name');
if ($field) {
   // At least 1 of it's sub-fields has a value!
}
else{
   // None of it's subfields have values!
}

```

# Answer
> 1 votes
You might want to try use the `field_group_field_group_is_empty()` function.

From the field\_group module itself:

```
  // Example from field_group itself to unset empty elements.
  if ($display) {
    foreach (element_children($element) as $name) {
      if (in_array($name, $groups)) {
        if (field_group_field_group_is_empty($element[$name], $groups)) {
          unset($element[$name]);
        }
      }
    }
  }

```

---
Tags: 7, entities
---


title: Drupal 7 Custom Search Result Page

text:
# Question
Title: Drupal 7 Custom Search Result Page
I am trying to create a custom page that display my resuslts which I receive after I search for a post.

I am having no luck, I am a total begginer in drupal 7, I googled and looked around here but I did not quite understood what I have to do.

What I tried:

```
function **themename**_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  if (!empty($variables['module'])) {
    $variables['module'] = check_plain($variables['module']);
  }
  foreach ($variables['results'] as $result) {
    $variables['search_results'] .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
  }
  $variables['pager'] = theme('pager', array('tags' => NULL));
  $variables['theme_hook_suggestions'][] = 'search_results__' . $variables['module'];
}

```
1. Creating a search-results.tpl.php ( did not work )
2. The only module I have installed for search is the default search module.

Nothing seems to work. Thanks in advance

# Answer
You are just processing the search results in your function but haven;t handled the output. Change the tpl.php to display the variables from your function rather than from the default search function.
> -1 votes

---
Tags: theming, search
---


# Question
Title: How to create a view which would list related content for current article?
I try to create a view which would list related content (some articles) to a content type article.

Here is what i’ve done. I’ve created a field "Entity reference" in the content types "Article". It works. I can see in database the related article ID .

Then, I create a view with a block. It works, i can see all articles listed in that view (which is visible on each article).

Here is my issue. I need to display only articles related to the current article. So, in contextual filter, i have tried with Content: ID and also tried with advanced/Relationships but without success. I don’t see my related articles.

How can I do ?

I’ve also tried a different way (create a twig) and even if it works, it is not the best solution i think

# Answer
> 4 votes
Ignore using fields in the View. This has been and will always be problematic IMO for 95% of Views people are making.

You need the Content ID argument from the URL so the correct node is selected, but here is where it takes a turn:

Set the view to show "Content" and give it a view mode, for instance, create a view mode called "Related Content" for nodes. In the field display for that view mode, only set the "Related Articles" field to be visible. Set its field formatter to "Rendered Entity", and create a view mode for *that* content type and theme it. On that content type, you would have title and body, or whatever fields you want to show (hard to tell without seeing a design).

Now the View will pull the node, render it, and in turn render the nodes that are being referenced in a view mode.

Then, you would get something like this, for example:

That is a View that looks at the current node, and renders it. The view mode has a field (Related Content), which is a node reference, and those nodes are rendering in a "Preview" view mode - and this is the result. All of the markup lives in two twig files (for the node--node-type--view-mode.html.twig) and the Views configuration is super simple.

The Views display would be a block, and you can place that block in whatever region works for you.

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


# Question
Title: How can i import plain password that are not encrypted during a user migration?
I am able to migrate all the datas of users account including the password but it doesn’t work due to encryption and hash in drupal 8.

My password are not MD5. They are not encrypted, in csv file they are like normal plain text.

I’ve seen here : https://www.drupal.org/docs/8/api/migrate-api/migrate-destination-entityuser

> If the incoming passwords are not plain or are not MD5 hashed you'll have to deal with this in your migration

My password are plain so i guess it should work.

Here is what i’ve tried but the password are imported but not encrypted :

```
destination:
  plugin: 'entity:user'
  plaintext_passwords: true

```

In the documentation, it is explained how to import MD5 password but not plain password.

What should i use for the configuration ?

---

**EDIT :**

I’ve tried this :

```
pass:
    -
      plugin: callback
      callable: 'Drupal\Core\Password\PhpassHashedPassword::hash'
      source: passwebservice

```

And

```
pass:
    -
      plugin: callback
      callable:
        - 'Drupal\Core\Password\PhpassHashedPassword'
        - hash
      source: passwebservice

```

Error :

> Error: Using $this when not in object context in Drupal\Core\Password\PhpassHashedPassword::hash() \[error\] (line 215 of Core/Password/PhpassHashedPassword.php) 0 \[internal function\]: Drupal\Core\Password\PhpassHashedPassword::hash('9BQmM1') 1 core/modules/migrate/src/Plugin/migrate/process/Callback.php(54): call\_user\_func('Drupal\Core\Pas...', '9BQmM1')

When i check hash()

```
public function hash($password) {
    return $this->crypt('sha512', $password, $this->generateSalt());
  }

```

I can't invoke method this way (`$this` does not exist in class context) so how can I do ? Is it possible in configuration file ?

# Answer
You can use Ivan Jaros' code in two ways:

As you said, preprocess your passwords to convert them to hashes. This can be done via a Drush script that can be run from the command line. Drush scripts are just snippets of PhP code that run in the Drupal context. Run by the command:

drush @site-alias scr \[path to php snippet\]

The alternative is to override you CVS Source class and use the preparerow method to hash the password.

```
  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $password = $row->getSourceProperty('password');
    $hash = \Drupal::service('password')->hash($password);
    $row->setSourceProperty('password', $hash);
  }

```

As pointed out in the comments, you can also use a process plug-in to do this. The callback plugin only uses static classes and AFIAK the hash method requires access to the context information that is not available via static methods.

Here's some quick untested code to create your own process plug-in to hash a plain text password.

```
<?php

namespace Drupal\my_mode\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * Converts a plain password to an hash.
 *
 * Example:
 *
 * @code
 * process:
 *   password:
 *     plugin: my_module_hash_password
 *     source: field_password
 * @endcode
 *
 * @see \Drupal\migrate\Plugin\MigrateProcessInterface
 *
 * @MigrateProcessPlugin(
 *   id = "my_module_hash_password"
 * )
 */
class HashPassword extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $hash = \Drupal::service('password')->hash($value);
    return $hash;
  }

}

```
> 4 votes

# Answer
I have written custom migration to migrate users from CSV file. I have successfully migrated the user but when i tried to login its give me login error so I have checked my migration code found `md5_passwords: true` in it. `md5_passwords` convert any string to hashed string with `md5()` encryption. so i have written my custom plugin and added to my migration code without `md5_passwords: true`.

Here is the step by step solution:

1. Create custom module and define your plugins file in it:

```
custom_module->src->Plugins->plugins_name->process->plugin_file.php

```

in my case:

```
custom_module->src->Plugins->migrate->process->HashPasswords.php

```
2. Write this example code in your plugin\_file.php

```
<?php

namespace Drupal\custom_module\Plugin\migrate\process;
use Drupal\Core\Password\PhpassHashedPassword;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
* Converts a plain password to an hash.
*
* Example:
*
* @code
* process:
*   password:
*     plugin: hashpasswords
*     source: password
* @endcode
*
* @see \Drupal\migrate\Plugin\MigrateProcessInterface
*
* @MigrateProcessPlugin(
*   id = "hashpasswords"
* )
*/
class HashPasswords extends ProcessPluginBase {

/**
* {@inheritdoc}
*/
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
   $passwordHasher = new PhpassHashedPassword(1);
   $hashedPassword = $passwordHasher->hash($value);
   return $hashedPassword;
  }
} ?>`

```
3. Now write your migration code and add this custom plugin.

```
id: ROF_user
label: 'Migrate ROF User from CSV'
source:
  plugin: csv
  path: modules/custom/custom_module/csv/user.csv
  header_row_count: 1
  keys:
    - ID
process:
  uid: ID
  name: name
  field_first_name: firstname
  field_last_name: lastname
  mail: email
  pass:
    plugin: hashpasswords
    source: password
  roles:
    plugin: explode
    delimiter: ','
    source: roles
  status: status
destination:
  plugin: 'entity:user'
migration_dependencies:
  required: {  }
  optional: {  }

```
> 0 votes

---
Tags: 8, users, migrations
---


title: Dependecies prefix coding standard

text:
# Question
Title: Dependecies prefix coding standard
Running `phpcs --standard=DrupalPractice` in several modules \*.info.yml file I get a warning message:

```
All dependencies must be prefixed with the project name

```

I've seen some modules that use the module name as prefix

```
dependencies:
  - modulename:modulename
  - modulename:submodulename

```

Others when it belongs to Drupal core:

```
dependencies:
  - drupal:modulename_already_in_core

```

Others when it belongs to always Drupal (doesn't taking into account if the module is in the core or not):

```
dependencies:
  - drupal:modulename

```

Which is the right syntax? Should I use "drupal" always? Just when the module is in Drupal (core)? What is the aim of this requirement?

Thanks!

More info: https://www.drupal.org/project/coder/issues/2854781

# Answer
As described in Let Drupal 8 know about your module with an .info.yml file, the correct format is:

* project-name:module-name for third-party modules
* drupal:module-name for a core module

> Dependencies should be namespaced in the format: {project}:{module} where {project} is the project name as it appears in the Drupal.org URL (e.g. drupal.org/project/views) and {module} is the module's machine name.

Since the project page for Drupal core is https://www.drupal.org/project/drupal, the case for Drupal core modules is the same as for third-party modules.
> 1 votes

---
Tags: coding-standards
---


# Question
Title: Remove import instance from list using Migrate Tools module
I'm trying to remove an rss reference of a migration. Once I put the yaml code into the Migrate module in the drupal admin interface, it creates a reference to that yaml code, but there is no one in the UI that I can see the reference. The Migrate Tools module gives me access to drush commands, but none of which could remove a reference.

Does anyone know how to delete a reference to an import? I can see references through the command line using `$ drush ms`

I searched but could only find using this, but it doesn't work.

```
$ drush php

>>> Drupal::configFactory()->getEditable('migrate_plus.migration.my_rss_importer')->delete();

```

Here is the list of imports from the CLI I am trying to remove. Just for reference "migrate\_plus" mentioned in the code above is another module that compliments the migrate module.

```
Group: Default (default)      Status  Total  Imported  Unprocessed  Last imported
 berkeley_news_rss_importer_1  Idle    20     20        0            2017-12-09 23:08:36
 berkeley_news_rss_importer_2  Idle    20     20        0            2017-12-09 23:12:34
 berkeley_news_rss_importer_3  Idle    20     20        0            2017-12-09 23:14:03
 berkeley_news_rss_importer_4  Idle    20     20        0            2017-12-09 23:20:04
 berkeley_news_rss_importer_5  Idle    20     20        0            2017-12-09 23:33:17
 berkeley_news_rss_importer_6  Idle    20     20        0            2017-12-09 23:42:26
 berkeley_news_rss_importer_7  Idle    20     0         0            2017-12-10 00:11:17
 berkeley_news_rss_importer_8  Idle    20     20        0            2017-12-11 09:46:45
 berkeley_news_rss_importer_9  Idle    20     0         20

```

# Answer
So you want to get rid of the migrations so that they don't appear in the `drush ms` output? Do this:

*Removing imported content*

Upon reading your question the second time, I thought you might even be asking "How to remove the content which is imported already?". If that is your question, then try `drush migrate-rollback` or `drush mr` for short. See documentation with `drush mr --help`.

*Deleting the migrations*

* If you are using configuration management, then delete the relevant config YML files from the config sync directory and do `drush cim`. There should be files named `migrate_plus.migration.MIGRATION_ID`. It will ask for confirmation and if you say `y`, the relevant migrations will be deleted.
* If you are not using configuration management, do `drush config-list`. Now, for every migration you want to delete, search for the name of the migration in the output of the config list and do a `config-delete` for it. Example: `drush cdel migrate_plus.migration.MIGRATION_ID` Consider using config management in the long run.

*Deleting migration mappings*

* The migrate module might have created some mapping tables in the database to track your migrations. To delete these tables (I assume you know what you're doing), delete the mapping and messages tables for the migration. Example: `DROP TABLE IF EXISTS migrate_map_MIGRATION_ID, migrate_messages_MIGRATION_ID`. After you do this, you will never be able to do `rollback`.

Hope it helps.
> 4 votes

# Answer
Migrate plus migrations are entities: the following code is adapted from MigrationGroup::delete(), where it finds each migration in a group and deletes them:

```
$migration_to_delete = 'my_rss_importer';
$migration = \Drupal::entityTypeManager()
  ->getStorage('migration')
  ->load($migration_to_delete);
$migration->delete();

```

Note that this calls Cache::invalidateTags(\['migration\_plugins'\]), so after a cache clear, it will remove your cached plugins.
> 1 votes

---
Tags: 8, drush, migrations, feeds
---


# Question
Title: Changing a user password through phpMyAdmin
Hopefully this should be a quickly resolvable query:

If I only have phpMyAdmin as a means of changing a password - e.g. say I can't login and need to change the Admin password (and Drush is equally not available etc) should I be able to reset a user's password using the following query:

```
UPDATE drupal_users SET pass = SHA2( 'the_password', 256 ) WHERE uid = 20

```

where the drupal tables are prefixed with "drupal\_"

I have tried the above query in order to change the password for a user, but when using the password specified in the above sql statement I am still unable to login. This makes me think I am missing something here.

Anyone got any ideas how to change a drupal 7 user password via PhpMyAdmin using SQL?

# Answer
> 2 votes
Drupal 7 uses a hash salt (see your settings.php) in addition to several other bit of information in order to create a SHA2 of the users PW. You should really use drush to change a user's pw if you need to.

# Answer
> 1 votes
If you have some other Drupal user account access to the site with enough rights, you can generate new hash as follows: Create any content page with PHP text format and put there:

```
<?php
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
print('Hash: ' . user_hash_password('my_password'));
?>

```

Otherwise, if we don't have any Drupal user access or file access I am afraid we are in trouble, because the hash salt is stored in the config file.

# Answer
> 0 votes
If you have a local version with the same setting.php / salt hash, you can use the password-hash script. This will generate a new hashed password that can be inserted via SQL.

All this is explained in the docs.

---
Tags: 7, users, database
---


# Question
Title: How can I programmatically populate a drop-down list field's options?
I have a paragraph bundle with several fields, on of them being drop-down list.

How would I go about populating this dropdown list via code, programmaticaly?

I don't really know where to begin with this...

# Answer
Ok, here's what I figured out:

Use `hook_field_widget_form_alter()`

My case:

```
function my_module_field_widget_form_alter(&$element, &$form_state, $context) {

  // Check if element is paragraph type, belongs to a specific paragraphs
  // bundle and contains a specific field.
  if (empty($element['#entity']) || $element['#entity_type'] !== 'paragraphs_item' ||
    $element['#bundle'] !== 'content_block' || $element['#field_name'] !== 'field_dropdown_text_single') {
    return;
  }

  // Get entity metadata
  $form_field_wrapper = entity_metadata_wrapper('paragraphs_item', $element['#entity']);

  // Set default value. If there is already a set value use that,
  // else set to '_none'
  $default_value = $form_field_wrapper->field_dropdown_text_single->value();
  $element['#default_value'] = !empty($default_value) ? $default_value : '_none';

  // Code to get your custom select options goes here

  // Inject custom options into paragraph's dropdown selector.
  $element['#options'] = $my_options;
}

```
> 1 votes

# Answer
Check out hook\_options\_list() to dynamically populate available options.
> 0 votes

---
Tags: 7, entities, paragraphs
---


# Question
Title: How to process an http request with a controller?
I try to write a custom Restful API to send contents between two drupal site. The present code work except the datas are in a weird format with @ in the json.

My resquest is:

```
$serializer = \Drupal::service('serializer'); $data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);

$response = \Drupal::httpClient()
        ->post("http://site1.test/api_test/send_content", [
          'headers' => [
            'Content-type' => 'application/json',
          ],
          'json' => $data,
        ]);`

```

The function which process my request:

```
public function createNewContent(Request $request) {

   if ( 0 === strpos( $request->headers->get( 'Content-Type' ), 'application/json' ) ) {

     $data = json_decode( $request->getContent() );

     \Drupal::logger('test_rest_api')->notice($data);
   }

   $response['data'] = 'Query well received';
   $response['method'] = 'POST';

   return new JsonResponse( $response );
}

```

The problem is, after the json\_decode my datas let a big string and look like:

> @"nid":\[{"value":5197\],"uuid":\[@"value":"8310f782-06ce-4fb8-957d-ec7feecc8929"\],"vid":\[@"value":63527\],"langcode":\[@"value":"en"\],"type":\[@"target\_id":"page","target\_type":"node\_type","target\_uuid":"189f826c-e516-4a22-8d4d-f3a2f418aea9"\],"revision\_timestamp":\[@"value":"2017-12-19T21:08:36+00:00","format":"Y-m-d\TH:i:sP"\],"revision\_uid":\[@"target\_id":1,"target\_type":"user","target\_uuid":"3e68a310-1da4-4691-8501-854c329d9899","url":"/fr/user/1"\],"revision\_log":\[\],"status":\[@"value":true\],"title":\[@"value":"Test"\],"uid":\[@"target\_id":1,"target\_type":"user","target\_uuid":"3e68a310-1da4-4691-8501-854c329d9899","url":"/fr/user/1"\],"created":\[@"value":"2017-12-19T21:07:57+00:00","format":"Y-m-d\TH:i:sP"\],"changed":\[@"value":"2017-12-19T21:08:36+00:00","format":"Y-m-d\TH:i:sP"\],"promote":\[@"value":true\],"sticky":\[@"value":false\],"default\_langcode":\[@"value":true\],"revision\_translation\_affected":\[@"value":true\],"moderation\_state":\[\],"content\_translation\_source":\[@"value":"und"\],"content\_translation\_outdated":\[@"value":false\],"metatag":@"value":{"title":"Test","og\_site\_name":"Test","shortlink":"http://site1.test/en/node/5197/sendContent","canonical\_url":"http://site1.test/en/node/5197/sendContent","og\_type":"article","og\_url":"http://site1.test/en/node/5197/sendContent","image\_src":"http://site1.test/sites/default/files/styles/header\_full/public/medias/img/hero\_pr4\_0282.jpg?itok=kSm8zY0q","og\_title":"Test","og\_description":"This is a test","og\_image":"http://site1.test/sites/default/files/styles/header\_full/public/medias/img/hero\_pr4\_0282.jpg?itok=kSm8zY0q","og\_updated\_time":"2017-12-19T16:08:36-05:00","article\_published\_time":"2017-12-19T16:07:57-05:00","article\_modified\_time":"2017-12-19T16:08:36-05:00"},"path":\[@"alias":"/test","pid":16287,"langcode":"en"\],"rh\_action":\[@"value":"bundle\_default"\],"rh\_redirect":\[\],"rh\_redirect\_response":\[@"value":301\],"publish\_on":\[\],"unpublish\_on":\[\],"menu\_link":\[\],"body":\[@"value":"\u003Cp\u003EThis is a test\u003C/p\u003E","format":"full\_html","summary":""\]}

I precise the @ are already present before the json\_decode. I don't know where I could have made a mistake.

I suppose I can clean it easily but I'm more interested to understand what is this format and how can I convert it properly and quickly.

# Answer
> 1 votes
Ok, my problem was the serialization. To recover my node object in my function of POST, I should deserialize the json with the function:

```
 $data = \GuzzleHttp\json_decode( $request->getContent(), TRUE);
 $serializer = \Drupal::service('serializer');
 $node = $serializer->deserialize($data, \Drupal\node\Entity\Node::class, 'json');

 $new_node = Node::create(array(
   'type' => $node->bundle(),
   'title' => $node->title,
   'langcode' => $node->language()->getId(),
   'uid' => '1',
   'status' => 1,
   'body' => $node->get('body'),
 ));

 $new_node->save();

```

Now, I can manipulate my node like I want in my other website.

---
Tags: 8
---


# Question
Title: Webform: get field value from the Entity select option
I have an entity select list based on **View** which collects a list of groups and their corresponding email address(may not be unique!). It seems that there is bug in **entity\_reference.module** so only titles of nodes are displayed.

I want to send emails based on the selected group. I have tried to set the **Custom To email address** using tokens but failed.

```
[webform_submission:values:groups:0:entity:field_email:*]
[webform_submission:values:groups:0:entity:field_email:value]
[webform_submission:values:groups:field_email:value]

```

Do I type the wrong tokens or is there any other alternative solution for this situation?

# Answer
> 1 votes
I was able to get all three of the below tokens to pull the single first email address for the group node's field\_email.

\[webform\_submission:values:groups:entity:field\_email\] \[webform\_submission:values:groups:0:entity:field\_email\] \[webform\_submission:values:groups:0:entity:field\_email:value\]

Only \[webform\_submission:values:groups\] returns 'Node Title (NID)'.

---
Tags: 8, webforms
---


# Question
Title: How can I verify users the first time they log in?
I was reading this article. I would like to know how logging in with the REST API in Drupal 8 works. By default, when users log in, Drupal will verify username and password. After the login, the browser has a cookie for the created session.

>

With the REST API, how can Drupal 8 verify users the first time they log in? After the login, how does it check the current login?

# Answer
Log in to Drupal by POSTing the user credentials. Make sure you set the "Content-Type" header. This starts the user's session.

POST URL:

```
/user/login?_format=json

```

Header:

```
Content-Type: application/json

```

POST data:

```
{
  "name": "username",
  "pass": "password"
}

```

Successful response:

```
{
  "current_user":{
    "uid": "1",
    "roles":[
      "authenticated",
      "administrator"
    ],
    "name": "username"
  },
  "csrf_token":   "asda09820380_2238019280dk09n908asjdlkajdaoa",
  "logout_token": "asdasd09a8sdaslkdasl-asdasdklsajdlkasdjlksj"
}

```

Use the CSRF token in subsequent GET, POST, PATCH, DELETE etc. requests by setting the header:

```
X-CSRF-Token: asda09820380_2238019280dk09n908asjdlkajdaoa

```

To log out, use the logout token in a POST request. This ends the user's session.

```
/user/logout?_format=json&token=asdasd09a8sdaslkdasl-asdasdklsajdlkasdjlksj

```

GET login status:

```
/user/login_status?_format=json

```

GET token:

```
/rest/session/token

```

References:
> 15 votes

# Answer
Drupal Core version: **8.x-4.x**

You need to enable the user login service first thing, this may be accomplished in so many ways, I prefer using REST UI module.

Go to **/admin/config/services/rest** and enable **User** Rest resource.

Once enabled it you can go to **/admin/config/services/rest/resource/entity%3Auser/edit** by clicking on **Edit** next to the **User** resource. Make sure to enable the **GET** method.

Now you have everything setup, you can start using the service by running this command in the terminal or by using any application for curl requests like: Postman and Restlet clients.

**NOTE**: CSRF Token can be obtained from: ***/rest/session/token***

```
curl -i -L -X POST \
  -H "Content-Type:application/json" \
  -H "Accept:application/json" \
  -H "X-CSRF-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \
  -d \
     '{
       "name": "my_username",
       "pass": "my_password"
     }' \
'http://SITE-URL/user/login?_format=json'

```

**The return objects are as below:**

***SUCCESS***:

```
{
  "current_user": {
  "uid": "1",
    "roles": [
      "authenticated"
    ],
    "name": "Admin"
  },
  "csrf_token": "bbbbbbbbbbbbbbbbbbbbbbbbbb",
  "logout_token": "ccccccccccccccccccccccccc"
}

```

***FAILURE***:

```
{
  "message":"Sorry, unrecognized username or password."
}

```
> 3 votes

---
Tags: 9
---


# Question
Title: How can I prepopulate a field's value when creating a new entity
I have a custom entity (foo) which contains an entity reference field to another custom entity (bar). I would like to create a URL on the bar's unique page to create a new foo entity, where the entity reference is pre-populated with the correct target\_id.

For example, a link to /admin/structure/my\_module/foo/add?target\_id=2501

Is this feature already available? Can I add something to the entity buildForm method to prepopulate my value?

```
class FooForm extends ContentEntityForm {
  public function buildForm(array $form, FormStateInterface $form_state) {
    //SOMETHING LIKE THIS?
    //if (isset(REQUEST::get('target_id'))) {
    //  $form_state['edit-bar-id-0-target-id'] = REQUEST::get('target_id');
    //}
    /* @var $entity \Drupal\my_module\Entity\Foo */
    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;
    return $form;
  }
}

```

I'm not familiar enough with the structure of the `$form_state` or best practices on `get()` to be comfortable testing this.

# Answer
> 0 votes
After adding dependency injection of a requestStack, this works.

```
/**
 * @var Symfony\Component\HttpFoundation\RequestStack
 */
protected $requestStack;

/**
 * Constructor.
 *
 * @param Symfony\Component\HttpFoundation\RequestStack $request_stack
 */
public function __construct(RequestStack $request_stack) {
  $this->requestStack = $request_stack;
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container) {
  return new static(
    $container->get('request_stack')
  );
}

public function buildForm(array $form, FormStateInterface $form_state)
  /* @var $entity \Drupal\my_module\Entity\Foo */
  $target_id = $this->requestStack->getCurrentRequest()->query->get('target_id');
  $this->entity->set('bar_id', $target_id);
  $form = parent::buildForm($form, $form_state);
  $entity = $this->entity;

  return $form;
}

```

---
Tags: 8, forms, entities
---


# Question
Title: How do I programmatically add a new search page to the search page list?
I have been able to successfully create a search plugin for a custom module, which allows users to search for my custom entity by name. After creating this file, I have to enable it by visiting /admin/config/search/pages selecting my search type from the dropdown, and add it after specifying the target path. What is needed to do this within the module? I imagine I would have to create a route somewhere, and then associate this route with the search page list. Any advice on how to do it?

# Answer
After you've configured the plugin in UI, export the config and look for the configuration file `search.page.[search_plugin_id].yml`.

Remove the uuid and hash line and place the file in the directory `config/optional/` of the module.

You find examples in the core modules Node and User, see http://cgit.drupalcode.org/drupal/tree/core/modules/user/config/optional/search.page.user\_search.yml
> 1 votes

---
Tags: 8, routes, search, plugins
---


# Question
Title: Does anybody know how to add the remove button in a custom module (field type) with unlimited number of values?
I am trying to add my custom field/module to a content type. I select `Unlimited` for the `Allowed number of values` option in `Field Settings` and I am able to Add another Item, however there is no remove button. Furthermore, each time I edit the content; an extra (blank) field is added.

# Answer
The custom field type has to implement a method which tells whether the field is empty (if the inherited default method is not able to do this).

For example for a numeric field:

NumericItemBase::isEmpty()

```
  public function isEmpty() {
    if (empty($this->value) && (string) $this->value !== '0') {
      return TRUE;
    }
    return FALSE;
  }

```
> 0 votes

---
Tags: 8, nodes, entities
---


# Question
Title: Looking for a strategy to optimize a big body field on a node
I'm using Drupal 8.4.x

I have just one node with a big text on its body field (about 2.5 MB). Looking a strategy to optimize:

1. *Page load.* Does exist any "content lazy loading" module? (I can see one for D7 but without a stable release).
2. I'll like to create *revisions* on this node. I'm gonna use Diff module to see changes and also to enable visitors to see those changes. This a consuming task on a big node and not sure how to cache/optimize those Diffs.

*Note:* I've tought about spliting the content in different nodes (like a book) and then use something like Views Infinite Scroll but I'll find hard to implement 2 with this aproach.

# Answer
> 1 votes
Using the Paragraphs module is probably the current go-to solution for a more manageable setup than a large body field. Functionally, it's right in between a single text field and completely separate nodes. It enables you to create more manageable chunks of content that replace the traditional body field. Each chunk can be simple text, or more complex things. Each "paragraph" is an entity with fields, and the node references those entities. When editing, it feels like a more focused interface. The content creator stays on the node, so the complexity is hidden in the background.

Another strength it has is good support for revisions. In fact, it requires the Entity Reference Revisions module, and its project page suggests using the Diff module.

---
Tags: 8, nodes, entities, caching
---


# Question
Title: Display block on homepage depending on value in user profile field?
I'm currently displaying a block on my D7 site' homepage.

Now I've a requirement to display that block only if the logged in user has a specific value in their profile.

I know it can be done using php evaluation by navigating to the bottom of the block and then click (Pages \> Pages on which this PHP code returns TRUE ) but have no experience in writing php scripts.

Can anyone help with this please.

thanks

# Answer
You can do something like this

```
global $user;

 If($user->your_profile_field_value == 'requiredvalue') {
    Return true;
    }
    Else {
    Return false;
    }

```
> 0 votes

---
Tags: 7, blocks
---


title: View is not working the intended way

text:
# Question
Title: View is not working the intended way
I created a view and set it as in the following screenshots.

>

> \[

If (under the *Format* section) I select *Show:Content* or any other setting, I can see the view being displayed on page and on the preview like I want it to show; if I select *Show:Fields*, the view doesn't show on page, but it does show on the preview.

To clarify the *it shows on page* part:

* The theme is the right one
* The region is defined on that particular theme, and I can display content on that region besides the one I really want to show, which also dismisses block settings preventing it from showing

Why is this happening? What can I do to make the view show on page when selecting the *Show:Fields* option?

Since I am a Drupal beginner, I don't know if the issue is merely caused from a wrong value I set for one or more settings.

# Answer
> 0 votes
Sometimes a clear cache solves the issue. Don't know if yours is the same issue but it happened to me and i cleared cache and it resolved the issue.

---
Tags: views, nodes
---


# Question
Title: How to detect entity translation without using path prefix or domain?
We have a situation where we want to have Content Translation enabled. It is our understanding that this is using Entity Translation(from D7) that is now in D8 core. This also means that there will be one Node (ID), but there will be a table to hold translations for the fields.

Goal:

1. Enable Content Translation for Article content type and make all fields translatable
2. Create an English page call Test-Page
3. Click Translate and add translation to Spanish
4. Enter in the Spanish content for the body and title field

Expectation:

1. As a site visitor, When i clicked on the Language Switcher and select Spanish, I should see Spanish content
2. As a logged in user (admin or content editor) when i view the English version I should see English content on the edit screen for body and title
3. As a logged in user when editing the Spanish translation I should see the Spanish translations for body and title.

Issue:

1. Whenever we click on the Spanish translation we are always served up the English content
2. When i change the language using the Language Switcher to Spanish, we are still served up the English content

How can we setup the translations so that the issues above do not occur?

# Answer
> 0 votes
I am adding an answer so others can see what i had to do.

To resolve this we did the following:

1. Enabled the custom settings for language detection
2. Enabled "Selected Language"
3. Set "Selected Langauge" with the highest row weight so it is done first
4. Enabled "URL" with the second highest row weight
5. Modified Admin Content (/admin/content) view to output a customized URL that has "?language\_content\_entity="
6. Now on click of edit or translate of the that page, it will redirect to the correct language and all my issues are resolved.

---
Tags: 8, nodes, entities, i18n-l10n
---


# Question
Title: Drupal 8 Customize CKEditor Format Options
Drupal 8.4.x

I am trying to add custom formats to the ckeditor dropdown.

Having the Geshi Filter module installed it would be nice to have the tags associated with the different languages available as a format option for users.

Following a reply here: https://drupal.stackexchange.com/a/244331/79805, I have success adding the "div" tag, but seem unable to add anything else like a "css" tag or even a "span" tag.

Is it possible to add custom tags to the format list?

This is the function running right now from user @rémy:

```
function ckeditor_add_format_tags_editor_js_settings_alter(array &$settings) {

    foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
        if ($settings['editor']['formats'][$text_format_id]['editor'] === 'ckeditor') {
            $settings['editor']['formats'][$text_format_id]['editorSettings']['format_tags'] .= ";div";
        }
    }

}

```

# Answer
> 1 votes
CKEditor's format drop down is intended for block-level elements only. So e.g. for headlines, divs, blockquotes, paragraphs and so on.

Inline-elements as spans, links (in CKEditor inline elements by default, even HTML5 specs state they can wrap block elements), i, b, strong, em and so on will have to use the styles drop down.

The `css` tag is neither block nor inline element, and you'd have to define it as custom block element first.

You can let CKEditor know about your block-level elements by extending the dtd setting, but this exceeds the scope of the Drupal Answers group, even Drupal 8 is using CKEditor by default. Please refer to the CKEditor docs for more information.

For your very special use case, I do have a suggestion:

In one of our projects, we have been using the GeSHi filter module in conjunction with the codesnippet module and added a text filter module codesnippet\_geshifilter that "translates" codesnippet markup to GeSHi filter compatible markup.

The intention was to have JavaScript based syntax highlighting while editing the source code, but render pages with server-side generated GeSHi highlighting.

It works well for code blocks. There are some flaws with inline code however. These require tweaking the available CKEditor styles drop down.

---
Tags: 8, wysiwyg
---


# Question
Title: Can menuTree load a menu's items including children
From what I understand I should be able to retrieve all the items in a menu using menuTree. However I only get one level/depth no matter what I try.

My Menu Looks Like:

> Imported Content
> --Products
> ----A Child
> ------Grand Child
> --------Great Grandchild
> ------Grand Child 2
> ----Child 2
> --A Sibling

**Menu structure** (screenshot): https://www.evernote.com/l/AAKdnwekb7BM87AFANo1z2XjCdEvR8HgDEI

This is my code:

```
  $menu_name = 'imported-content-menu';
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
  $parameters->setMaxDepth(100);
  $parameters->setMinDepth(0);
  $tree = $menu_tree->load($menu_name, $parameters);

```

When I inspect **$tree**, it is an array of two items **"Products"** and **"A Sibling"**.

I inspected these two items to see if there were nested items (the children) but there were not.

The **"Products"** item has **'hasChildren'** set to **TRUE**. But I don't see those children.

# Answer
> 4 votes
Within the typical route context (`$menu_tree->getCurrentRouteMenuTreeParameters($menu_name)`), subtree elements are loaded only, if the menu item is flagged as "Show as expanded" within the menu item settings.

To load the entire tree, you have to pass in a plain MenuTreeParameters object without the current route context:

```
use Drupal\Core\Menu\MenuTreeParameters;

$parameters = new MenuTreeParameters();

// Optionally limit to enabled items.
$parameters->onlyEnabledLinks();

// Optionally set active trail.
$menu_active_trail = \Drupal::service('menu.active_trail')->getActiveTrailIds($menu_name);
$parameters->setActiveTrail($menu_active_trail);

// Load the tree.
$tree = \Drupal::menuTree()->load($menu_name, $parameters);

```

---
Tags: navigation
---


# Question
Title: Views query alter for specific node/content type
My idea are instead of update the views name to the custom code one by one. I like to apply to same content type, but I don't know the syntax.

```
 function myModule_views_query_alter(&$view, &$query)

   if(($view->name == '?????????'){

}

```

I would get the node/content type "myArticle" for node table as following code

```
$content_type = $wrapper->type->value();

```

but how can I update `$view->name` to `$views->node->type` ? I try `print_r` the `$view` but not fully understand the syntax to access the field. Not sure if I went in the wrong direction. Please advise.

# Answer
If You only want to display data for specific roles to specific persons then you can use Global php in views to filter your results, Just take "User: Roles (Roles)" in your field as excluded and use its token in Global PHP field.example

```
if([roles] == "admin"){print [your_field_token_name];}
elseif([roles] == "your_roles"){print [your_field_token_name];}

```

You have to download the module of viewsphp to use global php.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Views Rest Export and sending page numbers in it's response
I have a paginated views using "rest export" and I'm using it to show that data on mobile app, everything works fine, but I want to know how many pages exist on that endpoint to show page numbers in my app.

I know I can alter the view programmatically, but I'm asking if there is a simple solution to achieve this.

This is the view settings page.

# Answer
As of now there is no way to display total page count in views rest export. But you can get **total pages, current page, items per page and total number of items** using new custom style in your custom module which extends existing `Serializer` class as shown below:

```
<?php

namespace Drupal\custom_module\Plugin\views\style;

use Drupal\rest\Plugin\views\style\Serializer;

/**
 * The style plugin for serialized output formats.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "custom_serializer",
 *   title = @Translation("Custom serializer"),
 *   help = @Translation("Serializes views row data and pager using the Serializer component."),
 *   display_types = {"data"}
 * )
 */
class CustomSerializer extends Serializer {

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];
    // If the Data Entity row plugin is used, this will be an array of entities
    // which will pass through Serializer to one of the registered Normalizers,
    // which will transform it to arrays/scalars. If the Data field row plugin
    // is used, $rows will not contain objects and will pass directly to the
    // Encoder.
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[] = $this->view->rowPlugin->render($row);
    }
    unset($this->view->row_index);

    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }

    $pager = $this->view->pager;
    $class = get_class($pager);
    $current_page = $pager->getCurrentPage();
    $items_per_page = $pager->getItemsPerPage();
    $total_items = $pager->getTotalItems();
    $total_pages = 0;
    if(!in_array($class, ['Drupal\views\Plugin\views\pager\None', 'Drupal\views\Plugin\views\pager\Some'])){
      $total_pages = $pager->getPagerTotal();
    }

    $result = [
      'rows' => $rows,
      'pager' => [
        'current_page' => $current_page,
        'total_items' => $total_items,
        'total_pages' => $total_pages,
        'items_per_page' => $items_per_page,
      ],
    ];
    return $this->serializer->serialize($result, $content_type, ['views_style_plugin' => $this]);
  }

}

```

After adding above file clear drupal cache and edit the view. There you need to change the format from `Serializer` to `Custom serializer`.

In this style there is a little difference in the output. All rows are children of `rows` and pager information is part of `pager`. Sample output is as shown below:

```
{
   "rows":[
      {
         "title":"Test"
      },
      {
         "title":"Test"
      },
      {
         "title":"Title 5"
      },
      {
         "title":"Title 4"
      },
      {
         "title":"Title 3"
      }
   ],
   "pager":{
      "current_page":0,
      "total_items":6,
      "total_pages":2,
      "items_per_page":5
   }
}

```
> 8 votes

---
Tags: views, 8, paging
---


title: static sql WHERE into dynamic

text:
# Question
Title: static sql WHERE into dynamic
I have this sql segment:

`WHERE MONTH(pd.field_publish_date_value) = MONTH(CURRENT_TIMESTAMP) AND YEAR(pd.field_publish_date_value) = YEAR(CURRENT_TIMESTAMP) AND fd.langcode='sk' AND fd.type='article'`

I need to transform it into something like this:

```
->condition(MONTH(pd.field_publish_date_value), MONTH(CURRENT_TIMESTAMP), '=')
->condition(YEAR(pd.field_publish_date_value), YEAR(CURRENT_TIMESTAMP), '=')
->condition(fd.langcode, 'sk', '=')
->condition(fd.type, 'article', '=');

```

but, how to interpret MONTH() and YEAR() functions in D8? Google offered me only Drupal 7 `->where()` \- I need to make it with `->condition()`.

\[EDIT\]

```
$sqlSK = "SELECT COUNT(fd.nid)
    FROM node fd
    LEFT JOIN node__field_publish_date pd
    ON fd.nid=pd.entity_id
    WHERE MONTH(pd.field_publish_date_value) = MONTH(CURRENT_TIMESTAMP) AND
    YEAR(pd.field_publish_date_value) = YEAR(CURRENT_TIMESTAMP) AND
    fd.langcode='sk' AND fd.type='article'
";

```

Thanks.

# Answer
> 1 votes
With a `Connection` object (`\Drupal::service('database')` or `@database` with DI).

```
$database = \Drupal::service('database');
$database->select('node_field_data', 'fd');
$database->join('table','pd', 'pd.XXX=fd.XXX'); //trying to match your query
$database->where('MONTH(pd.field_publish_date_value = MONTH(CURRENT_TIMESTAMP)');
$database->condition('fd.langcode', 'sk')
$database->condition('fd.type', 'article');
$result = $database->execute();
//do something
$result->fetchAll();

```

---
Tags: database
---


title: Add image css field in content type

text:
# Question
Title: Add image css field in content type
I want to add an image css field in one of my content types. Drupal provides an "alt" and an "title" field for the image, but now I need to add a css field too.

Im using the image on a view, and I know I can add css there, but I want to be able to add special css for single images.

Is there a module or something, which makes it possible to add an css field in my content type? thanks.

# Answer
You might want to take a look at Field Formatter Class module which allows to add a CSS class to any field in `Content Type -> Manage Display`.

Of course, first you must implement your CSS class in your CSS file, then add it to the image field through `Manage Display`. Do not forget to clear the cache to get the results shown.

**EDIT:** I didn't notice you want your CSS style to be applied individually. Perhaps adding a new field for CSS class, then adding it to Field Formatter Class through Token module. Not sure whether this is feasible or not.
> 0 votes

---
Tags: theming, media
---


title: Views contextual filter

text:
# Question
Title: Views contextual filter
I really would need some help with contextual filter.

I have a content type I use for products, different kind of security cabinets. In this particulary case it is aboyt burglary safes. They have a classification of 0,1,2,3,4,5, S1 or S2. So all burglary safes has one of these classes. To give them the class I have created a Vocabulary with the name "Burglary Classes" and there I have created the classes 0,1,2,3,4,5, S1 or S2 as terms.

In Views I have made a block with a table presenting all burglary safes, containg fields like dimensons and weight and so on and have brought in this table block to the Content type, as a field, and it works just fine.

Now to my question; All products in the Content type are not burglary safes so some are not classified according to 0,1,2,3,4,5, S1 or S2 , but I can't firgure out how to configure the Contextual filter.

I want ALL safes classifed to ANY of the terms 0,1,2,3,4,5, S1 or S2 to appear in ALL of the nodes having ANY of the terms 0,1,2,3,4,5, S1 or S2 but NOT to appear in any other node

The best shot I have had is filtering so that in the node only products belonging to the same Burglary Class as the node itself, appears. But as said, I want all products with a burglary class to appear.

Greatful for your help

Hans

(On request I have tagged the question for Drupal 7! Sorry for forgetting)

# Answer
Have you looked at the PHP filter module? I believe you could make two views, one which displays the burglary safe items and one which displays the non-burglary safes. Add both blocks to all pages, then use the filter module with a PHP expression to decide which to make visible and which invisible.
> 0 votes

---
Tags: 7, views
---


title: How does "cache dates" work?

text:
# Question
Title: How does "cache dates" work?
Having a hard time finding documentation explaining in any depth how date caching works in Drupal 7. Adding a date field to a content type allows a checkbox option that says "Cache dates: Date objects can be created and cached as date fields are loaded, rather than when they are displayed, to improve performance." In what scenarios is it a good idea to select this option? How does it improve performance?

# Answer
> 0 votes
Found this 5 year old comment in the issue thread that gives some more context. Not sure why the enhanced help text didn't make it into the 7.x module, but it helped me make the decision. https://www.drupal.org/project/date/issues/1358790#comment-6327490

> In order to display a date, a date object is created. Creating and caching date objects at the time date field data is entered may improve performance. For single-value, non-repeating, date fields caching will be neutral or have a performance benefit. For multiple-value or repeating dates with a large number of values, caching may negatively impact performance as some date objects that are cached may never actually be required.

---
Tags: 7, caching, datetime
---


# Question
Title: How to modify the value of a taxonomy field of a node using hook_node_view()?
I'm using Drupal 8 and I have a taxonomy field in a content type. I have created a node and added the term reference value to this node. Now the node shows up the link to the term.

I want to show value of the text field added in that taxonomy instead of link to the term.

I want to use this hook and set the value of the term field via code.

```
function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) { }

```

# Answer
You don't have to use the node view hook. It can be achieved using a taxonomy display as well.

Here is how to do it:

* Navigate to "Administration / Structure / Display modes / View modes"
* Scroll down to "Taxonomy term"
* Add a new Taxonomy term view mode by clicking the according link and giving it a name
* Now head to the display settings of your Taxonomy at "Administration / Structure / Taxonomy / \[Your vocabulary\] / Manage display"
* Find the "Custom display settings" tab, tick your newly created view mode and save
* A new tab with the name of your view mode will appear, where you can just add the field you like to display and disable all others; save again
* Head to the manage display settings of your content type that features the entity reference field to this taxonomy at "Administration / Structure / Content types / \[Your content type\] / Manage display"
* Find your entity reference field and switch "Format" to "Rendered entity"
* Using the cogwheel at the very right, you can now choose your above created view mode for how to render the referenced taxonomy entity

Save and you have the rendered field of your taxonomy shown at the node page.

PS.: The above procedure can be used for many other referenced entities as well and does not require any custom programming.
> 1 votes

# Answer
What I was trying to do is that change the entire value of the term field (field\_tax) with the field value of a field (field\_tax\_text). But I am not able to do that.

The max I could change is the value of 'field\_tax\_text', but for that I have to render the value of term field 'field\_tax' as rendered entity instead of link to term in display settings of content type.

I have done by two ways programmatically

1st Way:

function template\_preprocess\_node(&$variables) {
$variables\['elements'\]\['field\_tax'\]\[0\]\["#taxonomy\_term"\]-\>set('field\_tax\_text','new value');
}

2nd Way:

function module\_node\_view(array &$build,\Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view\_mode) {
if ($entity-\>getType() === 'page') {

```
  $entity->get('field_tax')->referencedEntities()[0]->set('field_tax_text', 'new value');
}

```

}

But instead of doing all this I would go with @Mario Steinitz solution
> 0 votes

---
Tags: 8, taxonomy-terms, hooks
---


# Question
Title: Get language path prefix code as contexual filter parameter
In Drupal 7, I have a block that shows recent posts which created with views.

I want it to show the translated posts of each language when I click the language switcher to switch the language.

I have two language prefixes (url code):
'en' and 'fa'
mysite.com/en
mysite.com/fa

I set in a contexual filter of that block view to show just the nodes of the specific language by raw value from url set to 1, but it considers the next value of language code as the first parameter.

What should I do to make Drupal consider the language code as the first value?

# Answer
> 1 votes
In Views with i18n there is also a filter available for that matter:

> Content: Language

You can set this to 'Current user's language' in order to filter your content based on the selected language.

# Answer
> 1 votes
You can have access to the prefix code of the current language as:

```
global $language;
$prefix_code = $language->prefix;

```

# Answer
> 0 votes
I made it with that function *(in your "Content: language" contextual filter -\> provide default value -\> PhP code)* :

```
$uri = explode('/', request_uri());
switch($uri[1]) {
    case 'en':
        return 'en';
        break;
    default :
        return 'fr';
        break;
}

```

Obviously, adapt it your languages ; for my part, french is the default *(no prefix)* state and english is my only other language.

---
Tags: 7, blocks, views, i18n-l10n
---


# Question
Title: How can I add a class to a title of a view?
I'd like to add a class to the title (H1) of a view, so that a specific style could be applied. This is Drupal 6 with a Zen subtheme.

Thanks

# Answer
> 3 votes
If you're using Views 3, you should be able to click on Style Settings on the field, Customize field HTML. From there, you can set `H1` as the HTML element or click on "Create a CSS class" to add a class.

# Answer
> 1 votes
* Go to Theme Information in your view.
* Copy the code for the entire view in the top level template.
* Create a file named after the most specific suggestion with this code inside in your theme's template folder.
* Add your class to the `H1` element.
* Style to your heart's content in your theme's CSS.

# Answer
> 0 votes
In the view rewrite the output of title as

```
<div class="H1">[title]</div>

```

then u can do the styling properties for this H1 in your CSS file easily.

# Answer
> 0 votes
Simply you can do with

```
<div id="my_custom_class">my title</div>

```

another way need to overwrite template files of that view

---
Tags: views, 6, theming
---


# Question
Title: How to alter the CartBlock build result?
I'd like to alter the cart block links (replace Cart link by a checkout link).

CartBlock.php is a BlockBase but neither hook\_block\_build\_alter nor hook\_block\_view\_alter is called :-( (same result with a specific block hook like hook\_block\_view\_BASE\_BLOCK\_ID\_alter or hook\_block\_build\_BASE\_BLOCK\_ID\_alter with id "commerce\_cart" )

https://api.drupal.org/api/drupal/core!modules!block!block.api.php/funct...

https://api.drupal.org/api/drupal/core%21modules%21block%21block.api.php...

Do I have to use a views hook ? which one ? and how to access to the block render array to change the links at the bottom of the cart block ?

Thanks

# Answer
I'm not sure that it is the best way to do it but I successed using hook

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook\_preprocess\_HOOK/8.2.x

```
YOUR_MODULE_preprocess_block(&$variables)

```

==\> to identify the block :

```
$variables["elements"]["#configuration"]["id"] == "commerce_cart"

```

==\> to change the links with customs :

```
$variables['content']['#links']=$custom_links;

```
> 0 votes

---
Tags: commerce
---


title: Creating a Rule for email recipients

text:
# Question
Title: Creating a Rule for email recipients
I am working on a site that has a registration form (created with Webform) for 4 different conferences.

The registration goes to everyone on the list (there are 8 people on the email list). But we just added another conference that should only go to 3 people in particular.

Is there a way, to write a rule (we have custom ruleset module) to have the registration email for a particular conference go to a specific person? I am working on Drupal 7.

Any suggestions would be greatly appreciated.

# Answer
There doesn't seem to be a "custom ruleset" module on Drupal.org, but I'd simply use the Rules module, together with the Webform Rules module, as further explained below.

### Step 1 - Create a basic eMail about the submitted Webform

Have a look at this example rule (in Rules export format):

```
{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "form-id" ], "value" : "2" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occured",
          "message" : "A new webform submission has occured (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Some details about the above rule:

* Rules Event: After a webform has been submitted
* Rules Conditions:
    + Form-id has value "`2`" (change to whatever form-id to fit your case).
    + User submitting the form is logged in.
* Rules Action: Sent an eMail.

Not sure if it is the case for you, but if the user who submitted the form is authenticated (not anonymous), then you do already have access to a limited set of tokens related to the user who submitted the webform, such as `[user:id]`, `[user:name]` and `[user:mail]`. If the user is anonymous, just omit that condition, and don't refer to those tokens in the eMail being created.

### Step 2 - Include data from the submitted Webform data in your eMail

You do have access to all ***labels*** and all ***values*** of any field of a Webform, ie:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name MachineFieldName.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name MachineFieldName

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

* the *1st attempt* relates to using "Entity has field" (which doesn't work for Webform).
* the *2nd attempt* explains what to do in case of Webform.

And while the above is a good start, it may still not be sufficient to achieve your goal. I.e. if you want to use specific data from the submitted webform. However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

* Add an extra Rules Action to `Add a variable`, with a value assigned to it equal to your `[data:SomeField-value-raw]` (and with an appropriate data type). I'm assuming a field in your webform has a machine name like `SomeField` (adapt to fit your machine name).
* In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).

### Step 3 - Cover all possible variations of the Webform data

To make this work for each of the 4 (or 5?) conferences, you basically have 2 options:

* Duplicate this rule for each possible form id (or form component value if all conferences are covered via a single form) you want to process this way. E.g 1 such rule for each conference.
* Use the Conditional Rules module if you want to have a single (consolidated) rule for all conferences to be processed.

Here is an example rule (in Rules export format), which uses the Conditional Rules module:

```
{ "rules_process_submitted_webform_based_on_a_component_value" : {
    "LABEL" : "Process submitted webform based on a component value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "form-id" ], "value" : "2" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:somefield-value-raw]" },
          "PROVIDE" : { "variable_added" : { "submitted_form_component_value" : "Submitted form component value" } }
        }
      },
      { "SWITCH" : {
          "USING" : { "data" : [ "submitted-form-component-value" ] },
          "DO" : [
            { "CASE" : {
                "USING" : { "value" : "1" },
                "DO" : [ { "drupal_message" : { "message" : "Webform Option 1 was selected" } } ]
              }
            },
            { "CASE" : {
                "USING" : { "value" : "2" },
                "DO" : [ { "drupal_message" : { "message" : "Webform Option 2 was selected" } } ]
              }
            },
            { "CASE" : {
                "USING" : { "value" : "3" },
                "DO" : [ { "drupal_message" : { "message" : "Webform Option 3 was selected" } } ]
              }
            },
            { "DEFAULT CASE" : [
                { "drupal_message" : { "message" : "Webform Option selected was different from 1, 2 and 3" } }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

Some details about the above rule:

* Rules Event: After a webform has been submitted
* Rules Condition: Form-id has value "`2`" (change to whatever form-id to fit your case).
* Rules Actions:

+ Add an extra Rules Action to `Add a variable`, with a value assigned to it equal to your `[data:SomeField-value-raw]` (and with an appropriate data type). I'm assuming a field in your webform has a machine name like `SomeField` (adapt to fit your machine name).
    + Show a message on the site (depending on the value of the variable that was added via the prior Rules Action).

What is left to do to further tune the above Rules example to fit your needs:

* Replace the "Show a message on a site" by an appropriate eMail to be created (for each "*case*").
* And for each of those eMails just indicate which eMail Ids should receive that eMail.

***Voilà***

PS: forget about your "custom ruleset module", no more need for it to solve this challenge.
> 2 votes

---
Tags: 7, rules, webforms
---


title: Hide child pages from menu tree

text:
# Question
Title: Hide child pages from menu tree
Hopefully some wise Drupal guru will be able to help me with this one.

I'm using menu and menu block to output a side menu in Drupal 7. Using Panelizer, on a basic page I can customize display and add a view pane (Case study: Teaser), which will display a list of case study teasers:

I can add a case study content type, which provides a menu link. The problem is over time there will likely be hundreds of case studies, and it will look unwieldly to have hundrens of children/sub-pages in the menu.

I could list the links and disable them from the menu (and also keep the breadcrumb path):

However, various admin and editors will be using this, so ideally I'd like some functionality whereby sub-pages do not appeaer in the menu when a Case Study content type is used, but the breadcrumb path is still shown:

If anyone could point me in the right direction, I'd be eternally grateful :)

# Answer
If you don't need the case studies to appear in the secondary nav/sidebar menu, you could try using the Path Breadcrumbs module to set custom rules for any of the following scenarios:

* all "Case Study" content resides in a fixed hierarchy
* "Case Study" content with a specific tag goes in a fixed hierarchy
* "Case Study" content breadcrumbs are defined by url alias/path that reflects parent pages.

The module is rather flexible in the rulesets you can define.
> 0 votes

---
Tags: navigation, breadcrumbs
---