title: Image styles are not beeing generated

text:
# Question
Title: Image styles are not beeing generated
I have a problem where Drupal tries to access the files in the "styles/stylename" directory, but they are not there since they aren't beeing generated. I allready tried changing the theme for a while (image style (imagecache) images are not being created) and also tried creating the style folder, changing permission and editing the .htacces file (https://www.drupal.org/forum/support/post-installation/2015-06-16/image-styles-not-generating#comment-11859066). I also tried a few other things, nothing seems to work.
Maybe usefull information: the images are created in a directory based on the month and year.
for example "sites/default/files/2019-07/filename.png"

edit: When accessing the url of the image style it returns:

> Error: Class 'lsolesen\pel\PelJpeg' not found in Drupal\file\_mdm\_exif\Plugin\FileMetadata\Exif-\>getFile() (line 108 of modules/file\_mdm/file\_mdm\_exif/src/Plugin/FileMetadata/Exif.php). Drupal\file\_mdm\_exif\Plugin\FileMetadata\Exif-\>getFile() (Line: 127) Drupal\file\_mdm\_exif\Plugin\FileMetadata\Exif-\>doGetMetadataFromFile() (Line: 280) Drupal\file\_mdm\Plugin\FileMetadata\FileMetadataPluginBase-\>loadMetadataFromFile() (Line: 377) Drupal\file\_mdm\Plugin\FileMetadata\FileMetadataPluginBase-\>getMetadata('Orientation') (Line: 183) Drupal\file\_mdm\FileMetadata-\>getMetadata('exif', 'Orientation') (Line: 39) Drupal\image\_effects\Plugin\ImageToolkit\Operation\gd\AutoOrient-\>execute(Array) (Line: 172) Drupal\Core\ImageToolkit\ImageToolkitOperationBase-\>apply(Array) (Line: 124) Drupal\Core\ImageToolkit\ImageToolkitBase-\>apply('auto\_orient', Array) (Line: 143) Drupal\Core\Image\Image-\>apply('auto\_orient') (Line: 138) Drupal\image\_effects\Plugin\ImageEffect\AutoOrientImageEffect-\>applyEffect(Object) (Line: 302) Drupal\image\Entity\ImageStyle-\>createDerivative('public://2018-05/02\_1.jpg', 'public://styles/project\_gallery\_image/public/2018-05/02\_1.jpg') (Line: 161) Drupal\image\Controller\ImageStyleDownloadController-\>deliver(Object, 'public', Object) call\_user\_func\_array(Array, Array) (Line: 123) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() (Line: 582) Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 124) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) (Line: 97) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() (Line: 151) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 68) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 99) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 52) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 693) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

# Answer
Try to installed missed library by the following comment on the root of your drupal website :

```
composer require drupal/image_effects:^2

```
> 1 votes

---
Tags: 8
---


title: Set a specific changed date for a node

text:
# Question
Title: Set a specific changed date for a node
I am creating nodes programatically based on the feed from an external api. I have managed to create all nodes, assign field values and also set the `created` date. Now my problem is that I also need to set the `changed` date of each node to match the value returned from the feed. I have tried to set this value before saving the node without any success:

```
// $data contains the release information used to create and populate the node
$node = new stdClass();
$node->title = $data->Release->Title;
$node->type = 'release';
node_object_prepare($node);
$node->status = NODE_PUBLISHED;
$node->uid = 1;
$node->language = LANGUAGE_NONE;

// handle any field data - not really important
handleFields($node, $data);

// submit the node
$node = node_submit($node);

$node->created = strtotime($data->Release->PublishDate);
// here I'm trying to set the changed value for the node
$node->changed = strtotime($data->Release->LastChangeDate);

// finally save the node
node_save($node);

```

Would be nice if anyone have a solution to this problem. Perhaps I can make a raw query against the database in order to update the `changed` date of the node? The reason I need to set this value is because later on it will be used to compare against the modification date of a release in the feed so I can decide if the node needs to be updated or not. I know I could use a custom field for this purpose, storing the releases modification time and then compare against this value instead of the changed column in the node table.

# Answer
> 7 votes
The code you are using doesn't work as expected because you first set `$node->changed` and then call `node_save()`, which sets `$node->changed` to `REQUEST_TIME` using the following code.

```
// Set the timestamp fields.
if (empty($node->created)) {
  $node->created = REQUEST_TIME;
}
// The changed timestamp is always updated for bookkeeping purposes,
// for example: revisions, searching, etc.
$node->changed = REQUEST_TIME;

$node->timestamp = REQUEST_TIME;
$update_node = TRUE;

// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

```

If you want to set `$node->changed`, you would need to implement `hook_node_presave()`, which is invoked right after `node_save()`. For example, with the code you show, I would add the following line.

```
$node->release_change_date = strtotime($data->Release->LastChangeDate);

```

In `hook_node_presave()`, you would then use the following code.

```
$node->changed = $node->release_change_date

```

# Answer
> 0 votes
For drupal 7:

```
$update_node = node_load($nid_to_change);
$update_node->changed = $timestamp_in_unix_form;
drupal_write_record('node', $update_node, 'nid');

```

This is very dumb routine; it's bypassing a lot of error checking in node\_save(). It expects a complete, intact node. so it's up to you to make sure the node integrity is good. Otherwise you **risk corrupting your database.**

---
Tags: 7, nodes
---


# Question
Title: Is jQuery .once() needed if we filter by context?
When implementing a Drupal behavior, a selector can use the 'context' parameter to let the behavior only apply to new elements. On page load the context is the document (I think), on ajax load it is the new ajax content.

```
Drupal.behaviors.my_behavior = {
  attach: function attach(context, settings) {
    $('.my-selector', context).each(function() {..});

```

Until now I thought that this alone is sufficient to make sure the behavior runs only once per element.

But in Drupal core and contrib, I see a lot of cases where context is used in combination with .once(), like so:

```
Drupal.behaviors.my_behavior = {
  attach: function attach(context, settings) {
    $('.my-selector', context).once(function() {..});

```

Is this ever necessary? Or is 'context' sufficient? And if it is not necessary, why is it used so much in core and contrib?

If it is necessary, does this also apply to click handlers? E.g. would the following cause duplicated click handlers in some cases?

```
Drupal.behaviors.my_behavior = {
  attach: function attach(context, settings) {
    $('.my-selector', context).click(function() {..});

```

NOTE: A secondary question would be if 'context' is still necessary if we use 'once()'. My answer to this is: Even if it is not necessary, it is still a good idea because it reduces the search space for jQuery on subsequent calls, thus reducing client-side energy consumption.

NOTE: I encountered this question on D7, but it might equally apply to D8.

# Answer
> 5 votes
The short answer, is 'yes'. The longer answer is that if all developers properly used the API, you would likely not have to use `$.once()`. However, you cannot count on developers using the API correctly, so `$.once()` insulates you against that.

This is because the `context` passed to `Drupal.behaviors` is the part of the DOM passed by developers when calling `Drupal.attachBehaviors()`. However, a lot of the documentation on the web has not specifically stated this, resulting in many developers not passing any value to `Drupal.attachBehaviors()`. If no value is passed, then the entire DOM becomes the `context`. This means that your code could be passed through your handler multiple times. This is why `$.once()` is used.

---
Tags: 7, javascript
---


title: How do I get the cache string?

text:
# Question
Title: How do I get the cache string?
In Drupal 8, CSS files, images and many other files, are cached by appending a token at the end, as in */sites/default/files/styles/lrg\_thumbnail/public/p2i-product\_1\_zoomout.png?itok=DroPCbms*.

Notice the *itok=DroPCbms* part.

What Drupal function returns this code?

# Answer
Contrary to CSS/JS the `itok` is not for caching, but for DoS protection, see this question
Why are tokens added to image URLs?

The token is generated in
https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Entity%21ImageStyle.php/function/ImageStyle%3A%3AgetPathToken/8.2.x
> 3 votes

---
Tags: 8
---


# Question
Title: Using the menu API, how do I get only the enabled links?
Using the code below I am able to get all the titles and links from the main menu, however, I only need the enabled ones. I have been searching for an answer for a couple of days but have been unable to find any.

```
$tree = \Drupal::menuTree()->load('main', new MenuTreeParameters());
foreach ($tree as $item) {
  $title = $item->link->getTitle();
  $url_object = $item->link->getUrlObject();
  array_push($menulinks, $title);
  array_push($urlformenulink, $url_object);
}

```

Please assist.

# Answer
Set onlyEnabledLinks() on the menu tree parameters:

```
$parameters = new MenuTreeParameters();
$parameters->onlyEnabledLinks();
$tree = \Drupal::menuTree()->load('main', $parameters);

```
> 1 votes

---
Tags: navigation
---


# Question
Title: What does extension-provided configuration mean in Config Snapshot?
> Configuration Snapshot enables snapshotting of **extension-provided** configuration. It's used by Configuration Synchronizer to support updating configuration provided by modules, themes, and the install profile.

Recently I checked my database and found there are two tables
config
and
config\_snapshot
I found that the module Config Snapshot creates the table config\_snapshot table
While reading through project page text,I see it says "it enables snapshotting of **extension-provided** configuration" What does extension-provided configuration mean ?

# Answer
As commented by Clive,

> “Extension” seems just to be being used as a catch-all term for modules, themes and installation profiles. Those three are the only things that can provide config outside of core, so it seems a safe bet
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: How to rebuild route cache programmatically
I installed a module quizzard and after uninstallation I am getting this error

```
Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "quizard.quizard_config_form" does not exist." at /home/paddu008/public_html/core/lib/Drupal/Core/Routing/RouteProvider.php line 190

```

So how do I rebuild route cache programmatically.

# Answer
If you would like to clear route cache programmatically in drupal 8, use the following:

```
\Drupal::service('router.builder')->rebuild();

```
> 4 votes

# Answer
Rebuild cache programmatically execute: `drush cr`
> 1 votes

# Answer
**On Exact Cases** such as `hook_preprocess_pager(&$variables) {...`

You can also use

> `$variables['#cache']['max-age'] = 0;
>  \Drupal::service('page_cache_kill_switch')->trigger();
>  cache_clear_all() // For Drupal-7
>  drupal_flush_all_caches() // For Drupal-8`
>
> You can also use this as guide - **https://stackoverflow.com/questions/43608217/how-to-clear-cache-programmatically-in-drupal-8**
> 1 votes

