# Question
Title: Getting "Call to a member function getName() on null" in custom breadcrumb
I'm trying to customize the breadcrumb of drupal 8 to get something like this:

Home \> category \>article-title.

I wrote this and I wrote the code below.

```
namespace Drupal\module_demo\Breadcrumb;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Link;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\taxonomy\Entity\Term;

class ArticleBreadcrumbBuilder implements BreadcrumbBuilderInterface {

    public function applies(RouteMatchInterface $route_match) {
        $parameters = $route_match->getParameters()->all();
        if(isset($parameters['node'])) {
            return $parameters['node']->getType() === 'article';
        }

    }

    public function build(RouteMatchInterface $route_match) {

        $breadcrumb = new Breadcrumb();

        $term = $route_match->getParameter('taxonomy_term');

        $breadcrumb->addCacheContexts(["url"]);

        $breadcrumb->addLink(Link::createFromRoute(t('Home'), '<front>'));

        $breadcrumb->addLink(Link::createFromRoute(t('Articles'), '<none>'));

        $breadcrumb->addLink(Link::createFromRoute($term->getName(), 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));

        $request = \Drupal::request();
        $route_match = \Drupal::routeMatch();
        $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
        if (!empty($page_title)) {
            $breadcrumb->addLink(Link::createFromRoute($page_title, '<none>'));
        }

        return $breadcrumb;
    }
}

```

but I have the error below.

> The website encountered an unexpected error. Please try again later. Error: Call to a member function getName() on null in Drupal\module\_demo\Breadcrumb\ArticleBreadcrumbBuilder-\>build() (line 34 of modules/custom/module\_demo/src/Breadcrumb/ArticleBreadcrumbBuilder.php).

Apparently the problem is with `getName()` and `id()`.

Can someone tell me where the mistake is?

# Answer
> 3 votes
You can also use `hook_system_breadcrumb_alter` to achieve this:
Try this:

```
/**
 * Implements hook_system_breadcrumb_alter().
 */
function MyModule_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  $node = \Drupal::request()->attributes->get('node');
  if ($node && $node instanceof Drupal\node\Entity\Node) {
    if ($node->bundle() == 'article') {
      // Add Articles item.
      $breadcrumb->addLink(Link::createFromRoute(t('Articles'), '<none>'));
      // Add category term item to breadcrumb.
      // Change here the field_tags with your taxonomy you want to add to breadcrumb.
      $term_id = $node->field_tags->getValue()[0]['target_id'];
      $term = Term::load($term_id);
      $breadcrumb->addLink(Link::createFromRoute($term->getName(), 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));
      // Add title as breadcrumb item.
      $request = \Drupal::request();
      $route_match = \Drupal::routeMatch();
      $page_title = \Drupal::service('title_resolver')
        ->getTitle($request, $route_match->getRouteObject());
      if (!empty($page_title)) {
        $breadcrumb->addLink(Link::createFromRoute($page_title, '<none>'));
      }
    }
  }
}

```

**Update:** To fix the error.
Update the `applies` method to apply your breadcrumb only on articles as it mentioned in @Jdrupal answer:

```
  public function applies(RouteMatchInterface $route_match) {
    $parameters = $route_match->getParameters()->all();
    if (isset($parameters['node'])) {
      return $parameters['node']->getType() === 'article';
    }
    if (isset($parameters['term'])) {
      return TRUE;
    }
  }

```

The error comes from the line:

```
$term = $route_match->getParameter('taxonomy_term');

```

`$term` equal `NULL` its normal, you are in node page so the `taxonomy_term` param always null, so try to get your term from the node object something like:

```
 $node = \Drupal::request()->attributes->get('node');
 // Change the field_tags with your filed.
 $term_id = $node->field_tags->getValue()[0]['target_id'];
 $term = Term::load($term_id);

```

# Answer
> 2 votes
The problem is that you try to get the `term` from the route, but in your `applies()` method you have restricted the breadcrumb to apply only on pages where you can get the node from the route.

If you want your breadcrumb to apply for taxonomy term pages as well your `applies()` function must look like this:

```
public function applies(RouteMatchInterface $route_match) {
  $parameters = $route_match->getParameters()->all();
  if (isset($parameters['node'])) {
    return $parameters['node']->getType() === 'article';
  }
  if (isset($parameters['term'])) {
    return TRUE;
  }
}

```

Otherwise you have to remove `$term->getName()` from your `build()` method.

**UPDATE:** Since you mention you only want to display the breadcrumb on article pages, you must fetch the term from the node.

Replace this line:

```
$term = $route_match->getParameter('taxonomy_term');

```

With:

```
$term = $route_match->getParameter('node')->field_term->first()->entity;

```

Then you can call `$term->label()`.

# Answer
> 0 votes
Your applies() checks for a node-route while your build() wants a taxonomy-route. That's why $term is null here. You have to fetch your $term object from the corresponding node field.

---
Tags: 8, taxonomy-terms, breadcrumbs
---


# Question
Title: How to change view's field (Custom-Text field specifically) value based on other field value using hook_view_pre_render?
I have created a taxonomy-term view. I have added two fields in a view: term-id and custom-text field.

I want to check if term-id has children and depending upon the result, I want to set markup inside custom-text field.

I am able to get term-id in **hook\_views\_pre\_render** with following code, but I am not able to set the value of custom-text field

```
function mymodule_views_pre_render(\Drupal\views\ViewExecutable $view) {
 if ($view->id() == 'test_view' && $view->current_display == 'block_2') {
    foreach($view->result as $value){
        $tid = $value->_entity->get('tid')->value;
        kint($tid);

        //trying to set value for custom text field, with foll. line of code
        //'nothing' is the field-name you get for any custom-text field
        $value->_entity->set('nothing', '<h1>This is my custom mark-up</h1>');
    }
 }
}

```

I referred the code from these following 2 sources, but they are not dealing with custom-text field:

1. How to change views field value using a hook
2. https://api.drupal.org/comment/62573#comment-62573

Or should I use template\_preprocess\_views\_view\_fields(), if yes then how can I get term-id value to check if it has children terms.

Any help will be appreciated.

# Answer
You can't set a value for "nothing" aka "Global: Custom text" in `hook_views_pre_render()` because `_entity` is the entity object. The entity (Taxonomy Term in your case, and Node in my test case) does not contain this field.

Therefore, you need to use template\_preprocess\_views\_view\_field

```
function THENAME_preprocess_views_view_field(&$vars) {
  if(isset($vars['view']) && ($vars['view']->id() == 'test_view') && ($vars['view']->current_display == 'block_2')) {
    if (isset($vars['view']->field) && (count($vars['view']->field) > 0)) {
      if ($vars['field']->field == 'nothing') {
        $tid = $vars['row']->_entity->get('tid')->value; // get tid
        if ($vars['field']->field == 'nothing') {
          $vars['output'] = [
            '#markup' => "<h1>This is my custom mark-up with term id: $tid</h1>",
          ];
        }
      }
    }
  }
}

```
> 2 votes

# Answer
I referred the code from this source https://drupal.stackexchange.com/a/262718/97205 which was also helpful and figured out following solution:

```
function THEMENAME_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];

  if ($view->id() == 'test_view' && $view->current_display == 'block_2') {
    foreach ($view->field as $id => $field) {

      if ($field->field == 'nothing') {
        $tid = $variables['row']->tid; //get tid
        $variables['fields']['nothing']->content = "<h1>Custom markup goes here $tid</h1>";
        //kint($tid);
      }
    }
  }
}

```

But solution from @NoSssweat is more appropriate.
> 0 votes

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


title: Get term value from referenced node

text:
# Question
Title: Get term value from referenced node
Drupal 8 Twig I have a content, which have entity reference field `field_field_data_provider_ref`, referencing another content, which itself contains a field field `buisness_property_type` (single taxonomy term)

```
 {{ node.field_field_data_provider_ref.entity.buisness_property_type.value }}

 {{ node.field_field_data_provider_ref.entity.buisness_property_type|views }}

```

doesn't work for me

# Answer
If the referenced field is a taxonomy term, you need to specify what property to show (usually the name). So your solution should be like

```
{{ node.field_field_data_provider_ref.entity.buisness_property_type.name.value }}

```

or, as NoSssweat said, with correct spelling (check your fieldnames)

```
{{ node.field_field_data_provider_ref.entity.business_property_type.name.value }}

```

also, I assume your machine name is field\_business\_property\_type, so its

```
{{ node.field_field_data_provider_ref.entity.field_business_property_type.name.value }}

```

also, your field field\_field\_data\_provider\_ref is named field\_data\_provider\_ref, then it's

```
{{ node.field_data_provider_ref.entity.field_business_property_type.name.value }}

```

Check your field names!
> 0 votes

# Answer
I managed to get target\_id only , there is no .name in array for this field

```
{{ node.field_field_data_provider_ref.entity.field_buisness_property_type.target_id }}

```

Also , this works only with page--node.html.twig , but I need it within region.html.twig ( here it returns nothing)
> 0 votes

---
Tags: theming
---


# Question
Title: Use Color Field Value in Views Field Template File
I have two fields in my view:

field\_background\_colour and field\_heading

The are both being pulled from nodes and displayed in a rotating hero banner. Each node has a different colour and different heading.

The field\_background\_colour is defined by the color field module and therefore can be any colour they select.

