title: How to find the pressed button

text:
# Question
Title: How to find the pressed button
Help me please. How can I get the value of the pressed button. Thanks!

$items = \[\];

```
foreach ($result as &$value) {
  $items[] = [
    $form['repo'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('FIELD REPO'),
    ],
    $form['repo']['repo_name'] = [
      '#type' => 'item',
      '#title' => $value->name,
    ],
    $form['repo']['user_name'] = [
      '#type' => 'hidden',
      '#title' => $value->name,
      '#value' => $value->name,
    ],
    $form['repo']['submit'] = [
      '#type' => 'submit',
      '#value' => $value->name,
    ],
  ];
}
$form['repositories_arr'] = [
  '#theme' => 'item_list',
  '#items' => $items,
  '#attributes' => ['id' => 'repositories_arr'],
];

return $form;

```

# Answer
> 0 votes
In the `foreach` loop of your example, you create multiple buttons and you can set a different/distinct `'#name'` property property to each submit button, e.g.:

```
foreach ($result as &$value) {
  ...
  $form['repo']['submit'] = [
    '#type' => 'submit',
    '#value' => $value->name,
    '#name' => $value->name,
  ];
  ...
}

```

In your validation and/or submit handler you can retrieve the element that triggered the form submission using `$form_state->getTriggeringElement()['#name']`.

# Answer
> 0 votes
So, what i wanted ...

```
for ($i = 0; $i < count($arr_git); $i++) {
  $form[] = [
    $item['repo_name'] = [
      '#type' => 'submit',
      '#title' => 'name'.$i,
      '#prefix' => '<div class="form__item">',
      '#attributes' => ['class' => ['item_name']],
    ],
    $item['repo_del'] = [
      '#type' => 'submit',
      '#name' => 'NA::ME___' . $i,
      '#value' => 'Delete',
      '#attributes' => ['class' => ['btn_del']],
      '#suffix' => '</div>',
    ],
  ];
}]

return $form;

```

This is then what made it work:

```
$form_state->getTriggeringElement()['#name'];

```

I rendered the form incorrectly

---
Tags: forms
---


title: How to get triggering_element

text:
# Question
Title: How to get triggering_element
I want to get `triggering_element` element on `form_alter` after form rebuild, Also I know that this could be used on submit handler on Ajax controller to findout which element cause form submit or Ajax triggered.

**So how can I get triggering\_element after Ajax call or form submissions?**

# Answer
Eyal is correct. FormState has a method getTriggeringElement. See the original change record for details.

```
$form_state->getTriggeringElement();

```

and if you want to get id try

```
$triggerdElement = $form_state->getTriggeringElement();
$htmlIdofTriggeredElement = $triggerdElement['#id'];

```
> 12 votes

# Answer
My preferred method is:

```
$triggering_element = $form_state->getTriggeringElement();
$button_name = $triggering_element['#name'];
if ($button_name === 'button1') {
  // ...
}

```

Works both for validateForm() and submitForm().

Ensure you have #name for all your buttons. E.g.:

```
$form['button1'] = [
  '#type' => 'submit',
  '#name' => 'button1',
  '#value' => $this->t('Button 1'),
];

```

Compared to $triggering\_element\['#id'\] it's more stable because #id auto-generated and can change implicitly.

Compared to $triggering\_element\['#value'\] it's better because:
\- #value can be not unique;
\- #value is a part UI (button label) and frequently changes.
> 5 votes

# Answer
# 3

```
$triggering_element = $form_state->getTriggeringElement();
$button_name = $triggering_element['#name'];
if ($button_name === 'button1') {
  // ...
}

```

Works both for validateForm() and submitForm().

Ensure you have #name for all your buttons. E.g.:

```
$form['button1'] = [
  '#type' => 'submit',
  '#name' => 'button1',
  '#value' => $this->t('Button 1'),
];

```

This is the correct answer.
> 1 votes

---
Tags: forms, 8
---


# Question
Title: Set the width of the select box in Drupal form
Currently I have a select box in a form as follows :

```
$form['fieldset']['event_trigger'] = array('#type' => 'select',
    '#title' => t('E-mail event trigger'),
    //'#default_value' => $edit['mail'],
    '#size' =>20
    //'#options' => select_eventtrigger_dropdown(),
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
  );

```

But here `#size` attribute is not fitting my requirement. It should have been the width of the select box. How can I achieve this or is there any workaround?

# Answer
> 1 votes
The size attribute you are trying to set there is related to how many items are shown at one time. So in those terms the height would increase and it would show a scrolling list of items to choose from if you added size to the select box. See Form API Docs for more information.

You need to target the select box with CSS to change the width (most themes/browsers set the width of a select box to `width: auto;` so it would be as long as the longest item to be selected).

So for instance if you want to set all of your `select` elements to take up the entire width of their containing divs you would set:

```
select {
  width: 100%;
}

```

Or if you want to target all select elements with a class of `.form-select` you could use:

```
select.form-select {
  width: 50em;
}

```

You can use id's also like `select#id-of-element` but using a class is the more generally accepted best practice for styling (not just in Drupal but general FED practices also).

# Answer
> 1 votes
In the Drupal 8 forms api, any form element attributes not directly supported by the API get stuffed into the '#attributes' FormElement property. This property supports the entire HTML spec for form element tag html attributes, as far as I know. It's the catch-all for anything the Drupal development folks don't feel the need to directly define and model.

```
$form['fieldset']['event_trigger'] = array('#type' => 'select',
    '#title' => t('E-mail event trigger'),
    '#size' =>20
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#attributes' => [
      'style' => 'width: 50em;'
    ],
  );

```

**or (usually preferred)**

```
$form['fieldset']['event_trigger'] = array('#type' => 'select',
    '#title' => t('E-mail event trigger'),
    '#size' =>20
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#attributes' => [
      'class' => 'select-css'
    ],
  );

```

coupled with a stylesheet:

```
.select-css {
  width: 50em;
}

```

---
Tags: forms, 6
---


# Question
Title: Add textfield to system branding block form to specify link URL
I would like to alter the branding block to add a textfield in the block form to specify the URL it should redirect to. The URL is currently fixed to `<front>` in the Twig template.

What I've done so far is to add the text field with hook\_form\_alter. I'm saving the value using `$form['entity_builders']` and `$block->setThirdPartySetting`. This works.

I want to retrieve this value in `hook_preprocess_block__system_branding_block(&$variables)` but `$variables` does not contain the block entity. How can I get the block in this preprocess function so that I can load my added value with `$block->getThirdPartySetting`?

# Answer
> 0 votes
A different approach: You can override the system branding block template via the block--system-branding-block.html.twig file (instead of using a preprocess hook).

On a Bootstrap theme, block--system-branding-block.html.twig looks like this:

```
{% block content %}
  {% if site_logo %}
    <a class="logo navbar-btn pull-left" href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">
      <img src="{{ site_logo }}" alt="{{ 'Home'|t }}" />
    </a>
  {% endif %}
  {% if site_name %}
    <a class="name navbar-brand" href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}</a>
  {% endif %}
  {% if site_slogan %}
    <p class="navbar-text">{{ site_slogan }}</p>
  {% endif %}
{% endblock %}

```

You can alter the href of those links to point anywhere you'd like, for example:

```
<a class="logo navbar-btn pull-left" href="/some/other/page" title="{{ 'Home'|t }}" rel="home"><src="{{ site_logo }}" alt="{{ 'Home'|t }}" /></a>

```

---
Tags: 8, blocks
---


# Question
Title: How to create node twig template suggestions for one content type?
I need to create a node twig template that is just for the `basic page` content type that based on a custom field on the content type. We have other content type like `Article`, `Blog`, `Products` that do not need these specific twig template.

**How would we create twig templates based on the `field_type` so that it only applies to the basic page content type?**

Here is what we tried, but couldn't find how we could detect for the `basic page` content type and the value for the `field_type`. We tried `ksm($suggestions)` and `ksm($variables)`, but it does not print which implies that the hook isn't called even after clearing cache.

```
function mymodule_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  // This is what we are looking for.
  $node_bundle = $node->bundle();
  if($node_bundle == 'page') {
    // we want something like this.
    $node_type_value = $node->field_type->value;
    $node_view_mode = $node->view_mode; // not sure what this would be.
    $suggestions[] = 'node__' . $node_bundle . '__' . $node_type_value
  }
}

```

# Answer
> 1 votes
You need to get the values first you want to work with. For example the node object is inside `$variables['elements']['#node']`. In the sample below `field_foobar` is a text field. Depending on what your field type is you may need to get the value you want a little bit differently. And also maybe sanitize it first before you use it in a template suggestion (replace spaces etc.).

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  /** @var \Drupal\node\Entity\Node $node */
  $node = $variables['elements']['#node'];
  if ($node->bundle() === 'page') {
    if (!$node->get('field_foobar')->isEmpty()) {
      $value = $node->get('field_foobar')->first()->getValue()['value'];
      $view_mode = $variables['elements']['#view_mode'];
      $suggestions[] = 'node__page__' . $view_mode . '__' . $value;
    }
  }
}

```

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


# Question
Title: How to filter only first level menu links using views?
I have created the menu with the below structure,

* A
    + Link A1
    + List A2
        - Link A21
        - List A22
* B
    + Link B1
        - Link B11
        - List B12
    + List B2

Now my requirement is to get only first level menu links i.e **A and B only** using views module.

# Answer
I found the answer by adding Filter criteria as given below in views. Please improve this answer if I am not correct.

```
Parent plugin ID (not_begins menu)

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to call hook_theme_suggestions_HOOK_alter twice, if node is shown twice?
What I want to do is show the contact person responsible for a language in two different regions simultaneously, but with different twig templates.

I therefore have two regions: footer and sidebar

I have a node type of Contact Person (contact\_person) with several fields and I create one content of this node type per language (using Only One module)

I started with creating a View which get's me the correct content, but with two blocks. This gave me the same issue. I tried to circumvent this issue by creating two Views (`Contact Person (Footer)` and `Contact Person (Sidebar)`) each with one block display.

I changed the system names in the views to be `block_sidebar` and `block_footer` instead of the default `block_1` for added clarity.

I used these blocks in the Block Layout, where I added both blocks to their respective regions.

If I examine the theme suggestions, the blocks behave as expected

### For Sidebar:

`block--views-block--contact-person-sidebar-block-sidebar.html.twig`
`___________________________________^^^^^^^_______^^^^^^^`

### For Footer:

`block--views-block--contact-person-footer-block-footer.html.twig`
`___________________________________^^^^^^_______^^^^^^`

But when I examine the node theme suggestions, the are the same

