title: How do I place my script after jQuery?

text:
# Question
Title: How do I place my script after jQuery?
How can I move the following markup after the one loading jQuery and drupalsettings?

```
<script src="https://abc.ai/js/w?key=abc.jdnwVFfn4YUZA0in"></script>

```

Actually, the order is the one in the following markup.

```
<script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"node","currentPathIsAdmin":false,"isFront":true,"currentLanguage":"en"},"pluralDelimiter":"\u0003","ajaxTrustedUrl":{"\/search\/node":true},"user":{"uid":0,"permissionsHash":"a791675a6fdb4f639fabce88c7e91295566b58e25f936b9d181582d9321c503f"}}</script>
<script src="/core/assets/vendor/jquery/jquery.min.js?v=3.2.1"></script>
<script src="/core/misc/drupalSettingsLoader.js?v=8.5.1"></script>
<script src="/modules/abc/js/abc.js?v=1.x"></script>

```

I used `hook_page_bottom()` to attach the script in the abc module.

```
function acobot_page_bottom(array &$attachments) {
  $attachments['#attached']['library'][] = 'acobot/acobot-initialise';
  $attachments['acobot'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#attributes' => array('src' => 'https://acobot.ai/js/w?key=' . $token),
    ],
    'acobot-token',
  ];
}

```

The content of the abc.libraries.yml file is the following.

```
abc-initialise:
  version: 1.x
  js:
    js/abc.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

I added weight in the below code(instead of #attached in hook\_page\_bottom) but it does not change the position .

```
function acobot_library_info_alter(&$libraries, $extension) {
$libraries['acobot'] = array(
  'version' =>'1.x',
  'js' => array(
     'acobot/acobot.js' => array(
        '#weight' => 100,
     ),
   'dependencies' => array(
     0 => 'core/jquery',
     1 => 'core/drupalSettings'
   )
  ),
);

  return $libraries;
}

```

# Answer
I have an alternative idea: provide the dynamic value in drupal settings, define your main script as library, and get the setting in run time.

```
 '#attached' => [
  'library'        => [
    'mymodule/mylibrary',
  ],
  'drupalSettings' => [
    'myModule' => [
      'key' => 'value',
    ],
  ],
],

```

Then in your library script, get the setting and use it.

```
var data = drupalSettings.myModule.key;

```

You can see how to create a dynamic script tag if needed here: https://stackoverflow.com/questions/20737442/document-writescript-throws-unexpected-token-illegal
> 1 votes

# Answer
The problem is that you're adding it to page bottom region, which is above the JS.

What exactly is $token, is it something personalized or is it a global license key/identifier for the whole site? If the second, then use a library alter hook to load it instead.

See https://cgit.drupalcode.org/jw\_player/tree/jw\_player.module#n129 for example, that dynamically alters the library definition to either load from a CDN with a dynamic url or a local path that can vary based on input from the libraries module.
> 4 votes

# Answer
To add Javascript to a theme that depends on jQuery, you should define it as a library and add a dependency to "core/jquery";

See: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

> Remember, Drupal 8 no longer loads jQuery on all pages by default, so for example if cuddly-slider needs JQuery you must declare a dependency on the core library that contains jQuery (Drupal core provides jQuery, not a module or theme). Declare the dependency with an extension name followed by a slash, followed by the library name, in this case core/jquery. If another other library required cuddly-slider it would declare:fluffiness/cuddly-slider, the theme name, followed by the library name. You cannot declare an individual file as a dependency, only a library.
>
> So, to make jQuery available for cuddly-slider, we update the above to:

```
# fluffiness.libraries.yml
cuddly-slider:
  version: 1.x
  css:
    theme:
      css/cuddly-slider.css: {}
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery

```

So following your example:

```
abc-initialise:
  version: 1.x
  js:
    js/abc.js: {}
    'https://abc.ai/js/w?key=abc.jdnwVFfn4YUZA0in':
      type: external
  dependencies:
    - core/jquery
    - core/drupalSettings

```
> 1 votes

---
Tags: 8, javascript
---


# Question
Title: Decode an image in base 64 to a file, using feeds, feeds tamper and jsonpath
I have a problem importing a 64 base image through the feeds module. I am consuming a service through jsonpath.

I am using the tamper feeds module to try to decode the image and then save it as a file but I have not succeeded.

I get the data well in the attribute mapping between the service and the content type, but I can not get the feed tamper to decode it and save it as an image in the content type.

Is this possible to do?

# Answer
**Feeds Base64 images module**

I have developed a module for this which adds two additional targets for file and image fields:

* Filename
* Base64

The 'Filename' target always needs to be mapped first.

I created this module years ago, but I never published it on drupal.org... until today!

https://www.drupal.org/sandbox/megachriz/2961717
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: CKEditor table td style not showing in frontend
I use CKEditor (WISYWYG editor) to edit text and HTML for my Drupal project. I want to edit an HTML table and try to horizontally align text in a table cell `<td>` to the right.

My steps:

1. select the text in the table cell
2. right+click \> Cell \> Cell properties \> Horizontal Alignment: Right.

When I am logged-in and I inspect the HTML I see `<td style="text-align: right;">My text</td>`. But as soon as I am logged-out the HTML is stripped and I see only `<td>My text</td>` (style="text-align: right;" disappeared).

I certainly need to align my text to the right in some HTML table cells.

Update:

1. I use `Filtered HTML`
2. In `admin/config/content/formats/filtered_html`, I added the following settings (see screenshot):

# Answer
Had a similar issue for a long text field (filtered html format).

HTML tags were getting removed when switching between formats (editor was removing them).

At /admin/config/content/ckeditor/edit/Advanced (advanced is a profile name used for the filtered html format in my case), under "advanced content filter", choosing disabled solved the issue (server side filtering works, this filtering is there for the wysiwyg ux essentially).
> 0 votes

---
Tags: 7, wysiwyg
---


title: Allow tables in content with CK-Editor

text:
# Question
Title: Allow tables in content with CK-Editor
I have problems to configure my dupal 7 installation to allow entering tables.

*I will add the link to the page I mean because not everytime sure that I use the right words.*

I have created a type (admin/structure/types) which has four fields (admin/structure/types/manage/my-type-name/fields). The field body (admin/structure/types/manage/my-type-name/fields/body) has set filtered text as text processing. The selectbox under the CK-Editor has the value Filtered HTML. I tried to set its value to a custom clone of Filtered HTML which allows the attentional tags table, td, th and thead.

How can I allow tables for a special kind of type?

# Answer
You can use Full Html to allow tr th and table but If you need to use Filtered HTMl for security reason you can use wysiwyg\_filter Module that allow you to add some html tags to filtered html about select box under ck-editor it's a permission problem that only filtered html appear
> 1 votes

# Answer
Related issue at CKEditor table td style not showing in frontend.

Check your ckeditor settings at /admin/config/content/ckeditor, had to disable "advanced content filter" (or well, reconfigure the editor), which was strapping all html tags not present in the editor features.
> 0 votes

---
Tags: 7, nodes, wysiwyg
---


# Question
Title: How can $build['#attached']['drupalSettings'] change from hook_node_view to javascript?
I'm afraid the title isn't clear: I am passing a value from hook\_node\_view to my javascript in $build\['#attached'\]\['drupalSettings'\]\[\]. But the value that is set there is not the value that the js is using. I've checked in several places to make sure that this value is indeed the one set in the variable; nevertheless, the js script is getting a different value. I'm sure I'm missing something easy, at least something I should be aware of. The stack trace in the js debugger isn't helpful, so it seems there is some processing happening after the hook is called and the js getting the value in drupal settings.

# Answer
> 0 votes
I had strongly suspected a caching issue while ignoring something more obvious, that the hook was being called several times and passing the value of the last time it's called to the javascript. Just added a check to make sure it's passing the correct value and it solved the issue.

---
Tags: 8, javascript
---


# Question
Title: how to use Views Datasource to export view in JSON
I am new in Drupal. I am using Drupal 7 and i have created a view based on the terms and displaying it as Block to display it in the website. But, I want to export the view data in the JSON format.

I have installed Views Datasource module and enabled it in the Module administration.

But, i can't see the way to export my current view data to JSON through this module.

Can any one please help? is there any settings i am missing?

or is there any easy way like modules or plugins i can use?

# Answer
> 1 votes
You can achieve this by combination of two modules. Views data export and Views data export - JSON support. Once you install these two modules create a view as data export and select format as JSON.

# Answer
> 0 votes
To use Views Datasource to output JSON:

1. Enable the views datasource sub-module views\_json
2. Add a new Page display to your view
3. Under "Format" switch to "JSON data document"
4. Set the path for your display

---
Tags: views
---


title: Alter url aliases programmatically

text:
# Question
Title: Alter url aliases programmatically
I have a pattern set up to create the URL aliases based on a field of type list text.

the field looks like this:

selection 1|selection 1

selection 2|selection 2

How can I alter the alias so it will show something like this:

www.example.com/1-was-selected rather than www.example.com/selection-1

UPDATE: I'm using Pathauto for the patterns.

# Answer
> 3 votes
I would create a custom token and use that in my alias. I'm assuming you're using pathauto to create your aliases. This page gives a pretty good example of how to create your own token. Then you can select your token in the pathauto UI.

You can create the hook\_tokens\_info hook basically exactly as they've done, but replacing the "customs" with your real values. For your hook\_tokens implementation, you should have access to the entity in the `$data` variable i.e., `$data['node']` will have your node object if you're using this for nodes. From there you should be able to do something like `$data['node']->field_your_list_field->getValue()` to get the value of your field. Just be sure to return a `$replacements` array where the key is your custom\_token and the value is the value to replace with, in your case this would be something like `you-selected-value-X`.

# Answer
> 2 votes
In this case I guess you should create a token in a custome module. Todo so you should implement hook\_token\_info() and then hook\_tokens().

Or maybe you could look at hook\_tokens\_alter() and target the token you are actually using in your pattern to changed its rendering.

example from durpal.org:

```
function hook_tokens_alter(array &$replacements, array $context, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $options = $context['options'];

  if (isset($options['langcode'])) {
    $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
    $langcode = $options['langcode'];
  }
  else {
    $langcode = NULL;
  }

  if ($context['type'] == 'node' && !empty($context['data']['node'])) {
    $node = $context['data']['node'];

    // Alter the [node:title] token, and replace it with the rendered content
    // of a field (field_title).
    if (isset($context['tokens']['title'])) {
      $title = $node->field_title->view('default');
      $replacements[$context['tokens']['title']] = drupal_render($title);
    }
  }
}

