# Question
Title: How to print the relative url or node id for each referenced node in twig?
I am using paragraphs to render a number of nodes on a page. The nodes are obtained through an entity reference field called 'field\_nodeslist' in my cards paragraph type. The cards are then rendered using a custom view layout.

Here is a snippet of my view layout:

```
<a href="????">
   <h3>{{ content.top_region|striptags}}</h3>
   <p>{{ content.middle_region }}</p>
</a>

```

The problem I am having is printing the relative path for each referenced node. I have tried the following twig commands but have not had any success so far:

```
<a href="{{ url }}">
<a href="{{ uri }}">
<a href="{{ node.id }}">
<a href="{{ link }}">
<a href"{{ content.field.0['#url'] }}">

```

The following allows me to manually specify the node id in twig however that's not what I am looking for:

```
<a href="{{ path('entity.node.canonical', {'node': 6 }) }}">

```

Any ideas?

**Notes/Thoughts:** In my first code snippet, the fields in 'top\_region' just contains the nodes title. There was an option to link the field to content however I had to add the '*|striptag*' filter in twig due to additional markup messing up the style. Is it possible to grab the url path from the node title?

# Answer
You probably need to work more in UI to configure what is in `{{ content }}` and then render the fields as they are.

If still necessary you can use `{{ node }}` respectively `{{ paragraph }}` to access all field values, see How to retrieve value of hidden field in twig?, but you can't access the url directly. You have to build this with the help of the raw database value `target id`, see How to print the URL path of a referenced node using paragraphs?.

BTW the result is the same as the entity method toUrl() would provide, only that this method is blocked by the twig sandbox policies. As a third (least favourable) option you can change this, too, see https://stackoverflow.com/questions/40091324/allow-new-methods-in-sandbox-policy-in-twig-drupal-8
> 1 votes

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


# Question
Title: Show Description Field on Individual Webform Submission Result
I would like to include the description field when viewing individual webform submissions for each component. The standard webform individual submission display shows the label and the answer, but the description field for the component is not shown.

I had a look at webform-submission.tpl.php but wasn't sure how I could modify this to include the description being displayed.

Can anyone tell me how I can get the description to display?

I'm using Drupal 7 with Webform 7.x-4.19

# Answer
> 1 votes
After looking through the webform module I found out how to achieve this.

I used hook\_webform\_component\_display\_alter() which is there to enable customising the display of components in display only contexts. This function is in webform.api.php. I created my own function using this hook in a custom module to add the description to all textfield components as follows:

```
<?php
function my_mod_webform_component_display_alter(array &$element, array &$component) {
  if ($component['type'] == 'textfield') {
    $element['#description'] = $component['extra']['description'];
  }
}

```

For reference, the notes and example given from the webform module for `hook_webform_component_display_alter()` are:

```
/**
 * Allow modules to modify a "display only" webform component.
 *
 * @param array $element
 *   The display element as returned by _webform_display_component().
 * @param array $component
 *   A Webform component array.
 *
 * @see _webform_display_component()
 */
function hook_webform_component_display_alter(array &$element, array &$component) {
  if ($component['cid'] == 10) {
    $element['#title'] = 'My custom title';
    $element['#default_value'] = 42;
  }
}

```

---
Tags: 7, theming, webforms
---


# Question
Title: Unset widget tab from media browser programmatically
Need to unset a widget tab from media browser based on the condition of media type supported by the field.

**Media types:** Image and Video.

For example, There is a field which references **image** media type only. When the media browser appears on the form, it displays **create embed** tab as well to embed the videos.

As the field doesn’t reference the **video** media type, need to unset the tab programmatically to help the content author.

I have tried the form alter, but I don't get any information about the media type referenced by the field in the hook.

# Answer
It should be possible with some code like this:

```
function MY_MODULE_form_entity_browser_MY_FORM_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#pre_render'][] = 'MY_MODULE_pre_render';
}

function MY_MODULE_pre_render($element) {
  kint($element); //Find the tab you want to remove.
  if (...) {
    unset($element['...']);
  }
  return $element;
}

```

Another commonly used solution is to create 2 or 3 media browsers depending on your needs. So you will have an `image media browser`, a `video media browser` and an `image + video media browser`.

Then you just select which one to use in the field settings.
> 2 votes

---
Tags: 8, forms, media
---


# Question
Title: How do I turn off mobile menu collapse for bootstrap 3 theme in drupal 8?
I am looking to use a different mobile menu solution and replace the default bootstrap 3 mobile menu.

How can I turn off the bootstrap collapsed mobile menu function?

# Answer
> 1 votes
Just override the `menu--main.html.twig` template that comes along with the bootstrap theme, and replace the HTML classes with your own classes, then the bootstrap mobile styling won't affect your menu.

---
Tags: 8, navigation, bootstrap-theme
---


# Question
Title: url alias not working when logged in as admin
When I'm logged in as admin, the urls are un-aliased ("node/24"). When logged out they appear aliased ("about/us"). It might have something to do with the module admin\_menu as suggested in a post over at drupal.org – but applying the recommended patch didn't work for me.

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

Hope somebody knows a way out? Thank you! t

update: thank you for suggesting to investigate first, if it REALLY is the admin menu – and of course it's not. I switched it off, but same situation. So I guess I'll better do some further 'research' by switching off and on various recently installed modules first…

-closing-

# Answer
After dealing with this exact issue for a while in drupal 8, this thread made it click as to what the solution was.

For me, it was my choice of detection for the language that was causing the issue.

Go to /admin/config/regional/language/detection

And make sure that the only checked is the "selected language"

I had the User method checked "Follow the user's language preference." and that was what was causing the issue.

Now this might not work for a multi language site, but my site was originally in danish and I only wanted to have an english version.
> 1 votes

# Answer
found the solution – or actually the problem:
it was my language prefs! A couple days ago I switched the admin accounts' language pref from german back to english and that made the 'german' url aliases disappear. Hope this helps somebody else someday at some point.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: Pagination in external api consume custom module
I created a custom module in order to consume an external api call in my drupal project following this question. The module is working fine, but I need to have a pagination in the received results which will pass as a variable in the api call:

```
http:/example.com/api.ashx?q=documents&page=1

```

How is possible to achieve that? In case I receive all the data from the api is it possible to "separate" them somehow with pagination operation?

Thanks in advance

# Answer
Is responsability of the external API paginate the results with the page parameter. If it was designed for such thing.

Then you only need to request the appropiate page.

If in another hand if you receive all the data, then, you only need to divide it.

Assuming in the referenced question that $data contains all rows, you need to divide the array (array\_chunk() maybe).
> 0 votes

---
Tags: paging, 8
---


# Question
Title: How do I pass variables into Twig template?
In my preprocess function I have variables with the route name and route parameters:

```
function my_theme_preprocess_node(&$variables){
  $variables['route_name'] = $route_name;
  $variables['route_parameters'] = $route_parameters;
}

```

How do I pass them to the following link function in my page.html.twig file:

```
{ <a href="{{ path('$route_name', {'node': $route_parameters}) }}">Link to the object with $route_name and $route_parameters</a> }

```

Is it at all possible?

# Answer
> 3 votes
The '$' isn't used in twig to designate a variable. This code should work:

```
<a href="{{ path(route_name, {'node': route_parameters}) }}">
   Link to the object with {{ route_name }} and {{ route_parameters }}
</a>

```

---
Tags: 8, theming
---


# Question
Title: Can I combine multiple "no results behavior" to avoid repetition?
I have a Search API view that has 3 attachments. This is so I can display different content type results with unique layouts.

If the user searches something too specific, they'll see the No Results Behavior up to 4 times in a row. This looks bad.

How can I only display the No Results Behavior (custom textarea) when there are no results in the view AND its 3 attachments?