I need to add the value of the background colour in hex (e.g. #000000) to the html output of field\_heading.

```
<div style="background:[field_background_colour];">[field_heading]</div>

```

I tried using some html and replacement patterns in the rewrite of the field but it seems that gets stripped out by views. It seems to me that I need to use the field's template file to get what I want.

# Answer
In this use case, I believe inline styles are the way to go. There are methods to write a CSS file in your module or theme, for example, but since users can select, and update at any time, any color code, all situations would be very difficult or messy to manage. Inline styles are not ideal in the grand scope of things, but with multiple users, and multiple hex values reaching the millions, sometimes requirements make our choices for us. And plus, we just want to get it done.

---

Below assumes the view shows nodes, both fields are on the content type, and the title being styled is the `node title`, not the `views title`. This is best achieved setting the view to display *content*, and utilizing template files for your chosen display mode such as `node--content-type--teaser.tpl.php`.

**node--content-type--rotating-hero.tpl.php**:

```
<section>
  <h1
    title="<?php print render($title); ?>"
    alt="<?php print render($title); ?>"
    <?php if (isset($content['field_background_colour'])) : ?>
      style="color: #<?php print $content['field_background_colour']['#items'][0]['value']; ?>;"
    <?php endif; ?>
  >
    <?php print render($title); ?>
  </h1>
</section>

```

Here, each `.views-row` will contain an individual node display, and you can focus your javascript and CSS on those for the slider.

**multiple h1 tags on the same page need to be wrapped in a `<section>` tag, otherwise, use h2 tags*.

**Templates are related to structure and usage. Views templates are for the structure and layout of content aggregation, node templates are the structure of individual entities. Wherever the field (or desired data) resides is the best place to theme template files*.

---

Below assumes you need to style the `views title` itself...

`will need more info about where the color field lives. If user profile, for example, you will need to load the user object to access the field value.`

**MYMODULE.module**:

```
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'view_name') {
    $view->build_info['title'] = "custom title";
  }
}

```

**template.php**:

```
function MYTHEME_views_pre_render(&$variables) {
  if (&$variables['view']->name == 'view_name') {
    &$variables['view']->build_info['title'] = "custom title";
  }
}

```
> 4 votes

# Answer
Aren't you actually just trying to style one of the fields according to the value of the other field?

Inline CSS isn't the best way to go because of a number of reasons, mainly, it can't be easily overriden so it breaks the cascade, and maintenance is a nightmare.

There is a way to style your views rows based on field values: You add a class to your Heading field Style settings that is based on the bg-color field value. Using classes to mark up content and then style the classes with CSS is the way to go.

You need to add the CSS rules applied to the classes to your (sub)theme. Some themes provide the interface to add your custom CSS, if not you can use the CSS Editor or a similar module.

Here are the steps:

1. Position the bg-color field above the Heading field (good if it's Hidden). If you need it visible in some other order then add a second bg-color field just for this purpose and position it above the Heading field
2. Edit the Heading field \> Uncollapse `Style settings` \> **Customize field and label wrapper HTML** (or `Customize field HTML` if you don't need the wrapper) \> **Create a CSS class** and enter the first part of your class (`heading`) (class names can't start with numbers so that's why)
3. Uncollapse `Rewrite results` (don't enable it, you just need to look up the token), uncollapse `Replacement patterns`, copy the bg-color field token and paste it in the above `CSS class` field (you end up with something like `heading-[field_bg_color]`).
4. Save the View and check your HTML output, you will see a class based on the color field on your Heading, something like `class="views-field views-field-title heading-008000"`. The hash sign has been stripped automatically as it can break CSS.
5. Add the CSS to your (sub)theme or the CSS Editor, for all the colors you have in your content:

```
.heading-008000 {
  background-color: #008000;
}

```

With Sass you can use a list to store all your colors and create the rules automatically.

If this is just a way to allow content editors to choose some preset styles try looking into Paragraphs and Bricks (D8).
> 1 votes

# Answer
You can simply use template\_preprocess\_views\_view\_fields to rewrite content of the field, and wrap it inside another div with the markup.

like the following:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function YourTheme_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  foreach ($view->field as $id => $field) {
    if ($id == 'field_background_colour') {
      $content = $vars['fields']['field_heading']->content;
      $background_colour = trim(strip_tags($vars['fields']['field_background_colour']->content));
      $vars['fields']['field_heading']->content = '<div style="background:' . $background_colour . '">' . $content . '</div>';
    }
  }
}

```

Result:
> 1 votes

# Answer
You can use twig file and wrap your div code around {{output}}

```
    <div style="background-color: #{{ view.field.field_color.original_value }}">
    {{ output -}}
    </div>

```

**Twig File**: views-view-field--{page or block machine name}--{field name}.html.twig

**Example**: views-view-field--frontpage--field-color.html.twig

**Note**: You can access any field value from any views-view-field--{field name} by using {{ view.field.{field name}.original\_value }}
> 0 votes

# Answer
It's very simple, i added a working example, no need for template, first add colour\_field:\[field\_background\_colour\], hide from display, then add field:\[field\_heading\], in field settings do choose rewrite results (toggle checkbox), add this in input box:

```
<div class="background:#[field_background_colour]">[field_heading]</div>

```

or

```
<div class="background-color:#[field_background_colour]">[field_heading]</div>

```

\[field\_background\_colour\] field must be before of \[field\_heading\] in your list of fields in view settings.

Supouse that \[field\_background\_colour-value\] is #000000, HTML output will be:

```
<div style="background:#000000">[field_heading-value]</div>

```

or

```
<div style="background-color:#000000">[field_heading-value]</div>

```

please see my WORKING sample settings, HTML output and CSS:

HTML

css
> 0 votes

# Answer
1. Use the views\_html\_tags module to add tag in available HTML tags list.
2. Add nid (Node ID) to view fields, put it on the top and hide it.
3. Add class "node-\[nid\]" to field\_heading.
4. Add field 'field\_background\_color' to view fields and place it between 'nid' and 'field\_heading' fields. Don't hide it.
5. Rewrite it's output to: .node-\[nid\] { background-color: \[field\_background\_color\]; }
> 0 votes

---
Tags: 7, views
---


# Question
Title: Search results are not displaying on top by relevancy
I have to use **"Search API"** module with configured on solr server and indexed. The search results are displaying but "relevancy" content is not on top of the page.

**Example #1:**
Search key word: `course in the page`

**Actual Result:**
1) Test `course`
2) Test content `in` shedule `page`
3) Test `page`
4) `Course in the page`

**Expected Result:**
1) `Course in the page`
2) Test `course`
3) Test content `in` shedule `page`
4) Test `page`

Here I need to display first `4) Course in the page` then display others. I am used views for that search. Views Interface Please post your suggestions!

# Answer
> 0 votes
Sorry I got the answer. Add the sort criteria `relevance`.  It's working fine. Cheers!!

---
Tags: 8, search
---


# Question
Title: Filter nodes by paragraph user reference
Say you have a content type **Exercise** which has a **Related Users** paragraph field. In turn, **Related Users** has a user reference field:

(content type) **exercise** --\> (paragraph) **related\_users** --\> (user) **user**

I want to filter all Exercises with a certain related user:

```
/api/node/exercise?filter[field_related_users.field_user.name]=some_user

```

But it returns empty data: **"data": \[\],**. Same if tried with user id.

I'm sending a request with admin user, so there are no permission issues. Also, I did a similar filtering on a referenced content type (with a user reference) and it does return data.

I couldn't find anything related to this in JSON:API open issues. Does filtering by paragraph reference work differently? Or maybe there are limitations on this?

# Answer
> 0 votes
According to this issue, Unable to filter on columns of entity reference fields. It seems like you need to add `.entity` after the field name to the entity reference fields.

Try to use this URL instead:

```
/api/node/exercise?filter[field_related_users.entity.field_user.entity.name]=some_user

```

Or if `field_related_users` can contain multiple values, you might want to do like this instead:

```
/api/node/exercise?filter[field_related_users.0.entity.field_user.entity.name]=some_user

```

---
Tags: 8, nodes
---


title: Programmatically Update Geofield Data

text:
# Question
Title: Programmatically Update Geofield Data
My setup is:

1. Addressfield on nodes to collect address data
2. Geofield using "Geocode from another field" choosing the addressfield and the Google Geocoder

When I edit/save a node in the UI, the data is geocoded. However, I have thousands of nodes and am trying to write a script to update the geocode info on each node.

I tried loading all the nodes and doing a node\_save() but the geocode hooks didn't fire.

How can I programmatically update the geofield information? Is there a hook I can use?

# Answer
According to README.TXT:

> ## API NOTES
>
> Geofield fields contain nine columns of information about the geographic \> data that is stores. At its heart is the 'wkt' column where it stores the full geometry in the 'Well Known Text' (WKT) format. All other columns are metadata derived from the WKT column. Columns are as follows:
>
> 'geom' Raw value. By default, stored as WKB, loaded as WKT
> 'geo\_type' Type of geometry (point, linestring, polygon etc.)
> 'lat' Centroid (Latitude or Y)
> 'lon' Centroid (Longitude or X)
> 'top' Bounding Box Top (Latitude or Max Y) 'bottom' Bounding Box Bottom (Latitude or Min Y)
> 'left' Bounding Box Left (Longitude or Min X)
> 'right' Bounding Box Right (Longitude or Max X)
> 'geohash' Geohash equivalent of geom column value
>
> When a geofield is saved using the provided widgets, these values are passed through the geofield\_compute\_values function in order to compute dependent values. By default dependent values are computed based on WKT, but this may be overriden to compute values based on other columns. For example, geofield\_compute\_values may be called like so:
>
> geofield\_compute\_values($values, 'latlon');
>
> This will compute the wkt field (and all other fields) based on the lat/lon columns, resulting in a point. As a developer this is important to remember if you modify geofield information using node\_load and node\_save. Make sure to run any modified geofield instances through geofield\_compute\_values in order to make all columns consistent.

This translates to:

```
      $spot->field_coordinates[LANGUAGE_NONE][0] = geofield_compute_values(
          array(
              'lat' => $venue->location->lat,
              'lon' => $venue->location->lng,
      ), GEOFIELD_INPUT_LAT_LON);

```
> 4 votes

# Answer
Using values like this, I was able to update a geofield's data programatically:

# PHP

```
$lat = 42.281646;
$lon = -83.744222;
$geofield = array(
  'geom' => "POINT ($lon $lat)",
  'geo_type' => 'point',
  'lat' => $lat . "000000",
  'lon' => $lon . "000000",
  'left' => $lon . "000000",
  'top' => $lat . "000000",
  'right' => $lon . "000000",
  'bottom' => $lat . "000000"
);
$lang = $node->language;
$node->field_position[$lang][0] = $geofield;

```

# JSON for Services Module

```
{
  "nid":123,
  "field_position":{"und":[
    {"geom":{"lat":"42.2808256","lon":"-83.7430378"}}
  ]}
}

```

In both cases, the widget for the geofield is `Latitude / Longitude`, so results may vary for other widgets, especially with the Services module.
> 2 votes

# Answer
A wild guess: You may run your node through the `node-edit-form` process to get the geofield-magic fired.

Have a look at drupal\_form\_submit(), observe the `$form_state['values']` from an ordinary, manual submission of your node type's "add content" form and rebuild them programmatically to send it in the `drupal_form_submit()` function.

I wonder if that would work...

On the other hand, you could just inspect the structure of your geofield's value and rebuild that programmatically leveraging the `geocoder()` function of the geocoder module's API.
> 1 votes

# Answer
You can use the method described in https://www.drupal.org/node/905814#comment-4931016.

1. Take a database backup
2. Make a view of your content. Add a filter to select the content where the geofield latitude is empty.
3. Add the Views Bulk Operations module, add a bulk operations field and choose as action "execute arbitrary php".

```
$test = node_load($entity->nid);
module_load_include('inc', 'node', 'node.pages');
$test_state['values']['op'] = t('Save');
drupal_form_submit('NODENAME_node_form', $test_state, $test);

```

This approach works perfectly except that Date fields that are using the date popup display become empty, so be careful if you have date fields.

Also notice that the Google geocoder has a 24h limit of 2500 addresses to geocode.
> 0 votes

# Answer
There's a Drupal 7 module that does this exact thing for you using the cron. You can set the number of nodes to process per cron run, and select what content types to have it fire against.

Check it out: https://www.wutime.com/downloads/automatic-geofield-update-to-render-gmaps/
> 0 votes

---
Tags: entities, location
---


# Question
Title: How can I redirect a user after login to the current page?
I have a Drupal 8 site. And I have approximately 5 pages in a site.

For example if a user hits login from the contact-us page the user should not redirect anywhere, they should stay on same page. How can I accomplish this?

# Answer
> 3 votes
The way to solve this can be done by adding the `destination` parameter to the login link.

Whenever the user is navigating a page, you update the destination based on the current page.

This can be done by implementing the hook\_link\_alter as the following:

```
/**
 * Implements hook_link_alter().
 */
function custom_link_alter(&$variables) {
  $routes = [
    'user.login',
    'user.logout',
  ];
  /* @var Drupal\Core\Url $url */
  $url = $variables['url'];

  if (!$url->isExternal() && $url->isRouted() && in_array($url->getRouteName(), $routes)) {
    // Get current path.
    $current = \Drupal::service('path.current')->getPath();
    $variables['options']['query']['destination'] = $current;
  }
}

```

This works fine for login and also for logout links. So when user login/logout through menu link he will be redirected to the previous page.

One problem might face you with that is cache, Drupal will start caching the destination value and won't be updated when you move between pages.

You can solve this problem by implementing `hook_preprocess_menu` and add destination as cache contexts.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function custom_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'account') {
    $variables['#cache']['contexts'][] = 'url.query_args:destination';
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, \Drupal::service('path.current')->getPath());
  }

}

```

---
Tags: users
---


# Question
Title: Difference in form when first loaded and submitted
When debugging commerce checkout panes, which are basically forms I see that form is loaded on page load(obviously). It is again loaded when I click submit and debugger goes through same lines of form, thing is I am not sure which marker to use to differentiate code when this occurs, I would need to do something different in this case, but only thing I see different is superglobals at this point, which I could use, but somehow I would be more comfortable using drupal local vars?

# Answer
> 2 votes
If all you want to know is whether the form is being loaded before or after a submit while debugging, then look at the array in `$form_state['input']`. If it is an empty array, then it is being loaded for the first time (before a submit). If it has elements then the form is being loaded after a submit.

If you want to see if field values have been changed in a submit, then how you do it depends on where or why you need to check. If debugging, then compare `$form_state['input'][FIELD]` with `$form[FIELD]['#default_value']`

You can also add your own functions as submit or validate handlers to the form. After the form is submitted, your function will be called, and you can compare the changed values in `$form_state['values'][FIELD]` (note: use `values` here, not `input`) to the original values in `$form[FIELD]['#default_value']`.

You add your submit/validate handler by implementing `hook_form_FORMID_alter()`for the form you are debugging, and adding the names of your functions to the end of the `$form['#submit']` and `$form['#validate']` arrays respectively. Remember to clear caches.

```
function my_module_form_other_module_form_alter(&$form, &$form_state) {
  $form['#submit'][] = 'my_module_custom_submit';
  $form['#validate'][] = 'my_module_custom_validate';
}

function my_module_custom_submit($form, &$form_state) {
  $original_field_x_value = $form['field_x']['#default_value'];
  $submitted_field_x_value = $form_state['values']['field_x'];
  if ($submitted_field_x_value != $original_field_x_value) {
    do_something();
  }
}

function my_module_custom_validate($form, &$form_state) {
  do_something();
}

```

---
Tags: 7
---


# Question
Title: How to add a referenced taxonomy term name to the node title in page-title.html.twig
Using a term reference field, I am adding the manufacturer's name to the front of our node titles in views for styling and line breaks between the manufacturer field and the title which is really nice. For the node display titles, I am currently using a block view for the manufacturer's name, and placing it above the page title block in the block layout. This stacks the Manufacturers name above the Node title which i **don't** really prefer:

*Manufacturer*
**Some Node Title**

I would like to add the `field_manufacturer` field to the node display title as a prefix so that it is inline and not stacked like my example above, and I need to add a class to it so that I can target and style it. I am not sure which twig file is responsible for rendering the title, so I would really appreciate help marking this up properly.

Thanks!

# Answer
Posting this answer to help those trying to accomplish the same thing. I was told the code above had security vulnerabilities (which has since been removed see comments below). On the Drupal Slack channel, someone pointed out the following concern with runwithscissors' answer:

> "This code is potentially dangerous:`$variables['title'] = \Drupal\Core\Render\Markup::create($new_title);` A user could set `<script>alert("foo")</script>` as the Node or Term title and potentially execute code on the site. Typically you don’t want to ever create Markup objects manually. For what you’re doing, I’d suggest setting `$term_name` to a new key in `$variables`, then forming your combined title in the Twig template like `{{ term_name}} {{ title }}`"

So what i ended up doing was adding this `template_preprocess_page_title` to my MY\_SITE.theme file.

**(Note:** `field_manufacturer` is the specific field for my use case, so you would need to change all instances of that to your taxonomy reference field name.)

```
/* Add field_manufacturer to all node titles with field_manufacturer and not empty */
function template_preprocess_page_title(&$variables) {
   $node = \Drupal::request()->attributes->get('node');
   if ($node && $node->hasField('field_manufacturer') && !$node->field_manufacturer->isEmpty()) {
     $term = \Drupal\taxonomy\Entity\Term::load($node->get('field_manufacturer')->target_id);
     $term_name = $term->getName();
     $variables['term_name'] = $term->getName();
   }
 }

```

This applies to all nodes with the `field_manufacturer`, but also checks that the term field is NOT empty with `&& !$node->field_manufacturer->isEmpty())`. **This was critical** as the reference field was not required, so nodes that had the field but didn't have a value crashed the site with `Error: Call to a member function getName() on null in template_preprocess_page_title()`

Then I copied and overwrote the `page-title.html.twig` file from my bootstrap base theme which originally renders the title like this:

```
{% if title %}
  <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
{% endif %}

```

And changed the H1 title line to this:

```
{% if title %}
  <h1{{ title_attributes.addClass('page-header') }}>
    {% if term_name %}
      <span class="MY-DESIRED-CLASS-NAME">{{ term_name }}</span>
    {% endif %}
  {{ title }}</h1>
{% endif %}

```

This adds a `MY-DESIRED-CLASS-NAME` span class to the `term_name`. Also by putting it within `{% if term_name %}`/`{% endif %}` statement, it prevents that class from being rendered in the html where there is no `term_name` present.

Hope this helps someone!
> 2 votes

# Answer
Would you want to use Automatic Entity Label to actually change the title?
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to create a select drop down that opens a URL?
I have a select drop down. When the user selects a value from the drop down, the user will then click on a button and based on what the user has selected it will open a url in a new tab. While this is quite simple in JavaScript I am struggling how to figure this out in drupal.

So far I have created a custom module which has a select form and the submit button. From here I am stuck as to how to write if user has selected value a open google.com etc. any suggestions or pointers would be greatly appreciated.

# Answer
> 4 votes
You can do this by using `$form_state->setResponse()` together with `TrustedRedirectResponse`.

Create the dropdown, like this:

```
$form['select'] = [
  '#type' = 'select',
  '#title' => t('Select'),
  '#options' = [
    'https://google.com' => t('Google'),
    // More links...
  ]
];

```

To open the link in a new tab, you can add this to your form:

```
$form['#attributes' => ['target' => '_blank']];

```

Then create the submit handler, like this:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setResponse(new TrustedRedirectResponse($form_state->getValue('select'), 302));
  // You can change the response code from 302 to whatever you need
}

```

---
Tags: 8, forms, javascript
---


# Question
Title: How to programmatically render a webform to display specific Elements
I have tried this way but not able to hide "confirmation\_id" element.

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

$my_webform_machinename = 'request_form';
$my_form = \Drupal\webform\Entity\Webform::load($my_webform_machinename);
$my_form['elements']['flexbox_layout']['confirmation_id']['#access'] = FALSE;

return [
    'form' => [
    '#type' => 'webform',
    '#webform' => $my_form,
    '#sid' => $sid,
    ],

];

}

```

# Answer
To hide custom field in webfrom you need to use the `hook_form_FORM_ID_alter`.

```
function CUSTOM_MODULE_form_webform_submission_request_form_add_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $elements = &Drupal\webform\Utility\WebformFormHelper::flattenElements($form['elements']);

  $elements['flexbox_layout']['confirmation_id']['#access'] = FALSE;
}

```

To get specific form elements you can use `getSubmissionForm()` method:

```
public function buildForm(array $form, FormStateInterface $form_state, $sid = NULL) {
  $my_webform_machinename = 'request_form';
  $my_form = \Drupal\webform\Entity\Webform::load($my_webform_machinename);

  $webform = $my_form->getSubmissionForm();

  $form['my_field'] = $webform['elements']['flexbox_layout']['confirmation_id'];

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

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Update the from name in workbench email template
I'm trying to update the "from" name in my workbench email template. I created a custom module and added the following hook ('hook\_mail\_alter') but it's still not updating the from name for my email template. Does the below hook look right?

```
function my_module_mail_alter(&$message) {
  if ($message['id'] == 'needs_review') {
  $message['from'] = 'Full Name <email@address.com>';
  }
 }

```

https://api.drupal.org/api/drupal/core%21core.api.php/function/hook\_mail\_alter/8.7.x

# Answer
> 1 votes
I'm pretty sure that `$message['from']` shall be an email address.

Try to set the `From` header instead, like this:

```
$message['headers']['From'] = 'Full Name <email@address.com>';

```

---
Tags: 8, workbench
---


# Question
Title: Can't update radio button fields after ajax callback
I'm having troubles with a FORM in Drupal 8, the idea is:

Chose a radio value from radio-estaciones to recharge radio-contaminantes, but, after the callback, the result I see is empty, but in replace command I use, I see it correcly

This is the code of buildForm

```
public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state){

    $arrRadioContaminantes = array();
    $arrRadioContaminantes["0"] = t("ALL");

    //My function to access DB
    $result = \Drupal\map_data\Controller\Contaminante::list();
    foreach ($result as $it){
        $arrRadioContaminantes[$it["id_contaminante"]] = t($it["description"]);
    }

    $form['radio_contaminantes'] = array(
        '#type' => 'radios',
        '#options' => $arrRadioContaminantes,
        '#ajax' => [
            'callback' => '::seleccionContaminantes',
            'disable-refocus' => true,
            'event' => 'change',
            'wrapper' => 'radios-estaciones',
            'method' => 'replace'
        ]
    );

    $form['radio_estaciones'] = array(
        '#type' => 'radios',
        '#id' => 'radios-estaciones',
        '#options' => ['-1'=>t("SELECT CONTAMINANTE FIRST")]
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
        '#button_type' => 'primary',
    );

    $form_state->setCached(false);
    $form_state->setRebuild(true);

    return $form;
}