```

---
Tags: 8, path-aliases
---


# Question
Title: Use Webform to email users with query parameter or argument?
I want to be able to have a contact form that lets visitors send email to different users (like a staff directory) without exposing the email address or user id. I am going to come up with my own way of identifying users to not expose Drupal specific information. Anyway.

However, I need to:

* Pass that value in the URL to identify the user to locate, to know where to send the mail
* Load and check the user from that passed value before showing the form
* *If* the user is not a certain role, serve a 404 instead of a form (only certain roles can be contacted).
* Preferably have a url like `/staff/{FOO}/contact` where `{FOO}` is my custom value.

Would it be easier to just implement this myself, or rely on Webform? I wanted to take advantage of Webform in case the client wanted to add another field later or create other forms (more basic ones), throttle repeat submissions and the dozens of other things Webform can do.

# Answer
> * Pass that value in the URL to identify the user to locate, to know where to send the mail
> * Load and check the user from that passed value before showing the form
> * *If* the user is not a certain role, serve a 404 instead of a form (only certain roles can be contacted).
> * Preferably have a url like `/staff/{FOO}/contact` where `{FOO}` is my custom value.

If you want to make a webform integrated module, you can achieve all of the above by altering certain webform's route(s) & maybe service(s).
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Remove user permission from content after creation
We have a business case where it is needed to remove user permission for a specific content type after submission.

Think of it something like submitting an application.

If there is better workflow suited than removing user permission, please let me know.

# Answer
> 0 votes
Are you asking because you only want a user to be able to create 1 (and only 1) node of a specific type? Or (as Ziftman suggests) do you just want to prevent the person the person from editing content after they have created it? If its the former, you could do something like this:

Create a custom module with a hook\_form\_alter that checks if the user has created content of that type and, if so, hide the form or redirect or whatever. D7 code below, but similar works for D8) Ex:

```
function my_module_form_node_form_alter(&$form, $form_state) {
  global $user;

  // do a query to find out if the user has created a node of this type before
  $already_created = db_query("SELECT count(*) as count FROM {node} WHERE type='application' and uid=%uid", array('%uid' => $user->uid))->;

  if ($already_created->count) {
    $form['#access'] = FALSE;
    drupal_set_message("You cant do this");
    drupal_goto('some/other/path');
  }
}

```

---
Tags: 7, users
---


# Question
Title: how to restrict access in routing.yml based on roles
I know how I to restrict access in the routing.yml file based on permissions, but how can I do it based on roles? This is how to do it by permissions:

```
requirements:
  _permission: 'access administration pages'

```

How to do it based on roles?

# Answer
This should work

```
requirements:
  _role: 'administrator'

```

See more details here https://www.drupal.org/docs/8/api/routing-system/structure-of-routes
> 10 votes

# Answer
That *is* how you do it based on roles.

To complete the process, visit your site’s permissions administration and assign the relevant permission to the relevant role(s).
> 3 votes

---
Tags: routes, users
---


title: Alter Links/Menu to show a modal dialog

text:
# Question
Title: Alter Links/Menu to show a modal dialog
I have two type of roles 'base' and 'full'. For the base role I would like to alter some menu links to open a modal dialog instead of the original destination url. I would like to replace the link. I know about route subscriber and how to change the route. But in my case I want to change the link (use an ajax enabled link and open a modal dialog instead). Is there any way I can do this?

# Answer
I think you can use hook\_link\_alter

```
function hook_link_alter(&$variables) {
  $url = $variables['url'];

  if ($url->isRouted() && $url->getRouteName() == 'user.login') {
    $variables['options']['attributes']['data-dialog-type'] = 'modal';
    $variables['options']['attributes']['class'] = 'use-ajax';
  }
}

```

See more details here https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/function/hook\_link\_alter/8.5.x
> 4 votes

---
Tags: 8, ajax, navigation
---


# Question
Title: Should I run tests for the entire core and contributed modules, or only for the codes I wrote?
I am planning to integrate unit testing in CI/CD. I wonder what would be the good practice for running.

Should I run tests for the entire core and contributed modules, or only for the codes I wrote?

# Answer
The whole point of doing unit testing is verifying code functionality and preventing regression bugs on new code changes. Unless you're working on some development branch (i.e. not a release), running 3rd party vendor (core, contrib modules) unit tests is redundant; you should write unit tests for code that you're maintaining and trying to keep reliable and bug free.
> 3 votes

---
Tags: 8, testing
---


# Question
Title: Reference a filename in form validation for an image
I am new to Drupal and am making a module to alter a content type. I have a content type that allows a user to submit an email and an image and I want to change the filename of the image to the email before it submits to the database. I figured I can do this in the form validation but I am having trouble finding the right code to access the filename value using $form\_state. I am using the form alter hook and adding to the validation.

# Answer
I think you can get value using Form API

```
$upload = $form_state->getValue('file');
$file = File::load($upload[0]);
$file->setPermanent();
$file->setFilename(‘test’);
$file->save();

```
> 0 votes

---
Tags: forms, files
---


# Question
Title: Drupal unexpected "Fatal error: Class name must be a valid object or a string [...] common.inc" on every page
"**Fatal error**: Class name must be a valid object or a string in **C:\xampp\htdocs\uc\includes\common.inc** on line **7506**"

The error above showed up unexpectedly. I was adding a "Long text" field to a content-type, but when I expected to be brought to a saved field configuration page, I instead got a Fatal error on every page.

**I had a look at includes\common.inc**:

```
/**
 * Get the entity controller class for an entity type.
 */
function entity_get_controller($entity_type) {
  $controllers = &drupal_static(__FUNCTION__, array());
  if (!isset($controllers[$entity_type])) {
    $type_info = entity_get_info($entity_type);
    $class = $type_info['controller class'];
    $controllers[$entity_type] = new $class($entity_type); // Line 7506
  }
  return $controllers[$entity_type];
}

```

However, I just don't understand Drupal at a low enough level to understand the relationships between these variables and functions.

**I also searched Drupal for people with a similar problem**:

(1) I found one user who claims that I have to install the submodule "Relation Endpoints Field", but searching Drupal, there doesn't seem to be such a module.

(2) Another user suggested clearing the cache manually:

```
DELETE FROM cache;
DELETE FROM cache_filter;
DELETE FROM cache_menu;
DELETE FROM cache_page;
DELETE FROM watchdog;

```

(via WordPress API, misleading name, I know.)

Clearing those tables from the cache did not help.

(3) And another user suggested disabling old modules, specifically the "Old search facets" module. Because I can't find a module specifically pertaining to old search facets, I went into MySQL system table, and marked the Search module's line with a 0 status, indicating to stop loading the module altogether.

On that same link as (3), one user suggested enabling the Database Search Module, so I dropped all the tables, imported the latest stable .sql, and installed the module, but after recreating the problem (trying to add a field to a content-type), that as well concluded fruitless.

**Still, the problem remains**

The Fatal error shows up on every page, making the site completely non-functional. Any help or direction would be immensely appreciated. Thank you for looking.

# Answer
> 8 votes
The error means that Drupal can't find the entity type information for a entity that it tries to load.

Add `var_dump($entity_type);` in there and reload the page. The *last* one that it's going to print (if there are multiple) is the culprit. What you need to do then depends on the entity type. It could for example be that you disabled a module which is still being called.

# Answer
> 1 votes
This issue has been raised and closed (without repair) a huge number of times (more than 50 that I can see). It is, admittedly, a tough one to find. I have entered the issue. I have tracked down the actual cause, but the intricacies of the cache are a bit beyond me.

Clearing the cache could help here. Sadly, you can't always get there, largely because drush cc will also blow up when this error is occurring. So will anything having to do with accessing a user (in my case). . Requiring a user to clear the cache every time this occurs is improper by its nature - you can't have a user do a workaround as a normal course of business.

This is the tip of the iceberg on this problem. (the PHP Fatal error: Class name must be a valid object or a string in /includes/common.inc on line 7522).

\[\[\[\[in 7.28, at line 7855, 6 = \]\]\]\] $class = $type\_info\['controller class'\]; $controllers\[$entity\_type\] = new $class($entity\_type);

The symptom appears because the search for the element \['controller class'\] is presumed to be successful. It is not, and no secondary message (such as in a try / catch or an actual test here) is generated.

The issue stems from, for whatever reason, not being able to obtain a $class value from the $type\_info array by executing module\_invoke\_all('entity\_info'). Certainly a call time pass by reference could do it, but that would normally be caught. The actual problem is in /includes/common.inc at 7644.

```
      if (empty($entity_info)) {
        if ($cache = cache_get("entity_info:$langcode")) {
          $entity_info = $cache->data;
        }
        else {
          $entity_info = module_invoke_all('entity_info');
          // Merge in default values.
          foreach ($entity_info as $name => $data) {
            $entity_info[$name] += array(
              'fieldable' => FALSE,
              'controller class' => 'DrupalDefaultEntityController',
              'static cache' => TRUE,
              'field cache' => TRUE,
              'load hook' => $name . '_load',
              'bundles' => array(),
              'view modes' => array(),
              'entity keys' => array(),
              'translation' => array(),
            );
            $entity_info[$name]['entity keys'] += array(
              'revision' => '',
              'bundle' => '',
            );
            foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
              $entity_info[$name]['view modes'][$view_mode] += array(
                'custom settings' => FALSE,
              );
            }
            // If no bundle key is provided, assume a single bundle, named after
            // the entity type.
            if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
              $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
            }
            // Prepare entity schema fields SQL info for
            // DrupalEntityControllerInterface::buildQuery().
            if (isset($entity_info[$name]['base table'])) {
              $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
              if (isset($entity_info[$name]['revision table'])) {
                $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
              }
            }
          }
          // Let other modules alter the entity info.
          drupal_alter('entity_info', $entity_info);
          cache_set("entity_info:$langcode", $entity_info);
        }
      }