# Answer
I solved it myself (that's a first and probably a last)!

I'm sure this isn't the best code but it works and I don't know enough PHP to clean it up.

I disabled all "No Results Behaviors" in the view settings. I'm using the hook\_preprocess\_views\_view hook to count the number of results for each of my attachments. Only if all 4 === 0 will it print the correct empty message.

```
function MYTHEMENAME_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'search_results') {
    $view1 = $view2 = $view3 = $view4 = $view;

    if (is_object($view1) && is_object($view2) && is_object($view3) && is_object($view4)) {
      $view1->setDisplay('page_1');
      $view2->setDisplay('attachment_1');
      $view3->setDisplay('attachment_2');
      $view4->setDisplay('attachment_3');

      $view1->execute();
      $view2->execute();
      $view3->execute();
      $view4->execute();

      if (count($view1->result) === 0 && count($view2->result) === 0 && count($view3->result === 0 && count($view4->result) === 0)) {
        $variables['empty'] = "Sorry, but we couldn't find any results for your query. Try broadening your search terms.";
      }
    }
  }
}

```
> 1 votes

---
Tags: views, search
---


# Question
Title: Building views relationship with location
I have an article and food content types. I use location module fields in both content types. So for example, when I write an article about restaurants in New York, I choose article's location as country: US, state: NY and city:New York. Now, I want to be able to show related food items in view with same country, state and city. Now, how do I display food items matching with article's location.

# Answer
Sibling items are usually displayed with the help of two Relationships and one Contextual filter.

Create Food item Views.

You first add the Relationship for your Location field, it introduces info about the Location.

Then you add the **reverse** Relationship to the first one, it will use the first Relationship. The second one points back to the content that is using that Location field.

Add the Contextual filter for Node ID and make it use the second Relationship. Set it the usual way, default value and ID from URL, validate against Article Content type.

I haven't tried this with the Location field but the logic should be the same.
> 0 votes

---
Tags: 7, views, location
---


# Question
Title: Managing custom aliases on translated content
We have a Drupal 8 site with translated content, and using the Pathauto module. The issue we are running into is that when we un-check the "Generate automatic URL alias" on, say, the Chinese node, because the content editors want to customize that URL, that applies to all the other languages of that node, and path aliases are no longer automatically generated.

Ideally, we would like to separately control how to generate path aliases for each language a node is using, whether automatic or custom. The Pathauto\_i18n module looks like it might be helpful, but it's woefully unfinished for Drupal 8 and I don't think we have the resources to finish it on our own right now.

Is there something else I am missing?

# Answer
> 0 votes
I had to create a custom path based on a field. I was able to use hook\_pathauto\_pattern\_alter(). If you need custom path per node then this should work. You will need to add a field. It can be a plain text field. Pathauto conditions. Here is an example of the hook. code review for hook\_pathauto\_pattern\_alter

# Answer
> 0 votes
In addition to the post of paulcap1 you can look into pathauto.api.php located inside the pathauto module to see which hook suits you best for setting the path programmatically (if this is an option for you).

The path can be set or modified per language (which is german and english in this case) like this:

```
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), '/some_alias/' . $node->id(), "en");
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), '/some_alias/' . $node->id(), "de");

```

I hope I did get you right and this is useful to you.

---
Tags: 8, i18n-l10n, path-aliases
---


# Question
Title: Multiple url aliasses per node in multi language website
Hope this is the right place for this question. I'm turning to you guys because I just cannot decide on the best way to go for this issue.

I'm currently developing a multi-language site which is split up in 2 main sections. Section A will be the main section and is available in 2 languages; Dutch and English. Section B will only be available in English.

Section B will have a different Menu, a slightly modified layout and some other blocks will be shown on different pages within the section.

I'd like to achieve the following url structure:

Section A:

`/nl/title-of-a-node-in-dutch`

`/en/title-of-a-node-in-english`

Section B:

`/en/section-b/title-of-a-node-in-english` *(If possible, I'd like to drop the language prefix `/en/` here)*

I've configured Drupal with Entity Translation (+ Title module), so each node has translations on field-level and is not entirely duplicated like it would be the case with Content Translation (i18n).

The problem is that I'm going to have a lot of content (tens of thousands of nodes) for this site and some items should be shown in both Section A and B. Content that will be shared with both sections should only exist in one node. I definitely do not want to create an extra node with the same content just to make it available for Section B, this would be bad for content management and have a huge impact on the database.

Some of the solutions I've thought of:

* Create 2 checkbox fields in the content type to indicate in which section the node should be made available. Create a hook on node insert/update and check which section was selected. If Section B was chosen, create an extra url alias which starts with `/section-b/{node-title}`. This would make the node content available via this extra alias, but I'm not sure what the implications this method will have, like how to handle breadcrumbs or (multilingual) Menu Structures for Section B
* Configure Drupal to use a language fallback with Language Neutral and somehow add Section B as a custom language with the prefix `'section-b'`. (is this even possible?)
* Use url rewrites `/section-b/my-title` -\> `/en/my-title` and programatically load the node and show the content via theming/templates
* Maybe I can do something with Rules?

Relevant modules I'm using: `pathauto`, `entity_translation`, `path_translation`, `i18n_translation`, `title`

Do you guys have any other suggestions in how to set this up? I hope I'm clear on this issue. Content management is very important in this matter :)

Thnx!

# Answer
> 0 votes
I'm not sure if this article helps, but here it is: https://www.drupal.org/node/1516444

For something more complex, I've actually implemented a hook\_url\_inbound\_alter() to control the redirection of pages and it's worked pretty well for me, but it involves creating the logic yourself. On the other hand, the benefit is that you can completely control when and where you redirect page visits.

# Answer
> 0 votes
You can look into pathauto.api.php located inside the pathauto module to see which hook suits you best for setting the path programmatically (if this is an option for you).

The path can be set or modified per language (which is german and english in this case) like this:

```
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), '/some_alias/' . $node->id(), "en");
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), '/some_alias/' . $node->id(), "de");

```

I hope I did get you right and this is useful to you.

---
Tags: hooks, i18n-l10n
---


# Question
Title: How to create a custom Webform handler to submit to a SOAP API
I have a Webform that when submitted needs to be posted to a SOAP web service. I have search for a bit of direction but I can't seem to find anything about SOAP and Drupal 8/Webform. Can anyone point me in the right direction to create a custom handler to submit to SOAP.

I'm using Drupal 8.6.16 and Webform 8.x-5.2

# Answer
In your custom module add a folder `src/Plugin/WebformHandler` and create a file `Subscription.php`. Add the following code:

```
<?php
namespace Drupal\<mycustommodule>\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "subscription",
 *   label = @Translation("Subscription"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers subscriptions via SOAP"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class Subscription extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  const SOAP_URL = 'x'; // url of soap call here

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // The data to send to the API
    $values = $webform_submission->getData();
    $email = strtolower($values['e_mail']);
    $first_name = $values['first_name'];
    $last_name = $values['last_name'];

    // Add your SOAP Call here
    $client = new SoapClient(self::SOAP_URL);
    // .. Go on here
  }
}

```

Enable the module and clear cache. Now, in your webform backend, go to settings and then emails / handlers (/admin/structure/webform/manage//handlers). Add your handler here. For a little more detail and instructions, see: https://stefvanlooveren.me/blog/how-create-mailchimp-subscription-drupal-8-webform-module
> 6 votes

---
Tags: 8, webforms
---


title: hook to alter custom blocks?

text:
# Question
Title: hook to alter custom blocks?
I am having a problem with my custom blocks rendering, and I want to programmatically manipulate the blocks to troubleshoot the issue.

I used this question to add this hook to my module:

```
function mymodule_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message($block->getBaseId());
}

```

However, when I navigate to my site, I see only the base ids of system blocks:

```
- page_title_block
- system_main_block
- help_block
- local_tasks_block

```

My site's header and footer are made of custom blocks, so I should be seeing their ids.

How can I programmatically access my custom blocks?

**Edit** this is my actual code:

```
$ cat my_block_hooks.module
<?php

function my_block_hooks_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $block->getBaseId() );
}

```

And here's a screenshot:

You can see that all the system blocks show up, but my custom block does not.

This is the custom block as I have it set up:

And here I have it placed in the layout:

And of course, I've cleared the cache many times to get to this point.

What am I doing wrong?

# Answer
> 13 votes
The type of entity you are dealing with defines the hook you need to implement; in this case it is NOT `block` but rather `block_content`, as provided by the "Custom Block" core module.

**N.B.**: It is generally good practice to use more specific hooks when possible, as it will have a general effect on your code's performance, i.e. your hook implementation will be called less times if it is more specific. In your case, instead of going through all blocks available on any page during page loading, you are going through only custom blocks (`block_content` entities).

In order to get your `hook_ENTITY_TYPE_view()`/`hook_ENTITY_TYPE_view_alter()` implementation to work, you need to replace `ENTITY_TYPE` with `block_content`. That should give you the following code (which I tested and works):

```
use Drupal\block_content\Entity\BlockContent;
...
function my_block_hooks_block_content_view_alter(array &$build, BlockContent $custom_block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $custom_block->id() );
}

```

And the visual result:

Good luck!

# Answer
> 3 votes
You're using the built-in custom block which ships with Drupal. In your code your getting the baseId which is in your case `block_content` and it is shown in your screenshot actually.
I think you need to use `$block->id()` instead.

# Answer
> 3 votes
You can use getPluginId to get the id of the block:

```
function my_block_hooks_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $block->getPluginId());
}

```

here is the result:

# Answer
> 1 votes
Yes, you should be seeing the IDs of your custom blocks. Here are some things you can try:

* Make sure you actually have the custom block nicely defined and placed on your *Manage blocks* page.
* Make sure your custom block is actually visible on the page? Return some temporary output like "foo" from your custom block plugin and make sure that the "foo" is visible on the page.
* Try removing cache for your block temporarily by adding `$build['#cache']['max-age'] = 0;` to your block's output.
* Drush `drush cr` or clear cache and see if your custom block is visible.
* Check the visibility rules for your custom block in block configuration. Try removing all visibility rules temporarily and see if the block shows up.
* If you've implemented any block access rules, try disabling them to see if your block becomes visible.
* Multiple blocks can have the same `Base ID`. Try doing `$block->getPluginId()` or `$block->id()`. In your case, it should give you an item like `block_content:UUID` where `UUID` is the unique ID of the custom block you created in your custom block library.

The ID of your block not showing up is basically sounds like your block is not being displayed on the page.

# Answer
> 0 votes
```
use Drupal\block_content\Entity\BlockContent;

//...

function my_block_hooks_block_content_view_alter(array &$build, BlockContent $custom_block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $custom_block->id() );
}

```

You will get your block id here, based on that set condition and override that specific block output.

```
use Drupal\block_content\Entity\BlockContent;

// ...

function my_block_hooks_block_content_view_alter(array &$build, BlockContent $custom_block) {
    if($custom_block->id() == 5){
       $build['content']['#markup'] = Markup::create('Your text');
    }
}

```

# Answer
> -2 votes
I am going to take a wild guess, but have you tried clearing the cache? Custom blocks normally do not contain dynamic data and as such can be heavily cached. This causes the block output to be rendered without your hook getting called.

In the configuration menu go to development \> performance and hit the 'Clear all caches' button. Then go back to the page with your blocks and see if it made a change. Alternatively you can install the devel module to clear the cache from each page directly.

---
Tags: 8, blocks
---


# Question
Title: Detect when 'Remove' is clicked on a file widget form element?
I have a handful of file fields that have the following default Drupal behavior:

* User can upload a file
* User can upload another file in place
* User can remove file

Standard config. Whats happening is the user wants the file being replaced to be *deleted* before the new one is uploaded, and thus, avoiding the issue where files have their names replaced with \_N identifiers to ensure unique filenames.

This is because they are referencing physical file paths from the menu and WYSIWYG fields - which means the old replaced file is being referenced instead of the new one. Since these are core file fields and over 100 files have been uploaded, I cannot switch out to a Media field. I'm also not sure if that would even solve the problem at hand, anyway.

Is there any way I can hook into this widget via form alter, detect a click on the upload field, and if a new file is being added, delete the old one in place so that the file being uploaded the name stays intact and thus preserving link targets?

I have looked at the form with both `hook_form_alter` and `hook_field_widget_form_alter` \- but I am not really seeing anything I can use to hook into.

# Answer
You can use this approach.

```
/**
 * Implements hook_field_widget_form_alter().
 */
function insights_analyst_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
    if($element['#field_name'] == 'field_figure'){
        $element['#process'][] = 'removeFile';
    }
}

function removeFile(&$element , \Drupal\Core\Form\FormStateInterface $form_state, &$complete_form){
    $element['remove_button']['#submit'][] = 'markupRemove';
    return $element;
}

function markupRemove($form , \Drupal\Core\Form\FormStateInterface $form_state){
    $parents = $form_state->getTriggeringElement()['#array_parents'];
    $button_key = array_pop($parents);
    //print_r($button_key);
    if($button_key == 'remove_button'){
       //Write your logic here
    }
}

```
> 1 votes

---
Tags: 8, forms, files
---


# Question
Title: Execute a view in code and pass multiple arguments to an exposed filter?
I am executing a View in code of a paragraph preprocess to allow dynamic listings. The user selects which content types they would like to show, and the View should return nodes of those types with the same taxonomy selected. The idea is they can add multiple paragraphs with different configuration, leveraging the same View just with different arguments.

In this view, Content Type is an exposed filter, set to allow multiple. Here is the code in the preprocess\_paragraph hook:

```
$types = $paragraph->field_related_content_types->getValue();
$content_types = [];

foreach ($types as $type) {
  $content_types[] = $type['target_id'];
}

$view = Views::getView('related_content');
$view->setDisplay('related_content_display');
$view->setArguments(['type' => $content_types]);
$view->setExposedInput(['type' => $content_types]);
$view->preExecute();
$view->execute();

if (count($view->result)) {
  $variables['results'] = $view->buildRenderable('related_content_display', ['type' => $content_types]);
}

```

'type' is the filter name in the View. If I change it to only allow one value and pass it as a string, it works. So it seems like a syntax issue, but I cannot figure it out.

The method seems to indicate that this is possible:

```
  /**
   * Sets the arguments for the view.
   *
   * @param array $args
   *   The arguments passed to the view.
   */
  public function setArguments(array $args) {
    // The array keys of the arguments will be incorrect if set by
    // views_embed_view() or \Drupal\views\ViewExecutable:preview().
    $this->args = array_values($args);
  }

```

# Answer
> 4 votes
It looks like you're you doing an exposed filter and contextual filter for the type. As setArguments is for contextual filters and setExposedInput for exposed filters. If you've only got the exposed filter for type you should be able to remove setArguments and the 2nd argument on buildRenderable (which you dont need if you're doing setArguments)

I've got something very similar with an exposed type filter and just pass it an array to setExposedInput and it seems to works

```
$view->setExposedInput(['type' => ['news','page']]);

```

---
Tags: views, 8
---


# Question
Title: How can you find out in which module your code runs?
I often face the issue that I need to have module metadatas (such as relative path) and in the standard Drupal way I seem to be enforced to hardcode the module name like this:

```
\Drupal::moduleHandler()->getModule('my_module')->...

```

Is there an official way or a workaround to able to tell anywhere in your code (so not just .module) which module you are in (if it is module at all)?

# Answer
As Clive mentioned, a constant is your best bet. When I start up a new project, typically one of the first things I do is create an interface that contains constants that are applicable to the entire project. Usually the very first constant is for the module's machine name. I then use these constants, and not strings, throughout the project.

Here's a simplified and obfuscated version from one of my projects: (this file would be located in the folder `my_module/src/MyModuleInterface.php`)

```
<?php

namespace Drupal\my_module;

interface MyModuleInterface {

  const MODULE_NAME = 'my_module';
  const SERVICE = 'my_module.foobarbaz';
  const TAX_VOCAB_FOO = 'foo';
  const TAX_VOCAB_BAR = 'bar';
  const TAX_VOCAB_BAZ = 'baz';

  const PERM_ADMIN_FOO = 'administer foo';

  /**
   * Returns TRUE if the specified module is enabled.
   *
   * @param string $module_name
   *  The machine name of the module to check as enabled. Defaults to this
   *  module's machine name.
   *
   * @return boolean
   *  TRUE if the specified module is enabled.
   */
  function isModuleEnabled($module_name = self::MODULE_NAME);
}

```

The benefits to this approach are:

* Consistency through your project as well as for any other projects that might want to call on your module; they can also utilize the constant.
* Reduction of errors due to typos.
* If you use an IDE such as PHPStorm, you can take advantage of auto-completion, which is convenient and speeds code writing.
> 1 votes

---
Tags: 8
---


title: Strip html tags in preprocess hook

text:
# Question
Title: Strip html tags in preprocess hook
We have a `mytheme.theme` file that has a `mytheme_preprocess_node(&$variables)` function. Within this preprocess hook, we would like to remove all HTML tags within a formatted (long) field. The goal is to do without using `striptags` within the `node--page.html.twig` template.

**How can we do this securely without using `striptags` in a `twig` template?**

Here is what we tried, but cannot find how to do it using `mytheme_preprocess_node` hook.

`mytheme.theme`

```
function mytheme_preprocess_node(&$variables) {

  $node = $variables['node'];
  $field_value = $node->get('body')->first()->getValue()['value'];
  ksm($field_value);
  // cannot find way to remove `html` tags

  $variables['field_value'] = $field_value;
}

```

node--page.html.twig

```
{{ field_value }}

```

output of `ksm($field_value)`

```
"& lt;p & gt;When looking at & lt;a href="https://www.example.com/some-path/"& gt;article trends& lt;/a& gt; over time, attacks are cyclical in nature. Attackers develop new attack types and vectors, which are used to launch a new wave of attacks. As defenders become more proficient in stopping these new attacks, the attackers develop new types of attacks and the cycle repeats itself.</p& gt;

```

In order to properly display the output, I had to a space between `&` and `lt` characters above because StackExchange will convert those to proper tags. Within the `ksm` statement there is no space.

Additional item we tried within a twig template, but not sure if it is secure.

```
{% set body_processed = {
  '#type' : 'processed_text',
  '#text' : content.body.0,
  '#format' : content.body.format
} %}

```

# Answer
> 1 votes
Then better apply strip\_tags() on the processed text `$node->body->processed`. You might also want to apply Html::decodeEntities(). Still take care you configure the text format restrictively, because outputting the text in a non standard way can be a security risk increasing with features you allow. And you don't get security updates for custom code.

---
Tags: 8, theming, hooks
---


title: Ajax error render

text:
# Question
Title: Ajax error render
I receive this error message when I try my custom form in Drupal 8.

> User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children()

This is the code I am using

```
namespace Drupal\drupalup_simple_form\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

/**
 * Our simple form class.
 */
class SimpleForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'drupalup_simple_form';
  }

  /**
   * {@inheritdoc}
   */

 public function buildForm(array $form, FormStateInterface $form_state) {
  $form['search'] = array(
    '#type' => 'textfield',
    '#title' => t('Search:'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Submit'),
    '#button_type' => 'primary',
    '#ajax' => array(
      'callback' => [$this, 'submitForm'],
      'event' => 'click',
    ),
  );
  return $form;
}

  /**
   * {@inheritdoc}
   */

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $url = 'http://example.se/api/json/1.0/searchProduct.json?query=';
    $term = $form_state->getValue('search');
    $query_url = $url. $term;
    $client =  \Drupal::httpClient();
    $request = $client->get($query_url);
    $data = json_decode($request->getBody(), TRUE);
    $results = [];
    if (!empty($data) && !empty($data['items'])) {
      foreach ($data['items'] as $item ) {
        $results[] = $item['name'];
      }
    }
    return $results;
     }
  }
?>

```

The end result should be that all results from the URL with the \[searchword\] are shown when you have entered the search word in the textfield and pressed submit. Does anyone know how to solve this?

# Answer
I think this error relates to using an ordinal array, rather than an associative array, for the `$results` variable.

I think you might be able to fix it by replacing this loop:

```
foreach ($data ['items'] as $item ) {
  $results[] = $item['name'];
}

```

With this one:

```
foreach ($data['items'] as $key => $item ) {
  $results[$key] = $item['name'];
}

```

Hope it helps.
> 0 votes

# Answer
The error message isn't helping you out much here. In an ideal world it would be more like this:

> The value for element with key '0' is not an array, but also not NULL.

That would be more in-keeping with the logic that triggered the error in `Element::children()`, which is expecting each element whose key isn't prefixed with `#` to itself be a render array.

A valid render array can be formed with very little effort, changing your code to this should bring better luck:

```
foreach ($data['items'] as $key => $item ) {
  $results[] = ['#markup' => $item['name']];
}

```

See the Render arrays docs for more info.
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: How do I print an image field value in views-view.html.twig?
It seems I'm able to print text field values with `{{ view.field.field_example.getvalue(view.result[0]) }}`, but this same method doesn't work for image fields. Please help.

# Answer
> 0 votes
views-view.html.twig is not meant to be used for field printing.

You should use **views-view-fields--\[view-name\].html.twig**

OR

**views-view-fields--\[view-name\]--\[machine-name\].html.twig** if you want to be even more specific.

and there you just do

`{{ fields.field_name.content }}`

---

> For multi value fields, is there a way to print just one value within a field at a time?

```
{% set field_values = row._entity.get('field_name').getValue() %}
{% for field_value in field_values %}
    <li>{{ field_value['value'] }}</li>
{% endfor %}

```

> By doing {{ fields.field\_color\_hex.content }}, I printed them all at once.

In your case:

```
{% set hexes = row._entity.get('field_color_hex').getValue() %}
{% for hex in hexes %}
    <li>{{ hex['value'] }}</li>
{% endfor %}

```

---
Tags: views, theming
---


title: How do I migrate file uploads?

text:
# Question
Title: How do I migrate file uploads?
I'm working on a custom migration from Drupal 6 to Drupal 8. Some of the content types have a field used for file attachments (*field\_attachments*).

When I run the migration that connects the files to the nodes, I get this error.

> SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'title' cannot be null: INSERT INTO {node\_field\_data} (nid, vid, type, langcode, status, uid, title, created, changed, promote, sticky, default\_langcode, revision\_translation\_affected) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10, :db\_insert\_placeholder\_11, :db\_insert\_placeholder\_12); Array ( \[:db\_insert\_placeholder\_0\] =\> 2064 \[:db\_insert\_placeholder\_1\] =\> 3019 \[:db\_insert\_placeholder\_2\] =\> forum \[:db\_insert\_placeholder\_3\] =\> en \[:db\_insert\_placeholder\_4\] =\> 1 \[:db\_insert\_placeholder\_5\] =\> 0 \[:db\_insert\_placeholder\_6\] =\> \[:db\_insert\_placeholder\_7\] =\> 1558576761 \[:db\_insert\_placeholder\_8\] =\> 1558576761 \[:db\_insert\_placeholder\_9\] =\> 0 \[:db\_insert\_placeholder\_10\] =\> 0 \[:db\_insert\_placeholder\_11\] =\> 1 \[:db\_insert\_placeholder\_12\] =\> 1 ) (/app/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:847)

The *migrate\_plus.migration.custom\_upload.yml* file for the migration contains the following lines.

```
langcode: en
status: true
dependencies: {  }
id: custom_upload
class: Drupal\migrate\Plugin\Migration
field_plugin_method: alterFieldInstanceMigration
cck_plugin_method: null
migration_tags:
  - 'Drupal 6'
  - Content
migration_group: custom
label: 'File uploads'
source:
  plugin: d6_upload
process:
  nid:
    -
      plugin: get
      source: nid
  vid:
    -
      plugin: get
      source: vid
  langcode:
    -
      plugin: user_langcode
      source: language
      fallback_to_site_default: true
  type:
    -
      plugin: get
      source: type
  field_attachments:
    -
      plugin: sub_process
      source: upload
      process:
        target_id:
          plugin: migration_lookup
          migration: custom_file
          source: fid
        display:
          plugin: default_value
          default_value: 1
        description: description
destination:
  plugin: 'entity:node'
migration_dependencies:
  required:
    - custom_file
    - custom_article
    - custom_forum

```

From the error message, it appears that Drupal is trying to create a node; even though, I'm actually running the *custom\_upload* migration after I ran the migration of all nodes.

I have migrated the nodes and the files already and I can see all the nodes in the database as well as the files in their directory and the database.

What am I missing?

# Answer
> 4 votes
Your `custom_upload` migration *is* trying to create nodes; the `custom_upload` migration is taking a `d6_upload` source plugin:

```
source:
  plugin: d6_upload

```

...and mapping it to a `node:entity` destination plugin:

```
destination:
  plugin: 'entity:node'

```

Since the `d6_upload` source doesn't have a `title` field to map to the `node:entity` field in the `process` definition of your migration, the migration fails as it tries to insert a titleless node.

You need update your node migration. If your node/file migrations are working, the node migration should have a `process.field_attachments` yml property to map `field_attachments.target_id` to the `fid` property from your `custom_file` migration.

# Answer
> 2 votes
Every content type migration creates its own mapping table.

I got a clue from how the taxonomy terms are migrated. The trick was to tell Drupal where to look for the `nid`.

I replaced:

```
process:
  nid:
    -
      plugin: get
      source: nid
  vid:
    -
      plugin: get
      source: vid

```

with...

```
process:
  nid:
    -
      plugin: migration_lookup
      migration:
        - custom_article
        - custom_forum
      source: nid
    -
      plugin: skip_on_empty
      method: row

```

... and now it works.

By listing the internal names of my two content types, Drupal was able to figure out what node mapping table should be used.

Note that I removed the `vid:` block with the replacement. I'm not importing node revisions and therefore, I'm not expecting that this will affect anything in my case.

---
Tags: 8, migrations
---


title: How to show sub-menu in a block?

text:
# Question
Title: How to show sub-menu in a block?
I have a menu in Drupal 7 with 2 main links like home and about us, but I have 3 sub menu in about us like

* About us
    + About Us 1
    + About Us 2

I need to show these 2 submenu in a block and show active when about1 same for about2.

# Answer
> 0 votes
Sounds as if you need the Submenu Tree module.

This is an excerpt form the project page:

> Submenu Tree provides a method for structuring content hierarchically. For content which has a menu link, Submenu Tree display a list of content which is at the same level or below the content in the menu.

Is this what you were looking for?

# Answer
> 0 votes
Sorry I dun get what you mean block. Just wonder will tb mega menu module help you. Check this link: https://www.youtube.com/watch?v=WnuhbFwsJ3M

# Answer
> 0 votes
You can use the superfisch module. https://www.drupal.org/project/superfish

Set the about menu entry to expand by default, so when you hover over menu item about you will see about1, about2.

The superfisch menu can be used in any block.

# Answer
> 0 votes
It sounds like Menu block is all you need.

---
Tags: 7, navigation
---


title: Drupal 8 Theming

text:
# Question
Title: Drupal 8 Theming
I am beginner with drupal 8 theming.

My Question is: I have created a custom content type name project\_images for making carousal SlideShow. It consists multiple images as a field. Now I want to retrieve all images in a custom region with twig templating how to access all images from project\_images content. Thanks

# Answer
> 1 votes
What is the type of the field that stores the multiple images ?

Is it an Image field or an Entity Reference field (Media Entity) ?

1. check this if it's an image field
2. check this if it's an Entity Reference field

The two methods will let you extract the value of the image field using a twig syntax.

---
Tags: theming
---


title: REST API 401 Unauthorized

text:
# Question
Title: REST API 401 Unauthorized
I am trying to create a new node with POST through REST in D8. I have enabled the relevant modules (hal, serialization, http basic authentication, Rest web services, rest ui) and added the required permissions to users (create content). I configured the services with restui and added basic\_auth for authentication and allowed post on my endpoints. I send X-CSRF-Token together with Content-Type json (or jal+json as configured) and I get either a login popup (basic auth style with user/pass) in restlet client and a 401 Unauthorized with this response.

> { "message": "No authentication credentials provided." }

I even tried using cURL from command line to create my node, with the same result and a GuzzleHttp Exception.

> PHP Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: `POST http://www.xxxxxx.com/loyalty/node/?_format=json` resulted in a `401 Unauthorized` response: {"message":"No authentication credentials provided."} ' in /home/xxxxx/public\_html/loyalty/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113

If I allow anonymous to create articles and disable basic\_auth everything works fine.

Any clues?

# Answer
Can you post an exact curl request? Does the user in your request have permission to create content?

if basic auth is enabled then you need to add the user name and password to the request. For example curl request:

```
curl --include \
  --request POST \
  --user admin:admin \
  --header 'Content-type: application/hal+json' \
  https://ddj9.ply.st/node?_format=hal_json \
  --data-binary '{"_links":{"type":{"href":"http://ddj9.ply.st/rest/type/node/article"}},"title":[{"value":"Example node title"}],"type":[{"target_id":"article"}]}'

```

Otherwise If the user must be authenticated via cookie then: 1. you have to send a post to login the user.

`curl --header "Content-type: application/json" --request POST --data '{"name":"admin", "pass":"admin"}' http://drupal.d8/user/login?_format=json`

The output will look like:

```
{"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"wBr9ldleaUhmP4CgVh7PiyyxgNn_ig8GgAan9-Ul3Lg","logout_token":"tEulBvihW1SUkrnbCERWmK2jr1JEN_mRAQIdNNhhIDc"}

```
2. Retrive a token from the returned value result
3. Do what you need to do. :

```
// get X-CSRF-Token.
$url = 'your_url';
$json = '{
"name": "admin",
"pass": "PASSWORD"
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
 'Content-Type: application/json')
);
$result = curl_exec($ch);
$user = json_decode($result, TRUE);
$x_csrf_token = $user['csrf_token']
if ($x_csrf_token) {
    // do what you need
 curl_setopt_array($curl, array(
  CURLOPT_URL => "http://www.xxxxxx.com/loyalty/node/?_format=json",
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input,
  CURLOPT_HTTPHEADER => array(
   // if you need basic auth then uncomment the nextline
   // "authorization: Basic b64Value",
    "cache-control: no-cache",

    "x-csrf-token: $x_csrf_token"
  ),
));
$response = curl_exec($curl);

```
> 0 votes

# Answer
Had a similar issue when I switched from a laptop to another... on the old one there was no error, on the new one I got the same error. The authorization header was not coming in the server request. After some digging, I discovered that I didn't enable rewrite module on the new one. After enabling the module everything worked fine. So try `sudo a2enmod rewrite`
> 0 votes

---
Tags: 8
---


# Question
Title: Possible to theme the form's elements with own twig?
I was thinking to get twig outputs so I could use these twig variables on a `form.html.twig` such as below:

```
    <div class="row">
        <div class="col-md-6">
            {{ form.name }}
            {{ form.mail }}
            {{ form.subject }}
        </div>
        <div class="col-md-6">
            {{ form.body }}
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            {{ form.submit }}
        </div>
    </div>

```

Any idea how to get the similar variables via hooks on `MYTHEME.theme`?

# Answer
I found out a solution which I ended with using `{{ element.[machine name] }}` instead of `{{ children }}` on my custom template which is cloned by `form.html.twig`. The result of the code look similar below:

```
    <div class="row">
        <div class="col-md-6">
            {{ element.name }}
            {{ element.mail }}
            {{ element.subject }}
        </div>
        <div class="col-md-6">
            {{ element.body }}
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            {{ element.submit }}
        </div>
    </div>

```

If you have other suggestion, I am happy to know! :)
> 1 votes

---
Tags: theming, forms, hooks
---


# Question
Title: Newly created fields are not being displayed
I have a content type "Article" with fields and data that was migrated from a Drupal 7 website.

1. In the admin/structure/types/manage/article/fields I added a new text field called "Test" with default value some of some HTML added.
2. Then, I went to manage form display and disabled that field from the form
3. Then I went to manage display of the appropriate view mode and enabled that field.
4. Flushed the cache

Reloading the article page doesn't display the newly added field. I believe it is because there is no value in it, but shouldn't adding a default value to the field pre-populate that field for all previous content belonging to that content type? Or am I missing something here?

# Answer
> 3 votes
Adding a default value doesn’t actually set any value in the field. To do that you must either edit the nodes you want the field on and click save, or write an update hook that sets the field value on all the nodes.

An update hook must be placed in a custom module’s .install file, in your case it would be something like:

```
function MY_MODULE_update_N() {
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties('type' => 'article');
  foreach ($nodes as $node) {
    $node->set('field_name', $value);
    $node->save();
  }
}

```

As @4k4 mentioned if you have to update too many nodes as you have memory to, you can create batch updates using the &$sandbox, click here for more information

---
Tags: 8, entities
---


# Question
Title: Programatically copy an image from user entity to webform submission entity
Using a custom webform handler, I am trying to copy an image **from** the image field (`field_usr_avatar_img`) located at the user account page **to** the image element (`avatar_img`) located at the webform submission of the a webform where my custom handler is set.

In my custom handler, I have tried the below:

```
use Drupal\user\Entity\User;
use Drupal\file\Entity\File;

public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

$userid = 25;
$userprofile = \Drupal\user\Entity\User::load($userid);

// Get the image id.
$avatarimg = $userprofile->field_usr_avatar_img->id()

// Set webform submission Data.
$webform_submission->setElementData('avatar_img', $avatarimg);

// Save the updated webform submission.
$webform_submission->save();

}

```

However, I ended up with below error:

```
Error: Call to undefined method Drupal\file\Plugin\Field\FieldType\FileFieldItemList::id() in Drupal\my_custom_module\Plugin\WebformHandler\customWebformHandler->submitForm() (line 61...

```

Line 61 is: `$avatarimg = $userprofile->field_usr_avatar_img->id()`

any help on how to copy the image from an entity to another ?

Thank you,

# Answer
You must call `->entity` to get the file entity, then you can call `->id()` like this, `$userprofile->field_usr_avatar_img->entity->id()`.
> 1 votes

---
Tags: 8, entities, users, files, webforms
---


title: How to place Contact form in block?

text:
# Question
Title: How to place Contact form in block?
I have to embed a contact form inside of a block, and I'm trying to use the entity.form\_builder service, But I'm not sure which entity I should give it, I found Message and ContactForm entity, so what I'm thinking is to create a contact form entity and give it to the `entityFormBuilder->getForm($contactFormEntity)`

My current code is:

```
<?php

/**
 * @file
 * Contains Drupal\pid_contactform_block\Plugin\Block\TellUsYourStoryBlock
 */

namespace Drupal\pid_contactform_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class TellUsYourStoryBlock
 * @package Drupal\pid_contactform_block\Plugin\Block
 * @Block(
 *     id = "tell_us_your_story_block_id",
 *     admin_label = "Tell us your story block",
 *     module = "pid_contactform_block"
 * )
 */
class TellUsYourStoryBlock extends BlockBase implements ContainerFactoryPluginInterface {
    protected $entityFormBuilder;

public function __construct(array $configuration, $plugin_id, $plugin_definition, $entityFormBuilder) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityFormBuilder = $entityFormBuilder;
}
/**
 * Builds and returns the renderable array for this block plugin.
 *
 * If a block should not be rendered because it has no content, then this
 * method must also ensure to return no content: it must then only return an
 * empty array, or an empty array with #cache set (with cacheability metadata
 * indicating the circumstances for it being empty).
 *
 * @return array
 *   A renderable array representing the content of the block.
 *
 * @see \Drupal\block\BlockViewBuilder
 */
public function build()
{
    return $this->entityFormBuilder->getForm();

}

/**
 * Creates an instance of the plugin.
 *
 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
 *   The container to pull out services used in the plugin.
 * @param array $configuration
 *   A configuration array containing information about the plugin instance.
 * @param string $plugin_id
 *   The plugin ID for the plugin instance.
 * @param mixed $plugin_definition
 *   The plugin implementation definition.
 *
 * @return static
 *   Returns an instance of this plugin.
 */
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition)
{
    return new static(
        $configuration,
        $plugin_id,
        $plugin_definition,
        $container->get('entity.form_builder')
    );
}

```

}

My question is basically:

* Am i doing it the right way?
* How do I initialize the ContactForm entity correctly, if I am right, should I just import it or should I require it through a service or something?
* If I'm not right, do you have any idea how I should do it then?

# Answer
> 11 votes
Try Contact block module, which provides the contact form in a block.

From module documentation,

> The Contact Block module provides contact forms in a block. It uses the contact forms that can be created using the Drupal 8 core Contact module.

# Answer
> 5 votes
Try https://www.drupal.org/project/entityform\_block project, which allows you to create add form blocks for any entity type.

# Answer
> 3 votes
Create a new block type with an ER field that points to contact forms, enable contact\_storage, and create a block, no coding required

# Answer
> 3 votes
There is also a module FormBlock, which looks more general.

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

I found an issue, to merge the FormBlock and the ContactBlock module together.

# Answer
> 3 votes
The simplest way is to use contact block module that is made specifically for this need. It will provide blocks for each of your contact form.

# Answer
> 1 votes
Since this applies to a few of the answers I am posting a separate response, hope that is okay...

For both contact\_block and formblock I have tested both a custom theme, and then (to be sure) Bartik (8.6.1 for 8.6.x site on pantheon, if it matters). For both, the module "fails" to render the block. However, it does create "space" as if it was rendered. That is, if you put it in sidebar-first and that is the only thing for sidebar-first in the Block-Layout then there is a Fat Margin As-If it was rendering the sidebar with the Contact Form.

On a hunch, I uninstalled BigPipe, and presto! it works.

(Knowing that the order of module implementation sometimes matters, I did try re-installing BigPipe and the non-rendering behavior returned.)

I had a hunch to post as an Issue, but I am not certain how BigPipe fits in with all of this so I didn't. Maybe someone that knows more about BigPipe and why it would have this effect can respond to this post, and perhaps submit it as an issue.

# Answer
> 1 votes
Simple solution of your problem:

```
public function build() {
  $message = \Drupal\contact\Entity\Message::create(['contact_form' => 'feedback']);

  return \Drupal::service('entity.form_builder')->getForm($message);
}

```

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


title: How to configure webform with smtp

text:
# Question
Title: How to configure webform with smtp
I have create a webform and i want to configure it sending emails with smtp authentication. I have install the SMTP authentication module also, but i cant find any option that allows me to setup webform for using smtp.

Is this possible? Any advice?

# Answer
> 11 votes
Webform module uses the `mail()` for sending the mails. `SMTP Authentication Support` module allows Drupal to bypass the PHP `mail()` function and send email directly to an SMTP server.

Along with `SMTP Authentication Support` module you would need to install the Mail system module and configure it to assign a smtp class to webform which is step by step explained in this tutorial.

If you have SMTP module installed in your drupal site than you would have to configure the SMTP settings (`/admin/config/system/smtp`) for sending the email

Example (Configuring SMTP for GMAIL):

```
A. INSTALL OPTIONS:
 1. Turn this module on or off: (SELECT "ON")

B. SMTP SERVER SETTINGS:
 1. Server: smtp.gmail.com
 2. Backup server: (LEAVE BLANK)
 3. Port: 465
 4. Use encrypted protocol: (SELECT "Use SSL")

C. SMTP AUTHENTICATION:
 1. Username: (ENTER YOUR GMAIL EMAIL ID)
 2. Password: (ENTER YOUR ABOVE EMAIL ID PASSWORD)

D. E-MAIL OPTIONS:
 1. E-mail from address: (ENTER YOUR GMAIL EMAIL ID AS ENTERED ABOVE)
 2. E-mail from name: (ENTER SITE NAME, ITS DEFAULT VALUE IS DRUPAL VERION)
 3. Allow to send e-mails formated as Html (ENABLE CHECKBOX IF YOU WANT)

E. SEND TEST E-MAIL:
 1. E-mail address to send a test e-mail to:
   (ENTER YOUR EMAIL ID AT WHICH YOU WANT TO RECEIVE TEST MAIL)

```

Instead of GMAIL if you want to use some other service provider than check their server details and the port details.

# Answer
> 3 votes
Yes it is possible.The Problem is that by default webform send emails out via mail(). To fix it we have to assign a smtp class to webform. To do so follow this step and in order to configure smtp with a gmail account @Ankit has mentioned it very clear here already.

steps in summary

* You need to settup mailsystem : this module will help us configure mail variables or we can see it will tell webform to use smtp.
* As given in step guide select webform in thee new setting, keep the key as empty save the settings and now you see "Webform module class" select-list on the top of same page where you have just saved the settings.
* Here is the "Webform module class" select-list you can set the webform to use smtp module.

# Answer
> 1 votes
Drupal SMTP auth module can help you.

**SMTP Auth:**

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP. This module uses the smtp and mail class's from PHPMailer. https://github.com/PHPMailer/PHPMailer

# Answer
> 1 votes
This are the steps you have to follow to configure Mail System Module on Drupal 7

Step 1: Go to Configuration \> System \> Mail System Step 2: Go to new setting Step 3: Select the mail system you want to use with the module

# Answer
> 1 votes
Is it possible that only two projects support SMTP authentication?
https://www.drupal.org/project/phpmailer
https://www.drupal.org/project/smtp
Both still in beta.
Typical mail server today won't send any mail without smtp authentication (not talking about VPS or spam services).

---
Tags: 7, webforms
---


# Question
Title: Composer install dependency error drupal/drupal dev-master
I'm managing my site dependencies via composer, most of the times works really well. Now I installed my site on a new server, using the exact same code-base as before (but with composer 1.8.0 instead of 1.7.x as before though). On running `composer install` I get the following error:

> * don't install drupal/core 8.6.4|remove drupal/drupal dev-master
> * remove drupal/drupal dev-master|remove drupal/core 8.6.4
> * Installation request for drupal/drupal dev-master -\> satisfiable by drupal/drupal\[dev-master\].
> * Installation request for drupal/core 8.6.4 -\> satisfiable by drupal/core\[8.6.4\].

Usually I can solve these sorts of errors but this time I'm having a hard time. What's the meaning of `drupal/drupal dev-master`, because usually you do not specify this anywhere directly?

# Answer
I ran into the same issue. My issue was related to upgrading to a new Drupal core minor version (ex: 8.6 to 8.7). If that's not the case for you, then my steps may be unnecessary.

I was able to resolve it by removing the `core` directory of Drupal. Then run `composer update drupal/core --with-dependencies`. I believe the issue stems from the `core/composer.lock` file having conflicts with what you are trying to install.
> 2 votes

# Answer
Let me start off by saying that I've never encountered `drupal/drupal dev-master` before.

Based on my Composer experience, the nuclear option is to run `composer install` and upgrade everything all at once.

The more nuanced option is to use `composer prohibits` to figure out what's blocking an update.

This blog post from Jeff Geerling might help:

https://www.jeffgeerling.com/blog/2018/updating-drupalcore-composer-drupal-core-doesnt-update

From the article:

> The thermonuclear option with Composer is to delete your vendor directory, delete your lock file, hand edit your `composer.json` with newer package versions, then basically start over from scratch. IMO, this is always a bad idea unless you feel safe upgrading all the things all the time (for some simple sites, this might not be the worst idea, but it still removes all the dependency management control you get when using Composer properly).

So it's better to find out exactly what dependencies are blocking you, and then explicitly require the packages with:

`composer update drupal/core vendor/package --with-dependencies`

Also:

https://www.jeffgeerling.com/blog/2017/composer-and-drupal-are-still-strange-bedfellows
> 1 votes

---
Tags: composer
---


# Question
Title: Result should return a value greater than or equal to the selected facet
Here is the scenario. I have created a facet which list all GPA's (these are decimal numbers). e.g. 2.0, 2.5, 3, 3.5 etc.

What I wanted is when say a user choose 2.5 GPA from the facet, the returned contents should be contents that has a GPA of 2.5 and above.

I have been trying to figure it out using views alone, but I can't get it to work. If It can be done with just views, can you please suggest what to do? Or do you think this can only be achieved by code?

# Answer
> 0 votes
I wasn't able to find answers on how to solve this with Facets alone, or writing custom code which is related to facet API. Honestly, I've been ignoring the most obvious solution to my problem which is Views exposed filter, and this is how I managed to solve my problem:

1. Create an exposed filter for GPA, which filters result that are greater than or equal to the provided GPA. I made this hidden by default.
2. I disabled the GPA facet I was using, and wrote my own GPA filter block. It's just a matter of querying the GPA field table, disregarding duplicates.
3. Wrote a custom script that captures the selected GPA value, from the custom GPA block I created, and then feed it hidden views exposed filter.
4. I added few more customization to it so that it behaves exactly like the rest of the facets.

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


title: AJAX callback inside hook_form_alter()

text:
# Question
Title: AJAX callback inside hook_form_alter()
I don't know how to implement AJAX callback in hook\_form\_alter().

The field is plain text by default and it is populated by NID (number) of the client company. The module name is "my\_car". I didn't use node reference in this field.

Here is the code:

```
function my_car_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'car_node_form') {

        $clientCompanies = companyTitle(12); // TID 12

        // Replace Client company NID with title
        $form['field_car_company']['und'][0]['value'] = array(
            '#title' => 'Client company',
            '#type' => 'select',
            '#default_value' => $form_state['node']->field_car_company['und'][0]['value'],
            '#options' => $clientCompanies,
            '#required' => TRUE,
            '#empty_option' => t('- Select -')
        );
    }
}

```

Here I use companyTitle() function to return all companies (nodes) that have TID 12 and replace field type ("textfield" with "select") and it's content - a number with text (NID with title).

```
function companyTitle($tid) {

    $results = db_query("
        SELECT n.nid, n.title
        FROM {node} AS n
        LEFT JOIN {field_data_field_company_type} AS ct ON ct.entity_id = n.nid
        WHERE n.type = 'company' AND ct.field_company_type_tid = :tid
        ORDER BY n.title ASC",
        array(':tid' => $tid))->fetchAllKeyed();

    return $results;
}

```

I have written the function that returns NID and title of client company based on TID and title:

```
function ajaxCompanyTitle($tid, $companyName) {

    $query = db_select('node', 'company')
        ->fields('company', array('nid', 'title'))
        ->condition('company.type', 'company', '=')
        ->condition('type.field_company_type_tid', $tid, '=')
        ->condition('company.title', '%'.db_like($companyName).'%', 'LIKE')
        ->orderBy('company.title', 'ASC')
        ->range(0, 10);

    $query->leftJoin('field_data_field_company_type', 'type', 'type.entity_id = company.nid');

    $results = $query->execute()->fetchAll();

    return $results;
}

```

Now is the question of how to implement AJAX with the last function. I need text field (it does not to be a select list) with AJAX search where NID will be rendered as title (NID remaining only in the database in the field\_car\_company\_value column).

Apparently, I don't know how to implement a callback function.

```
function my_car_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'car_node_form') {

        // Replace Client company NID with title
        $form['field_car_company']['und'][0]['value'] = array(
            '#title' => 'Client company',
            '#type' => 'textfield',
            '#required' => TRUE,
            '#ajax' => array(
                'callback' => 'ajax_callback',
                'wrapper' => 'edit-field-car-company-und-0-value',
            )
        );
    }
}

function ajax_callback($string = '') {

    $matches = array();

    if ($string) {

        $clientCompanies = ajaxCompanyTitle(12, $string);

        foreach ($clientCompanies as $clientCompany) {
            $matches[$clientCompany->title] = $clientCompany->title;
        }
    }

    drupal_json_output($matches);
}

```

# Answer
There are two types of ajax in Drupal. Traditional AJAX, and the Drupal Form API #ajax api. You are mixing the two, by using #ajax in your form, but returning and AJAX response, rather than an #ajax callback response.

To understand #ajax, you need to understand the process by which the Form API works. This is how a standard non-Ajax Form API form works in Drupal:

1. Some function is called which builds a render array representing the form.
2. Form alter hooks are called, allowing other modules/theme to alter the form.
3. Drupal caches the render array in the database, to be used for comparison on submission, as a security measure to ensure that the submitted data matches the type of data expected to be submitted.
4. The form is rendered into HTML and sent to the browser.
5. The user submits the form.
6. Drupal retrieves the form from the database, confirms that the submitted data is allowed, and sanitizes it.
7. Drupal validates the form, runs submission hooks, and redirects the user to whatever page they are supposed to be on after form submission.

When #ajax is implemented, the process is the same as above, but with some additional steps in the middle.

1. Some function is called which builds a render array representing the form.
2. Form alter hooks are called, allowing other modules/theme to alter the form.
3. Drupal caches the render array in the database, to be used for comparison on submission, as a security measure to ensure that the submitted data matches the type of data expected to be submitted.
4. The form is rendered into HTML and sent to the browser.

---------- #ajax behavior start --------------

5. The user does something that triggers #ajax
6. The browser sends all the data in the form back to Drupal, as if the form were submitted.
7. Drupal retrieves the form from the database, and confirms that the submitted data is allowed, and sanitizes it.
8. Validation and submit handlers for the form are called. The form must be set to be rebuilt in the submit handler for the ajax to work.
9. The form is rebuilt from the original form definition, passing it the #ajax submitted values.
10. Form alter hooks are called, allowing other modules to alter the form, using the #ajax submitted values.
11. Drupal caches the new render array in the database, to be used for comparison on submission.
12. The ajax built form is passed to the #ajax callback handler. The handler then returns the part of the form to be injected back into the DOM on the browser. This can be part or all of the form.
13. The new content is inserted into the DOM.

---------- #ajax behavior end --------------

14. The user submits the form.
15. Drupal retrieves the form from the database, confirms that the submitted data is allowed, and sanitizes it.
16. Drupal validates the form, runs submission hooks, and redirects the user to whatever page they are supposed to be on after form submission.

Referring back to your code, your ajax callback will receive two arguments, $form and $form\_state, and needs to return a section of your form. So it should look something like:

```
function ajax_callback($form, $form_state) {
  return $form['some_element']['of_the_form'];
}

```

In your form, this is likely `$form['field_car_company']['und'][0]['value']`. You will build the options of that form element when the form is initially rendered the way you are now, and if the form has been submitted using ajax, use the submitted values to determine the new options to show.
> 2 votes

# Answer
> @Jaypan

I did the following:

```
function my_car_menu() {

    $items = array();

    $items['car/autocomplete'] = array(
        'title' => 'Autocomplete for cars',
        'page callback' => 'car_autocomplete',
        'access arguments' => array('list of cars'),
        'type' => MENU_CALLBACK
    );

    return $items;
}

function my_car_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'car_node_form') {

        $form['field_car_company']['und'][0]['value']['#ajax'] = array(
            'callback' => 'ajax_callback'
        );

        $form['field_car_company']['und'][0]['value'] = array(
            '#type' => 'textfield',
            '#default_value' => $form_state['node']->field_car_company['und'][0]['value'],
            '#title' => 'Client company',
            '#description' => 'Zakupac',
            '#required' => TRUE,
            '#autocomplete_path' => 'car/autocomplete'
        );
    }
}

function ajax_callback($form, $form_state) {
    return $form['field_car_company']['und'][0]['value'];
}

function car_autocomplete($string = '') {

    $matches = array();

    if ($string) {

        $clientCompanies = ajaxCompanyTitle(12, $string);

        foreach ($clientCompanies as $clientCompany) {
            $matches[$clientCompany->title] = check_plain($clientCompany->title);
        }
    }

    drupal_json_output($matches);
}

```

The AJAX callback is now working. I have achieved it using `'#autocomplete_path' => 'car/autocomplete'`. But in database is now written `$clientCompany->title` instead of `$clientCompany->nid`. I still need NID in database.
> 0 votes

---
Tags: nodes, hooks, ajax
---


# Question
Title: How to validate field in inline entity form referenced field
I have created field "Referenced" which is entity reference field of other content type. Also this field have inline entity form functionality means its giving two button "add new node" and "and existing node"

Once we clicked on "add new node", publication content type node form will open. i want to make field\_author entity reference field inside the inline entity form

# Answer
> 0 votes
Inline entity form only makes the *connection* to some structure and *displays* it, it doesn't change it. In your case the Inline entity form is showing the Create node form of a certain type (you haven't mentioned which type is in your case), but you can't change the structure through the Inline entity form.