```

This is callback function:

```
public function seleccionContaminantes(array &$form, FormStateInterface $form_state){
    if($form_state->getValue("radio_contaminantes") != 0){
        $form['radio_estaciones']["0"] = t("All");
    }

    //My Database function
    $resultado = \Drupal\montar_mapa\Controller\Estacion::list($form_state->getValue("radio_contaminantes"));
    foreach ($resultado as $it){
        $form['radio_estaciones'][$it["id"]] = t($it["name"]);
    }

    $ajaxResp = new AjaxResponse();
    $ajaxResp->addCommand(new \Drupal\Core\Ajax\ReplaceCommand('radios-estaciones', \Drupal::service('renderer')->render($form['radio_estaciones'])));

    return $ajaxResp;
}

```

I try returning $form\['radio\_estaciones'\] with same results, and try DataCommand pasing new values, same result... I need help

# Answer
> 0 votes
After change type to 'select' works fine.

Drupal have this bug active

https://www.drupal.org/project/drupal/issues/2758631

Same situation with checkboxes

---
Tags: 8, ajax
---


title: Preprocess a twig template file

text:
# Question
Title: Preprocess a twig template file
I don't fully understand how preprocessing works

I have a twig template `/themes/custom/client/templates/content/node--myfile.html.twig` that I want to alter

I want to show/hide a part of that template depending on a field `display` with the machine name `field_display` stored in the matching content type called `Project` and with the machine name `project_machine_name`.

So I well understand I have to use hooks in order to do this, but I don't understand how I am supposed to name the hook functionnality neither how I'm supposed to access the data stored from the content type into the hook to alter the template view.

I know the hooks goes into the `.module` file. Actually I already have some of them, but I don't understand them properly. The only things I know for sure is that the function name must start by the module name

```
function my_module_SOMETHING_SOMETHINGELSE() {

}