```

Notice that if the condition is true in the if at

```
if ($cache = cache_get("entity_info:$langcode")) {
  $entity_info = $cache->data;
}

```

then the module\_invoke\_all('entity\_info') is never executed. It just happens that the condition is always met after some other processing is done to create the cache. That means that there is no way to get the entity\_info set up --- in my case there was no way to obtain the 'user' entity info, causing the original error above. I made the 'else' one level higher (took out the 'else {}') for testing, and everything worked as it should to clear the error.

I believe that the real bug is that the checking of cache is less than adequate, and that a check on the existence of the entity\_info about the specific entity being searched for is needed. In fact, it may be justifiable to also search for the element \['controller class'\] for that entity in the entity\_info stored in cache. D

# Answer
> 0 votes
I felt stupid after spending a day to find two typos but if this helps anyone..

I have a custom module that creates new fieldable entity type with bundles: I used word 'entity' as a last word in my module's name and later used search and replace to change: module\_name\_entity to module\_name.

Due to this or some previous hook\_entity\_property\_info() and hook\_entity\_info() were now called: module\_name\_property\_info() and module\_name\_info() without the hooks 'entity' part in the function name.

That caused common.inc not to find the entity info and produced this error for me.

---
Tags: 7
---


# Question
Title: Must implement interface > Drupal\Core\Entity\EntityTypeManagerInterface, none given in __construct() function
I am trying to write a custom eventsubscriber for commerce 2.x for an event after a successful checkout. Everything works and now I want to create a `__construct` function to initialize an object, but then I get the following error:

> TypeError: Argument 1 passed to Drupal\custom\_module\EventSubscriber\OrderCompleteEventSubscriber::\__construct() must implement interface Drupal\Core\Entity\EntityTypeManagerInterface, none given, called in /home/user/websiteName/docroot/core/lib/Drupal/Component/DependencyInjection/Container.php on line 264 in Drupal\custom\_module\EventSubscriber\OrderCompleteEventSubscriber-\>\__construct()

I've tried explicitly defining the `EntityTypeManagerInterface` within the class, but everything is resulting in this error. Not finding anyone with any similar issues, and this particular block of code works for other people, just wondering what I am missing or If I am doing something incorrect. This code runs great if I don't construct an object with `EntityTypeManagerInterface`as the argument ... any ideas?

```
namespace Drupal\custom_module\EventSubscriber;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\rng\RegistrantFactoryInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class OrderCompleteEventSubscriber implements EventSubscriberInterface {

  use StringTranslationTrait;

  /**
   * The registration entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $registrationStorage;

  /**
   * The user entity storage.
   *
   * @var \Drupal\user\UserStorage
   */
  protected $userStorage;

  /**
   * The registration access handler.
   *
   * @var \Drupal\Core\Entity\EntityAccessControlHandlerInterface
   */
  protected $registrationAccessHandler;

  /**
   * The registrant factory.
   *
   * @var \Drupal\rng\RegistrantFactoryInterface
   */
  protected $registrantFactory;

  /**
   * Drupal\Core\Session\AccountProxyInterface definition.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a new OrderCompleteEventSubscriber object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\rng\RegistrantFactoryInterface $registrantFactory
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, RegistrantFactoryInterface $registrantFactory, AccountProxyInterface $current_user) {
    $this->registrationStorage = $entity_type_manager->getStorage('registration');
    $this->registrationAccessHandler = $entity_type_manager->getAccessControlHandler('registration');
    $this->userStorage = $entity_type_manager->getStorage('user');
    $this->registrantFactory = $registrantFactory;
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      'commerce_order.place.post_transition' => ['buildRegistration'],
    ];
  }

  /**
   *
   * @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
   */
  public function buildRegistration(WorkflowTransitionEvent $event) {
    $order = $event->getEntity();
    // do stuff
      }
    }
  }

}

```

`Services.yml` File

```
services:
   custom_module_event_subscriber:
      class: '\Drupal\custom_module\EventSubscriber\OrderCompleteEventSubscriber'
      tags:
        - { name: 'event_subscriber' }

```

# Answer
A bit late but the code from EventSubscriber has three arguments so your services.yml file should read:

```
services:
  custom_module.order_complete:
    class: Drupal\custom_module\EventSubscriber\PurchaseBuildRegistration
    arguments: ['@entity_type.manager', '@rng.registrant.factory', '@current_user']
tags:
  - { name: event_subscriber }