### For Sidebar *AND* Footer:

`node--view--contact-person-sidebar--block-sidebar.html.twig`
`___________________________^^^^^^^________^^^^^^^`
if the Sidebar block get's rendered first.

If I swap the blocks in their regions (Sidebar Block goes inside the Footer region and Footer block inside the Sidebar region) and clear all the caches, the footer block is rendered first and so the theme suggestions changed for both of them:
`node--view--contact-person-footer--block-footer.html.twig`
`___________________________^^^^^^________^^^^^^`

These suggestions seem to generated in the Views module itself

```
// File core/modules/views/views.module
// ...
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function views_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $node = $variables['elements']['#node'];
  if (!empty($node->view) && $node->view->storage->id()) {
    $suggestions[] = 'node__view__' . $node->view->storage->id();
    if (!empty($node->view->current_display)) {
      $suggestions[] = 'node__view__' . $node->view->storage->id() . '__' . $node->view->current_display;
    }
  }
}
// ...

```

If I try to debug this I discovered that the hook\_theme\_alter function is only called once for the node. I isn't called a second time, because the `hook_theme_suggestions_HOOK_alter` was already called for this very node.

**How can I say Drupal that I want these suggestion alter function to be called a second time, if one node is shown a second time on the same page?**

# Answer
Nodes are rendered only once per view mode and then are cached. So the easiest solution would be to configure different view modes. Which makes sense in this case, these are in fact two different displays of the same node. Another benefit, you don't need this hook, because view modes have theme suggestions out-of-the-box.
> 3 votes

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


title: How to redirect on Access Denied

text:
# Question
Title: How to redirect on Access Denied
When getting a 403 error, Drupal is not redirecting to the URL configured in the Site Information settings. Instead, it keeps the URL in the address bar of the browser, uses the page template (`page--XYZ.html.twig`) for that same URL and **only the content of the page** (`{{ page.content }}`) reflects the URL I've configured in the site information settings.

Does anyone know how to get a full redirect to the configured 403 page?

# Answer
> 1 votes
Well, by now I just found that my question is technically wrong. Drupal is not supposed to do any redirect (HTTP 301/302) on access denied errors (HTTP 403). This is not how HTTP works (as mentioned by @Hudri in the comments).

On an access denied error, Drupal **replaces** the actual page content with the one from the "*Default 403 (access denied) page*" site setting. **The URL being accessed is valid. It's just that we don't have the permission to see its contents**.

I just figured what I was actually wanting to do, was telling Drupal not to use that page's regular template file (`page--xyz.html.twig`) on the case of an HTTP 403 error, but instead, to use a different one.

Found useful instructions on how to theme HTTP error pages here: https://www.axelerant.com/resources/team-blog/customizing-http-error-pages-in-drupal-8

---
Tags: 8
---


title: Fetch value from JSON

text:
# Question
Title: Fetch value from JSON
I have a field in drupal "field\_xyz". it stores json values. JSON looks like this:

{"Id\_-\_SiteWasteProductAction":"34638393224", "Postcode": "CSF 12CF"}

I want to fetch postcode value from this json using mysql query

i used

```
$query = $connection->query("SELECT @@sql_mode"); //for group by (php 7.0)
$query = $connection->query("set @@sql_mode=''"); //for group by (php 7.0)
$query = $connection->select('node_revision', 'n');
$query->fields('n', ['vid', 'nid']);
$query->fields('shad', ['field_xyz_value']);
$query->join('node__field_xyz', 'shad', 'n.vid = shad.revision_id');

```

i fetch postcode value from url-

```
   $filter_postcode_value = \Drupal::request()->query->get('filter_postcode_value');//postcode

```

and i use this condition

```
   if(!empty($filter_postcode_value)){
          $query->condition('an.field_xyz_value->"$.Postcode"', '%' . db_like($filter_postcode_value) . '%' ,'LIKE');
     }

```

output is coming out as-

```
    Column not found: 1054 Unknown column 'shad.field_sheet_all_data_value.Postcode

```

Please help!

# Answer
If I recall, you need to use the json\_ specific query functions to query within a tuple.

There is an example query on the JSONB module page demonstrating this. This module is not required, but does have an example of how to write a `db_query`:

> If you wanted to query for JSON records that were in the 2005-2006 timeframe for high school graduates, you could do the following:

```
$results = db_query("SELECT point
      FROM (SELECT jsonb_array_elements(field_jsondata_value) point FROM {node__field_jsondata}) points
      WHERE point->'DataType' = :type
        AND point->'TimeFrame' = :frame
        AND point->'Education' = :education",
      array(':type' => '"Percent"', ':frame' => '"2005-2006"', ':education' => '"High school graduate"'));

```

> You would receive the fourth object only. The function jsonb\_array\_elements expands data at runtime to query data in this manner.

I don't think Drupal core supports the usage of these functions outright, maybe it does, but I accomplished this in both Drupal 7 and 8 with `db_query`.
> 2 votes

---
Tags: 8, database
---


# Question
Title: How to generate different image styles at upload?
I'm using Drupal 8. Is there a hook for generating image from image style or better one module?

For example. I upload an image. When image is displayed for the first time, Drupal generates image style. Can I hook to that event somehow, at best when uploading the image?

# Answer
Ah yes, you are right.

> Image derivatives will be automatically generated once requested and not-yet existing.

That's a quote from my own answer to a similar question. I guess you could try to hook into the upload somehow like Image Style Warmer does it, or simply try that module out yourself.

> ### Synopsis
>
> The Image Style Warmer module provides options to create image styles during upload or via queue worker. So configured image derivates already exists when they are requested.
> 1 votes

# Answer
You don't need to write code to generate image styles in Drupal.

This functionality is provided by the Image module in Drupal core.

From the documentation:

> To create or change image styles:
>
> 1. Choose *Administration \> Configuration \> Media \> Image styles*.
> 2. Add or select a style to edit its settings.
> 3. When configuring styles you can add effects: crop, scale, resize, rotate, and desaturate (other contributed modules provide additional effects). For example, by combining effects as crop, scale, and desaturate, you can create square, grayscale thumbnails.
> 4. Save the settings.
>
> To start using the defined styles they must be assigned to the display of a content type.
>
> For each display (e.g. "default" or "teaser"), a different style can chosen.
>
> To assign a style:
>
> 1. Choose Administer \> Structure \> Content types \> Manage display.
> 2. Choose the display (e.g. "default" or "teaser") via the tab buttons.
> 3. Click the gear wheel button to choose an image style; you are also able to link the image to the node.
> 4. Save the settings.
> 5. Check the content that contains the image style in question to see your new styles at work.

By design, properly configured image styles should be generated when the image is first uploaded, *not* when it is displayed for the first time. (NOTE: I was wrong about this. See @leymannx comments below and answer above!)

Additionally, whenever you change an image style configuration, the module automatically refreshes all created images by flushing the imagecache.

Also from the documentation:

> The Drupal 6 imagecache module was introduced into the Drupal 7 core. Since then, the option to 'flush' the image presets has changed. In the Drupal 7 UI, this 'Flush' image styles preset option was removed, but now, just resaving your image style will flush the image cache.

If you need to flush all image styles (eg. after adjusting the JPEG quality), you can execute `drush image-flush`, use the Image style flush module, or run the following code (for instance using Devel):

```
// Flush all image styles in Drupal 7.
foreach (image_styles() as $style) {
  image_style_flush($style);
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Checking for an Acquia Environment variable
Trying to check for an Acquia cloud environment variable in my twig template, but its not working in Dev or in Production.

Similar question is answered here, but I still can't get the twig syntax right: Is there a way to get (and use) an environment variable in my Twig template?

This is a snippet from the page.html.twig file.

```
{% if AH_SITE_ENVIRONMENT == 'prod' %}
  // Javascript Analytics Code
{% else %}
  <!-- env is {{ AH_SITE_ENVIRONMENT }} -->
{% endif %}

```

# Answer
> 2 votes
The other question mentioned having passed that variable from a preprocess function to the template first. I guess that can be done using PHP's `getenv` then. Let me just try that out.

Yep, that works.

```
/**
 * Implements template_preprocess_page().
 */
function MYTHEME_preprocess_page(&$variables) {
  $variables['my_environment'] = getenv('AH_SITE_ENVIRONMENT');
}

```

Then continue in `page.tpl.php`.

```
{% if my_environment == "prod" %}
  // Javascript Analytics Code
{% else %}
  <!-- env is {{ my_environment }} -->
{% endif %}

```

---
Tags: 8, theming
---


# Question
Title: How to change taxonomy term ID to term name?
I'm trying to change path of my site which is based on taxonomy tags. Default path of my site in this context is `/taxonomy/term/120` (or other number - TID).

In Drupal 7 option to change TID to term:name was easy using **Contextual filter** and **Filter value type** set to **Term name coverted to Term ID** (shown eg here: Views contextual filters taxonomy name).

The big problem I'm struggling with is that there is no **Filter value type** field (dropdown menu) in Drupal 8. This is picture of my screen:  So I **cannot change TID to term name**.

Have anyone idea how I can exchange them. Is there another way to change them in Drupal 8?

# Answer
You first have to create a relation with the taxonomy terms by adding the relationship with the taxonomy list or `Taxonomy terms on node`. Once you have added the relation, you can now add a contextual filter called `name` with the category `Taxonomy term`. This way you can pass the taxonomy term by name to the filter.
> 1 votes

# Answer
I have found that a relationship to taxonomy term: field will do just about the same thing as taxonomy term: on node
> 0 votes

---
Tags: 8, views
---


# Question
Title: 'default_value' plugin does not run if 'get' returns null or empty value
I’ve got a D7 to D8 migration where I’m trying to migrate a field with a null value in D7 to a default value in D8. Process pipeline is similar to this:

```
  field_privacy:
    -
      plugin: get
      source: field_office_privacy
    -
      plugin: default_value
      default_value: 'open’

```

It seems if the field value is null, the default\_value plugin never runs.

When D7 has a non-null value, then the field migrates perfectly via the `get` plugin. The D8 API documentation gives this pipeline as an example of exactly what I'm trying to do, yet I cannot get it to work. When I should get a value for all 164 items selected by the migration source, I instead only get 132, which precisely matches the number of fields in D7 that have non-null values.

How can I set a default value when `get` doesn't find a value?

# Answer
> 2 votes
The catch here is that you should not use the `get` process plugin explicitly. The behaviour you want is already implicitly used the `default_value` plugin. This is because get is the default process plugin and can be shorthanded. In your case this should work:

```
 field_privacy:
   plugin: default_value
   source: field_office_privacy
   default_value: 'open’