```

So the issue is: how to name the hook function in order to alter the template ? I guess I understand the name is some kind of standard structure which will tell drupal if the function needs to be called before a specific action.

How to retrieve data stored from the `display` field of the content-types `Project`?

Thanks for your assistance.

# Answer
> 2 votes
Preprocess hooks are named `MY_MODULE_preprocess_TEMPLATE_NAME`, in your case:

```
function my_module_preprocess_node__myfile(&$variables) {}

```

Notice how I replace the template's dashes with underscores in the function name.

Now you can get the `display` variable from `$variables['node']->field_display->value`.

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


# Question
Title: How to set node creation limit by user type in Drupal
I'm trying to set the limit on authenticated user for creating particular type of content(adding user limit on content type).

Node limit module has same functionality in Drupal 7 but i'm looking for Drupal 8.

# Answer
> 1 votes
Another new module for Drupal 8: https://www.drupal.org/project/entity\_limit

Some details about it, from its project page:

> Entity Limit allows administrators to restrict the creation of the number of entities that users may create. Basically, this module provides options to define a creation limit based on user and role.

# Answer
> 0 votes
entity limit module should have what you need.

> Currently, entity\_limit offers the following functionalities
>
> 1. Per User entity limit settings.
> 2. Per Role entity limit settings.
> 3. Priority based entity limit configurations.

But you can also try node limit has a Drupal 8 dev version .

---
Tags: 8, nodes
---


# Question
Title: Navigate to page with content displays page not found error
I have a URL (/url1) that I navigate to that is showing content because of the Context module.

The Context module has a condition that when the user navigates to /url1, some view blocks are rendered on the page. However, it is also rendering a "Page not found" error at the bottom of the page.

I can't figure out how to remove that message and get it to work properly. It even has the title "Page not found" on the tab with the page. The blocks render just fine in the way I want them.

# Answer
You need to have some sort of content assigned to the URL `url1`. The simplest way would be to create a new `Basic page` node and set its `URL alias` field to `url1`.

By the way, what you are seeing now is the *"page that is displayed when no other content matches the requested document"* (`Administration >> Configuration >> System >> Site Information >> Default 404 (not found) page`). You can have a specific page assigned as your `Page not found` page, or Drupal will build the content for it on the fly, and show it using the most appropriate template in your theme (most likely `page.tpl.php`).
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: I don't find something similar to drush field-create in Drush 9
I'm looking for a similar command `drush field-create` with Drush 9, I only find `drush generate field` but when I execut it I don't get nothing, also if I try `drush generate field --help` I get:

```
Too many arguments, expected arguments "command" "command_name".

```

There is any way to get `drush field-create` running with Drush 9?

Thanks.

# Answer
> 1 votes
`drush field-create` has not been ported to Drush 9.

You can install Drupal console and use `drupal generate:plugin:field` instead.

---
Tags: 8, drush
---


# Question
Title: Different front page for logged in users
I want to show different front pages for different roles: Anonymous users should see www.domain.com\front, logged-in users should see www.domain.com\dashboard.

There are two options I found so far:

1. **Using the Front Page module**
I tried this but it doesn't work. I add the new front page locations to the right role. But the redirect doesn't happen.
2. **Making a custom module**
Unfortunately (because of my limited knowledge on routes and controllers) the article I found doesn't give me enough information on how to make this module.

Can someone help me figuring out how to create a module based on the article? Point me in the right direction to learn how these routes and controllers work.

Or help me with another set up for a module that does this?

---

The answer of Ziftman is great. I changed it to my needs. I changed the if statement to check if the current page is the frontpage and not the path `/front`

Because I found out that this `\Drupal::service('path.matcher')->isFrontPage()` does not always work. I used this to figure out if I'm on the frontpage:

```
$current_path = \Drupal::service('path.current')->getPath();
$front_uri = \Drupal::config('system.site')->get('page.front');
$front_alias = \Drupal::service('path.alias_manager')->getAliasByPath($front_uri);
$current_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
$isFrontPage = \Drupal::service('path.matcher')->isFrontPage() || $front_alias === $current_alias;

```

Then I not only wanted to see if the user is logged in but also specify it by role. So I used this to see if the current user has a certain role:

```
$hasRole1 = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())->hasRole('role_name_1');
$hasRole2 = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())->hasRole('role_name_2');

```

These combined make this if statement:

```
if($ifFrontPage && $hasRole1){
...
}
if($ifFrontPage && $hasRole2){
...
}

```

And finally I changed the local path to a domain change, because I needed it to check a role, and if the current user has a role. Then go to the dashboard on a different domain:

So this:

```
$path =  \Drupal::service('path.alias_manager')->getAliasByPath('/dashboard');
$event->setResponse(new RedirectResponse($path));

```

Became this is replaced by:

```
$domain_url =  'https://domain1.nl/dashboard';
$response = new TrustedRedirectResponse($domain_url);
$event->setResponse($response);

```

The complete if statements ended up like this:

```
if($ifFrontPage && $hasRole1){
    $domain_url =  'https://domain1.nl/dashboard';
    $response = new TrustedRedirectResponse($domain_url);
    $event->setResponse($response);
}
if($ifFrontPage && $hasRole2){
    $domain_url =  'https://domain2.nl/dashboard';
    $response = new TrustedRedirectResponse($domain_url);
    $event->setResponse($response);
}

```

# Answer
> 6 votes
You need to create a custom event subscriber.

With that event you are checking if the path is front and the user is logged in, then you perform the redirect.

Assuming your custom module name is '**custom**':

1- Register the even in the services file **custom/custom.services.yml**

```
services:
  custom.event_subscriber:
    class: Drupal\custom\EventSubscriber\MyCustomModuleSubscriber
    tags:
      - {name: event_subscriber}

```

2- Create the event subscriber at **custom/src/EventSubscriberMyCustomModuleSubscriber.php**:

```
<?php

namespace Drupal\custom\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MyCustomModuleSubscriber implements EventSubscriberInterface {

/**
* {@inheritdoc}
*/
public function checkFrontRedirection(GetResponseEvent $event) {
  if (\Drupal::service('path.matcher')->matchPath('/front') && !\Drupal::currentUser()->isAnonymous()) {
    $path =  \Drupal::service('path.alias_manager')->getAliasByPath('/dashboard');
    $event->setResponse(new RedirectResponse($path));
  }

}

/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = array('checkFrontRedirection');
  return $events;
 }

}

