title: How do I add a new group permission?

text:
# Question
Title: How do I add a new group permission?
How to add new group permissions? describes how add new group permissions when using the Drupal 7 version of the module.

```
function [mymodule]_group_permission() {
  return array(
    'schedule publishing of nodes' => array(
      'title' => t('Schedule content publication'),
      'description' => t('Allows users to set a start and end time for content publication'),
    ),
    'view scheduled content' => array(
      'title' => t('View scheduled content list'),
      'description' => t('Allows users to see all content which is scheduled.'),
    ),
  );
}

```

This does not appear to be the case in Drupal 8.
How can I add my own custom permissions to the group permissions screen, in Drupal 8?

# Answer
I found the answer to this question here: https://www.drupal.org/project/group/issues/2959912

Create a .yml file, for example: my\_module.group.permissions.yml

It should contain:

```
access group menu edit:
  title: 'Edit group menu'
  description: 'Allow users to edit the group menu'

```

First line is the permission itself. I did this. Flushed cache, and my permissions now appear in Group module permissions screen under "My Module".
> 2 votes

---
Tags: group
---


# Question
Title: Custom module javascript Drupal.behaviours doesn't seems to load
I have a custom module which has a javascript file. Here's the content of the javascript file:

```
(function ($, Drupal) {
    Drupal.behaviors.promotionalOverlayBlock = {
        attach: function(context, settings) {
            console.log("hello world")
        }
    };
})(jQuery, Drupal);

```

The location of javascript file:

```
mymodule/js/overlayblock.js

```

In my `mymodule.libraries.yml` file it has the following:

```
mymodule:
  js:
    js/overlayblock.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupalSettings

```

When I load my drupal page, I expecting to see the "hello world" in the browser console. However, nothing show up. I view the page html code and search for my javascript there, but I can't seems to find anything related to my javascript file.

What could be the problem here?

Here's how I attached my library through the hook\_preprocess\_block() I'm not sure if this is the right place to add the attached.

```
function mymodule_preprocess_block(&variables){
  $variables['#attached']['library'][] =
  'mymodule/overlayblock';
}

```

# Answer
When attached make sure to use the correct name of the "library"

Inside your `mymodule.libraries.yml` file. **The first line is your library name**.

I use a different name inside my library file, and I attached a wrong library name.

```
 function mymodule_preprocess_block(&variables){
     $variables['#attached']['library'][] =
      'mymodule/mylibraryname';
 }

```

My library file mymodule.libraries.yml

```
mylibraryname:
  js:
    js/promotional-overlay-block.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupalSettings

```
> 3 votes

# Answer
In Case if your library called mymodule, then attached shoud be as i described below

```
function mytheme_preprocess_block(&$variables) {
  if ($variables['elements']['#id'] == 'myblock') {
    $variables['#attached']['library'][] = 'module_name/mymodule';
  }
}

```
> 2 votes

---
Tags: 8, theming, javascript
---


# Question
Title: Get Username from UID with Preprocess for Template
I'm a bit lost at finding the username based on the uid. I get the uid from the address using:

```
  $current_path = \Drupal::service('path.current')->getPath();
  $urluid = (explode("/",$current_path));

  $us = \Drupal::entityTypeManager()->getStorage('user')
  ->loadByProperties(['uid' => $urluid[2]]);

  kint($us);

```

returns an array of data where i do see the uid, but not the username for that uid. Name:

```
'name' => array(1)
*DEPTH TOO GREAT*

```

returns NULL:

```
kint($us->name);

```

I'd like to return the UID-\>Name as the title on the ROLES and EDIT screens for the user. Exactly how it is returned for VIEW (example dvweb is: /user/10):

EDIT:::

Was able to get it with:

```
  $u = Drupal\user\Entity\User::load($urluid[2]);
    kint($u->getUsername());

```

# Answer
It's better to use the route instead of the path, where you'll find the already loaded user entity:

```
if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {
  $user = \Drupal::routeMatch()->getParameter('user');
  $username = $user->getUsername();
}

```
> 1 votes

---
Tags: 8, users
---


# Question
Title: What to do in a case of plugin ID not found?
I'm fairly new to Drupal, the inside settings are quite easily to understand for me but when it gets to error fixing I'm kind getting stuck sometimes.

For a project I've installed the Open Social platform as my Drupal, which is working fine but a couple bugs and things for me to find out. I wanted a file browser as a Knowledge Base into my site so I've installed the FileBrowser module.

Now when I want to specify (open social) group rights to a file browser node, so only that group can look into this file browser, I get the following error and I cannot seem to find out where to solve it:

```
Uncaught PHP Exception Drupal\\Component\\Plugin\\Exception\\PluginNotFoundException: Plugin ID 'group_node:dir_listing' was not found.

```

Could anyone point me into the right direction?

# Answer
It looks like the error is coming from a missing plugin provided by the group\_node module, which if I recall ships with the Group module. Try re-downloading that module to your codebase, and clearing your cache. If that doesn't work, uninstall the group\_node module.
> 0 votes

---
Tags: 8
---


title: How to create Dynamic Routes

text:
# Question
Title: How to create Dynamic Routes
I have been trying to create dynamic routes by using RouteSubscriberBase class.