```

Also see documentation for get and default\_value

---
Tags: 8, migrations
---


# Question
Title: Change the front page basing on the domain
I need to write a custom module to map some static pages used as front page to some specific domains. For example,

* If domain is www.abc.com, the front page should be static\_page\_1
* If the domain is www.bcd.com, the front page should be static\_page\_2

I have made a form for administrator users to enter the domain name and the static page they want as front page, but now I don't have any idea on where and how to write the code for detecting the domain name and set the front page. Any information and suggestion will be very appreciated.

# Answer
I've already find the answer by referring to Programmatically set the front page per site?. It is much simpler than the reference, because I just want to map the domain with my static page and I don't have a multisite drupal. So, I just add an event subscriber and put all the mapping there.

> In the getSubscribedEvents method you need to set the weight to something greater than 30 which overrides the Page Cache and Dynamic Cache.

```
$events['kernel.request'] = ['kernel_request', '35'];

```

> Add this function in the same event subscriber file

```
public function kernel_request(Event $event) {
$config = \Drupal::configFactory()->getEditable('system.site');
$site_path = \Drupal::service('site.path');
$site_path = explode('/', $site_path);
$site_name = $site_path[1];

if ($site_name === 'site2' && $event->getRequest()->getPathInfo() == '/') {
  $config->set('page.front', '/node/239')->save();
}
else {
  $config->set('page.front', '/home-content')->save();

}
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Kanban-style view : Group nodes in a view into columns based on a field value
I have a custom node type in Drupal - Order - which has a status field. The status can have three values.

What I would like to do is create a view in which orders are grouped into columns based on their status - essentially a primitive Kanban board - and the columns are ordered in a particular way.

Is this possible and if so, how?

# Answer
> 1 votes
One possible solution would be to use the Views Field View module, which provides a Global: View option as a field in a view.

https://www.drupal.org/project/views\_field\_view

You would create a main page view, use the Table format. Then create an Embed display for each status that filters your items by that status.

Back on your main view you would add a Global: View field for each status and select your status displays.

I'll note that the main page view needs to bet set to show 1 item, so you don't have multiple rows of the same content. Each embed display would be set to show all items.

One issue with this method is the vertical alignment is in the middle of the table columns when there are is a different number of items per column.

It's a little bit hacky but may be a step in the right direction.

# Answer
> 1 votes
I don't think it is possible right now without custom programming (either within a theme or custom module)

You can probably get started with grouping your view based on the status field and than using CSS in your theme (`display:inline or float: left`) you can get all groups next to each other.

There could be more sorting criteria for each column within the view.

For extra functionality like dragging/dropping within status areas (changing status) you will need to create your your own module to handle drag drop events and do ajax calls to the backend.

There was some work done for openlucius (drupal 7) that you can look at https://www.drupal.org/project/openlucius\_board

# Answer
> 0 votes
Check out Content Planner Drupal 8 contrib module \- it provides Kanban planning.

> Drupal Content Planner helps you to create, plan and manage content. It offers a dashboard, a content calendar and a todo list. It's completely open source and free to use.

Feature highlights Content Planner dashboard

Editorial team widget Content status widget Custom views widgets Kanban activities

Create custom widgets with plugins ...

Also, see this issue here, writing about Kanban solutions in Drupal and other open source platforms: https://www.drupal.org/project/contrib\_tracker/issues/3046824

# Answer
> 0 votes
Another workaround to this Kanban board feature is to use multiple panels on a panels page. Combine with Views Auto Refresh for a more user friendly experience. Zero coding required.

---
Tags: views, 8
---


# Question
Title: Display the results of a form submit on the same page just under the form
I have created a form and it takes in 3 values which are Brand, Item and Zipcode. The values are queried and the results are fetched the database table. I want the results to be shown in a table

```
function form_example_form_submit($form, &$form_state) {
$sql3 = /*my select query*/

$result = db_query($sql3);
$records = $result->fetchAll();

//code to display table

 echo "<table border=1>";
   echo"<tr>";
    echo"<th>Retail Accounts</th>";
    echo"<th>Address</th>";
    echo"<th>City</th>";
    echo"<th>State</th>";
   echo "</tr>";
   foreach ($records as $record) {
    $record     = get_object_vars($record);
    echo "<tr>";
      echo "<td>";
        echo $record['Retail Accounts'];
      echo "</td>";
      echo "<td>";
        echo $record['ADDR'];
      echo "</td>";
      echo "<td>";
        echo $record['CITY'];
      echo "</td>";
      echo "<td>";
        echo $record['STATE'];
      echo "</td>";
    echo"</tr>";
}
echo "</table>";
}

```

The result is properly fetched but not displayed on the page.

I tried `$form_state['rebuild'] = TRUE;` but it displays the result on top of the page.

I want the result to be visible just below my form. How can I achieve that?

Any help is very much appreciated. Thanks in advance.

# Answer
As suggested in the comment the SQl query were made on the hook\_form and the hook\_form\_submit contains only the `$form_state['rebuild'] = TRUE;`. Detailed code is as follows:

```
function form_example_form($form, &$form_state) {

//your form fields or items

$form['submit_button'] = array(
 '#type' => 'submit',
 '#prefix' => '<div class="button-wrapper">',
 '#suffix' => '</div>',
 '#value' => t('Find my store'),
 '#attributes' => array('class' => array('btn btn-primary')),
);

/*-----Query database code Start--------*/

if(isset($form_state['values']['item-name'])){
  //get the values to variable
}

if(isset($zip_code)){

//setup the sql query

if(isset($sql3)){
  $result = db_query($sql3);
}
$records = $result->fetchAll();
$tot_records = count($records);
}

if(isset($tot_records)){
 if($tot_records>0){

  $form['result_table'] = array(
    '#type' => 'markup',
    '#prefix' => '<table border=0 class="table table-bordered">',
    '#markup' => '<tr><th>Store Name</th><th>Address</th><th>City</th><th>State</th></tr>',
  );

  $i=0; $j=0;
  foreach ($records as $record) {

    $record_in_array = json_decode(json_encode($records[$i]), true); //Convert object to array

    $form[$j]['result_table1']= array(
      '#type' => 'markup',
      '#markup' => '<tr>',
    );

    $form[$j]['result_table2']= array(
      '#type' => 'markup',
      '#prefix' => '<td>',
      '#suffix' => '</td>',
      '#markup' => $record_in_array['sql column name1'],
    );
    $form[$j]['result_table3']= array(
      '#type' => 'markup',
      '#prefix' => '<td>',
      '#suffix' => '</td>',
      '#markup' => $record_in_array['sql column name2'],
    );
    $form[$j]['result_table4']= array(
      '#type' => 'markup',
      '#prefix' => '<td>',
      '#suffix' => '</td>',
      '#markup' => $record_in_array['sql column name3'],
    );
    $form[$j]['result_table5']= array(
      '#type' => 'markup',
      '#prefix' => '<td>',
      '#suffix' => '</td>',
      '#markup' => $record_in_array['sql column name4'],
    );

    $form[$j]['result_table6']= array(
      '#type' => 'markup',
      '#markup' => '</tr>',
    );

    $i++;
    $j++;
  }

  $form['result_table7']= array(
    '#type' => 'markup',
    '#suffix' => '</table>',
  );

  }
 }

/*-----End Query database code--------*/

return $form;

 }

 function form_example_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
 }

```

Hope this helps!
> 1 votes

---
Tags: 7, forms, search
---


# Question
Title: Updating Drupal project using Composer fails
I have site (which is originally installed also with composer) with drupal core version 8.7.2. I'm trying to update it to latest 8.7.8. When I do:

```
composer outdated "drupal/*"

```

I get the list of all outdate and for core I get row:

```
drupal/core                       8.7.2       8.7.8       Drupal is an open source content management platform powering millions of websites ..

```

But when I try:

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

```

I get:

```
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files

```

In composer.json core is added under require as (I just followed install docs - didn't change anything by hand):

```
"drupal/core": "^8.7.0",

```

That was suspicious to me so I tried replacing it with:

```
"drupal/core": "8.*",

```

But result was the same - nothing to update.

That message about phpunit/phpunit-mock-objects dependency is in green so I doubt that it causes this update to fail, but I'm not sure.

Why composer says that there's nothing to update?

**Update:**

Tried also:

```
composer prohibits drupal/core:8.7.8

```

and it says:

```
webflo/drupal-core-require-dev  8.7.2  requires  drupal/core (8.7.2)

```

And I really have inside composer.json:

```
"require-dev": {
    "webflo/drupal-core-require-dev": "^8.7.0"
},

```

Also tried:

```
composer update drupal/core --with-dependencies --no-dev

```

which removed dev dependencies, but also didn't update drupal core. How to solve this?

# Answer
Normally you can simply update core and all extensions in a single pass:

```
composer update

```

Only if this doesn't work, try to update core in a separate step by following the procedures described in the drupal composer project:

```
composer update drupal/core webflo/drupal-core-require-dev "symfony/*" --with-dependencies

```

See https://github.com/drupal-composer/drupal-project
> 2 votes

# Answer
Solved it. I had to add that "webflo/drupal-core-require-dev" to update command to be updates as well, because without that core couldn't be updated:

```
composer update drupal/core "webflo/drupal-core-require-dev" --with-dependencies

```

Saw that in "known issues" section. :/ It's really strange - what's the purpose of `--with-dependencies` when I have to add dependencies manually after all...
> 2 votes

---
Tags: 8, updating, composer
---


# Question
Title: alternative to storing api keys in migration yaml files?
I've created a yaml file to import Twitter timeline items (not super simple since documentation on the `migrate_plus` OAuth plugin seems to be few and far between); this migration naturally requires the use of ostensibly-secret API information. I'd like to keep this out of the yaml and I've seen answers (like this one) that talk about setting things in code, but I'm wondering if there's another customer-serviceable way. For example, here's my config file, called `migrate_plus.migration.migrate_sample_twitter`:

```
id: migrate_sample_twitter
label: Sample Twitter Migration
dependencies:
  - migrate
  - migrate_plus
status: true

source:
  plugin: url
  data_fetcher_plugin: http
  authentication:
    plugin: oauth2
    base_uri: 'https://api.twitter.com'
    token_url: /oauth2/token
    grant_type: client_credentials
    client_id: <twitter app consumer key>
    client_secret: <twitter app consumer secret>

  urls: https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=tmountjr

  fields:
    -
      name: id
      label: Tweet ID
      selector: id_str

destination:
  plugin: table
  table_name: twitter_import
  id_fields:
    id:
      type: string

```

Now, running `drush cget migrate_plus.migration.migrate_sample_twitter` drops all that information on the console, which is fine. BUT, I'm unable to retrieve any information deeper than that. What I was hoping to do was, in my `settings.local.php`, specify this:

```
$conf['migrate_plus.migration.migrate_sample_twitter.source.authentication.client_id'] = 'consumer key here'
$conf['migrate_plus.migration.migrate_sample_twitter.source.authentication.client_secret'] = 'consumer secret here'

```

...and then just omit the `client_id` and `client_secret` keys from the yaml file. But that doesn't seem to work; when I make those changes and run `drush migrate-status` I get an error: `The config is missing the following key: "client_id"`.

So short version of this question: is there any way to omit values from an exported yaml file and instead have those values stored in a user-editable settings file that can be `.gitignore`d from the repo?

# Answer
In Drupal 8, If the migration is one that is a config entity (shows up in /config rather than in migrations/) values can be overridden in settings.php or environment specific settings.

```
// Set migration settings from environment variables.
$config['migrate_plus.migration.node_article']['source']['urls'] = [getenv('CMS_ARTICLE_API_URL') . '/services/articles/facilities/all'];
$config['migrate_plus.migration.node_article']['source']['headers']['apikey'] = getenv('CMS_ARTICLE_API_KEY');

```
> 2 votes

# Answer
I'm not entirely sure if this will work in your use case, but I know the `key` module is designed to keep secret keys outside of any config files. Then you just ask the `key` service for whatever key you need and it returns it to you. It can store the key in several different formats.
> 0 votes

# Answer
$conf is 7.x, Drupal 8 uses $config for configuration overrides and the syntax is \`$config\['config\_object'\]\['property.path.key'\].

In your case, should be something like:

$config\['migrate\_plus.migration.migrate\_sample\_twitter'\]\['source.authentication.client\_id'\] = 'consumer key here';

That should work but keep in mind that migrations are cached unless you disable the cache by setting the bin to null, so don't forget to clear caches.
> 0 votes

---
Tags: 8, migrations, configuration
---


# Question
Title: ContentEntityForm buildForm method parent out of memory
I have the following issue with my form class that extends the ContentEntityForm class.

When calling the parent **buildForm** which is needed my system runs out of memory.

```
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    // Here is already runs of memory. $form is never initiated.

    /* @var $entity \Drupal\sg_configuration_rule\Entity\ConfigurationRule */
    $entity = $this->entity;

    $form_state->set('old_cron_value', $entity->get('cron_settings')->first()->value);

    $type = FALSE;

    if (!$entity->isNew()) {
      $type = $entity->getPluginInstance()->getPluginId();
    }

    if ($entity->isNew()) {
      $type = \Drupal::request()->query->get('type');
      if (!$type) {
        return new RedirectResponse(Url::fromRoute('configuration_rule.add_form_step1')->toString());
      }
    }

    if ($type) {
      try {
        /** @var \Drupal\sg_base_api\Plugin\BaseApiPluginInterface $enabled_api */
        $enabled_api = $this->baseApiPluginManager->createInstance($type);
      }
      catch (PluginException $exception) {
        LoggerService::error($exception->getMessage());
        return new RedirectResponse(Url::fromRoute('configuration_rule.add_form_step1')->toString());
      }

      $enabled_api->configRuleForm($form, $entity);

      $form['plugin_type']['widget'][0]['value']['#value'] = $type;
      $form['plugin_type']['widget'][0]['value']['#access'] = FALSE;
      $form['plugin_type']['widget'][0]['value']['#disabled'] = TRUE;
      $form['server_node']['widget']['#options'] = $this->getServerNodesByType($enabled_api->entityType());
    }

    $form['user_id']['#access'] = FALSE;

    return $form;
  }