```

---
Tags: 8
---


title: Limit multiple fields node add form

text:
# Question
Title: Limit multiple fields node add form
How can I (either with a module or programmatically) limit the number of values for multiple fields? For example, the user can add only a single value for field A OR field B OR field C. The total maximum number of values behind all fields can't exceed 1.

# Answer
**Using a contrib module:** You can use the conditional\_fields module.

**Doing it programatically:** You can use the `#states` property in a custom form or `form_alter` hook.

You must add this to field A, B and C:

```
'#states' => [
  'invisible' => [
    [':input[name="field-name"]' => ['filled' => TRUE]],
    'or',
    [':input[name="field-name-2"]' => ['filled => TRUE]],
  ],
],

```

Of course you have to replace "field-name" and "field-name-2" with the two field names that are not the one adding the states to, hope it makes sense.

If you can’t find the name of the field you can look in the browser inspector to get the name of the input field.
> 1 votes

---
Tags: 8, nodes, forms
---


# Question
Title: Prevent directory permissions of sites/default from being protected in a local environment?
Drupal automatically changes the directory permissions of `sites/default` to 555 (i.e. read-only), which means that if I'm editing `sites/default/settings.php`, even if I've set the permissions for that file to read/write (which it again reverts on a page load), PhpStorm still gives me a permission denied error on the **swap** file it's attempting to create in the same directory.

* Is there a more flexible way to update settings (especially on a dev machine) other than manually setting the file and directory permissions every time you need to edit those files?
* Do I just have to do it via sudo?
* Can I disable permissions checking for a specific environment?

# Answer
If you are on Drupal 8, you can configure settings.php to include a settings.local.php with a simple environment check (to ensure you are running a local env).

In that file, you can add this:

`$settings['skip_permissions_hardening'] = TRUE;`

This will allow you to open and write to settings.php without it being locked back down.
> 7 votes

# Answer
Filezilla allowed me to change the permissions from the the Filezilla console when cpanel could not Drupal Docs
> -3 votes

---
Tags: configuration, files
---


# Question
Title: How can I make the coupon code field in commerce mandatory?
Using D7 commerce coupon/discount modules. I need to make the coupon field mandatory. Every order needs a coupon code entered.

There is no standard "required" checkbox on the field and I tried using conditional fields module to no avail.

# Answer
You must do this in a `hook_form_FORM_ID_alter()`.

You wouldn't use `hook_form_alter()` unless you are checking on a dynamic form ID. In this case it's better to use `hook_form_FORM_ID_alter()`.

The reason for this, is that `hook_form_alter()` is called on every form render and `hook_form_FORM_ID_alter()` is only called when that specific form is being rendered.

Add this code to your `.module` file to make the field required:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['commerce_coupon']['coupon_code'])) {
    $form['commerce_coupon']['coupon_code']['#required'] = TRUE;
  }
}

```
> 6 votes

# Answer
You can do that by Implements `hook_form_BASE_FORM_ID_alter` but that would allow passing the step if the user enters any random string inside the coupon field.

To avoid this confusion you need to use the form alter to make coupon field required and also add custom validation to check if the coupon is valid.

if the coupon is not valid, then the user will stay in the step and will get the same error message provided by the commerce coupon module.

I assume your custom module name is '**CUSTOM**'

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function CUSTOM_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['commerce_coupon']['coupon_code'])) {
    // Set code as required.
    $form['commerce_coupon']['coupon_code']['#required'] = TRUE;
    $form['buttons']['continue']['#validate'][] = 'my_custom_coupon_validate';
  }
}

/**
 * Custom coupon validate.
 */
function my_custom_coupon_validate(&$form, &$form_state) {
  $code = $form_state['input']['commerce_coupon']['coupon_code'];
  $order = $form_state['order'];

    $coupon = commerce_coupon_redeem_coupon_code($code, $order, $error);
    if ($coupon) {
      // Reload the order so it is not out of date.
      $order = commerce_order_load($order->order_id);
      // Recalculate discounts.
      commerce_cart_order_refresh($order);
    }
    else {
      form_set_error('coupon_code',$error);
    }
}

```
> 4 votes

---
Tags: 7, forms, commerce
---


# Question
Title: Create a draggable table and save weights
I'm struggling a bit with creating a draggable table.

I want to have a table that lists node labels, where it's possible to rearrange the order of the nodes. The new weights shall be available when I submit the form.

This is my code so far:

```
$rows = [];
foreach ($nodes as $node) {
  $weight = $node->weight;

  $row = [
    'weight' => $weight,
    $node->label(),
  ];

  $rows[] = [
    'data' => $row,
    'class' => ['draggable'],
    '#weight' => $weight,
  ];

  $form['table'][$node->id()]['weight'] = [
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#title_display' => 'invisible',
    '#default_value' => $weight,
    '#attributes' => [
      'class' => [
        'draggable-weight'
      ]
    ],
  ];
}

$form['table'] = [
  '#type' => 'table',
  '#header' => [
    $this->t('Weight'),
    $this->t('Title'),
  ],
  '#rows' => $rows,
  '#attributes' => [
    'id' => 'my-module-table'
  ],
  '#tabledrag' => [[
    'action' => 'order',
    'relationship' => 'sibling',
    'group' => 'draggable-weight',
  ]],
];

```

When I `kint($form_state->getValues())` in my submit handler `table` is equals to `''`.

I feel like I'm missing something simple, but the lack of documentation for this makes it hard to find out.

# Answer
With the help from @Leigh I found the problem. I was setting some keys on `$form['table'][$node->id()]` and then overriding `$form['table'][$node->id()]` at the bottom.

I have moved a bit around in the code and now it works perfectly.

```
$form['table'] = [
  '#type' => 'table',
  '#header' => [
    '',
    $this->t('Weight'),
    $this->t('Title'),
  ],
  '#attributes' => [
    'id' => 'my-module-table'
  ],
  '#tabledrag' => [[
    'action' => 'order',
    'relationship' => 'sibling',
    'group' => 'draggable-weight',
  ]],
];

foreach ($nodes as $node) {
  $weight = $node->weight;

  $form['table'][$node->id()] = [
    'data' => [],
  ];
  $form['table'][$node->id()]['#attributes']['class'] = ['draggable'];
  $form['table'][$node->id()]['weight'] = [
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#title_display' => 'invisible',
    '#default_value' => $weight,
    '#attributes' => [
      'class' => [
        'draggable-weight'
      ]
    ],
  ];
  $form['table'][$node->id()]['label'] = [
    '#markup' => $node->label(),
  ];
}

```
> 3 votes

---
Tags: 8, forms
---


# Question
Title: AJAX form submit error when sending form to twig in hook_preprocess_page
I have a simple AJAX form that I can't submit when the form is passed from module to the template in hook\_preprocess\_page. The same form works fine if sent from controller, it's just that the layout is complicated and I prefer to write the HTML part in the twig file and integrate the form where it fits best.

The form class:

```
    <?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class SubmissionForm extends FormBase {
  public function getFormId() {
    return 'mymodule_submission_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#prefix'] = '<div id="submission-form-wrapper">';
    $form['#suffix'] = '</div>';

    $form['mail'] = array(
      '#title' => 'E-mail',
      '#type' => 'textfield',
      '#required' => TRUE,
    );

    $form['actions'] = array(
      '#type' => 'actions'
    );

    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Submit',
      '#attributes' => array(
        'class' => array(
          'btn',
          'btn-success',
          'use-ajax-submit'
        ),
      ),
      '#ajax' => array(
        'wrapper' => 'submission-form-wrapper',
      )
    );

    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

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

```

The preprocess function:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function mymodule_preprocess_page(&$vars) {
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $vars['page']['submission_form'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\SubmissionForm');
  }
}

```

The error:

> TypeError: Argument 1 passed to Drupal\Core\Ajax\AjaxResponse::setAttachments() must be of the type array, null given, called in /Volumes/Work/Git/myproject/public\_html/core/lib/Drupal/Core/Render/MainContent/AjaxRenderer.php on line 56 in Drupal\Core\Ajax\AjaxResponse-\>setAttachments() (line 37 of /Volumes/Work/Git/myproject/public\_html/core/lib/Drupal/Core/Render/AttachmentsTrait.php).

* it's a fresh Drupal 8.7.10
* devel and kint as contrib modules enabled
* core inline form errors enabled
* the form has only one required textfield and the submit button

Any suggestions on how to fix this?

Thank you!

# Answer
The `#ajax['wrapper']` replaced with `#ajax['wrapper_selector']` that's why the form disappear see this issue:

Try with:

```
<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class SubmissionForm extends FormBase {

  public function getFormId() {
    return 'mymodule_submission_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#prefix'] = '<div id="submission-form-wrapper">';
    $form['#suffix'] = '</div>';

    $form['mail'] = [
      '#title'    => 'E-mail',
      '#type'     => 'textfield',
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
      '#type'       => 'submit',
      '#value'      => 'Submit',
      '#attributes' => [
        'class' => [
          'btn',
          'btn-success',
          'use-ajax-submit',
        ],
      ],
      '#ajax'       => [
        // Change here the wrapper with wrapper_selector
        // 'wrapper' => 'submission-form',
        'wrapper_selector' => '#submission-form-wrapper',
      ],
    ];
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

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

```
> 0 votes

---
Tags: 8, ajax
---


# Question
Title: How do I access URL parameters from my custom module?
I have set up a custom page with Panels.

In the Panel configuration I have set the page path to `/products/%term`.

I made a custom module which currently displays "Hello world" on this page, and all is well.

```
function product_tree_block_view($delta='') {
  $block = array();
  switch($delta) {
    case 'product_tree' :
      $block['content'] = theme('product_tree', array("greet" => "Hello world",));
      break;
  }
  return $block;
}

```

However; I would like to process the %term to fetch some additional information, relevant only to the current %term.

My question is: How can I access the %term? Is this variable accessible from my module at all?

# Answer
> 9 votes
The function `arg()` will do that for you. For example, in path `http://siteurl/products/%items`,