---
Tags: 8
---


# Question
Title: Can we have multliple routing.yml files in a single module?
I have more than 50 menus which I need to create custom. as per the module structure, we need to create routing.yml in root folder. but I want to do something like this below:

```
   myModule
      -  products(folder)
              - routing.yml
              - src(folder)
                - productController
      -  brands(folder)
              - routing.yml
              - src(folder)
                - brandsController.php
      - myModule.info.yml
      - myModule.module

```

is it way to do achive something like this.

I just want to make code seperation and avoid to add all routes in routing.yml

# Answer
> 3 votes
Instead of adding multiple routing files, you can define products, brands as modules inside your main module and then can define routing file for each of them like what is done in aggregator module in core.

# Answer
> 1 votes
The routing.yml can split by multiple files. You can include separate routing files in your routing.yml file.

```
acme_demo_user:
  resource: "@acmeDemoBundle/Resources/config/routing/user_routing.yml"
  prefix: /user
acme_demo_vehicles:
  resource: "@acmeDemoBundle/Resources/config/routing/vehicles_routing.yml"
  prefix: /vehicles
.............
.............

```

It would works in symfony not sure in drupal 8, I hope it would works in drupal 8 too. Source : https://stackoverflow.com/questions/16355385/symfony2-splitting-routing-yml-in-multiple-files

# Answer
> 0 votes
the included routing files in a single file reouting.yml does not work under drupal because in drupal there is not the notion of bundle

I tested by passing the module name and also the namespace but it does not work

```
myroute_form:
  resource: "@module_name/routing/salesforce_front_routing.yml"

myroute_form2:
  resource: "@Drupal/module_name/routing/salesforce_front_routing.yml"

```

---
Tags: 8, routes
---


title: How to enable inactive fields

text:
# Question
Title: How to enable inactive fields
I have a content type with a field that has been set to inactive. This happened after I reverted my feature in an attempt to undo a change I made to the content type.

The error message given is the following:

> This content type has inactive fields. Inactive fields are not included in lists of available fields until their modules are enabled.

I've disabled and re-enabled the feature module, but the field is still inactive.

How can I activate my field?

# Answer
> 4 votes
I've had this quite a few times, I'm not sure what the initial problem is but I've solved it by doing either one of the following:

1. Disabling the feature and re-enabling it
2. If above fails disable delete content type then re-enable (not an option if there existing content on the site)
3. Manually editing the content\_field\_instance table (D6) and enabling it there.

# Answer
> 1 votes
Try: http://drupal.org/project/cck\_manage\_inactive.

Once you activate the module, the module will expose a new tab: "Manage inactive fields", on the content type administration page, usually: admin/content/node-type//fields-inactive.

It will allow you to completely remove, or re-activate the field(s).

Good luck!

# Answer
> 0 votes
Everything related to fields configurations is inside field\_config table. All the following columns should be correct for field to appear in entity/content type fields list : active : must be 1
storage\_type : sql\_field\_storage or an alternative
storage\_module : sql\_field\_storage or an alternative
storage\_active : must be 1
deleted : must be 0

# Answer
> 0 votes
**"I fixed the problem by turning off ALL CCK modules and then turning them back on." http://drupal.org/node/883354**

It seems that when I upgrade the core of Drupal, somehow the CCK modules where, automatically, activated before other modules that enable special field types.

# Answer
> 0 votes
This is a really old question but it was the one I kept finding whilst soul searching on Google.

I was observing the same as OP. Most fields wasn't being displayed.

I was also seeing this on lots of pages.

Invalid argument supplied for foreach() in field\_attach\_load() (line 660 of /var/www/vhosts/hicrowds.com/httpdocs/qa.hicrowds.com/modules/field/field.attach.inc)

All the modules providing the fields were enabled.

When flushing the cache via Drush and the UI, it kept throwing a site error.

So I tried truncating all the cache tables manually. Still had a few errors but less, so I re-saved the modules page. Then finally all the fields appeared again.

So something else to try I guess if you're hitting this.

# Answer
> -1 votes
Check the `content_field_instance_delete()` function.

---
Tags: entities, features
---


title: Hide a region with empty view in it

text:
# Question
Title: Hide a region with empty view in it
I have a region `page_intro` where I display a view, with some CSS on it. When the view is empty (return no result), the region is still displayed (All html code before and after `{{ page.page_intro }}`). Is there a way to compltetly remove it when the view is empty ?

template :

```
{% if page.page_intro %}
    {# #page-intro #}
    <div id="page-intro" class="clearfix">
        <div class="container-fluid">
            <div class="row">
                {# #page-intro-inside #}
                <div id="page-intro-inside" class="col-md-10 col-md-offset-1 clearfix">
                    {{ page.page_intro }}
                </div>
                {# EOF: #page-intro-inside #}
            </div>
        </div>
    </div>
    {# EOF: #page-intro #}
{% endif %}

```

I'm on Drupal 8.2.0 version.

# Answer
> 1 votes
I would suggest you use the views template for your view (views-view--page-intro.html.twig, and put the wrapping markup in there, rather than in the page template.

```
{% if rows %}
    <div id="page-intro" class="clearfix">
        <div class="container-fluid">
            <div class="row">
                <div id="page-intro-inside" class="col-md-10 col-md-offset-1 clearfix">
                    {{ rows }}
                </div>
            </div>
        </div>
    </div>
  {% endif %}

```

turn on twig debugging to see the template suggestions in your page markup. this will be the default.services.yml file in your config directory where you have settings.php

```
 twig.config:
    debug: true

```

# Answer
> 1 votes
I'd do it like this. Example below is used for node templates:

```
use \Drupal\views\Views;

function MYTHEME_preprocess_node(&$variables) {
  // make the result count available as a variable for a certain content type
  if($node->getType() == 'news') {
    $view = Views::getView('related_news');
    $view->setDisplay('default');
    // contextual relationship filter
    $view->setArguments([$variables['node']->id()]);
    $view->execute();
    $variables['related_news_count'] = count($view->result);
    $variables['related_news'] = $view->render();
  }
}

```

Then, in your node

```
{% if related_news_count > 0 %}
  // Region stuff here
{% endif %}

```

https://stefvanlooveren.me/blog/get-views-row-count-twig-drupal-8

# Answer
> 0 votes
You could do it purely with CSS, just make it so the region itself only gets its width/height from the views rows.

You could also set the region to "display:none;" then use Javascript to detect if there's any views rows and change the display if it finds one.

I'm not sure if there's a simple solution in PHP. You could recreate the views db query in your theme's preprocessing, and use that to hide the region if it doesn't find any results.

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


# Question
Title: How can I load all Media of a certain type?
I am trying to load all media items of a certain type but I can't find how to.

Is there a way to set a filtering type on something like

```
$media = Media::loadMultiple();

```

Or do you have to load all media and then filter manually?

# Answer
> 5 votes
If you use entity query you can filter the entities by type before uploading them.

```
$ids = \Drupal::entityQuery('media')
  ->condition('bundle', 'YOUR_TYPE')
  ->execute();

$medias = Media::loadMultiple($ids);

```

---
Tags: 8, media
---


# Question
Title: Rewriting the page path from /my-drupal-project/docroot/user/login to /project/user/login using Drupal 8/Thunder?
I'm helping someone write some ReWriteRules for their Drupal project, but the expected behaviour for:

`ReWriteRule ^my-project/(.*)$ /my-drupal-project/docroot/$1`

isn't happening - there seem to be multiple .htaccess files in the project. Adding the rule to the .htaccess and another in `docroot` takes us to a 404 error page.

I'm gonna assume someone has had to do something similiar in the past, but I can't see anything in my searches that solves the issue.

Any help or direction appreciated.

# Answer
on the root of your Drupal project find `.htaccess` file, then search for `RewriteRule ^ index.php [L]` and after that add the following line and save the file.

```
 ReWriteRule ^my-project/(.*)$ /my-drupal-project/docroot/$1 [R=301,L]

```

make sure clear the drupal cache and check it on a **New incognito window** first. ( sometimes browsers cache the redirects )
> 1 votes

---
Tags: .htaccess
---


title: List files in a directory as a table

text:
# Question
Title: List files in a directory as a table
I created a folder inside of my Drupal directory where my client can directly FTP into and upload or remove PDFs.

What I'm trying to do is create a page called "Documents" which then displays all PDFs in that directory as a table. So when a new PDF is either uploaded or deleted a new row is either added or deleted in the table.

I found this thread here: Can you create a view to display all files within a certain directory? \- And was looking into Filebrowser.

The problem is I want to be able to control the front end look of the table. Because the function of the table would be for users to be able to download and view the PDFs that the client uploaded in the directory.

Would this approach here by my best solution, I'm trying to stay away from using any outside modules. https://stackoverflow.com/questions/8559308/how-can-i-list-files-in-a-directory-using-php

# Answer
> 0 votes
I guess Filebrowser module is what you looking for :

```
This module provides an interface for administrators to expose directories on the file system to users through a file listing as in a FTP application.

You will create one node (node type dir_listing) for each each Directory Listing (DL). Node settings are used to control access and other features of the DL. These settings can vary per node and per user.

This module offers the following features:

Private downloads so that files (such as PHP files) can be downloaded.
File blacklists so that specific files can be removed from directory listings.
Node-based. All features available to nodes, such as path aliasing and access control can be applied to directory listings.
Settings to limit exploration of subdirectories

```

---
Tags: views, theming, nodes, taxonomy-terms, database
---


title: SQL Error when updating to utf8mb4

text:
# Question
Title: SQL Error when updating to utf8mb4
I have successfuly followed the instructions on the Drupal page for updating uft8mb4 except for 1 table which is pulling up the below errror:

https://www.drupal.org/node/2754539

```
Error
SQL query:

ALTER TABLE `file_managed` CONVERT TO CHARACTER SET utf8mb4 COLLATE
utf8mb4_general_ci
MySQL said: Documentation

#1062 - Duplicate entry 'public://listings/4232.jpg' for key 'uri'

```

What do I do to be able to complete the updating?

# Answer
> 1 votes
The field uri has to be unique within the file\_managed table. Apparently, in your old database (before updating to utf8mb4) this index was not created or not active and so your table got "corrupt".

Fix this by renaming the uri field of one of the records that refer to public://listings/4232.jpg to e.g. public://listings/4232\_0.jpg and copying the image /sites/default/files/listings/4232.jpg to /sites/default/files/listings/4232\_0.jpg (assuming that public:// refers to /sites/default/files/).

Note: just deleting one of the duplicate records will result in image/file fields pointing to no longer existing managed files, so better duplicate the file as described above.

If, afterwards, you want to get rid of those duplicate images, you can use my module duplicate images :)