```

When i check the parent function i noticed that the line:

$form = $this-\>form($form, $form\_state); is causing this in the class EntityForm(Core method).

```
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // During the initial form build, add this form object to the form state and
    // allow for initial preparation before form building and processing.
    if (!$form_state->has('entity_form_initialized')) {
      $this->init($form_state);
    }

    // Ensure that edit forms have the correct cacheability metadata so they can
    // be cached.
    if (!$this->entity->isNew()) {
      \Drupal::service('renderer')->addCacheableDependency($form, $this->entity);
    }

    // Retrieve the form array using the possibly updated entity in form state.
    // This is causing my memory timeout.
    $form = $this->form($form, $form_state);

    // Retrieve and add the form actions array.
    $actions = $this->actionsElement($form, $form_state);
    if (!empty($actions)) {
      $form['actions'] = $actions;
    }

    return $form;
  }

```

If i comment that line out it is working fine but this is needed to save my values in config. Also this is core and should work.

Anyone else have this problem and knows the solutions to this?

Thanks.

# Answer
> 1 votes
Are you sure this is a coding error? Are you loading any large quantities of content in the form by any chance? Loading a lot of nodes in a select field, for instance, can generate memory overflows.

---
Tags: 8, forms
---


# Question
Title: Entity:media doesn't exist error when searching for url in "add link" in wysiwyg
When adding a link into a rich text field (**wysiwyg**) (see images bellow) and searching for a keyword the throbber icon keeps spinning and that's it.

I looked at the error logs and found the following, this was working recently, no idea what happened.

```
Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "entity:media" plugin does not exist. Valid plugin IDs for Drupal\linkit\MatcherManager are: entity:contact_form, email, entity:contact_message, entity:feeds_feed, entity:node, entity:scheduled_update, entity:taxonomy_term, entity:user, entity:file, front_page"

```

If anyone has an idea what happened? **Drupal 8.7.3**

# Answer
> 0 votes
I had a similar problem, but not with entity:media, but with entity:shortcut

I ended up by deleting the matcher from the database.

It is in the datatable config under the name "linkit.linkit\_profile.ckeditor"

`SELECT * FROM config WHERE name= "linkit.linkit_profile.ckeditor";`

The data is stored in a serialized string. To remove it, you must be confident in editing serialized strings, which is a bit dangerous.

I used (UN)Serialize.me to convert the unserialized string to a JSON string, then edited the JSON in JSON Editor Online and back again.

I first tried to use drush to export the config, editing the config YAML file and then importing, but it yielded the same error.

---
Tags: media, wysiwyg
---


title: Create custom table with pagination

text:
# Question
Title: Create custom table with pagination
I have a function in a controller which shows data in table format. I need pagination and styling for the table. I tried as follow.

### MyController.php

```
public function my_requests() {
        //load the current user details
        $user= User::load(\Drupal::currentUser()->id());
        $user_id = \Drupal::currentUser()->id();

        //Query the database
        $query = \Drupal::entityQuery('node')
           ->tableSort($header)
           ->condition('status', 1)
           ->condition('type', "forward_proxy_request")
           ->condition('uid', $user_id)
           ->sort('nid' , 'ASC');
        $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
        $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
        $nids = $pager->execute();

        //creates the table header
        $header = [
                'Node id',
                'title',
                'Name',
                'Ip',
                'SLU',
            ];
        foreach ($nids as $nid) {
            $node = Node::load($nid);
            $row  = [
                'data' => [
                    $node->nid->value,
                    $node->title->value,
                    $node->field_p_name[0]->value,
                    $node->field_ip[0]->value,
                    $node->field_p_slu[0]->value,
                ],
            ];
            $rows[] = $row;
        }
        //Build the table
        $build = [
          'table'           => [
          '#prefix'        => '<h1>My Requests</h1>',
          '#theme'         => 'table',
          '#attributes'    => [
              'data-striping' => 0
          ],
          '#header' => $header,
          '#rows'   => $rows,
      ],
    ];
    //for pagination
    $build['pager'] = array(
        '#type' => 'pager'
    );

     return $build;
}

```

But it throws an error.

> Error: Call to undefined method `Drupal\\Core\\Entity\\Query\\Sql\\Query::extend()` in /var/www-drupal/modules/ga/src/Controller/MyController.php on line 196

Without `extendQuery`, it shows a plain table without any style.

>

How do I resolve this issue?

# Answer
Query extenders is a concept of low-level database queries. Content entities don't have that. The extenders just add the ability to do something, they don't do anything out of the box.

Both the pager and table sort functionality is built-in in entity queries. Just call `pager()` and `tableSort()` as you would do with a raw query after adding the extenders.
> 2 votes

# Answer
Here is an example of sortable table with pagination.

```
$header = [
  'id' => [
    'data' => $this->t('ID'),
    'specifier' => 'nid',
  ],
  'title' => [
    'data' => $this->t('Title'),
    'specifier' => 'title',
  ],
  'created' => [
    'data' => $this->t('Created'),
    'specifier' => 'created',
    // Set default sort criteria.
    'sort' => 'desc',
  ],
  'uid' => [
    'data' => $this->t('Author'),
    'specifier' => 'uid',
  ],
];

$storage = \Drupal::entityTypeManager()->getStorage('node');

$query = $storage->getQuery();
$query->condition('status', \Drupal\node\NodeInterface::PUBLISHED);
$query->condition('type', 'article');
$query->tableSort($header);
// Default value is 10.
$query->pager(15);
$nids = $query->execute();

$date_formatter = \Drupal::service('date.formatter');
$rows = [];
foreach ($storage->loadMultiple($nids) as $node) {
  $row = [];
  $row[] = $node->id();
  $row[] = $node->toLink();
  $created = $node->get('created')->value;
  $row[] = [
    'data' => [
      '#theme' => 'time',
      '#text' => $date_formatter->format($created),
      '#attributes' => [
        'datetime' => $date_formatter->format($created, 'custom', \DateTime::RFC3339),
      ],
    ],
  ];
  $row[] = [
    'data' => $node->get('uid')->view(),
  ];
  $rows[] = $row;
}

$build['table'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => $this->t('No content has been found.'),
];

$build['pager'] = [
  '#type' => 'pager',
];