```
> 1 votes

---
Tags: 8, entities, event-subscribers
---


title: How do I translate a view's "Menu tab"

text:
# Question
Title: How do I translate a view's "Menu tab"
I am on Drupal 7.56 on a multilingual site.

I have created a view that contains tab menu links. Almost all the site it available now in two languages. But I still can't **translate those view tab menu links**.

I use those tabs to let users access some information via their account area

**Example** : in a view that contents articles (that I want to user to see only those they created) I add a menu link this way :

* link : "user/%/myarticles".
* Menu name : My Articles
* Menu type : menu tab
* Menu "Menu : User menu

I have translated the view but I can not find any way to translate the "Menu name", not even in "admin/config/regional/translate/translate".

Users will see "My Articles" in both languages when I want them to see it written in the correct language in each case.

How do I present the user with only the correctly translated tab?

# Answer
The first steps when dealing with translations, particularly with user entered strings like Views Tabs labels, is to clear the cache and visit the page showing the string in question but make sure you **visit in a language other than English**!

The visit to that page with the interface in another language will trigger Drupal to refresh the Translate Interface list, and you should be able to find the new string when doing a search there (`admin/config/regional/translate/translate`).

Remember that the Translate Interface search is case sensitive! You *have to* enter "My Articles" and not "my articles" or any other case style.

If that search still isn't giving you any results, it may be you're missing a module that enables those strings to be included in translations. Make sure you have "String translation" or perhaps even "Variable translation" enabled.

If you've just enabled "String translation", similar to above, visit the page in another language then search for the string in Translate interface.
> 1 votes

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


title: Extended Audit logs

text:
# Question
Title: Extended Audit logs
I am using Audit log module for Drupal 8.5. But it looks the audits are very limited - i.e it audits only user updates and node updates. Not for creating templates, changing configurations, changing themes , creating pages, views etc. Since this site will be audited , I believe I might need more than this.

Any help on how to achieve this?

# Answer
> 1 votes
IMO the Message module would be a possible solution to answer this question. Using this module, you can create your own custom "*Events logging*" (to register things that happened in a site).

About *Message types*: think of them as equivalent to Content types, whereas you create messages (instead of nodes) of a specific Message type (instead of Content type).

### Example included in Commerce Kickstart

A great sample of this can be found in Commerce Kickstart, which uses the Commerce Message module, to create such "*Events logging*". In that case in the format of an Order History, as shown in this screenprint (from this module's project page).

### More info about the Message module

The Message module is an amazing module, it is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views, etc.

Though there is ***not a lot of documentation about it*** (which is what makes it a hidden gem ...). A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to have a look at the answers to:

**Tutorials:**

---
Tags: 8, security
---


title: Migrate Paragraphs from CSV

text:
# Question
Title: Migrate Paragraphs from CSV
I am migrating Paragraphs from CSV file. I have Paragraph called Text with two fields -\> title and body.

The problem is that I would like to also migrate translations for them, which currently don't know how to achieve. Tried with the migration\_lookup plugin and translations: true option, but receive error for duplicate primary key ids.

What is the way to do this?

# Answer
A simple solution could be the content import module that allows you to import among other things paragraph content from CSV I believe and you can specify language for each field. Give it a try
> 0 votes

# Answer
You will need two migrations. One for the paragraphs in the default language and one for the translations. Make sure the migration for the translation include the language code as a key.

And this post looks useful, https://evolvingweb.ca/blog/migrate-translations-csv-json-or-xml-drupal-8. As do all the links here, How to migrate multilingual content from CSV to Drupal 8?
> 0 votes

---
Tags: i18n-l10n, migrations, paragraphs
---


# Question
Title: Conditionally display one of two fields in Display Suite?
I'm wondering if there is a clever or preferred way of using Display Suite to display one of two fields.

So my case calls for either an image, if it is uploaded, or a EVA (entity views attachment). I have them both displaying correctly, and of course if the image is not uploaded (unpopulated), then the EVA field displays fine. But if the image is uploaded, I want to hide the EVA field.

I guess I could do a custom code field, but I would like to avoid that if there is a built-in method of choosing one over another field. Maybe something with field groups?

Thanks!

# Answer
Your only option is a custom code field. There have been attempts to make conditional fields possible through the UI, but it was too complex.
> 2 votes

# Answer
Use the field formatter conditions module: https://www.drupal.org/project/ffc

This will give you the same options that you have on a blocks (and more). So you can show the field based on any url pattern just as you would blocks:

http://cl.ly/image/2A2Y373Y3e1J

Hope this help.
> 4 votes

# Answer
You can use Renderkit with Entity Display Plugin for Field UI for problems like this.

I have not tried it with EVA specifically, but it can embed views displays, among other things.

The integration of the drilldown form into the field UI form is currently a bit clunky, but it works.

I recommend to also enable Cfr Preset.

Preparation:

* Enable entdispfieldui
* Optionally enable cfrpreset

On the "Manage display" page:

* Scroll to the bottom, add an EntDisP field.
* Move the field up into an active Region.
* Click "Save" at the bottom of the page.
* Edit the configuration for the EntDisP field (click the cog-wheel).
* Choose "Chain of responsibility", then "Field with formatter" or "Image with processor".
* Click "Update" on the sub-form.
* Click the cog-wheel again to open the form again.
* Choose "Views display.." for "New item". Choose the views display id.
* Click "Update" on the sub-form.
* Click "Save" at the bottom of the page.

It should work now, but having this configuration within the display configuration is messy.

To avoid this, you can use `cfrpreset`.

On the "Manage display" page:

* Click the cog-wheel again.
* Mouse-hover next to the drilldown select element for "Entity display".
* Click "Create a preset" (opens in new tab).

On the "Add preset" page:

* Choose a name for the preset.
* Save.

On the "Manage display" page:

* Close the sub-form, if it is still open.
* Click the cog-wheel again.
* Choose the preset you just created.
* Click "Update" on the sub-form.
* Click "Save" at the bottom of the page.

Optionally, you can export partial configuration as new presets.

## Screenshots

*I hope these are not too much. Would be great to have an expand/collapse thingie.*

Add EntDisP field.

Configuration with "Field with formatter".

Alternative configuration with "Image with processor".

Export as preset.

Save the preset.

Use the preset instead of the in-place configuration.
> 1 votes

---
Tags: 7, entities
---


title: Image styles deleted on node save

text:
# Question
Title: Image styles deleted on node save
I just created a custom module following this tut: generate-programmatically-image-styles-drupal-8

It works great but the following occurs. When I create a new node and upload the image you see that for every style I have it creates a image (like the custom module should). But when I save the node all the created images are deleted?

Is this a standard function in Drupal that can be disabled? Hope someone can help me with this.

Thanks in advance

# Answer
> 0 votes
It turns out that image\_path\_flush() is being fired in Drupal\file\_entity\Entity\FileEntity-\>postSave() even when the image is not actually updated. You can see the issue and proposed resolution outlined here: https://www.drupal.org/project/file\_entity/issues/2816761

---
Tags: 8, media
---


# Question
Title: Reference Live Files with Built-In Server
I use the built in php server most often when developing locally.

```
drupal server

```

Is there any tweak I could make locally to have all my assets referenced on the live site? When I ran apache locally I use to put this in the vhost file.

```
<IfModule mod_rewrite.c>
  RewriteEngine on
  rewriteCond %{DOCUMENT_ROOT}/sites/%1/files/%2 -f
  rewriteRule ^(.*)$ $1 [QSA,L]
  # Otherwise, send anything else that's in the files directory to the
  # production server.
  rewriteCond %{REQUEST_URI} ^/sites/[^\/]*/files/.*$
  rewriteCond %{REQUEST_URI} !^/sites/[^\/]*/files/css/.*$
  rewriteCond %{REQUEST_URI} !^/sites/[^\/]*/files/js/.*$
  rewriteCond %{REQUEST_FILENAME} !-f
  rewriteCond %{REQUEST_FILENAME} !-d
  rewriteRule ^(.*)$ http://www.livesite.com$1 [QSA,L]
</IfModule>

```

But now that I'm using the built in server, I can't do that. I was wondering if there may be another way? Preferably without a module that would affect my Drupal site. I just want this as a local modification.

# Answer
If I understand this correctly, you can just use the Stage File Proxy module. Configure it to point at your production site. It has more configuration associated to it instead of just rewrite rules (which will be overwritten the next time you update core anyway).
> 1 votes

# Answer
So `drupal server` is a Drupal Console wrapper around Symphony's `server:start` & PHP's built in web server. As you can see in the Symphony (& PHP) docs, you can configure a router script for the server that adjust the server's output based on the response. If you turn up the verbosity on Drupal console (`drupal -vvv server`), you'll see debug info that points where Drupal console is retrieving its default wrapper script.

You *might be* able to do some sort of hackery with the router script to achieve something similar to Apache's redirect/rewrite directives, but you're likely to get something that's not exactly 1:1 due to difference in the PHP/Apache web server.
> 1 votes

---
Tags: 8
---


# Question
Title: Merge two fields using Display suite, like views inline fields
Is there a way to merge two or more fields using Display suite, like Views inline fields? What I mean is - if I have the fields "Author", "Publication date" and "Article series", then I would like to display them as "Author1 | 01-May-2012 | Learning series" etc.

# Answer
> 8 votes
Here's a list of possible approaches:

* **Code field**: You can accomplish this with a custom code field in Display suite. A code fields supports usage of tokens and html. Additionally, you can use a Display Suite code filter to use php itself. More info found here: http://www.youtube.com/watch?v=mvFP16PJt4c
* **Use a Custom formatter**: If you need more heavy processing you can utilize the custom field formatter module.
* **Preprocess Field**: Additionally, you can access variables that are preprocessed via a "preprocess field". A preprocess field will print out the value of the key in the $variables array. Lullabot has an example on using the preprocess field.
* **Entity Views Attached**: This might be a bit extra overhead but if you download the eva module you can create views and pass the current NID in and combine fields through views. This is often helpful if you need to create various different photo galleries with different fields, etc.

# Answer
> 1 votes
Try Field Group module. It provides grouping fields feature within DS view mode UI ;)

# Answer
> 1 votes
Another option is using renderkit \+ entdispfieldui.

renderkit 7.x-1.2 contains an EntityDisplay plugin "Sequence of entity displays, with list format". You can add a sequence of entity displays within that.

If you add "Field with formatter" items, you should set the "Field display processor" to "Full reset" to get rid of all the div wrappers, and make it show up inline.

renderkit 7.x-1.3 has an EntityDisplay plugin "Display suite field", which gives you things like "Post date".

It can be useful to export the configuration as a preset using cfrpreset, to make it reusable and configurable outside of field UI.

Details:

I added a lot of details in Conditionally display one of two fields in Display Suite?, a lot of this will be similar.

Caveats:

* This method adds a lot of dependencies to your project. You need to decide for yourself if this is worth it.
* The integration of the drilldown forms in the field UI subform is a bit clunky. But it does work in the end.
* Adding an item to a sequence (here: Entity displays Item #0, Item #1 etc) requires to submit / reopen the form for each new item. This is a bit annoying, but survivable.

Below is an example configuration.

---
Tags: entities, display-suite
---


# Question
Title: Passing $form_state data into \Drupal::entityQuery('user')
I have the following D8 form

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['bulk_perfplans_roles'] = array(
      '#type'          => 'checkboxes',
      '#title'         => $this->t('Generate plans for which roles?'),
      '#options'       => user_role_names(),
    );
    $form['bulk_add'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Create new Performance Plans'),
    );

    return $form;
  }

```

I'm trying to pass the information into an entityQuery as follows...

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $selectedRole = $form_state->get('bulk_perfplans_roles');
    $uids = \Drupal::entityQuery('user')
      ->condition('roles', $selectedRole)
      ->sort('created', 'ASC')
      ->execute();

```

I'm trying to make it so it conditionally alters the query based on the user selected roles from $form\_state. It's currently not working, and I'm not sure where to go next. Any thoughts?

# Answer
> 2 votes
Does `$selectesRole` have the expected value? I'm pretty sure you want to use `$form_state->getValue('bulk_perfplans_roles')` instead. Details here.

Also is it a single value field? You may need to pass an additional `IN` parameter to your field condition and do some additional prep if the result from getValue is an array.

Also make sure you're passing the machine name of the role and not the label.

# Answer
> 1 votes
As @sonfd said you submit function will be like:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
    $selectedRole = $form_state->getValue('bulk_perfplans_roles');
    $uids = \Drupal::entityQuery('user')
      ->condition('roles', $selectedRole,'IN')
      ->sort('created', 'ASC')
      ->execute();
}

```

After submitting your roles look like:

And UID's will be like:

---
Tags: 8, forms
---