---
Tags: 7
---


# Question
Title: How do I print the payment method name in the order receipt email?
The commerce-order-receipt.html.twig contains a variable called {{ payment\_method }}, which returns no data. Likewise, when I add Payment Method field to my orders table view, it shows no data. Payment Gateway does contain the name of the payment method used in the order. I'd like to print that value in my order receipt email, but cannot seem to find the correct syntax. So far I have tried the following.

```
{{ payment_gateway }}
{{ order_entity.field_payment_gateway }}
{{ order_entity.field_payment_gateway.value }}
{{ field_payment_gateway }}
{{ field_payment_gateway.value }}

```

All of those turn up blank in the email.

How can I show the payment gateway title in the order receipt email?

# Answer
> 0 votes
The patch given in Show payment instructions in the order receipt, comment #10, fixed my issue. It requires patching the commerce\_order.module and commerce\_payment.module files, as well as adding the display code to the order email receipt template file.

---
Tags: 8, commerce
---


title: Securing Admin on separate port

text:
# Question
Title: Securing Admin on separate port
I am attempting to secure the admin pages (/admin/\*) and login page (/user/login) to port 8443. I have successfully done that with the following in apache 2.4:

```
<VirtualHost _default_:443>
    ServerName example.com:443
    ServerAlias drupal
    DocumentRoot "/opt/rh/httpd24/root/var/www/html/example.com/current"
    <LocationMatch /(user|admin)>
            Require all denied
    </LocationMatch>
</VirtualHost>

<VirtualHost *:8443>
    ServerName example.com:8443
    ServerAlias drupal
    DocumentRoot "/opt/rh/httpd24/root/var/www/html/example.com/current"
</VirtualHost>

```

The problem I am having is when I go to https://www.example.com:8443/user/login and login, I am redirected to http://www.example.com:8443/user/1.

This creates a 400 error - Bad request. Trying to serve http content over a SSL port.

How do I tell drupal to stay on https protocol and remain on port 8443?

# Answer
> 0 votes
So I wasn't able to do this on a separate port, but for anyone who needs to secure the login page from public eye, this is what I did.

```
<VirtualHost _default_:443>
  ServerName example.com:443
  ServerAlias drupal
  DocumentRoot "/opt/rh/httpd24/root/var/www/html/example.com/current"
  <LocationMatch /(user|admin)>
        Require all denied
        Require ip 10
  </LocationMatch>
</VirtualHost>

```