```
> 6 votes

---
Tags: 8, database
---


title: Menu options missing in node form

text:
# Question
Title: Menu options missing in node form
In Drupal 8, despite the fact that there is a menu set for the content type, menu options are not showing in the node form.

I have disabled some menu modules in case they were interfering, but with no result.

What else can I check?

# Answer
> 0 votes
I found it. Silly me, it was the module Menu link (field), it actually says in the project page `The "Menu settings" tab is however removed from the node form and replaced by an field widget`. Argh, so much time looking for the reason, I didn't see that one when I uninstalled the ones that were interfering.

---
Tags: 8, forms, navigation
---


# Question
Title: View block filter by taxonomy term (field)
I am doing some block experiments because I'm new in Drupal and I want to know if I can create a view block to place X(more than one) times in the same page with different results by taxonomy term content.

I have a new content type which its related(a field) to a taxonomy term, and I want to place the same block for each taxonomy term created and inside the block show the created content related to that taxonomy term.

Ex: Imagine you have a taxonomy term called "Vehicle type". We create two terms into "Vehicle type"(car and truck). Now I create a content type called "Vehicle info" and I create.

I create a new "Vehicle info" content with a field "Vehicle Type" and check Reference type -\> Vocabulary -\> "Vehicle Type".

So now I want only a Block which can be placed twice in the same page and each block must list "Vehicle type" contents (one will have cars and the other trucks list).

I tried with contextual filters but when I place the block it does not shows to choose cars or trucks terms.

Many thanks :D

# Answer
> 0 votes
What is the criteria according to which the two different blocks will "know" whether you want to show cars or trucks?

---

If you want to control this, and have two separate Blocks showing different term-related content, you can create two Blocks but add **regular** Filters to them, filtering to show content related to either cars or trucks. The add each separate Block where you want them in a theme region.

---

If you want an automatic solution where a contextual filter does everything, you usually want to show either cars or trucks, but not both on the same page. Contextual filter will "sense" the context, it will recognize something on the page you're currently viewing, and where you placed the Block, and it will pass this context info to your Views, and filter results according to it. This is commonly used to place Blocks on Node pages, where you want to show other content that has been tagged with the same term. For example you're viewing Car1 node, and want the Block to list all the other nodes that have also been tagged with the term "car", so you would see Car2, Car3 etc. Besides the Contextual filter to pull the related content, you will also want the second contextual filter that would exclude the current node from the list, because it doesn't make sense to the visitor to see it there. You will need to adjust Contextual settings when placing the Block in a theme region.

---

The third option may sound the closest fitting to your description: Create One Block listing all nodes of that type, add the Field for the Taxonomy reference field, and under `Format` use the Taxonomy reference field to "Grouping field Nr.1". This will list all content but it will be Grouped in clusters based on the "car" or "truck" tags. You can edit the Field and "Exclude from display" because you will see it in the group title. There is no need for Contextual filters here as you want to list everything, you only want it separate into groups. Place the Block in a theme region and adjust visibility...

---

You can add **the same Block** to display in Drupal as many times as you want, in the same theme region, or in a different place, but you can't make it behave differently. A Block with a Contextual filter can show different results only if the Context it's surrounded with is different. But if on the same page, the context is the same, and the result will be the same.

BTW the "Vehicle type" is a Taxonomy Vocabulary, and the "car" is a Taxonomy Term.

---
Tags: taxonomy-terms, blocks, 8
---


# Question
Title: Add a class to a image for a specific view
I need add a class to a image for one specific views.
I tried:

* `theme_preprocess_field()` but it doesn't work
* `theme_preprocess_image()` but it's for all the images
* I tried what suggested in Override image template for field image\_formatter own, but it is too complex to simply add a CSS class
* This answer is the more accepted but I like other ways

Is it possible to override a field/image template file for a specific view?

# Answer
> 2 votes
If your view is outputting fields (& not a teaser) you can easily do it in the views UI.

1. Edit your view
2. Click on the image field
3. STYLE SETTINGS \> Customize field HTML \> Create a CSS class
4. Save

Now your image field should have a class:

---
Tags: views, 8
---


# Question
Title: Change remove from cart button to an image button
I want to change the remove-button, that removes line items from the cart to an image button representing a trash can like this:

The code I am using in a custom module looks like this:

```
<? php
function mymodule_custom_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state, $form_id) {
  foreach ($form['edit_delete'] as &$item) {
    $item['#type']='image_button';
    $item['#src']='sites/all/themes/mytheme/images/trash.svg';
    $item['#alt']='Remove';
  }
}

```

That code shows the icon instead of the text as expected, but unfortunately it introduces a major issue: now pressing the button doesn't remove the correponding line item, but wrongly successively removes the last added line-items. So when I added item1, item2, item3 to the cart in this order, then no matter which corresponding remove-button you press, item3 is removed. Next time, you press one of the remove-buttons of the remaining 2 line-items, then item-2 is removed. What's wrong with the above code?

# Answer
You need to unset the `#value` on your image\_buttons:

```
  $item['#type']='image_button';
  $item['#src']='sites/all/themes/mytheme/images/trash.svg';
  $item['#alt']='Remove';
  unset($item['#value']); // this line here

```

The line item that is deleted is determined by the `#triggering_element` in your `$form_data`. This element is determined by a function `_form_button_was_clicked($element, &$form_state)` in form.inc in the core.

It seems that when you a `#value` has been set on your image\_button, every image button is detected to have been clicked.

```
  // line 2227 in form.inc
  elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
    return TRUE;
  }

```

That means at the end of the ride, the last image button is always set as the #triggering\_element, and the last line item is always removed.

Unsetting the `#value` fixes that. Setting it to an empty string doesn't, somehow.
> 4 votes

# Answer
Instead of unsetting the `#value` property (which works, but I find it personally counter-intuitive), you could try setting it by using the `form_type_image_button_value()` function.

As an example:

```
function my_custom_module_form_views_form_commerce_cart_form_default_alter(&$form,
&$form_state, $form_id) {
  if (!empty($form['edit_delete'])) {
    foreach (element_children($form['edit_delete']) as $key) {
      $form['edit_delete'][$key]['#type'] = 'image_button';
      $form['edit_delete'][$key]['#src'] = 'sites/all/themes/trash.png';
      $form['edit_delete'][$key]['#alt'] = 'Remove';
      $form['edit_delete'][$key]['#value'] =
        form_type_image_button_value($form['edit_delete'][$key], NULL, $form_state);
    }
  }
}

```

The `form_type_image_button_value()` function is built to correctly extract the clicked image button's value from the $\_POST array taking browsers' peculiarities into account.

Good luck!

P.S.: Rewrote the hook implementation mildly to use `element_children()` when iterating through the line item delete elements.
> 2 votes

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


# Question
Title: How can I log in as any given user with Drush?
How do you login to a Drupal site if you do not have the password of the admin user or user 1 but still have access to the command line? Can I use Drush to log in to the Drupal site?

# Answer
> 4 votes
You can log in to any Drupal site if you have access to the command line and Drush, knowing either the username

```
$ drush uli username --no-browser

```

OR the user ID.

```
$ drush uli --uid 123 --no-browser

```

This will return you an URL that you can copy paste into your browser address bar and login as that user. You can leave out the `--no-browser` option when you want the command to directly launch the browser.

---
Tags: drush
---


# Question
Title: Steps to update vendor files after pulling changed composer.lock file
Let's say I work in a group and somebody else did `composer update` and pushed changed `composer.lock` file. I pulled it and now I have to do update too, to match the files from changed lock file.

In symfony I would delete vendor dir and run `composer install`. But in drupal not all files are in vendor dir.

What is the best workflow in this case? Should I manually delete old vendor files (what dirs exactly?) or there is some composer command that will do all the work for me - check current vendor files with versions from composer.lock file and update what has to be updated?

# Answer
> In symfony I would delete vendor dir and run composer install. But in drupal not all files are in vendor dir.
>
> What is the best workflow in this case? Should I manually delete old vendor files (what dirs exactly?)

See .gitignore in your project dir:

```
# Ignore directories generated by Composer
/drush/contrib/
/vendor/
/web/core/
/web/modules/contrib/
/web/themes/contrib/
/web/profiles/contrib/
/web/libraries/

```

In case you want to do a fresh start with `composer install` you can delete all files with:

```
git clean -fdx .

```

See https://www.git-scm.com/docs/git-clean/1.7.0
> 1 votes

---
Tags: updating, composer
---


# Question
Title: Approach to removing extra space at beginning of RSS file?
I ran the RSS xml file through W3C's RSS validator. The results say:

```
line 2, column 0: XML parsing error: <unknown>:2:0: XML or text declaration not at start of entity

```

I'm not sure how to approach this one. I searched on drupal.org and found these:

Based on the 2nd link, I tried placing an echo in the current template.php being used and the output appeared **after** the space right before the XML tag. That means the extra line in the RSS XML was placed there **before** the theming was invoked, right? Where should I look?

# Answer
> 2 votes
It seems all of the core and contrib modules were solid. It was the premium theme I used. The new line may not have been in template.php but it was in another file invoked from inside template.php.

My approach: In a local development environment, I added an echo statement in suspected areas. When I added echo at the bottom of the template.php, the output appeared as described in the question **but** when I placed the echo at the start of the template.php, the echo output appeared **before** the newline so I tracked down inside template.php what functions or other php files it was calling and soon, I found the dependency php file that had extra lines and fixed it.

This might differ in your case though.

# Answer
> 3 votes
Someone left a space at the beginning of a module.

```
[space]<?php

```

You can either try to find that bit of code with some tool or command OR put this in includes/bootstrap.inc at line 1112:

```
echo $filename;

```

The line number could change subject to updates to Drupal 7 so make sure it is inside the drupal\_load function:

```
if ($filename) {
    echo $filename;  //this is your included line
    include_once DRUPAL_ROOT . '/' . $filename;
    $files[$type][$name] = TRUE;

```

The result will be a long list of the modules being loaded in source code of the page. The space will be right after the module with the problem.

# Answer
> 2 votes
As JAmatulli said its mostly because someone left a space at very beginning in template or module or inc file

Here is another way of using grep to find the culprit. Mostly it is module file so...

```
grep -R -H '^  <?php' modules/**/*.module

```

This will check all module files withing your module folder ( i am a step back in my sites/all folder in my linux terminal to find culprit.) If you find two spaces leave two space between ^ and

If you just get the filename you can find its path via

```
locate -br 'culprit.module'

```

After correcting clear cache. :)

Improvising: `grep -R -H '^ *<?php' modules/**/*.module` Check for one or more spaces.

For windows: `findstr "^ *<?php" *.module` Current position inside modules directory, will check for all .module file withing modules and its sub directory.

# Answer
> 1 votes
Echo gives a long list of module names and finding a space is difficult. Instead I check for the space in the file name only.

```
if ($filename) {
  if (strrpos($filename, " ")) {
      echo $filename;
  }
  include_once DRUPAL_ROOT . '/' . $filename;
  $files[$type][$name] = TRUE;

```

# Answer
> 0 votes
In my case I had a leading space in my settings.php file. So the file was included before the first call of drupal\_load() in bootstrap.inc.

Showing all included files before the first include called by drupal\_load() gave me good insights of where to look at. I placed this code at the same place as in the answers above.

```
  if(!isset($GLOBALS['show_once'])){
      echo '<pre>'.print_r(get_included_files(), true).'</pre>';
      $GLOBALS['show_once'] = 5;
  }

```