# Question
Title: How can I check, if node has a new (unpublished) revision in node-template?
I have user created content. I use the content-moderation plugin, so user can update their nodes but the updates will only be published after moderation. I like to display a little batch (has new unpublished update) on the user-nodes, to give the user an information about the moderation state.

For nodes with new revision in draft-state shows drupal a "last-version"-link in node-links-menü. It must be possible to check, if there is a new revision in draft state (in preprocess\_node). Who can help me and write a little php code for this check so I can generate a twig\_variable "has\_draft\_state".

Thanks in advance

# Answer
Maybe this could help you

```
{% set isNew = node.isNewRevision %}

```

Otherwise use template\_preprocess\_node() in your theme to generate needed variable.
> 0 votes

---
Tags: theming
---


# Question
Title: Create content of different entity by user programatically
I am using an OpenSocial site, and writing a custom code that will create a post content by specific user. The post was created but assigning user is not working. How to properly assign userID to a post entity type?

```
use Drupal\social_post\Entity\Post;
...
    $node = Post::create([
      // The node entity bundle.
      'type' => 'post',
      'field_post' => $post,
      'field_visibility' => 1,
      'uid' => 2, // user = John
    ]);
    $node->save();

```

Actual result:

```
POST ID  POST   AUTHOR  CREATED                   OPERATIONS
1        Test   admin   Wed, 04/18/2018 - 10:19   Edit

```

Expected result:

```
POST ID  POST   AUTHOR  CREATED                   OPERATIONS
1        Test   john    Wed, 04/18/2018 - 10:19   Edit

```

# Answer
The key is `user_id`, so presumably the correct code would be:

```
$post = Post::create([
  'type' => 'post',
  'field_post' => $post,
  'field_visibility' => 1,
  'user_id' => 2,
]);

$post->save();

```

I changed the var name to `$post` as it's not a node and you don't want to confuse those two things. I also removed the `type` as the social post entity type doesn't have such a field.
> 1 votes

---
Tags: 8, users
---


# Question
Title: Mismatched entity and/or field definitions
I have no idea how to fix this, I don't even understand what the problem is.

```
Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
Taxonomy term

The Term ID field needs to be installed.
The UUID field needs to be installed.
The Language field needs to be installed.
The Vocabulary field needs to be installed.
The Name field needs to be installed.
The Description field needs to be installed.
The Weight field needs to be installed.
The Term Parents field needs to be installed.
The Changed field needs to be installed.
The Default translation field needs to be installed.
The taxonomy_term.field_icon field needs to be installed.
The taxonomy_term.field_link field needs to be installed.
The taxonomy_term.field_meta_tags field needs to be installed.

```

I tried `drush entity-updates` but it finishes on error:

```
Character set 'utf8mb4' is not a compiled character set and is not specified
in the '/usr/share/mysql/charsets/Index.xml' file
PHP Parse error:  syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /var/www/vhosts/mysite/httpdocs/core/lib/Drupal/Component/Serialization/Yaml.php on line 54
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: syntax error, unexpected 'class' (T_CLASS), expecting
identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in
/var/www/vhosts/mysite/httpdocs/core/lib/Drupal/Component/Serialization/Yaml.php,
line 54

```

EDITED (after fixing drush install) I get the following for `drush entity-updates`

```
-sh-4.1$ drush entity-updates
The following updates are pending:

taxonomy_term entity type :
  The UUID field needs to be installed.
  The Language field needs to be installed.
  The Vocabulary field needs to be installed.
  The Name field needs to be installed.
  The Description field needs to be installed.
  The Weight field needs to be installed.
  The Term Parents field needs to be installed.
  The Changed field needs to be installed.
  The Default translation field needs to be installed.
  The taxonomy_term.field_icon field needs to be installed.
  The taxonomy_term.field_link field needs to be installed.
  The taxonomy_term.field_meta_tags field needs to be installed.
Do you wish to run all pending updates? (y/n): y
Drupal\Core\Entity\EntityStorageException: Exception thrown while performing a schema update. Cannot add unique key                              [error]
taxonomy_term_field__uuid__value to table taxonomy_term_data: unique key already exists. in
Drupal\Core\Entity\Sql\SqlContentEntityStorage->wrapSchemaException() (line 1470 of
/var/www/vhosts/mysite/httpdocs/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Failed: Drupal\Core\Entity\EntityStorageException: !message in Drupal\Core\Entity\Sql\SqlContentEntityStorage->wrapSchemaException() (line    [error]
1470 of /var/www/vhosts/mysite/httpdocs/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
Cache rebuild complete.                                                                                [ok]
Finished performing updates.

```

The bizarre thing is that all these things (field\_icon, link, meta\_tags..) are installed.

The site has many modules (both custom and from the drupal community) and it works alright. Should I export it all and do a clean install and then import it?

---

## UPDATE

I did not manage to fix this and it was giving very weird problems out of the blue, although the already created content types and nodes worked fine. After 24h+ of non stop working I reset the stype up from a clean install and copied content manually (tried doing the Configuration \> Configuration synchronization with single items, but it didn't work very well).

I can report now that the problem is gone. I have no idea what could have caused it or even when.

# Answer
> 0 votes
I got the above errors but with the node table. I am not sure if this is a safe thing to do but I executed the following MySQL command at the prompt:

```
ALTER TABLE node DROP INDEX node_field__uuid__value;

```

After that the entity updates executed without any problem.

For the author's problem I suppose you could adapt the command to:

```
ALTER TABLE taxonomy_term_data DROP INDEX taxonomy_term_field__uuid__value;

```

The key should be generated the next time you run that entity updates Drush command.

# Answer
> 0 votes
I had the same problem. The table structure changed. It was:

```
CREATE TABLE `taxonomy_term_data` (
    `tid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `vid` VARCHAR(32) NOT NULL COMMENT 'The ID of the target entity.' COLLATE 'ascii_general_ci',
    `uuid` VARCHAR(128) NOT NULL COLLATE 'ascii_general_ci',
    `langcode` VARCHAR(12) NOT NULL COLLATE 'ascii_general_ci',
    PRIMARY KEY (`tid`),
    UNIQUE INDEX `taxonomy_term_field__uuid__value` (`uuid`),
    INDEX `taxonomy_term_field__vid__target_id` (`vid`)
)
COMMENT='The base table for taxonomy_term entities.'
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2157
;

