# Question
Title: List of all active modules used in a site
Is there a way of having a list of all the used (active) modules on a site?

I am in the process of documenting a site and I would like to list all the active modules. I know I can take them from admin/modules, but there must be another way.

# Answer
> 63 votes
You can use `drush pm-list --type=Module --status=enabled` command for getting a list of all installed modules.

If you want to exclude the core modules use `drush pm-list --type=Module --no-core --status=enabled`

# Answer
> 26 votes
The two options I use are Drush and a custom script.

For Drush, you can use `drush pm-list`:

```
$ drush help pm-list
Show a list of available extensions (modules and themes).

Options:
 --type                                    Filter by extension type. Choices:
                                           module, theme.
 --status                                  Filter by extension status. Choices:
                                           enabled, disable and/or 'not
                                           installed'. You can use multiple
                                           comma separated values. (i.e.
                                           --status="disabled,not installed").
 --package                                 Filter by project packages. You can
                                           use multiple comma separated values.
                                           (i.e. --package="Core -
                                           required,Other").
 --core                                    Filter out extensions that are not
                                           in drupal core.
 --no-core                                 Filter out extensions that are
                                           provided by drupal core.
 --pipe                                    Returns a space delimited list of
                                           the names of the resulting
                                           extensions.

Aliases: pml

```

I also wrote this script for Drupal 6. You need to edit the bootstrap for Drupal 7, and you may also want to tweak the path checking. I put this in a file called modules.php in my DOCROOT and add access restriction around it to prevent it from being called from the wild.

```
<?php
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
header('Content-Type: text/plain');

$files = drupal_system_listing('/\.module$/', 'modules', 'name', 0);

system_get_files_database($files, 'module');

ksort($files);

$core_installed = array();
$core_enabled = array();
$core_disabled = array();

$contrib_installed = array();
$contrib_enabled = array();
$contrib_disabled = array();

foreach ($files as $info) {
  $filename = $info->filename;
  $name = $info->name;
  $status = $info->status;

  $contrib = strpos($filename, "sites/all/modules/") === 0;

  if ($contrib) {
    $contrib_installed[] = $name;
    if ($status) $contrib_enabled[] = $name;
    else $contrib_disabled[] = $name;
  } else {
    $core_installed[] = $name;
    if ($status) $core_enabled[] = $name;
    else $core_disabled[] = $name;
  }
}

print "Installed Core Modules: " . join(", ", $core_installed) . "\n\n";
print "Enabled Core Modules: " . join(", ", $core_enabled) . "\n\n";
print "Disabled Core Modules: " . join(", ", $core_disabled) . "\n\n";

print "Installed Contrib Modules: " . join(", ", $contrib_installed) . "\n\n";
print "Enabled Contrib Modules: " . join(", ", $contrib_enabled) . "\n\n";
print "Disabled Contrib Modules: " . join(", ", $contrib_disabled) . "\n\n";

```

This script can be called with drush using: `drush scr modules.php`

# Answer
> 8 votes
The Enabled Modules (enabled\_modules) module provides lists of all enabled modules on a website.

Or,

You can use this API function module\_list to get all enabled modules.

# Answer
> 5 votes
Yes, check the Module Filter module: It's excellent administrator helper that makes managing modules much easier.

> The modules list page can become quite big when dealing with a fairly large site or even just a dev site meant for testing new and various modules being considered. What this module aims to accomplish is the ability to quickly find the module you are looking for without having to rely on the browsers search feature which more times than not shows you the module name in the 'Required by' or 'Depends on' sections of the various modules or even some other location on the page like a menu item.
>
> When tabs is enabled via the Module Filter's settings page, a new module layout theme is implemented. This tab layout provides a tab for each package as well as a tab that will show every module alphabetically. The filter textfield is available on each tab but currently doesn't support autocomplete.

# Answer
> 3 votes
The simplest way I've found is a database query you could put in a custom module or Drush script to output it in a format you want.

`$enabled_modules = db_query("SELECT name FROM {system} WHERE type = 'module' AND status = 1")->fetchCol('name'); print implode("\n", $enabled_modules);`

# Answer
> 2 votes
Drush make has a primitive makefile generation capability. To use it, simply change your directory to the Drupal installation from which you would like to generate the file, and run the following command:

`drush generate-makefile /path/to/make-file.make`

You get make-file.make with a list of modules. Then you can load these modules in other project. Read http://www.drush.org/en/master/make/#usage

# Answer
> 2 votes
If you don't have commandline access to run drush, you might be looking for something you can do from the Web UI. The best solution I could find was browsing to the Modules page and then running this command in the console:

```
jQuery('table.sticky-enabled input[checked=checked]')
  .closest('tr')
  .find('td label strong')
  .each(function() {
    console.log(jQuery(this).text());
})

```

This will print all the enabled modules in the console, where you can copy paste them anywhere you'd like.

# Answer
> 2 votes
Install and enable the Forena module (disclosure I'm a co-maintainer). Users with role "administrator" will then be able to navigate to the delivered (sample) report located at `reports/drupaladmin.enabled_contributions`, which will give you the list this question is about.

Here is how the specification (`.FRX` file, an XHTML document) to create the report looks like:

```
<?xml version="1.0"?>
<!DOCTYPE root [
<!ENTITY nbsp " ">
]>
<html xmlns:frx="urn:FrxReports">
<head>
<title>Enabled Modules and Themes</title>
<frx:category>Drupal Administration</frx:category>
<frx:options hidden="0" />
<frx:parameters>
</frx:parameters>
<frx:docgen>
</frx:docgen>

</head>
<body>
  <div frx:block="drupal/enabled_modules" id="forena-1">
    <table>
      <thead>
        <tr>
          <th>name</th>
          <th>owner</th>
          <th>weight</th>
        </tr>
      </thead>
      <tbody>
        <tr frx:foreach="*" id="forena-2">
          <td>{name}</td>
          <td>{owner}</td>
          <td>{weight}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>
</html>

```

And here is how the data block (SQL statement) referred to in the report looks like:

```
--ACCESS=access administration pages
SELECT name, owner, weight FROM {system}
WHERE status=1 AND 'module'=type
ORDER BY name

```

That's really "it".

PS: feel free to tune (adapt) the `.FRX` file and/or the data block to fit your own needs.

# Answer
> 2 votes
```
<?php
$files = system_rebuild_module_data();
$modules_list = [];

foreach ($files as $filename => $file) {
  // Hidden modules and Themes will be excluded.
  if (!empty($file->info['hidden']) || $file->type != 'module') {
    continue;
  }

  // Get module type.
  $type = 'Contrib';
  if ($file->info['package'] == 'Core') {
    $type = 'Core';
  }
  elseif (strpos($file->uri, "sites/all/modules/custom/") !== false) {
    $type = 'Custom';
  }

  // Check module installed or not.
  if ($file->status) {
    $modules_list[$type]['installed'][] = $file->name;
  }
  else {
    $modules_list[$type]['disabled'][] = $file->name;
  }

}

foreach ($modules_list as $type => $module_info) {
  print $type . " Modules:\n\n";
  print "Enabled " . $type . " Modules: " . count($module_info['installed']) . "\n\n";
  print "Disabled " . $type . " Modules: " . count($module_info['disabled']) . "\n\n";
}

```

The above code will help to get the modules installed in Drupal 7 website.

# Answer
> 0 votes
For those without drush: go to modules page, with module filter enabled (not absolutely necessary, but good for formatting).

Then show source page, copy modules html inside "\<"table\>" to "\<"/table\>. Paste into gedit, wrap some html around it (html, body), and you'll have a html page, including indication of unused/disabled modules (showing check box unchecked) which can be important when rebuilding a site (insofar as the disabled modules might be needed, or can be installed -\> uninstalled for the sake of cleaning up the database)

# Answer
> 0 votes
Schema module is one option while Views can do the trick too although without the additional Views System module, which i found buggy, you dont get version numbers.

---
Tags: 7
---


title: How do I overwrite a page template?

text:
# Question
Title: How do I overwrite a page template?
I created a bunch of products, but I need to style them per the designer's design. I know that I have to overwrite the template from `/modules/contrib/commerce/modules/product/templates/commerce-product.html.twig` but where do I put it in my theme?

Does it go to the root of my templates folder? What is the correct way to style the single product page?

# Answer
> 0 votes
To do this, just create a **copy** of **commerce-product.html.twig** from the product module in commerce to **your theme's template** directory.

for more instruction to visit https://docs.drupalcommerce.org/commerce2/developer-guide/products/displaying-products/theme-product.

# Answer
> 0 votes
@Amy Ling

The best practice for this use case is, in your theme templates folder create a product folder and create a copy of commerce-product.html.twig from the product module in commerce directory.

Eg: web/themes/custom/custom\_theme/templates/product/commerce-product.html.twig

for more instruction to visit https://docs.drupalcommerce.org/commerce2/developer-guide/products/displaying-products/theme-product.

---
Tags: theming, commerce
---


# Question
Title: Redirect from within controller always goes to home page
I have a custom module named `rsc`.

My `Default 404 (not found) page` is set to `/page-not-found` in `Basic site settings`.

My rsc.routing.yml file contains

```
  rsc.pageNotFound:
    path: '/page-not-found'
    defaults:
      _controller: 'Drupal\rsc\Controller\rscController::pageNotFound'
      _title: ''
    requirements:
      _permission: 'access content'

```

My rscController.php file contains:

```
  class rscController extends ControllerBase
  {
    public function pageNotFound()
    {
      $path = '/test-page'; // Just for testing

      if (($url = \Drupal::service('path.validator')->getUrlIfValid($path))) {
        $route = $url->getRouteName();
        $param = $url->getRouteParameters();
        error_log("route=$route param=" . print_r($param, true));
        return $this->redirect($route, $param);
      }
      else {
        return
        [
          '#markup' => 'No such page'
        ];
      }
    }
  }

```

`/test-page` is the alias for `/node/125`.

If I type `mywebsite.com/junk` in the address bar (to force the not found page to be invoked) and press Enter, I am always redirected to the home page, even though the error log contains the result

route=entity.node.canonical param=Array ( \[node\] =\> 125 )

What am I doing wrong? Why doesn't $this-\>redirect() take me to the node?

# Answer
> 2 votes
When you call a controller as error page via the basic site settings this is not the controller of the main request, this controller is executed in a subrequest to get a themed output of the otherwise simple text message you see for non 4xx exceptions like a 500 error.

Better place the redirect in the main request, before the rendering of the exception is delegated to a subrequest by CustomPageExceptionHtmlSubscriber. You can use the default priority 0, because the core exception handler has -50.

@MarshallMorrise has posted the working code at https://drupal.stackexchange.com/a/290659/47547

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


# Question
Title: Aggregation with count that includes empty field values
I saw other questions regarding the aggregation but i didn't found anything similar to what i need.
I've a view with enabled the aggregation, results are grouped by a field value (a text field) with also the count for that field. Everything is ok, but i'd like to include also the count for the empty values, and i can't make this thing to work...
Now i've something like

```
| FIELD VALUE | COUNT |
|-------------|-------|
| value 1     | 10    |
| value 2     | 3     |

```

And i'd like to have something like

```
| FIELD VALUE | COUNT |
|-------------|-------|
| value 1     | 10    |
| value 2     | 3     |
| -empty-     | 5     |

```

Is there any way to achieve this? i tried writing something like "-empty-" in the no results behaviour, but the only thing i manage to have is a line with always the counter to `0`, like

```
| FIELD VALUE | COUNT |
|-------------|-------|
| value 1     | 10    |
| value 2     | 3     |
| -empty-     | 0     |

```

I really don't know what to try now.. Thanks!

# Answer
> 0 votes
I've not found a way to do this thing, but if any other needs something similar, i end up using Computed Field to handle this case, so i can store the actual field value normally, or another text (in my case 'Not filled').

Using this computed field instead of the actual field makes everything works...

But i'm open to change this thing if there's a better way to do this, as this sound a bit hacky...

---
Tags: 7, views
---


# Question
Title: How to handle config changes on core update?
I have an 8.6.15 site managed by composer and drush. The db and config exports are in sync.

Roling our new features using drush cim on production works fine.

I now update core to 8.7 by running copmoser update and drush updb successfully, and everything seems to be working as expected.

The update process causes configuration differences between the db and the exported config files

My question: What is the proper way of handling these config changes?

1) drush updb -\> drush cex (seems logical to me)