To check every included file for a space or new line character near to php-tags:

```
$file_arr = get_included_files();

foreach ($file_arr as $file){

    if(preg_match('/(\s<\?php)|(\?>\s)/mi', file_get_contents($file)) > 0)
          echo 'The file '.$file.' contains spaces or new lines near the php-tags.<br>';

}

```

---
Tags: 7, theming, feeds
---


# Question
Title: Why is the apostrophe converted to ' in account activation e-mail?
In admin/config/people/accounts, the body of Welcome e-mail is (my site in in French):

```
user:display-name],

Un administrateur sur [site:name] a créé un compte pour vous. Vous pouvez maintenant vous connecter en utilisant le lien ci-dessous ou en le copiant dans votre navigateur :

[user:one-time-login-url]

Ce lien ne peut être utilisé qu'une seule fois pour vous connecter et vous redirigera vers la page où vous pourrez choisir votre mot de passe.

Après avoir choisi votre mot de passe, vous pourrez vous connecter sur [site:login-url] en utilisant :

nom d'utilisateur : [user:name]
mot de passe : Votre mot de passe

--  L'équipe de [site:name]

```

And in the e-mail received by the recipent, every apostrophe is changed to `'` like in the signature:

```
--  L'équipe de Le Jardin de Poissy

```

My version of Drupal is 8.7.8 and I use these modules: Mail System and Swift Mailer.

How can I let Drupal send properly formatted mails including apostrophes?

# Answer
> 1 votes
The easiest way to fix this is simply set the formatter to the Default PHP Mailer, if you want to stick to plain text mail.

This is a known bug in the SwiftMailer module where Html::escape is called, even for plain text. Bug report here: https://www.drupal.org/project/swiftmailer/issues/2937293 .

The Html::escape function declares:

```
  /*
   * This method escapes HTML for sanitization purposes by replacing the
   * following special characters with their HTML entity equivalents:
   * - & (ampersand) becomes &
   * - " (double quote) becomes "
   * - ' (single quote) becomes '
   * - < (less than) becomes <
   * - > (greater than) becomes >
   */

```

And that's where your `'` comes from.

---
Tags: 8, emails
---


# Question
Title: Node and Webform - Open, Close, Scheduled and Limit per source entity
I use Drupal 8 with webform. I have a content type called "Event" which has several fields of simple type and reference type for other content types.

In addition it has a field entity reference that points to a webform named "Team".

In "Event" in creation and edit mode, using the field\_permissions-8.x-1.0-rc2 module, I prevent access to authenticated users, because the default aspect is too complex for users who create content with the "Event" content type.

Among other things, if I do not prevent these settings, there is the possibility of changing the content type, which I would definitely not want.

For this reason I would like to link some simple fields of the "Event" content type to the "Team" webform.

* Status (open, closed, scheduled)
* Open (date and time)
* Closed (date and time)
* Max submissions (Total submissions limit per source entity)

Can anyone suggest me how to do it? Can it be done with Tokens? Should you use a Hook? I searched the net but I didn't find anything like that.

# Answer
> 1 votes
The Webform module includes the 'Webform Demo: Event Registration System' module which shows how to pass field related tokens from a Webform 'event' node to a webform submission.

# Answer
> 0 votes
Sorry if I insist, I keep asking myself without finding an answer: why in the section 'admin/structure/webform/manage/demo\_event\_registration/handlers' add-handler-\>custom settings, I find 'entity\_limit\_total' and can't find 'status', 'open\_date' and 'close\_date'?

---
Tags: 8, webforms
---


# Question
Title: Create a view from both user and node content
Is it possible in Drupal 8 to create a view from both Users and other content? I need a page that shows photo's from Users and logo's from a content type 'Organisation'.

If I make a page view from content, it will not give the possibility to select data from 'Users', and vice versa.

# Answer
> 1 votes
You would normally add a relationship to the view to achieve this. I'm guessing you've got a field on either the user entities the organization entities that references the other?

If you add that field as a relationship in the view that will expose that entity's fields for you to add into your view

---
Tags: views, 8
---


title: How to get image URL with GraphQL?

text:
# Question
Title: How to get image URL with GraphQL?
Let's say I have a field *image* in a *Product* entity. When I query a *Product*, I'd like to include the URL of the field *image* in the response.

The documentation states we can use `image_url`.

According to this issue I tried the following but I still get `null` for my field in the response.

```
$registry->addFieldResolver('Product', 'image',
  $builder->compose(
    $builder->produce('property_path')
      ->map('type', $builder->fromValue('entity:product'))
      ->map('value', $builder->fromParent())
      ->map('path', $builder->fromValue('field_image.value')), // not sure if value is the correct property here
    $builder->produce('image_url')
      ->map('entity', $builder->fromParent())
      ->map('field', $builder->fromValue('field_image'))
  )
);

```

# Answer
The property of `field_image.value` is wrong, it should be `field_image.entity`.

```
$registry->addFieldResolver('Product', 'image',
  $builder->compose(
    $builder->produce('property_path')
      ->map('type', $builder->fromValue('entity:product'))
      ->map('value', $builder->fromParent())
      ->map('path', $builder->fromValue('field_image.entity')),
    $builder->produce('image_url')
      ->map('entity', $builder->fromParent())
      ->map('field', $builder->fromValue('field_image'))
  )
);

```
> 2 votes

---
Tags: 8
---


title: Many items in one table cell

text:
# Question
Title: Many items in one table cell
I have a very complicated view, and I can't change the existing field structure (it's an established and functioning site). This is a simplification of the problem, but it has to happen this way, I can't turn it the other way around...

There are two node types (Author and Book), the Book type has an entity reference pointing at the Author.

The view I want to create lists the authors and needs to display all the Book titles in a single column (one author per row, all the book titles in one cell together).

How do I create the entry in the view, so it does that?

# Answer
> 1 votes
You might be able to get the result you want using the Views Aggregator Plus contrib module.

It's still in alpha for Drupal 8, but it allows you to group and aggregate results.

---
Tags: views, 8
---


# Question
Title: How to change an address field that says "There is data for this field in the database. The field settings can no longer be changed."?
How to change an address field that says "There is data for this field in the database. The field settings can no longer be changed."?

I want to add a "Company" field as part of the address. I don't want to ditch all existing address data. I don't want to create a separate field.

# Answer
> 0 votes
The message you see is for the settings of an *existing* field name "Adresse". It tells you that you can no longer change *its* field settings.

There is nothing that prevents you from adding a *new* field named "Company" to the content type. Just go to the "Manage fields" tab for the content type, fill in the "Label" (i.e. Company) and other settings for the new field, click "Add new field" and then "Save".

# Answer
> 0 votes
This is an case where *you* know that the change won't destroy existing data, but Drupal doesn't have the ability to figure that out, so it blanket blocks all such requests.

Here's an example that manipulates radio options, but the technique for changing an address field will be fundamentally the same:

```
/**
 * Updates allowed values for field_custom_radio_buttons.
 */
function mymodule_update_8001(&$sandbox) {
  // Queries for relevant nodes already using that field.
  $nids = \Drupal::entityQuery('node')
    ->condition('type', 'my_custom_content_type')
    ->condition('field_custom_radio_buttons', 'green')
    ->execute();
  // Loads queried nodes.
  // NOTE: If you have a non-trivial number of nodes to modify,
  // you should use the Batch API to drive your update function instead.
  // @see https://api.drupal.org/api/examples/batch_example%21batch_example.install/function/batch_example_update_8001/8.x-1.x
  $nodes = Node::loadMultiple($nids);
  // Updates field_custom_radio_buttons values.
  // Replaces any “green” values with “blue”.
  $updated_value_map = [
    'green' => 'blue',
  ];
  /** @var \Drupal\node\Entity\Node $node */
  foreach ($nodes as $node) {
    $node
      ->set('field_custom_radio_buttons', $updated_value_map[$node->field_custom_radio_buttons->value])
      ->save();
  }

  // Updates field storage config for field_custom_radio_buttons.
  // @see https://www.drupal.org/node/2012896
  // @see https://www.drupal.org/docs/8/api/update-api/updating-entities-and-fields-in-drupal-8#example-updating-a-field-from-an-obsolete-type-to-a-new-type
  $old_config = FieldStorageConfig::loadByName('node', 'field_custom_radio_buttons');
  $new_config = $old_config->createDuplicate();
  $new_config->original = $new_config;
  $new_config->enforceIsNew(FALSE);
  $new_config
    ->setSetting('allowed_values', [
      'red' => 'red',
      'blue' => 'blue',
    ])
    ->save();
}