If you want to add a User reference field to that node type you have to go through Structure \> Content types \> \[Your type\] \> Manage fields.

There you can add a new field (or use an existing one if it makes sense to your structure) of the type Reference \> User.

Once you add that field when you go to created nodes that reference that node type through the Inline entity form, you will see the User reference field among the fields after clicking on "Add new node".

---
Tags: nodes
---


# Question
Title: How do I stringify objects or at least get a string value?
The `item.content` for my field item is 'active'. However, when I use a comparison operator as seen below, it never equates to True but always False. I thought maybe some spacing issues was the reason, but that seems to not be the case.

Is the content in `item.content` not a string? I am assuming when I call item.content, its probably a object, but I can't find any documentation on how to turn a object's value into a string so it equates to true.

```
{% for item in items %}
  {% if item.content == 'active' %}
    <div{{ item.attributes.addClass('field__item', 'status_item_active') }}>{{ item.content }}</div>
  {% else %}
    <div{{ item.attributes.addClass('field__item', 'status_item_notactive') }}>{{ item.content }}</div>
  {% endif %}
{% endfor %}

```

# Answer
> 4 votes
You can try this instead

```
{% if element['#items'][key].value == 'active' %}

```

# Answer
> 0 votes
I solved it with this code:

```
{% if 'active' in item.content|render|render %}

```