2) drush updb -\> drush cim -\> drush cex

The two strategies result in slightly different end configurations.

# Answer
> 0 votes
Schema updates in different versions of core and contrib which cause changes to the config will cause an issue where your config becomes outdated.

On your local environment, run:

```
drush updb
drush cex

```

Then you can commit and push your configuration, and on your target (i.e. production, or stage, etc) environment, run:

```
drush updb
drush cim

```

Failure to do so will cause hard-to-diagnose issues in some case. More info and examples at:

---
Tags: updating, configuration
---


# Question
Title: How to import a million of nodes? Very slow import
I've been dealing with this problem for several days. I need to import around 1,600,000 nodes (one time). Everything is set correctly, but the speed is horrible.

**Both on the shared server and on the localhost (WAMP and attempts to set the optimal my.ini file).** The import is simply horribly slow and after importing 400,000 nodes is even slower.

I understand that processing in Drupal 8 happens per item, but how to set up / edit the import to make it faster?

Well, in the end, I dared to get on the train and started with Migrate CSV and Migrate Tools + Drush.

It looks, it works much better.

# Answer
Performance is typically due to the Entity API system operations and the complexity of your migration.

First thing would be to ensure you have nothing enabled like XML Sitemap, Search API / Search indexing, Rules, and other operations that happen on node/entity save unless absolutely necessary (like Pathauto for example).

Second, try leveraging Migrate, Migrate Plus and Migrate CSV instead of Feeds. Grab Migrate Tools so you can run migrations from the command line instead of the UI.

Third, as 4k4 suggested in comments, don't base it only on WAMP / local import. Run this in the environment where the site will be hosted - this will be a much better idea of your performance instead of how it runs on your machine.

You could also try loading the CSV file in and creating a MySQL table out of it, and use the native Sql plugin in Migrate over Migrate CSV. This difference may be negligible, though.

If you are creating/migrating Paragraphs or files (PDFs/images), performance/processing is going to be slower, regardless.

Someone contributed a module to do parallel processing of a migration (ex. 5 at once instead of one at a time) but I can't locate it at the moment. I will update when I do. But modules like this are experimental right now, so YMMV.
> 1 votes

---
Tags: 8, migrations, feeds, importing-exporting
---


# Question
Title: How can you reference taxonomy term by another field in Yaml file?
I created my own Yaml file with fields inside to migrate nodes.

I run into this problem. If I use the feeds module, I can set (during mappings) that a given field (taxonomy term reference field) can be referenced by any other field from my site. The term name is therefore assigned based on the value in the reference field.

**If I use Migrate CSV module, how do I set this in Yaml file?** This is my Yaml:

```
uuid: bf1e53ae-6a95-48f2-8888-4b928e6e33ea

id: testovacimigrace2
label: My own migration !!!!!!!
migration_group: migration

source:
  plugin: 'csv'
  # Full path to the file.
  path: 'modules/custom/migrace/assets/csv/upload1.csv'
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  ids:
    - ID

process:
  title: title
  field_email: email
  type:
    plugin: default_value
    default_value: submitlawyer

destination:
  plugin: entity:node

```
1. Every term in my taxonomy called "fishes" has its own field with a unique number.
2. My CSV contains a column called fish that does not contain a term name but its unique number (ad.1)
3. I need to assign the correct term by using this unique number.

# Answer
> 2 votes
Here is a simple migration for looking up a taxonomy term by name based on the text in a CSV.

```
taxonomy_field_name:
  plugin: entity_lookup
  source: name_of_source_column
  value_key: name
  bundle_key: vid
  bundle: name_of_taxonomy
  entity_type: taxonomy_term

```

For example, if you have a taxonomy called `fishes`, and your CSV has a column called `fish`, and your node has a field called `field_fish` which is an entityreference to a taxonomy term of the `fishes` vocabulary, and there is a taxonomy term "Carp" with entity ID 14

```
field_fish:
  plugin: entity_lookup
  source: fish
  value_key: name
  bundle_key: vid
  bundle: fishes
  entity_type: taxonomy_term

```

Given a row in the CSV with "Carp" set as the fish, this will assign entity id 14 to that field.

Does that help? I am not sure what you mean by "a given field can be referenced by any other field from my site".

---
Tags: taxonomy-terms, migrations
---


# Question
Title: How to get rid of large classes with numbers from views?
Which is the purpose of classes like that one:

```
class="js-view-dom-id-0fc70eec09ba01f6b7c7867ee7e19f7dcec1ee8b64de9dc8b791865caf299ec7"

```

It's safe to change this class from twig templates?

Thanks.

# Answer
They are used to uniquely target views elements with javascript for AJAX purposes. If you have enabled the use of AJAX on your views display for pagination, filtering etc without page reloads, then removing or changing those might break it. If you are not using AJAX at all, you should be fine, although this comment is not a promise or guarantee!
> 2 votes

---
Tags: views, theming
---


# Question
Title: How to get the Published or Archived revision of a node
I'm trying to compare some field values from the edit form of a node to the published/archived field values. However I'm running to an issue where when im trying to load the Node object using `Drupal::entityTypeManager()->getStorage('node')->load($nid)` It's returning the last saved draft revision. How do i get the Node object of the published/archived revision?

P.S. Content Moderation is turned on, and content type is assigned to a workflow.

# Answer
> 2 votes
You can do this with a direct database query in your function, then load the specific revision.

```
$connection = \Drupal::database();
$query = $connection->query("SELECT vid FROM {node_field_data} WHERE nid = :nid",
    [':nid' => $node_nid,]);
$node_revision_id = $query->fetchField();

$node_revision = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

```

Untested code, but this should put you on the right track. Might also be worth confirming in your SQL query that "WHERE status = 1" to confirm that the node is still published.

---
Tags: 8, nodes
---


# Question
Title: How do I fix this commerce_auction_node_presave error message?
I am working on a reverse auction for our youth group. I'm using D7 with the commerce\_auction module. I ran into the error below when setting up the content type for the auction:

```
Notice: Undefined offset: 0 in commerce_auction_node_presave() (line 260 of /public_html/catz/sites/all/modules/commerce_auction/commerce_auction.module).
EntityMalformedException: Missing bundle property on entity of type commerce_product. in entity_extract_ids() (line 7697 of /public_html/catz/includes/common.inc).

```

for the first notice, line 260 contains this: $product\_reference = $product\_reference\[0\];

Does anyone know how to fix this error? There's not a lot of commenting as yet on this auction module, so I can't find a solution.

/\** * Implements hook\_node\_presave(). \*/

```
function commerce_auction_node_presave($node) {
  $types = variable_get('commerce_auction_display_types', array());
  if (in_array($node->type, $types) !== FALSE) {
    $product_reference = field_get_items('node', $node, 'field_product');
    $product_reference = $product_reference[0];
    $product = commerce_product_load($product_reference['product_id']);
    $price = field_get_items('commerce_product', $product, 'commerce_price');
    $node->auction_starting_price[LANGUAGE_NONE][0]['amount'] = $price[0]['amount'];
    $node->auction_starting_price[LANGUAGE_NONE][0]['currency_code'] = $price[0]['currency_code'];
  }
}

```

# Answer
> 0 votes
Change the code below :

```
 $node->auction_starting_price[LANGUAGE_NONE][0]['amount'] = $price[0]['amount'];
    $node->auction_starting_price[LANGUAGE_NONE][0]['currency_code'] = $price[0]['currency_code'];

```

with

```
 $node->auction_starting_price[LANGUAGE_NONE][0]['amount'] = $price['und'][0]['amount'];
        $node->auction_starting_price[LANGUAGE_NONE][0]['currency_code'] = $price['und'][0]['currency_code'];

```

# Answer
> 0 votes
You can fix that error by updating (or moving) to the 7.x-2.x-dev version of the module. `commerce_auction_node_presave()` has been changed to use the following code.

```
function commerce_auction_node_presave($node) {
  $types = variable_get('commerce_auction_display_types', array());
  if (in_array($node->type, $types) !== FALSE) {
    $product_reference = field_get_items('node', $node, 'field_product');
    if (!empty($product_reference)) {
      $product_reference = $product_reference[0];
      $product = commerce_product_load($product_reference['product_id']);
      $price = field_get_items('commerce_product', $product, 'commerce_price');
      $node->auction_starting_price[LANGUAGE_NONE][0]['amount'] = $price[0]['amount'];
      $node->auction_starting_price[LANGUAGE_NONE][0]['currency_code'] = $price[0]['currency_code'];
    }
  }
}

```