```

And now:

```
CREATE TABLE `taxonomy_term_data` (
    `tid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `vid` VARCHAR(32) NOT NULL COMMENT 'The ID of the target entity.' COLLATE 'ascii_general_ci',
    `uuid` VARCHAR(128) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `langcode` VARCHAR(12) NOT NULL COLLATE 'ascii_general_ci',
    PRIMARY KEY (`tid`),
    INDEX `taxonomy_term_field__vid__target_id` (`vid`)
)
COMMENT='The base table for taxonomy_term entities.'
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2157
;

```

So `uuid` line changed and `UNIQUE INDEX` removed. I applied those changes in the database and after that I could use the `drush entity-updates`.

---
Tags: 8, entities
---


# Question
Title: The ComplexData plugin does not exist, after upgrade
After my Drupal 8.51 upgrade, I keep getting this error.

> Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "ComplexData" plugin does not exist."

I have Googled it for two days and haven't found any information about what this is or how to fix it. I get the error while using Panels/Page Manager. I did upgrade both modules to the 4/14 release but that didn't help. Any ideas?

# Answer
I read in another post where an OP wrote that Composer didn't put all the /core files in place, so he manually copied the /core directory and all its files and that solved a similar problem he was facing.

I tried that last night, manually copying the Drupal 8.51 /core folder into my local install. It fixed the problem. I then copied the files into production and all is well. Thanks to all who commented.
> 0 votes

---
Tags: upgrading
---


title: Private files return 404 not found

text:
# Question
Title: Private files return 404 not found
I have a problem whereby any files uploaded into the private directory cannot be viewed - returning a 404 not found error. The images upload ok and get placed in sites/default/files/private directory. The image path when trying to view is in the form /system/files/image.jpg which I believe is correct.

Firstly I found that there are conflicts with the Fast 404 module. Disabling this module makes the private files now work on my staging server, but not on our live server.

Could there be any server-side settings that could be affecting this?

What else should I be checking?

# Answer
Merely disabling the Fast 404 module isn't enough if you are calling `fast_404_ext_check();` in `settings.php`. Be sure you've removed the Fast 404-related settings from `settings.php`.

Due to the way private files are implemented in Drupal, you will never be able to use private files with the extension-checking features of Fast 404.
> 2 votes

# Answer
If you are using the Fast 404 Module this can be solved by adding the path system/files to the

Array of whitelisted URL fragment strings that conflict with fast\_404.

in your settings.php fast 404 section. $conf\['fast\_404\_string\_whitelisting'\] = array('cdn/farfuture', '/advagg\_', 'structure/menu/item/', '/flag','group/','/taxonomy/term/','media/', 'system/files')
> 1 votes

---
Tags: 7, files
---


title: Global preprocess for all links

text:
# Question
Title: Global preprocess for all links
Is there a some sort of global preprocessing hook for *any* link on a Drupal site?

Use case:

I've got an enquiry webform embedded on a node that presets some inputs by URL parameters. Editors can set links to that enquiry node on multiple different places on the site (in navigation menus, inside text fields using LinkIt, in URL fields,...).

Whenever the currently active context is a certain node type (e.g. on every full view of a product like "/product/product-id"), I want all links that are rendered on the page (e.g. menu links, blocks, entity reference field on the product pointing to the enquiry node, etc) to have the product\_id appended.

I know how to get the current node id in preprocessing and I do know `hook_link_alter` for menus. But I wonder if there is some sort of global hook that captures *all* links, saving me from creating 453 different hooks doing all the same thing.

# Answer
One way to accomplish this would be by using a service tagged with the `path_processor_outbound` service tag.
Your service should then implement the `processOutbound()` function in order to modify all links on a page, if the request delivers a node object of the type you want.

This is an example service definition using the described service tag:

```
services:
  dummy.link_modifier_service:
    class: Drupal\dummy\DefaultService
    tags:
      - { name: path_processor_outbound }
    arguments: ['@request_stack']

```

This is an example implementation of such a service:

```
<?php

namespace Drupal\dummy;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Render\BubbleableMetadata;

/**
 * Class DefaultService.
 */
class DefaultService implements DefaultServiceInterface, OutboundPathProcessorInterface {

  /**
   * Symfony\Component\HttpFoundation\RequestStack definition.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;
  /**
   * Constructs a new DefaultService object.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {

    if (empty($request)) {
      $request = $this->requestStack->getCurrentRequest();
    }
    $node = $request->attributes->get('node');
    if ($node && $node->bundle() === 'product') {
      $options['query'][] = [$node->bundle() . '_id' => $node->id()];
    }
    return $path;
  }

}

```

This code will now be modifying all Drupal-handled URLs and adding a product\_id=XX parameter to them.

Hope this helps, good luck!

@see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21PathProcessor%21OutboundPathProcessorInterface.php/function/OutboundPathProcessorInterface%3A%3AprocessOutbound/
> 5 votes

# Answer
If you want to alter all links then you need to adjust the input for the preRenderLink and add the query to the element before its generated.

Firs you implement this hook\_element\_info\_alter to use your own class which extends the core Link class

```
/**
 * Implements hook_element_info_alter().
 */
function custom_element_info_alter(array &$info) {
  $info['link']['#pre_render'] = [
    [Drupal\custom\Links\CustomLink::class, 'preRenderLink'],
  ];
}

```

You extends the Link class and add your check if true then you can inject the parameters to your query

```
namespace Drupal\custom\Links;
use Drupal\Core\Render\Element\Link;
use Drupal\node\NodeInterface;

class CustomLink extends Link {

  public static function preRenderLink($element) {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof NodeInterface && $node->getType() == 'product') {
      $element['#options']['query']['product_id'] = $node->id();
    }

     return parent::preRenderLink($element);
  }

}

```

Another solution can be with javascript which not recommended. You can take look how extlink module is changing the links icon based on the link if it's external or not.
> 2 votes

---
Tags: 8
---


# Question
Title: How can I use 'format_type' => 'custom' for a datetime field?
I have a custom entity with (among others) a field defined this way:

```
$fields['duedate'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Due Date'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => '2050-12-31',
  )))
  ->setDisplayOptions('view', [
  'type' => 'datetime_default',
  'settings' => [
    'format_type' => 'date_courte',
  ],
    'weight' => 5,
  ])
  ->setDisplayOptions('form', array(
    'weight' => 5,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

'date\_courte' is a custom date format I created to display date as 'dd/mm/yyyy'. And it works!
I'd like to have the same result without using 'date\_courte' so I tried

```
  'settings' => [
    'format_type' => 'custom',
    'format' => 'd/m/Y',
  ],

```

instead of

```
  'settings' => [
    'format_type' => 'date_courte',
  ],

```

And it doesn't work!

I'm pretty sure of `'format_type' => 'custom'`.
I think the problem comes from 'format' in `'format' => 'd/m/Y'`.

What should be the correct syntax?

# Answer
> 3 votes
I'm pretty sure you need to use the `datetime_custom` display type vs `datetime_default`. You won't need to pass the `format_type` parameter in your settings array. You will end up with something like:

```
...
->setDisplayOptions('view', [
  'type' => 'datetime_custom',
  'settings' => [
    'date_format' => 'd/m/Y',
  ],
...

```

That should work how you'd like. The datetime\_custom formatter is defined in core's datetime module.

---
Tags: 8, entities
---


# Question
Title: How can I display conditional fields on page view?
I want to display one of two fields on page render, depending on which field was selected on save.

I have a content type with a paragraph field called Banner Header. Banner header has a field group called Callout links. Callout links contains three items:

1. A field that accepts a single link.
2. A field that accepts multiple links.
3. A select list radio button called Callout Link Control.

Here is the custom paragraph code for my banner header:

```
{# initiate the printing of the banner #}
{{content.field_banner}}
<div class="banner-info
{% if content.field_callout_icon.0 or content.field_callout_text.0 %} has-callout
{% else %}
no-callout
{% endif %}">
    {# print out the title of the node #}
    <h1>{{ node_title }}</h1>
    <div class="leadin-wrapper {{ content.field_leadin_background.0['#markup'] }}">
       <div class="leadin-subwrapper">
           {{content.field_leadin}}
       </div>
    {# If there is content in the field_callout_icon or field_callout_text #}
        {% if content.field_callout_icon.0 or content.field_callout_text.0 %}
           <div class="callout-wrapper {% if content.field_callout_link.0 or content.field_small_callout_button_link.0 %} linked{% endif %}">
                {% if content.field_callout_link_control.0 == 'A single large button link' %}
                         <a href="{{ content.field_callout_link.0['#url'] }}">
                {% endif %}
                {% if content.field_callout_link_control.0 == 'Multiple small button links' %}
                        <a href="{{ content.field_small_callout_button_link.0['#url'] }}">
                        {% if content.field_callout_link.0 %}
                                <div style="visibility: hidden;">{{content.field_callout_link.0}}</div>
                        {% endif %}
                {% endif %}
                <div class="callout-wrapper-inner">
                   {{ content.field_callout_icon }}
                   {{ content.field_callout_text }}
               </div>
                </a>
           </div>
        {% endif %}
    </div>
</div>

```

Depending on which radio button is selected, I want to display the corresponding Callout Link field: either field\_callout\_link or field\_small\_callout\_button\_link.

I've tried this a couple different ways. As you can see my my code, I attempted to control the way the fields display with twig.

I have also tried the conditional\_fields module and set the following dependencies:

Cond. 1

* Target Field: field\_callout\_link
* Controlled By: field\_callout\_link\_control
* Description: !disabled
* Value: \[corresponding radio button is selected\]

Cond. 2

* Target Field: field\_small\_callout\_button\_link
* Controlled By: field\_callout\_link\_control
* Description: !disabled
* Value: \[corresponding radio button is selected\]

The behavior I see is that only the field field\_callout\_link displays on page render - regardless of which radio button is selected.

How can I control which field(s) display when the page renders based on radio button selection?

# Answer
> 1 votes
You don't need conditional fields for this. The simplest way to do this IMO is just look at the values either in the Twig file, or create a new variable in a preprocess function to indicate what to do.

Example:

```
{% if node.field_callout_icon or node.field_callout_text %}
  {% if node.field_callout_link_control.value == 'A single large button link' %}
    markup
  {% elseif ... %}
    markup
  {% endif %}
{% endif %}

```

Or you can preprocess the node and look at the field value there:

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

  $field_value = $node->get('field_name')->getValue();
  // .. do stuff with the field value
  $variables['my_new_flag'] = 'some value or bool';
}

```

Then in the node twig, if its a bool:

```
{% if my_new_flag %}

```

Or if you assigned a value:

```
{% if my_new_flag == '...' %}

```

One thing I would advise against is looking into the render array to read or look for values. Use the node object or preprocess the node to evaluate the values and create new variables if you need them.

Here is a real example I am using which seems very similar to yours. I have a select field in a node type that indicates if the content is a service or a tool. Depending on which, I need to output the right SVG file next to the title. I am checking the value and creating a variable for the template:

**mytheme.theme:**

```
/**
 * Implements hook_preprocess_node().
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];

  if ($node->getType() == 'services') {
    $variables['icon_type'] = $node->get('field_service_or_tool')->value;
  }
}

```

**The node type twig file:**

```
{% if icon_type == 'service' %}
  {% include "@mytheme/svg/general/service.html.twig" %}
{% else %}
  {% include "@mytheme/svg/general/tool.html.twig" %}
{% endif %}

```

I could just check that in the twig as well, but it keeps the template cleaner / easier to read in my opinion.

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


# Question
Title: Theming a views field output using views-view-fields.html.twig
I am trying to customize a views output on a view page to wrap the fields in custom markup. I need to group a set of fields to achieve the desired layout like so:

Example:

```
   <div class="wrapper">
       {{ field.[field_name_1].content }}
   </div>
   <div class="wrapper2">
       {{ field.[field_name_2].content }}
       {{ field.[field_name_3].content }}
       {{ field.[field_name_4].content }}
   </div>

```

This is what I have come up with so far:

```
{% if view.projects_page -%}
    <div class="project-img columns large-8 medium-12 small-12">
        {{ field.field_project_image.content }}
    </div>
    <div class="description columns large-4 medium-10 small-12">
        {{ field.field_project_header.content }}
        {{ field.field_sub_header.content }}
        {{ field.field_short_project_description.content }}
    </div>
{%- endif %}

```

This doesn't throw any errors but also doesn't seem to work because {% if view.projects\_page -%} does not target the view in the way I thought it would.

So the question is - How do I detect the view with a conditional so I get the output desired above?

# Answer
You need to refer documentation for the working with twig template. Here you can use conditional twig :

Twig: `{% if field.[field_name].content is not empty %} field.[field_name].content {% endif %}`
> 0 votes

# Answer
Sorry, but this is confusing me. Do you really mean views-view-fields.html.twig?
Because you reach the fields like
`{{ fields.[field_name].content }}` and not
`{{ field.[field_name].content }}` and inside the "for" you can test with
`{% if field == fields.[field_name] }}`

**EDIT:**
Ah and try

```
{{ kint(row.[field_name] ,row._entity.get('[field_name]').value) }}

```

Because when you need to check for a value and you have twig in development mode (literally spoken:
`twig.config:
 debug: true`
) you will get the template suggestions in field.content. So when you are checking for the nid it would be
`{% if row.nid == 900 %} Do someting {% endif %}`
Greeeeetings
> 0 votes

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


# Question
Title: Search API view doesn't display placed block
Using Drupal 8.6 here and going mad with this:

I installed Search API module that has Database Search and Database Search Default included.

I can't install Database Search Default for the following reason "Content type article not found. Database Search Defaults module could not be installed.

Content type page not found. Database Search Defaults module could not be installed.".

I don't know what content type article or content type page the message is referring to

Another strange thing that i noticed is that i am not able to preview fulltext with "expose filter to visitiors" on my view and also i can't see the block in my page tho i place it on block layout.

Can someone please tell me how do i display the block in the block layout?

Thank you for reading,

# Answer
Database Search Default module expects the page and article content types that exist with the Standard Drupal install. You should be able to recreate these content types (and then later delete them) if you want to install that module. You should create `Page|page`, `Article|article` and keep both with the default `body` field. *I think* that'll be enough to let you install the Database Search Default module and see the configuration. You'll probably want to remove the configuration for page and article from the search configuration before you delete the content types.

If you don't choose to expose your form in block then you cannot place the form as a block on a page. If you're search results view is a block then *I believe* choosing to expose the form as a block will not work at all. If you want to expose the view as a block, you'll want to be sure that "Exposed form in block: No." Alternatively, if you're view is a page and you want your form to be a block, "Exposed form in block: Yes" and make sure Ajax is not enabled. (Afaik, Exposed form in block and ajax are not compatible at this time.
> 1 votes

---
Tags: views, 8, search
---


title: Page not found after installation

text:
# Question
Title: Page not found after installation
I am totally new to Drupal. After following the installation instructions, I have access to my site on Drupal. However, I am directed to an error page when I tried to click on Content Tab. The error page indicates "The requested URL /drupal-8.5.1/admin/content was not found on this server."

I have tried the following

* uncomment RewriteBase /drupal and change *drupal* to the name of my subdirectory *drupal8.5.1*

I have attached a copy of htaccess file in case it's required. Appreciate if anyone can help.

Thanks

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock))$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
  </IfModule>
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Add correct encoding for SVGZ.
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

# Most of the following PHP settings cannot be changed at runtime. See
# sites/default/default.settings.php and
# Drupal\Core\DrupalKernel::bootEnvironment() for settings that can be
# changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value assert.active                   0
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
  # PHP 5.6 has deprecated $HTTP_RAW_POST_DATA and produces warnings if this is
  # not set.
  php_value always_populate_raw_post_data   -1
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Set a fallback resource if mod_rewrite is not enabled. This allows Drupal to
# work without clean URLs. This requires Apache version >= 2.2.16. If Drupal is
# not accessed by the top level URL (i.e.: http://example.com/drupal/ instead of
# http://example.com/), the path to index.php will need to be adjusted.
<IfModule !mod_rewrite.c>
  FallbackResource /index.php
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "/\.|^\.(?!well-known/)" - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/foo will be redirected to http://example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /drupal-8.5.1
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Redirect common PHP files to their new locations.
  RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]
  RewriteCond %{REQUEST_URI} ^(.*)?/(rebuild.php)
  RewriteCond %{REQUEST_URI} !core
  RewriteRule ^ %1/core/%2 [L,QSA,R=301]

  # Rewrite install.php during installation to see if mod_rewrite is working
  RewriteRule ^core/install.php core/install.php?rewrite=ok [QSA,L]

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Various header fixes.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
  # Disable Proxy header, since it's an attack vector.
  RequestHeader unset Proxy
</IfModule>

```

# Answer
A few questions:

* Do you have the rewrite module for apache2 installed and enabled?
* What installation instructions did you follow?
* Is this a local stack or a server?
* What operating system are you using?
> 0 votes

---
Tags: installation
---


# Question
Title: How to display the profile url in the comments?
I have the module :

https://www.drupal.org/project/profile

https://www.drupal.org/project/twig\_tweak

Here is the twig file of my comments :

```
{#
/**
 * @file
 * Default theme implementation for comments.
 *
 * Available variables:
 * - author: Comment author. Can be a link or plain text.
 * - content: The content-related items for the comment display. Use
 *   {{ content }} to print them all, or print a subset such as
 *   {{ content.field_example }}. Use the following code to temporarily suppress
 *   the printing of a given child element:
 *   @code
 *   {{ content|without('field_example') }}
 *   @endcode
 * - created: Formatted date and time for when the comment was created.
 *   Preprocess functions can reformat it by calling format_date() with the
 *   desired parameters on the 'comment.created' variable.
 * - changed: Formatted date and time for when the comment was last changed.
 *   Preprocess functions can reformat it by calling format_date() with the
 *   desired parameters on the 'comment.changed' variable.
 * - permalink: Comment permalink.
 * - submitted: Submission information created from author and created
 *   during template_preprocess_comment().
 * - user_picture: The comment author's profile picture.
 * - status: Comment status. Possible values are:
 *   unpublished, published, or preview.
 * - title: Comment title, linked to the comment.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class may contain one or more of the following classes:
 *   - comment: The current template type; for instance, 'theming hook'.
 *   - by-anonymous: Comment by an unregistered user.
 *   - by-{entity-type}-author: Comment by the author of the parent entity,
 *     eg. by-node-author.
 *   - preview: When previewing a new or edited comment.
 *   The following applies only to viewers who are registered users:
 *   - unpublished: An unpublished comment visible only to administrators.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 * - content_attributes: List of classes for the styling of the comment content.
 * - title_attributes: Same as attributes, except applied to the main title
 *   tag that appears in the template.
 * - threaded: A flag indicating whether the comments are threaded or not.
 *
 * These variables are provided to give context about the parent comment (if
 * any):
 * - comment_parent: Full parent comment entity (if any).
 * - parent_author: Equivalent to author for the parent comment.
 * - parent_created: Equivalent to created for the parent comment.
 * - parent_changed: Equivalent to changed for the parent comment.
 * - parent_title: Equivalent to title for the parent comment.
 * - parent_permalink: Equivalent to permalink for the parent comment.
 * - parent: A text string of parent comment submission information created from
 *   'parent_author' and 'parent_created' during template_preprocess_comment().
 *   This information is presented to help screen readers follow lengthy
 *   discussion threads. You can hide this from sighted users using the class
 *   visually-hidden.
 *
 * These two variables are provided for context:
 * - comment: Full comment object.
 * - entity: Entity the comments are attached to.
 *
 * @see template_preprocess_comment()
 *
 * @ingroup themeable
 */
#}

<article{{ attributes.addClass('js-comment comment--field-article-commentaire') }}>

  <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bs-region-comment">

    <div class="col-xs-3 col-sm-3 col-md-2 col-lg-2 bs-left">
      <div class="row">

        {{ drupal_entity('user', comment.uid.target_id, 'comment_teaser_relation') }}
        {{ author }}

        <div class="bs-field-link">
          <a href="{{ ??? URL PROFILE USER ??? }}" title="{{ ??? USERNAME ??? }}"></a>
        </div>

      </div>
    </div>

    <div class="col-xs-9 col-sm-9 col-md-10 col-lg-10 bs-right">
     <b><i>{{ created }}</i></b>
     {{ content.field_article_commentaire }}
     {{ content.links }}
     {{ content.flag_report_comment }}
    </div>

  </div>

</article>

```

I want to display instead of :

```
{{ ??? URL PROFILE USER ??? }}

```

The url of the profile (profil\_personnel) of the author of the comment.

On the `comment_teaser_relation` view of the user account, there is a profile field `personnel` that I activated.

Here is the twig file of the user account :

```
{#
/**
 * @file
 * Default theme implementation to present all user data.
 *
 * This template is used when viewing a registered user's page,
 * e.g., example.com/user/123. 123 being the user's ID.
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 *   print a subset such as 'content.field_example'. Fields attached to a user
 *   such as 'user_picture' are available as 'content.user_picture'.
 * - attributes: HTML attributes for the container element.
 * - user: A Drupal User entity.
 *
 * @see template_preprocess_user()
 *
 * @ingroup themeable
 */
#}
<article{{ attributes.addClass('user--comment-teaser-relation') }}>

    {{ content.profile_personnel }}
    {{ content.user_picture }}

</article>

```

If I enter the code `{{ content.profile_personnel }}` in the twig file of the user display, the profile is displayed.

How to display only the profile link ?

And how to display the profile link of the author of the comment, in the comments twig ?

Here is the twig of the profile if it can help :

```
{#
/**
 * @file
 *
 * Default theme implementation for profiles.
 *
 * Available variables:
 * - content: Items for the content of the profile.
 *   Use 'content' to print them all, or print a subset such as
 *   'content.title'. Use the following code to exclude the
 *   printing of a given child element:
 *   @code
 *   {{ content|without('title') }}
 *   @endcode
 * - attributes: HTML attributes for the wrapper.
 * - profile: The profile object.
 * - url: The profile URL, if available.
 *
 * @ingroup themeable
 */
#}

```

# Answer
> 0 votes
To link to this in the twig file, you can use the `path` function like so:

```
<a href="{{ path('entity.profile.canonical', {'profile': comment.uid.content.profile_personnel.target_id}) }}">{{ 'View user profile'|t }}</a>

```

I am guessing that `comment.uid.content.profile_personnel.target_id` returns the entity id of the profile. This will create a `/profile/{id}` href where `{id}` is the profile id.

I don't use twig tweak, but I assume it would be:

```
{{ drupal_entity('profile', comment.uid.content.profile_personnel.target_id) }}

```

But I think that would embed the profile, not *link* to it, which is why you want something like the `path` function.

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


# Question
Title: Setting multiple checkbox values with form_set_value
I have a field that is a taxonomy term reference with a checkbox widget that allows multiple values.

I am looping through a json structure, finding the associated code value and then setting the value on the checkbox widget in the form with a case statement.

My problem is it's only setting the last value, not all the values. Here is the code. In this case where the hosts array contains all three values, I would expect all checkboxes associated with all three taxonomy terms to be checked. Only the last one is checked.

```
//json structure
"hosts": [
    {
        "alias": "external",
        "url": "abc.com"
    },
    {
        "alias": "internal",
        "url": "abc.com"
    }
    {
        "alias": "local",
        "url": "abc.com"
    }
]

          //php
          $hosts = $response->{'hosts'};

           foreach($hosts as $host){

           $alias = $host->alias;

            switch($alias){
                case "external":
                    form_set_value($form['field_proxy_host'], array(LANGUAGE_NONE => array(0 => array('tid' => '758'))), $form_state);
                break;
                case "internal":
                    form_set_value($form['field_proxy_host'], array(LANGUAGE_NONE => array(0 => array('tid' => '759'))), $form_state);
                break;
                case "local":
                    form_set_value($form['field_proxy_host'], array(LANGUAGE_NONE => array(0 => array('tid' => '760'))), $form_state);
                break;

            }

        }

```

# Answer
> 2 votes
I believe you want to pass an array with all values to `form_set_value()` as the function is setting the value, not appending to it. I would alter your setup to build an array of values with your switch/foreach block and then pass that array in a single `form_set_value` call below the switch, outside of the foreach.

Update your your foreach / switch like so:

```
$host_values = [];
foreach($hosts as $host){
  switch($host->alias){
    case "external":
      $host_values[] = ['tid' => '758'];
      break;
    case "internal":
      $host_values[] = ['tid' => '759']
      break;
    case "local":
      $host_values[] = ['tid' => '760']
      break;
    default:
      break;
  }
}

form_set_value($form['field_proxy_host'], [LANGUAGE_NONE => $host_values], $form_state);

```

---
Tags: forms, taxonomy-terms
---


# Question
Title: Install Drush on shared hosting with SSH access?
I have SSH access on shared hosting and I followed this guide to install the composer: https://getcomposer.org/download/

```
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

```

I got the composer.phar installed/downloaded into custom dir `/composer/composer.phar`

And it works if you run it `php composer.phar`.

Then I ran `php composer.phar require drush/drush:7.x` to install drush. And it installed in the `/composer/vendor/bin`.

Now, if I run `php composer.phar drush` I get error:

```
[Symfony\Component\Console\Exception\CommandNotFoundException]
  Command "drush" is not defined.

```

I set paths `PATH=$PATH:~/composer/vendor/bin` and `PATH=$PATH:~/composer/`

If I run just `composer` or `drush` I get `The program 'composer' is currently not installed. To run 'composer' please ask your administrator to install the package 'composer'`.

# Answer
Rename `composer.phar` to `composer` and move it to `$HOME/bin` then make sure `$PATH` contains `$HOME/bin`. You can do that by putting the line `export PATH=$PATH:$HOME/bin/vendor/bin` in your `.bashrc` and then doing a `source .bashrc`

Once you can run `echo $PATH` and see a string containing your home directory followed by `/bin/vendor/bin` and *if* you have moved `composer.phar` there under the name `composer` you know that the computer will look there when you run a command (`composer` for example).

The following command is what worked for me to install Drush with composer:

`composer global require drush/drush:dev-master`
> 3 votes

# Answer
you can also install manually as long as you have ssh access

```
# get drush latest 8 version
# drush 8 works with D8, D7 and D6
# https://github.com/drush-ops/drush/releases
wget https://github.com/drush-ops/drush/releases/download/8.4.11/drush.phar

# make it executable
chmod +x drush.phar;

# move it to home directory or any other directory
mv drush.phar ~/drush;

# go to that directory
cd ~

# find out the path to the directory
pwd
# the output would look similar to this
# /home/your_user

# edit the following file
nano .bashrc
# or
# nano .bash_profile

# add this the end of the file
alias drush='/home/your_user/drush';

# use the alias you just setup
source ~/.bashrc;

```
> 5 votes

---
Tags: 7, drush
---


# Question
Title: Twig finds if statement true whether or not field has value
I have a paragraphs field that contains a sub-title which is optional. My code below still prints out the h3 tag whether or not the sub-title has any value. Any idea why this is happening as I need to hide the h3 html if there is no value, thanks.

```
{% block content %}
    <div class="bene">
        <div class="container">
            <h2>{{ content.field_title }}</h2>
            {% if content.field_sub_title %}
            <h3>{{ content.field_sub_title }}</h3>
            {% endif %}
            <div class="row">
              {{ content.field_prod }}
            </div>
        </div>
    </div>
{% endblock %}

```

# Answer
> 1 votes
Look at the object itself not the render array:

```
{% if paragraph.field_sub_title %}
  <h3>{{ content.field_sub_title }}</h3>
{% endif %}

```

---
Tags: theming, paragraphs
---


# Question
Title: How do I limit the number of rows affected from the query?
In my custom module for Drupal 8, I am using the following code.

```
$query = $this->connection->select('node_field_data', 'nf_data');
$result = $query->execute();

```

I want to get the first 500 rows. I tried with `$query->limit(50)`, but that gives the following error.

> Call to undefined method Drupal\Core\Database\Driver\mysql\Select::limit()

What is the correct code to get the first 500 rows?

# Answer
See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Select.php/class/Select/8.6.x

```
$query->range(0, 500);

```
> 20 votes

# Answer
The object returned from `$this->connection->select()` is an object of a class that extends `\Drupal\Core\Database\Query\Select` (not `\Drupal\Core\Entity\Query\QueryInterface` which is for entity queries). In your case, since you are using MySQL as database engine, that class specifically is `\Drupal\Core\Database\Driver\mysql\Select`, as the error you quoted says.

The method you are looking for is `Select::range()`.

You are confusing it with `PagerSelectExtender::limit()`, used to limit the number of elements per page, and implemented from the `PagerSelectExtender` class. To use this method, you need to add a pager to the query, though.
> 3 votes

---
Tags: 8, database
---


title: Module css not displayed

text:
# Question
Title: Module css not displayed
I have created a custom module for Drupal 7 that displays a block, and I would like to add some CSS. The problem is that the CSS is not working.

This is the module code.

```
/**
 * Implements hook_block_info().
 */
function filter_search_form_block_info() {
  $blocks['filter_search_form'] = array(
    'info' => t('Filter Search Form'),
    // 'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function filter_search_form_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'filter_search_form':
      $block['subject'] = t('block Title');
      $block['content'] = array(
        '#markup' => '<div id="filter-search-form">
          <form id="filter-search-form-form">
            <div class="form-group">
              <input type="text" class="form-control form-text" name="txt_search">
                <label for="chk_brigadista">' . t('Brigadista') . '</label>
                <input type="checkbox" class="form-control" name="chk_brigadista">
                <label for="chk_fuente">' . t('Fuente Documental') . '</label>
                <input type="checkbox" class="form-control" name="chk_fuente">
                <label for="chk_encuadramiento">' . t('Encuadramiento Militar') . '</label>
                <input type="checkbox" class="form-control" name="chk_encuadramiento">
                <input type="submit" value="' . t('search') . '">
              </div>
            </form>
          </div>',
          '#attached' => array(
            'css' => array(
              drupal_get_path('module', 'filter_search_form') . '/css'
             ),
             'js' => array(
               drupal_get_path('module', 'filter_search_form') . '/js/'
             ),
           ),
         );
         break;
    }

    return $block;
}

```

This is the module .info file.

```
name = Filter Search Form
description = Module that create a Block for Filter Search Form, form with checboxes to filter search.
core = 7.x
package = CUSTOM

scripts[] = 'js/filter_search_form.js'

stylesheets[all][] = css/filter_search_form.css

```

These are the CSS styles.

```
#filter-search-form {
    float:left;
    background-color:red;
}

```

Why aren't the CSS styles applied to the module output? I cleared the cache with `drush cc all`.

The structure is:

* css/
    + filter\_search\_form.css
* js/
    + filter\_search\_form.js
* filter\_search\_form.info
* filter\_search\_form.module

# Answer
> 1 votes
You may need to rename the CSS file.

> The word "style" can not be used in the name, like "myown\_style.css". It will conflict with the default style.css. Anyhow, myownstyle.css will work.

See Adding style sheets from .info files for more details.

---
Tags: blocks
---