---
Tags: 8, theming
---


# Question
Title: "Add to Cart" button/from in template (form ID from Node ID)?
I'm working on a website made with D7 and the Commerce Module, with a "Products" view (for the Product content type) having this relationship field:

*(Products referenced by field\_info\_prodotto) Commerce Product: Add to Cart form*

I want this "Buy Now" button/form to also be inside each products' page (= in the template for the Product content type).

I can create a template for single nodes (see code), but how should I edit the general template (node--product-display.tpl.php)?

```
# node--181.tpl.php
<form class="commerce-add-to-cart commerce-cart-add-to-cart-form-24" autocomplete="off"
action="/en/products" method="post" id="commerce-cart-add-to-cart-form-24" accept-charset="UTF-8">
<div><input type="hidden" name="product_id" value="24">
<input type="hidden" name="form_id" value="commerce_cart_add_to_cart_form_24">
<input name='form_token' type='hidden' value='<?php print drupal_get_token('commerce_cart_add_to_cart_form_24'); ?>'>
<div id="edit-line-item-fields--9" class="form-wrapper"></div><input type="hidden" name="quantity"
value="1">
<input type="submit" id="edit-submit--9" name="op" value="Add to cart" class="form-submit">
</div>
</form>

```

(In the template there is already the code to show a "Buy Now" field - field\_tab\_5 - but that's just an empty text field and I suppose it's not what I'm after).

# Answer
Found a solution!

* Add a field of type "Product reference" to the Product content type ("Inline entity form - Multiple values" as widget)
* Use "Add to Cart Form" to its display format
* Field API in node--product-display.tpl.php:

print render($content\['field\_info\_prodotto'\]);
> 0 votes

---
Tags: commerce
---


# Question
Title: Provide autocomplete field with user's Display Name
Drupal core already supports autocompletion of username fields. However is there a way to provide autocomplete for user's Display Name? Since this is a virtual field, a database query with % like cannot be performed.

One way I could think of accomplish this would be to save display name for each user in the user\_data table, and set this storage with an event subscriber that reacts on account creation and account update. Once this field is available, it could then be used with database queries for autocomplete.

Interested to know if there is another way to do this.

# Answer
> 0 votes
I looked at realname module, which autocompletes the real name. Since realname stores the user defined DisplayName equivalent in the database, it can issue % LIKE queries and autocomplete on both username and realname.

I posted this question to see if there were other approaches, the realname module validates the proposed method as asked in the question.

---
Tags: 8, entities, users, forms, ajax
---


# Question
Title: Remove a contextual filter programmatically
Is there a way to programmatically remove a contextual filter from a view? I have a view where, at times, I want to display it without the contextual filter active. This is the code I tried.

```
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'some_view') {
    unset($view->args);
  }
}

```

I also tried the same code within `hook_views_pre_execute()`.

How can I achieve this?

# Answer
> 0 votes
To remove a contextual filters just set the `$args` to empty array or unset the desired arguments `unset($args[0])` to remove the first argument an so on: Here is an example to remove all contextual filters:

```
/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'some_view') {
    // Remove all filters.
    $args = [];
  }

```

---
Tags: 7, views
---


# Question
Title: Overriding a specific display doesn't work
I created a view in Drupal 8 with 2 displays. I want to keep a display content view mode as teaser and the other as featured (custom), but when I change a display it updates the other display as well.

>

# Answer
It's easy to miss if you're always clicking on the `| Settings` link of an Option.

Options can be set to apply to `All displays` or you can override for each Display separately `This attachment (override)`.

But you have to click on the Option itself and not its "Settings" link to see that Dropdown.

You clicked on the "Teaser" or the "Featured" Settings link of your `Show` Option, but there is no Dropdown to override there.

You have to click on the **`Content`** link first, Override through the Dropdown for this Attachment only and Apply (this display). Then you can change the Settings for the Option if you have to. It will only apply to the current Display.

You can change the original Display Option to what you want and Apply to all displays, that one doesn't have to be overridden, unless it makes sense for that particular case.
> 1 votes

# Answer
You need to first select content and change the setting to this attachment override. Then select the mode. Like the below image.
> 0 votes

---
Tags: views
---


title: Redirect user after one-time-login

text:
# Question
Title: Redirect user after one-time-login
When users get an email with one time login link, they will arrive on a page to set their password (separated form via Password Separate Form) But once they click submit, it doesn't redirect them to the normal view of the profile page.

How should I make the redirect? I tried different Rules (Test 1, Test 2) and I even wrote to the module support of Password Separate Form, but nobody answer me and I need to fix the issue.

# Answer
For people that want to have a separate form, here is my own solution:

I deinstalled Password Separate Form and, instead, installed Password Reset Landing Page (PRLP) It does the redirect, the separate form and make sure people don't forget to actually set the new password.
> 1 votes

---
Tags: 8, rules, redirection
---


# Question
Title: Why doesn't LinkFormatter::viewElements bubble cache metadata?
I am trying to understand how the token system in Drupal 8 interacts with the cache bubbling system and in `LinkFormatter` I see `$link_title = \Drupal::token()->replace($item->title, [$entity->getEntityTypeId() => $entity], ['clear' => TRUE]);` doesn't pass in a `BubbleableMetadata` object to the token system. But why?

# Answer
Is this causing a bug for you, or are you just trying to understand how it works at all?

Making the token system integrate with the cache system happened *very* late in the Drupal 8 development cycle (see https://www.drupal.org/node/2528662).

Note that if that optional `Token::replace(…, …, …, BubbleableMetadata $bubbleable_metadata = NULL)` argument is not passed, it does check whether this token replacement is happening within an active render context (see the `hasRenderContext()` condition in `::replace()`) and if so, it bubbles it automatically, directly onto the render context. Since `Linkformatter::viewElements()` is only ever called during rendering, AFAICT it should actually be working fine already, thanks to that automatic bubbling. We should not be relying on that, but precisely because it was added so late in the D8 development cycle, we had no choice but to resort to such approaches to minimize disruption.
> 3 votes

---
Tags: caching, tokens
---


title: Context module: User ID / role from url

text:
# Question
Title: Context module: User ID / role from url
I'm trying to display some blocks on the user profile pages only when the user owing that user profile has certain roles.

I saw there is a node type condition based. Is there a way to do the same for users?

# Answer
You can use a Context "Condition" plugin, and extend the already core existing "UserRole" condition to do this. Here is example code I have tested on 8.7 w/ Context latest dev version. The module is called `ctx_custom`, and this plugin is defined in the file within the module `/src/Plugin/Condition/UserProfileCondition.php`:

```
<?php

namespace Drupal\ctx_custom\Plugin\Condition;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\user\Plugin\Condition\UserRole;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\User\Entity\User;
use Drupal\Core\Url;

/**
 * Provides a 'User profile path exclusion' condition.
 *
 * @Condition(
 *   id = "user_profile_condition",
 *   label = @Translation("User profile request exclusion"),
 *   context = {
 *     "user_profile_condition" = @ContextDefinition("user_profile_condition", label = @Translation("User profile path exclusion"))
 *   }
 * )
 */
class UserProfileCondition extends UserRole implements ContainerFactoryPluginInterface {

  /**
   * Constructor.
   *
   * @param array $configuration
   * @param $plugin_id
   * @param $plugin_definition
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   *
   * @return static
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    return parent::buildConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function evaluate() {
    $current_path = \Drupal::service('path.current')->getPath();
    $params = Url::fromUserInput($current_path)->getRouteParameters();
    if (isset($params['user'])) {
      $configuration = $this->getConfiguration();
      $user = User::load($params['user']);
      foreach ($configuration['roles'] as $role_id) {
        if ($user->hasRole($role_id)) {
          return TRUE;
        }
      }
    }
  }

}

```

Once you've added this plugin definition and enabled the module, you should be able to add this Via `context_ui` as a Condition, and then whatever reaction you want, e.g. showing blocks or any other Context Reaction that is desired.
> 2 votes

# Answer
Since the situation is not very clear as to what block you're placing and how, here are some general suggestions.

If you're using views to display the blocks on the user profile page, you can do the following:

* Add a role condition to the view so that it will only have contents for the correct set of roles
* Enable the option that says *Hide block when empty*
* The block will be empty for all but the right roles; when the block is empty, the block will be hidden

In general, you should be able to implement `hook_block_access()` and hide the block based on your requirements.

### Note

To hide/show a block based on the role of the visiting user, you can simply use the *Roles* condition provided by Drupal Core. But you're case is different because you're trying to hide/show a block based on the user whose profile is being visited.
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: How can I update existing config from a custom module's config/install yamls?
I added some config yml files to my module's config/install directory so that it is installed directly when installing my module, it works well only if there isn't a config file with the same name installed already and only if it's the first install. So my question is there a way to update the config files already installed with my module's config file, and delete them when uninstalling the module ?

# Answer
A module install should not update config. If you want to update existing config, your module should implement `hook_update_N()` (see docs) instead.

However, you could add a `dependencies: enforced` section to your YML config files. This will remove your existing config on module uninstall, and install the newest config on module reinstall. This way you can "emulate" a simple update mechanism for your own, private custom module. See doc for enforced config dependencies
> 4 votes

# Answer
You can update custom config with a settings form you build. In a custom module *custom\_mailing* add a file called *custom\_mailing.routing.yml* add the following route:

```
custom_mailing.route_admin_settings:
  path: '/admin/config/mailing'
  defaults:
    _title: 'Custom mailing'
    _form: '\Drupal\custom_mailing\Form\AdminSettingsForm'
  requirements:
    _permission: 'administer custom_mailing settings'

```

Now I want a boolean value to be editable. I create a file in a map `config/install` called *custom\_mailings.settings.yml* with the following content:

```
mailsettings:
  enabled: 0

```

In a module called *custom\_mailing*. Inside `src/Form` add file called `AdminSettingsForm.php`.

```
<?php

namespace Drupal\custom_mailing\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class AdminSettingsForm.
 *
 * @package Drupal\custom_mailing\Form
 */
class AdminSettingsForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'custom_mailing_admin_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'custom_mailing.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('custom_mailing.settings');

    $form['mailsettings'] = [
      '#tree' => TRUE,
      '#type' => 'fieldset',
      '#title' => $this->t('Email settings'),
    ];

    $form['mailsettings']['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable sending of e-mails.'),
      '#default_value' => $config->get('mailsettings.enabled'),
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('custom_mailing.settings');
    $config->set('mailsettings', $form_state->getValue('mailsettings'));
    $config->save();
    parent::submitForm($form, $form_state);
  }

}

```
> 1 votes

---
Tags: 8, installation, configuration
---


# Question
Title: Fet the fields from a Paragraph without duplicate records
I have a content type (*Testimonials*) with a title field and a field configured as a Paragraph. I'm trying to create a view showing all the nodes of this content type.

In the *Add field* section of the view creation page, I can only select the title field. I cannot select the fields that are part of the paragraph.

How can I show them in the view?

I tried with *Add relationship* (paragraph referenced from field\_dl\_testimonial\_components). It works but I get duplicate records in my view (1 record per paragraph).

These are the paragraphs visible in the node edit form.

>

# Answer
> 4 votes
When working with views and entity references, which is what paragraph fields are essentially, it is preferred (in my opinion) to use rendered entities instead of relationships because of the exact issue of duplication.

Rendered entities lets you add/remove fields per view mode of the entity in a separate form.

First you must add the field of the paragraph (the one you placed on the node) to the view, choose 'Rendered Entity' and select the view mode you want (the choice of view mode depends on if you use it in other places and wouldn't want to affect appearance in these other places, or the opposite if you want to reuse appearances):

Then go to the paragraph management page, manage displays, and select your view mode (you can add additional view modes at the bottom)

From here you can configure the appearance of the paragraph like you would a content type, such as adding/removing fields.

The end result will have a view with your node titles and the paragraphs with the fields you configured in the paragraph's view mode.

---

## Edit

In the case that a single paragraph type is needed from the field, then relationship would be appropriate here, you just need to add a filter. Add 'Type' filter and choose your paragraph type.

# Answer
> 0 votes
Try this filter:

Pardon my french, it means "is the last revision", check and apply.

---
Tags: views, 8, paragraphs
---


# Question
Title: Is there an alternative to rowCount in a query?
In Drupal 8 we can not use the `rowCount` property anymore in case of a `select` statement. Is there an elegant alternative?

I can use a foreach, but when converting from Drupal 7 I would like to replace the `result->rowCount()` more elegantly.

# Answer
> 7 votes
According to the Drupal API, "in D8 rowCount() is the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed or throws \Drupal\Core\Database\RowCountException if the last executed statement was SELECT."

If you need to select count of rows you can use $query-\>addExpression('COUNT(\*)');

```
   $query = \Drupal::database()->select('table', 't');
   $query->addExpression('COUNT(*)');
   $count = $query->execute()->fetchField();

```

# Answer
> 4 votes
You can try this:

```
$query = db_select('node', 'n')->fields('n', ['nid'])->execute();
$query->allowRowCount = TRUE;
$count = $query->rowCount();

```

Or:

```
$query = db_query('Select * from node');
$query->allowRowCount = TRUE;
$count = $query->rowCount();

```

**Note:** `db_select()` and `db_query()` are marked as deprecated, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call `select()` or `query()` on it.

# Answer
> 3 votes
Setting the `allowRowCount` property to TRUE is not a good way to solve this issue.

A better way to do this is to use the built in `countQuery`:

```
$query = db_select('node', 'n')->fields('n', ['nid']);
$num_rows = $query->countQuery()->execute()->fetchField();

```

# Answer
> 0 votes
`rowCount()` is supported for DELETE, INSERT, or UPDATE statements performed with structured query builders only, since they would not be portable across database engines otherwise

# Answer
> 0 votes
This is how I did it:

```
$database = \Drupal::database();
$query = $database->select('node__field_node_url', 'nnu');
$query->addField('nnu', 'entity_id');
$query->condition('nnu.field_node_url_uri', "entity:node/" . $article->entity_id);
$results = $query->execute()->fetchAll();
$count = count($results);

```

---
Tags: database, 8
---


# Question
Title: Pay order only after it been placed and validated
I need to create a following workflow for the store checkout:

* The user adds a product(s) to a cart.
* The user goes to checkout.
* During checkout, the user can register or authenticate on site. This is required and there is not possible to checkout as a guest.
* Then it goes to the pane with contact information and payment information (? not sure do I need it at this step).
* Then the user sees the last step of checkout — review.
* Then the order is placed.

What I need is to send this order to validation by the store manager to ensure the product can be crafted or already exists.

I thought about `CheckoutFlow` plugin at first, but this does not exactly solve the problem. If I set order state in `onStepChange()` differ from 'place' the order is messed. There is no order ID on complete step and order as well listed in cart.

I also thought about special `CheckoutPane` that blocks further checkout before the manager is change order status. But this also not looks like a good idea, and limit order numbers to the single.

The obvious solution here is let the user finish checkout as soon as possible, then he got the message that order is only set to validate now. And only after additional manual actions from the store manager, there will be possible to pay for the order (it can took days, so there will be additional emails).

I think I will use custom **.workflows.yml** for further order processing. When the manager is set status "validated" next to it will be a "payment" state. During this state, I want to show payment form on the user order page (entity.commerce\_order.user\_view) or maybe better create a special route with `order_id` and generate form there (in this case it also will be possible to send this link in the notification email).

Also, I will add EventListener for `commerce_order.order.paid` to change state from "payment" to "fulfillment".

Maybe there is a better solution and I don't see it? Did I choose the right direction to solve the issue? Are there any drawbacks to manage payments manually or behaviors I need to take into account?

**UPD**

I didn't mention in the original post but it seems to be very important in that case - the order can be edited after or during validation in some cases, so total amount will change and as I understand, previously authenticated payment with gateway will be invalid.

# Answer
> 1 votes
The standard approach here is to use the payment information to create an authorization for as much as you will need assuming the order is to be placed. If it's for $100 of custom merchandise, you authorize a $100 charge on the customer's credit card and then capture it after manual review. This is very typical and in many places a requirement - the idea being you can only authorize payment during checkout and capture it once the order has been shipped.

How the authorization + prior authorization capture flow works will depend on your payment gateway and the methods of payment you're accepting, but most should support this. (I don't have direct experience with Russian payment gateways if you're developing this for a Russian merchant, though.)

In your case, you might just include a message on the checkout form that the customer will see the payment authorization but will not have funds debited from their account until the order has been manually approved by an administrator. There is no automation that I'm aware of in Commerce 2.x core for capturing prior authorizations on specific state transitions, but that's something you should be able to include in your site's customizations module. Again, the exact process there will be very dependent on your payment gateway's API.

---
Tags: commerce
---


title: How to migrate text format

text:
# Question
Title: How to migrate text format
I'm figuring out how migrating works. When trying to migrate one of my nodes from a Drupal 7 site to Drupal 8 site I can't figure out how to set the Text Format of a field. I found this solution below, when looking for an answer, but this doesn't work.

```
field_name:
      plugin: get
      source: field_name
      process:
        value: value
        format:
          plugin: default_value
          default_value: "basic_html"

```

I also tried something like

```
field_name:
          plugin: get
          source: field_name
field_name/format:
          plugin: default_value
          default_value: "basic_html"

```

Or

```
field_name/value:
          plugin: get
          source: field_name
field_name/format:
          plugin: default_value
          default_value: "basic_html"

```

But non of these work. What am I doing wrong?

# Answer
Have you tried removing the quotes?

```
field_reference:
-
  plugin: sub_process
  source: field_reference
  process:
    value: value
    format:
      plugin: default_value
      default_value: basic_html

```
> 8 votes

# Answer
Although it is more elegant to use a `sub_process` as @dibs proposed, you can also use a `get` process plugin

```
field_name/value:
  - plugin: get
    source: field_name/0/value
field_name/format:
  - plugin: default_value
    default_value: basic_html

```
> 4 votes

---
Tags: 8, migrations
---