Differently from the 7.x-1.x-dev version, the code now verifies `$product_reference` is not an empty value (for example, an empty array), before trying to use `$product_reference[0]`, which is sufficient to avoid the error you are seeing.

---
Tags: commerce
---


# Question
Title: How to get one time URL when we are writing hook_mail_alter?
My Question is already present here but the previously given answer for my question can applied to Drupal 7 and I can not use the same solution in Drupal 8.

I hope it is okay not put the same question once again.

# Answer
Bingo! Found the Solution myself:

```
    function custom_module_mail_alter(&$message) {
      if (!empty($message['id']) && $message['id'] == 'user_password_reset') {
        $token_service = \Drupal::token();
        $language_interface = \Drupal::languageManager()->getCurrentLanguage();
        $account = $message['params']['account'];
        $one_time_url_token = '[user:one-time-login-url]';
        $one_time_url = $token_service->replace($one_time_url_token, ['user' => $account], ['langcode' => $language_interface->getId(), 'callback' => 'user_mail_tokens', 'clear' => TRUE]);
      }
    }

```
> 2 votes

---
Tags: 8, users, emails
---


# Question
Title: How do I update customers cart prices and add discount and then let them checkout?
I'm using Drupal 7 Commerce and Commerce discount, amongst many others.

So the use case is this. We often get enquiries for bulk orders containing many products. We want our customer to go to the website and add what they want into their cart. As admin I want to open that unpaid cart, edit product prices and apply a Fixed Price Discount. Then when the customer refreshes their cart they will see our amendments and continue with payment. Is this possible? Am I missing something obvious?

At present I can edit a order that is in the cart but when the customer refreshes their cart the order is reverted back to prior my changes. I can't edit product prices at all whilst the order isn't completed. Once in Completed status, I can tweak product prices and add the discount.

To get the Fixed price discount feature to work I had to switch from the Line Item Manager widget over to Multiple Inline Entity References. For the line items field on orders that is. Before that I couldn't use the Fixed price discount feature at all.

Any help would be greatly appreciated. I must be performing the wrong searches or something.

# Answer
> 0 votes
There was a few steps to this

1) Create a custom field on your product line items. Use a "price" field type. I called it "Discount unit price".
2) On your order entity line item field widget, you'll need the "Multiple Inline Entity References." This allows you to edit your custom field.
3) Create a pricing rule
**Event:** Calculating the sell price of a product
**Conditions:** 1) "Entity has field" and select our new field. 2) "Data value is empty" with the negate box checked. In other words we're interested if the field is not empty.
**Action:** "Set the unit price to a specific amount". Enter the token for your new field. I used "amount" not "amount-decimal."
4) Create a 2nd rule to re-apply pricing rules when admins create or update a order
**Event:** "After saving a new commerce order", "After updating an existing commerce order"
**Conditions:** "User has roles". Select your admin roles.
**Action:** "Execute custom PHP code" (you need "php filter" module enabled). Enter this "commerce\_cart\_order\_refresh(\[commerce-order:order-id\]);"
5) In order to send the customer a payment link with the discounted prices, install this small module: https://github.com/sjsam/Drupal-MOPL. When you download the zip folder, you'll want to change the folder name to "mopl".
In order to use this:
1) Create a new order or update a existing order.
2) Set your discounted prices in your new field.
3) Set the status to "Checkout: checkout".
The customer will now get a link to click in order to complete the checkout.
If they have populated their cart first. Edit it accordingly and save the order. When they refresh the page their cart prices will get updated.
In the question I also wanted to add a fixed price discount from the discount module. I couldn't work out how to have the "Fixed price discount" applied when the customer completes checkout. So I created a product called Discount and set the price to zero. I then add that product to the cart and set the discounted unit price to the discount I want ie -300.
At this point the customer could go back to the Shopping cart page and update the qty for the discount product. So I added a filter to exclude the "discount" product.
That's it!

# Answer
> 0 votes
There aren't many good solutions here, because you're hitting up against the limitations of the pricing system. You have two basic options: custom line item fields that contain special pricing paired with a pricing rule that overrides the default product price or some combination of discounts that adjust product prices solely for that user. The former may be a challenge, because I can't remember if we ever fully got Inline Entity Form to manage line items, and the latter would be a pain for orders with a lot of different products.

The Commerce Price List module was ultimately developed to handle situations like this, where price lists can be assigned on a per user / quantity basis. It appears the same feature set works in D7 as in D8, but it would give the customer access to that pricing on any order while the price list was active, not just a single one. If that's no problem, then that's probably your solution.

---
Tags: 7, commerce
---


# Question
Title: How to test an alter hook in your .module with ModuleHandler service?
I have setup a kernel test to test a function in my module:

```
/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {
  // ... code
}

```

In my test, I tried:

```
$variables = [...array];
$this->container->get('module_handler')->invoke('mymodule', 'link_alter', $variables);

```

But what I got was:

> Parameter 1 to mymodule\_link\_alter() expected to be a reference, value given.

For now I removed that line and just called the function directly. Is there a way to invoke a hook that does not throw that error?

# Answer
> 2 votes
For alter hooks, there is `ModuleHandler::alter()`. That is what, for example, the `AlterTest` class uses.

```
// Verify alteration of a single argument.
$array_copy = $array;
$array_expected = [
  'foo' => 'Drupal theme',
];
\Drupal::moduleHandler()->alter('drupal_alter', $array_copy);
\Drupal::theme()->alter('drupal_alter', $array_copy);
$this->assertEqual($array_copy, $array_expected, 'Single array was altered.');
$entity_copy = clone $entity;
$entity_expected = clone $entity;
$entity_expected->foo = 'Drupal theme';
\Drupal::moduleHandler()->alter('drupal_alter', $entity_copy);
\Drupal::theme()->alter('drupal_alter', $entity_copy);
$this->assertEqual($entity_copy, $entity_expected, 'Single object was altered.');

```

The Drupal 7 documentation for `module_invoke()` is more explicit in suggesting to use `drupal_alter()` for arguments passed by reference.

> All arguments are passed by value. Use `drupal_alter()` if you need to pass arguments by reference.

If the hook you are testing is also implemented from one of the modules from which your module depends, `ModuleHandler::alter()` would invoke the hook implemented from those modules (if those modules are installed from the test), but I take that testing an alter hook means also testing it works together the same hook implemented by the module dependencies. (In this way, the module can also test if its alter hook implementation needs to be executed earlier or later, respect other implementations of the same hook.)

if you really need to invoke a single alter hook, and other modules installed from the test implement it, you could use the following method to add in the test class.

```
function protected invokeAlterHook($module, $type, &$data, &$context1 = NULL, &$context2 = NULL) {
  $function = "$module_$type";
  $function($data, $context1, $context2);
}

```

If you look at the code in `ModuleHandler::alter()`, that is simply the way it invokes the hook implementations.

```
  foreach ($this->alterFunctions[$cid] as $function) {
    $function($data, $context1, $context2);
  }

```

`ModuleHandler::invoke()` doesn't work with parameters expected to be passed as reference because it uses the following code to invoke the hook.

```
$function = $module . '_' . $hook;
return call_user_func_array($function, $args);

```

To pass an argument by reference, `call_user_func_array()` should be called, for example, as `call_user_func_array($function, [&$data])`.

---
Tags: 8, testing
---


# Question
Title: Cannot print page title in page.html.twig
The following line in `page.html.twig` does not print the page title:

```
<h1>{{ title }}</h1>

```

The page title outputs using the `Page title` block, but not this piece of template code. I found the `title` variable in the documentation commented out at the top of `page.html.twig`. Does this code need to be wrapped in something else?

# Answer
The variable `{{ title }}` is only used in maintenance and install pages where blocks are not available. See the change record https://www.drupal.org/node/2568563
> 2 votes

# Answer
Sometimes your overall site architecture might have **Page Title block** settings using content types or other configuration which might leave one-off cases where this doesn't allow the rendering of the block via a given region.

You *can* render the page title with:

```
<h1>{{ drupal_title() }}</h1>

```

But much better... You can call the page title block in your `page.html.twig` template this way:

```
{{ drupal_block('page_title_block') }}

```

This will render the Page Title block (which works with translations).

---

Small note that printing the Page Title block this way can have a different array structure than rendering the page title block via a region, so if you are applying a page title alter somewhere, for example, you may have to take this into consideration.

```
function MYMODULE_preprocess_page_title(&$variables) {
  if (array_key_exists('#markup', $variables['title'])) {
    $variables['title']['#markup'] = $value;
  }
  else if (isset($variables['title'])) {
    $variables['title'] = $value;
  }
}

```

---

But of course, you can place another instance of the Page Title block via the block admin form and configure unique display settings, as well as place it in a custom region if needed.
> 2 votes

---
Tags: theming
---


# Question
Title: How do I disable Twig and block cache for a specific module?
I'm working on a module in Drupal 8 which retrieves time sensitive data from an external REST api. The data is processed and forwarded to a Block. The final data is sent to a Twig template like so:

```
...

public function build() {
  $build = [];

  $build['ticker_block'] = [
    '#theme' => 'module_theme',
    '#data' => $myService->data(),
  ];

  return $build;
}

```

This doesn't work on the production environment where cache is enabled and the rendered data shows up as stale. How do I disable cache for my module only, and do I have to do it for both the Twig template and Block plugin?

# Answer
You can control the cache in the render array with the #cache element.

To disable the cache add:

```
$build['#cache']['max-age'] = 0;

```

In this case the block will not be cached for logged in users or anonymous users with a session.

If you want to disable the cache for anonymous users without a session:

> Disable it either by uninstalling the page\_cache module completely or by triggering the kill switch, see How can I prevent a particular page being cached? for example.

The caching of the twig code is not connected to this, the twig code is only cached once, the first time it is used after you cleared the cache.

(edit acc. to comments of Berdir)
> 28 votes

# Answer
To stop caching a specific block use the following function:

```
/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function template-name_preprocess_block(&$vars) {
  if($vars['derivative_plugin_id'] == 'add-block-id-name') {
    //-- This stops the block being cache in drupal 8
    $vars['#cache']['max-age'] = 0;
  }
}

```
> 9 votes

# Answer
Disable cache for a specific page/content type/controller

> Disable cache for a custom page from route declaration.
>
> If you want to disable cache for a custom controller (Custom module), You have `no_cache` option (YOUR\_MODULE.routing.yml). Example : File : mymodule.routing.yml