* `arg(0)` will have the value `products` (first value after your `$base_url`)
* `arg(1)` will have the value of `%items` (second value).

You might then just apply your logic, in this this case you could do the check `arg(1)`.

# Answer
> 0 votes
For Drupal 7 use arg() function and you are good to go.

For Drupal 8 follow below procedure,

Here's the example of accessing URL parameters and passing them to a TWIG template, I am considering you have already created your module and required files and suppose "/test?fn=admin" is your URL

1. In Your .module file implement hook\_theme and define variables and template name (Make sure you replace "\_" with "-" when creating the template file)

```
 function my_module_theme () {
         return [
          'your_template_name' => [
             'variables' => [
                 'first_name'    => NULL,
              ],
         ];
       }

```

Now create your controller and put below code in it.

```
 namespace Drupal\my_module\Controller;

 use Drupal\Core\Controller\ControllerBase;
 use Symfony\Component\HttpFoundation\Request;

 class MyModule extends ControllerBase {

   public function content(Request $request) {

     return [
       '#theme' => 'my_template',
       '#first_name' => $request->query->get('fn'), //This is because the parameters are in $_GET, if you are accessing from $_POST then use "request" instead "query"
     ];
   }

 }

```

Now in your TWIG file which should be "my-template.html.twig" you can access this parameter as,

```
 <h3>First Name: {{ first_name }}</h3>

```

And its done. Hope this helps.

---
Tags: 7
---


title: How to get $_POST and $_GET parameters

text:
# Question
Title: How to get $_POST and $_GET parameters
I call a route via AJAX and pass data to it. In a controller, I want to get `$_POST['var']`, but it does seem to work on Drupal 8.

How I can get values contained in `$_POST` from a controller?

# Answer
From the change record:

```
$name = $_POST['name']; // form param

```

becomes

```
$name = \Drupal::request()->request->get('name'); // form param

```

Incidentally, for `GET` vars, you would use:

```
$query = \Drupal::request()->query->get('name');

```
> 94 votes

# Answer
In a controller get the request with a type-hinted argument `Request $request`:

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;

class ExampleController extends ControllerBase {

  /**
   * Controller to return a POST or a GET parameter.
   */
  public function action(Request $request) {

    // get your POST parameter
    $foo = $request->request->get('foo');

    // or get your GET parameter
    $foo = $request->query->get('foo');

    // POST requests are not cached, but for GET you need a cache context
    return [
      '#plain_text' => $foo,
      '#cache' => ['contexts' => ['url.query_args:foo']],
    ];
  }

}

```

More info https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes

Use #plain\_text to escape the input data for HTML output. See https://www.drupal.org/node/2559263
> 44 votes

# Answer
Inject the `RequestStack` into your controller.

The current request contains the `query` attribute that in turn contains the GET parameters. `request` contains the POST parameters.

```
<?php

namespace Drupal\example_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * An example controller.
 */
class ExampleController extends ControllerBase {

  /**
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  private $requestStack;

  /**
   * Constructor.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

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

  /**
   * {@inheritdoc}
   */
  public function action() {
    // Get your GET parameter here.
    $this->requestStack->getCurrentRequest()->query->get('foo');
  }

}

```
> 23 votes

# Answer
If you are using `Content-Type: application/json` please use :

```
$post_data = json_decode( $this->request->getContent(),TRUE);

```
> 5 votes

# Answer
You can check the Request object like

```
\Drupal::request()->getMethod();

```

it will returns GET or POST or whatever. If you are working inside an object, remember to DI the Request service.
> 4 votes

# Answer
None of the other answers worked for me but I found this that did:

```
$request->getContent();

```
> 2 votes

# Answer
This is an example for accessing URL parameters and passing them to a template. I am assuming you have already created your module and required files and that */test?fn=admin* is the path your module is using.

In Your .module file implement `hook_theme()` and define variables and template name. (Make sure you replace *_* with *-* when creating the template file.)

```
function my_module_theme () {
  return [
    'your_template_name' => [
      'variables' => [
        'first_name'    => NULL,
      ],
    ],
  ];
}

```

Now create your controller and put the following code in it.

```
 namespace Drupal\my_module\Controller;

 use Drupal\Core\Controller\ControllerBase;
 use Symfony\Component\HttpFoundation\Request;

 class MyModule extends ControllerBase {

   public function content(Request $request) {
     return [
       '#theme' => 'my_template',
       '#first_name' => $request->query->get('fn'), //This is because the parameters are in $_GET, if you are accessing from $_POST then use "request" instead "query"
     ];
   }

 }

```

In template file, which should be *my-template.html.twig*, you can access this parameter as `<h3>First Name: {{ first_name }}</h3>`.
> 1 votes

---
Tags: 8, page-controller
---


# Question
Title: Migrating revisions from external data source
We are trying to migrate content from an external data source into Drupal 8 using the core migrate modules. This is a stripped down example of the data being migrated:

```
id     resourceId     articleId     version     title          body
---------------------------------------------------------------------------
1      10             10            1           Page title     Page content
2      10             10            1.1         Page title     Page content
3      10             10            1.2         Page title     Page content
4      11             11            1           Page title     Page content
5      11             11            1.1         Page title     Page content

```

The *id* field is the unique identifier, and is the field set in the *getIds()* method, when as you can see the *resourceId* and *articleId* are more a preferred representation for a node id to be migrated into Drupal.

From my understanding, after reading through the *migrate\_example* modules, the *query()* method must only return a single row; so when our migration runs, all these records are migrated as new nodes when in the previous database they were just revisions of one piece of content.

If we are intended to only return a single row in the *query()* method, what is the best way to only migrate the most recent version of each piece of content?

My first attempt was to try and achieve this in the *processRow()* method, but then if the migration is going through the table row by row, then how can you remove/update a previous row if the next row is a more recent version?

We have an option to just run our own script on the table first, to filter out all most recent versions and then run the migrate script on that, but I would like to know if there is a way to achieve this using the core modules in Drupal.

Thanks in advance.

# Answer
> 1 votes
Yeah, this part is not documented at all, I had now also problems with it, so here is how I solved it:
When you want to migrate a content that has revisions, you need to migrate the first version with the `entity:node` plugin, then you migrate the next versions with the `entity_revision:node`. You don't do anything else, just change the destination plugin and when you migrate the revisions, you set the nid value to the first version of the node. So you keep the body and the file and other fields, you just add the nid field, so the revision plugin will know where to put the content. That's it at least from the yml part.
From the source, you have two one for the node plugin where you list only the first version of your content that you want to migrate and one for the revisions where you list everything EXCEPT the first version also, you have a new column which contains the first version's ID for every revision's it's own.

If you migrate the current publish one into the node table, and you migrate the rest into the revision, the IDs, the order of the revision and some other things will be messed up. At least my case was that.

By code (not 100% complette, just main parts):

migrate\_plus.migration.node.yml:

```
id: my_node
source:
  plugin: my_node
process:
  title: title
  body: body
  langcode:
    plugin: default_value
    default_value: "und"
  status:
    plugin: default_value
    default_value: 1
  #other fields except nid.
destination:
  plugin: entity:node

```

Query for the source plugin (id = my\_node):
`SELECT id, title, body FROM content WHERE version = 1`
in `getIds()` the `id` is the only id.

migrate\_plus.migration.node\_revision.yml:

```
id: my_node_revision
source:
  plugin: my_node_revision
process:
  nid:
    plugin: migration_lookup
    migration:
     - my_node
     - my_node_revision
    source: first_version
  title: title
  body: body
  langcode:
    plugin: default_value
    default_value: "und"
  status:
    plugin: default_value
    default_value: 1
  #other fields.
destination:
  plugin: entity_revision:node

```

Query for the source plugin (id = my\_node\_revision):

```
SELECT first_ver.id AS first_version, c.id, c.title, c.body FROM content c
  INNER JOIN (
    SELECT * FROM content c
    WHERE version = 1
  ) first_ver ON c.resourceId = first_ver.resourceId AND c.articleId = first_ver.articleId
WHERE c.version <> 1

```

in `getIds()` the `id` is the only id.

The above example will give new id's for the content.

EDIT: note that the example in this answer is a migration from confluence database into drupal, so therefore slightly different than a normal drupal-drupal migration. Also, if you look in the entity\_revision:node plugin, which is located here: `core/modules/migrate/src/Plugin/migrate/destination/EntityRevision.php` you will notice that you have two ways of doing this.
A) Providing revision id.
B) Not providing revision id.

When you don't provide the revision ID, then as you add new revisions, it will always make the latest added revision the latest content version. (the example yml and source are like this above)

When you provide a revision ID, then you first need to add the current version into the node table, then add all the revisions and provide the revision ID, in that case, it won't make the last added revision as the latest content version.

---
Tags: 8, database, migrations
---


# Question
Title: Randomly display questions in Webform - to use as an exam
Is it possible to randomly select a fixed number of questions to display in a Webform? I have a request to set up over 500 questions in a webform but for each user who visits the webform, only a random selection of 100 questions will be displayed. The rest will not be displayed. The purpose of this is to use the Webform as an exam/quiz.

Note: the hidden questions cannot be visible in the code, so CSS or other Javascript hiding techniques are not suitable.

Any ideas how I might achieve it.

Thanks a mil

F

# Answer
You can use form alter to access `$form` array and display/hide specific elements, more details: https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-programmatically-hide-and-show-webform-elements.

```
function CUSTOM_MODULE_form_webform_submission_WEBFORM_NAME_add_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $elements = &Drupal\webform\Utility\WebformFormHelper::flattenElements($form['elements']);

  $elements['question_one']['#access'] = FALSE;
  $elements['question_two']['#access'] = FALSE;
}

```
> 2 votes

---
Tags: webforms
---


title: Drupal queue item not being processed

text:
# Question
Title: Drupal queue item not being processed
I am creating queue items from a cronjob. But it seems they are not getting processed. Any ideas why?

Do we need to process the items separately? I mean i have created the worker class and everything.

Thanks BR/Pratip

# Answer
> 3 votes
1. Make sure cron is running on your site.
2. Make sure cron time is set on your QueueWorker

```
/**
 * Create node object from the imported XML content
 *  * @QueueWorker(
 *   id = "import_content_from_xml",
 *   title = @Translation("Import Content From XML"),
 *   cron = {"time" = 60}
 * )
 */

