# Question
Title: Strategy for Import/exporting Drupal8 as content and structure
We are setting up feature\>dev\>production environments on Platform.sh for a Drupal 8 project. Expecting multiple contributors to the project, we have run into a slight snag regarding Importing/Exporting custom blocks. See this thread for more info about the issue.

See this as well for a different but similar issue.

In our previous D7 site, we used scripts to rsync files and drop/import databases via ssh which was super easy and reliable. I know there were lots of other ways to sync which (at that time) added a layer of complexity and potential points of failure that in our opinion made sense for some, just not for us. The concept of intentionally managing separate content and structure strategies is obviously becoming standard practice so we are being urged to deal with it.

Platform.sh documentation states that the easiest way to keep things in sync is through drush sync and aliases. However, this feels like what we were doing for D7 and the point is to move away from having to drop/replace the remote database. We'd like to nail down a process at this stage that makes things easier to maintain from a project management perspective. I think most things are solved for how to get content and structure downstream so the problem really exists for how to push it all upstream without breaking things.

What strategies are typically employed for content/structure synchronization when it comes to things like this custom blocks issue?

Also, we'd be grateful if anyone has Platform.sh specific ideas to automate this step.

# Answer
> 1 votes
As solution for site structure I use config synchronization, which is in Drupal 8 Core, and I use it with drush commands ("cex" - configuration export and "cim" - configuration import).

For content sync I don't have much experience, but I saw new module that can be interesting solution: https://www.drupal.org/project/content\_sync.

---
Tags: database, files, importing-exporting
---


# Question
Title: How to pass dynamic parameters through a local action button?
I created a local action button with the following in *my\_module.links.action.yml*:

```
my_module.content.action:
  route_name: node.add_page
  title: 'My action'
  deriver: 'Drupal\my_module\Plugin\Derivative\ContentByDomainLocalActions'
  appears_on:
    - view.affiliated_content.page_1

```

Then, the local action button appears in the page `admin/content/domain-content/firstdomain_local`

I'd like use the argument `firstdomain_local` from this URL path to pass it in my local action button.

So, I retrieve the param from `\Drupal::routeMatch()` in `getDerivativeDefinitions`, like in this tutorial:

```
class CustomLocalActions extends DeriverBase {
  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives['example.action_id'] = $base_plugin_definition;
    $this->derivatives['example.action_id']['title'] = "Add content";
    $domain = \Drupal::routeMatch()->getParameter('arg_0');
    $this->derivatives['example.action_id']['route_parameters'] = [
      'domain' => $domain
    ];
    return $this->derivatives;
  }
}

```

But the param of the local action button is only updated after I clear the cache. I have to clear the cache each time I use different parameter value in the URL.

**What's the correct way to pass dynamically this argument?**

# Answer
> 3 votes
Local actions and local tasks are quite similar, so looking at the Customising local task behavior I've managed to pass in dynamic route parameters to my local actions by specifying the ***class*** parameter (MyClassName) in my\_module.links.action.yml and overriding the LocalActionDefault::getRouteParameters() method in that class. Only one initial cache rebuild was required.

```
use Drupal\Core\Menu\LocalActionDefault;
use Drupal\Core\Routing\RouteMatchInterface;

class MyClassName extends LocalActionDefault {

  public function getRouteParameters(RouteMatchInterface $route_match) {
    return array(
      'my_local_action_parameter' => $route_match->getParameter('existing_parameter_from_route')
    );
  }
}

```

# Answer
> 1 votes
Since it's a cache issue, awaiting an official fix, I solved it by rebuilding actions on the page in question:

```
function my_module_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'view.affiliated_content.page_1') {
    \Drupal::service('plugin.manager.menu.local_action')->clearCachedDefinitions();
  }
}

```

---
Tags: 8, uri, domain-access
---


title: Issues with view preview

text:
# Question
Title: Issues with view preview
I'm having an issue when creating a new view. The preview pane, upon refreshing/updating" will, instead of updating in the preview section, force the window to navigate to "admin/structure/views/view/MyView/preview/default/" . It doesn't matter is "auto preview" is checked or if I manually press the "update preview" button. I have no idea what i changed recently to start getting this behaviour. My initial thought is that I removed an important js class from a template but I haven't been able to identify which one. I also know it's a theme issue because reverting to any other stable theme fixes the problem!

Is there a better resource for finding what classes are important for core ajax components because I can't find much on the official documentation. Additionally, has any experienced this and know what I might have changed to get this behavior?

# Answer
I figured out my problem and it had to do with classes as I suspected. For whatever reason, a snippet of javascript that was not previously interfering with the preview functionality just recently started breaking the view. I'm still not entirely sure why but I'm guessing I removed the class in another template and so it was never being rendered and now my javascript was overwriting it.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How do I index all the content with the search_api module?
I am using the Search API module with Search API Solr. When I visit my index page at http://example.com/admin/config/search/search-api/index/my-example-index, I see the "Index Now" button is disabled and inactive. I see "Content (7796/7796 indexed)" for the data source. However, recent content items are not showing up in my search results.

At admin/config/search/pages, I see "6% of the site has been indexed. There are 7693 items left to index." Ok, how do I index the rest?

I know that not all content is indexed, because recent content is not showing up in search results. I don't want to index just 50 or 100 content items at this time. I want to index everything, so all content can show up in search results.

# Answer
You must click the "Queue all items for reindexing" link that appears below the "Start Indexing Now" fieldset, and then once you run that process, you can return to the index UI (example.com/admin/config/search/search-api/index/my-example-index) and at that point the "Index Now" button is active.
> 0 votes

---
Tags: 8, search
---


# Question
Title: How do I enable and weight fields through .yml?
I have a custom module where I succesfully created a field for videos. But I want the field to be enabled and weighted on by default. I supposed active and widget-\>weigth and display-\>weight was the way to go but it's disabled.

```
id: media.field_video_alt_text
field_name: field_video_alt_text
entity_type: media
bundle: video
label: 'Alternativ tekst'
description: 'Kort beskrivelse som vises under videoen. Lad feltet være tomt, hvis dette ikke ønskes.'
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: string
active: true
widget:
  weight: 2
display:
  weight: 1
  label: hidden

```

# Answer
> 0 votes
Adding formatters or widgets to field configuration doesn't work. You have to add them to the existing display modes in hook\_install().

See entity\_get\_display and entity\_get\_form\_display, which are deprecated, but contain examples how to add components to display modes and code replacing the deprecated functions to load the entity displays.

---
Tags: 8
---


# Question
Title: How to alter response headers from module hook
I am puzzled how to alter the response headers from specific hook (hook\_file\_download)?

```
/**
 * Implements hook_file_download().
 */
function example_file_download($uri) {
  $scheme = FileSystem::uriScheme($uri);
  if ($scheme === 'public') {
// Set custom headers here.
  }

}

```

Basically I want under certain conditions to set additional headers and in D7 this would happen with drupal\_add\_http\_header() but in D8 as far as I can see this can happen only by implementing custom subscriber and using getSubscribedEvents and then KernelEvents. However this does not solve my case as I want to add custom headers only for specific file types.

If I use custom subscriber then this would be possible by:

```
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = ['exampleFunc'];

return $events;
}

```

And then:

```
/**
*
*/
public function exampleFunc(FilterResponseEvent $event) {

$response->headers->set('Header', 'Value');
}

```

# Answer
> 1 votes
> in D7 this would happen with drupal\_add\_http\_header()

In other hooks that might have been true, but `hook_file_download` works the same in Drupal 8 as it did in Drupal 7, without using `drupal_add_http_header`.

This is the documentation for both versions’ return value from that hook:

> If the user does not have permission to access the file, return -1. If the user has permission, **return an array with the appropriate headers**. If the file is not controlled by the current module, the return value should be NULL.

Emphasis mine.

You can't get access to the response object in `hook_file_download`, because it doesn't exist yet. It's not created until after the hook is invoked in `FileDownloadController::download()`. The headers you return are added to the response, so returning a suitable key-value array from the hook is the way to achieve what you want.

---
Tags: 8, files, event-subscribers
---


title: Retina image support (@1x @2x @3x)

text:
# Question
Title: Retina image support (@1x @2x @3x)
I've been struggling for a while to figure out how to support higher pixel density screens for my images in drupal. I have 3 variations for every image on the site (@1x, @2x, @3x) but I haven't been able to find an easy way to use them. I searched around and found articles like: https://www.advomatic.com/blog/adding-responsive-images-to-your-drupal-8-site and https://evolvingweb.ca/blog/making-drupal-websites-retina-ready

but they usually talk about using the retina module for drupal which seems to not pass security adviory policy or are just adding different image styles and using the picture tag. Is there no way to use just srcset and using 3 different images for different dpi in drupal?

Ideally I'd like to have an image field which will just let me upload 3 images for different dpi.

# Answer
I think the answer from @ipwa is close but is not quite there.

What you want is an output like this:

```
<img src="/fallback.jpg" srcset="/1x.jpg 1x, /2x.jpg 2x, /3x.jpg 3x" />

```

Here's what you need to do:

1. Enable both the Breakpoint and Repsonsive Image Style modules.
2. Add an image field for uploading 1 image to a content type. Editors should upload the highest quality image needed.
3. Configure three normal image styles that produce the desired resolutions for each of the 1x, 2x, and 3x pixel densities.
4. In your theme, or a custom module, create a breakpoint yaml file with the following contents:

```
my_module_or_theme.image_pixel_density_only:
  label: Pixel Density Only
  mediaQuery: ''
  weight: 0
  multipliers:
    - 1x
    - 2x
    - 3x

```
4. Rebuild caches.
5. Add a new responsive image style.
6. Configure the responsive image style so that it uses the breakpoint group that you just created. This should expose a 1x, 2x, and 3x fieldset. For each of these fieldsets, select type "Select a single image style." and choose the appropriate image style.
7. Configure the image field formatter for image field you created in step 1 to use the responsive image style you just created.