This will require the user to be on a local IP. (I am in-housing the site, so when I access the site I'm on a local IP.)

---
Tags: http-request
---


# Question
Title: Role can't see CKeditor options on Body field
Probably a simple setting somewhere, but I can't find it.

On a Drupal 8 site, I have an editor role, to edit/create blog posts. They can see the body field, but it shows as raw html. The wysiwyg CKEditor doesn't appear for them.

The editor role is assigned to the same CKeditor configuration profile as the Administrator. They have ability to to edit the field and the content type. It's just specifically the CKEditor editing that is unavailable to them.

When I look under role permissions, the only option I see relating to any wysiwyg is "Administer Imce File Manager" and toggling this on/off doesn't make a difference.

I've double-checked that the role can edit simple html all the way up to full advanced html.

thoughts?

# Answer
> 1 votes
After some trial-and-error, changing role permissions, I was able to narrow things down.

I have a module called Simplify installed. When the permission "View hidden fields" is UN-checked, the role cannot see CKEditor. When I check that, everything works as intended.

---
Tags: 8
---


# Question
Title: How to get list of all keys defined in the routing e.g path, defaults, options etc and how can we add new custom key?
```
route_with_two_nodes:
  path: '/foo/{node1}/{node2}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::foo'
  options:
    parameters:
      node1:
        type: entity:node
      node2:
        type: entity:node

```

I need to get list of all keys path, defaults, options etc, where is it defined in Drupal Core ? so that if I need to add custom key and extend it

# Answer
Add a route enhancer:

Example how `_form` gets replaced by `_controller`:

*Drupal\Core\Routing\Enhancer\FormRouteEnhancer:*

```
<?php

namespace Drupal\Core\Routing\Enhancer;

use Drupal\Core\Routing\EnhancerInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;

/**
 * Enhancer to add a wrapping controller for _form routes.
 */
class FormRouteEnhancer implements EnhancerInterface {

  /**
   * Returns whether the enhancer runs on the current route.
   *
   * @param \Drupal\Core\Routing\Enhancer\Route $route
   *   The current route.
   *
   * @return bool
   */
  protected function applies(Route $route) {
    return $route->hasDefault('_form') && !$route->hasDefault('_controller');
  }

  /**
   * {@inheritdoc}
   */
  public function enhance(array $defaults, Request $request) {
    $route = $defaults[RouteObjectInterface::ROUTE_OBJECT];
    if (!$this->applies($route)) {
      return $defaults;
    }

    $defaults['_controller'] = 'controller.form:getContentResult';
    return $defaults;
  }

}

```
> 1 votes

---
Tags: routes, 8
---


# Question
Title: Form token wrong if logging in during rebuild
I have a multi-step form using AJAX. When you submit the form it increments the step, and then sets `$form['#rebuild']` to `TRUE`, and the entire form is replaced by AJAX.

It works fine, right up until one of the steps involved calling `user_login_finalize()` in the submit handler - the user can go from anonymous to logged in. Then when it tries to build the next step I get the error:

> Form errors cannot be set after form validation has finished

I puzzled over this error for a while. I thought the validation handler might be firing twice, but then I saw in the debug trace that `setInvalidTokenError()` is being called in `FormBuilder->doBuildForm()`.

After looking in `doBuildForm()`, I think the problem is that Drupal thinks the form is being submitted in a naughty way or has the wrong token. What can I do?

# Answer
> 0 votes
The only way I could fix it was to set `$form['#token']` to `FALSE` when building the form. This disables the token checking functionality, which isn't ideal, but I think it's my only option.

# Answer
> 0 votes
Make sure, you do not have `$form_state->setRebuild()` calls inside final submit handler. Use it only for AJAX or steps in multi-step forms. Because, if it used in the `submitForm()` callback or any other, and this is the last one, and the form has something to do with authentication, the form will rebuild, but the user will be already authenticated. And here is the problem strikes. The forms for authenticated users must contain token, but your form is rebuilt, and initially, this form was built for anonymous user.

I.e. If you use AJAX, set rebuild mark only in ajax callback, not in the submit callback. If you create a multi-step form, use rebuild only to submit callbacks which affect steps (next, previous), etc., but don't call it for the last step submission.

P.s. My answer obviously is too late. But having the same problems now and figured out how to fix it. So maybe it will save some time who will google it in the future.

---
Tags: 8, forms
---


# Question
Title: How can I ensure that fields from a Views query plugin work as tokens?
I have a Drupal 7 Views query plugin module that pulls in data from a RESTful API for use in Views. I used this series of articles as a starting point to build it: https://www.lullabot.com/articles/building-views-query-plugins. I now need to port it to Drupal 8.

I have made a start on the porting process, with the help of this series of articles: https://www.lullabot.com/articles/building-views-query-plugins-dupal-8-part-1. The Drupal 8 module now successfully pulls in data for the fields that use the 'standard' handler.

I'm currently stuck on trying to get tokens representing one of those fields to work when rewriting results.

The field is called `access-url` and contains URLs. If I tick 'Override the output of this field with custom text' on that field, and enter the token form, `{{ access-url }}`, it just returns '0' for every record, whereas if I untick that box it returns the URLs correctly. Meanwhile, the token form of the `id` field works correctly.

(In real life I will want to use `{{ access-url }}` under 'Output this field as a custom link', but 'Override the output of this field with custom text' illustrates the problem better.)

How can I get the `{{ access-url }}` token to work correctly?

I expect it would be helpful if I posted some code, but I'm not sure what code would be most helpful, so please let me know.

**Additional debugging info:** as far as I can tell, all seems well until it gets to the line in `PluginBase::viewsTokenReplace()` that runs `$this->getRenderer()->renderPlain($build)`. `$build` at that point has the value of `access-url` in it, but the renderer returns zero.

# Answer
Eventually I realised that it was only tokens containing hyphens that weren't working, and sure enough, it turns out that hyphens are not allowed in Twig tokens. Or, to be more accurate, they are interpreted as minus signs (https://www.drupal.org/project/drupal/issues/2371633). That was why the `{{ access-url }}` token was returning zero: access minus url equals zero, apparently. So I just replaced all of the hyphens with underscores.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to create a custom context by using Drupal's context API?
I can access current node context in my block plugin by adding:

```
 *  context_definitions = {
 *    "node" = @ContextDefinition("entity:node", label = @Translation("Node"), required=FALSE)
 *  }

```

to its annotation. And then access node object by using:

```
$context = $this->getContext('node');

/** @var NodeInterface $node */
$node = $context->getContextData()->getValue();

```

Provided it's available. But let's say I want to create context that is active only if node has specific field.

I'm currently trying to reverse engineer this, because there are literally no resources on context API that I could find, but maybe someone have some working example to share?

# Answer
Ok, I figured it out and I'm describing it here. It's really surprising for me that it's not explained anywhere else as of now.

Let's say we have a content type `news` that have a field `field_section` storing reference to the term from the `sections` vocabulary. Now, everytime we are on the node's page, and this node is referencing a section, we want to trigger the context, that will give as a `Term` object representing our section. Moreover we have a block plugin, that depends on the availability of this section, and should be visible only if section is available on the current page.

We could do this with the `node` context, but then we would have to add logic checking the content of the `field_section` of our node, in every context aware plugin that needs this information, and we want to have this simplified to just having context active when section is available on the current page - that's the whole point.

So first off, we have to provide a service that implements `Drupal\Core\Plugin\Context\ContextProviderInterface`, and tag it with `context_provider` tag, like that:

```
  mymodule.section_context:
    class: Drupal\mymodule\ContextProvider\SectionContextProvider
    arguments: ['@context.repository']
    tags:
      - { name: context_provider }

```

Note that we are injecting `@context.repository` service, we will be able to extract the `node` context from it. We are dependent on the node being available in the first place, so we can as well reuse this context. We could also inject here `@node.node_route_context` service directly and have more explicit dependency, but I felt that it would be more clean to do this trough the repository service. It's up to you.

Now the code of our context provider:

```
namespace Drupal\mymodule\ContextProvider;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextInterface;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;

/**
 * Class SectionContextProvider
 */
class SectionContextProvider implements ContextProviderInterface {

  use StringTranslationTrait;

  /**
   * @var ContextRepositoryInterface
   */
  private $contextRepository;

  /**
   * @param ContextRepositoryInterface $contextRepository
   */
  public function __construct(ContextRepositoryInterface $contextRepository) {
    $this->contextRepository = $contextRepository;
  }

  /**
   * {@inheritdoc}
   */
  public function getRuntimeContexts(array $unqualified_context_ids) {

    $nodeContextId = '@node.node_route_context:node';

    /** @var ContextInterface $nodeContext */
    $nodeContext = $this->contextRepository->getRuntimeContexts([$nodeContextId])[$nodeContextId];
    $value = NULL;

    /** @var NodeInterface $node */
    $node = $nodeContext->getContextData()->getValue();
    if ($node && $node->hasField('field_section')) {
      $value = $node->get('field_section')->entity;
    }

    // We are reusing cache contexts.
    $cacheContexts = $nodeContext->getCacheContexts();
    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts($cacheContexts);

    $contextDefinition = EntityContextDefinition::create('taxonomy_term');

    $context = new Context($contextDefinition, $value);
    $context->addCacheableDependency($cacheability);
    $result['mymodule_section'] = $context;

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getAvailableContexts() {
    $context = EntityContext::fromEntityTypeId('taxonomy_term', $this->t('Mywebsite Section from Node'));
    return ['mymodule_section' => $context];
  }

}

```

Basically will are getting the current node from the `node` context, and then extract section data if it's available.

But that's not all.

We want to make our plugin block dependent on the context, so we are are adding to its annotation:

```
 *  context_definitions = {
 *    "mymodule_section" = @ContextDefinition("entity:taxonomy_term:sections", label = @Translation("Mywebsite Section"))
 *  }

```

But it still won't work, and that's the tricky part. We also have to configure the context mapping of our plugin block. We can do this by providing it as a part of default configuration like that:

```
  /**
   * @return array
   */
  public function defaultConfiguration() {
    return [
      'context_mapping' => [
        'mymodule_section' => '@mymodule.section_context:mymodule_section',
      ],
    ] + parent::defaultConfiguration();
  }

```

And ONLY THEN it will work. The block wont be rendered if context is not available, and if it is, we can access the term referenced by node's `field_section` field by:

```
$sectionTerm = $this->getContext('mymodule_section')->getContextData()->getValue();

```

That's way too complicated for this to not have any documentation, but I hope this description will help someone.

And if anyone know, where on the drupal.org website I could write up a documentation for that, please let me know, we have to improve that stuff.
> 19 votes

---
Tags: 8
---


title: How do I access $_SESSION in a view?

text:
# Question
Title: How do I access $_SESSION in a view?
Let's say I want to use `$_SESSION['user_variable']` with a view as a filter value. I read that in Drupal 7 I could add such a value with custom PHP code. How should I do in Drupal 8? I didn't find an easy solution so far.

Would it be better to temporarily save a user's choice that is valid for the whole session in the database and tell the view to get the value from there?

# Answer
> 0 votes
In case this might be helpful for other (beginners): Using the session object in a custom controller class with dependency injection.

```
Drupal\user\PrivateTempStoreFactory;

class mymodule_Controller extends ControllerBase {

  /**
  * The user's private $tempStore object.
  *
  * @var \Drupal\user\PrivateTempStoreFactory
  */
  protected $tempStore;

  public function __construct(PrivateTempStoreFactory $temp_store_factory) {
    $this->tempStore = $temp_store_factory->get('mymodule_name');
  }

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

 // Now get and set values in tempstore
 public function foo() {
  $foo = "xyz";
  // Set a session object "bar" and give it value $foo
  $this->tempStore->set('bar', $foo);

  // Get the 'bar' object from the session object.
  $value = $this->tempStore->get('bar');
 }

}

```

# Answer
> 0 votes
There is a module for this - check this out: https://www.drupal.org/project/views\_extras

---
Tags: views, sessions
---


# Question
Title: How to set the public file path to migrate site files and images through Migrate Drupal UI
I am working on migrating a drupal 7 site to drupal 8 site that has image fields in content types, as well as some pdf files that I am trying to migrate through the Migrate UI. None of those files are in private directories. I have run the migration through the core Migrate UI many times and the content, taxonomy, redirects, alias patterns all have been coming through flawlessly. I cannot however seem to get the path right for my public files to migrate at all.

I am using Acquia Dev Desktop, which by default sets the file path for the D8 site to `sites/"your-website".dd/files` in `/admin/config/media/file-system` as they have essentially 2 paths to get to your site files. I have changed this in the settings.php to `sites/default/files` which did not fix the problem. The Drupal 7 site files are on my local machine, and that site is a dev site also on Acquia dev desktop. The Drupal 7 site has the path set to `sites/default/files` in `/admin/config/media/file-system`.

When using the full local path :`C:\Users\user\Documents\mywebsite\sites\default\files` I am getting the following pattern, which makes me think that the files are not being recognized properly in the directory as I am not seeing the slashes in the path:

```
Source ID 1701: File '//sitesdefaultfilesschematicsimagesah-00-3.5.JPG' does not exist

```

When using `sites/default/files`or `sites/default/files/`I am getting a double slash in the path when it shows the results `sites/default/files//*`

```
Source ID 1701: File 'sites/default/files//schematics/images/ah-00-3.5.JPG' does not exist

```

Here is my question. What path should I be using, and is the Migrate Drupal UI designed to get the files and move them just by setting the public path for source files, or should i be manually moving the files (copy/pasting) into the D8 directory in conjunction with setting the source file public path in the UI to properly reference them?

I would really like to sort out if it's possible to migrate my files through the UI as I am not very savy with drush.

# Answer
So it turns out though I had difficulty understanding them, the directions are "correct". The difficulty I had is partly because of my inexperience, but it's also partly because of a slightly confusing UX in Migrate Drupal UI. The label is asking for your "**Public files directory**", but what it really wants is your absolute docroot path. The directions state this: *"To import from you current Drupal Site,enter a local file directory containing your site (e.g **/var/www/docroot**), or your site address (for example http://example.com)"*

This means when the source files UI is asking for the "**public files directory**", the `sites/default/files` portion is already assumed by Drupal Migrate and is not needed, nor is it welcome. I used `C:\Users\user\Documents\mywebsite` and it worked the first try, where repeated attempts that included \sites\default\files path failed.

Also, the unique settings in settings.php from Acquia dev desktop for the public file path for the new Drupal 8 site were not a factor. I left those settings as they were by default when I executed the migration.
> 1 votes

---
Tags: 8, files, migrations
---


# Question
Title: How to add certificate to drupal_http_request()?
I am currently setting up a payment method in my Drupal 7 site and following the API documentation for the service I could use this cURL command for testing purposes:

```
$ curl -s -S -i --cert
./Swish_Merchant_TestCertificate_1231181189.p12:swish --cert-type p12 --
cacert ./Swish_TLS_RootCA.pem --tlsv1.1 --header "Content-Type:
application/json"
https://mss.cpc.getswish.net/swish-cpcapi/api/v1/paymentrequests --data
'{ "payeePaymentReference" : "0123456789", "callbackUrl" :
"https://myfakehost.se/swishcallback.cfm", "payerAlias" : "4671234768",
"payeeAlias" : "1231181189", "amount" : "100", "currency" : "SEK",
"message" : "Kingston USB Flash Drive 8 GB" }'

```

But since I am developing this function in Drupal 7 I want to use drupal\_http\_request instead. But I am confused about how to include the certificates used in the cURL command. Anyone?

EDITED: After the suggestion below I added a context parameter. I still get "connection refused by destination". Is there anything more I should do? This is how my function looks so far:

```
function create_payment_request(){
  // Send payment request to Swish API
  $headers =  array('Content-Type'=>'application/JSON' );
  $url = "https://mss.cpc.getswish.net/swish-cpcapi/api/v1/paymentrequests";

  $context = stream_context_create([ 'ssl' => [
  'local_cert'        => '/mypathtocertificates/TestCertificate_123456789.pem',
  'passphrase'        => 'pass' ]]);

  $json = '{
  "payeePaymentReference": "0123456789",
  "callbackUrl: "/swish_callback",
  "payerAlias": "4671234768",
  "payeeAlias: "1231181189",
  "amount": "100",
  "currency": "SEK",
  "message": "testo 925"
}
';

  $options=array(
      'headers'=>$headers,
      'context' => $context,
      'method'=>'POST',
      'data'=>$json,
    );

    $result=drupal_http_request($url, $options);
    dpm($result);
}

```

# Answer
You need to supply a `context` parameter in the options for `drupal_http_request`. The value is a stream context created using the PHP function stream\_context\_create.

There are a lot of possible parameters so you may have to hunt through the parameter list to find the ones you want.
> 2 votes

---
Tags: 7, http-request
---


# Question
Title: How do I know if a link has the "active" class?
I've added a custom twig template for links--language-block.html.twig.

Inside of it, I want to render additional HTML when the current item is active. But I can't figure out how to check when the current item is active.

```
{% if links -%}
  {%- if attributes.hasClass('inline') -%}
  <ul{{ attributes.addClass('list-inline') }}>
  {%- else -%}
  <ul{{ attributes }}>
  {%- endif -%}
    {%- for key, item in links -%}

      {% if item.attributes.hasClass('is-active') %} << this is always false
        <li>foobar</li>
      {%- endif -%}

      <li{{ item.attributes.addClass('dropdown') }}>
        {%- if item.link -%}
          {{ item.link }}

          {# <a class="dropdown-toggle" data-target="#" data-toggle="dropdown">Deutsch <span class="caret"></span></a> #}
        {%- elseif item.text_attributes -%}
          <span{{ item.text_attributes }}>{{ item.text }}</span>
        {%- else -%}
          {{ item.text }}
        {%- endif -%}
      </li>
    {%- endfor -%}
  </ul>
{%- endif %}

```

How can I check if the link as the *active* class?

# Answer
In some cases, the active state is not set by design due potential problems with caching. This behavior is documented in this change record.

> Setting the active class is now an opt-in feature:
>
> l() and LinkGenerator::generate() now have a set\_active\_class option that defaults to FALSE theme\_links() now accepts a set\_active\_class key that defaults to FALSE Those links that you'd expect to get the active class set, do get it: menu links, language switching links …
>
> The output of l(), LinkGenerator::generate() and theme\_links() no longer contains the active class, even if you do opt in. Instead, they get a data-drupal-link-system-path attribute, and if there's a GET query, they also get a data-drupal-link-query attribute…

In those cases, where it is not set on server side, you can take a look at core/misc/active-link.js to get an idea how to manipulate the active state on client side.
> 3 votes

# Answer
It seems you can just use "is\_active". This works for me:

```
{% set link = link|merge({ '#attributes': { 'class': [ 'classes', 'if', 'active'] } }) %}
{% if is_active %}
{% set link = link|merge({ '#attributes': { 'class': [ 'classes', 'if', 'not', 'active'] } }) %}
{% endif %}

<li{{ attributes.addClass('nav-item') }} role="presentation">{{ link }}</li>

```
> 1 votes

# Answer
In Drupal 8 the "is-active" class is added in two different ways:

* For anonymous users it's added in the server side.
* For authenticated users it's using javascript to add the class, as this allows for better cacheability.

You might consider adding the `<li>` in JS when the DOM is ready, to make sure the class has been added to the DOM.
> 1 votes

# Answer
For `core/themes/classy/templates/navigation/menu.html.twig`:

```
{#
/**
 * @file
 * Theme override to display a menu.
 *
 * Available variables:
 * - menu_name: The machine name of the menu.
 * - items: A nested list of menu items. Each menu item contains:
 *   - attributes: HTML attributes for the menu item.
 *   - below: The menu item child items.
 *   - title: The menu link title.
 *   - url: The menu link url, instance of \Drupal\Core\Url
 *   - localized_options: Menu link localized options.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 */
#}

```

Then you can write:

```
{% if item.in_active_trail %}
   <li>foobar</li>
{% endif %}

```
> 0 votes

# Answer
Define a JS library with a dependency on the `core/drupal.active-link` library:

*mytheme/mytheme.libraries.yml*

```
remove-active-links:
  version: 1.x
  js:
    js/remove-active-links.js: { }
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.active-link

```

Then your JS code knows which link has an `is-active` class and you can add HTML or remove the link wrapper like in this example:

*mytheme/js/remove-active-links.js*

```
(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.removeActiveLinks = {
    attach: function (context) {

      $(context).find('a.is-active').contents().unwrap();

    }
  };

})(jQuery, Drupal);

```

For more info and an alternative PHP solution (only for anonymous requests) see this answer Don't link menu in the active page
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How do I pull data from an external database, and display it in Views?
I am fairly new to Drupal, and just started working with Drupal 8. I know a table can be generated in Views for the content which is displayed/used somewhere on the site, and a table can also be generated as a "Content" with manual entries in there.

But I have a MySQL table - in a non-Drupal external database. I would like to use the data in that table, and generate a table on my Drupal site using that data, either as a View, or a Content, or something else.

Are there any suggestions on how I can go about doing that?

# Answer
There are a couple of solutions to do this.

**First** one is to convert your data into nodes (content) and then easily show them in Views as a table. (You might achieve this using the Feeds module. Export your table data as CSV and use Feeds to import it as a new content type.)

**Second** solution is to use the Views Custom Table module.

> ### About
>
> View custom table module provide you functionality to integrate your custom table data to views, and access all it's column in views. This module use hook\_view\_data to add custom tables in views. this module provides you following functionalities.
> 1 votes

---
Tags: views, 8, database
---


# Question
Title: How do I hide "View most recent blog entries"
If you enable the contributed **Blog** module, a link with the anchor text "View most recent blog entries" shows up on every post. I want to hide this link using PHP (i.e. not resorting to css or javascript).

So far I've tried this in `hook_node_links_alter()`:

```
unset($links['usernames_blog']['#links']['blog_usernames_blog']);

```

It doesn't work. I don't think the offending link is in the links array, but somewhere else (I've yet to figure out where).

# Answer
> 3 votes
> `unset($links['usernames_blog']['#links']['blog_usernames_blog']);`

Might be correct, but make sure your module has higher weight, so your hook alter fires after the blog's module.

I suggest using the weight module to give your custom module higher weight. Else, you could run on Devel's Execute PHP `module_set_weight('mymodule', 11);` to give it higher weight.

---

If that doesn't work, If you look at the module's code, there is another link that gets added via hook\_ENTITY\_TYPE\_view

Thus, all you gotta do is use hook\_ENTITY\_TYPE\_view\_alter

**mymodule.module**

```
/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if (!empty($build['summary']['blog'])) {
    unset($build['summary']['blog']);
  }
}

```

---
Tags: 8
---


# Question
Title: How do I modify a webform submission field right before it is saved?
When an end-user is submitting data entered in a Drupal 8 webform, I would like my custom module to modify a field that is on the same form based on values of other fields. I am having trouble accessing the values of the submitted data and also setting the value of the field that I wish to change before being saved.

There is a sample webform API file included which has some starters for hooks. A hook which I found may be useful is the following.

```
function hook_webform_submission_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {}

```

I used the `dpm()` to print the values of these variables. The `$form_state` variable has the data submitted, and I know I can use the `$form` variable to change these values before being saved.

How can I get values of the data submitted and also set the value of another field on that same page before the submission is saved? In Drupal 7 this was fairly straightforward, but with Drupal 8 navigating the array and object structures of variables is not as transparent.

# Answer
> 7 votes
You can use `preSave` method in your handler. Please check out the *Webform module handler tests* module which is part of Webform codebase, it has `TestWebformHandler.php` file which defines the submission test handler which displays a status message for every handler event.

For example:

```
<?php

namespace Drupal\webform_test_handler\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformInterface;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform submission test handler.
 *
 * @WebformHandler(
 *   id = "test",
 *   label = @Translation("Test"),
 *   category = @Translation("Testing"),
 *   description = @Translation("Tests webform submission handler behaviors."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_IGNORED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class TestWebformHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   */
  public function preCreate(array $values) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postCreate(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postLoad(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preDelete(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postDelete(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $this->displayMessage(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $this->displayMessage(__FUNCTION__, $update ? 'update' : 'insert');
  }
}

```

Then you can use a standard ways of modifying your `$webform_submission`.

See also: Way to do an action after a webform submission has been created.

# Answer
> 4 votes
After much trial and error, I found an answer with the help of these pages:

https://www.drupal.org/node/2841729

https://www.drupal.org/node/2637958

The idea is to create a custom module and add a validation function using `hook_form_alter()`. The validation function then sets the values before the form is saved permanently with the `setValues()` method.

Here, I am setting the webform element `observations` to an arbitrary value.

```
function MYMODULE_form_alter(&$form,$form_state, $form_id) {
  if ($form_id == 'MYFORM') {
    $form['actions']['submit']['#validate'][] = 'MYMODULE_operation_form_validate';
    }
}

function MYMODULE_operation_form_validate(&$form, $form_state, $form_id) {
  $values = ['observations' => 777];
  $form_state->setValues($values);
}

```

# Answer
> 4 votes
In Drupal 8 you can use `hook_ENTITY_TYPE_presave`, for example:

```
/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function mymodule_webform_submission_presave(\Drupal\webform\Entity\WebformSubmission $submission) {
  // var_dump($submission); exit;
}

```

in order to access, validate or modify the elements of your webform `$submission`.

See: How to track webform element create, update, and delete operations.

For Drupal 7, see: How to alter the Webform submission information.

# Answer
> 2 votes
Use this hook `hook_webform_element_alter`

```
/**
 * Implements hook_webform_element_alter().
 *
 * @param array              $element
 * @param FormStateInterface $form_state
 * @param array              $context
 */
function module_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {
    //use kint
    kint($element);
    //alter location field
    if ($element['#webform_id'] === 'my_form--location') {
        //do the logic
    }
}

```

Bingo!

# Answer
> 1 votes
There are multiple ways of doing this.You can use :-

1.hook\_webform\_element\_alter()

```
function your_module_name_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {
  if (isset($element['#webform_id'])){
    if ($element['#webform_id'] === 'abc') {
        //do the logic
    }
  }
}

```

Follow this for better understanding https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-add-custom-validation-to-a-webform-element

2.hook\_form\_alter()

```
function your_module_name_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    $form['#validate'][] = 'your_module_name_form_validate';
  }
}

```

And your logic goes into validate function

```
function your_module_name_form_validate($form, &$form_state) {
  $values = $form_state->getValues();
  //Your logic goes here.
}

```
3. hook\_ENTITY\_TYPE\_presave()

```
function your_module_name_webform_submission_presave(EntityInterface $entity) {
  // Entity new will only allow you to modify the value for first time.
  if ($entity->isNew()) {
      $entity->setElementData('key', value);
  }
}

```

---
Tags: 8, webforms
---


# Question
Title: I want to set some error message at one method and display it at another method
I have a method , here I set some message .

```
function doSomeAction(){

$messenger = \Drupal::Messenger();
$messenger->addMessage('error msg',$messenger::TYPE_ERROR,true);
 $response = new RedirectResponse(\Drupal::url('action_error.content',[], ['query' => ['error' => '1'],'absolute' => TRUE,]));
$response->send();
return $response;

}

```

I want to display this error message at another method

```
function action_error(){
$messenger = \Drupal::Messenger();
$msg = $messenger->messagesByType($messenger::TYPE_ERROR);
print_r($msg); die();

}

```

As a result I got Blank array.. Method doSomeAction and action\_error is in same class differentiated by routing.yml

I have checked error-log from back-end , displaying some error i.e

> RuntimeException: Failed to start the session because headers have already been sent by "\vendor\symfony\http-foundation\Response.php" at line 1286.

**In D7**

> In drupal 7 drupal\_set\_message() & drupal\_get\_messages() available..We can easily handle message

# Answer
> 2 votes
It's not about how you set and get the message, although you normally don't get a message but display it in the system message block.

The issue is that you can't send a response from inside a Drupal 8 function. This sends the response headers too early, so that the session handling for the message doesn't work anymore. If doSomeAction() is a controller, then only return the redirect response, do not send it:

```
function doSomeAction(){
  $messenger = \Drupal::Messenger();
  $messenger->addMessage('error msg',$messenger::TYPE_ERROR,true);
  $response = new RedirectResponse(\Drupal::url('action_error.content',[], ['query' =>
    ['error' => '1'],'absolute' => TRUE,]));
  // $response->send();  ... don't send responses from inside a D8 function
  return $response;
}

```

---
Tags: 8, status-messages
---


# Question
Title: Problem with programmatically creating a redirect
**Background**

Client has Event webforms hosted externally by a marketing automation service, leading to an unusual situation: a node of Event content type should have its summary displayed in certain Views on the client site, but navigating directly to the node address should result in a 301 redirect to the offsite form.

Client can achieve this manually by using the Redirect module:

`/admin/config/search/redirect/add?redirect=node/1234`

... and then entering the node path in the *From* field and the offsite destination in the *To* field. (Yes, this is exactly backwards, but it kind of works.) However, they would like to automate this process.

I tried to do this with Rules:

**Events:**

* After saving new content of type *Event*
* After updating existing content of type *Event*

**Conditions:**

* NOT Data value is empty (Parameter: Data to check: `[node:field-external-url]`)

**Actions:**

* Page redirect (Parameter: URL: `[node:field-external-url]`)

Unfortunately, this does not modify the Page Redirect settings on the node by adding an entry to the `redirect` table in the database.

Instead, it fires a one-time system event and redirects the site administrator to the desired URL at the moment that the Event content node is created or updated. Subsequent visits to the node URL do not redirect site visitors; instead, they see the node at that URL.

So, I'm trying a different approach, with a small `custom_event_redirect` module:

```
/**
 * Implements hook_form_alter().
 */
function custom_event_redirect_form_alter(&$form, &$form_state, $form_id) {
  // add submit handler only to Event content forms
  if ($form_id === 'event_node_form') {
    array_unshift($form['#submit'], 'custom_event_redirect_search_form_submit');
  }
}

/**
 * Drupal FAPI submit handler implementation
 */
function custom_event_redirect_search_form_submit(array $form, array &$form_state) {
  if (!empty($form['field_external_url']['und'][0]['value']['#default_value'])) {
    //create redirect programmatically

  }
}

```

Is it possible to use the Redirect API to fire off a `redirect_edit_form_submit()` when the `event_node_form` is submitted?

This is such an edge case. Google results are skewed heavily toward `drupal_goto()` redirects after form submission -- but if that was what I wanted, I could have used Rules.

I don't want to fire off a one-time redirect on form submission; I want to add an entry to the `redirect` table on form submission.

¯\\\_(ツ)\_/¯

# Answer
> 1 votes
Rabbit Hole should get you close, if not entirely there. After enabling the rh\_node submodule, `admin/structure/types/manage/event` will show "Rabbit Hole settings" where you can set the behavior to "Page redirect" and the "Redirect path" field has "You may enter tokens in this field" in the help text, so \[node:field-external-url\] should work there. You probably need custom code for your "Conditions: NOT Data value is empty" but you might be able to have a custom module for that, so long as you set the weight of your custom module such that it runs earlier than rh\_node (alternatively, Rabbit Hole offers a PHP filter, but that has an implied dependency on Bad Judgement).

Out of the box, Rabbit Hole does offer a "Bypass Rabbit Hole action for nodes" permission that you can grant to administrators.

# Answer
> 1 votes
You can use below code snippets to create programmatically URL redirect. \[Drupal 7\]

```
// Create an object with the redirect parameters
$redirect = new stdClass();
redirect_object_prepare($redirect);
$redirect->source = 'old-url';
$redirect->source_options = array();
$redirect->redirect = 'node/5'; // New system path
$redirect->redirect_options = array();
$redirect->type = 'redirect';
$redirect->language = LANGUAGE_NONE;
redirect_save($redirect);

```

---
Tags: 7, redirection
---


# Question
Title: Use Display Suite token field in custom block type template
* I have a custom block type, which uses its own theme template.
* I have a display suite token field `link_card_edit_block`
* It just uses HTML and tokens to create a link.
* I want to use that field in my block type template.
* Without the custom template, the field shows up.
* If I add `{{ content }}` in the custom block template, the field shows.
* But I can't figure out how show that field individually.

Here is what I have tried:

```
{{ content['#block_content'].field_link_card_edit_block.value }}
{{ content['#block_content'].field_link_card_edit_block[0] }}
{{ content['#block_content'].field_link_card_edit_block }}
{{ content.field_link_card_edit_block.value }}
{{ content.field_link_card_edit_block[0] }}
{{ content.field_link_card_edit_block }}

```

All of them produce nothing.

# Answer
My teammate figured this out:

{{ content\['dynamic\_token\_field:block\_content-link\_card\_edit\_block'\] }}
> 0 votes

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


title: Get block id in block theme template

text:
# Question
Title: Get block id in block theme template
I'd like to be able to print the block id/number of my custom block in its template. I feel like these must exist because Display Suite has a token for it: `[block_content:id]`.

Like a url to edit a block is, it goes to the edit form: `block/17`

How do I get that `17` in the twig template? Looking in block.html.twig, I don't see anything about a block's number.

# Answer
> 6 votes
You find the `block_content` entity in the template variable `elements` to get the ID:

*block.html.twig:*

```
{{ elements.content['#block_content'].id() }}

```

---
Tags: 8, theming, blocks
---


title: What exactly does this part of code do?

text:
# Question
Title: What exactly does this part of code do?
There is a code snippet in a .twig file that I can't understand.

Here is the code:

```
{% set show_emer_alert = 'ALL CLEAR' in page.emergency|render ? 'N' : 'Y' %}

{% if show_emer_alert == 'Y' %}
     {{ page.emergency }}
{% endif %}

```

I know that this one `{% if show_emer_alert == 'Y' %}` is a condition, But I can't get how it becomes `Y` or `N`.

Can you please help me understanding what this code does?

Where can I find the page.emergency file?

# Answer
> 1 votes
The following is called a tertiary operator. First, it renders the field page.emergency. Then it checks if the value is equal to `ALL CLEAR'` If it is, then `show_emer_alert` is set to `N`, otherwise it is set to `Y`.

```
{% set show_emer_alert = 'ALL CLEAR' in page.emergency|render ? 'N' : 'Y' %}

```

Tertiary operators act as follows. Imagine the following:

```
$sex = user_is_male($user) ? 'male' : 'female';

```

This code assigns a value to $sex. It does this by executing the function user\_is\_male(). If this evaluates as `TRUE`, then the value of $sex is set to 'male'. If it evaluates as `FALSE`, then $sex is set to 'female'.

You could do this as well:

```
$male = user_is_male($user);
$sex = $male ? 'male' : 'female';

```

The point is, the first value (before the question mark) is evaluated to `TRUE` or `FALSE`, and the value of the variable is set accordingly. The first value, between the question mark and the colon, is used for `TRUE`, and the second value, after the colon, is used for `FALSE`.

In your code a few things happens. First, `page.emergency` is rendered in `page.emergency|render`. This will result in a string value. Next, that string is checked to see if it contains the text `ALL CLEAR`. This is the value that is `TRUE` or `FALSE`. If it is `TRUE`, then `show_emer_alert` is set to 'N'. If it is `FALSE`, then `show_emer_alert` is set to `Y`.

---
Tags: theming
---


title: Modification of HTML mail template

text:
# Question
Title: Modification of HTML mail template
I am using HTML Mail module. I have created an html email template specific to my form(webform) in the template folder of my theme directory. My form name is newsletter and the template name is `htmlmail--webform--newsletter_email.html.twig`

I want to override the email body based on a particular language. But my problem is that `hook_mail_alter` doesn't work in my case.

Drupal API documentation for `hook_mail_alter` says that `hook_mail_alter()` allows modification of email messages created and sent with `MailManagerInterface->mail()`.

Any help?

# Answer
The hook `hook_mail_alter()` should work in this case.

Have you double checked if your module is activated and you have cleared your cache after adding the hook?

Also i am not sure if your template will work, because normally all templates are working with dashes instead of underscores.
> 0 votes

---
Tags: 8, theming, emails
---


# Question
Title: Additional file entity fields in widget_form
I've added additional fields to my file entity types and would like to have them in upload widget, just like file description.

How can I add my custom fields element using field\_widget\_form\_alter? (if that's the way to go)

# Answer
> 0 votes
You have to add it to the field type, not entity type. Extend `FileItem` and override propertyDefinitions() to add it to the field properties. Like the description you've mentioned was added by `FileItem` extending `EntityReferenceItem`:

```
  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['display'] = DataDefinition::create('boolean')
      ->setLabel(t('Display'))
      ->setDescription(t('Flag to control whether this file should be displayed when viewing content'));

    $properties['description'] = DataDefinition::create('string')
      ->setLabel(t('Description'));

    return $properties;
  }

```

---
Tags: forms, files
---


# Question
Title: How to do automatic card authorization during checkout process?
I have a website that uses Drupal Commerce, we use Authorize.net for authorization and use AcceptJS as a plugin. When you put in the credit card information, it checks with Auth to make sure that you're using a real credit card and saves it as a payment method without authorizing the actual value. It gets saved in Auth, as well as the commerce\_payment\_methods table with a remote\_id for Auth. Currently in our workflow, after you submit your order, in Commerce-\>orders-\>payments, you have to add the payment and manually authorize/capture the amount. I want it to automatically authorize the amount when you finalize checkout, however I'm running into difficulty figuring out where and how I do this. I know it must be something simple. Can anyone help?

# Answer
> 0 votes
Is this a Drupal 7 or a Drupal 8 site? That will impact the admin URL as noted below: 8: /admin/commerce/config/payment-gateways/ 7: /admin/commerce/config/payment-methods/

You will want to edit the Authorize payment method, and look for "Default credit card transaction type" - that setting should be "Authorization and capture" as opposed to "Authorization only"

# Answer
> 0 votes
So I realized the Payment Process step was broken and it was doing everything leading up to that. It wound up being a subclassed PaymentInformation class that was set up improperly. I added a hook directing to the subclass and set up the subclass the correct way and it's all good now.

---
Tags: commerce, payment-gateways
---


# Question
Title: Show all nodes with the same term, the current user is assigned to
That sounds quite simple but I can't find a hint how to do this:

I have invoices with a term reference to a "Department" vocabulary \[field\_invoice\_department\]. The user has a term reference to the same vocabulary \[field\_user\_department\].

So how should I configure my contextual filters to show all invoices assigned to the same department, the current user is assigned to?

# Answer
There are a lot of answers you can search for "sibling taxonomy" or some other wording.

Here's one answer you can follow: Filter taxonomy term attached to user field

The only difference is you always want your views to show the current user's matches, and not create, for example, profile pages for everyone separately as it is in that answer.

To make your Views show only the current user's matches in the User ID Contextual filter you have to choose **User ID from logged in user** instead of `User ID from route context`.
> 0 votes

---
Tags: views, 8
---


# Question
Title: render or print image in a drupal 7 node.tpl?
I am trying to theme a node with tpl and when i tried to print image , I cant find image path like in d6.. which function i have to call to properly output image .. I mean something like theme('')?

```
Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [fid] => 13
                    [alt] =>
                    [title] =>
                    [width] => 416
                    [height] => 335
                    [uid] => 1
                    [filename] => Capture2.PNG
                    [uri] => public://Capture2.PNG
                    [filemime] => image/png
                    [filesize] => 215377
                    [status] => 1
                    [timestamp] => 1346837738
                    [rdf_mapping] => Array
                        (
                        )

                )

        )

)

```

# Answer
> 37 votes
```
<?php print render($content['field_image']); ?>

```

If you want to change how the image is displayed (dimensions, link, etc), set them in Manage Display tab in the node type settings.

You can also do an imagecache preset like this:

```
<?php
print theme('image_style', array('path' => $node->field_image[LANGUAGE_NONE][0]['uri'], 'style_name' => [STYLE NAME]));
?>

```

But that's not the recommended way!

if you want to build URL from URI,

```
<img src="<?php print file_create_url($node->field_image[LANGUAGE_NONE][0]['uri']); ?>" />

```

# Answer
> 3 votes
For those using the file\_entity module (perhaps with the media module), you may be wondering how to programmatically render files/images:

```
$image = (object) $node->field_image[ LANGUAGE_NONE ][0];
$image_entity = file_view($image, "summary");
echo drupal_render($image_entity);

```

Where "field\_image" is your field name, and "summary" is your view mode.

# Answer
> 1 votes
If you want to simply render the image with the image style set for that image in manage display: Just type `<?php print_render($content['field_image']) ?>`

If you want to display image with any other image style you have SUPPOSE : 'sales\_album' then type:

```
list($albumImage) = field_get_items('node', $album, 'uc_product_image');

$albumImageUrl = file_create_url($albumImage['uri']);

$style_array = array('path' => $albumImage['uri'], 'style_name' => 'sales_album');

$render_album_image = theme('image_style', $style_array);

print $render_album_image;

```

# Answer
> 1 votes
```
$img_url = $node->field_name['und'][$i]['uri'];
print image_style_url("style_name", $img_url);

```

`$i` is in case you have multiple images to display. You can use a for loop like:

```
for($i=0;$i < $imageCount; $i++) { /*the above code*/ }

```

and `$imageCount` is basically declared above for loop as

```
$images = array();<br>
$imageCount= count($node->field_image['und']);

```

Hope this helps!

# Answer
> 1 votes
When using the field module, I found this was better:

in page--yourcontenttype.tpl.php:

```
<?php
  $this_field_image = field_view_field('node',$node,'field_image');
  print render($this_field_image);?>
?>

```

using field\_view\_field() provides additional advantages whereby one can set an array of display settings:

```
<?php
  $hide_labels = array('label'=>'hidden');
  $this_field_image = field_view_field('node',$node,'field_image', $hide_labels);
  print render($this_field_image);?>
?>

```

https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field\_view\_field/7.x

---
Tags: 7, theming, media
---


# Question
Title: Hide a field for that particular row based on value from custom table
I have a custom module where in a user requests access to view a node. I have a view page which currently lists all nodes and has a button "Request Access" to it. When the user clicks on it, an entry for the same is captured in my custom table for that node id. Then the admin approves or rejects it. If it is approved i want the user to view "Approved" status for that node id and for others it should show "Request Access". The name of my custom table is `access_node_custom`. I tried using the below code (with some static data):

```
function access_node_custom_views_pre_render(&$view) {
    if ($view->name !== 'access_node_custom'  || $view->current_display !== 'page_access_node_custom') {
        return;
    }

    $results = &$view->result;
    foreach ($results as $key => $result) {
        if($result->nid == 656){
            $view->field['request_access']->options['exclude'] = TRUE; //Hide request access since this is already approved
        }
    }
}

```

The problem with this is that it hides for every row on that page. I am fairly new to drupal so I don't know how can i do this. Is it possible to use relationship? or query alter?

Thank you.

# Answer
> 1 votes
> `$view->field['request_access']->options['exclude'] = TRUE;`

Exclude will always exclude the field for every single row.

What you need to do is set it to `null` or empty `''`

```
$result->field_request_access = null; // hide request

```

A possible downfall is that a user could guess, or have someone tell them the direct link, and still be able to see /node/656.

Thus; in addition, to what you're already doing, should also use hook\_node\_access

```
/*
 * Implements hook_node_access()
 */
function access_node_custom_node_access($node, $op, $account) {
  if($node->nid == 656 && $op == 'view'){
    // some db_query here
    if ($something_is_true) {
      return NODE_ACCESS_ALLOW;
    }
    else {
      return NODE_ACCESS_DENY;
    }
  }
}

```

If the person does not have access, the above will automatically hide any "view" link in Views.

---
Tags: 7, views
---


title: Relationship duplicates data

text:
# Question
Title: Relationship duplicates data
I have a view of content type documents wherein I want the logged in user to request access for each document and after it approved or rejected the status next to that list of documents should show approved or rejected respectively.

I created a custom module to capture the node id, the user id of the requester and the status of the request.

I then created a `mymodule.view.inc` file to add the fields of this custom module using handlers. This is the below code:

```
<?php

function mymodule_views_data() {
    $data = array();

    $data['mymodule']['table']['group'] = t('Document Approval');

    $data['mymodule']['table']['join']['node'] = array(
        'left_field' => 'nid',
        'field' => 'nid',
    );

    $data['mymodule']['nid'] = array(
        'title' => t('Nid'),
        'help' => t('The node id of the approval node'),
        'field' => array(
            'handler' => 'views_handler_field_node',
            'click sortable' => TRUE,
        ),
        'argument' => array(
            'handler' =>'views_handler_argument_node_nid',
            'name field' => 'title',
            'numeric' => TRUE,
            'validate type' => 'nid',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_numeric',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
        'relationship' => array(
            'label' => t('Node'),
            'base' => 'node',
            'base field' => 'nid',
        ),
    );

    $data['mymodule']['uid'] = array(
        'title' => t('Uid'),
        'help' => t('The user id of the user requested access'),
        'field' => array(
            'handler' => 'views_handler_field_user',
            'click sortable' => TRUE,
        ),
        'argument' => array(
            'handler' =>'views_handler_argument_user_uid',
            'name field' => 'title',
            'numeric' => TRUE,
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_numeric',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
        'relationship' => array(
            'label' => t('User'),
            'base' => 'users',
            'base field' => 'uid',
        ),
    );

    $data['mymodule']['status'] = array(
        'title' => t('Status'),
        'help' => t('The status of the approval node'),
        'field' => array(
            'handler' => 'views_handler_field_node',
            'click sortable' => TRUE,
        ),
        'argument' => array(
            'handler' =>'views_handler_argument_node_nid',
            'name field' => 'title',
            'numeric' => TRUE,
            'validate type' => 'nid',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_numeric',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
        /*'relationship' => array(
            'label' => t('Node'),
            'base' => 'node',
            'base field' => 'nid',
        ),*/
    );

    return $data;
}

```

I am able to see these fields in my view. I am confused as to how do I further use this in my views to get what I want. I want the user to see the status in front of each node.He should see all nodes. And for the user whose no record is found in my custom table he should also see all nodes with "request access" status.

I tried creating a relationship using nid of my custom table and adding a field status with requiring relationship, but I get duplicate results.

I would also like to know if there is any better way of handling this use case.

# Answer
> 0 votes
Try looking into Permissions by Term and similar modules that override how access is handled. That module can take care of hiding the nodes from users based on taxonomy terms. You can create a Vocabulary with access terms and assign nodes with them, and allow different user roles to view nodes based on that taxonomy.

Then in the Views listing all the nodes disable the node access checks:

> ```
>  Disable access checks
>
> ```
>
> Do not apply node\_access checks to this query. Selecting this option omits that tag from the alterable query.

under `Query settings`.

This will list all the nodes regardless of the access rules, but it applies to the Views only. Once the user clicks through to the node the access check will kick in and they will/will not be able to view it based on the taxonomy access or other node access you set up.

---
Tags: 7, views
---


# Question
Title: Filebrowser thumbnails "can not create img for private://"
I am using Drupal 8.7.5 and PHP 7.3.7 running on Apache 2.4.6.

**UPDATE:** I'm trying to make available a library of images to the public. I chose the content type of 'Directory listing' to do this. In the Directory listing I have configured a private file path (i.e. located outside of Web root) to hold the images. Apparently I have done something right as it is working except for the thumbnails. I get constant 404 errors in my apache logs and the other errors through the web interface seen in the images below.

What have I missed in terms of getting the thumbnails working? Am I missing an binary or library to render the thumbnails? Did I not create or configure a path for the thumbnails?

Below are some of the steps I have done to configure the Directory listing.

**UPDATE** On the server I have installed Druapl 8 using composer and drush to $APACHE\_CONTENT/drupal. The drush site-install then goes to $APACHE\_CONTENT/drupal/web (drupal app\_root) and have added a 'private' path as $APACHE\_CONTENT/resources. This puts the 'private' path outside of the drupal site's DocumentRoot. The permissions and ownership for the 'private' path are 775 and apache.apache. Also, a .htaccess file was auto generated for the 'private' path. It contains the following:

```
# cat .htaccess
# Deny all requests from Apache 2.4+.
<IfModule mod_authz_core.c>
  Require all denied
</IfModule>

# Deny all requests from Apache 2.0-2.2.
<IfModule !mod_authz_core.c>
  Deny from all
</IfModule>

# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

In drupal/sites/default/settings.php I have:

```
$settings['file_private_path'] = $app_root . '/../../resources';

```

Viewing the *Configuration-\>Media-\>File system* is see:

I've configured a private file path to use with content created via *Content-\>Add Content-\>Directory listing*.

I have then used `scp` to copy files into the private path.

Through the web interface, I can browse through the content but I never see the thumbnails. I get errors above my content.

In the apache logs I see 404s for the thumbnails:

```
GET /system/files/styles/thumbnail/private/Images/JPG/Marshal_Hub.jpg?itok=QwQds55m HTTP/1.1" 404 11730

```

I have GD installed.

While I can browse all of the content in the 'private' paths, none of the thumbnails get generated.

What do I need to do to get the thumbnails working?

# Answer
> 0 votes
This is a workaround I used to solve the issue:

\[https://www.drupal.org/project/private\_files\_download\_permission\]

I don't consider this 'magic' to be a fix. There is a lack of documentation and/or a bug in the filebrowser module.

How can one raise an issue with the developers?

PS: Also, now have another issue with the filebrowser module: sort order is not being honoured in Grid view!

# Answer
> -1 votes
It's my understanding that the 'private' directory can not be used to serve files. The whole point of this special directory is to provide a protected place for the files you choose to place in there. If the images are place in another directory under the 'sites/\*/files' directory they should be accessible to be served.

---
Tags: 8, files
---


# Question
Title: Drush custom command not found in context of running --root option
Drush 8. Have the custom module with the custom command.

Call `drush custom-command` works as expected.

Call `drush --root=sites/subsite custom-command` thiggers the error:

`The drush command 'custom-command' could not be found.`

How to call the drush command in the context of the subsite?

# Answer
> 1 votes
To call a command on a certain instance of a multisite you are supposed to pass the `-l` option. Also be sure that the custom module that provides the custom command is enabled on the multisite instance you are trying to call that command on.

```
$ drush custom-command -l subsite

```

---
Tags: 8, drush
---


# Question
Title: How do I render a field twice with two different field formatters?
So there was already the same question for D7 (How do I render a field on a node twice with two different field formatters?) but now i wanted to know how to do this in d8.

Maybe this helps a little bit, but i could not get it working. Rendering arbitrary field values without a parent entity in Drupal 8

# Answer
> 5 votes
So in drupal 7 you could use:

```
$output = field_view_field('node', $node, 'field_foo', array('type' => 'some_formatter', 'settings' => array(...), $langcode));

```

to render a field with a specific formatter. The drupal 8 the equivalent is:

```
$output = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));

```

source: Change record

Now to render the fields I would create a preprocess for a node

```
function HOOK_preprocess_node(&$variables) {
  $variables['my_field_formatter1'] = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));
  $variables['my_field_formatter2'] = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));
}