```

---
Tags: 7, entities
---


# Question
Title: redirect after login in drupal without impacting the password reset functionality
The problem:

When using hook\_user\_login to redirect a user to the correct language this is also triggered during password reset. And the hook params do not provide a way to deal with this.

This How can I redirect users on login based on their chosen language? post details multiple not working concepts.

And i can't comment cause of the silly reputation thing, while i'm a developer for over 10 years... (getting tired)

I guess the form alter is the ONLY way.

# Answer
> 1 votes
hook\_user\_login is as you'd expect for when someone goes from anonymous to authenticated. This happens by using the login form and by using a password reset link.

Having a look on Drupal's API site is always worthwhile as people have usually commented on comment occurances like this. For example on https://api.drupal.org/api/drupal/modules%21user%21user.api.php/function/hook\_user\_login/7.x it has exactly what you're describing and recommends using something like:

```
if((!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset')){
  //your redirect code
}

```

But also using form\_alter would also be perfectly fine really as you want to target a specific action of logging in via a specific form

---
Tags: 7
---


# Question
Title: Show workflow transition bar in all states
I've created a custom workflow using the workflow module with the transitions listed below and I've noticed that when going to the view page of a node the workflow 'bar' that lets you transition a node between states only appears when it's set for review.

From what I can gather this is because only when it's in the review state is it considered moderated content which is also why it appears on the "Moderated Content" view. What I'd like is to have that appear no matter the moderation state it is in. How could I accomplish this?

**States**

* Draft
* Review
* Published

**Transitions**

* Draft || Review || Published \> Draft
* Review \> Published
* Draft \> Review

# Answer
> 0 votes
I worked out what the issue is, you can only see that bar when you're looking at the Latest Version of a node (using the "Latest Version" tab) not when viewing the latest published version of the node (using the "View" tab).

So this is now resolved by checking if they have access to the "Latest Version" tab of a node (basically checking that exists) and sending them to that if it does, otherwise sending them to the "View" tab. The code below does it and is called from `hook_node_insert` & `hook_node_update` in my custom module `.module` file.

```
function send_user_to_view_page_after_save(NodeInterface $node) {
  $nid = (string) $node->id();

  if (!is_null($nid)) {
    $alias = Drupal::service('path.alias_manager')->getAliasByPath("/node/{$nid}");
    $url_service = new Url("entity.node.latest_version", ["node" => $nid], []);

    if ($url_service->access() === TRUE) {
      $response = new RedirectResponse("/node/{$nid}/latest");
      $response->send();
    }

    $response = new RedirectResponse($alias);
    $response->send();
  }
}

```

---
Tags: 8, nodes, workflows
---


# Question
Title: How do I disable caching for the Forum module or, alternatively, how do I fix caching?
I use the normal standard Drupal Forum module with a clean Drupal 8 installation. After I have installed it, I have a problem where "2 new posts" shows for all users. In other words, the /forum page is caching and showing the cached page of one user for the other user.

So I have two options

1. Disable caching for /forum \<--- I don't mind doing this for now, as there aren't many users at the moment so I have time to fix this properly later.
2. Figure out why this page is caching the way it is. As mentioned, I am using a clean installation with hardly any confirm and this still happens.

Can someone confirm if the /forum page normally does this or if something is probably wrong with my installation? Or maybe I'm missing some setting? Or maybe caching is meant to be disabled for this to work?

Any help would be greatly appreciated!

# Answer
This documentation is the most suitable for your query: https://www.drupal.org/docs/8/api/cache-api/cache-contexts

Please learn all the details on that page and the other associated page. This may resolve your issue.

Thank you.
> -2 votes

---
Tags: 8, caching
---


# Question
Title: How to get node's view mode in hook_page_attachments?
I need to get the node's view mode so that in the `mymodule_page_attachments`, I can add libraries conditionally if the node's view mode is set to `full` or `default`. I tried the following but not able to get the node`s view mode once I retrieve the`$node\` object.

**How to get node's view mode in hook\_page\_attachments?**

Here is what we tried:

```
function mymodule_page_attachments(array &$attachments) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if(is_object($node)) {
     // we tried printing but that didn't result any view_mode field.
     ksm($node);

    // Goal
    if($node['view_mode'] == 'full' or $node['view_mode'] == 'default') {
       // proceed with my logic.
    }
  }
}

```

# Answer
To attach a library only when a node in a certain view mode is displayed you can use `hook_entity_view`/`hook_ENTITY_TYPE_view` like following.

```
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $node = $entity;
  if ($node->bundle() === 'page') {
    if ($view_mode === 'full') {
      $build['#attached']['library'][] = 'MYMODULE/foo';
    }
    elseif ($view_mode === 'default') {
      $build['#attached']['library'][] = 'MYMODULE/bar';
    }
  }
}

```
> 4 votes

# Answer
Drupal does not distinct between full and default here. If no full viewmode is given for a certain node type than the default viewmode is used. So you could check whether a given node type implements the full viewmode and apply your conditional logic based on this, like this:

```
function hook_page_attachments(array &$attachments) {
  /* @var \Drupal\node\Entity\Node $node */
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $view_modes = \Drupal::service('entity_display.repository')->getViewModeOptionsByBundle('node', $node->bundle());
    if (isset($view_modes['full'])) {
      // this is full
    }
    else {
      // this is default
    }
  }
}

```
> 1 votes

---
Tags: 8, nodes, hooks
---


# Question
Title: How to load content on different domain with jquery .load()
using this code in the drupal block:

```
<script type="text/javascript">
$('#block-block-16').load('http://nashmir.kz');
</script>

```

but it won't load content from domain nashmir.kz. With local files it works well. Can somebody throw me a working example on how to load content from another domain?

# Answer
> 4 votes
You can use a local PHP script to pull the external data. Then use AJAX to show it in a block.

```
      // ajax call to a php script
      $.post("/sites/scripts/my_script.php",
        { "post_parameter" : "post_value" },
        function(data){
          // put the result into a div
          $('#result').html(data);
        }
      );

```

Then again if you only want to display an external website, you can use an `<iframe>`.

# Answer
> 3 votes
Cross domain can not be invoked with .load(). It's a security problem. Ajax cross domain is XSS. http://en.wikipedia.org/wiki/Same\_origin\_policy If the other site has some scripts, it can mess with your page basically.

What you need is jsonp or cors https://developer.mozilla.org/en/HTTP\_access\_control

cheers T

# Answer
> 0 votes
There is a little hack with php. And it works not only with Google, but with any website you don't control and can't add Access-Control-Allow-Origin *

We need to create PHP-file (ex. getContentFromUrl.php) on our webserver and make a little trick.

**PHP**

```
<?php

$ext_url = $_POST['ext_url'];

echo file_get_contents($ext_url);

?>

```

**JS**

```
$.ajax({
    method: 'POST',
    url: 'getContentFromUrl.php', // link to your PHP file
    data: {
        // url where our server will send request which can't be done by AJAX
        'ext_url': 'https://stackoverflow.com/questions/6114436/access-control-allow-origin-error-sending-a-jquery-post-to-google-apis'
    },
    success: function(data) {
        // we can find any data on external url, cause we've got all page
        var $h1 = $(data).find('h1').html();

        $('h1').val($h1);
    },
    error:function() {
        console.log('Error');
    }
});

```

**How it works:**

1. Your browser with the help of JS will send request to your server
2. Your server will send request to any other server and get reply from another server (any website)
3. Your server will send this reply to your JS

And we can make events onClick, put this event on some button. Hope this will help!

---
Tags: ajax, javascript
---


# Question
Title: file_unmanaged_copy - Any service alternatives?
The functionality of the `file_unmanaged_copy` is exactly what I need. The only problem is: it's a global function which uses static service calls. Since I need to unit test my class (and not to mention how I dislike hidden dependencies coming from global functions) I can't use it.

Am working with D8 since the very beginning, but am failed to find any OO alternatives. Has anyone faced the same situation? Any "Best-practises" or workarounds?

# Answer
> 2 votes
This changed in Drupal 8.7.0 See https://www.drupal.org/node/3006851

```
try {
  \Drupal::service('file_system')->copy($source, $destination, $replace);
}
catch (\Drupal\Core\File\Exception\FileException $e) {
    // Log or set message or doing something else.
}

```

# Answer
> 0 votes
As for now **Berdir**'s comment is the right answer:

> There is no oop replacement yet. There are a number of issues to convert those function to services but it didn't happen yet. The common approach that core uses to solve this problem so to hide this function in a protected method and in the unit test, you mock your own class so that you are able to mock that method. Or you make a separate service that just wraps that method so you can mock it

Personally, I prefer the later one, wrapping it the globals into a service.

---
Tags: 8, files
---


# Question
Title: Is there any elegant way of excluding form element from the `values` array of the `FormState`?
I know that the `values` array can be cleaned up in the validation or submit callback, but can we somehow mark the element itself to be not put in the `values` array of the `FormState`?

# Answer
Not within the building of the form as far as I know. You'd need to strip out the values you don't want in the submit handler as you mentioned.

This is probably the easiest way to remove the default form values:

```
$values = $form_state->cleanValues()->getValues();

```

That will remove: form\_id, form\_token, form\_build\_id, op
> 1 votes

---
Tags: 8, forms
---


# Question
Title: How do I render the page to add products into my custom module?
Here is my code

```
<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Controller\ControllerBase;
class HelloController extends ControllerBase
{
  public function content() {

       $form = \Drupal::formBuilder()->getForm('\Drupal\commerce_product\Form\ProductForm');
}
}

```

I want to render the default add to product page(product/add/default) in my custom module controller file .

> Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm-\>getBaseFormId() (line 79 of core/lib/Drupal/Core/Entity/EntityForm.php).

# Answer
You need to create an empty product and use `entity.form_builder` service to generate the form.
Try the following.

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\commerce_product\Entity\Product;
use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {
  public function content() {
   $product = Product::create([
     'type' => 'default',
   ]);
  return  \Drupal::service('entity.form_builder')->getForm($product);
  }
}

```
> 0 votes

---
Tags: commerce
---


title: Manually disable a module

text:
# Question
Title: Manually disable a module
In Drupal 7, I could manually edit the `{system}` table in the database to disable a stubbon module. In my Drupal 8 site, this table is gone.

How can I manually disable a module in Drupal 8?

# Answer
> 62 votes
The Drupal 7 `system` table data is now stored in the `config` table in Drupal 8 against the `core.extension` parameter.

**Solution 1: Update configuration**

You can run the following code using `drush eval` or may be using the Devel module's provision to `Execute PHP Code`.

```
// Read the configuration.
$module_data = \Drupal::config('core.extension')->get('module');

// Unset the modules you do not need.
unset($module_data['MODULE_NAME']);

// Write the configuration.
\Drupal::configFactory()->getEditable('core.extension')->set('module', $module_data)->save();

```

You can do this all in a quick one-liner with `drush`.

```
drush eval "\$module_data = \Drupal::config('core.extension')->get('module'); unset(\$module_data['MODULE_NAME']); \Drupal::configFactory()->getEditable('core.extension')->set('module', \$module_data)->save();"

```

**Solution 2: Edit config table if you cannot execute PHP**

If the site is broken because of the problematic module and you can't even run PHP code, then may be you can edit the `config` table directly.

In the row in the `config` table where `name = "core.extension"` and edit the BLOB column `data`. The `data` is a serialized PHP array where you have to remove the module you want to get rid of from the `module` key of the configuration.

**Solution 3: Fast and dirty solution**

* Remove the module from the file system
* Truncate the table `cache_config`

However, this solution might result in messages saying the module does not exist in file system which mean something is wrong. But at least the broken module gets disabled and you can access your site in most of the cases.

**Clearing Cache**

Sometimes you might have to clear cache after following the above steps. Read this handy documentation on how to clear cache.

# Answer
> 21 votes
* Manually edit the `config` table where `name = 'core.extension'` and remove the module from the data blob which is a serialized array.
* Be aware to decrement the module array length as well `(...s:6:"module";a:HERE;{...)`
* Truncate the `cache_config` table from phpmyadmin or using command-line.

# Answer
> 16 votes
Do this:

```
rm -rf modules/your_stubborn_module
rm -rf sites/default/files/php

```

# Answer
> 6 votes
If you need to update anything related to Drupal configuration, in this case `core.extension`, use Drush:

\[Drush 8.x in this example\]

```
drush cedit core.extension

```

# Answer
> 5 votes
In Drupal 8, try to removing the module from your module folder and run rebuild.php.

Try `drush pm-uninstall module-name` as well.