```

Source: An example module to help understanding the Queue API and the Batch API in Drupal 8.

I highly recommend using Queue UI to monitor the queue from there. If it is not running, check your database log and try running the process as a batch (sometimes that is easier to troubleshoot).

---
Tags: 8
---


# Question
Title: Loading a views block inside another block
I'm pretty new to this, but I have been stumbling on a feature I would like to have. I'm using Drupal 7.

I've created a some blocks on my front page. In one of those blocks I have a some div's and text that goes inside of my block. That works just fine and looks great.

Problem is that I want to place some randomly generated testimonials inside this block and I can't figure out how to do so.

Now, I've already created another view block that lists my testimonials randomly, but I just need to know the correct php code. Note: I've also enabled the PHP filter module, but it doesn't seem to be working.

I can easily assign my random testimonial view to a block, but I want to combine some HTML along with the testimonial and I just dont know enough about php.

Example:

Some random text here...

\**PHP to bring in my random block of testimonials from views\**

Some random text here...

I've also heard that placing in PHP like this is not good practice. If anyone has a better way for me to do this I would appreciate it. Like I mentioned, placing this view in a empty block works fine. I just want to be together with some html.

Thanks!

-Dan

# Answer
> 2 votes
You can achieve it by following snippet in your block,

```
  Some random text here...
  echo views_embed_view('view-name', $display_id = 'display-name');
  Some random text here...

```

eg:

```
 <?php echo views_embed_view('test', $display_id = 'block'); ?> //dont forgot to enable text format as PHP.

```

# Answer
> 0 votes
you can use Insert block (it's div version but it work perfectly)module to insert a block into another block.
See the Readme file

# Answer
> 0 votes
Late answer for anyone who comes across this.

The cfrblock module, based on renderkit, allows to combine blocks and elements in any way you want, also supports conditional logic.

Follow the instructions on the module page:

* Install cfrblock, renderkit, cfrpreset. This involves some composer packages, you will find instructions on renderkit module page.
* Go to admin/structure/cfrpreset, add a preset for "BlockInterface".
* Configure the block as you like.
* Go to admin/structure/block. The presets you just created will appear there as blocks.

Possibilities when configuring the block:

* Sequence of elements (blocks or other things).
* Views display.
* Views exposed form.
* Existing block.
* Element wrapped into a special container.
* Combination of the above, with endless nesting.

If you are crafty and creative, you can create your own elements and then recombine them into a block.

I am using this on a website where I have more custom plugins than you currently find in renderkit. I should add some of those to the contrib module..

---
Tags: 7, views, blocks, theming
---


title: Block within another block

text:
# Question
Title: Block within another block
In drupal 7, I want to render block into another block, for example block-1 into block-2. I guess I should put some PHP code into block-2, but I don't know what the code could be?

# Answer
Based on Ashlars's comment.

A minipanel, provided by Panels, is for anyone not used to Panels, essentially a block, that supports internal layouts. You can use a mini-panel to wrap several different blocks (and many other things, views, nodes, etc) into a single "block".

Unfortunately, I must admit that documentation is scarce on this topic. I will refer you to this other question: looking for a good mini panels tutorial.
> 3 votes

# Answer
Completely agree with Letharion's comment but if there is absolute need for such, this code snippet can help:

```
<?php
//D7
$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);
?>

```

If you are unsure what are exact parameters for **'module\_name'** and **'block\_delta'** I'd recommend searching the database table **block** and locating your specific

* module\_name under column **module**
* block\_delta under column **delta**

second parameter block\_view remains exactly like that.

Reference: https://www.drupal.org/node/26502
> 3 votes

# Answer
Late answer for anyone who comes across this.

The cfrblock module, based on renderkit, allows to combine blocks and elements in any way you want, also supports conditional logic.

I am not sure if this covers the specific requirement of the original question: The original question wants to insert block-1 into block-2. What I am proposing here allows to create a new block which combines two existing blocks.

Follow the instructions on the module page:

* Install cfrblock, renderkit, cfrpreset. This involves some composer packages, you will find instructions on renderkit module page.
* Go to admin/structure/cfrpreset, add a preset for "BlockInterface".
* Configure the block as you like.
* Go to admin/structure/block. The presets you just created will appear there as blocks.

Possibilities when configuring the block:

* Sequence of elements (blocks or other things). This is, I think, what you want here.
* Views display.
* Views exposed form.
* Existing block.
* Element wrapped into a special container.
* Combination of the above, with endless nesting.

If you are crafty and creative, you can create your own elements and then recombine them into a block.

I am using this on a website where I have more custom plugins than you currently find in renderkit. I should add some of those to the contrib module..

NOTE: This is essentially the same answer I gave here, https://drupal.stackexchange.com/a/288747/2974. It applies in both cases.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: How do I pass a checkbox value to a Webform through URL?
When I click a webform link, I want one of the checkbox checked. I've set already set up the default value for that checkbox as %get\[foo\] in Webform.

I tried:

a href="node/34?foo=checked"

a href="node/34?foo=selected"

a href="node/34?foo=1"

a href="node/34?foo\[\]=1"

Am I missing something?

# Answer
> 2 votes
Webform provides this functionality by itself.

1. Define in your checkbox field a default value:

%get\[customkey\]

2. The url will be:

http://example.com/node/1?customkey=one,two

# Answer
> 1 votes
Use `[current-page:query:foo]` in Default Value field and set query string to node/1?foo=1,2 and it will work.

Installing Tokens module will show you some values you can use in your default value field.

# Answer
> 0 votes
Keep in mind that, at the moment of writing, there's an issue with tokens and the Options Element module in Webform.

# Answer
> -1 votes
This feature is not directly available on Webform module. You've to implement some code to prefill the form fields.

A simple method is to write some JS which reads the URL parameters and set the values to the corresponding fields.

There are many ways to implement this code. This is an example of JavaScript code:

```
var current_url = window.location.href;
if (current_url.indexOf('foo=') > 0){
  $('#field-id').val(current_url.substr(current_url.indexOf('foo=') + 4));
}

```

At first the script get the current url and if the "foo" parameter is found, then the value will be loaded and used to set the #field-id value. #field-id is the id of the input field on the webform. 4 is the length of "foo=".

If you have many parameters you can use

> current\_url.split("&")

method which returns an array with all the parameters.

# Answer
> -1 votes
You can use the Prepopulate module which autofills your fields. Here is a quote about it (from the module's project page):

> ... allows fields in most forms to be pre-populated from the $\_REQUEST variable.
>
> For example, the following URL,
>
> `http://www.example.com/node/add/blog?edit[title]=this is the title`
>
> will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets.

---
Tags: webforms, uri
---


# Question
Title: How do I render a submit button so that it's disabled initially and enabled by JavaScript?
We have a form that includes a React JS frontend component. The component collects some required information, which the React component then supplies to the backend by populating a hidden form field.

To ensure that a user cannot bypass entering the required data through the component, we need to satisfy the following requirements:

* Before the React component loads, the "Submit" button needs to be disabled. This ensures that a user can't submit the form just by disabling JS or just clicking the button before the page finishes loading.
* After the React component loads, any time that the required values get cleared, the "Submit" button needs to be disabled.
* Once the required values are supplied, the "Submit" button should be enabled.
* It must not be possible to submit the form if the hidden value is empty.

I've tried rendering the form like this:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];

    $form['selected_values'] = [
      '#type' => 'hidden',
    ];

    $form['actions'] = [
      '#type'   => 'actions',
      '#weight' => 100,
    ];

    $form['actions']['submit'] = [
      '#type'         => 'submit',
      '#value'        => $this->t('Submit'),
      '#button_type'  => 'primary',
      '#disabled'     => TRUE, // Controlled by JS on the frontend
    ];

    return $form;
  }

```

And then in JavaScript, I have an `onValueChange()` event callback that looks like this:

```
function onValueChange(value) {
  if (value.trim() === '') {
    $(submitButton).prop('disabled', true);
  }
  else {
    $(submitButton)
      .prop('disabled', false)
      .removeClass('is-disabled');
  }
}

```

I also tried:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];

    $selected_values = form_state->getValue('selected_values');

    $form['selected_values'] = [
      '#type' => 'hidden',
    ];

    $form['actions'] = [
      '#type'   => 'actions',
      '#weight' => 100,
    ];

    $form['actions']['submit'] = [
      '#type'         => 'submit',
      '#value'        => $this->t('Submit'),
      '#button_type'  => 'primary',
      '#disabled'     => !empty($selected_values),
    ];

    return $form;
  }

```

Both of these approaches demonstrate the same problem -- clicking the "Submit" doesn't submit the form; it just seems to rebuild the form. With the second approach, it looks like the incoming selected values are always empty during the form render; they don't get applied to the form state until *after* the form is constructed.

How can we ensure that the "Submit" button starts out disabled, while requiring the necessary values?

# Answer
Using `#disabled` on the submit button is the wrong solution because it communicates to the Drupal form API that the button is not expecting input. In other words, it causes Drupal to act as if the button were not there at all. Hence, clicking the submit button has no effect. This all makes sense from a security perspective, because normally you wouldn't want crafty users disabling backend logic just by using developer tools to force a disabled or read-only form element into being enabled.

Instead, the solution is two-fold:

1. Render the button as disabled via HTML attributes, so that the button is only disabled in the browser but is still considered an active button on the backend.
2. Mark the hidden field as `'#required' => TRUE` so that it's not possible to bypass the form even if the user is crafty with Dev Tools.

Here's what that looks like in practice:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];

    $form['selected_values'] = [
      // Though this field is hidden, it's required. So, the title is still
      // shown if/when the field is ever NULL during submission.
      '#title'    => $this->t('File selection'),
      '#type'     => 'hidden',
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type'   => 'actions',
      '#weight' => 100,
    ];

    $form['actions']['submit'] = [
      '#type'         => 'submit',
      '#value'        => $this->t('Submit'),
      '#button_type'  => 'primary',
      '#attributes' => [
        // This button is programmatically enabled/disabled via JS on the
        // frontend.
        'disabled' => 'disabled',
    ];

    return $form;
  }