```
mymodule.myroute:
  path: '/mymodule/mypage'
  defaults:
    _controller: '\Drupal\mymodule\Controller\Pages::mypage'
    _title: 'No cache page'
  requirements:
    _access: 'TRUE'
  options:
    no_cache: 'TRUE'

```

Added 'no\_cache' route option to mark a route's responses as uncacheable
> 6 votes

# Answer
To prevent caching of a particular block:

add the below code in *theme\_name.theme* file

```
function theme_name_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_id') {
    $variables['#cache']['max-age'] = 0;
  }
}

```
> 1 votes

# Answer
To disable the cache for a block type, preprocess the block of that type and set max\_age to 0.

```
   /**
     * Implements hook_preprocess_HOOK() for Block document templates.
     */
    function THEMENAME_preprocess_block(array &$variables) {

      //disbale cache from spotlight
      $content = $variables['elements']['content'];
      //dump($content); //check the contents
      if (isset($content['#block_content']) && $content['#block_content'] instanceof BlockContentInterface) {

        if ($content['#block_content']->bundle() == 'BLOCK_TYPE') {
          $variables['#cache']['max-age'] = 0;
        }

      }

    }

```
> 1 votes

---
Tags: 8, caching, theming
---


# Question
Title: How do I manipulate a variable's property in Twig?
I want to add classes to a link render element that's a property of the {{content}} variable in my template.

I can do this:

```
{% set link = content.my_link %}
{% set link = link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ link }}

```

But I don't seem to be able to manipulate content.my\_link directly. Why can't I do this:

```
{% content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ content.my_link }}

```

# Answer
`{%` doesn't render, and `merge` doesn't operate by reference. With those two things in mind, this:

```
{% content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}

```

does nothing, except to waste CPU cycles; you're not rendering, nor saving, the result of the `merge`.

There are various ways to solve, this is probably the simplest:

```
{% set link = content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ link }}

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to let users remove a specific field or fieldset on a custom form using the form api?
I followed this Drupal example: https://git.drupalcode.org/project/examples/blob/8.x-1.x/form\_api\_example/src/Form/AjaxAddMore.php

I've edited the code a bit to use fieldsets instead of just one field. This seems to work, though I'm not sure if I did this correctly.

I now have a custom form that allows users to create new fields and remove the last field in the list.

What I need is a remove button next to each field that allows the end-user to choose which field to remove instead of only being able to remove the last field.

I don't know how to get the selected field or fieldset in the submit handler though.

Here's the code I currently have:

```
<?php

namespace Drupal\xxx\Form;

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

class DebtorForm extends FormBase {

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

  public function buildForm(array $form, FormStateInterface $form_state) {

    // Gather the number of lines in the form already.
    $num_lines = $form_state->get('num_lines');
    // We have to ensure that there is at least one line field.
    if ($num_lines === NULL) {
      $num_field = $form_state->set('num_lines', 1);
      $num_lines = 1;
    }

    $form['#tree'] = TRUE;
    $form['names_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Je onbetaalde factuur'),
      '#prefix' => '<div id="invoices-fieldset">',
      '#suffix' => '</div>',
    ];

    for ($i = 0; $i < $num_lines; $i++) {
      // Fieldset line title
      $form['names_fieldset'][$i] = [
        '#type' => 'fieldset',
        '#title' => $this->t('Factuur') . ' ' . ($i + 1),
      ];
      // disputed
      $form['names_fieldset'][$i]['disputed'] = [
        '#type' => 'radios',
        '#title' => $this->t('Mijn factuur is'),
        '#options' => array(
          0 => $this->t('Niet betwist'),
          1 => $this->t('Betwist'),
        ),
      ];
      // date
      $form['names_fieldset'][$i]['date'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Datum factuur'),
      ];
      // amount
      $form['names_fieldset'][$i]['amount'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Bedrag factuur'),
      ];
      // invoiceId
      $form['names_fieldset'][$i]['invoiceId'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Factuurnummer'),
      ];
      $form['names_fieldset'][$i]['invoiceId'] = [
        '#type' => 'submit',
        '#value' => $this->t('Verwijder'),
        '#submit' => ['::removeCallback'],
        '#ajax' => [
          'callback' => '::addmoreCallback',
          'wrapper' => 'invoices-fieldset',
        ],
      ];
    }

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

    $form['names_fieldset']['actions']['add_name'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add one more'),
      '#submit' => ['::addOne'],
      '#ajax' => [
        'callback' => '::addmoreCallback',
        'wrapper' => 'invoices-fieldset',
      ],
    ];

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

    return $form;

  }

  /**
   * Callback for both ajax-enabled buttons.
   *
   * Selects and returns the fieldset with the names in it.
   */
  public function addmoreCallback(array &$form, FormStateInterface $form_state) {
    return $form['names_fieldset'];
  }

  /**
   * Submit handler for the "add-one-more" button.
   *
   * Increments the max counter and causes a rebuild.
   */
  public function addOne(array &$form, FormStateInterface $form_state) {
    $num_field = $form_state->get('num_lines');
    $add_button = $num_field + 1;
    $form_state->set('num_lines', $add_button);
    $form_state->setRebuild();
  }

  /**
   * Submit handler for the "remove" button.
   *
   * Removes the corresponding line
   */
  public function removeCallback(array &$form, FormStateInterface $form_state) {
    $num_field = $form_state->get('num_lines');
    if ($num_field > 1) {
      $remove_button = $num_field - 1;
      $form_state->set('num_lines', $remove_button);
    }
    $form_state->setRebuild();
  }

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

  }

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

  }

}

```

# Answer
After extensive searching and testing I found the following solution:

```
<?php

namespace Drupal\form_api_example\Form;

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

class AjaxAddRemoveElements extends FormBase {

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

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['description'] = [
      '#type' => 'item',
      '#markup' => $this->t('This example shows an add-more button and a remove button for each specific element.'),
    ];

    // Get the number of names in the form already.
    $num_lines = $form_state->get('num_lines');
    // We have to ensure that there is at least one name field.
    if ($num_lines === NULL) {
      $form_state->set('num_lines', 1);
      $num_lines = $form_state->get('num_lines');
    }

    // Get a list of fields that were removed
    $removed_fields = $form_state->get('removed_fields');
    // If no fields have been removed yet we use an empty array.
    if ($removed_fields === NULL) {
      $form_state->set('removed_fields', array());
      $removed_fields = $form_state->get('removed_fields');
    }

    $form['#tree'] = TRUE;
    $form['names_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('People coming to picnic'),
      '#prefix' => '<div id="names-fieldset-wrapper">',
      '#suffix' => '</div>',
    ];

    for ($i = 0; $i < $num_lines; $i++) {
      // Check if field was removed
      if (in_array($i, $removed_fields)) {
        // Skip if field was removed and move to the next field
        continue;
      }

      // Create a new fieldset for each person where we can add first and last name
      // Fieldset title
      $form['names_fieldset'][$i] = [
        '#type' => 'fieldset',
        '#title' => $this->t('Person ') . ' ' . ($i + 1),
      ];
      // date
      $form['names_fieldset'][$i]['firstname'] = [
        '#type' => 'textfield',
        '#title' => $this->t('First name'),
      ];
      // amount
      $form['names_fieldset'][$i]['lastname'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Last name'),
      ];
      $form['names_fieldset'][$i]['actions'] = [
        '#type' => 'submit',
        '#value' => $this->t('Remove'),
        '#name' => $i,
        '#submit' => ['::removeCallback'],
        '#ajax' => [
          'callback' => '::addmoreCallback',
          'wrapper' => 'names-fieldset-wrapper',
        ],
      ];
    }

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

    $form['names_fieldset']['actions']['add_name'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add one more'),
      '#submit' => ['::addOne'],
      '#ajax' => [
        'callback' => '::addmoreCallback',
        'wrapper' => 'names-fieldset-wrapper',
      ],
    ];

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

    return $form;

  }

  /**
   * Callback for both ajax-enabled buttons.
   *
   * Selects and returns the fieldset with the names in it.
   */
  public function addmoreCallback(array &$form, FormStateInterface $form_state) {
    return $form['names_fieldset'];
  }

  /**
   * Submit handler for the "add-one-more" button.
   *
   * Increments the max counter and causes a rebuild.
   */
  public function addOne(array &$form, FormStateInterface $form_state) {
    $num_field = $form_state->get('num_lines');
    $add_button = $num_field + 1;
    $form_state->set('num_lines', $add_button);
    $form_state->setRebuild();
  }

  /**
   * Submit handler for the "remove" button.
   *
   * Removes the corresponding line
   */
  public function removeCallback(array &$form, FormStateInterface $form_state) {
    // We use the name of the remove button to find the element we want to remove
    // Line 72: '#name' => $i,
    $trigger = $form_state->getTriggeringElement();
    $indexToRemove = $trigger['#name'];

    // Remove the fieldset from $form (the easy way)
    unset($form['names_fieldset'][$indexToRemove]);

    // Remove the fieldset from $form_state (the hard way)
    // First fetch the fieldset, then edit it, then set it again
    // Form API does not allow us to directly edit the field
    $namesFieldset = $form_state->getValue('names_fieldset');
    unset($namesFieldset[$indexToRemove]);
//    $form_state->unsetValue('names_fieldset');
    $form_state->setValue('names_fieldset', $namesFieldset);

    // Keep track of removed fields so we can add new fields at the bottom
    // Without this they would be added where a value was removed
    $removed_fields = $form_state->get('removed_fields');
    $removed_fields[] = $indexToRemove;
    $form_state->set('removed_fields', $removed_fields);

    // Rebuild form_state
    $form_state->setRebuild();
  }

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

  }

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

  }

}

```
> 2 votes

---
Tags: 8, forms
---


# Question
Title: Accessing contents of a node id not working in .theme file
I have a page(node) with a certain ID. On the front page, I want to pull a field called field\_image1 and field\_link1.

To do that I added the following to my themename.theme:

```
function themename_preprocess_page(&$variables) {

    $variables['vanilla_spice'] = Node::load(61);

    $variables['variable'] = "tetsing the variable";

}

```

page--front.html.twig:

```
{{ kint(vanilla_spice) }}
{{ kint(variable) }}

```

When I visit the page, the variable is null :(

How can I load this information inside the variable?

Note: I based myself in this answer here, but even if I assign a normal string to the vanilla\_spice variable

```
$vanilla_spice = "tetsing the variable";