# Answer
> 4 votes
Consider using Drush. Drupal 8 is still defining what "disabling modules" should be. There is an ongoing discussion if there should be that option or it should be removed.

# Answer
> 4 votes
I tried all of the other answers but kept getting a drupal error message. To solve it I had to remove a row from the key\_value table (look for the module name in the name column)

# Answer
> 3 votes
This is how, I manually removed a module named "better\_messages" from my Drupal 8 instance. As soon as I installed the "better\_messages" module, the site went down. So there was no way to uninstall the module from user interface. I dont have Drush installed. I have done many settings given in forums, but this is how it finally worked for me.

1 Renamed the module to old\_better\_messages in modules folder.

2. Through the url, ran http://IP:port/foldername/rebuild.php. This ensured that site is back, but only in read-only mode. I couldnt do the admin activities or edit articles.
3. Used following command to delete the entry from database

DELETE FROM key\_value WHERE collection='system.schema' AND name='better\_messages';

In my case, there was no entry in the database. I think it might have got deleted because of the various stunts that I did earlier.

4. Then using DB visualizer, I deleted entries from all the tables that starts with cache.

This resolved the issue. This is based on my interpretation of https://www.drupal.org/node/2487215

# Answer
> 2 votes
There is a module for that. ***This module was posted in Aug-2013 on drupal.org***. In case somebody needs.

Disable modules

As stated on the page of this module,

> Drupal 8 has removed the ability to disable modules for many reasons. See #1199946: Disabled modules are broken beyond repair so the "disable" functionality needs to be removed and many other issues in the queue of various core and contributed modules.
>
> This module brings back the ability to (temporarily) disable modules from the UI or with Drush. Note, that there's no guarantee for your content, config or even your site after you disable a module.

# Answer
> 1 votes
Jigarius' answer above, *sort of worked...*

I had to: // Read the configuration.

```
$module_data = \Drupal::config('core.extension')->get()['module'];

```

Which *should* do the same thing. Not sure why it didn't work as Jigarius wrote it...

---
Tags: 8
---


# Question
Title: Add a css class to the active link then remove it when becomes inactive
I know this question might not fit here but I am afraid that I am doing something wrong related to Drupal since it is my first time with JS code and its implementation into Drupal core.

I have placed a block available on all of my pages made with views and is working as the main menu for all users.

This view block consists of 3 **Custom Text** fields having the same class name: **menu-item** as below:

* **Custom Text fields #1:** `<a class="menu-item home-item" href="/link-1">Home</a>`
* **Custom Text fields #2:** `<a class="menu-item services-item" href="/link-2">Services</a>`
* **Custom Text fields #3:** `<a class="menu-item contact-item" href="/link-3">Contact</a>`

I want to add the class name **active-page** to a link once a user clicked on a it then remove it once the user click on another link in that block.

I am using a subtheme of Bartik theme and so far:

**general\_css.css** file:

```
.active-page {
background-color: blue;
}

```

**THEME\_NAME.libraries.yml** file:

```
global-styling:
  version: 1.x
  css:
    theme:
      css/general_css.css: {}
global-scripts:
  version: 1.x
  js:
    js/general_js.js: {}
  dependencies:
    - core/jquery

```

**THEME\_NAME.info.yml** file:

```
libraries:
  - 'THEME_NAME/global-styling'
  - 'THEME_NAME/global-scripts'

```

**js/general\_js.js** file:

```
(function ($, window, Drupal) {
  $(document).ready(function () {
    $(".menu-item").on('click', function (e) {
      $(this).addClass("active-page") // Add active-page class to the clicked link.
        .siblings() // Select clicked link brothers.
        .removeClass("active-page"); // Remove active-page class if exist from clicked link brothers.
    })
  });
})(jQuery, window, Drupal);

```

Using Chrome browser and while inspecting the element, I have clicked on a link from the block and during the loading of the page, the **active-page** class has been successfully added to the clicked link; However the **active-page** class has disappeared directly after the loading of the page has finished.

Any help on what is missing here ?

Thank you,

# Answer
"menu-item" is a global class which can be used with several links on your Drupal site, so you have to be more specific with your css selectors (for example use your block ID and then the selector will be "#yourBlockId .menu-item".

Also I invite you to use jQuery library it will help you to simply implement your JS solution by using jQuery methods (addClass(), removeClass(), siblings(),...).

First add jQuery as a dependency of your global-scripts library: **THEME\_NAME.libraries.yml** file

```
global-styling:
  version: 1.x
  css:
    theme:
      css/general_css.css: {}
global-scripts:
  version: 1.x
  js:
    js/general_js.js: {}
  dependencies:
    - core/jquery

```

**js/general\_js.js** file:

```
(function ($, window, Drupal) {
  $(document).ready(function () {
    $('#yourBlockID .menu-item').on('click', function (e) {
      $(this).addClass('active-page') // Add active-page class to the clicked link.
        .siblings() // Select clicked link brothers.
        .removeClass('active-page'); // Remove active-page class if exist from clicked link brothers.
    })
  });
})(jQuery, window, Drupal);

```
> 1 votes

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


# Question
Title: How do you change the core forum module to only show a certain depth?
I am using the core forum module. If I have this forum structure:

```
- A1
 - A2
  - A3
- B1
 - B2
  - B3
- C1
 - C2
  -C3

```

I want it to show A1, B1 and C1. As well as A2 and B2. But not A3, B3 and C3.

I checked the forum-list.html.twig file, but before I start hacking away, I was wondering if there isn't a more obvious hook of some sort I could use to do this?

# Answer
If you want to change list of forums using hook try `hook_preprocess_HOOK` something like like

```
function MYMODULE_preprocess_forum_list(&$variables) {
// dump here forums and search for the forum you want to remove and unset it .
 dpm($variables['forums']);
}

```
> 1 votes

---
Tags: 8
---


# Question
Title: How do I free the memory used from node_load()?
I am using code similar to the following one.

```
for ($i = 0; $i < 1000000; $i++) {
   $nid = get_node_id($i);
   $node = node_load($nid);
   $data = [
     $node->field_1,
     $node->field_3,
     ...
   ];
   save_to_database($data);

   echo round(memory_get_usage() / 1024 / 1024, 2) . ' MB'. PHP_EOL;
}

```

Every time a loop is completed, the used memory is increased. For example, after the first loop, the used memory is 110 MB, and after the third loop is 230 MB.

How do I avoid the used memory keep increasing?

# Answer
It happens because `node_load()`, as every Drupal function that loads entities from the database, stores in memory the loaded entity. If you want to avoid that happens, you can use code similar to the following one.

```
for ($i = 0; $i < 1000000; $i++) {
  $nid = get_node_id($i);
  $node = entity_load('node', array($nid), array(), TRUE);
  $data = [
    $node->field_1,
    $node->field_3,
  ];
  save_to_database($data);
}

```

The last argument of `entity_load()` is telling Drupal not to store in memory cache the previously loaded entity.

This is what happens with the default entity controller implemented from Drupal, `DrupalDefaultEntityController`, which uses the following code for `DrupalDefaultEntityController::resetCache()`.

```
public function resetCache(array $ids = NULL) {
  if (isset($ids)) {
    foreach ($ids as $id) {
      unset($this->entityCache[$id]);
    }
  }
  else {
    $this->entityCache = array();
  }
}

```
> 2 votes

---
Tags: 7, nodes, performance
---


# Question
Title: How to prevent drupalSettings to sort settings object
I attach `drupalSettings` in a preprocess hook using code similar to the following one.

```
$settings = [
  'bcd' => 'BCD',
  'abc' => 'ABC'
];

$variables['#attached']['drupalSettings']['options'] = $settings;

```

When I print the content of `drupalSettings` using `console.log(drupalSettings.options);` I get a sorted object.

```
{ 'abc' : 'ABC','abc' : 'BCD'}

```

Is this the normal behavior? How can I prevent it?

# Answer
It's not Drupal that sorts the *drupalSettings* array, but it's `console.log()` that sorts the properties of `drupalSettings.options` before outputting it. See Show original order of object properties in console.log where the answer explains this.

If you really want to avoid `console.log()` sorts the object properties, you could call `console.log()` using code similar to the following one.

```
console.log(JSON.stringify(obj, drupalSettings.options, null, 2));

```

I would rather use this code if it's really important to see the object properties in the order they are set.
> 2 votes

---
Tags: 8, javascript
---


# Question
Title: Have Views based Taxonomy Term page use term description for title
I am using a view to replace the standard Taxonomy Term page (turned on the standard one in Drupal 8.x). I want the Title of the page to be changed from the Name of the term to the Description of the term everywhere it appears, in the Title attribute in the Header but more importantly in the Title that is rendered on the page. I have tried all sorts of tricks in a custom page--taxonomy.html.twig file to no avail.

# Answer
> 0 votes
There is an incompatibility to use Description as Title, at least if you use the default settings. Description is a long text field and it possibly contains HTML. Titles are supposed to be plain text only, they are usually "cleaned" against HTML in them.

That said, if you think you have a case where this makes sense, you can try to use the field tokens for the Taxonomy term Description field. But you'll have to make a lot of changes to the Views if you want to do it through the interface and not custom code.

"Taxonomy term" Views is of the "Content" type, not "Taxonomy term" type, so you don't get taxonomy term info out-of-box in there. You have to add a Relationship towards the term in order to get the term info to be available in Views.

So first add the Relationship for your Taxonomy reference field, it will be under "Content" Category, named something like "Taxonomy term referenced from field\_tags". You'll probably want to Require it, to exclude all nodes that don't have that taxonomy tag.

Once you have the Relationship you will be able to add the Field "Description" to your views (change the Format to "Fields" if it's "Content"). You can Exclude it from display if you don't want it in the Views results. And recreate the "Content" Format with Fields, add the node Title field etc.

The Title in the "Taxonomy term" Views isn't coming from the Views Title field, it's coming from the Contextual filter "Override title" option. There is also the Header option rendering the Taxonomy term which shows the linked term name and its description below it.

So if you want to change how that behaves, that's where you'll have to make the changes. I don't think you'll be able to have the Description token work in the default "Has taxonomy term" Contextual. You'll have to remove it and add the Contextual for your tags field, possibly for the Description field (I haven't tried it). Then set the title override on that Contextual and adjust the Views Header option.

Since your Contextual is limited to one field, and no longer covers entire site's Taxonomy, you have to be careful to recreate other Taxonomy pages (for other Vocabularies) if you need them. It's always a good practice not to work on the original "Taxonomy term" Views, instead keep it intact and disabled for future reference, and Duplicate into a new Views and work on the Duplicate.

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