```

and then print my\_field\_formatter1 and my\_field\_formatter2 in your twig template for the node.

# Answer
> 2 votes
There is a module for that™: Use Display Field Copy

From the module page:

> Display Field Copy provides the ability to make a display copy of a field with Display Suite. The copy of the field can use a different formatter (with different config) than the single field that is currently available in core.
>
> For instance, if a site has a single entity reference field and the display needs the list rendered on the page twice (once as a rendered entity and once as a list of links). This module could be used to create a copy of the field and apply a different formatter to it.
>
> This module does not have a copy limit. Theoretically, an unlimited number of copies could be created. It should work for any field that has at least one formatter available.

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


title: Multiple pagers on same view page

text:
# Question
Title: Multiple pagers on same view page
When creating a view whose display type is page, we got an option to apply pagination using pager option given in view, where you get sort of radio buttons to select pager, full, mini, etc..

Do we have check-boxes instead of those radio buttons?

What If want to render 2 different pagers in my view display - full and mini?

Any help is really appreciated.

# Answer
There is the `Expose items per page` option under Pager options, so this might help a bit. This allows users to change how many results they want to see per page.

Why do you want to show different pagers for the same set of results? Pagers can add to the performance strain.

There are some contributed modules that add to the Views pager, try searching for them and see if they come close to what you need. For example Pagerer or Views Extra Pagers.
> 1 votes

---
Tags: 7, views
---


title: X-Frame-Options to sameorigin

text:
# Question
Title: X-Frame-Options to sameorigin
My Drupal site is on a subdomain of my old html/php site. So, I am running into problems sharing content from my Drupal site via iFrame.

I looked up solutions that worked for others and the consensus seems to be either edit settings.php

```
$conf['x_frame_options'] = '';