```

I still see a null.

# Answer
First, you are using the wrong hook. peeprocess\_node won't send new variables into the page template. You need preprocess\_page for that. The page template is not the same as the node template.

Second you are not assigning any new variables. You have to add or alter what is in $variables array or they are not passed to the template.

`$variables['vanilla_spice'] = "testing the variable";`
> 1 votes

---
Tags: theming, entities
---


# Question
Title: login form generated by drupal_get_form('user_login_block') does not log in
I have a custom module part of which builds a block with the login form

```
function my_module_block_view($delta = '') {
  switch ($delta) {
    case 'awsImage_public_info_forms':
      $user_login = drupal_get_form('user_login_block');
      $out = drupal_render($user_login);
      $block['content'] = $out;
      break;
    }
  return $block;
}

```

Form shows up on the page I have set the block to, BUT it will not log in. I can add and incorrect username / password and I'll get a drupal status error about the incorrect username, but when the login details are correct, it will not log in - the page will reload with "?destination=node/1137" - node/1137 is the node I am using the block on. Admin pages just show access denied.

I can log in via /user and there are no watchdog messages.

# Answer
You shouldn't need to render the form, and this may be causing your problems. The output of drupal\_get\_form() is a render array, so you can use that directly. Try changing this:

```
$user_login = drupal_get_form('user_login_block');
$out = drupal_render($user_login);
$block['content'] = $out;

```

To this:

```
$block['content'] = drupal_get_form('user_login_block');

```

Also, are you doing anything else to the block with preprocessing or processing? Is the system rendering the block normally, or are you rendering the block in some different manner, with a template or something?
> 0 votes

---
Tags: 7, forms, blocks
---


title: Where do I find the comment IP address?

text:
# Question
Title: Where do I find the comment IP address?
I am searching for comments ip address in D8 and I can't find where they are located in database. In D7 it was easy to find.

Is there a chance that D8 is not storing the commenters ip address? If it is not, how can I store it?

# Answer
> 3 votes
IP addresses are stored in the `hostname` field of the comment entity (which you'd usually find in the `comment_field_data` table).

This functionality is disabled by default, though (see Stop logging comment IP addresses by default). To enable it, it looks like you need to set the config manually, e.g.

```
 \Drupal::configFactory()->getEditable('comment.settings')
   ->set('log_ip_addresses', TRUE)
   ->save(TRUE);

```

After running that, IP addresses will start being logged in the `hostname` field.

---
Tags: 8, comments
---


# Question
Title: Composite block from multiple other blocks + layout
I would like to create a block consisting of multiple other blocks, combined with a layout or some other kind of wrapper html.

A typical example would be a footer with 4 columns containing a menu, some custom text, etc.

The entire thing should be configurable in the UI and then exportable to the CMI system.

## Known solutions

I know that this is possible in Drupal 7 using renderkit \+ cfrblock. However this has not been ported to Drupal 8 (yet). I will get there eventually, but atm I would like to find out if another solution might already exist.

EDIT: On D8 there is blockgroup, but it does not really work for me.

## Related issues

How to group multiple blocks into one big block I think this is for D7.

Thanks!

# Answer
> 0 votes
Use blockgroup. Add block\_class if needed.

When creating the block groups, make sure that the machine name does not clash with existing theme region machine names! (from any theme, ideally)

After you created a block group, it will show up in two ways in the blocks UI:

* As a new theme region (if you avoided the name clash)
* As a block that can be placed.

Block class allows to add classes (e.g. bootstrap grid classes) to each block and block group.

This is not 100% what you would get with a layout, but it is getting close, and will be sufficient in many cases.

---
Tags: 8, blocks
---


# Question
Title: How to change the condition operator in the search api query?
I have a date field facet filter on my search api views page.

When I select a date in the filter, the search api display those results which has that date value selected in the date field.

I want to display those results which has a date value which is greater than or equal to the selected in the date facet filter.

Is it possible? I checked with the search api query alter hook but I can't see any helpful function to alter the condition.

# Answer
I have overridden these classes in my custom module

```
Drupal\facets\Plugin\facets\query_type\SearchApiDate;
Drupal\facets\QueryType\QueryTypeRangeBase;

```

And then modified this function

```
public function execute()

```

of `QueryTypeRangeBase` and used the correct operator.
> 0 votes

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


# Question
Title: How to display a date facet in a date popup/picker?
I have a date range field in my content type.

Is there any way to display a date popup/picker facet on my search page.

Any workaround? through facet api, javascript etc?

Because I have searched all the issues of facets module but nothing found any helpful.

# Answer
I have done it with the following way.

Created a custom form with date popup fields.

Displays it on the search page and hide the actual facet which is in links.

Then through javascript, I used the actual facets with the values from the date popup fields.
> 0 votes

---
Tags: 8, search
---


# Question
Title: Why is the programmatically removed paragraph item still showing after adding a new paragraph to the node?
I have a paragraph field in a node with unlimited add paragraph. I am removing these paragraph programatically. Its removing but when I am adding a new paragraph its adding blank paragraph along with.

I am using this code to remove paragraph

```
use Drupal\paragraphs\ParagraphInterface;
use Drupal\paragraphs\Entity\Paragraph;

$ids = \Drupal::entityQuery('paragraph')->execute();
foreach ($ids as $id) {
  $paragraph = Paragraph::load($id);
  if ($paragraph instanceof ParagraphInterface) {
    $paragraph->delete();
  }
}

```

# Answer
You have 3 tables doing the job: a table which stores node data, a table which stores paragraphs data, and a table which stores relation about node and paragraphs. Now you emptied the table which stores the paragraphs data, but the node-paragraph relation table is still there. So if you have added 4 paragraphs to a node and deleted that 4 paragraphs, still drupal assumes there should be 4 paragraphs attached to that node.

---

so if you want to delete them entirely you have to fetch node data which has "paragraph" field value, delete field value from each node and save it.

so here are steps : you can run a database query on field table, and get all node-paragraph relations. now you have a list of all nodes that have a paragraphs, so having node ids and paragraph ids you can first remove paragraphs from node using a code like this:

```
$node = Node::load($nid);
$node->FIELD_NAME->setValue(array());
$node->save();

```

and then delete correspond paragraphs using a code like the one you mentioned. of course you don't need another query as you have paragraph ids.

---

if you don't mind removing all paragraph values from database and only don't like them to be shown in your node, then you can write an entityquery like this :

```
$query = \Drupal::entityQuery('node');
$query->exists('field_to_check');//Check A field value is NOT NULL
$ids = $query->execute();

```

so it gives you all nodes which has value for that field, then you only can run :

```
foreach($ids as $nid) {
  $node = Node::load($nid);
  $node->FIELD_NAME->setValue(array());
  $node->save();
}