Drupal will output the srcset just like I described above and will not output a "sizes" attribute (which you don't need). Browsers will know what the pixel density is of the device and automatically select the most appropriate image based on that.
> 1 votes

# Answer
You can do this in Drupal 8 with just core:

1. Skip creating specific breakpoints in your theme, they aren't needed with this approach.
2. Setup your different image styles at admin/config/media/image-styles. Usually something like, Author Small, Author Medium and Author Large.
3. Create a responsive image style at admin/config/media/responsive-image-style. Make sure the Responsive Image module is enabled first.
4. Ensure "Responsive Image" is selected for the "Breakpoint group".
5. Choose a suitable "Fallback image style". Click "Save". The following screen is where the secret sauce is.
6. Under the "1x Viewport Sizing \[\]" fieldset, Select "Select multiple image styles and use the sizes attribute."
7. Select each of Image styles you'd like to use.
8. Adjust the Sizes value as needed. The default here 100vw is hard-coded for a good reason, it's a pretty sane default and works well in most situations. Customize this is you want even finer control.

From: https://chromatichq.com/blog/responsive-images-drupal-8-using-srcset
> -1 votes

---
Tags: theming, entities, media
---


title: Is MySQL 5.7 compatible?

text:
# Question
Title: Is MySQL 5.7 compatible?
My server has been on MySQL 5.6 for quite awhile and now I need to upgrade to MySQL 5.7. Is it safe to upgrade to 5.7 for all of my Drupal 7.x sites? Just doing a quick google for *drupal 7 mysql 5.7*, I get a few people reporting issues when updating with Drupal 7.x.

# Answer
Yes. MySQL 5.7 is compatible with D7.x. Per the docs:

> Drupal 7 supports MySQL 5.0.15/MySQL 5.1.30/MariaDB 5.1.44/Percona Server 5.1.70 or higher, and requires the PDO database extension for PHP (see What is PDO?).

Is it safe? *Maybe*. It depends on your code/infrastructure setup.

Just because a web application is compatible with a version of a DB server, doesn't mean an upgrade will happen flawlessly. There can be many things that could go wrong (e.g. hidden dependencies).

It will *probably* be fine with a minor version upgrade, but always have a test/backup plan in place when rolling out infrastructure changes.
> 3 votes

---
Tags: 7, database
---


title: push jsonlog data to elasticsearch

text:
# Question
Title: push jsonlog data to elasticsearch
I have installed the module jsonlog on drupal 7, but there are no information on how can I push the logs to elasticsearch or kibana or logstash. How do I do that?

# Answer
> 2 votes
As JSONlog project page states:

> Logs watchdog events JSON-formatted to log files. **Provides a Logstash/ElasticSearch-ready log source**.

The module only does one thing: turn Drupal watchdog events into JSON-loggable files and writes them to whatever server dir you've configured for it.

Before using this module you will need to:

* Setup ElasticSearch & Kibana. This is a separate task from setting up LogStash. It will depend on your service provider (this is off-topic for Drupal Answers).
* Setup LogStash. This will vary based on whatever app server you're running Drupal on. You'll have to find instructions applicable to the app server running Drupal.

---
Tags: 7
---


# Question
Title: How to return a View's content in search results?
We have a page display of a view that contains two or more nodes, but when searching for a keyword that would pertain to those nodes, only links to the individual nodes are returned. What we really want is just the link to the page display of the view to be returned, but it doesn't show up in the results list.

I'm looking into caching the View and index the cached content through a custom module, but i was wondering if anyone has come across this situation and can share their solution?

edited: made some clarifications.

# Answer
> 1 votes
There is the Search by Page module that allows this (and much more). Some details from its project page:

> This module is an enhancement to the core Drupal search module, which adds a new tab to the core Search page or can also be used in stand-alone mode. The differences between Search by Page and the existing tabs in the core Search module lie in what is indexed for searching and how it is indexed:
>
> * Search by Page indexes the content of your pages as rendered by your theme (Search indexes the default rendering you would have from an unmodified theme)
> * Search by Page allows you to omit content from indexing (such as "database table" node types that should never be viewed as stand-alone content)
> * Search by Page allows you to index non-Node pages, including user profiles, file attachments, and Views
> * Search by Page is language-aware, so it only shows you results in the current language.
> * Search by Page has multiple search "environments", so you can have different search pages/blocks to search different things.

Maybe you can use that or look how they index the views pages.

# Answer
> 0 votes
Search in drupal is entirely themeable - meaning you can alter the markup.

@see

You could invoke your view programmatically in search-result.tpl.php using an argument of nid

# Answer
> 0 votes
From your question, it is very hard to determine if you are talking about an actual view, or search. But I'm going to assume you are talking about a view that has an exposed filter.

When you create a view with an exposed filter, the results upon submission usually stay formatted the same unless another display is involved. In the case that another display is taking care of results, then you would simply modify that display to format the results in the desired way, by either changing the style or the fields being displayed and their options.

It would help if you could explain your question a bit more, providing details on the actual view's setup/structure. This is actually the reason Earl first created the ability to 'export' a view. If you can provide an export of your view, it will be easier for others to help you.

# Answer
> 0 votes
> "The view containing the nodes is what i want to return when searching for a keyword that is part of its content, and not the nodes themselves"

You can either let views handle all your searching on your site, or embed the view into your search-results.tpl.php, but the latter is counter productive.

# Answer
> 0 votes
i have been struggling for customizing "D8 Search Index". Though there are many solutions and discussion, it's really not possibly to get it configured the way you want, unless you really get your hands dirty with twig templates.

i believe in less coding. This allows end-user to customize things without actually entering the code. So i was looking to avoid coding as much possible.

"search pages" in "search & meta" config gives you path of /search/node. Create your own view and give it path "search/node" Then add contextual filter "search keyword" and select "provide default value" as "query parameter"... there specify parameter as "keys" .. customize other things like title, grouping as you may want. dont forget cache! views gives you lot of power!

Check output by searching. see my search page with grouping "https://shabdakosh.marathi.gov.in/search/node?keys=knowledge"

---
Tags: views, search
---


# Question
Title: How do I increase the length of a text-field with saved values?
I have a multi-value text-field, *projects*. Its length is 4, and I would like to increase it to 255, but there are values saved in the database for that field.

How can I increase its length?

# Answer
I got an answer from my friend as well. I would like to share his code here:

```
/**
 * Update field.
 */
function MODULE_update_8301() {
  $db = \Drupal::database();
  $field_name = 'field_MY_TEXT_FIELD';
  $table_prefixes = [
    'node',
    'node_revision'
  ];
  foreach ($table_prefixes as $table_prefix) {
    $db->schema()->changeField(
      "{$table_prefix}__{$field_name}",
      "{$field_name}_value",
      "{$field_name}_value",
      [
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
      ]
    );
  }

  $config = \Drupal::configFactory()->getEditable('field.storage.node.' . $field_name);
  $settings = $config->get('settings');
  $settings['max_length'] = 255;
  $config->set('settings', $settings);
  $config->save();
}

```
> 4 votes

# Answer
The schema of a field is not changeable until it has data inside. There can be many scenarios like you have multiple languages, or revisions are important etc, but the following steps can be an abstract approach of the situation:

1. Keep in memory (variable) or save all the field values, which host field you are about to manipulate
2. Delete your old field and import the new one (you can do it based on the YML file itself)
3. Backup all the information with help of the EntityTypeManager.

This is indeed an advanced part of Drupal, but once you master it, updates like this will work like charm.
> 1 votes

# Answer
I tried the answer of asrob, but it doesnt work with entity update (drush entup).

There is a better solution using Drupal API. The code is from here: https://coderwall.com/p/uyidlq/updating-the-storage-definition-of-entities-that-already-have-content-in-drupal-8

```
/**
 * Increase FIELD size to 50.
 */
function MODULE_update_8XXX() {
  $database = \Drupal::database();
  // Retrieve existing field data.
  $entity_type = 'ENTITY_TYPE';
  $field = 'FIELD_NAME';
  $tables = [
    "{$entity_type}__$field",
    "{$entity_type}_revision__$field",
  ];
  $existing_data = [];
  foreach ($tables as $table) {
    // Get the old data.
    $existing_data[$table] = $database->select($table)
      ->fields($table)
      ->execute()
      ->fetchAll(PDO::FETCH_ASSOC);

    // Wipe it.
    $database->truncate($table)->execute();
  }

  $field_storage_configs = \Drupal::entityTypeManager()
    ->getStorage('field_storage_config')
    ->loadByProperties([
      'field_name' => $field,
    ]);
  foreach ($field_storage_configs as $field_storage) {
    $new_field_storage = $field_storage->toArray();
    $new_field_storage['settings']['max_length'] = 50;

    $new_field_storage = FieldStorageConfig::create($new_field_storage);
    $new_field_storage->original = $new_field_storage;
    $new_field_storage->enforceIsNew(FALSE);

    $new_field_storage->save();
  }

  // Restore the data.
  foreach ($tables as $table) {
    $insert_query = $database
      ->insert($table)
      ->fields(array_keys(end($existing_data[$table])));
    foreach ($existing_data[$table] as $row) {
      $insert_query->values(array_values($row));
    }
    $insert_query->execute();
  }
}

```
> 1 votes

# Answer
This is what I do. I would only use it to increase the length of a string. I have not tested, but assume that shortening a string will truncate data.

**First, backup the database.**

Then, edit the structure of the following tables (change yourfield to match the name of your field):

```
field_data_field_yourfield
field_revision_field_yourfield

```

Change the length of the field\_data\_field\_yourfield\_value field (VARCHAR) in both tables to the value you want. This allows the fields to hold more characters. But doesn't tell Drupal about the change in length.

Next, locate this table:

```
field_config

```

Find your field in the list and edit the **data** value. Look for a section like this:

```
s:10:"max_length";s:3:"100";

```

The length of the field in this example is 100. Change it to match the change you made earlier. If the number of characters changes (e.g. you increase it from 100 to 1000), change the s:3 value to reflect the new character count.

Flush all caches.

Edit the field on an entity type to which it is attached to verify that its length has changed.

Edit an entity with this field and verify that you are able to enter a value that is the new length.

That's all ....
> -1 votes

# Answer
Up-to-date method for Drupal 8 (for field name "`field_myfield`"):

1. Backup database
2. Edit structure for table `node__field_myfield`, set new length for column `field_myfield_value`.
3. Edit structure for table `node_revision__field_myfield`, set new length for column `field_myfield_value`.
4. Use Admin Toolbar Extra Tools module, top menu: go to Development \> Config editor
5. Filter by "field.storage.node.field\_myfield"
6. Edit the `max_length:` line under `settings:` to match new column length.
7. Flush all caches.
8. Enable the `entity_update` module.
9. `drush @miniloco upe --show`
10. Give up....

Will keep trying and will come and edit this if/when I find a solution.
> -1 votes

---
Tags: 8, entities, database
---


# Question
Title: Programmatically using values from a loaded entity inside a message
I am using Firebase module to send push notifications to a specific mobile user when a webform is submitted.

Below is my custom webform handler:

```
<?php

namespace Drupal\my_custom_module\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Send Push Notification when a webform submission is submitted.
 *
 * @WebformHandler(
 *   id = "Send Push Notification when a webform submission is submitted",
 *   label = @Translation("Send Push Notification when a webform submission is submitted"),
 *   category = @Translation("Push Notification"),
 *   description = @Translation("Send Push Notification when a webform submission is submitted"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class PushNotificationWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get (NID) from text element available on the webform.
    $nidvalue = $values["attached_node"];

    // Load the node.
    $node = \Drupal\node\Entity\Node::load($nidvalue);

    // Get (selected_node_owner) value from the User Entity reference element available on the webform.
    $nodeowner = $values["selected_node_owner"];

    // Get (token) value from the loaded node through the 'field_node_owner' Entity field.
    $usertoken = $node->field_node_owner->entity->field_user_push_token->value;

    // Send the Push Notification.
    // Token is generated by app. You'll have to send the token to Drupal.
    $messageService = \Drupal::service('firebase.message');
    $messageService->setRecipients($usertoken);
    $messageService->setNotification([
        'title' => 'Hello',
        'body' => 'Hello $nodeowner this is your body message',
        'badge' => 1,
        'icon' => 'optional-icon',
        'sound' => 'optional-sound',
        'click_action' => 'optional-action',
    ]);
    $messageService->setData([
        'score' => '3x1',
        'date' => '2019-04-05',
        'optional' => 'Data is used to send silent pushes. Otherwise, optional.',
    ]);
    $messageService->setOptions(['priority' => 'normal']);
    $messageService->send();
    }
}

```

Everything is working as expected but the 'Variables' are not rendering any values and printed as they are.

**Example:**

I am expecting the body of the notification message to be something like below (Say the **selected\_node\_owner** name is "Elie Masaad"):

```
Hello Elie Masaad this is your body message

```

but instead I am getting the below:

```
Hello $nodeowner this is your body message

```

**Module maintainer gave the below hint:**

You should use a Token or simple str\_replace for replacing something in string.

Can anyone guide me on how to pragmatically use tokens for my above requirement ?

# Answer
As Clive also mentioned use double quotes instead of single quotes to allow the variables to get replaced inside the string

```
'body' => "Hello $nodeowner this is your body message"

```

if `$values["selected_node_owner"]` gives you the UID here is how to get the username

```
$account = \Drupal\user\Entity\User::load($values["selected_node_owner"]);
$nodeowner = $account->getUsername();

```
> 2 votes

---
Tags: 8, tokens, notifications
---


# Question
Title: Trying to get property of non-object in simplenews_scheduler_node_page()
I am using simplenews\_scheduler in Drupal 7 to set up a weekly digest of new content. I am getting the following error on the screen and scheduled newsletters aren't going out, even after running cron. When I send it right away or send it as a test, it goes out and renders just fine.

> Notice: Trying to get property of non-object in simplenews\_scheduler\_node\_page() (line 600 sites/all/modules/simplenews\_scheduler/simplenews\_scheduler.module)

For reference, here is lines 598-601, referenced in the error:

```
foreach ($result as $row) {
    $node = node_load($row->eid);
    $rows[] = array(l($node->title, 'node/' . $row->eid), format_date($row->date_issued, 'custom', 'Y-m-d H:i'));
  }

```

I'm not sure this error is related as it seems to go only to loading editions already sent.

Drupal 7.65, simplenews 7.x-1.1, simplenews\_scheduler 7.x-1.0-beta2

Does anyone know what could be causing this error or an alternative to sending a scheduled mailing? The module makes a copy of a base node each for each edition so it's kind of nice.

# Answer
This issue was solved by deleting the node (master newsletter) and creating a new one. I had probably deleted a previous test edition, which caused it to start delivering the error. If there is only one test edition, don't delete it even if the master is preserved.
> 0 votes

---
Tags: 7
---


# Question
Title: How do I avoid "geo:" is removed from links?
I need to place on my site link with geo scheme:

```
<a href="geo:44.1234124,43.14314321432">some location</a>

```

But drupal cuts schema from link and i have following result:

```
<a href="44.1234124,43.14314321432">some location</a>

```

Is there any way to disable geo scheme filtering?

I'm using drupal 8.3.5, basic installation without any additional extensions(except autoinstalled during setup process).

UPD. I using view that displays some fields of custom nodes as HTML list. Most of fields marked as "excluded from output" and for one field i'm using html output override like this:

```
<a href="geo:{{ field_somefield }}">{{ field_linktitlefield }}</a>

```

field\_somefield and field\_linktitlefield is a simple text.

# Answer
You need to add geo as an allowed scheme. See https://blog.werk21.de/en/2017/06/06/change-list-valid-uri-schemes-drupal-8 for details.
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: Drupal 8 dropping session variables on password reset. Gives 403 Access Denied
I have a fresh install of Drupal 8.6.13, default everything with no custom themes or modules. It was created via:

`drupal-composer/drupal-project:8.x-dev` with the `drupal site:new` command.

When I use a one time login link I get a 403 access denied error because the session data (timestamp and hash) gets lost on the redirect from `UserController::resetPass` to `UserController::getResetPassForm`.

Here is the source code for reference: https://api.drupal.org/api/drupal/core%21modules%21user%21src%21Controller%21UserController.php/8.6.x

When I log the session variables when they are created in `resetPass` they are stored and show correctly.

When I then log the session variables on `getResetPassForm` they are no longer there. This causes the following code to execute which returns the 403:

```
if (!$hash || !$timestamp) {
  throw new AccessDeniedHttpException();
}

```

I'm not sure if this is a Drupal problem or Symfony problem or what.

Everything has worked fine on previous versions of Drupal 8.6.x. I noticed the issue when upgrading from 8.6.8 to 8.6.13. I have now tested with just a fresh install of 8.6.13 and am seeing this issue.

Server is Nginx.

Any ideas?

# Answer
This is an issue with symfony/http-foundation v3.4.24. See https://www.drupal.org/project/drupal/issues/3045844.
> 4 votes

---
Tags: sessions
---


title: Where do extra parameters come from?

text:
# Question
Title: Where do extra parameters come from?
Not a real issue but more of an informative question.

Concrete case:

**system.routing.yml** integrates **system.entity\_autocomplete** that uses `controller::method`

`\Drupal\system\Controller\EntityAutocompleteController::handleAutocomplete`. First parameter in `handleAutocomplete()` is `$request` and the rest are the ones we could explect from url.

Where did `$request` come from?

# Answer
> 1 votes
This is a feature provided by Symfony:

> # The Request object as a Controller Argument
>
> What if you need to read query parameters, grab a request header or get access to an uploaded file? All of that information is stored in Symfony's Request object. To get it in your controller, just add it as an argument and type-hint it with the Request class:
>
> ```
> use Symfony\Component\HttpFoundation\Request;
>
> public function indexAction(Request $request, $firstName, $lastName)
> {
>   $page = $request->query->get('page', 1);
>
>   // ...
> }
>
> ```

---
Tags: 8
---


# Question
Title: How do I execute a view in a custom module and print the output (as HTML markup)?
I want to print the output from a simple view in my custom module. But is doesnt work. I have tried many options from forums and stackoverflow. All of them print "array" instead of html-markup.

My controller:

```
class DefaultController extends ControllerBase {

    public function myfunc1() {

        $view = Views::getView('myfirstview');

        $view->setDisplay('page_1');
        $view->preExecute();
        $view->execute();

        // $myresults = $view->preview();  = array
        // $myresults = $view->render();  = array
        $myresults = $view->result; // = array

        return array(
            '#title' => 'Hello World!',
            '#markup' => $myresults,
        );
    }
}

```

How can I print the result/output of a view programmatically?

I dont want to make it without "embed view" , because I want to set some exposed filters later.

# Answer
Views implements its own render element type (`Drupal\views\Element\View`), which you can use like so:

```
return [
  '#title' => 'Hello world',
  'view' => [
    '#type' => 'view',
    '#name' => 'myfirstview',
    '#display_id' => 'page_1',
    '#arguments' => ['foo', 'bar'],
    '#embed' => TRUE,
  ],
];

```

If you need to manipulate the View before rendering it, (you mentioned exposed filters), you can do that first and pass along the object:

```
$view = Views::getView('myfirstview');
$view->setFoo('bar');

return [
  '#type' => 'view',
  '#name' => 'myfirstview',
  '#view' => $view,
  '#display_id' => 'page_1',
  '#embed' => TRUE,
];

```
> 2 votes

# Answer
Notes: The View has to be a block. Exposed filters can be added but will not be displayed on your page. You can set them in your page, eg for a 'severity' field:

```
$filters = $view->getDisplay()->getOption('filters');
$filters['severity']['value'] = [0,1,2,3,4,5,6]; // include a set of values.
$view->getDisplay()->overrideOption('filters', $filters);

```
> -1 votes

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


# Question
Title: Cannot configure the site as SAML SP with simplesamlphp_auth
I have a functioning SAML IdP, implemented with LemonLDAP::NG. I know it functions because it works with Nextcloud as an SP. I've also successfully configured a DokuWiki SP in the past.

The IdP, the Nextcloud SP and the Drupal 8 SP are all behind an Nginx reverse proxy. All of them are directly reachable from my IP, but I have restricted access from other IPs.

I have been trying on and off for a year to make SAML login work with Drupal 8, using `simplesamlphp_auth`, but without success. I have lost count of how many articles I have read on the net, which all suggest that configuring SAML is trivial. Sadly, not for me.

Currently, when I select the Drupal 8 SP under 'Test authentication sources' in the 'Authentication' tab, I get the following error:

> Too many redirects occurred trying to open “https://www.xxxx.tld/simplesaml/module.php/core/authenticate.php?as=wmh-www-sp&%5CSimpleSAML%5CAuth%5CState.exceptionId=\_568428306a7ad7ad7bf8f8f47a94940de364239c67%3Ahttps%3A%2F%2Fwww.xxx.tld%2Fsimplesaml%2Fmodule.php%2Fcore%2Fas\_login.php%3FAuthId%3Dwmh-www-sp%26ReturnTo%3Dhttps%253A%252F%252Fwww.xxx.tld%252Fsimplesaml%252Fmodule.php%252Fcore%252Fauthenticate.php%253Fas%253Dwmh-www-sp”. This might occur if you open a page that is redirected to open another page, which then is redirected to open the original page.

The log file contains repeated occurrences of the following error messages:

> 2019/04/03 22:31:48 \[error\] 21251#21251: \*982 FastCGI sent in stderr: "PHP message: simplesamlphp DEBUG \[e54b9408f4\] Session: 'wmh-www-sp' not valid because we are not authenticated.
>
> PHP message: simplesamlphp DEBUG \[e54b9408f4\] getIdpMetadata: METADATANOTFOUND('%' =\> '\\'https://cloud.xxx.tld/saml/metadata\\'')
>
> PHP message: simplesamlphp DEBUG \[e54b9408f4\] getIdpMetadata: METADATANOTFOUND('%' =\> '\\'https://cloud.xxx.tld/saml/metadata\\'')
>
> PHP message: simplesamlphp DEBUG \[e54b9408f4\] Saved state: '\_f37c552249cf34b640de1dac7ad22b1481c763fc0f:https://www.xxx.tld/simplesaml/module.php/core/as\_login.php?AuthId=wmh-www-sp&ReturnTo=https.xxx.tld.php.php-www-sp'
>
> PHP message: simplesamlphp DEBUG \[e54b9408f4\] saving key SimpleSAMLphp.session.161a8f86a89cf6e93f36117cc21a26af to memcache" while reading response header from upstream, client: NN.NNN.NNN.NNN, server: www.xxx.tld, request: "GET /simplesaml/module.php/core/authenticate.php?as=wmh-www-sp HTTP/2.0", upstream: "fastcgi://unix:/var/run/php-fpm-www.sock:", host: "www.xxx.tld", referrer: "https://www.xxx.tld/simplesaml/module.php/core/authenticate.php"
>
> 2019/04/03 22:31:48 \[error\] 21251#21251: \*982 FastCGI sent in stderr: "PHP message: simplesamlphp DEBUG \[e54b9408f4\] loading key SimpleSAMLphp.session.161a8f86a89cf6e93f36117cc21a26af from memcache" while reading upstream, client: NN.NNN.NNN.NNN, server: www.xxx.tld, request: "GET /simplesaml/module.php/core/authenticate.php?as=wmh-www-sp HTTP/2.0", upstream: "fastcgi://unix:/var/run/php-fpm-www.sock:", host: "www.xxx.tld", referrer: "https://www.xxx.tld/simplesaml/module.php/core/authenticate.php"

(`www.xxx.tld` is the SP, `cloud.xxx.tld`is the IdP, `wmh-www-sp` is the entityID of the SP.)

Specific things I do not understand:

* `we are not authenticated` \- I have logged into the `simplesamlphp_auth` interface
* `METADATANOTFOUND('%' => '\'https://cloud.xxx.tld/saml/metadata\'')` \- this is the address of the IdP's metadata and is correct as such

I created file `metadata/saml20-idp-remote.php` from the IdP's metadata URL, `https://cloud.xxx.tld/saml/metadata` using `simplesamlphp_auth`'s metadata converter under the "Federation" tab.

Can anyone help me to make sense of all the above?

Steve

# Answer
> 0 votes
The problem was - as so often - between the keyboard and the chair. I had some subtle mistakes in a couple of file paths in `config/config.php`. Apparently `simplesamlphp_auth` doesn't do any validation of file names, so mistakes blow up without any apparent context at runtime.

---
Tags: 8
---


# Question
Title: How do I get the weight of a multiple value field collection in a computed field?
I have the following structure in a content type:

. field\_collection\_parent (multiple value = 7)

.. computed field (single value)

.. field\_collection\_child (unlimited multiple value)

field\_collection\_parent represents the days of the week and field\_collection\_child are some work reports of each day. The computed field returns the day (monday, tuesday, etc.)

The problem is that I can have data in the first and thrid items of the field\_collection\_parent (that is Monday and Wednesday), but when I save the node, I only have two rows, because the second was empty, and computed returns Monday and Tuesday.

So, is it possible to get the weight of each field collection item although they were empty, and code it in the computed field?

Thanks.

P.D. I tried

```
$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$entity_field[0]['value'] = print_r($wrapper->delta(), true);

```

as indicated in "how to get weight or delta of current field collection item that is being computed" but it returns "Fatal error: Call to undefined method EntityDrupalWrapper::delta()"

# Answer
Ok, finally I got a workaround. I was focussed on entities and computed field, but it turned out to be a death end. So, I change the approach and found the rules\_form module.

This modules allows apply a rule in the node form, so I created an integer field called delta in my field\_collection\_parent and populate it with rules when the form is created. In this way, I always keep a seven-rows field\_collection\_parent even though the field\_collection\_child is empty (because the field delta is filled).
> 0 votes

---
Tags: entities
---


# Question
Title: I want to override the template of the contact page
I use bootstrap as theme in Drupal 8, and I created a sub-theme. I want to override the contact page with a custom template.

I added `debug: true` in services.yml, but I didn't find the right template to recreate it in the sub-theme.

# Answer
> 5 votes
The contact page is a form, so you can theme it like any usual form:

* Implement hook\_theme in your theme to tell drupal you want to theme the form.
* Create the template file

**Example**

```
/**
 * Implements hook_theme().
 */
function <your theme>_theme($existing, $type, $theme, $path) {
  return [
    '<your form id here>' => [
      'render element' => 'form',
    ],
    '<another form id, if you have multiple contact forms>' => [
      'render element' => 'form',
    ],
  ];
}

```

The form id depends on the machine name of your contact form. For example, if your contact form is named 'feedback', the form id will be

```
contact_message_feedback_form

```

Now drupal will by default look for the template file

```
contact-message-feedback-form.html.twig

```

Place the twig file in where Drupal can find it, i.e. under the templates folder in your theme.

At the minimum, what you need in that twig template file is

```
{{ form }}

```

But you can control what is printed by doing so:

```
<div class="from">
  {{ form.mail }}
</div>

<div class="message">
  {{ form.message }}
</div>

<div class="actions">
  {{ form.actions }}
</div>

{# Renders the rest of the form #}
{{ form|without('mail','message','actions') }}

```

# Answer
> 2 votes
You could use hook\_theme\_suggestions\_HOOK to suggest a new template to use for your form. Currently I have this which will allow me to create templates for forms that I create in the future without having to add them each time:

```
function MODULE_NAME_theme_suggestions_form($variables) {
  // Specific templates for contact forms.
  $suggestions[] = 'form__' . $variables['element']['#theme'][0]; // Machine name of form.
  return $suggestions;
}

```

# Answer
> 2 votes
@joekers's answer may work for modules; however, here's how to accomplish this in themes. First, put this in your .theme file:

```
function themename_theme_suggestions_form_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'form__' . $variables['element']['#form_id'];
}

```

Be sure to replace "themename" with the machine name of your theme.

Second, create a template named `form--machine-name-of-form.html.twig`. For example, `form--node-page-form.html.twig` would be a valid template suggestion.

# Answer
> 1 votes
You could override it in two ways:

1. Copy the relevant twig file from the (core) module directory to your theme directory and change it there.
2. Customize the form as much as you can from the GUI. To customize the general appearance of the form page\node, Use GUI-level theming modules like Context and modules like Block\Panels in the peripheral - Block, level.

# Answer
> 0 votes
I know its and old question,but to the ones who still needs a solution, open Your drupal template .theme file and paste this code

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

  // Name
  $form['name']['#prefix'] = '<div class="row"><div class="col-md-12"><div class="form-group">';
  $form['name']['#suffix'] = '</div>';
  $form['name']['#attributes']['placeholder'][] = $form['name']['#title'].'*';
  $form['name']['#attributes']['class'][] = 'form-control';
  unset($form['name']['#title']);

  // Mail
  $form['mail']['#prefix'] = '<div class="form-group">';
  $form['mail']['#suffix'] = '</div>';
  $form['mail']['#attributes']['placeholder'][] = $form['mail']['#title'].'*';
  $form['mail']['#attributes']['class'][] = 'form-control';
  unset($form['mail']['#title']);

  // Subject
  $form['subject']['widget'][0]['value']['#attributes']['class'][] = 'form-control';
  $form['subject']['widget'][0]['value']['#attributes']['placeholder'][] = $form['subject']['widget'][0]['#title'].'*';
  $form['subject']['widget'][0]['#title'] = '';
  unset($form['subject']['widget'][0]['value']['#title']);
  $form['subject']['widget'][0]['#prefix'] = '<div class="form-group">';
  $form['subject']['widget'][0]['#suffix'] = '</div></div>';

  // Message
  $form['message']['widget'][0]['value']['#attributes']['class'][] = 'form-control';
  $form['message']['widget'][0]['value']['#attributes']['placeholder'][] = $form['message']['widget'][0]['#title'].'*';
  $form['message']['widget'][0]['#title'] = '';
  unset($form['message']['widget'][0]['value']['#title']);
  $form['message']['widget'][0]['#prefix'] = '<div class="col-md-12"><div class="form-group">';
  $form['message']['widget'][0]['#suffix'] = '</div></div></div>';

  // Submit
  $form['actions']['#prefix'] = '<div class="clearfix">';
  $form['actions']['#suffix'] = '</div>';
  $form['actions']['submit']['#attributes']['class'][] = 'btn';
  $form['actions']['submit']['#attributes']['class'][] = 'btn-success';
  $form['actions']['submit']['#attributes']['class'][] = 'pull-right';

}

```

where your YOURTHEMENAME is the real name of your Drupal template, hope it help someone

---
Tags: 8, emails
---


# Question
Title: Cannot instantiate interface DrupalStreamWrapperInterface
I am trying to replace drupal\_realpath with realpath. What I did is

```
$stream_wrapper = new DrupalStreamWrapperInterface();
$file_path = $stream_wrapper->realpath($img_path);

```

But it gives me this error: `Cannot instantiate interface DrupalStreamWrapperInterface`. Any idea how do I use DrupalStreamWrapperInterface::realpath?

# Answer
> 4 votes
The error is because you are trying to create an object of a PHP Interface, which is not allowed in PHP. You can only create objects from a PHP Class.

To solve your issue, something like this might work:

```
$wrapper = file_stream_wrapper_get_instance_by_uri($img_path);
if (is_object($wrapper)) {
  $file_path = $wrapper->realpath();
}

```

---
Tags: 7, stream-wrappers
---


title: Ajax form content security policy

text:
# Question
Title: Ajax form content security policy
Conversation around: how to set content-security-policy header read and noted

https://www.drupal.org/project/csp (Drupal 8 only) mentioned unsafe-inline is mandatory for WYSIWYG edits to work.

My question is that when I use a standard Ajax form with CSP enabled to default, I get the following upon clicking the submit button.

"Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self'" Either the 'unsafe-inline' keyword, a hash (\[redacted\]), or a nonce ('nonce-...') is required to enable inline execution."

How can I add either a hash or a nonce to Ajax forms?

Do all Drupal 7 websites require unsafe-inline for any WYSIWYG fields to work? Is that likely to be fixable?

# Answer
> 1 votes
`script-src 'unsafe-inline'` is required by CKEditor 4 included in Drupal 8 core, so a newer WYSIWYG editor may not require it. Drupal 9 will hopefully include CKEditor 5, which will not require `'unsafe-inline'`. CSP Level 3 also introduces the `script-src-attr` and `script-src-elem` directives, which can be used to allow only scripts in element attributes and not `<script>` elements, which will enable CKEditor 4 to work and reduce risk.

Drupal 7 also requires inline scripts be allowed for `drupalSettings`, though there is a patch available.

---

Hashes and nonces have some downsides and challenges

* CSP Level 2 only allows hashes on inline `<script>` elements, not element attributes like `onclick`. CSP Level 3 introduces `'unsafe-hashes'` to allow hashes for attributes, but it can't really be used at this time because of a lack of browser support.
* CKEditor 4 would require a 1.5KB CSP header for all of the hashes it would require.
* Nonces are only applicable to `<script>` elements.
* Nonces must be regenerated on each page load, preventing the page cache or other front-end caches from being able to cache the page.

---
Tags: 7, security
---


# Question
Title: text_format field value not appearing in full_html mode
I'm using a block plugin to display content based on what the user inputs into a form. Select boxes, and radio buttons are saved and displayed in the form just fine but the text\_format field isn't working the same way.

```
public function blockForm($form, FormStateInterface $form_state){

    $form['bodytext'] = array(
      '#type' => 'text_format',
      '#title' => $this->t('Block contents'),
      '#format' => 'full_html',
      '#description' => $this->t('This text will appear in the block.'),
      '#default_value' => $this->configuration['bodytext-submit'],
    );
}

public function blockSubmit($form, FormStateInterface $form_state) {

    $this->configuration['bodytext-submit']  = $form_state->getValue('bodytext');
}
public function build(){

    return array(
        '#title' => '',
        '#type' => 'markup',
        '#markup' => '<div>' . $this->configuration['bodytext-submit']['value'] . '</div>',
    );
}

```

Anything input into the text\_format element in the form is saved properly but when returning to the form, the field is empty unless the format is set to 'basic\_html'. So I know the values are being saved, and are even presently available in the configuration form of the block. It simply isn't displayed in 'Full\_html' mode.

# Answer
> 1 votes
I was able to resolve this by eliminating the '#format' specification in the blockForm function and specifying the value of bodytext-submit rather than just bodytext-submit. Like so

```
    $form['bodytext'] = array(
      '#type' => 'text_format',
      '#title' => $this->t('Block contents'),
      '#description' => $this->t('This text will appear in the block.'),
      '#default_value' => $this->configuration['bodytext-submit']['value'],
    );

```

# Answer
> 2 votes
You don't need to eliminate the #format.

The format and value of the text\_format are stored as an array. So in the same way as you retrieve the value you can retrieve the format.

See this example:

```
public function blockForm($form, FormStateInterface $form_state) {

  $body = !empty($this->configuration['body']) ? $this->configuration['body'] : '';
  $form['body'] = array(
    '#type' => 'text_format',
    '#title' => 'Body',
    '#format' => isset($body['format']) ? $body['format'] : 'full_html',
    '#default_value' => isset($body['value']) ? $body['value'] : '',
  );
  return $form;
}

public function blockSubmit($form, FormStateInterface $form_state) {
  $this->configuration['body'] = $form_state->getValue('body');
}

```

---
Tags: forms, 8, plugins
---


title: Hook naming conflicts: what happens?

text:
# Question
Title: Hook naming conflicts: what happens?
If two modules implementing two separate hooks ended up with functions with the same name, could that cause a conflict or problem?

### a.module

```
/**
 * Implements hook_a_b().
 */
function a_a_b() {}

```

### b.module

```
/**
 * Implements hook_b().
 */
function b_b() {}

```

### c.module

```
/**
 * Implements hook_a_b().
 */
function c_a_b() {}

```

### c\_a.module

```
/**
 * Implements hook_b().
 */
function c_a_b() {}

```

Does the scoping prevent that from causing a problem, even though the functions have the same names?

What happens if two modules declare the same hooks, even though they follow the naming scheme and the hook names contain the module names?

### a.module

```
/**
 * Implements hook_a_b_c().
 */
function a_a_b_c() {}

```

### a\_b.module

```
/**
 * Implements hook_a_b_c().
 */
function a_b_a_b_c() {}

```

### x.module

```
/**
 * Implements hook_a_b_c().
 *
 * It's not clear which of the two hooks this actually implements.
 */
function x_a_b_c() {}

```

# Answer
Hooks are plain PHP functions that follow a specific name schema. As such, the same function name cannot be used from two modules. Furthermore, Drupal is not able to understand if `c_a_b()` is the implementation of `hook_a_b()` done from c.module, or the implementation of `hook_b()` done from c\_a.module. To answer the question, yes, there would be conflicts and (in the case both the modules are installed) PHP errors.

Use something other than a single underscore for hook namespacing aims to not use a single underscore to separate the module name from the hook name, for example two underscores. Doing so, `c__a_b()` would be an implementation of `hook_a_b()` done from c.module, and it would not be confused with `c_a__b()`, the implementation of `hook_b()` done from c\_a.module.
There is also Module names should not contain an underscore, which would avoid any ambiguity with `c_a_b()`. As underscores would not be allowed in module machine names, `c_a_b()` could just be the implementation of `hook_a_b()` done from c.module. (That feature request is set to *closed (won't fix)*; at the moment, it's not going to be implemented.)

As for two modules invoking the same hook for different purposes and/or with different parameters, that is going to cause conflicts and errors.
The code invoking hooks calls a function basing on its name (`<module>_<hook name>`) directly passing the arguments to the function. If the arguments don't match the function parameters, PHP will raise an error; if the arguments match the function parameters, there will be other errors, as a hook supposes to be invoked in a specific moment, as described in the hook documentation. Imagine what would happen if a module would invoke `hook_user_delete()` after a user deleted a node; the modules implementing it would delete the data associated to that account from their database tables, since `hook_user_delete()` is documented to be invoked before a user account is deleted, not any data associated to the deleted node.

In both the cases, the only solution is naming hooks and modules in a way to avoid conflicts.

As per https://www.drupal.org/project/hook, that URL returns a 403 error because there is an unpublished project. (I can visit the project page because I have more permissions than what other people normally have on drupal.org.)

>

The project has been created to avoid somebody would name a project Hook.
> 5 votes

# Answer
All hooks are in the global scope; PHP doesn’t allow two functions to have the same name in the global scope (it wouldn’t be able to distinguish which the intended callee was). It will exit with a fatal error during parsing.

Yes, there is a definite potential for conflicts in the style you mentioned, but I doubt you’ll see it happen that often in the real world.

I’m not really sure what you mean by the 2nd example. Modules don’t “declare” hooks as such, not in any programmatically significant way at least, they just invoke them (and hopefully document them in an include api file).

There’s the `hook_hook_info` concept, but that’s just for allowing hooks to be implemented in an automatically included sub-file of a module.
> 2 votes

---
Tags: hooks
---


# Question
Title: Start with multiple entity reference items
In Drupal 8, I have created an entity reference to an "author" taxonomy on a content type. The form display settings are set to autocomplete. By default it starts with one field and you can click "Add another item" to add more. Yet usually we are adding content with multiple authors, so to make the form more user-friendly, would it be possible to start with four fields by default?

To add clarity to the question, the field currently starts like this by default:

I want it to start like this:

Any suggestions?

# Answer
Try Unlimited fields settings module may help you.
> 2 votes

# Answer
You can enter the default values in your Field settings which is useful is you often need to enter the same combination of authors.

This will display the default values in their own "rows".

But it may be counterproductive if there are no commonly used combinations in your case.

You could limit the field to a certain number of values instead of `Unlimited`. Then the form element would display the exact number of input fields. This can work if the number of values you need to enter will never exceed some number.

If this is also not acceptable you can use a different widget completely: instead of Autocomplete use `Select list` or `Check boxes/radio buttons`. You can change that on the `Manage form display` page for the content type.

Other than that you can modify the deafault look of your widget through your theme with some custom code.
> 0 votes

---
Tags: forms
---


# Question
Title: What do I need to pass to the Image class as the first parameter?
I'd like to use the Image API directly to perform few simple operations with images (I'm aware of image styles and for various reasons I would prefer to not use image styles for the application I'm working on). The trouble I'm having is what I need to pass to the Image class as the first parameter. The constructor of the Image class expects an `ImageToolkitInterface $toolkit` as the first parameter. I'm not sure what to plug in for it.

Hunting around the forums, I see people have used `\Drupal::service('image.toolkit')` to pass in as the first parameter however this isn't working for me.

Here is a snippet of one of the operations I'm attempting to perform. Feel free to pan my whole approach.

```
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Image\Image;

class myImageController extends ControllerBase {

  public function imageHeight() {

    $image_path = 'public://path/to/image.jpg';

    $image = new Image(\Drupal::service('image.toolkit'), $image_path);

    $image_height = $image->getHeight();

    ksm([$image_height]);

    return [

      '#markup' => $this->t('Did this work?'),
    ];
  }
}

```

Does anyone know what I should use to pass in as the first parameter? I'm only using the default GD2 Image toolkit. Also, I'm on Drupal 8.6. Thanks!

# Answer
> 1 votes
```
$image = \Drupal::service('image.factory')->get($image_path);

```

See the whole usage

---
Tags: 8, media
---


# Question
Title: How to add a checkbox to form builder component settings form?
I have webform and formbuilder modules installed.

In the file field settings form I want to add an extra checkbox field just like the required field but I am unable to do that.

I can add it to the `webform_component_edit_form` like the following

```
$form['validation']['check'] = array(
      '#type' => 'checkbox',
      '#title' => t('Check'),
      '#default_value' => ($component['check'] == '1' ? TRUE : FALSE),
      '#description' => t('Check this option if the user should be able to upload files.'),
      '#weight' => -1,
      '#parents' => array('check'),
    );

```

But it is not displaying in the `formbuilder` file settings edit form `form_builder_field_configure`.

Is there any way to add a field to `form_builder_field_configure` form and save with the node just like other fields?

# Answer
> 0 votes
you have to do it inside the form\_id 'form\_builder\_field\_configure'. Example :

```
hook_form_alter($form,$form_state,$form_id){
`switch($form_id){
     case 'form_builder_field_configure':
     // You put your code here
     $form['check'] = array(
       '#form_builder' => array(
         'property_group' => 'validation'
       ),
       '#type' => 'checkbox',
       '#title' => t('Check'),
       '#default_value' => '',
       '#description' => t('Check this option if the user should be able
    to upload
     files.'),
      '#weight' => -1,
);
  break;
 }

```

} \`

I hope it'll help you.

---
Tags: 7, webforms
---


# Question
Title: After failing to remove fontyourface I'm left with PluginNotFoundException
I ran into the error described in this issue when uninstalling the google\_fonts\_api used by @font-your-face: https://www.drupal.org/node/2916712

I tried going through some manual uninstall steps for google\_fonts\_api and fontyourface. But now I'm stuck when trying to enable/disable other modules or clearing the cache with this recurring error:

```
exception 'Drupal\Component\Plugin\Exception\PluginNotFoundException' with message 'The "entity:font" plugin does not exist.' in                           [error]
/srv/bridgemojo.com/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php:52
Stack trace:
#0 /srv/bridgemojo.com/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryCachedTrait.php(25):
Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition(Array, 'entity:font', true)
#1 /srv/bridgemojo.com/core/lib/Drupal/Core/Plugin/Factory/ContainerFactory.php(16): Drupal\Core\Plugin\DefaultPluginManager->getDefinition('entity:font')
#2 /srv/bridgemojo.com/core/lib/Drupal/Component/Plugin/PluginManagerBase.php(84):
[...]

```

I've tried truncating the cache tables. I'm stuck with trying to manually remove any references to this plugin.

If there's no successful cleanup possible, I'll have to rebuild the site from scratch, but I'm afraid I'll lose all of the content I have created.

# Answer
For others who might land on this problem, I gave up on solving it, and rebuilt my site from scratch. Luckily it wasn't a major effort.
> 0 votes

# Answer
I stumbled upon the same issue and solved it with these commands:

reinstall via `composer require drupal/fontyourface`, but do not enable it

```
drush config-delete views.view.fontyourface_font_manager
drush config-delete taxonomy.vocabulary.font_classification
drush config-delete taxonomy.vocabulary.font_designer
drush config-delete taxonomy.vocabulary.font_foundry
drush config-delete taxonomy.vocabulary.font_tags

```

see if other settings by a `drush config-edit` hope this helps
> 0 votes

---
Tags: plugins, theming
---


# Question
Title: Why is file_managed not updated correctly?
In a custom module (amap), I have a custom content entity (contract) created with Drupal Console.
There are standard CRUD functions on this entity.
One of the fields of the entity is a file field:

```
$fields['file1'] = BaseFieldDefinition::create('file')
  ->setLabel(t('Source file'))
  ->setDescription(t('Source file (may be modified)'))
  ->setSettings([
    'target_type' => 'file',
    'file_extensions' => 'doc docx odt pages',
    'uri_scheme' => 'private',
    'file_directory' => 'contracts',
  ])

```

When I create one contract adding a file (a.pages) to the entity, everything works as expected: a file with permanent status is added to file\_managed table and appears in Files tab of content page:

and the corresponding record is added to file\_usage table:  My first problem appears when I want to update the contract changing the file (to Contract.doc, for example):
file\_usage table is correctly updated:  but file\_managed table is not! The previous file (a.pages) is still there with permanent status.
The second problem is quite the same: when I delete the contract, file\_usage table is correctly updated: there is no more record related to these files.
But file\_managed table is not! The previous file (a.pages) is still there with permanent status (as in update mode).

My question is: is is normal?
Do I have to handle file\_managed table myself?
Why is file\_usage correctly updated and not file\_managed?
I naively thought it was the case...

# Answer
I changed `file.settings` config entry `make_unused_managed_files_temporary` to `true` and it seems to do the job.
Just hope there won't be any side effects...
> 3 votes

---
Tags: 8, entities
---


# Question
Title: View listing page/block relationship configuration
I have a Part-Time Course content type that holds information about whatever course that needs to be added to the site.

I then have a Part-Time Course Offerings content type that has two fields. Course Reference, which is an Entity Reference and links it to the Part-Time Course content type mentioned above and Course Offerings, which is an Entity Reference Revisions field type that gets fields from my Part-Time Offering paragraph type. That paragraph type holds various fields including Status and Season.

I have a block view that places the part-time course offerings on each part-time course content type page below the content based on contextual filters of Course Reference based on Content ID from URL.

What I'm now trying to do is create a Course Listing page that lists all the Part-Time Courses that I have but I want to filter it to only show courses that currently have Offerings available. So, if a course doesn't have an Offering available, I don't want it to show up on this listing page. I also want to be able to filter by status and season.

I have a feeling this has to do with Relationships but no matter what combination I've tried, I can't seem to get it to work.

Any suggestions?

The structure is basically like below:

```
Course - Part-Time (Content-Type)

    --> Course - Part-Time Offering (Content-Type)
        - field_course_reference
        - field_course_offerings

          --> Part-Time Offering (Paragraph)
              - various fields including Status & Season

```

**EDIT:** See below answer for an update.

# Answer
> 0 votes
Ok, so **Content using field\_course\_reference** *(Relate each Content with a field\_course\_reference set to the content.)* was used and required and then **Content using field\_course\_offerings** *(Relate each Content with a field\_course\_offerings set to the paragraph.)* was used and required using the first relationship.

This ended up allowing me to filter out and only display courses that had an available offering using Content: Course Reference (field\_course\_reference) with an operator set to **Is NOT empty**. I was also able to get the other two filters required to work.

However, I still have an issue where instead of just showing the course once, it displays it as many times as course offerings it has. So say that I have 5 different times the course is offered *(The Part-Time Offering \[Paragraph\] allows for unlimited offering choices)*, it ends up listing the same course 5 times on my page.

Is there any way for the view to only display each course once, disregarding how many offerings are available for each course?

**EDIT:** Found the answer to the above. Once I turned on aggregation in the advanced settings, it only displayed each Course once.

---
Tags: views, 8
---


# Question
Title: Where can we store 3rd party application passwords?
I've written a Drupal 8 custom module that communicates with 3rd party APIs which need authentication. I have an application username and password for those APIs which I need to store somewhere. I can think of the following two ways to achieve that.

1. I can store the credentials in the Drupal database as configuration. But the password then becomes visible in plain text to all the site admins, and we don't want all the site admins to see the password (I also am aware that we can set up roles and permissions, so we can disable access to a particular configuration for all the site admins, but still the password is saved in plain text in the database).
2. I can also store the credentials in the settings.php file.

Is there any other way we can store these credentials? What is the best, secure and preferred way to store 3rd party account credentials in Drupal 8?

# Answer
> 3 votes
Yes, if you're looking for a Drupal-centric solution, the Key module might provide what you're looking for. It supports pulling your stored secrets from a few different locations:

* Config
* File
* Environment Variable
* 3rd party services

As far a *best*, there's really no one-size-fits-all answer. It depends on your data storage requirements and what you're protecting (e.g. an API key for a medical records REST API should have heavy restrictions whereas a Slack webhook is pretty low risk).

If you're wanting a scalable solution, you might want to consider one of the many 3rd party services that provide secret management.

# Answer
> -2 votes
What about creating a specific permission *'view users password'* and give it only to specified user's role *'super admin'*? And disable this permission for basic *'administrator'* role?

Then your users may store 3rd party app passwords in specified fields and your admins won't see it.

---
Tags: 8, security
---


title: Adding product to blog sidebar

text:
# Question
Title: Adding product to blog sidebar
In Drupal 8 commerce 2, how would I embed a product with an add to cart button and select ID of my choosing into the sidebar of a blog post?

# Answer
This can be done please see this issue from drupal.org
https://www.drupal.org/project/commerce/issues/2935377
> 0 votes

---
Tags: commerce
---


# Question
Title: Add/List/Edit paragraphs while add/edit node
I have installed paragraph module.

I have paragraph called Address contains relevant info.

It is attached to node.

Per page/article I have more than 100 address. If I use default Paragraph Classic view mode then page is going to be too huge.

What will be alternate solution?

Should be there List and Add button. Add/Edit/List will open in Modal Widget?

Need to use Entity browser and Paragraph Views.

# Answer
I have been using the Paragraphs Collapsible module for a project with a big list of paragraphs to a node, and it works quite fine.

> Improves the Paragraphs widget by applying CSS tweaks and collapsible feature
> 1 votes

---
Tags: 8, paragraphs
---


# Question
Title: How to avoid "The form has become outdated" after login in separate tab
I've read this and this and I can't see how to apply that to my situation, so asking another question.

1. not-logged in user visits a page with a form on it.
2. User opens a new tab and logs in.
3. User switches back to their first tab and tries to submit the form.
4. Gets the outdated error.

How can I accept the anonymous form submissions once logged in?

In my application it's quite possible that the user has quite a few pages open in different tabs before they log in.

# Answer
The error is related to form CSRF protection, the error message comes from core form validation.

To avoid the error, it's possible to remove that CSRF token validation check in `hook_form_alter` e.g:

```
function my_module_form_alter(&$form, &$form_state, $id) {
  if (strpos($id, 'webform') === 0) {
    // Bypass per user CSRF token check and allow cache.
    unset($form['#token']);
  }
}

```

The caveat is, the form will no longer have default CSRF protection.

Alternatively, you might be able to detect the user has logged in (e.g custom local storage set event) and reload the original page to refresh it as is.
> 5 votes

# Answer
You're getting the error because the form is outdated - the form was created for a "different" user. Drupal's request-forgery protection is there for a reason.

Many sites have this "problem" and the best way IMO to deal with it is for the site to take the submitted form (during validate) and re-present it with existing user-visible values filled in (but obvs. new form tokens etc).

It is then clear to the user that the form has been refreshed and they get a chance to try to submit as themselves.

I expect, though haven't tried, that the refresh action can be achieved using a form validate hook that you ensure is run first, and if it detects the form token is not valid it creates a redirect back to the form URL on the spot.

Alternatively, educate your users that filling forms in anonymously is not wise!
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to fetch nearest node based on geofield?
How to fetch nearest node based on location geofield,i want to fetch nearest node based on longitude and latitude of my current location ,for this i have installed and configured geolocation field module also created view enabled all settings,but its not giving desired result.

I have followed this tutorial https://www.drupal.org/docs/8/modules/geolocation-field/how-to-create-a-nearest-node-view-sorting-by-proximity

Can we fetch the data directly from database by something like below example of php in drupal .

```
set @orig_lat=122.4058; set @orig_lon=37.7907;
set @dist=10;

SELECT *, 3956 * 2 * ASIN(SQRT(
POWER(SIN((@orig_lat - abs(dest.lat)) * pi()/180 / 2), 2) +  COS(@orig_lat * pi()/180 ) * COS(abs(dest.lat) * pi()/180) *  POWER(SIN((@orig_lon – dest.lon) * pi()/180 / 2), 2) )) as  distance
FROM hotels dest
having distance < @dist
ORDER BY distance limit 10

```

By using this query i will try to alter views query for getting desired result

# Answer
Something like this should do the trick to implement haversine :

```
/**
 * Implements hook_views_pre_execute().
 */
function YOURMODULE_views_pre_execute(\Drupal\views\ViewExecutable $view) {
//...
    $view->build_info['query']->join('YOUR_FIELD_LATLNG', '...', '...');
    $view->build_info['query']->addExpression(sprintf('3956 * 2 *
                                            ASIN(
                                                SQRT(
                                                    POWER(
                                                        SIN((%s - TABLE.YOUR_FIELD_LATLNG_LAT)*pi()/180/2)
                                                    ,2)
                                                    +COS(
                                                        %s*pi()/180
                                                    )
                                                    *COS(
                                                        TABLE.YOUR_FIELD_LATLNG_LAT*pi()/180
                                                    )
                                                    *POWER(
                                                        SIN((%s-TABLE.YOUR_FIELD_LATLNG_LNG)*pi()/180/2)
                                                    ,2)
                                                )
                                            ) * 1.60934', $lat, $lat, $lon), 'kilometers');
}

```

---

edit nearest :

```
$view->build_info['query']->orderBy('kilometers', 'ASC');
$view->build_info['query']->range(0, 1);

```

---

Note there is a contribution with views on geofield : https://www.drupal.org/project/geofield/issues/3012750
> 0 votes

---
Tags: 8
---


# Question
Title: module_invoke_all() pass arguments by reference?
when I implement the HOOK\_node\_presave , I can access to the $node and alter it ex:

```
function drupal7_test_node_presave($node){
    $node->title = 'Abricoooooooooooooooooo';
}

```

the strange thing is that this hook is invoked with module\_invoke\_all which should pass argument by value (and not by reference like drupal\_alter() )

```
module_invoke_all('node_presave', $node);
var_dump($node->title); die();

```

this output : Abricoooooooooooooooooo , when the $node property has been changed ? it should not !!!!

# Answer
> this hook is invoked with module\_invoke\_all which should pass argument by value (and not by reference like drupal\_alter() )

That's not how PHP works - `$node` is an object; objects are (ostensibly) passed by reference. Or, more accurately, from the docs

> One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true.
>
> A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, **which points to the same object**.

Emphasis mine.
> 1 votes

---
Tags: nodes, hooks
---


# Question
Title: How to reuse the same custom template in Ajax callback
I am currently trying to display a list of nodes with a custom form containing taxonomy dropdowns (placed above node list) to filter out the contents. Now, on page load all content is displaying well by theming with custom template. Now my form is an Ajax form. After filtering I want to display the result with by using same template just passing the filter array of the node(s). Please find my ajax submit callback code.

Not working. `render()` works only if I pass nodes by loading node by viewMultiples. is there any way I can use similiar to `theme()` of drupal 7 like `theme('my_content_build_page', $nodes)`?

```
$nodes= Myclass::getNodesByEntityQuery($params);
$build = \Drupal::entityTypeManager()->getViewBuilder('node')->viewMultiple($nodes, 'full');
$response = new AjaxResponse();
$response->addCommand(
  new HtmlCommand(
    '.result_message', '<div class="my_top_message">'.render($build).'</div>'
  )
);
return $response;

```

On page load I am theming

```
$page_params['content'] = MyClass::getNodesByEntityQuery($params);

$build = [
  '#theme' => 'my_content_build_page',
  '#page_params' => $page_params,
];

```

Can I reuse the same template in Ajax Callback?

# Answer
The replacement for `theme()` is a build array with a `'#theme'` key, as you already have for the page.

In Drupal 8 pass this or the other build array from your question unrendered to an ajax html command, because `render()` in custom code should be avoided if possible:

```
$build = [
  '#type' => 'container',
  '#attributes' => [
    'class' => ['my_top_message'],
  ],
];

$build['content'] = \Drupal::entityTypeManager()
  ->getViewBuilder('node')
  ->viewMultiple($nodes, 'full');

$response = new AjaxResponse();
$response->addCommand(
  new HtmlCommand('.result_message', $build)
);
return $response;

```
> 1 votes

# Answer
```
$build = [
  '#theme' => 'my_theme_key',
  '#page_params'=> $nodes,
  '#attributes' => [
    'class' => ['my_top_message'],
  ],
];

$response = new AjaxResponse();
$response->addCommand(
  new HtmlCommand('.result_message', $build)
);
return $response;

```

Theme hook

```
function mymodule_theme() {
  return [
  'my_theme_key' => [
     'theme' => 'my_template_file',
     'variables' => ['page_params' => NULL],
    ],
 ];
}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How to sort view by content type, using literal ordering, as second order-by clause
In a view, I want to sort content by:

1. Collection (a taxonomy term)
2. Content type
3. Something else
4. Something else ...

I have this configured in the View UI and I want to leave most of it as it is but for the content type ordering, I want to make this literal - I want to state the order exactly ("article", "page", "thingy", "other one").

For this in MySQL you would use `FIELD()`

I have tried using `hook_views_query_alter` and setting `$query->orderby[1][field]` to `FIELD(node_field_data_type, "article", "page", "thingy", "other one")` but I am running into exactly this problem: https://www.drupal.org/node/1382016#comment-12058755 In other words, the brackets and quotes are being removed so that it thinks it's one long field name (which of course does not exist) rather than treating it as a function call. It seems this did not happen in Drupal 7.

Is there a known way to get around this in Drupal 8?

# Answer
> 1 votes
Although there may be a method to do this via a query alter I was unable to find the correct solution. I was however able to find a solution.

Although we utilise search API heavily and we can use the content type relevance weighting we had a requirement to sort by a custom content type order and then by date, in addition some content types needed the same weight.

**Our solution: Add a search weighting field to the required content types (e.g. integer 1-5) and include it in the index. In the view add a sort filter for your search filter field.**

You'll need to batch process or use views bulk operations to fill in existing node data and hide the field from content add / edit screens if required.

One added benefit of this method is, if the client wants to have a piece of content show at the top when it's in the result set they can manually amend the new field for it.

---
Tags: views, 8, hooks
---


title: Wysiwyg editor for webform 5

text:
# Question
Title: Wysiwyg editor for webform 5
Is there a way to configure textarea fields in Webform 5 to use Wysiwyg editor ? preferably without coding and overlay capability (I mean something like https://www.jqueryscript.net/form/jQuery-Plugin-For-Textarea-Fullscreen-Mode.html) ? Thanks

# Answer
You can switch the Webform's HTML Editor to any 'Text format' which are fully customizable.

@see /admin/structure/webform/config/elements
> 0 votes

---
Tags: webforms, wysiwyg
---


# Question
Title: How to download from private// following a link?
I have a custom entity (contract) created in a custom module (amap) by a bunch of BaseFieldDefinition, one of which being

```
$fields['file1'] = BaseFieldDefinition::create('file')
  ->setLabel(t('Source file'))
  ->setDescription(t('Source file (may be modified)'))
  ->setSettings([
    'target_type' => 'file',
    'file_extensions' => 'doc docx odt pages',
    'uri_scheme' => 'private',
    'file_directory' => 'contracts',
  ])

```

I have a View about the custom entity that displays some fields in table mode:
The download action (the yellow arrow) is defined using Custom text with `rewrite results`, `link path` being `{{ file1__target_id }}`:
The link is something like `mysite/system/files?file=contracts/Contract-4-20200408.doc` (for example).
And following the link gives different results depending on the browser. None of them being what I want: the default filename proposed is not correct 'files' or 'file.dot' instead of 'Contract-4-20200408.doc' (in my example).

So I tried to implement hook\_file\_download. My code is

```
function amap_file_download($uri) {
  $sFileName =  \Drupal::service('file_system')->basename($uri);
  $sFileNameWithPath = 'sites/default/files/_private/contracts/' . $sFileName;
  $response = new BinaryFileResponse($sFileNameWithPath);
  $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $sFileName);
  return $response;
}

```

and there I get this error!

```
Notice: Object of class Symfony\Component\HttpFoundation\BinaryFileResponse could not be converted to int in Drupal\system\FileDownloadController->download() (line 51 of core/modules/system/src/FileDownloadController.php).
Drupal\system\FileDownloadController->download(Object, 'private')
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)

```

What am I doing wrong?

# Answer
> 0 votes
Thanks to @Kevin, I updated my code to

```
function amap_file_download($uri) {

  $sFileName =  \Drupal::service('file_system')->basename($uri);
  return array(
      'Content-disposition' => 'attachment; filename="' . $sFileName . '"',
  );

}

```

And it works!

---
Tags: 8, files
---


# Question
Title: Configuration settings of Authcache for roles
I'm not sure about configuration of roles in Autchcache module, specifically with authenticated user role. I want to enable caching for both anonymous and authenticated users, but I want to exclude from caching some roles (administrator and webmanager). My web has a lot of roles but an authenticated user may has one, two or more of them.
For example, my web has the next roles: anonymous, authenticated, administrator, webmanager, rol1, rol2, rol3, etc. Some users may have some roles: rol3 and rol4, but other users may have only rol1 and rol2, etc. I want cahing for all of them except the ones who has webmanager or administrator.
How should I config this behavior in Authcache module?

# Answer
Authcache will only attempt to cache a page and deliver a cached page respectively if every single role of the logged in user is authcache enabled.

Consider the following example:

* Five roles are defined on the website (including the built-in ones): anonymous, authenticated, customer role 1, customer role 2, administrator.
* Three roles are enabled for authcache: anonymous, authenticated, customer role 1
* User Customer A has the following role: customer role 1
* User Customer B has the following role: customer role 2
* User Customer C has the following roles: customer role 1 and customer role 2
* User Customer D has no additional roles
* User Administrator has the following role: administrator

This will lead to the following behavior:

* Authcache will kick in for every anonymous user (anonymous role is authcache enabled).
* Authcache will kick in for Customer A (customer role 1 is authcache enabled).
* Authcache will not kick in for Customer B (customer role 2 is not authcache enabled).
* Authcache will not kick in for Customer C (customer role 2 is not authcache enabled).
* Authcache will kick in for Customer D (authenticated is enabled)
* Authcache will not kick in for Administrator (administrator role is not authcache enabled).
> 1 votes

---
Tags: 7, caching
---


# Question
Title: Should Text Format: "Full HTML" create a safe value?
When I am rendering fields I noticed that if the user selects "full html" as the WSYWIG text format on a "long text" field, a safe value is not created. For example the array would be:

```
value (String, 14 characters ) <div>test</div>
format (String, 9 characters ) full_html

```

But if "Filtered HTML" input selected it would be:

```
value (String, 14 characters ) <div>test</div>
format (String, 9 characters ) full_html
safe_value (String, 4 characters ) test

```

Settings to Full HTML seem to have no effect.

What controls whether a safe value is created?

# Answer
> 0 votes
The core text module does. This logic is driven by the text module's `text_field_load()`, an invocation of `hook_field_load()`. When the module loads text fields it looks up the filters used for the text format and sees if it's cacheable (i.e. if it saves to `safe_value`).

In your case, the logic is being triggered by toggling the `filtered_html` / `full_html` formats. Because raw HTML is potentially unsafe, it's not stored in the `save_value` cache. \`

---
Tags: 7
---


# Question
Title: PaymentMethodManager() get plugin on NULL ubercart error
Hi when trying to create an order in checkout state, the order gets created however when trying to view the order it errors out with the error below:

> Error: Call to a member function getPlugin() on null in Drupal\uc\_payment\Plugin\PaymentMethodManager-\>createFromOrder() (line 45 of /srv/bindings/6204a08fb5564631b33e310ef75fe465/code/modules/contrib/ubercart/payment/uc\_payment/src/Plugin/PaymentMethodManager.php) #0 /srv/bindings/6204a08fb5564631b33e310ef75fe465/code/modules/contrib/ubercart/payment/uc\_payment/src/Plugin/Ubercart/OrderPane/Payment.php(50):

Ubercart version: Version: 8.x-4.0-alpha5+227-dev

My payment methods are all setup however in order creation code we don't need payment method. Anyone facing the same issue?

# Answer
You can fix this error by applying the patch here: https://www.drupal.org/project/ubercart/issues/2826324
> -1 votes

---
Tags: 8, ubercart, payment-gateways
---


title: Pass selected values to node add form

text:
# Question
Title: Pass selected values to node add form
I have a view of nodes. I'd like to be able to select rows (thinking VBO is the best) and pass those selected nodes to a form (specifically /node/add/payments) to pre-populate entity references.

Any thoughts on how to do this? I've been playing around with several options and can't figure it out.

# Answer
At a high level, you could do something like this with a custom module:

* Create a custom VBO action (see docs) to take action on your selected nodes.
* Have your custom VBO action redirect to `/node/add/payments` with some query parameter that encodes your selected nodes (e.g. `/node/add/payments?my_nids=1,2,3`).
* Add `hook_form_alter()` invocation in your module to read this query parameter (e.g. `$nids = explode(',', \Drupal::request()->request->get('my_nids')`) and pre-populate the entity ref field with your values.
> 0 votes

---
Tags: 8, nodes, views
---


# Question
Title: How to access raw data in twig template using views table format
I use a table format view to display a list of articles `article-list` using draggable views to allow editors to order the list. I customize the content of rows depending on a boolean field `is_header` and a formatted text field `title_override`. I have sub-themed `views-view-table--article-list.html.twig` to accomplish this. It works well enough.

In the template, I test the truth of `is_header` and the non-emptiness of `title_override` as follows:

```
    {% if row.columns.field_is_header|render|striptags|trim %}

```

and

```
    {% if row.columns.field_title_override|render|striptags|trim %}

```

These tests yield the proper results, but they make the template very slow! Anything less than `render|striptags|trim` doesn't work.

QUESTION:

Is there a way to directly access the raw data values of these variables to avoid the `render|striptags|trim` overhead?

I've seen suggestions to use something like `row._entity.field_is_header`, but this way of using `_entity` seems to work only in templates for the HTML or Unformatted view styles. Seems like there should be an easy way to do this.

As a note, switching to using an HTML or Unformatted style doesn't seem possible because AFAIK draggable views can be set up only with the table format.

ANSWER:

Thanks to 4k4 for the answer to this question (see below). To apply his/her general answer to my specific question, here is a snippet of the twig script I ended up with:

```
{% for key, row in rows %}
  {% if view.field.field_is_header.value(view.result[key]) %}
    <conditional stuff>
  {% endif %}
  {% if view.field.field_title_override.value(view.result[key]) %}
    <stuff when the override is non-empty>
  {% else %}
    <stuff when the override is empty>
  {% endif %}
{% endfor %}

```

Note that `rows` is an array normally passed to the views-view-table.html.twig template, as documented in the original template's header comments. Note also that the availability of the `view` array is NOT documented in the original template's header comments (not that it would have saved me without 4k4's help).

# Answer
You can try to apply getValue() of the field handler on the result row, for example:

```
{% if view.field.field_name.value(view.result[key]) %}

```

Edit:

In a views table template `row` is not of the type `ResultRow`, so you need to get it directly from the `view` object using `key` of the loop `{% for key, row in rows %}`.

See these questions for different views templates: How can I get data from ResultRow object in views template and How to preprocess view field?
> 2 votes

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


# Question
Title: How Can I do a content type with a 1:n field inside?
I'm a bit lost about how Drupal manage content.

For example, I want to create a new content type called Game. When I create a "Game" I want to introduce "Platform" and "Release date".

For example:

Title: Sonic the Hedgehog.
Description: Whatever.
Released on:
Platform: Mega Drive Date: 23 june 1991
Platform: Arcade Date: 1991
Platform: Nintendo Switch Date: 2018

I want both platform and date to be keys for sorting games, so clearly platform might be a "vocabulary" in taxonomy?...I'n not really sure. How would be your take on this?

# Answer
> 0 votes
It seems Field collection/tabular data solution is what you're after.

In Drupal 7 the popular module for that was Field collection.

In Drupal 8 Paragraphs seems to be popular, although its description is pointing heavily to the current fad of designing content pages with separate sections, it is still a solution that allows for a more structured group of references. Then you reference the Paragraph you constructed for this particular purpose from within your nodes.

A more abstract solution similar to Paragraphs but more flexible is Bricks. Although its description is pointing to Layout integration you don't have to be distracted by that, it's still a great entity reference grouping mechanism you can use to construct your node structure.

I think Bricks might be better suited for your particular case since you'll always be using the same platform/date structure, but investigate both and see which fits you best.

In short, you need references from your nodes to the platform, and date, and they need to be grouped in pairs. You can do that by creating the abstract reference (brick) from your node, that in itself holds two other references (to platform and date). Platform items (entity reference) can be Taxonomy terms, Date can also be Taxonomy or Date fields, it all depends on your details, what type of data it is, how you're expected to manipulate it, etc.

---
Tags: views, entities, nodes, taxonomy-terms
---


# Question
Title: Get URLs of taxonomies terms in Link field
I am having a link field in drupal 8. It can accept both internal and external links with autocomplete feature. But it works only with nodes means with content but i want to use it with taxonomy terms as well.

How can i achieve this ? Any Help

# Answer
> 0 votes
Nodes and taxonomies both use fields but they're stored slightly differently. You will need to recreate your field for the taxonomy you wish to apply it to, it won't show up in `Use existing field`.

# Answer
> 0 votes
Taxonomy terms can be inserted into "entity reference" fields which accepts both content/nodes as well as taxonomy term but not both at same time. You might get help with that one as it is an autocomplete field too.

> Go to "Add Field" tab in manage fields.
>
> Select under Reference -\> Taxonomy Term.

# Answer
> 0 votes
It is not (yet) possible. See issue on drupal.org for *link fields* for example in *menu link* or *redirect to*: Allow multiple target entity types in the entity reference field.

---
Tags: 8, taxonomy-terms, navigation
---


title: Add site branding to external site

text:
# Question
Title: Add site branding to external site
Maybe I'm asking the wrong questions on google, but I can't seem to find a solution to what I'm trying to accomplish.

We've created a Drupal 8 site and we need to add the existing header and footer to an external site so that it includes our site branding.

What is the best solution to accomplish this?

I have some initial thoughts, but feel like I'm way off base:

1. Pull the `<header>` and `<footer>` out of the `page.html.twig` template and put them into a separate `header.html.twig` and `footer.html.twig` template. (My base theme is bootstrap barrio)
2. Create a custom API that exposes the html from the header and footer twig templates. (I'm not sure if this even possible)
3. Using the custom API, expose any paths to custom CSS/JS required for theming.

Then the external website would just call the API, grab the html/css/js and put all the gathered resources on their pages.

Is the above on the right track or am I completely wrong? If I am on the right track, how would I accomplish #2?

# Answer
I think creating a service REST API to be consumed by the client sites is the cleanest solution.

This has been implemented in Drupal 7 with sharedblocks but there no Drupal 8 port at this time.

Studying this module would give you a solid foundation on how to accomplish your task in Drupal 8.

Based on the same concept there is also distributed\_blocks module but again does not seem to have a Drupal 8 port.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: logging into development instance of Drupal
Ive rsynced the directory structure from mywebsite.com to mywebsite.local ( on my LAN) and copied the DB . the website mywebsite.local displays the website, but i cant log with the admin user/pw from the production site . The DB tables look the same to me. Its a single site and in sites/default/settings.php it points to DB host is 'localhost' Tailing apache access.log and I can see the .local site is served from localhost

Do I need to change anything else ?

# Answer
You can try login with https://drushcommands.com/drush-8x/user/user-login/

```
drush uli admin

```

Which will give you a login link for user `admin`

If you invoke it without a username it gives you a login link for user 1

```
drush uli

```
> -1 votes

---
Tags: database
---