```

Or to use the Securit Kit module to change the X-Frame options to disabled.

I have tried both, cleared the cache and the site with the iFrame is still saying Refused to display https://example.com/entity\_iframe/node/1 in a frame because it set 'X-Frame-Options' to 'sameorigin'.

Any ideas?

# Answer
The htaccess file was overriding everything. I installed https://www.drupal.org/project/htaccess and added "Header always unset X-Frame-Options"

That fixed it.
> 1 votes

---
Tags: 7
---


# Question
Title: Is there a way to downsize images on upload to save server space?
Ok, so I have a content type with an image field that gets cropped using the Image Widget Crop. My users will potentially be uploading images directly from their DSLR cameras which are anywhere from 8 to 12 MB each. I want to reduce them down to 1080px x 720px where they'll be around 300kb and drastically cut down on server space.

I've been using `hook_ENTITY_TYPE_presave()` to reduce the image size however I just discovered this is messing up my cropping. The Image Widget Crop is cropping the original full sized image but after the image size reduction in the presave hook the cropping is no longer valid.

So, is there a way I can hook into the image file as it's being uploaded to then reduce the image size before it hits the Image Widget Crop?

Alternatively, is there a way to convert the crop settings after the image size reduction?

# Answer
> 1 votes
I answered my own question and I feel a little silly. I realized resizing images programmatically is unnecessary. In the UI you can set maximum dimensions for an image that will be uploaded. I knew that but I'd never read the text underneath that mentions the image gets resized if it violates the limits. That's all I needed, no need to for me to do it in code.

---
Tags: 8
---


# Question
Title: Drush cannot find your database connection details
I try to install open social using drush-8.3.0 and drupal-8.7.5. The first step is to run `composer create-project goalgorilla/social_template:dev-master public_html/peer/opensocial --no-interaction`. that works fine. The next step is `drush -y site-install social --db-url=mysql://root:root@db:3306/social` and results in the following error:

> Drush\Sql\SqlException: Unable to find a matching SQL Class. Drush cannot find your database connection details. in phar:///home/username/bin/drush/drush/commands/sql/sql.drush.inc:554

Using MySQL Wizerd and MySQL admin I have created the social database and defined username, password and ip address in `drush -y site-install social --db-url=mysql db_username db_password://root:root@IP address:3306/social`.

I have no ida how to find out what is realy going on? I am on a linux shared server. Can anybody help? Here is stack trace:

> #0 phar:///home/username/bin/drush/drush/commands/sql/sql.drush.inc(539): drush\_sql\_get\_class(Array)
>
> #1 phar:///home/username/bin/drush/drush/commands/core/site\_install.drush.inc(124): drush\_sql\_get\_class()
>
> #2 phar:///home/username/bin/drush/drush/includes/command.inc(422): drush\_core\_pre\_site\_install('social', '://root:root@10...')
>
> #3 phar:///home/username/bin/drush/drush/includes/command.inc(231): \_drush\_invoke\_hooks(Array, Array)
>
> #4 phar:///home/username/bin/drush/drush/includes/command.inc(199): drush\_command('social', '://root:root@10...')
>
> #5 phar:///home/username/bin/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush\_dispatch(Array)
>
> #6 phar:///home/username/bin/drush/drush/includes/preflight.inc(67): Drush\Boot\BaseBoot-\>bootstrap\_and\_dispatch()
>
> #7 phar:///home/username/bin/drush/drush/includes/startup.inc(465): drush\_main()
>
> #8 phar:///home/username/bin/drush/drush/includes/startup.inc(369): drush\_run\_main(false, '/', 'Phar detected. ...')
>
> #9 phar:///home/username/bin/drush/drush/drush(114): drush\_startup(Array)
>
> #10 /home/username/bin/drush/drush(10): require('phar:///home/oi...')
>
> #11 {main}

when I run `drush @hpc.dev sql-conf` I get this:

> Scanning into /home/username/public\_html/peer/opensocial/html/sites/default for /hpc.dev.alias.drush(8|)rc.php$/ \[0.33 sec, 7.29 MB\] \[debug\] Could not find the alias @hpc.dev \[0.33 sec, 7.29 MB\]

# Answer
> 1 votes
First of all, you should really use Drush 9 or 10 - see https://docs.drush.org/en/master/install/#drupal-compatibility And install Drush site locally as described on the same page.

However, the message `Unable to find a matching SQL Class` probably means that shared server you are running Drush on is missing the needed PHP database extensions. This is typically PDO with MySQL (pdo\_mysql and mysqli) - see https://www.drupal.org/docs/8/system-requirements/php-requirements#database

A typically problem is that PHP in the web server has these extensions, but not PHP on the command line.

---
Tags: drush
---