```
> 5 votes

---
Tags: 8, paragraphs
---


# Question
Title: Cron error message. table or view not found: 1146
In watchdog I am seeing an error when cron is run.

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'tdtvnksvps.field\_deleted\_data\_38d3088921' doesn't exist: SELECT DISTINCT t.entity\_id AS entity\_id FROM {field\_deleted\_data\_38d3088921} t WHERE bundle = :db\_condition\_placeholder\_0 LIMIT 50 OFFSET 0; Array ( \[:db\_condition\_placeholder\_0\] =\> ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>readFieldItemsToPurge() (line 1686 of /home/300465.cloudwaysapps.com/tdtvnksvps/public\_html/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Pretty sure I mistakenly deleted a table from the database a while back and this is the result.

The issue appears to be similar to Error when deleting some node, but I think the advice given to find a record of the deleted field was written for D7.

Is this the same problem and how resolve it for D8?

# Answer
> 2 votes
I Had this issue sometimes ago, I deleted a field table from DB manually and this error started to showing up, A way to get rid of it is to create a table for a field, so you can use a mysql code like that :

```
CREATE TABLE `field_deleted_data_38d3088921` (
    `bundle` varchar(128) CHARACTER SET ascii NOT NULL DEFAULT '' COMMENT 'test',
    `deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'A boolean indicating whether this data item has been deleted',
    `entity_id` int(10) unsigned NOT NULL COMMENT 'The entity id this data is attached to',
    `revision_id` int(10) unsigned NOT NULL COMMENT 'The entity revision id this data is attached to',
    `langcode` varchar(32) CHARACTER SET ascii NOT NULL DEFAULT '' COMMENT 'The language code for this data item.',
    `delta` int(10) unsigned NOT NULL COMMENT 'The sequence number for this data item, used for multi-value fields',
    `test` varchar(2048) DEFAULT NULL COMMENT 'test',
    PRIMARY KEY(`entity_id`,`deleted`,`delta`,`langcode`),
    KEY `bundle` (`bundle`),
    KEY `revision_id` (`revision_id`)
)

```

# Answer
> 2 votes
This issue is the opposite of Can I delete leftover field\_deleted\_\* tables?. In your case you have leftover field and field storage config entities serialized in the database table `key_value` as `state` collection in the keys `field.field.deleted` and `field.storage.deleted`.

Normally both, the config entities and the deleted tables, are removed in cron runs.

---
Tags: 8, cron
---


# Question
Title: How do I remove JOIN in hook_views_query_alter()?
I have a view with two filters (A + B). Filter B should only be included in the query, if a specific value in filter A is set (like a "conditional filter").

So I tried to remove the where condition of filter B in `hook_views_query_alter` by unsetting it:

```
if($remove_filter_B){
  foreach ($query->where as $condition_group_key => &$condition_group) {
    foreach ($condition_group['conditions'] as $condition_key => &$condition) {
      if($condition['field'] == 'field_B_to_remove'){
        unset($condition_group['conditions'][$condition_key]);
        break;
      }
    }
  }
}

```

I successfuly removed the where clause but the INNER JOIN on the table of filter B is still part of the query. How can I remove it? I've tried `unset($query->tableQueue['node__field_B_to_remove'])` but this doesn't work because `tableQueue` is protected.

Maybe I'm going the wrong way. Basicly I just want to have a "conditional filter".

Some aditional info: The view lists nodes of two different types. You can filter those node types with filter A. The field of filter B only exists in one of the node types. So if you choose filter B you only get nodes of one type. And when you select the other one in filter A you get no result. And that's the issue.

# Answer
you can add field B as a relationship and use as a reference term in your View UI
> 0 votes

# Answer
Leaving this issue as reference for the future: https://www.drupal.org/project/drupal/issues/2830680
> 0 votes

---
Tags: 8, views
---


# Question
Title: Disable cache on base url for redirecting unauthenticated users
I am trying to redirect unauthenticated users. So anytime an unauthenticated user tries to get to the base url, redirect them to an external url. Currently works, but continues to redirect to the external url even after user is authenticated and logged in. So I am trying to disable cache whenever the base URL is accessed.

Here is my current code for redirecting in my `src/EventSubscriber/RedirectAnonymousSubscriber.php` file:

```
class RedirectAnonymousSubscriber implements EventSubscriberInterface {
  private $redirectCode = 301;

  public function checkForRedirection(GetResponseEvent $event) {
//    to kill page caching:
//    \Drupal::service('page_cache_kill_switch')->trigger();
    $is_authenticated = \Drupal::currentUser()->isAuthenticated();
    $route_name = \Drupal::routeMatch()->getRouteName();

    if (!$is_authenticated && $route_name !== 'user.login') {
      $response = new RedirectResponse('https://example.com', $this->redirectCode);
      $response->send();
      exit(0);
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection', 30);
    return $events;
  }
}

```

Would that would be the correct way to go about things? And how would I go about implementing that in my \*.routing.yml file and elsewhere? Thanks!

# Answer
> 1 votes
Not Drupal specific, but you should use the status code 302. Redirects with a status code 301 are cached very aggressively by browsers.

In Drupal custom code, never send a response directly, set it in the event, so that it can be returned and cached properly by Drupal, which is by the way not a bad thing, because the page cache can handle different cached versions for authenticated and anonymous users:

```
$event->setResponse($response);

```

---
Tags: 8, routes, caching, redirection
---


title: Grouping Exposed Filters

text:
# Question
Title: Grouping Exposed Filters
I am working with the module Better Exposed Filters (BEF) within my view. I have about 12 exposed filters, some of theme are select lists and some are range sliders. Some filters thematically belong together which is why I try to visually group them under a headline. Unfortunately, this can't be done using BEF.

I also tried Views Exposed Groups but this module can only be used instead of BEF, not together (I need BEF because of the slider funcionality). Besides I tried MEFIBS (More Exposed Filters in Blocks) which isn't suitable for me too.

Does somebody know of another module that helps me to accomplish this problem?

PS: I am no coder so editing the exposed-form.tpl.php is the last option for me.

Thanks, Thomas

# Answer
if you get the filter slider effect how you want save the view and disable the BEF module then go back to the view it can work. I remember I tried something like this before. It might break if you go back and mess with the filter and not just grouping.
> 0 votes

# Answer
Have you tried the Views Exposed Form Fieldset module? It has releases for both Drupal 7 and 8.
> 0 votes

---
Tags: views
---


# Question
Title: How can I generate custom XML for a SOAP client?
Im building a SOAP client that consumes from a SOAP web services in a Drupal 8 module.

I need to generate this final XML:

```
$inpunt_data = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:qual="http://websoap.com/">

                           <soapenv:Header/>

                           <soapenv:Body>

                              <qual:myMethod>

                                 <!--Optional:-->

                                 <qual:xmlMethod><![CDATA[

                                <Tag>
                                </Tag>
                               </qual:Method>';

```

How do I generate soapenv headers?

I'm using simplexml:

```
$getXML = new SimpleXMLElement($input_data);
             $urlTarifa = 'http://soapurl.com?wsdl';
             $client = new SoapClient($urlTarifa);

```

# Answer
> 2 votes
This is how I've done it:

some-feed.html.twig

```
<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <atom:link href="{{ some_variable_set_in_preprocess }}" rel="self" type="application/rss+xml"/>
      /* -- rest of feed omitted */
  </channel>
</rss>

```

Then hook\_theme() to register the template:

```
function hook_theme() {
  return [
    'some_feed' => [
      'render element' => 'elements',
      'template' => 'some-feed',
    ],
  ];
}

```

You can then generate a response with that theme:

```
$build = [
  '#theme' => 'some_feed',
];

$response = new \Symfony\Component\HttpFoundation\Response();
$xml = \Drupal::service('renderer')->renderRoot($build);
$response->setContent($xml);
$response->headers->set('Content-Type', 'text/xml');

```

You now have a Response object to work with. Depending on where you are working, you can return that, or set it as a response.

---
Tags: 8, theming
---


# Question
Title: Find the current node title from my custom module
I'm working on a simple custom module (Drupal 8). How can I get the title of the current node and use it in module's template twig file (or pass it to twig file through PHP)?

# Answer
You can get it from the route parameters:

```
// Get the node for the current page, if one exists:
if ($node = \Drupal::routeMatch()->getParameter('node')) {
  // $node contains the node for the current page.
  $node_title = $node->label();
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: How can I print the file size and other file info in a Views field template?
I have created a content type with a number of fields including file fields. In the node template for that CT (node--unit.html.twig) I am able to get the details with the following code:

```
{% if content.field_files.0 %}
   {% for key, value in content.field_files if key|first != '#' %}
      <a href="{{ file_url(content.field_files[key]['#file'].uri.value) }}">{{ content.field_files[key]['#description']}}</a>
   {% endfor %}
{% endif %}

```

Now I'm trying to get those same details for the field inside a view that lists nodes of that CT but the above code doesn't work. In fact all I can get from the field is the 'content' using the following code inside the views-view-field template (views-view-fields--units-e-resource-sheets.html.twig):

```
{{ fields.field_e_resources.content}}

```

All I can find using kint and other tools is the target\_id attribute. Do I have to use this to retrieve those other details in the view?

# Answer
> 0 votes
Well with some pointers from colleagues I have found out what I was doing wrong!

In the node you have all that info already there but views and their displays are more stripped back to keep them 'lean' so you have to be explicit that you need that info...

## Step 1 - add a 'relationship' to the field

In the settings for the display of the view, I added a relationship to the file from the field under the 'advanced' settings using the 'add' button and it shows like this:

## Step 2 - add fields for the stuff from the relationship

Under the fields for the view display I can now add fields for the relationship I just created. I added one for the URI and one for the filesize using the 'add' button and they show like this:

## Step 3 - build the template

Now you can use those just like any regular field in the template. Here is the code I'm using to build a link with the file extension, filesize and a link to download the file:

```
<a href="{{ file_url(fields.uri.content|striptags|trim|convert_encoding('UTF-8', 'HTML-ENTITIES')) }}" target="_blank">Download
  (.{{ fields.field_e_resources.content|striptags|split('.')[1] }})({{ fields.filesize.content }})
</a>

```

## Conclusion

I couldn't access the details for the uploaded file because they aren't included by default so by building the relationships as required you can add to the available fields and get the job done!

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


# Question
Title: LinkItem: how to create a disabled / null link
How do I create a LinkItem that will render into

```
<a href="javascript:void(0)">Do nothing</a>

```

or another form of unclickable link?

**Motivation:**

I am implementing a computed field of type link, which under some circumstances should become disabled. The HTML attribute `disabled` is not sufficient.

**Code:**

```
if ($disabled) {
  $url = 'internal:#'; # want: 'javascript:void(0)';
  $attributes = ['class' => 'btn btn-danger', 'disabled' => ''];
  $title = t('Disabled');
}

$field_item_list->createItem(0, array(
  'uri' => $url,
  'title' => $title,
  'options' => ['attributes' => $attributes],
));

```

# Answer
A different option:

* Add a class to your disabled links.
* Create a JS behavior that targets a.your-class and uses preventDefault() on the click event.
* Add to libraries file for your module and add library as needed.

```
...
  $('a.your-class').click( function (e) {
    e.preventDefault();
  });
...

```
> 1 votes

---
Tags: 8, entities, uri
---


# Question
Title: Webform multi-page submit handler fires on every page
I have created a couple of webform submit handlers before, but my new one fires on every page submit rather than when the last page is submitted.

How do I get the webform handler to only fire after the full form is submitted?

Below is what I have at the moment, which fires on each page:

```
namespace Drupal\the_api\Plugin\WebformHandler;

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

/**
 * Webform submission remote post handler.
 *
 * @WebformHandler(
 *   id = "membership_api_post",
 *   label = @Translation("New Membership to API"),
 *   category = @Translation("External"),
 *   description = @Translation("Posts a new membership through to the API."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class NewMembershipWebformHandler extends WebformHandlerBase {

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param \Drupal\webform\WebformSubmissionInterface $webform_submission
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    parent::submitForm($form, $form_state, $webform_submission);

    kint($form_state);

  }
}

```

# Answer
You can use $webform\_submission-\>getState() to determine if the submission is completed. The EmailWebformHandler includes decent examples on how to the submission state. I recommend trying to use WebformHandler::postSave() instead of WebformHandler::formSubmit().
> 6 votes

# Answer
As I noted in the comments of the answer by jrockowitz, `postSave()` will fire multiple times in certain situations. I ran into this issue after installing the webform\_pardot module, which creates it's own submission entity that references the original webform submission entity via an entity reference field. When the pardot submission is saved, the webform entity is saved as well and `postSave` fires. Shortly after that the webform submission is completed/saved and `postSave` fires again.

The following should work for all situations:

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

    // This check is done to ensure that multi-page webform submissions do not
    // fire this code when the entire form is submitted. If the current page is
    // set to 'completed' then the multi-page form has been completely submitted.
    // When a single page webform is submitted the current page will return an
    // empty string and that condition will skip this test.
    $current_page = $webform_submission->getCurrentPage();
    if (!empty($current_page) && $current_page != WebformSubmissionInterface::STATE_COMPLETED) {
      return;
    }
  }

```
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: Creating commerce users programmatically
I need to import customer data from CSV files with billing and shipping data using Drupal 8.8 and Commerce 2. I want to create the customer with its address data programmatically, but i do not know how to create billing and shipping.

I create the user as:

```
 $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
 $user = \Drupal\user\Entity\User::create();
 $user->setPassword('password');
 $user->enforceIsNew();
 $email="xyz@email.com";
 $user->setEmail($email);
 $user->setUsername($email);
 $user->set("init", $email);
 $user->set("langcode", $lang);
 $user->set("preferred_langcode", $lang);
 $user->set("preferred_admin_langcode", $lang);
 $user->activate();
 // Save user account.
 $user->save();

```

How do i create its billing and shipping data?

# Answer
you got 2 options 1 migrate them, such as (https://www.drupal.org/project/migrate\_source\_csv) or make an admin form to submit the csv file and get the content... but really you need to be create profiles for this billing info...

```
// Save user account.
$user->save();
// Add billing info.
$the_user_created_id = $user->id();
$profileStorage = \Drupal::entityTypeManager()->getStorage('profile');
$profile_data = [
 'type' => 'customer',
 'uid' => $the_user_created_id,
 'status'=> 1,
 'address' => [
   "langcode" => "",
   "country_code" => "AU",
   "administrative_area" => "NSW",
   "locality" => "SOME PLACE",
   "dependent_locality" => null,
   "postal_code" => "2000",
   "sorting_code" => null,
   "address_line1" => "Some Street",
   "address_line2" => "",
   "organization" => "47",
   "given_name" => "firstname",
   "additional_name" => null,
   "family_name" => "lastname",
  ],
];

$new_profile = $profileStorage->create($profile_data);
$new_profile->save();

```
> 2 votes

---
Tags: 8, commerce
---


# Question
Title: How to send an email to multiple recepient with contact form?
I want to send an email to multiple recepients when the contact form is submitted. By default when contact form is submitted it is sending mail to default email id which is saved in system configuration.

How can we add multiple email addresses which will receive messages when any user submitted the contact form?

# Answer
> 0 votes
Here is a possible implementation to achieve what you're asking about:

* define a new eMail ID, say `x@sample.com`.
* configure this `x@sample.com` to automatically forward all incoming eMail to your "multiple eMail addresses".
* in your form, use `x@sample.com`as the email ID where these forms should be eMailed to (which will then be forwarded after you completed the prior step).

# Answer
> 0 votes
You can add multiple email in contact form setting itself separated by comma. I am attaching the screenshot for reference.

---
Tags: emails
---


# Question
Title: How to display only those nodes that current user has commented
On my D7 site I am trying to enable users to view the nodes where they have submitted their comments. I have tried adding 'Comments of the node' relationship, then added 'Comment: Author' and 'Comment: Author uid' contextual filters. Then set up filter criteria 'Comment: Author' to be equal/not equal to \[current-user:name\] and \[current-user:uid\]. It didn't help.

# Answer
The following works for me without a problem. I'm not sure where my method differs from yours:

* Relationship: Comments of the node
* Contextual filter:
    + Author uid using comments relationship
    + Provide default value: "User ID from logged in user"
* Use aggregation: Yes (to avoid duplicate nodes)

That's all, and it works like a charm.
> 1 votes

---
Tags: views
---


# Question
Title: How to alter a form element's properties before rendering?
Here's a simple task.

For accessibility reasons, from a custom module I need to perform alterations on textfield based form elements (such as email, textfield, etc ...) on custom forms displayed to front users.

These forms extends the Drupal\Core\Form\FormBase class.

The alterations I need to perform would be for exemple to automatically and programmatically copy the value of the field's placeholder text and put it in the field's title attribute (not the field's label, I'm talking about the HTML title attribute).

So the field's markup would look something like this :

```
<input type="email" placeholder="Email" title="Email" />

```

I want to check all custom forms for the entire website.

I tried different methods :

* hook\_field\_widget\_form\_alter : doesn't fire for fields on custom forms because they are not widgets.
* hook\_preprocess\_form\_element : It's too late to perform these changes. The values just won't take effect on the field.
* hook\_form\_alter : Well it's just too general, I find it a bit dodgy to parse the entire Render Array, check for fields, etc ... but may be it is the only way..

I looked into the Form API, Render API, Plugins API, I looked into services, nothing seems to offer any solution, unless of course I missing something, and I probably do.

Has anyone any idea on how to achieve this in the best Drupal 8 way?

# Answer
In `hook_template_preprocess_form_element` the (input-)tags is already rendered. You can use

```
function hook/template_preprocess_input(&$variables) {
  $variables['attributes']['title'] = 'my-title';
  $variables['attributes']['placeholder'] = 'my-placeholder';
}

```

to alter the input tag. use the same method for all other desired tags. Here's a nice tutorial.

> You could make use of hook/template\_preprocess to go a more generic way.
> 4 votes

# Answer
here is a piece of code :

```
function MODULE_preprocess_input(&$variables) {
    if (!\Drupal::service('router.admin_context')->isAdminRoute()) {
        $field = $variables['element'];
        if ($field['#type'] == 'email') {
            if (isset($field['#attributes']['placeholder'])) {
                $placeholder = $field['#attributes']['placeholder'];
                $variables['element']['#attributes']['title'] = $placeholder;
            }
        }
    }
}

```
> 3 votes

# Answer
None of above works for me. There is no 'title' field which can be changed, but instead there is a TranslatableMarkup object inside `$variables["attributes"]["value"]`

For me this works:

```
function MODULE_preprocess_input(&$variables)
{
  if ($variables['attributes']['class'][0] == 'delete-order-item') {

    $variables["attributes"]["value"] = new \Drupal\Core\StringTranslation\TranslatableMarkup("X");
  }
}

```

Basically I'm changing name of "Remove" button to just "X" and title really is replaced, but problem is that with new name (value attribute actually) delete action is not working any more. But title is replaced successfully.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Drush rsync permission woes (files directory)
I'm rsyncing just the files directory (rest of the site is done through git) from my local Ubuntu setup to my centOS server. It worked at least (thankfully), but produced a ton of errors.

First it said:

> rsync: failed to set times on "/home/myuser/mycentossite/sites/default/files/ctools": Operation not permitted (1)

Then tmp files and js files stated play up (sometimes happens on Ubuntu setup when clearing cache also)

> rsync: mkstemp "/home/mycentosuser/mysite/sites/default/files/js/.js\_ouzQFXPVCjfNTxl3b4ONpKTE.js.nghTEc" failed: Permission denied (13)
>
> rsync: send\_files failed to open "/home/myubuntuuser/websites/mysite/sites/default/files/tmp/file5GjL": Permission denied (13)

I fixed the permissions errors gradually with CHOWN and things started to work on the site. Though I'm wondering what is the correct way to go about rsyncing between local/remote in regard to permissions? And what happens if I rsync again - will it overwrite the stuff I've changed the permissions for? Or just add the new files?

Somewhat related.. My CentOS setup which uses the DSO PHP handler is also nagging me whenever I visit a page which generates a new folder of some kind. Is there way to set this up without having to go around putting CHMOD 777 on everything? (I'm the only user, so 777 in itself is not a problem for me...)

Thanks for any thoughts :)

# Answer
> 1 votes
Permissions issues are fairly complicated.

First off, the "failed to set times" message occurs because only the file owner can perform this operation. The solution to this problem, then, is to insure that the 'remote-user' element of your Drush site alias is the same as the owner of the files on the target machine. When pulling files to the local machine with drush rsync, it works best if you run Drush as the same user that the files are owned as.

What specific sets of permissions you choose after that is largely up to you, as there are a number of options that will work fine. What I do is make all web server code files owned by a 'www-admin' user on the live site, and owned by my local user on my dev site. On both live and dev, the files group is the webserver group, usually www-data, with directories that the webserver can write to being group-writable (and all others are set to not be group-writable, of course). Any file created by the webserver will by necessity be owned by the webserver, of course.

This works well for most situations; however, it does mean that if you rsync %files from dev to live, you won't be able to overwrite anything that was uploaded by the webserver. You might consider this a useful feature, though, as it prevents accidental overwrites.

# Answer
> 1 votes
This is a pretty old post, but these days the Stage File Proxy module removes the need to rsync files from production environments to other environments.

---
Tags: drush, deployment
---


# Question
Title: View should show related articles from shared reference field - relation from a relation
I have two content types: Article and Magazine. in Article there's an entity reference field to Magazine, field\_related\_magazines.

On my website, when an article is shown, I would like to show a list of related articles that share the same magazine.

When I make a new article, I can choose the magazine edition in which the article appeared. Then, on the bottom of the node page, all other articles should be listed.

**The thing I tried:**

Make a views block 'Magazine related items' that lists Article titles and place the block on the Article pages.

Set the context for the block to work: Advanced\>Contextual Filters\>Content ID\>Provide default value\>Content ID from URL

Set the relation: relationships\>Content using field\_related\_magazines (relate each Content with a field\_related\_magazines set to the content item.)

However, this only shows the current articles' title, not the titles of all other articles that share the same magazine. How would I get all the others?

# Answer
> 1 votes
In order to fetch resources under specific Megazine, you need to have the Magazine ID on your contextual filter instead of the Article ID. Here is my suggestion:

Play with your URL pattern to add the magazine ID to it (You can do this using Pathauto and Token Module). Once you install those two modules define a URL Pattern for your articles (/\[node: field\_related\_magazines:entity\]/\[node:title\])

Now you each article page will have a URL with Magazine ID to it so, you can change your contextual filter to get Magazin ID from the URL using "Raw Value From URL". This will give you the result you are looking for.

---
Tags: views, 8
---


# Question
Title: How do I remove the itok token from the image URLs?
How do I remove the itok token from the image URLs?

I found an article discussing it, but it only works for Drupal 7 (https://www.drupal.org/node/1934498).

Some articles explains why Drupal adds tokens to the image URLs.

# Answer
> 13 votes
While it's recommended to keep the `itok` parameter, it is configurable.

You can suppress it from output using the `image.settings` config setting `suppress_itok_output`

```
  // The token query is added even if the
  // 'image.settings:allow_insecure_derivatives' configuration is TRUE, so
  // that the emitted links remain valid if it is changed back to the default
  // FALSE. However, sites which need to prevent the token query from being
  // emitted at all can additionally set the
  // 'image.settings:suppress_itok_output' configuration to TRUE to achieve
  // that (if both are set, the security token will neither be emitted in the
  // image derivative URL nor checked for in
  // \Drupal\image\ImageStyleInterface::deliver()).

```

https://api.drupal.org/api/drupal/core!modules!image!src!Entity!ImageStyle.php/function/ImageStyle%3A%3AbuildUrl/8.2.x

# Answer
> 2 votes
Put this in your settings.php (or local.settings.php):

```
$config['image.settings']['suppress_itok_output'] = TRUE;

```

---
Tags: 8, media
---


# Question
Title: How can you prepopulate a field based on another field's value?
this one was easy in Drupal 7. I defined a condition "If field A has value B, then field X will automatically get value Y".

How can I get this working for a Drupal 8 webform?

# Answer
FYI, the module maintainer will send you here if you enter a support question - he will **not** answer it in the issue queue.
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Explicitly passing argument to local action for access check
I'm using the group module, and in a custom module I'm trying to create a local task that will bring you directly to the create page for a particular group content type. My goal is to skip the create page where you select the content type.

I've defined a local task:

```
entity.group_content.create_form:
  route_name: entity.group_content.create_form
  title: 'Add new service'
  defaults:
    plugin_id: group_node:service
  appears_on:
    - 'view.group_services.page_1'

```

It doesn't complain about passing the `$group` for the access check, which I'm assuming is being successfully passed due to query magic. Where it breaks down is on `$plugin_id` on the access check with the error.

> RuntimeException: Callable "Drupal\group\Access\GroupContentCreateEntityAccessCheck::access" requires a value for the "$plugin\_id" argument. in Drupal\Component\Utility\ArgumentsResolver-\>handleUnresolvedArgument() (line 142 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).

As an example, the route I'm trying to provide would end up being:

/group/{group}/content/create/{plugin\_id}

aka

/group/1/content/create/group\_node%3Aservice

What am I missing here?

# Answer
Answered my own question. The key is that we are working with route parameters, not route options which are akin to `l()` in Drupal 7.

This article goes into more detail. Here is the important part:

```
# yaml file to define one or more local task(s).
#
# Definitions can contain any of the following:
# title: (required) The untranslated title of the menu link.
# description: The untranslated description of the link.
# route_name: (optional) The route name to be used to build the path. Either a
#   route_name or a link_path must be provided.
# base_route: Used to group together related tabs.
# parent_id: Use the parent_id to relate a tab to a parent tab for multiple
#   levels of tabs.
# route_parameters: (optional) The route parameters to build the path. An array.
# link_path: (optional) If you have an external link use link_path instead of
#   providing a route_name.
# weight: (optional) An integer that determines the relative position of items
#   in the menu; higher-weighted items sink. Defaults to 0.
#   Menu items with the same weight are ordered alphabetically.
# options: (optional) An array of options to be passed to l() when generating
#   a link from this menu item.

```

So my action routing file is updated:

```
entity.group_content.create_form:
  route_name: entity.group_content.create_form
  title: 'Add new service'
#  defaults:
  route_parameters:
    plugin_id: group_node:BUNDLE
  appears_on:
    - 'view.group_services.page_1'

```

Be sure to replace *BUNDLE* with the content type machine name you would like to pass.

Flush caches.
> 1 votes

---
Tags: 8, nodes, routes, group
---


# Question
Title: How do I assert for a link's href AND link text in a functional test?
In a functional test, I can use `WebAssert::linkByHrefExists()` to check that a link with a specific href exists on the page. And I can use `WebAssert::linkExists()` to check that a link with a specific link text exists on the page.

But there's no guarantee that these two will find the same link! How do I check that a link on the page has the expected href AND text?

# Answer
> 1 votes
Perhaps a better approach will be assert by XPath selector `\Drupal\Tests\BrowserTestBase::xpath` something like `'//a[@href="' . $url .'"][contains(text()=\'Some text\')]'` as XPath. Check this post about matching text and this about matching url.

# Answer
> 0 votes
I've done some poking around with Mink's selectors and the methods available on its element objects, and I can manage this:

```
$this->assertEquals('/expected/link/path', $page->findLink("Expected Link Text")->getAttribute('href'));

```

It's not quite as readable as the WebAssert methods though.

---
Tags: 8, testing
---


# Question
Title: How can I change a user's password from the command line using Drush?
How can I change a user's password from the command line using Drush?

# Answer
In Drush 9, the command is `drush user:password USERNAME "SOMEPASSWORD"`; its aliases are *user-password* and *upwd*.

In Drush 8 (and earlier) the command is `drush user-password USERNAME --password="SOMEPASSWORD"`; its alias is *upwd*.
> 145 votes

# Answer
You can execute `drush uli`, this will generate a one time login link. By default it provides one-time login link for administrator.

If you execute `drush uli some-username`, this will generate one time login link for that user.

**UPDATE:**

You can also use `drush upwd` for updating the password. Use it like this `drush upwd --password=<new password> <some-username>`
> 35 votes

# Answer
If you are using Drush 4, you can use the user-password command.

```
drush user-password usernamehere --password="newpasswordhere"

```
> 15 votes

# Answer
> $ drush help user-password (Re)Set the password for the user account with the specified name.
>
> Examples: drush user-password someuser --password="correct horse battery" Set the password for the username someuser. @see xkcd.com/936
>
> Arguments: name The name of the account to modify.
>
> Options: --password= The new password for the account. Required.
>
> Aliases: upwd
> 14 votes

# Answer
In Drush 9 (recommended for \> Drupal 8.4) this is slightly different:

```
drush upwd USERNAME PASSWORD

```
> 14 votes

# Answer
There is another way to reset password. You can use `drush uli "username"` which gives reset link in terminal, using the link you can login and change the password.

If you specify `-l http://localhost` (where localhost is your host), then terminal would automatically open web browser for you.
> 5 votes

# Answer
in New version of Drush(In Drush 9 Drupal \> 8.5 ) it doesn't work with

```
drush user-password USERNAME --password="SOMEPASSWORD"

```

**It must be**

```
drush user-password USERNAME SOMEPASSWORD

```

for example ( change password of root user)

```
drush user-password root MyPass0302

```

And with Drupal Console

```
drupal user:password:reset

```

then enter userid,
then type new password.

Enjoy it.

**Update**

in Drush \> 9

```
drush upwd USERNAME PASSWORD

```
> 4 votes

# Answer
If you have ssh access to the server, cd to the drupal root directory and run:

`drush upwd --password="myNewSecretPassword" "admin"`

Source: https://www.drupal.org/node/44164
> 2 votes

# Answer
Note that this command has changed in Drush 9.x, but can be found documented here

The syntax thus looks like this:

```
drush user:password someuser "correct horse battery staple"

```

For example, on the user 'bjenkins' it would be:

```
drush user:password bjenkins "newReallyComplexPassword123!"

```

You can also add a `--notify` command to notify the user of this password change to their registered email.
> 1 votes

# Answer
Here you can generate the query and run it in your Drupal Database then the password will be reset http://btobac.com/reset-drupal-admin-password-mysql-query-phpmyadmin
> 0 votes

---
Tags: users, drush
---


title: Download file after filling a form

text:
# Question
Title: Download file after filling a form
On my site, the visitors can download whitepapers as pdf. I would like to gather some information before handing over the file. Updates: the downloads should be open to unregistered users

What I tried: I looked around for modules. Some of them seemed to do something like this but were Drupal 7 only, like Webform Protected Downloads. On the site I can make use of the Webform module as per this question. I could make a form with a redirect page where the file can be downloaded. However, as there are many whitepapers, for each one there should be made a separate form and download page. Update: in Webform it is possible to stay on the same page and output a thank you message with download link, so that will limit the effort somewhat.

Is there a simpler way to solve this?

# Answer
Instead of creating different webforms for each file, you could just have one form that can handle this. Here is my suggestion:

1. Make all links to your whitepapers to load a webform and pass the filename as a parameter for your webform. You can then store that on a hidden field on the form.
2. Create a custom submission handler for your webform to trigger a download upon submission (use the filename from the hidden field on the form).
> 2 votes

# Answer
To stream (and protect) the file, you should try using https://www.drupal.org/project/webform\_confirmation\_file
> 2 votes

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


title: How do I inherit from the base theme?

text:
# Question
Title: How do I inherit from the base theme?
I want to inherit from the businessplus\_lite theme I use as base theme, but I can't see any CSS applicable. There is just a board template blank with articles. Can anyone tell me how I can inherit the CSS styles from businessplus\_lite?

```
name: some name
type: theme
description: 'description for my theme'
core: 8.x
base theme: businessplus_lite

```

# Answer
It looks like you've created the `*.info.yml` file, but not yet created a `*.libraries.yml` file.

The libraries file is where you'll define which CSS is used in your theme.

See for more details on how to set this up: https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme#s-example-sub-theme-fluffiness
> -1 votes

---
Tags: theming
---


# Question
Title: hook_form_FORM_ID_alter in theme file to toggle field visibility
I have a boolean check box that I want to control the visibility of an entity-reference field below it. By default, this check box is unchecked, which means the entity-reference field should not be shown.

I've tried a handful of things in my .theme file, but I can't seem to solve the problem.

```
use Drupal\Core\Form\FormStateInterface;

function mytheme_form_node_news_form_alter(&$form, FormStateInterface
  &$form_state, $form_id) {
    $form['field_news_top_story_image']['#states'] = [
    'visible' => [
        ':input[name="field_news_topstory"]' => ['checked' => TRUE]
    ]
];

```

}

node\_news\_form (and eventually node\_news\_edit\_form once I figure this out) appears to be the form I want to affect. field\_news\_topstory is my checkbox and field\_news\_top\_story\_image is the entity-reference field I want to hide\* until field\_news\_topstory is checked. \*I've set this field to disabled in Manage Form Display.

Am I close? :)

EDIT: Had my code backwards, but still not working.

# Answer
After a lot of banging on this, I found the right combo. We don't have a custom admin theme, so I ended up moving this code in to a custom module.

The important part I was missing was **\[value\]** in ':input\[name="field\_news\_topstory\[value\]"\]' =\> \['checked' =\> TRUE\]

```
use Drupal\Core\Form\FormStateInterface;

function mymodule_form_node_news_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    $form['field_news_top_story_image']['#states'] = [
       'visible' => [
         ':input[name="field_news_topstory[value]"]' => ['checked' => TRUE]
       ]
   ];
}

```
> 0 votes

---
Tags: 8, forms, hooks
---


title: Unique taxonomy term

text:
# Question
Title: Unique taxonomy term
I need a specific vocabulary (A) that has unique terms. I don't want to do validation at form level because I want to be able to add term from *everywhere*.

I successful used `hook_entity_bundle_field_info_alter()` and `addConstraint()` to be sure one specific field is unique on another vocabulary (B). (Will this be deprecated? See https://www.drupal.org/node/2346347.)

For the vocabulary (A), there is no specific field, so the `hook_entity_bundle_field_info_alter()` is not working here, as this field `name` is not a "true" field.

I use `hook_entity_presave()`, but I'm not able to do a proper validation because this hook is called too late in the code, except if I use Exception, but that is not a good way.

How can I achieve what I am trying to do?

# Answer
> 1 votes
For the Drupal 8 you can use the contrib module.
It's called Taxonomy unique .
It is a stable module with a good usage statistics

# Answer
> 0 votes
That hook wont' go away and its fine to use it. That warning was added a while ago, it's not possible to change it anymore in 8.x AFAIK. We hoped to do that before the stable release.

Name is a true field but it is a base field. You should be able to get the base field definitions from the entity type manager if it is not there, clone it and add your constraint.

---
Tags: taxonomy-terms, 8, entities
---