I know we can create dynamic routes by using slug parameter in the URL. Similar to this method ( https://befused.com/drupal/dynamic-route ).

But I want is dynamic Routes not URLs.Similar to this method ( https://www.previousnext.com.au/blog/dynamic-routes-drupal-8-routesubscriber )

Here is the code I have written so far but I cant get whats missing in the code.

When I try to access http://example.com/custom-module/dynamic-routes/ it is available but when I try to access http://example.com/custom-module/dynamic-routes/tents I am getting Page not found Error.

I have Cleared cache before accessing the new URL.

**DynamicRoutesAlter.php**

```
<?php

namespace Drupal\custom_module\Routing;

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

/**
 * DynamicRoutesAlter Class.
 */
class DynamicRoutesAlter extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

   $products = ['cooking_gear' => 'Cooking Gear', 'tents' => 'Tents' , 'sleeping_bags' => 'Sleeping Bags','rope' => 'Rope', 'safety' => 'Safety','packs' => 'Packs'];

    foreach ($products as $key => $value) {

      $url = preg_replace('/_/', '-', $key);

      $route = new Route(
        // The url path to match.
        '/custom-module/dynamic-routes/' . $url,
        // The defaults (see the custom_module.dynamic_routes for structure)
        [
          '_title' => $value,
          '_controller' => '\Drupal\custom_module\Controller\DynamicRoutesController::productType',
          'type' => $key, //Not sure what type does ? Is it required? I have seen it as the syntax in the book Mastering Drupal 8 By Chaz Chumley, William Hurley
        ],
        // The requirements.
        [
          '_permission' => 'create ' . $value,
        ]
      );

      // Add our route to the collection with a unique key.
      $collection->add('custom_module.dynamic_routes'. $key, $route);

    }
  }

}

```

**custom\_module.services.yml**

```
services:
  custom_module.dynamic_routes:
    class: Drupal\custom_module\Routing\DynamicRoutesAlter
    tags:
      - { name: event_subscriber }

```

**custom\_module.routing.yml**

```
custom_module.dynamic_routes:
  path: '/custom-module/dynamic-routes'
  defaults:
    _title: 'Dynamic Routes'
    _controller: '\Drupal\custom_module\Controller\DynamicRoutesController::productType'
  requirements:
    _permission: 'access content'

```

**DynamicRoutesController.php**

```
  /**
   * {@inheritdoc}
   */
  public function productType() {

    $build['results'] = [
      '#markup' => $this->t('Controller to get Products List.'),
    ];

    return $build;
  }

```

# Answer
# DynamicRoutesAlter.php

## Problem #1 - preg\_replace() without pattern

```
$url = preg_replace('_', '-', $key);

```

The `$url` will be always `NULL`, because you are using `preg_replace()` without regexp, use instead `str_replace()` or write appropriate regexp pattern: `'/_/'`.

### Solution #1

```
$url = preg_replace('/_/', '-', $key);

```

### Solution #2

```
$url = str_replace('_', '-', $key);

```

## Problem #2 - wrong variable mixing

```
$collection->add('custom_module.dynamic_routes'.{$key}, $route);

```

You are wrong with mixing variable and string. You want to concatenate it with the curly syntax. This is also incorrect.

### Solution #1

```
$collection->add("custom_module.dynamic_routes.{$key}", $route);

```

### Solution #2

```
$collection->add('custom_module.dynamic_routes' . $key, $route);

```

After you fix those problems, your code will work.

I'm also not sure about `'type' => $key,`, why is that here? There is nothing about `type` route param.

P.s. as you mentioned itself, better use slugs.

# UPD - all files

Check your files for mistakes.

**custom\_module.info.yml**

```
name: Custom module
type: module
description: For https://drupal.stackexchange.com/questions/281728
package: Custom
core: 8.x

```

**custom\_module.routing.yml**

```
custom_module.dynamic_routes:
  path: '/custom-module/dynamic-routes'
  defaults:
    _title: 'Dynamic Routes'
    _controller: '\Drupal\custom_module\Controller\DynamicRoutesController::productType'
  requirements:
    _permission: 'access content'

```

**custom\_module.services.yml**

```
services:
  custom_module.dynamic_routes:
    class: Drupal\custom_module\Routing\DynamicRoutesAlter
    tags:
      - { name: event_subscriber }

```

**src/Controller/DynamicRoutesController.php**

```
<?php

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Returns responses for Custom module routes.
 */
class DynamicRoutesController extends ControllerBase {

  /**
   * Builds response for dynamic routes.
   */
  public function productType() {

    $build['results'] = [
      '#markup' => $this->t('Controller to get Products List.'),
    ];

    return $build;
  }

}

```

**src/Routing/DynamicRoutesAlter.php**

```
<?php

namespace Drupal\custom_module\Routing;

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

/**
 * DynamicRoutesAlter Class.
 */
class DynamicRoutesAlter extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    $products = ['cooking_gear' => 'Cooking Gear', 'tents' => 'Tents' , 'sleeping_bags' => 'Sleeping Bags','rope' => 'Rope', 'safety' => 'Safety','packs' => 'Packs'];

    foreach ($products as $key => $value) {

      $url = preg_replace('/_/', '-', $key);

      $route = new Route(
      // The url path to match.
        '/custom-module/dynamic-routes/' . $url,
        // The defaults (see the custom_module.dynamic_routes for structure)
        [
          '_title' => $value,
          '_controller' => '\Drupal\custom_module\Controller\DynamicRoutesController::productType',
          'type' => $key,
        ],
        // The requirements.
        [
          '_permission' => 'create ' . $value,
        ]
      );

      // Add our route to the collection with a unique key.
      $collection->add('custom_module.dynamic_routes' . $key, $route);

    }
  }

}

```
> 1 votes

---
Tags: 8, routes, services
---


# Question
Title: How to get token of parent entity in paragraph?
I have a paragraph, which is referenced by a node. Now I am trying to pass field values of node to the paragraph using tokens. I'm only aware of `[paragraph:parent_id]` and `[paragraph:parent_type]` but don't know how to get specific field values.

What I've tried so far without success:
`[node:field_foo:value]`
`[paragraph:field_foo:value]`
`[paragraph:node:field_foo:value]`
`[paragraph:parent:field_foo:value]`
`[paragraph:parent:entity:field_foo:value]`

The list of available tokens does not contain parent tokens. Is it even possible to get token of the parent entity? And if so, how?

# Answer
> 9 votes
There's nothing out of the box (see this issue for the details). Implementing your own token isn't too tricky.

I haven't had a chance to test this but I'm pretty sure it'll work:

```
function MODULE_token_info_alter(&$info) {
  $info['tokens']['paragraph']['parent_entity'] = [
    'name' => 'Parent entity',
    'description' => 'Parent entity of the paragraph',
  ];
}

function MODULE_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'paragraph' && $paragraph = $data['paragraph']) {
    $parent = $paragraph->getParentEntity();
    $bubbleable_metadata->addCacheableDependency($parent);

    foreach ($tokens as $name => $original) {
      if ($name == 'parent_entity') {
        $replacements[$original] = $parent->label();
      }
    }

    $token_service = \Drupal::token();
    if ($parent_entity_tokens = $token_service->findWithPrefix($tokens, 'parent_entity')) {
      $replacements += $token_service->generate($parent->getEntityTypeId(), $parent_entity_tokens, [$parent->getEntityTypeId() => $parent], $options, $bubbleable_metadata);
    }
  }

  return $replacements;
}

```

# Answer
> 4 votes
So with the newest version of Drupal 8 and Paragraphs, this is possible.

Looking at the tokens on `/admin/help/token`, there is a `[paragraph:parent_entity]` under the paragraphs section which is exactly what you need.

Example use case: to get the title of the parent node, I used `[paragraph:parent_entity:title]`.

---
Tags: 8, tokens, paragraphs
---


# Question
Title: Unable to access translated node content
After performing a Drupal core update on my site today I've found that I can no longer access translated content. When I try to view or edit the translation, I only see the default language content.

I created a short GIF you can view here:

via GIPHY

As you can see, I'm editing the node for Canada and the US translation is showing instead. Translations were working fine with Drupal 8.6.2 but began to do this in 8.6.3. I have now done the following with no success:

* Updated to the latest Drupal core 8.7.2
* Updated all installed modules
* Created a new Drupal site with 8.6.3 and 8.7.2, but this issue does not exist
* Disabled Workbench moderation for a given content type, but that doesn't fix the issue

I'm really not sure where and or how to troubleshoot this issue. Where would you start?

I'm thinking I could start by uninstalling modules to see which is possibly causing the issues. I'm not sure if that is the right approach given that this issue began when I updated the Drupal core, not the modules.

Thank you for any feedback!

# Answer
Turns out this issue was due to my settings on the Detection and selection page at /admin/config/regional/language/detection. I reordered **URL** to be above **User** and the translations are now showing.

Hopefully, this is able to help someone else in the future.
> 0 votes

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


# Question
Title: How to insert line breaks in views global custom text field?
My view renders plaint text output - no HTML allowed. I want to format my fields with `\n` line breaks. How do I do that?

# Answer
> 0 votes
With HTML not allowed, you don't allow line breaks. You would need a `<br />` element to render a line break, otherwise it will be one big paragraph

If you have it set up the way you want, and all you want to do is add the `/n` to the output of a field:

* Add a Global Custom Text field (make sure it is below the field you want to add the /n to).
* Insert the token under Replacement Patterns for the applicable field.
* In the text box, add the `/n` after the token.

# Answer
> 0 votes
You could just run the text through nl2br(); Then your line breaks should convert to HTML ones.

`echo nl2br($val);`

https://www.php.net/manual/en/function.nl2br.php

---
Tags: views
---


# Question
Title: Issue with taxonomy term search in Views
I have a View that uses "Search Terms" to search nodes of the content type "Products". I added a new taxonomy term field to the Product nodes, and then added that field to the View. When I use the View to search for a taxonomy term, though, the it is not returning the nodes that have that term.

Is there a better way to handle this search or something obvious that I am doing wrong?

Here is the code for the view:

```
$view = new view();
$view->name = 'search';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Search';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Search';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* No results behavior: Global: Unfiltered text */
$handler->display->display_options['empty']['area_text_custom']['id'] = 'area_text_custom';
$handler->display->display_options['empty']['area_text_custom']['table'] = 'views';
$handler->display->display_options['empty']['area_text_custom']['field'] = 'area_text_custom';
$handler->display->display_options['empty']['area_text_custom']['empty'] = TRUE;
$handler->display->display_options['empty']['area_text_custom']['content'] = '<h3>Sorry, no results found. Please modify your search.</h3>';
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image_cache']['id'] = 'field_image_cache';
$handler->display->display_options['fields']['field_image_cache']['table'] = 'field_data_field_image_cache';
$handler->display->display_options['fields']['field_image_cache']['field'] = 'field_image_cache';
$handler->display->display_options['fields']['field_image_cache']['label'] = '';
$handler->display->display_options['fields']['field_image_cache']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image_cache']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image_cache']['settings'] = array(
  'image_style' => 'thumbnail',
  'image_link' => 'content',
);
$handler->display->display_options['fields']['field_image_cache']['delta_limit'] = '1';
$handler->display->display_options['fields']['field_image_cache']['delta_offset'] = '0';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Product: SKU */
$handler->display->display_options['fields']['model']['id'] = 'model';
$handler->display->display_options['fields']['model']['table'] = 'uc_products';
$handler->display->display_options['fields']['model']['field'] = 'model';
$handler->display->display_options['fields']['model']['label'] = '';
$handler->display->display_options['fields']['model']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['model']['alter']['text'] = '~ [model] ';
$handler->display->display_options['fields']['model']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['model']['link_to_node'] = TRUE;
/* Field: Field: Description */
$handler->display->display_options['fields']['field_description']['id'] = 'field_description';
$handler->display->display_options['fields']['field_description']['table'] = 'field_data_field_description';
$handler->display->display_options['fields']['field_description']['field'] = 'field_description';
$handler->display->display_options['fields']['field_description']['label'] = '';
$handler->display->display_options['fields']['field_description']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['field_description']['alter']['text'] = '[field_description]';
$handler->display->display_options['fields']['field_description']['alter']['max_length'] = '150';
$handler->display->display_options['fields']['field_description']['alter']['trim'] = TRUE;
$handler->display->display_options['fields']['field_description']['element_label_colon'] = FALSE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['label'] = '';
$handler->display->display_options['fields']['nid']['exclude'] = TRUE;
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = '';
$handler->display->display_options['fields']['nothing']['alter']['text'] = 'View Details';
$handler->display->display_options['fields']['nothing']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['nothing']['alter']['path'] = '/node/[nid]/view';
$handler->display->display_options['fields']['nothing']['element_label_colon'] = FALSE;
/* Field: Content: All taxonomy terms */
$handler->display->display_options['fields']['term_node_tid']['id'] = 'term_node_tid';
$handler->display->display_options['fields']['term_node_tid']['table'] = 'node';
$handler->display->display_options['fields']['term_node_tid']['field'] = 'term_node_tid';
$handler->display->display_options['fields']['term_node_tid']['label'] = '';
$handler->display->display_options['fields']['term_node_tid']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['term_node_tid']['type'] = 'ul';
$handler->display->display_options['fields']['term_node_tid']['link_to_taxonomy'] = FALSE;
$handler->display->display_options['fields']['term_node_tid']['limit'] = TRUE;
$handler->display->display_options['fields']['term_node_tid']['vocabularies'] = array(
  'product_tags' => 'product_tags',
  'blog_categories' => 0,
  'catalog' => 0,
  'vocabulary_2' => 0,
);
/* Field: Content: Product Tags */
$handler->display->display_options['fields']['field_product_tags']['id'] = 'field_product_tags';
$handler->display->display_options['fields']['field_product_tags']['table'] = 'field_data_field_product_tags';
$handler->display->display_options['fields']['field_product_tags']['field'] = 'field_product_tags';
$handler->display->display_options['fields']['field_product_tags']['label'] = '';
$handler->display->display_options['fields']['field_product_tags']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_product_tags']['type'] = 'taxonomy_term_reference_plain';
$handler->display->display_options['fields']['field_product_tags']['delta_offset'] = '0';
/* Sort criterion: Search: Score */
$handler->display->display_options['sorts']['score']['id'] = 'score';
$handler->display->display_options['sorts']['score']['table'] = 'search_index';
$handler->display->display_options['sorts']['score']['field'] = 'score';
$handler->display->display_options['sorts']['score']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Node: Is a product */
$handler->display->display_options['filters']['is_product']['id'] = 'is_product';
$handler->display->display_options['filters']['is_product']['table'] = 'uc_products';
$handler->display->display_options['filters']['is_product']['field'] = 'is_product';
$handler->display->display_options['filters']['is_product']['value'] = '1';
$handler->display->display_options['filters']['is_product']['group'] = 1;
/* Filter criterion: Search: Search Terms */
$handler->display->display_options['filters']['keys']['id'] = 'keys';
$handler->display->display_options['filters']['keys']['table'] = 'search_index';
$handler->display->display_options['filters']['keys']['field'] = 'keys';
$handler->display->display_options['filters']['keys']['group'] = 1;
$handler->display->display_options['filters']['keys']['exposed'] = TRUE;
$handler->display->display_options['filters']['keys']['expose']['operator_id'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['label'] = 'Search Terms';
$handler->display->display_options['filters']['keys']['expose']['operator'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['identifier'] = 'keys';
$handler->display->display_options['filters']['keys']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  9 => 0,
  8 => 0,
  3 => 0,
  7 => 0,
  6 => 0,
  4 => 0,
  5 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'product-search';

```

# Answer
The "Search terms" field isn't related to Taxonomy terms, it just denotes phrases you might enter into some search field and it searches through the indexed content. It isn't used so often unless you need generic keyword search.

If you want to add a Taxonomy term filter, try adding the `Content: Has taxonomy term` Filter and Expose it so users can choose terms directly. Choose `Dropdown` to see all the terms listed in the Exposed form instead of an autocomplete field where users have to type in the term themselves.

The module Better Exposed Filters can help you change the look of the Exposed filter form to see checkboxes next to terms instead of a list.

If you want to learn more about the "Search term" Filter try reading here: How To Create Search Pages Using Views In Drupal 7 although that's probably not what you're after.

BTW although views details show everything seeing a screenshot of the Views configuration is much easier and faster to read ;)
> 0 votes

---
Tags: views, search
---


# Question
Title: Get node data from entity reference field
I have an entity reference field to a content type blog. I referenced a specific blog, but when I render that field in twig using `{{ content.field_blog }}`. I want to get the autor name and time when that blog was created - not the blog's name by default. Field is in paragraph. I would like to do this using twig, so without any preprocesses.

How can I do that?

# Answer
You should be able to get the author like this:

```
{{ paragraph.field_blog.entity.Owner.name.value }}

```

and the creation:

```
{{ paragraph.field_blog.entity.createdtime|format_date('medium') }}

```
> 1 votes

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


# Question
Title: How to apply a patch file in composer to a submodule of a module?
I've added the patch to composer.json like this:

```
  "drupal/admin_toolbar_tools": {
    "Bring back media to dropdown menu": "https://www.drupal.org/files/issues/2019-01-16/admin_toolbar-media_link-3026216-3-option2-D8.patch"
  }

```

However, *admin\_toolbar\_tools* is a sub-module of *admin\_toolbar* (admin\_toolbar/admin\_toolbar\_tools).

I ran `composer install`, but it doesn't trigger the patch apply process.

The patch I am trying to apply is the following one (https://www.drupal.org/files/issues/2019-01-26/admin\_toolbar-media-link-3026216-8-option3.patch).

```
diff --git a/admin_toolbar_tools/admin_toolbar_tools.module b/admin_toolbar_tools/admin_toolbar_tools.module
index 9ac389c..1f8a36b 100644
--- a/admin_toolbar_tools/admin_toolbar_tools.module
+++ b/admin_toolbar_tools/admin_toolbar_tools.module
@@ -621,20 +621,23 @@ function admin_toolbar_tools_menu_links_discovered_alter(&$links) {

   // If module Media enabled.
   if ($moduleHandler->moduleExists('media')) {
-    $links['admin_toolbar_tools.add_media'] = [
-      'title' => t('Add media'),
-      'provider' => 'admin_toolbar_tools',
-      'route_name' => 'entity.media.add_page',
-      'menu_name' => 'admin',
-      'parent' => 'system.admin_content',
-    ];
+    // Displays media link in toolbar.
+    if (in_array('entity.media.collection', $routes)) {
+      $links['admin_toolbar_tools.media_add_page'] = [
+        'title' => t('Add media'),
+        'provider' => 'admin_toolbar_tools',
+        'route_name' => 'entity.media.add_page',
+        'menu_name' => 'admin',
+        'parent' => 'system.admin_content',
+      ];
+    }
     // Add node links for each media type.
     foreach ($entityTypeManager->getStorage('media_type')->loadMultiple() as $type) {
       $links['media.add.' . $type->id()] = [
         'title' => t($type->label()),
         'provider' => 'admin_toolbar_tools',
         'route_name' => 'entity.media.add_form',
-        'parent' => 'admin_toolbar_tools.add_media',
+        'parent' => 'admin_toolbar_tools.media_add_page',
         'route_parameters' => ['media_type' => $type->id()],
       ];
     }

```

# Answer
Use `admin_toolbar`.

```
"drupal/admin_toolbar": {
  "Bring back media to dropdown menu": "https://www.drupal.org/files/issues/2019-01-16/admin_toolbar-media_link-3026216-3-option2-D8.patch"
}

```

Then run `composer update` or `composer update --lock` if you want to apply your new patch and do not want to update any packages.
> 1 votes

---
Tags: 8, version-control
---


# Question
Title: Available options to implement a knowledge base or FAQ repository?
I just started with Drupal 7 in an enterprise environment. It's running on IIS7 with MySql as the backend.

I'd like to see this Drupal site host a Knowledge Base or FAQ repository. I did some searches for modules and I haven't found any popular solution.

Ideally, as software/product 'issues' arise and solutions are documented, I want the issue and solution to be easily entered and searched by a small (\<100) developer and help desk community.

Any suggestions about how to accomplish this? I'm still getting a grasp on the taxonomy, maybe proper use of taxonomy is all thats really needed?

# Answer
> 6 votes
# Ticketing system

Implement a ticketing system, using the Support module. Popular/great module, to the extend that you can live/agree with the design / assumptions / etc of this module. Definitely worth considering to "get started". Here is a list of features (from its project page):

> * Ticketing activity is illustrated with colorful charts (depends on the Chart API module).
> * Tickets can be assigned to users (and users can view all tickets assigned to them).
> * Tickets support states (new, active, pending, closed, etc) and priorities (low, normal, high, critical, etc).
> * Configurable email notifications for new and updated tickets.
> * Email integration allows tickets to be created and updated via email, with support for attachments. New users can be automatically created. Ticket properties can be updated via email (using included support\_mailcmd module).
> * Highly configurable client and user ticket overviews, highlighting tickets that haven't been updated for a long time.
> * Fully integrated with Drupal's search functionality, users can only search for tickets they have access to.
> * Supports an unlimited number of clients, each with their own configuration and access permissions.
> * Tickets are nodes, ticket updates are comments.

# Wiki system

Implement a **wiki system**, using modules such as these ones (excerpts are from their project pages):

* Wikitools:

> ... provides some settings to get a more wiki-like behavior. It aims to be lightweight; all features are optional, and it provides no database tables of its own.
>
> Some of the features of this module are:
>
> + **Node Creation**: Let users create new nodes when they type in a node name which does not exist.
>     + Node Search: Let users search for nodes when they type in a node name which does not exist.
>     + **Automatic Redirect**: If a title of a moved page is entered, redirect automatically.
>     + **Unique Titles**: Enforce that titles are unique over all wiki node types.
>     + **Move Protection**: Disallow change of node titles for users without administer nodes permission.
>     + **Underscore as Space**: Treat underscores as spaces when doing a node-lookup by title.
>     + **Dash as Space**: Treat dashes as spaces when doing a node-lookup by title.
>     + **Custom wiki 404 pages**: pick and choose from links to create, links to search, and an inline node add form.
>
> The module can be used in conjunction with the flexifilter module (of course), the freelinking module by hijacking freelinking links, or together with the pearwiki filter module for various wiki formats.
* Freelinking:

> ... implements a filter framework for easier creation of HTML links to other pages on the site or to external sites.
>
> The framework uses a wiki style format such as \[\[indicator:target\]\] as markup to identify links.

The video about Setting Up a Wiki in Drupal 7 contains an interesting introduction to the modules mentioned above (and some other modules you might also want to consider for this purpose).

There is also the Wiki installation profile (either just use that profile, are review it to get inspiration about possibilities). Excerpt from its project page:

> ... will set up Drupal with the following settings:
>
> * Moderator role which can revert / delete pages.
> * Revisions for pages.
> * Freelinking - easier creation of HTML links to new or existing pages.
> * Edit a section of a page (based on header).
> * Mediawiki input format.
> * Categorization via free tagging vocabulary.
> * Views: All pages / All categories / All Images.
> * Recent changes.

# Questions & Answer site

Implement a questions & answers site (similar to "Drupal Answers" here ...), using the Answers module (Disclosure: I'm a co-maintainer of it), for which a Demo site is available.

To experience it yourself, here are the steps to try it out:

* Head over to this sandbox site.
* Just accept the defaults to create a sandbox demo site (hit the create sandbox button, and wait for the process to complete).
* Login to the site (using the suggested defaults).
* Create at least 1 question using either the "*Add content*" menu link and then selecting "Question", or just enter relative path `/node/add/question`. And complete the title and body of the question.
* After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
* If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
* Use the ***Questions*** tab (or enter relative path `/questions`, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

**Note**: you may also want to enable the ***Answers Theme*** (sub-module of Answers, new as of 7.x-4.x). After you do, return to the question you created before, and see how the look-and-feel of both the question and related answer(s) below it changed ... Here is a sample screenprint of it:

# Groups of users

If your target audience consists of multiple groups of users, then you might want to use the Organic Groups module also.

A great resource for learning about Organic Groups is the (free) video training about Learn Organic groups, a set of 14 videos.

As an alternative you may want to consider the Group module, which only exists as of D7, but already has a pretty stable D8 version also.

# Roll your own cookies

After you become more familiar/experienced with Drupal, you could just build your own custom solution. With only site building techniques (using contributed modules), you could probably get pretty far. E.g. using modules such as the Frequently Asked Questions module.

However, I you want more flexibility and (way) more facilities that can be perfectly tuned to your specific needs, then you should consider using modules such as:

# Answer
> 0 votes
Old discussion but I feel the need to chime in because a lot of the things mentioned here are still relevant

The above response has some great suggestions if you want a ticketing or wiki section. Unfortunately, they don't answer the actual question because an FAQ/knowledgebase is not like either of those things.

There is an FAQ module that is mature and well used/tested. If you just want an FAQ that is worth looking at. But once you accumulate enough info, where you need to start categorizing it, you will want to move to a knowledge base.

You are right that there aren't any obvious answers for that one, still. I think the best is to do it using existing modules/features. More work but more customizable and adaptable. I have looked around and that seems to be what most people suggest. Unfortunately, I have not found any how to guides. So you are on your own and there is definitely a learning curve.

Here is the best discussion of it that I could find. Kind of old but still relevant imo. The OP mentions the modules they used at the very end of that discussion. Taxonomy (built in) with parent child hierarchy, taxonomy\_menu and taxonomy\_menu\_trails modules.

https://www.drupal.org/forum/support/post-installation/2013-07-23/best-way-to-build-a-knowledgebase-style-with-drupal

You can start here for how to structure your taxonomy terms in D7. I don't think it is too much different in D8.

https://www.drupal.org/docs/7/organizing-content-with-taxonomies/about-taxonomies

---
Tags: 7
---


title: Raw Field Value in Views

text:
# Question
Title: Raw Field Value in Views
We have a content type that has a Video Embed Field. In this field, we simply enter youtube or Vimeo url.

In a custom view we are trying to display the raw value of the field. Since this is a Video Embed Field, the only formatter in Views are to display the video or a thumbnail of it.

The problem is that we want to display just the raw value of this field which will be the video url.

Are there any workarounds that will allow us to display the raw value of this field when added in a view?

# Answer
> 1 votes
Different Field information can be displayed in Views by using the **`Rewrite results`** and `Replacement patterns` options in the Field configuration.

Different Field data is usually available as tokens (replacement patterns) that can be used to construct a different output than those available under the Formatter option.

Here's an example for displaying the image Alt text instead of the actual image:

It works similarly for the Video field, and many others too.

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


# Question
Title: How to generate my own patches to update core for security when fuerstnet.de's "Drupal upgrade the easy way" page is out of date?
For Drupal 7, under the current host I'm using (which doesn't provide things like drush), I've found that **patching** is the easiest approach to updating core. However, the commonly-referenced page which provides the .patch files for doing this ("Drupal upgrade the easy way") has not updated for 7.67, which contains a security-fix.

Rather than go back to the old way of doing things by following all the steps found within UPGRADE.txt, what process can I use to generate a patch for upgrading my own site?

# Answer
Per https://www.computerminds.co.uk/articles/quickly-update-drupal-core, Github itself can create patch-files for you. You can use commandline `curl` or `wget` to download the appropriate patch easily:

```
curl 'https://github.com/drupal/drupal/compare/7.66..7.67.patch' > "drupal-7.66-to-7.67.patch"

```

Alternatively, you can download the tar'd (or zipped) packages for both your current version of Drupal and the target and recursively diff them as described here, resulting in a functionally-identical patch-file.

This can then be tested out in the normal way:

```
patch -p1 --dry-run < "drupal-7.66-to-7.67.patch"

```

And then applied if no hunks failed:

```
patch -p1 < "drupal-7.66-to-7.67.patch"

```

Note of course that just because patching succeeded, it doesn't mean the successfully-applied patch hasn't broken your site in some way, so be sure to back up everything (files and Drupal database) before patching, trying this first on your dev site, running tests, etc. before repeating the process for real in production.

## Gotcha!

If you've upgraded using fuerstnet.de before, ***Drupal may falsely continue showing security-update warnings***, because at least one package with `$file->info['project']=='drupal'` and `$project['project_type']=='core'` will still be considered out of date. That's because some of your .info files may contain extra lines which override standard version-numbers:

```
; Information added by Drupal.org packaging script on 2019-04-17
version = "7.66"
project = "drupal"
datestamp = "1555533576"

```

Based off of experience, generating your own patch as described above ***will not*** remove this information, since it is not present in the vanilla packages, and the files containing these extra lines won't necessarily fail to patch either, if no changes to the vanilla editions' code occurred in the last update. (Common because .info files don't change very often.)

These extra lines need to be removed (or *adjusted*, if you prefer) before Drupal will stop complaining that you're behind on core updates, even though you're actually up-to-date.
> 1 votes

---
Tags: 7, updating, security, version-control
---


# Question
Title: Webform 8 - How can I make a text field value be A if a select value is 1?
In Webform 8 I am trying to figure out how to populate a text field with a value based on what is chosen on a drop down.

For example: Select Value are states If user selects Deleware then the value for the text field Ratified is equal to 1.

How can I achieve this in Webform 8x?

In Webform 7x I am able to do this with the Conditionals tab but can't seem to be able to figure out how to do this in Webform 8.

# Answer
> 2 votes
You have to use JS, go to settings - CSS/JS tab, write code in CUSTOM JAVASCRIPT textarea.

Some code for reference. I got a text input (id is edit-name), a select (id is edit-gender), the id you find enter 'F12' to see. ID is automatically generated by Webform. When I select male, the text input will appear male.

```
(function ($, Drupal) {'use strict';$(document).ready(function(){
  'use strict';
  var name = $("#edit-name");
  var gender = $("#edit-gender");
  var duty = $("#edit-duty-select");
  function ab() {if (gender.val()==='male'){name.val("male");} else {name.val("girl")}};
  gender.change(ab);  // add a Listener to select
});
})(jQuery, Drupal);

```

---
Tags: webforms
---


# Question
Title: How to check if a password reset token is still valid?
Is there a way to hook into the `user_pass_reset` form to detect if the provided hash is valid? Currently it seems to just throw a 403 error when submitting the form if the hash has already been used to change the password.

Using `hook_form_alter()`, I can retrieve the hash itself with `explode("/",$form['#action'])[5]`, but am unsure how to check if it's already been used or not, or if it's expired. I see that this information might be part of the `UserController` class, but I'm not sure how to retrieve that.

# Answer
Welp, I probably should have gotten the idea to follow where the form action actually takes you and see what its controller does. I pulled the timestamp and hash from the form action with the explode function, loaded the user object from the currentUser id, and used `Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp));`.
> 1 votes

---
Tags: 8, users
---


# Question
Title: Migration of field_collection with migration_d2d
In D7 to D7 migrations, when it comes to field\_collections I know “ Your field collection migration should be run after the host entity migration. ”.

I have done my host entity migration via the migrate\_d2d module.

For my field\_collection I have written a custom module and added migrate\_d2d class name (7f4f1882cNodecook\_committee\_vote) as a dependency.

Has this logic flowed?

I ask because my field\_collection migration does not update the previously migrated cook\_committee\_vote nodes, rather it makes empty stubs for them!!!

# Answer
The answer is: the logic is not flowed, it is correct. when you write your own custom migration module you can establish dependencies to other migrations that you have done via code or done via UI using migrate\_ui or d2d\_migrate\_ui modules. here is custom migration code that depends on a class generated by d2d\_migrade\_ui. this code worked for me:

```
$this->description = t('casey will migrate this field cllection even if it kills him!!!!!!');
// class of prviously imported node, this class name was generated by d2d_migrate module
// that is why the name is diffrent
$this->dependencies = array('7f4f1882cNodeorg_vote');

$query = $this->getConnection()
// start with the field that embeds the field_collection
->select('field_data_field_org_member_votes', 'nodeField')
->fields('nodeField', array('entity_id', 'field_org_member_votes_value', 'delta'))
->groupBy('nodeField.field_org_member_votes_value')
->orderBy('nodeField.entity_id')
->orderBy('nodeField.delta');

// join it to the fields that make up the field_collection, in my case there were 3 fields
$query->leftJoin('field_data_field_org_votes_member', 'member',
'nodeField.field_org_member_votes_value = member.entity_id');
$query->addField('member', 'field_org_votes_member_nid');

$query->leftJoin('field_data_field_org_votes_vote', 'vote',
'nodeField.field_org_member_votes_value = vote.entity_id');
$query->addField('vote', 'field_org_votes_vote_value');

$query->leftJoin('field_data_field_org_votes_majority', 'majority',
'nodeField.field_org_member_votes_value = majority.entity_id');
$query->addField('majority', 'field_org_votes_majority_value');

$this->source = new MigrateSourceSQL($query);

$this->destination = new MigrateDestinationFieldCollection(
    'field_org_member_votes',
    array('host_entity_type' => 'node')
);

$this->map = new MigrateSQLMap($this->machineName,
    array(
        'field_org_member_votes_value' => array(
            'type' => 'int',
            'not null' => TRUE,
            'description' => 'Unique ID for each commitee vote',
            'alias' => 'nodeField',
    )
  ),
  MigrateDestinationFieldCollection::getKeySchema()
); //map END

$this->addFieldMapping('host_entity_id', 'entity_id') ->sourceMigration('7f4f1882cNodeorg_committee_vote');

$this->addFieldMapping('field_org_votes_member', 'field_org_votes_member') ->sourceMigration('7f4f1882cNodemember');
$this->addFieldMapping('field_org_votes_member:source_type') ->defaultValue('nid');

$this->addFieldMapping('field_org_votes_vote', 'field_org_votes_vote');

$this->addFieldMapping('field_org_votes_majority', 'field_org_votes_majority');

}//construct END

 function prepareRow($row) {
   // this is a good wat to test and make sure
   // A) you have connected to the db
   // B) you are getting proper values from your query
   // drush_print_r($row);
 }//prepareRow END
 function complete($row) {
   // drush_print_r($row);
 }
 public function prependTextNotes($row) {
     return 'Imported notes: ' . $row;
 }//prependTextNotes   END

 }

```
> 0 votes

---
Tags: 7, migrations
---


title: Custom code doesn't work

text:
# Question
Title: Custom code doesn't work
i tried to add some code to my theme, following this: How do I include JavaScript on a single page in a way that is amenable to scale

i created my js file in: C:\xampp\htdocs\drupal-8.7.2\themes\bootstrap\js

i put this on the file:

```
        (function ($) {
         Drupal.behaviors.[myName] =  {
        attach: function(context, settings) {

          //Begin my code
          alert("'.$phpvariable.'");
         //I'm done with my code

        }
      };
    })(jQuery);

```

so i opened the file bootstrap.libraries.yml and putted this:

```
my-library:
  js:
    js/my-script.js: {}

```

after that i put on the file bootstrap.info.yml this:

```
type: theme
base theme: false

name: 'Bootstrap'
description: 'Built to use Bootstrap, a sleek, intuitive, and powerful front-end framework for faster and easier web development.'
package: 'Bootstrap'

core: 8.x
libraries:
 - my-theme/global-effects
 - bootstrap/js/my-library

```

now...nothing work and i not understand why....can anyone help me?

# Answer
> 1 votes
There are a few items worth mentioning here.

* The first is that you'll want to avoid making modifications to existing modules and themes. For your use case, it would be better to create a new theme of your own and use Bootstrap as the base theme. Here is a good link to get you started: https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme. Bootstrap is somewhat advanced, so it might be better to practice first using Classy as your base theme.
* As sdmeyers pointed out, YAML formatting is very important. If you have a script named `my-script.js` that lives in the `/js` folder in your theme, then your libraries YAML file will look like this:

```
my_module.my_cool_library:
  js:
    js/my-script.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

```

Take note also of the dependencies, which are necessary in order to use Drupal behaviors. Also note that, in YAML files, every indent is exactly 2 spaces (and no tabs!).

For your use case, your PHP would look like this:

```
$form['#attached']['library'][] = 'my_module/my_module.my_cool_library';
$form['#attached']['drupalSettings']['my_module'] = [
  'print_this' => 'Hello World!',
];

```

And your JS would look like this:

```
(function ($, undefined) {
  'use strict';
  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      $('body').once('my-module').each(function () {
        const print_me = settings.my_module.print_this;
        alert(print_me);
        // Success!
      });
    }
  }
})(jQuery);

```
* Any time you make changes to your theme, you'll need to clear your site's cache. You can do so by visiting Configuration \> Performance, or from the console with `drush cr` (this requires that Drush is installed) or `drupal cache:rebuild all` (this requires that Drupal Console is installed).

---

I strongly recommend building your own theme in order to practice. A minimal theme only needs a few files. Here's a good step-by-step introduction: https://www.lullabot.com/articles/drupal-8-theming-fundamentals-part-1

As for the PHP code, it's a snippet that you would attach to other code. For demonstration's sake, add this hook to your `.theme` file:

```
/**
 * Implements hook_form_alter().
 */
function MY_THEME_form_alter(&$form, &$form_state, $form_id) {
  // Attaches this functionality to any form on your site.
  // This probably isn't what you actually want to do, but is a good demonstration.
  // Don't forget to clear your site cache!
  $form['#attached']['library'][] = 'my_module/my_module.my_cool_library';
  $form['#attached']['drupalSettings']['my_module'] = [
    'print_this' => 'Hello World!',
  ];
}

```

Be sure to change the **MY\_THEME** part for the actual name of your theme. So, if your theme is named 'practice', then your hook would be `practice_form_alter()`.

Hooks are an absolutely essentially part of theme building, so be sure to understand how they work: https://api.drupal.org/api/drupal/core%21core.api.php/group/hooks/8.7.x

And as always: Don't forget to clear your site cache!

---
Tags: javascript
---


# Question
Title: Creating a displayable 'index' of content nodes within a path
Ok, it's been over a decade since I've worked with Drupal (primary use was for a personal blogging platform, with a bit of extra extensibility and a well developed plugin ecosystem). Sadly, most of my knowledge has escaped me, so I'm starting completely from scratch knowledge wise, and I don't know where to start.

**Summary**

I'm going to use Drupal as the platform to deliver an intranet for a small company I work for.

In order to make navigation as simple as possible, and without having to worry about themes and menus constantly - I'd like to have pages where it displays an automatically generated 'table of contents' for all the documents or items on one or more levels below it.

**Explanation**

I intend to structure and alias the content with a URL alias similar to directories in a file system, for example:

Marketing
⌊\_ eCommerce
⌊\_ Search Advertising
⌊\_ Google
⌊\_ Facebook
⌊\_ Product Maintenance
Administration
⌊\_ Vehicles
⌊\_ Accounting and Finance
and so on

On the homepage, I would like to have a content block or something appropriate in the body, which displays only the L1 directories (i.e. Marketing, Administration), and that is then linked to their relevant pages (i.e. domain.com/marketing, domain.com/administration).

From there, the home pages for these L1 areas have an index that traverses and lists everything automatically at L2, L3 and so on

I hope what i'm trying to achieve has made sense, and appreciate all and any help to point me in the right direction for achieving this.

# Answer
Basically, what you need to do is the following:

* Create a new vocabulary (taxonomy module)
* Insert your structure as you listed above (MArketing...etc)
* Add "entity reference" field to your content type
* Use "views" to create list the content in "table". Make sure to use the right filters
* Some other modules might help with the interface like menu taxonomy

You can find very good training courses for Drupal on Drupalize.me and Build a Module
> 2 votes

---
Tags: nodes
---


# Question
Title: How to restrict/provide access to particular entities of some ENTITY_TYPE to users which has email listed as field value?
I have a entity type Products with multiple entities in it. I want to give View, Edit, Delete Access of each entity to users only whose Emails are listed under field\_user\_email. I want to restrict access to rest of the users, whose Email-id is not listed under field\_user\_email field.

# Answer
This is a generic question, so my answer will be generic too.

First, inserting email addresses of users to grant permissions is not a standard Drupal way, you have to have an entity reference pointing to the users.

If you are using Drupal 7 you can use flexi access

For Drupal 8 you can find a previously answered question here
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Encrypt images before node saving and decrypt them when a node is viewed
I am searching for a way to encrypt images before saving them on server (private folder) and decrypt it when node is rendered for roles that have views permissions.

I found the Encrypted Files module, but it's not covered by Drupal’s security advisory policy.

I installed and configured both the available versions (1.x , 2.x). It seems files are encrypted successfully, but I can see the image when I view a node or in the image preview widget because it seems it can't be decrypted.

How can I use this module? Is there any video guidance? I searched Internet but I didn't find any useful video.

# Answer
Actually, I don't see the need to encrypt images as Private files will hide the images from direct access and will be served by Drupal.

You can find more about private files here

Encryption and decryption each time the node is viewed can have serious performance implications.

The only scenario that I would think of having encryption when there is a security concern of direct access to the server and then I will, for sure, not use PHP to do that for me as most Linux systems are providing encryption natively.

Can you share with us your requirements and scenario?
> 1 votes

---
Tags: files
---


# Question
Title: How to display article metadata in a custom div?
Metadata (publication date, author's name...) is normally displayed in the "Content" part between the "articles" tags. I have created a new region "titre d'article" in which I would like them to be displayed with the title of the article.

I was able to add the title block when the blocks were formatted. For metadata, I created a "Post metadata" view with a "custom text" field to display them.  But when I create a block with this view and add it to my region, it displays metadata for all published articles when it should display for the read-only article.   I don't know what I'm doing wrong. Yet I had already done it and it worked. I have to do it again because I'm going to lose the data from my old computer.

So basically, I want to hide or delete the default position of the metadata (that I can do easily) and display them in a custom div created using a region.

Please tell me if there's any mistake in what I did. Or if there's another way to do it more simply, I'd be delighted.

Thanks to help me

# Answer
> 0 votes
"Read-only" usually means a file or an item that cannot be changed/edited, you can only view it. I'm guessing what you actually mean is "current, the one being viewed right now".

You have to add a contextual filter to your Views that would filter the results to only the node you're currently viewing.

Here are the steps to configure Views to show only the current node's results:

1. Expand the `Advanced` area in your Views
2. Under `Contextual filters` click on `Add`
3. Add the **ID** filter from the `Content` Category and configure it: `When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Content**
**Article**
Hide View if the argument doesn't validate, or some other options that make sense to you.
4. Place the Block on article pages in your theme region (your have this already), adjust `Node from URL` and other Block options.

The Views Block will only show on article pages, and it will only display output related to the current node.

# Answer
> 0 votes
I think using views for displaying a part of node fields on the node page is not the best way to do it.

I would create a page template and a node template for Article content Type and display the needed fields there.

You can find more about Drupal 8 theming here

Also, training materials by Drupalize.me are fantastic. Let's do it the proper Drupal way.

---
Tags: views, theming
---


# Question
Title: How do I use Bootstrap theme's modal.jquery.ui.bridge's mapped events?
I am using a Bootstrap subtheme, and would like to trigger an event when a modal is closed.

Reviewing the main theme's `modal.jquery.ui.bridge.js` file, I see that the bridge is intending to map jQuery UI events (`beforeClose`, `close`) to framework events (`hide.bs.modal`, `hidden.bs.modal`).

I'm struggling with figuring out how to properly declare the `data-dialog-options` attribute of the triggering link to pass this event through the bridge.

In the JS file, `this.options.jQueryUiBridge` is true when `typeof options === 'object'`. My guess is that my `options` are not `typeof object`.

My attributes array on the Url object is

```
  $attributes = [
    'class' => ['use-ajax'],
    'data-dialog-type' => 'modal',
    'data-dialog-options' => Json::encode([
      'dialogClass' => 'modal-content--special-class',
      'beforeClose' => 'function() {console.log("closed");}',
    ]),
  ];

```

which results in the rendered link

```
<a href="/my-content-route" class="use-ajax" data-dialog-type="modal" data-dialog-options="{"dialogClass":"modal-content--space-wizard","beforeClose":"function() {console.log(\u0022closed\u0022);}"}">My Link Text</a>

```

What am I missing?

# Answer
> 2 votes
The technical reason it's not doing anything is that the value is retrieved as a string and not as a `Function` object.

You shouldn't pass anonymous functions in data attributes.

This would require whatever implements the callback (jQuery UI/Bootstrap) property to use `eval()` or some other sort of method to evaluate the callback.

This, of course, has major security implications and why it doesn't work.

All callbacks should be added via JavaScript.

If you don't have control over specific implementation, you can always set a global listening event and then use some sort of unique identifier on the modal to trigger a custom callback.

Example:

```
(function ($){
  var $document = $(document);

  // Create a custom beforeClose handler.
  var customBeforeCloseHandler = function (e) {
    console.log('closed');

    // Optionally, you should be able to stop it from closing
    // if that is the desired outcome by using the following:
    // e.preventDefault();
  };

  // jQuery UI Dialog Events.
  // @see http://api.jqueryui.com/dialog/#events
  $document.on('dialogbeforeclose', '.ui-dialog', function(e) {
    var $dialog = $(e.target);

    // Check if this dialog is ours.
    if ($dialog.is('.modal-content--special-class')) {
      // Proxy this event to our custom handler.
      customBeforeCloseHandler(e, ui);
    }
  });

  // Bootstrap Modal Events.
  // @see https://getbootstrap.com/docs/3.4/javascript/#modals-events
  $document.on('hide.bs.modal', '.modal', function (e) {
    var $modal = $(e.target);

    // Check if this modal is ours.
    if ($modal.find('.modal-content').is('.modal-content--special-class')) {
      // Proxy this event to our custom handler.
      customBeforeCloseHandler(e);
    }
  });

})(jQuery);

```

Given that the Drupal Bootstrap base theme has the jQuery UI Dialog bridge, I would recommend binding using jQuery UI Dialog events so it will work even without Bootstrap. That being said, if you can't seem to get that to work... using Bootstrap's events should work just as well.

However, don't use both as that would likely trigger your custom handler for both events.

---
Tags: 8, modal-dialogs, bootstrap-theme
---


title: Won't update taxonomy term

text:
# Question
Title: Won't update taxonomy term
I'm not really a Drupal guru, so any help it'd be awesome.

There's a taxonomy for every state (State Owner), which then allows me select the state when adding a new article.

However, I'm trying to add a National (NAT) to the list. I've added it to the taxonomy term list:

However, NAT won't show up on the State Owner field when adding a new article:

I can see the item on the DB too:

I've flushed the cache, even restarted the server... It just won't show up on the Add Article page (on the State Owner drop down).

Note that if I change the order of the states, it DOES change the order on the drop-down, so it's the correct taxonomy terms.

Any idea?

# Answer
> 0 votes
If anyone else lands here looking for an answer, after going around in circles for many many hours, I found out the solution.

When I gave up and was about to recreate a core component in order to overcome this issue, the first thing to do was to delete this taxonomy term, however, Drupal flagged to me that it'd affect the Access Scheme / Taxonomy Main. Interesting, so I decided to Google it, I found out this text came from a component called `Workbench Access`, which among other things could manage a Scheme for Taxonomy. Looking into installed modules, I indeed had it installed. Bingo. However, I had no access to it (that's why I never actually found it).

The old developer (which I no longer had access to), made me "Admin" of the system as part of his handover. However, this component was hidden for all users, but his.

After copying my hashed password, replacing his with mine, and logging in as him, I could see this component on his user homepage, which was just a matter of disabling it for State Owner and voilá. Working like a charm.

---
Tags: taxonomy-terms
---


title: Get Current Applied Image Style Name

text:
# Question
Title: Get Current Applied Image Style Name
How do you get the currently chosen image style name from the field format display option?

I can load an image with a given style with the code below, however, the style name (e.g. thumbnail) is hard-coded.

```
$imageStyle = \Drupal::entityTypeManager()
  ->getStorage('image_style')
  ->load('thumbnail');

```

I am hoping to get the selected style name dynamically.

**MYMODULE.module**:

```
HOOK_preprocess_menu() {

  $imagePath = getUser()['currentUser']->$imageFieldName
    ->entity->uri->value;

  $imageStyleFormatterValue = ???;

  $imageStyle = \Drupal::entityTypeManager()
    ->getStorage('image_style')
    ->load($imageStyleFormatterValue);

  $imageStyleURL = $imageStyle
    ->buildUrl($imagePath);

  $markup = new TranslatableMarkup(
    '<span style="background-image: url(@imageStyleURL);"></span>', [
      '@imageStyleURL' => $imageStyleURL,
    ]
  );

}

```

For my case, `$imageStyleURL` will be printed as `background-image: url();`, so I need to build the path in preprocess.

I've tried going through `FieldConfig`, `->entity`, and `FieldStorage`, but cannot find the image style value stored anywhere.

# Answer
> 0 votes
Field format display options are components of view modes, stored in the config entity `EntityViewDisplay`.

For example, load the `default` view mode for the user and extract the configured image style of the `user_picture` field:

```
use Drupal\Core\Entity\Entity\EntityViewDisplay;

  $component = EntityViewDisplay::load('user.user.default')->getComponent('user_picture');
  $image_style = $component['settings']['image_style'];

```

---
Tags: 8, hooks
---


# Question
Title: How to get all values from a new node being created in hook_ENTITY_TYPE_presave()
Drupal 8.7.2

```
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  data_dump($entity->original); //is empty because its a new node, not a node being updated.
  // How to get all values at one time?
  // By values I mean the same value you would get from:
  data_dump($entity->get('title')->value);
  // but from all fields and not just one field at a time.
}

```

I have a custom content type that has 30 custom fields that I need to examine inside this hook. I'd like to avoid getting the value of each field individually.

Thank you for your time.

# Answer
> 1 votes
There are probably a few different ways to get that info, but if the returned format suits your needs then `EntityInterface::toArray()`, which *Gets an array of all property values*, is probably the most succinct:

```
$field_data = $entity->toArray();

```

# Answer
> 0 votes
You can try use Content Entity Field definitions

Sample code:

```
foreach ($entity->getFieldDefinitions() as $field => $definition) {
    $entity->get($field)->getValue()
}

```

---
Tags: 8, hooks
---


# Question
Title: Views callback work only once with advanced form block
this code work but the views is callback only once (reload only once), any idea to reload more than one time ?

see in detail on drupal.org

```
function modulename_form_alter (&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'form_id_of_your_afb_form':
            $form['#validate'] = array();
            $form['ajax-submit']['#ajax']['callback'] = 'modulename_create_callback';
    }
}
function modulename_create_callback($form, &$form_state) {
    // load view
    $view1 = views_embed_view('view_name','view_display_name',$view_arguments_as_required);

    // replace the afb form with a clean form
    $newform = afb_ajax_handler($form, $form_state);
    $commands = array(
      ajax_command_replace('#target_div_id_of_view_to_update .view',$view1),
      ajax_command_replace('#target_div_id_of_afb_form_to_replace',render($newform)),
    );
    $form['#type'] = 'ajax';
    $form['#commands'] = $commands;
    return $form;
}

```

# Answer
> 1 votes
According to your description and code you have only one requirement that is **update views block on form submission**. So,

* You don't have to alter the form AJAX as AFB form submission already uses AJAX.
* Furthermore, you don't have to replace the form using ajax\_command\_replace() as its already replacing using AFB
* You don't have even to return the form as well.

**What do you need is to**

**So, use below code to get it worked.**

```
function MODULENAME_form_alter (&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'sport_node_form':
            if ($term = menu_get_object('taxonomy_term', 2)) $_SESSION['tid'] = $term->tid;
    }
}
function MODULENAME_ajax_render_alter(&$commands) {
    if(isset($_SESSION['tid']) && is_numeric($_SESSION['tid'])){
        $mavue_new = render(views_embed_view('mavue_new','default', $_SESSION['tid']));
        $commands[] = ajax_command_replace('.view-mavue-new', $mavue_new);
    }
}

```

I hope this would help someone else.

# Answer
> 1 votes
you just need to put the number of tid directly here :

```
ajax_command_replace('#target_div_id_of_view_to_update .view','1'),

```

---
Tags: 7, views, forms
---


# Question
Title: print data to twig file from custom form submit via controller
I have created a custom form, and I'm passing data to twig file from `submitForm` function as follows

```
public function submitForm(array &$form, FormStateInterface $form_state)
{
$form_state->setRebuild();

$data = ['role' => $form_state->getValue('role'),
'date' => $form_state->getValue('date')
];
MyController::Detail($data);

}

```

and in controller passing data to twig

```
public static function Detail($data) {

return [
'#theme' => 'my_report',
'#data' => $data,
];

}

```

but not able to get/print data in twig file.

# Answer
> 0 votes
When you set rebuild in a form submit there is no controller involved. The next page displayed is the rebuilt form, where you can print the my\_report twig template by adding it to the build array `$form`.

You don't need to transfer the values in $form\_state, because they are available while rebuilding the form. You can check in the form build function whether these values are present. If not, you are building a new form. If they are, this is a form rebuild, then display the result template:

```
  public function buildForm(array $form, FormStateInterface $form_state) {

    // build form

    if ($form_state->hasValue('role')) {
      $form['my_report'] = [
        '#theme' => 'my_report',
        '#role' => $form_state->getValue('role'),
      ];
    }
    return $form;
  }

```

---
Tags: 8, theming, forms
---


title: Managing custom theme translations file

text:
# Question
Title: Managing custom theme translations file
How to add a translation file to a custom theme?

I did

**my\_theme.info.yml**

```
'interface translation project': my_theme
'interface translation server pattern': themes/my_theme/translations/my_theme-%language.po

```

**twig template:**

```
 {% trans %}
  status
{% endtrans %}

{{ 'status'|t }}

```

**/my\_theme/translations/my\_theme-fr.po:**

```
msgid "status"
msgstr "statut"

msgid "statut"
msgstr "status"

```

followed by a

```
drush cr

```

The output is not translated when I am on the *fr* page (the default language being english).

# Answer
The .po file is not imported by being placed in the themes directory, you need to import it. To do that go here:

`Home > Administration > Configuration > Region and Language > Import`
> 1 votes

# Answer
Your implementation seems to follow the guidelines on the locale API documentation, but nevertheless, it wasn't working for me either.

What worked for me was implementing hook\_locale\_translation\_projects\_alter **on a module**:

```
function mymodule_locale_translation_projects_alter(&$projects) {
  $projects['my_theme'] = array(
    'info' => array(
      'interface translation server pattern' => 'themes/custom/my_theme/translations/my_theme-%language.po',
    ),
  );
}

```

I tested by enabling the module first, then enabling adding the language via drush command:

```
drush language-add fr

```

This is my PO file, Drupal seems to require a heading section:

```
# French translation of Drush Site-Install
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"POT-Creation-Date: 2018-10-11 16:30+0000\n"
"PO-Revision-Date: 2018-10-11 16:30+0000\n"
"Last-Translator: NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <EMAIL@ADDRESS>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

msgid "status"
msgstr "statut"

msgid "statut"
msgstr "status"

```

Without the header, it was skipping the first translation and I was getting this error:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /batch?id=14&op=do_nojs&op=do
StatusText: OK
ResponseText: Notice: Undefined offset: 1 in Drupal\Component\Gettext\PoHeader->parseHeader() (line 257 of /app/core/lib/Drupal/Component/Gettext/PoHeader.php). => Array ...

```
> 1 votes

# Answer
Thanks to what **@Cesar Moore** said and executing `drush locale:check` then `drush locale:update` and `drush cr`, my translation file is now working for my custom theme too :)

FYI : my PO file is in a custom module folder.

More refs :
> 0 votes

---
Tags: 8, theming, i18n-l10n
---


# Question
Title: How to get all the entity details which are using specific media?
I have a image "sample.jpg" (In media library) and I used this image in multiple custom blocks of different block types.

Now I need an information of all the custom blocks which are using "sample.jpg" image.

# Answer
> 0 votes
Thank you @Jdrupal, with reference to your answer I have updated 'block' to 'block\_content' and it is working fine.

```
        $blocks = \Drupal::entityTypeManager()
      ->getStorage('block_content')
      ->loadByProperties(['logo1' => $media_id_1, 'logo2' => $media_id_2]);

```

# Answer
> 1 votes
You can use the `entityTypeManager`, like this:

```
$blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(['field_media_1' => $media_id, 'field_media_2' => $media_id]);

```

Where $media\_id the the is of your media entity.

That will give you all the blocks that references that media entity.

---
Tags: 8, entities, media
---


# Question
Title: Override container.html.twig template for a specific context
I would like to override the container.html.twig template but the twig debugging tool doesn't give any suggestion.

I tried to add suggestion following https://drupal.stackexchange.com/a/249565/85029 answer but I end up with the suggestion being container----.html.twig.

The context is a display field with an embed view in a node.

I guess, the solution might be pretty close from what I have now (using the suggestion hook) but I'm not able to have some satisfying suggestion.

My current hook is

```
function mytheme_theme_suggestions_container_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#type']) && $element['#type'] == 'view') {
    $suggestions[] = 'container__' . $element['#name'];
    $suggestions[] = 'container__' . $element['#name'] . '__' . $element['#display_id'];
  }

  if (isset($element['#type']) && $element['#type'] == 'container' && isset($element['children']['#type'])) {
    $suggestions[] = 'container__' . $element['children']['#type'];
  }
}

```

Edit :

Ended up with something corresponding to my expectations by adding

```
if (isset($element[0]) && $element[0]["#theme"]) {
    foreach ($element[0]["#theme"] as $themElem) {
        $suggestions[] = 'container__' . $themElem;
        }
}

```

# Answer
I just did this a month ago for the same reason:

```
/**
 * Implements hook_theme_suggestions_container_alter().
 */
function mytheme_theme_suggestions_container_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#type']) && $element['#type'] == 'view') {
    $suggestions[] = 'container__' . $element['#name'];
    $suggestions[] = 'container__' . $element['#name'] . '__' . $element['#display_id'];
  }

  if (isset($element['#type']) && $element['#type'] == 'container' && isset($element['children']['#type'])) {
    $suggestions[] = 'container__' . $element['children']['#type'];
  }
}

```

This will work for Views and general types. It is coming up blank because you need to handle it a little differently depending on whats being rendered.

Then in my twig file I am just doing:

`{{ children }}`

because I didn't want wrapping divs.
> 13 votes

# Answer
Initially based on Kevin's code, the Template Suggest module now includes container template suggestions. An example of what it will provide for a view:

```
 FILE NAME SUGGESTIONS:
   * container--view--case-study--page-listing.html.twig
   * container--view--case-study.html.twig
   x container--view.html.twig
   * container--no-parent.html.twig
   * container.html.twig

```
> 2 votes

# Answer
Works for me:

```
/**
 * Implements hook_theme_suggestions_container_alter().
 */
function THEMENAME_theme_suggestions_container_alter(array &$suggestions, array $element)
{
    if (isset($element['element'][0]) && $element['element'][0]["#theme"]) {
        foreach ($element['element'][0]["#theme"] as $them_item) {
            $suggestions[] = 'container__' . $them_item;
        }
    }
}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: <form> and <input> tags in a text field of format Full HTML are not rendered in a field based view
In latest Drupal 8, I've got a text field of format Full HTML that contains `<form>` and `<input>` tags (It's a MailChimp subscribe snippet). As long as I am editing the text in CKEditor in the backend, the form is displayed correctly. But as soon as I view tha page in the frontend, both tags are stipped out. I checked my text format/CKEditor settings to see if tags are stripped out there, but "Limit Allowed HTML Tags" is unchecked. Does someone know what's happening here?

Edit: after checking out more, I realized that the text field is rendered inside a view (field based). When rendered as a node, the markup is perfectly rendered, just when rendered as a view, then the tags are stripped. I edited the question title to refelct this information. Any suggestions how to render the tags inside a view?

Edit 2: the text field is rewritten in views (added some wrapper tags).

# Answer
I confirmed on 8.7 that the following basic snippet is able to be used in Full HTML out of the box:

```
<form><input checked="checked" name="gender" type="radio" value="male" /> Male<br />
<input name="gender" type="radio" value="female" /> Female<br />
<input name="gender" type="radio" value="other" /> Other</form>

```

It's possible your particular snippet is being hit by the "Correct faulty and chopped off HTML" Format setting, so try it without that and see if it lets the code stay. Of course, this is not an ideal setting for a commonly used text format filter, so this snippet may be better off in a custom plugin block, or creating a new text format w/ the "Correct faulty and chopped off HTML" turned off, that can be used sparingly as needed.

UPDATE based on Views usage:

If you're using rewrite, it won't be possible out of the box to have it not strip tags, it's something baked into Views. You can override it at the theme layer - if for example you are using the `body` field, you create a `views-view-field--body.html.twig` file in your theme, and then put the desired wrapper tags around the `{{ output -}}`, e.g.:

```
<div class="foobar-wrapper">
{{ output -}}
</div>

```

And turn off rewrite in Views UI.
> 1 votes

---
Tags: 8
---


# Question
Title: Print multiple files field links, descriptions and file extensions in Twig
I have a content type with a field `field_file_attachment` that allows uploading multiple files with txt, pdf, gif and img extensions.

I would like to get links, descriptions and extensions of all these files printed in my Twig file `node--page--full.html.twig`.

Is this possible? Should I create a preprocess function for page?

# Answer
> 2 votes
You should be able to do something like this,

```
{% for file in node.field_file['#items'].entity %}
  {{ file.uri.value }}
  {{ file.name.value }}
{% endfor %}

```

# Answer
> 1 votes
Maybe it will be helpful for other, I use:

```
{% for file in content.field_file['#items'] %}
  {{ devel_dump(file.entity.name.value)}}
{% endfor %}

```

It gives me acces to all values from file field.

# Answer
> 0 votes
> You need to pass your file or image field `uri` value with `file_url()` function, Read the **Drupal Docs**, Then you will have field's exact value, **not** rendered

```
{{ file_url(node.field_policy_pdf.entity.uri.value) }} - if it has limited (1) value.

```

**Else you need to use twig** `{% for %} loop`

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


title: How to get fields in StylePluginBase?

text:
# Question
Title: How to get fields in StylePluginBase?
I´m building a new nap view style. I get the map shown correctly, but only without the data of the view :-(.

```
class OpenlayersViews extends StylePluginBase {
  /**
   * Whether the display allows the use of a pager or not.
   *
   * @var bool
   */
  protected $usesPager = FALSE;

  /**
   * Whether the display allows the use of a 'more' link or not.
   *
   * @var bool
   */
  protected $usesMore = FALSE;

  /**
   * Whether the display allows area plugins.
   *
   * @var bool
   */
  protected $usesAreas = FALSE;

  /**
   * Does the style plugin support grouping of rows.
   */
  protected $usesGrouping = FALSE;

  /**
   * Does the style plugin for itself support to add fields to it's output.
   */
  protected $usesFields = TRUE;

  /**
   * {@inheritdoc}
   */
  public function evenEmpty() {
    // Render map even if there is no data.
    return TRUE;
  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['openlayers_map'] = array('default' => 'none selected');
    return $options;
  }

   /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $openlayers_map_options = [];
    foreach (openlayers_get_map() as $key => $map) {
      $openlayers_map_options[$key] = $this->t($map['label']);
    }

    $form['openlayers_map'] = [
      '#title' => $this->t('OpenLayers Map'),
      '#type' => 'select',
      '#options' => $openlayers_map_options,
      '#default_value' => $this->options['openlayers_map'],
      '#required' => TRUE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    dsm("OpenlayersViews:render");
    $map = openlayers_get_map($this->options['openlayers_map']);
    $mapid = Html::getUniqueId('openlayers_map');
    $features = array();

    /*
     * Here i need a function to get the result of the view
     */

    $element = openlayers_render_map($mapid, $map, $features, FALSE);
    return $element;
  }
}

```

I do not know, if the render is in the right position for getting the data. So maybe some of you can explain, what is the next step to do.

best regards

# Answer
Normally you would iterate through the rows and call a row plugin to render the field values. As I understand the question you want to access the field values directly by row index and field id?

Then try StylePluginBase::getFieldValue:

```
$value = $this->getFieldValue($index, $field);

```

---

Normally a style plugin iterates the rows like this:

```
  public function render() {
    if (empty($this->view->rowPlugin)) {
      trigger_error('Missing row plugin', E_WARNING);
      return [];
    }
    $rows = [];

    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[] = $this->view->rowPlugin->render($row);
    }
    ...

```

For this to work you have to set `protected $usesRowPlugin = TRUE;` and configure a row plugin which renders the map.

---

If you want to do all rendering in the style plugin you can use the same loop and get the field values directly:

```
  public function render() {
    $rows = [];
    foreach ($this->view->result as $index => $row) {
      $rows[] = render_map(
        $this->getFieldValue($index, 'field1'),
        $this->getFieldValue($index, 'field2')
      );
    }
    ...

```
> 2 votes

---
Tags: views, theming
---


# Question
Title: Covert link field as link field text format?
I have used the link field for the button. Here, I have to change one word as Italic. I am not able to change the word as Italic in the link field.

I want to change the link field as link's title lik formatted.

How could I achieve this without using any module.

Please suggest me!

# Answer
If you need to change the HTML you can Rewrite the output using tokens, see more info here: Raw Field Value in Views and in this question and answer: Add link for each column

Then you can emphasize a word in the output to make it italic, or wrap it with some HTML element with a class and italicize it with CSS in your theme.

If you want to make the whole link text italic you can add a class to that field and style it with CSS.

If you just want to reword the link text you can use the `Rewrite results` as mentioned.
> 1 votes

---
Tags: 8
---


title: change of Public file system path

text:
# Question
Title: change of Public file system path
how can i change Public file system path in drupal 8 ? And can you tell more about how to increase the storage of database?

# Answer
> 1 votes
> How can i change Public file system path in Drupal 8?

You can add the following line to either your `settings.php` file, or your `settings.local.php` file. E.g. `docroot/sites/default/settings.php`

```
$settings['file_public_path']  = '/sites/default/files/my_custom_folder';

```

> And can you tell more about how to increase the storage of database?

I have no idea what this means.

---
Tags: files
---


title: Disable Ajax Views scroll behavior?

text:
# Question
Title: Disable Ajax Views scroll behavior?
How can I disable the *scroll to top* behavior in an Ajax based View? Preferably, with Javascript.

The scroll behavior is triggered when running a search from an Exposed Form.

# Answer
> 5 votes
The solution above is for Drupal 7. In Drupal 8, `hook_views_ajax_data_alter` is deprecated and was replaced by `hook_ajax_render_alter`.

For those of you looking for it, here is how to do it in Drupal 8 (source here).

```
function YOURMODULE_ajax_render_alter(array &$data) {
  foreach ($data as $key => $command) {
    if ($command['command'] === 'viewsScrollTop') {
      unset($data[$key]);
      break;
    }
  }
}

```

# Answer
> 1 votes
I found the solution from an old issue.

The scroll behavior is added as an ajax command `viewsScrollTop`, you can unset it in `hook_views_ajax_data_alter`.

**Example**

```
/**
 * Implement hook_views_ajax_data_alter().
 */
function YOURMODULE_views_ajax_data_alter(&$commands, $view) {
  // Remove scroll to top behaviour from views ajax
  foreach ($commands as $key => $command) {
    if ($command['command'] == 'viewsScrollTop') {
      unset($commands[$key]);
      break;
    }
  }
}

```

---
Tags: views, javascript, ajax
---


# Question
Title: Node Export being downloaded as a .sh file and unable to be imported
In my Drupal 7 project, I have some content of a custom content-type (page) that I need to import into another environment.

When I go to this content instance, I select on `Node Export`, which then gives me the option to download the file. When I download the file, it is downloaded as `-.sh`. In my other environment where I want to import this content using a `Node Export Import`, it says that that file isn't allowed..

How is it possible that you aren't able to use a `Node Export` for a `Node Export Import`??? That makes absolutely zero sense.

# Answer
> 0 votes
You can Import and export the content by using "Node Export with Features".

need to enable this module under node export module.

next, you have to go this URL admin/structure/features/create and create the feature with the particular content type of content and download the module. next, this module you have to enable in another site. content will be created.but make sure content type of fields same in two sites.

---
Tags: nodes, importing-exporting
---


# Question
Title: I want to build multidimensional array at Twig
I want to build multidimensional array at Twig.

In php

```
 $attributes['attributes']['class'] = array();
 $attributes['attributes']['class'][] = 'innerTab';
 $attributes['html'] = TRUE;
```

Same thing I want to build in Twig. I tried but not getting proper one . Please check my code below

```
 {% set ctn = 0 %}
         {% for key, value in menu.menu %}
{% set attributes = {'attributes':'class'} %}
{% set attributes = attributes|merge( [ { (ctn) :'innerTab'} ,  {'html' : true} ]  ) %}
{% set ctn = ctn+1  %}
 {% endfor %}
```

As a result I get :

> array(3) { \["attributes"\]=\> string(5) "class" \[0\]=\> array(1) { \[0\]=\> string(8) "innerTab" } \[1\]=\> array(1) { \["html"\]=\> bool(true) } } array(3) { \["attributes"\]=\> string(5) "class" \[0\]=\> array(1) { \[1\]=\> string(8) "innerTab" } \[1\]=\> array(1) { \["html"\]=\> bool(true) } } array(3) { \["attributes"\]=\> string(5) "class" \[0\]=\> array(1) { \[2\]=\> string(8) "innerTab" } \[1\]=\> array(1) { \["html"\]=\> bool(true) } }

# Answer
> 0 votes
In Drupal 8 use an Attribute object instead of a multidimensional array:

D7 PHP:

```
$attributes['attributes']['class'] = array();
$attributes['attributes']['class'][] = 'innerTab';

```

D8 Twig:

```
{% set attributes = create_attribute() %}
{% set attributes = attributes.addClass('innerTab') %}

```

You can use the Attribute object in Twig `link()`:

```
{{ link(title, support_url, attributes) }}

```

---
Tags: theming
---


# Question
Title: Drush won't work after installing drupal 8 on remote server using composer
After installing drupal 8 on a remote server (I have SSH access) using composer I installed drush using the following command: 'composer require drush/drush'. After I type vendor/bin/drush I get the following error:

> \[preflight\] The following restricted PHP modes have non-empty values: {disable\_functions}. This configuration is incompatible with drush. {Please check your configuration settings in /usr/local/lib/php.ini or in your drush.ini file; see examples/example.drush.ini for details.}

My drush version is 9.6. How do I make it work?

# Answer
It turns out that making it work wasn't at all easy, so I'll try to post an answer to my own question in the hope that it helps some other newbies, who do not have a lot of experience in working with remote linux servers, but want to use drush 9.x with their Drupal 8 installation:

1. First of all, after finding a similar problem in https://www.drupal.org/forum/support/post-installation/2015-08-02/solved-installed-drush-not-working-warning-popen-disabled (this quite long collection of posts is, I believe, worth reading) I found out that you have to give Drush its own php.ini file with looser security. One way to do it is described in here: http://www.6by9.net/drush-on-an-hosting-fix-using-custom-php-ini/
2. Sadly, the above doesn't work for drush 9.x, so after another search I chanced upon the following https://github.com/drush-ops/drush/issues/3294#issuecomment-370201342 In this comment Moshe Weitzman writes that you have to

> insure that the PHPRC environment variable is set to the directory containing the desired php.ini

3. So after another search I managed to find out how to do it using the following command:

> export PHPRC=/your/path

and in my particular case it looked like this:

> export PHPRC=~/.drush

I don't know if it is the 'right' way to do it, but it works :-)
> 0 votes

---
Tags: drush
---


title: Moving a site, links/admin do not work

text:
# Question
Title: Moving a site, links/admin do not work
I moved a drupal installation from one server to another. Steps I followed:

1. Copied whole directory structure from old server.
2. Exported database from old server.
3. added files to newdomain/drupal
4. Imported database
5. edited settings.php with new database information.

As of right now the home page is working (Except for some broken non-db images, but I know the reason for that and can fix it) But none of the links to any of the nodes or any of the admin paths I know seem to exist. I get a 404 File Not Found error.

I wonder if it's related to the fact that this installation is in a subdirectory and the other one was not, but is that enough to make every page except the homepage not function?

# Answer
> 3 votes
The link to the modules and themes are hard coded in the system table in the database. Reset them by visiting 'admin/modules', clear the cache, make sure clean urls are on, and make sure any op code cache like APC is cleared if you are using that.

# Answer
> 3 votes
Yes, that's possible. You can try to adjust the used base URL by setting the $base\_url value in your settings.php .

# Answer
> 2 votes
I had the same problem! The cause was a missing .htaccess file...it didn't get copied when I copied all the other site files. Once I copied that file into the test site, I was able to re-enable clean urls.

# Answer
> 0 votes
For windows server users: I had same issue. I added .htaccess file but no success. On windows server you need to

* open IIS
* click URL Rewrite
* Import Rules
* point to your .htaccess file in Site
* import -\> Remove any error shown
* Apply Rules.

That should solve this issue.

# Answer
> 0 votes
If you have any **languages** configured, you might have to go into the database directly and reconfigure the URLs under the table: `languages`, then change the settings under `domain`.

You can also configure these settings in the GUI under: `/admin/config/regional/language` if you can get to it.

**DON'T FORGET to clear your caches afterward.**

---
Tags: 7, backups
---


# Question
Title: How do I force Twig output from my custom module, instead of from the theme?
I'm new to Drupal, I create a module including block and twig. I want to call out my twig(modules/custom/footer\_block/src/templates) and store data in there when execute build() in block.

However, it output a twig from theme folder(a templates folder inside the theme folder) that's is not created by me.

How can I force to output from my module folder?

The block is using the following code.

### footerMenu\_block.php.

```
public function build(){
    return [
        '#theme' => 'footer_menu',
        '#address_title' => $this->configuration['address_title'],
        '#address_content' => $this->configuration['address_content'],
    ];

```

### footer-menu.twig.html

```
<div>
       <h2>{{ address_title }}</h2>
       <p>{{ address_content }}</p>
 </div>

```

### footer\_block.module

```
<?php
function footer_block_theme($existing, $type, $theme, $path){
  return array(
    'footer_menu' =>
      array(
        'variables' => array(
          'address_title' => '',
          'address_content' => '',
        ),
      ),
  );
}

```

If I move the Twig to that output folder (inside theme folder), it will be unable to store my data. If I make simple output '#markup' inside `build()` that will work fine. Therefore, other code in block should be working without problem.

I am using Drupal 8.6.x.

# Answer
> 0 votes
Try adding the template array key to your theme hook:

```
function footer_block_theme($existing, $type, $theme, $path){
  return [
    'footer_menu' => [
      'variables' => [
        'address_title' => '',
        'address_content' => '',
      ],
      'template' => 'footer-menu',
    ],
  ];
}

```

Or try adding the block twig template suggestion as:

```
function footer_block_theme($existing, $type, $theme, $path){
  return [
    'footer_menu' => [
      'template' => 'footer-menu',
      'base hook' => 'block',
    ],
  ];
}

```

---
Tags: theming, blocks
---