```

The frontend logic for enabling the button stays the same. The difference here is that the button is only disabled in the rendered HTML rather than being disabled in the backend form. In addition, if a crafty user enables the button by removing the `disabled` attribute on the HTML DOM element, they'll just end up with a validation error that says:

> File selection field is required.

Separately, as for why the second approach failed to enable/disable the "Submit" button based on the incoming values, this is because Drupal builds the form first before processing the incoming values so that it knows which form elements need to be invoked to process the input. So, at the time that the form builder is invoked, there is nothing yet in form state values. Hypothetically, it might be possible to get the raw input via `$form_state->getUserInput()` and then control whether or not the button should be enabled based on that; but, this approach may have security implications.
> 2 votes

---
Tags: 8, forms, javascript
---


# Question
Title: Display text in an empty field group tab using custom code
I have created a field group with an empty tab. I would like to use custom code in a module to display something in this empty tab - it will just be a render array.

Can someone show me how this can be done or a link that might help me discover how to do this?

# Answer
> 0 votes
Adding something like the below in hook\_form\_alter() works

```
<?php
    $group_name = 'group_some_name';
    $form['test'] = array(
      '#type' => 'container',
      'content' => array(
        '#markup' => 'test',
        '#prefix' => '<div>',
        '#suffix' => '</div>',
      ),
    );
    $form['#group_children']['test'] = $group_name;
    $form['#fieldgroups'][$group_name]->children[] = 'test';
?>

```

Seems like I had to add wrap the content in `'#type' => 'container'` for it to work

---
Tags: 8, entities
---


title: Render media entity image

text:
# Question
Title: Render media entity image
I have a media entity target id and I want to render the image contained in it. I've loaded the media entity using Media::load, I was hoping to use something like render() on some rendererable array that I can extract/generate from that media entity object. I found a somehow related question here: How to get Media entity image (Entity Reference Field) URL in TWIG theme, using ImageStyle::load, but I want to render the whole image with its defined attributes (alt, title or fields). Any suggestions please?

# Answer
You need to build a render array

```
$build = \Drupal::entityTypeManager()->getViewBuilder('media')->view($media, $view_mode);

```

and then place it unrendered in a template, Twig renders this automatically.
> 8 votes

# Answer
Using the twig\_tweak module, I found I could use:

```
<dd>{{ drupal_field('field_image', 'node') }}</dd>

```
> 1 votes

---
Tags: 8, theming, media
---


# Question
Title: How to update cart after deleting line items?
I have an Application (app) node that when it gets created (hook\_node\_insert) I add line items (based on info in the app) to my cart. This works great.

Step 2 now is that when I add a new app, I would like to empty the cart (or remove the line items) before adding the new line item (so there is effectively only ever 1 item in the cart).

If I try to do $item-\>delete() or $cart-\>delete() before I add the new line item (in my node insert hook) then I get this error:

> Drupal\Core\Entity\EntityStorageException: A cart order for type default, store 1 and account 1 already exists. in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>save() (line 847 of core\lib\Drupal\Core\Entity\Sql\SqlContentEntityStorage.php).

If I delete the line items after I add the new line item; then the cart almost looks correct. It shows only my new line item and the subtotal is the amount of my new line item; but the Total shown is the combined Total of the new line item added to the old line items (which have been successfully deleted).

My guess is there is something I need to do to "refresh" the cart after adding and then deleting line items?

# Answer
> -1 votes
instead of using $item-\>delete() this works:

```
  $cart_manager = \Drupal::service('commerce_cart.cart_manager');
  foreach($items as $item) {
    //$item->delete();
    $cart_manager->removeOrderItem($cart, $item, TRUE);
  }

```

the 3rd parameter is 'save cart' and setting it to TRUE updates the cart Total.

---
Tags: 8, commerce
---


# Question
Title: How to create a user with custom fields?
On my drupal site, using the User module, I have added extra fields to the user registration form such as 'Organization'. I notice that this has created a mysql database called 'user\__field\_organization'.

I am trying to write a custom module which involves creating new users.

At the moment my module creates a new user, with a username, password and email. The code for this (which works fine) is:

```
$user_data = ['name' => 'John', 'mail' => 'email@me.co.uk', 'pass' => 'examplePassword','status' => 1,];

$this->user = $this->user_store->create($user_data);

```

(where `$this->user_store = $etm->getStorage('user');` )

But I also need to update the extra fields such as Organization but can't work out how to do this.

I have looked at this question: How to programmatically create new user with custom fields?

And I have tried adding `custom_field_organization` or `user__field_organization` into `$user_data` but it doesn't work.

I have been trying to find out where in the User module a user is created once the registration form is submitted. If I could find that then I could copy what is done there.

# Answer
You are close to the right solution. You have to add `'field_organization' => 'some_value'` to your `$user_data` array.

They keys in the $user\_data array is the field names. The field name is what comes after `user__` in the table name. You can also see the field name in the UI where you add the fields (it’s also called machine name).
> 1 votes

---
Tags: 8, users, database
---


# Question
Title: How do you get the url of an image in a view twig template?
I want to check the fields.field\_image.content to see if it is empty or not. I want the view to display differently if there is no image in the page field\_image field.

I was thinking I could just get the URL of the field\_image and do a simple if statement, but I don't see a way to do that.

Is there to check if the fields.field\_image.content field is empty?

I've tried a few different things like:

```
{% if fields.field_image.content is empty %}
{% if fields.field_image.content0|striptags|trim is empty %}

```

I'd like to dump fields.field\_image to see the whole object, but my local setup always crashes.

Is this even possible?

The answer is yes it is possible to check if the image is present or not.

Here is how to do it:

```
{% set fieldimage = fields.field_image.content|render|striptags('<img>')|trim|length > 0 %}
{% if fieldimage == false %}
  image is empty
{% else %}
  image is not empty
{% endif %}

```

# Answer
> 1 votes
There is a `raw` variable available - you can use it to get raw result from the query, with all data it fetched. You can inspect it with the devel or twig\_vardumper module using xdebug or `dump(raw)`. More about debugging twig templates: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates#s-viewing-variables

---
Tags: views
---


title: How to create a link that uses a route?

text:
# Question
Title: How to create a link that uses a route?
I am trying to add a link to a taxonomy landing page, like this

```
$breadcrumbs->addLink(Link::createFromRoute($term_name,"/taxonomy/term/$tid"));

```

but I get the following error : `Symfony\Component\Routing\Exception\RouteNotFoundException: Route "/taxonomy/term/2041" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 187 of C:\drupaldevsites\pup-dev\docroot\core\lib\Drupal\Core\Routing\RouteProvider.php).`

# Answer
> 7 votes
The argument has to be a route name.

Try:

```
$breadcrumbs->addLink(Link::createFromRoute($term_name, "entity.taxonomy_term.canonical", ["taxonomy_term" => $tid]));

```

See the docs for this method.

# Answer
> 0 votes
Get the route name using :

```
dump(\Drupal::routeMatch()->getRouteName());

```

then use that route name :

```
$myBreadcrumbs [] = Link::createFromRoute('News Centre', 'ROUTE_NAME');

```

---
Tags: 8, routes
---


# Question
Title: How can I return a JSON response from an internal function ? (not the main callback)
I have a callback that is running for a specific post request. I am returning a certain JSON response at the end of it.

What if I want to catch errors inside one of the functions that are ran in that callback ? How do I get the Response object, or is there another way of sending a response immediately in case errors are catched ?

```
  private function someCalculation()
{

  try {

  } catch ($e) {
    //how to send response in case of error inside this function
    return new JsonResponse([
      'data' => null,
      'error' => $error
    ]);
  }
}

public function getTemplate(Request $request)
{

  $this->someCalculation();

  return new JsonResponse([
    'data' => $result,
  ]);

}

```

How do I send a JSON from inside the someCalculation function in case some errors are found ?

# Answer
> 3 votes
You can do it by checking is `$this->someCalculation()` is instance of `JsonResponse`. It is is we return the response, otherwise we set `$result` to the calculation result.

```
private function someCalculation() {
  try {
    // Something.
  } catch ($e) {
    return new JsonResponse([
      'data' => NULL,
      'error' => $e->getMessage(),
    ]);
  }
}

public function getTemplate(Request $request) {
  // Alternatively you can return an array with a status code and check on that instead.
  if ($this->someCalculation() instanceof JsonResponse) {
    return $this->someCalculation();
  }
  // If it didn't fail set set $result to the calculation result.
  $result = $this->someCalculation();

  return new JsonResponse([
    'data' => $result,
  ]);
}

```

---
Tags: 8, http-request
---


# Question
Title: How can I translate the field group description?
I have created two field groups on the manage form display tab for a content type. I have added some description also.

On the interface translation, I can translate the field group labels but there I can't translate the description of a field group. As when I search the description there I can't find any results.

I also checked it in the config translation but field group is not present on that page.

Is there any way I can translate the field group translation?

# Answer
As far as I know there is no proper UI for this yet, but field groups are config, so you should be able to translate all strings by creating/editing translated versions of those config files.

First, export your current config, e.g. `drush config:export`

Then, in your `config/sync` directory look for files like `core.entity_form_display.ENTITY.BUNDLE.FORMMODE.yml`. In those files you will see a structure like

```
langcode: ISO2CODE
status: true
depenencies:
  config:
    - ...
third_party_settings:
  field_group:
    GROUP_ID:
      children:
        - field_foo
        - field_bar
      label: MY_GROUP_LABEL
      format_settings:
        description: 'MY DESCRIPTION'
...some more stuff...

```

The `third_party_settings/field_group` contains your group labels in your primary language. To translate a label, create a file `language/LANGCODE/core.entity_form_display.ENTITY.BUNDLE.FORMMODE.yml` below your `config/sync` directory.

This file must contain the same structure as the one in the main config file, but remove everything that is not translateable:

```
third_party_settings:
  field_group:
    GROUP_ID:
      label: MY_TRANSLATED_LABEL
      format_settings:
        description: 'MY TRANSLATED DESCRIPTION'

```

Finally, reimport the config with the translated labels, e.g. `drush config:import`
> 3 votes

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