# Question
Title: How can I stop the Devel module from generating blog/forum entries for Anonymous user?
I'm using Devel's generate content feature to generate Blog/Forum entries for a site I'm working on and funny enough, I get to have a blog post by an anonymous user or forum topic by an anonymous user.

How can I stop Devel from doing this? I've only given Authenticated Users/ Administrators the permission to create a blog post or forum topic but still it generate for anonymous user. How can correct this?

# Answer
The Devel module doesn't have options to decide to which users the generated content is assigned, but you can create a custom module to limit the users to which the created content is assigned. You need to:

* Implement hook\_form\_alter() to add the extra form fields necessary to select which users accounts should be used in the form generated by devel\_generate\_content\_form()
* Replace the form submission handler with one that generates the content using the user accounts selected in the form

You can use the existing form submission handler (devel\_generate\_content\_form\_submit()) as guideline to build your submission handler.

```
function devel_generate_content_form_submit($form_id, &$form_state) {
  module_load_include('inc', 'devel_generate', 'devel_generate');
  $form_state['values']['node_types'] = array_filter($form_state['values']['node_types']);
  if ($form_state['values']['num_nodes'] <= 50 && $form_state['values']['max_comments'] <= 10) {
    module_load_include('inc', 'devel_generate');
    devel_generate_content($form_state);
  }
  else {
    module_load_include('inc', 'devel_generate', 'devel_generate_batch');
    devel_generate_batch_content($form_state);
  }
}

```

Unfortunately, devel\_generate\_content() doesn't allow to select the user accounts to use as authors of the nodes. This means you need to write all the code yourself. The bright side is that the function that in your module replaces `devel_generate_content()` is very similar to that function with a single difference: the function to call instead of devel\_generate\_content\_pre\_node().

```
function mymodule_generate_content($form_state) {
  if (!empty($form_state['values']['kill_content'])) {
    devel_generate_content_kill($form_state['values']);
  }

  if (count($form_state['values']['node_types'])) {
    // Generate nodes.
    mymodule_generate_content_pre_node($form_state['values']);
    $start = time();
    for ($i = 1; $i <= $form_state['values']['num_nodes']; $i++) {
      devel_generate_content_add_node($form_state['values']);
      if (function_exists('drush_log') && $i % drush_get_option('feedback', 1000) == 0) {
        $now = time();
        drush_log(dt('Completed !feedback nodes (!rate nodes/min)', array('!feedback' => drush_get_option('feedback', 1000), '!rate' => (drush_get_option('feedback', 1000) * 60) / ($now -$start))), 'ok');
        $start = $now;
      }
    }
  }
}

function mymodule_generate_content_pre_node(&$results) {
  // Get user id.
  $users = mymodule_get_users($results['exclude']);
  $results['users'] = $users;
}

function mymodule_get_users($exclude) {
  $users = array();
  $result = db_query_range("SELECT uid FROM {users} WHERE uid NOT IN :exclude", 0, 50, array(':exclude' => $exclude);
  foreach ($result as $record) {
    $users[] = $record->uid;
  }

  return $users;
}

```

The code I shown assume you add a form field (*exclude*) that contains the user ID for the user accounts that should not be assigned as authors of the generated nodes.

Probably, you also need to write the equivalent of devel\_generate\_batch\_content(), which is the other function used to generate content, for your module.

Notice that the Devel generate module is used to generate content for developing/testing purposes. It should not be used to generate content for a production server/web site. That is the reason why there aren't too much options for the content to generate.
> 2 votes

# Answer
setting status to zero did disable DEVEL ... it removed it from display on the configuration page. However, it did not deactivate the Page Array display and the Internal Error 500 continues to appear on the configuration pages. Would you happen to know how to disable the actual Page Array display option? Expert Drupal Developers help me for that. If that does not solve problem, I imagine I will have to reload everything.
> 0 votes

---
Tags: debugging
---


# Question
Title: solr is running, but search isn't working: "The Solr server of Solr could not be reached."
I am using Search API Solr (Version: 7.x-1.14), and search was working fine but has stopped working. I now see "The Solr server of Solr could not be reached" at admin/config/search/search\_api. In the past, when I have gotten this message, it was because solr had stopped running. In this case, solr is running. I have confirmed this with the "bin/solr status" command.

My settings should all be fine, since they have not changed and were working fine before:

```
Solr Host: localhost
Solr port: 8983
Solr path: /solr/drupal

```

What could cause Drupal to now be unable to reach solr when no settings have changed and solr is running?

# Answer
I'm not sure what caused the problem in the first place, but it was ultimately resolved by running solr with a different user. In trying to address the original problem (whatever it was), I ran solr using the wrong user. Once I ran it with my designated "solr" user, Drupal could then reach solr.
> -1 votes

---
Tags: 7, search
---


# Question
Title: What operator is equivalent to "Is not greater than or equal to"?
I have a view showing a list of events. The events are sorted by a date field, which a user can use to input the event starting date/time. However, I want the events removed from the list once the current time is 1 hour past the start date/time of the event. When I add the event date to the view filters, I get the following operators.

However, none of these operators give me the desired result. What I really want is a "Is not greater than or equal to" operator. All of this said, is there a workaround that I could easily implement to get my desired result?

# Answer
You must use "Is less than" with an offset - just like the screenshot.
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to get a list of entity types the Drupal 9 way?
I need to get a list of all entity types.

EntityManager is deprecated. In Drupal 9 EntityTypeRepository should be used, though I don't see any reference to its being used.

How would I use this class in a non-static way to obtain a list of all entity types?

# Answer
As the EntityManager docs say:

> Deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. **Use \Drupal::entityTypeManager() instead in most cases**. If the needed method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the deprecated \Drupal\Core\Entity\EntityManager to find the correct interface **or service**.

```
$entity_type_manager = \Drupal::service('entity_type.manager');
$entity_definitions = $entity_type_manager->getDefinitions();
// Create a list of entity types.
$entity_types_list = [];
foreach($entity_definitions as $entity_name => $entity_definition) {
  $entity_types_list[$entity_name] = (string) $entity_definition->getLabel();
}

```
> 5 votes

---
Tags: entities, 9
---


# Question
Title: Editing order confirmation email in Drupal 7 Commerce
I am using Drupal 7 with Drupal Commerce (not Kickstart). I am having difficulties editing the order confirmation email. I am hoping to basically "duplicate" the Order review page from the Checkout process to be included in the email (order items, prices, total and billing info).

The module I installed is Commerce message and I just had no luck trying to edit the order confirmation email. I do have the Tokens module installed and enabled.

I tried to edit the email under Structure -\> Message Types, however, the replacement tokens available (for example: `[message:message-commerce-line-item]`), don't seem to output anything in the email. Actually, the token itself is included in the email, like so:

```
<p>[message:message-commerce-line-item]</p>

```

I have tried several other tokens with the same result. I tried to select Filtered HTML and Full HTML.

Reading through the Drupal Answers I also tried to use `!order-summary` token, which seems to work, however the email is "unstyled" and includes HTML tags, like so:

```
<tr class="odd views-row-first views-row-last">
  <td class="views-field views-field-line-item-title" >
     testing credit card payment
  </td>
  <td class="views-field views-field-commerce-unit-price price" >
     $0.25
  </td>
  <td class="views-field views-field-quantity" >
     1
  </td>
  <td class="views-field views-field-commerce-total views-align-right price" >
     $0.25
  </td>
</tr>

```

What puzzles me the most is seeing answers like this or this, stating that

> You want the Commerce Message module and it's dependencies. It includes customer emails with a full order details, including customer profiles and all the products purchased

Any ideas on the issue? I failed to find any Commerce message tutorial or the way tokens should be used with it in Drupal Commerce. I'd be happy to go through one if it exists, I would be willing to even write one for future users who might have the same problems once I figure this out.

Thanks

# Answer
I the end, I had to install the Mime Mail module. My site uses gmail for the site's email, so I had to use Mime Mail together with SMTP module.

The emails render html tags and tokens as needed.

For someone who might experience the similar issue, here is how I configured the Mime Mail witih SMTP:

In `admin/config/system/mailsystem` scroll down to the "New Class" fieldset. Create a new class using `MimeMailSystem` for `format()` and `SmtpMailSystem` for `mail()`. Use that newly created class for the "Site-wide default MailSystemInterface class.

I'm still not completely satisfied with this solution as I was hoping to make Commerce Message to work. If someone ever gets to respond to this I would be thankful for the answer.
> 1 votes

# Answer
I though I'd put this out there as what worked for me.

I've had a storefront running on Commerce 7.x-1.x for four years. The order confirmation emails have always been lame, but now with purchasing shifted to web, that lameness was becoming too obvious.

I didn't want to install Commerce Message (for whatever reason), so I started with and edited the standard order confirmation email rule at /admin/commerce/config/checkout/rules.

I added a blend of PHP evalution and replacement patterns from the table beneath the Message text area. Here is the result. I'll comment it a little (a lot).

```
blah blah blah greetings

Here is a listing of your order:
<?php // start of PHP code insert
    // get the order; it is an entity I think vs. an array (?)
    // that distinction is common throughout this code segment and I'm too php-ignorant to understand it yet
    $order_wrapper = entity_metadata_wrapper('commerce_order', $commerce_order);
    // get an array (?) of line items on the order
    $line_items =  $order_wrapper->commerce_line_items->value();
    //loop through each line item
    foreach($line_items as $line_item){
        // I want to know if it's 'product' type cuz I treat them differently than 'shipping'.
        // you might see code examples which have this as
        // $line_item->type->value(), but that just gave me errors.
        $line_item_type = $line_item->type;
        // again here an ...->amount->value() construction gave me errors
        $unit_price = $line_item->commerce_unit_price['und'][0]['amount'];
        // here also
        $line_item_total = $line_item->commerce_total['und'][0]['amount'];
        // if it's product ...
        if ($line_item_type == 'product') {
            // casting to (int) gets rid of .00 in quantity.
            // you can't do above if you've got fractional quantities anywhere
            $quantity = (int) $line_item->quantity;
            // get the product from the line item
            $product = commerce_product_load($line_item->commerce_product['und'][0]['product_id']);
            // print out qty and product name separated by a few spaces, "x" and tab
            echo $quantity . "  x\t" . $product->title . "\n";
            // on next line start with tab and spaces, then @, then formatted unit price then line total amount
            echo "\t   @  \$" . number_format($unit_price/100, 2) . " ea ...\t\$" . number_format($line_item_total/100, 2) . "\n";
        }
        // if it's not 'product' it's 'shipping' and it's always the last one.
        else {
            // print tab, then "Shipping:  ", then the chosen shipping option, then that unit cost
            echo ucwords($line_item_type) . ":  " . $line_item->data['shipping_service']['display_title'] . " ... \$" . number_format($unit_price/100, 2) . "\n";
        }
    } // end foreach loop
?> // end of PHP code insert

Total incl. tax:  [commerce-order:commerce_order_total] // tax is not available as a distinct element as far as I could tell
Payment:  [commerce-order:payment-method-display-title] // this one is not very descriptive in practice

Your comments:  [commerce-order:field_order_comments]

Shipping address (if applicable):
[commerce-order:commerce_customer_shipping] // this one thankfully spits out all 4-6 lines

blah blah blah nice signoff

```

The end result is an email like so:

```
blah blah blah greeting

Here is a listing of your order:
1  x    Vivamus at laoreet orci
           @  $25.00 ea ... $25.00
2  x    Donec eleifend rutrum consequat
           @  $25.00 ea ... $50.00
2  x    Felis commodo tristique efficitur
           @  $25.00 ea ... $50.00
Shipping:  Fedex/UPS/Whatever ... $1.23

Total incl. tax:  $132.50
Payment:  Credit card

Your comments:

Shipping address (if applicable):
Alfred E Neuman
123 Elm St
Anytown, KS  12345
987-654-3210

blah blah blah nice signoff

```
> 1 votes

---
Tags: commerce
---


# Question
Title: Views insert current page node id to image link url
I want to create a block view of some content's image field. I am trying to insert current page node id to paths of image links. Because linked page is a entity form and I try to prepopulate node id in one of the field of the entity form.

How can write to current node id to URL with views rewrite results? URL pattern like that. example.com/form?edit\[field\_whatisrefferaelid\]\[und\]\[0\]\[value\]=\[currentpagenodeid\] Actually I am seraching for current node id token avaible in views block.

# Answer
> 0 votes
If you have a **Contextual Filter** in place for **Content: Nid** that is pulling in the nid from the currently viewed page, can

* Add a field for your image
* Choose **Image** for the formatter. Configure the image style that you want.
* Link image to **Nothing**
* In **Rewrite Results**, check **Output this field as a link**
* In the link path, use `form?edit[field_whatisrefferaelid][und][0][value]=!1`
* Check **Use absolute path**

The `!1` is the replacement pattern for the first contextual filter. It should be listed in the list of replacement patterns in the popup you do the configuration from.

That shuld

# Answer
> 0 votes
You can simply follow below steps:

1. Add `ID` field in your view, hide the display of it and drag it above the image field .
2. In you image field, link the image to nothing and rewrite the result as below using the `{{ nid }}` as replacement pattern:

```
<a href='/form?edit[field_whatisrefferaelid][und][0][value]='{{ nid }}>{{ your image }}</a>

```

**If the image is not part of current node**, you can simply use `{{ url('<current>')| split('/') | last }}` in you view rewrite result as:

```
<a href='/form?edit[field_whatisrefferaelid][und][0][value]='{{ url('<current>')| split('/') | last }}>{{ your image }}</a>

```

---
Tags: views, uri
---


# Question
Title: How to prevent closing ctools modal window with ESC?
I am using ctools modal window to edit some records with Form API.
How can I prevent closing window with ESC key and the default close button?

# Answer
> 0 votes
I had similar kind of a problem. I had to disable closing modal popup by pressing ESC. In my case solution was adding unbind for modalEventEscapeCloseHandler for page where I was going to get modal popup:

```
<?php
      drupal_add_js('
      jQuery(document).ready(function(){
        jQuery(document).unbind("keydown", modalEventEscapeCloseHandler);
      });
      ', 'inline');
?>

```

# Answer
> 0 votes
I tried like this and it works for me

```
$(function () {
    $('.modal').modal({
        show: true,
        keyboard: false,
        backdrop: 'static'
    });
});

```

If this won't work for you then try adding

```
data-keyboard="false"

```

Something like this:

```
<div class="modal hide fade" data-keyboard="false"
role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">

```

# Answer
> 0 votes
Dialog/Modal box can be disabled from closing as below:

**From escape key**:

```
$( ".selector" ).dialog({
  closeOnEscape: false
});

```

Reference: https://api.jqueryui.com/dialog/#option-closeOnEscape

**From close button**:

```
$( ".selector" ).dialog({
  beforeClose: function (event, ui) {
    return false;
  }
});

```

---
Tags: chaos-tool-suite
---


title: Get enabled content types machine name

text:
# Question
Title: Get enabled content types machine name
I'm trying to get the enabled content type machine names for a given group.

I wrote the following code, but to get the machine name I should cut the strings to *group\_node:*.

```
    /** @var \Drupal\group\Entity\GroupType $group */
    $group = GroupType::load($groupKey);
    $plugins = $group->getInstalledContentPlugins();
    foreach ($plugins->getConfiguration() as $key => $plugin) {
      // Cut key here.
    }

```

# Answer
> 0 votes
Okay, I don't know how I missed this.

```
/** @var \Drupal\group\Entity\GroupType $group */
$group = GroupType::load($groupKey);
$plugins = $group->getInstalledContentPlugins();
foreach ($plugins as $key => $plugin) {
  $bundle = $plugin->getEntityBundle();
}

```

---
Tags: 8, group
---


title: How to save configs in BrowserTestBase?

text:
# Question
Title: How to save configs in BrowserTestBase?
In a functional test I try to test a functionality after changing the module configuration:

```
public function setUp() {
  parent::setUp();
  ...
  $config = \Drupal::configFactory()->getEditable('move_file.settings');
  $config->set('vocabulary', 'tags');
  $config->save();
  ...
}

```

The tested functionality is located primarily in MoveFileService.php. But the service does not see the configs. When I debug the configs directly in the service, then I get:

```
public function __construct(ConfigFactory $config_factory, LoggerChannelFactoryInterface $logger_factory) {
    $this->config = $config_factory->get('move_file.settings');
    $this->logger = $logger_factory->get('move_file');
}

public static function create(ContainerInterface $container) {
    return new static(
    $container->get('config.factory'),
    $container->get('logger.factory')
    );
}

public function configsAreSet() {
    ...
    fwrite(STDOUT, "Settings: {$this->config->get('vocabulary')}\n");
    // Returns: Settings:
    // The configuration is null.

    $config = \Drupal::service('config.factory')->getEditable('move_file.settings');
    fwrite(STDOUT, "Settings: {$config->get('vocabulary')}\n");
    // Returns: Settings: tags
    // This returns the expected value. But the good practice is to use the dependency injection.
    ...
}

```

How can I save the config in the setUp() method of the functional test, so that the service can get the saved configuration, when the test is running?

# Answer
I have found, that the problem was caused, that in the setUp() method of the test class, was at first used the $this-\>drupalCreateNode(\[...\]) method and then were created the settings. **After moving the $config-\>set(...) method at the beginning of the setUp() method, works everything perfect.**

See:
> 0 votes

---
Tags: 8, configuration, testing
---


title: How to alter page content?

text:
# Question
Title: How to alter page content?
Simple thing. I have some page (node). At end it produces some content, i.e.

```
<h1>This is original content</h1>

```

I want to alter it with different content, i.e.

```
<h1>This is changed content</h1>

```

So I need a way to collect original content, parse it, replace some part of it and put it back.

`hook_ENTITY_TYPE_view()` should be the way to do that:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_ENTITY\_TYPE\_view/8.2.x

And I tried example from that page (by Devendra Mishra) and it works, but it's adding additional content. I need a way to access original content and change it, not to just add new one.

To be clear, I don't want to change content on field level, but want to change final content, with all fields combined, ready to be rendered.

# Answer
If you don't want to change the variables on field level you can parse the content in a #post\_render callback after it is rendered:

```
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $build['#post_render'][] = function ($html, array $elements) {
    return str_replace('original', 'changed', $html);
  };
}

```
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Replace \Drupal::service with Dependency injection in FieldWidget class
I have created an ajax callback inside a custom Field Widget plugin. In the Ajax callback I have called a custom service using

```
$service = \Drupal::service('service.name')

```

I am using phpmd to clean up the code and it suggested that the service should be called using dependency injection.

This means I should create a constructor for the Fieldwidget class and then get it as argument. I am not sure how to pass the argument when the Field widget is called. Not even sure what interface should be set for the Drupal service caller.

Any ideas on how to do that.

# Answer
This requires three steps:

1. Declare a property to hold the service.
2. Implement a \__construct() method to populate the property from step 1.
3. Implement a create() method, to generate the service that is passed to \__construct().

**1) Declare a property to hold the service**

In your class, declare the property that will hold the service.

```
/**
 * The example service.
 *
 * @var \Drupal\example\Service\ExampleService
 */
protected $exampleService;

```

With this, you can now refer to `$this->exampleService` within your class. However, at this point it is still `NULL`, so it needs to be populated.

**2) Implement a \__construct() method to populate the property from step 1**

This is done by overriding WidgetBase::\__construct(), and adding the service to it.

```
public function __construct(
  $plugin_id,
  $plugin_definition,
  FieldDefinitionInterface $field_definition,
  array $settings,
  array $third_party_settings,
  ExampleServiceInterface $exampleService
) {
  // Initialize the parent class:
  parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);

  $this->exampleService = $exampleService;
}

```

Now the property from step one can be populated when the class instantiated. However, the service itself needs to be generated, and passed to the `__construct()` method.

**3) Implement a create() method, to generate the service that is passed to \__construct().**

The service is generated in the `create()` method. This is done by copying the code from WidgetBase::create(), and adding the service to it. WidgetBase::create() looks like this:

```
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $plugin_id,
    $plugin_definition,
    $configuration['field_definition'],
    $configuration['settings'],
    $configuration['third_party_settings']
  );
}

```

Notice that the values returned are the same values passed to the `__construct()` method, but without the `example.service` service. The example service needs to be retrieved from `$container` and added to the above, by implemented `create()` in your class as follows:

```
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $plugin_id,
    $plugin_definition,
    $configuration['field_definition'],
    $configuration['settings'],
    $configuration['third_party_settings'],
    $container->get('example.service')
  );
}

```

This function call generates the example service, which passes it to `__construct()`, which in turn populates $this-\>exampleService, so it can be used in your class in place of `\Drupal::service('example.service')`.
> 3 votes

---
Tags: 8, dependency-injection, symfony-services
---


# Question
Title: How to apply image style in a views-view-fields--[view]--[machine-name].html.twig
In a views-view-fields--\[view\]--\[machine-name\].html.twig, I have

```
{% set images = row._entity.field_image %}

{% for image  in images %}
  <div>
   <div class="img">
     <img class="img-responsive" src="{{ file_url(image.entity.fileuri) }}" alt="">
   </div>
  </div>
{% endfor %}

```

I have tried with "|image\_style('style')" like so

src="{{ file\_url(image.entity.fileuri)|image\_style('style') }}

This doesn't work, so what am I doing wrong?

# Answer
Welcome to Drupal Answers!

You can try something like below in your for loop:

```
{% set image = {
    '#theme':      'image_style',
    '#style_name': 'your_image_style_name',
    '#uri':        image.entity.uri,
    '#alt':        image.alt
   }
%}

```

then render the image as `{{ image }}` **without** `img` tag as it is rendered along with `img` tag.
> 0 votes

# Answer
In your view, specify the Image Style that you want to use for the image field, then use the `|render` Twig filter on the field.

**Configure your Views field**

Add Style Settings if you want to inject a class, like `img-responsive`.

**Render the fields in Twig**

```
{% set images = row._entity.field_image %}

{% for image in images %}
  <div>
   <div class="img">
     {{ image|render }}
   </div>
  </div>
{% endfor %}

```
> 0 votes

---
Tags: views
---


title: ckeditor don't preview picture tag

text:
# Question
Title: ckeditor don't preview picture tag
i'm working on drupal 8 and i'm using picture instead of imag tags. To take the benefit of the responsivness feature. I'm just facing and issue that CKeditor can't preview the pisture tag. Any idea how to fix it ?

# Answer
In order to achieve this you would have to enable support of `<picture>` in your text format. You can do it as below:

1. Goto `/admin/config/content/formats` path and configure the text format you are using in your field.
2. Find the checkbox option `Limit allowed HTML tags and correct faulty HTML` and check it.
3. Scroll down and find the text area where **allowed html tags** are listed.
4. Add your tag `<picture>` here along with additional attribute. For example, if you want to add class attribute to your picture tag just add `<picture class>` in allowed html tags
> 1 votes

---
Tags: 8
---


# Question
Title: How to automatically install an image in taxonomy term field every time I install the module
I have a module with a custom taxonomy term called colors. The Colors taxonomy has 1 image field where I can upload a file based on the color names. I wanted the images to be automatically installed every time my module got installed. I think that I need to add a piece of code to my module.install file under hook\_install(). How do I achieve this?

# Answer
> 1 votes
There are a couple of steps to doing this. For our demonstration, let's make a few assumptions:

* The module is called **image\_taxonomy**.
* We have only one taxonomy term and one file to worry about.
* The image file is called **color.jpg**.
* The taxonomy term is called **color\_red**.
* The image field is called **field\_color\_image**.
* The image is stored in your module's folder under **/images**.

**Step 1. Make the file publicly available**

The first challenge is to get your module-bound asset (the color.jpg file) into your site's public files as a managed file. An abbreviated version of how to do this is:

```
// $absolute_path_to_file is the absolute server path to /image_taxonomy/images/color.jpg
$contents = file_get_contents($absolute_path_to_file);
$file = file_save_data($contents, "public://color.jpg", FILE_EXISTS_REPLACE);
$file->setPermananet();
\Drupal::service('file.usage')->add($file, 'image_taxonomy', 'image', $file->id());

```

Now you should have a copy of your **color.jpg** file in your site's `/files` folder.

**Step 2. Assign the file to the term.**

```
// $term is a reference to the color_red taxonomy term.
$term->get('field_color_image')->setValue([
  'value' => $file->id();
]);
$term->save();

```

**Last note**

I would run this code from hook\_modules\_installed(), just to make sure that all entities and fields have been installed before attempting to assign your image file. This is highly abbreviated code, so be sure to use proper dependency injection and other best practices in your module.

**References**

---
Tags: 8, hooks
---


# Question
Title: How can I make a multi-column content section with Paragraphs and Bootstrap?
How to adapt this code in php for Drupal 7?

https://jimbir.ch/blog/making-multi-column-content-section-drupal-paragraphs-bootstrap

```
drupal-paragraph-multi-column-field.html.twig
{% for item in items %}
<div class="col-sm-{{ 12 // loop.length }}">{{ item.content }}</div>
{% endfor %}

```

# Answer
I placed this code in field--\[field name\].tpl.php

```
    <?php foreach ($items as $delta => $item) : ?>
       <div class="col-sm-<?php print round(12/count($items)); ?>">
        <?php print render($item); ?>
         </div>
<?php endforeach; ?>

```

It seems to work !
> 0 votes

---
Tags: 7, theming, paragraphs, bootstrap-theme
---


# Question
Title: "Route "ctf.content" does not exist" when installing custom module
I tried writing my own copy of the skeleton module from https://github.com/sidharrell/D8HWexample.git modules/custom/hello\_world, but I thought I'd start by changing the module name and using "ctf" instead of "hello" in the routes. I tried to install the module but I got an exception.

> Route "ctf.content" does not exist

I deleted my module folder from beneath the custom folder and reloaded the page, but I still get this error. The site is now unusable.

Do I need to reinstall or is there an easy way to flush the cache or uninstall the module? I don't have drush installed (yet).

# Answer
> 0 votes
You do need to clear the caches any time you edit routes. The simplest way is from the performance settings page: `/admin/config/development/performance`.

To change the module's name you'll need to replace every instance of the original name throughout every file in the module.

---
Tags: routes
---


title: basic xml source migration problem

text:
# Question
Title: basic xml source migration problem
I am attempting to figure out how to write a simple migration from an XML source that is located on a separate URL.

I have tried a number of different configurations for the selector and so far nothing has worked. The migration and source example are below.

migration:

```
id: xml_test
label: xml test importer
migration_group: p_migrate
dependencies:
  enforced:
    # List here the name of the module that provided this migration if you want
    # this config to be removed when that module is uninstalled.
    module:
      - p_migrate
source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: simple_xml
  urls:
    - 'http://localhost:8888/test/source.xml'
  item_selector: /root/row
  fields:
    -
      name: title
      label: title
      selector: root/row/title
process:
  #  nid and vid commented out will allow them to autoincrement. Safe as long
  #    as nothing else is referencing them.
  #  nid: nid
  #  vid: vid
  #  type: type
  title: title

destination:
  plugin: 'entity:node'
  default_bundle: article

```

Source:

```
<?xml version="1.0" encoding="UTF-8" ?>
<root>
  <row>
    <title>Lorem ipsum</title>
  </row>
  <row>
    <title>Feeds Migrate is awesome!</title>
  </row>
</root>

```

This is the error I am currently getting: Invalid argument supplied for foreach() SimpleXml.php:79 Invalid argument supplied for foreach() SimpleXml.php:79

# Answer
I found the problem. I needed to add the id configuration to the source:

```
ids:
    title:
      type: string

```

I also changed the selector back to: title
> 0 votes

---
Tags: migrations
---


# Question
Title: Routing path with Entity Reference field
I'm working on a custom module (*my\_module*) which provides some functionality to a specific paragraph type (*my\_paragraph*) created from the user interface. In my routing file, I have the following route definition.

```
my_module_controller_action:
  path: '/node/{node}/my_paragraph/{paragraph}'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::action'
    _title: 'page title'
  requirements:
    _permission: 'access content'

```

Now I add a new entity reference field (*field\_paragraph*) to the *Basic page* content type. Using this field I can add *my\_paragraph* along with other paragraph types.

With this set up, I create a basic page, add a piece of *my\_paragraph*, and saved it (/node/123). I can see my custom controller is **not** called (because now the path is /node/123), but if I go to /node/123/my\_paragraph/1, my custom controller is getting called there and I get the output I want.

1. What should I do so that my custom controller can be used on /node/123 page?
2. If I add /about as path alias of /node/123, how do I achieve the same outcome?

I'm actually refactoring an old custom module I wrote and trying to move away from the hooks approach if possible. One of the main motivations for me by refactoring is I can use one or more services (together with dependency injections) to separate all the possible logics here.

# Answer
> 2 votes
The problem here is that controllers are specifically intended to return a result based on a given path. The result you want isn't dependent on a path, but rather on an operation performed on an entity.

What you'll want to use instead is one of the entity API hooks, found here: Entity CRUD, editing and view hooks

To respond to your entity being created, I recommend using: hook\_ENTITY\_TYPE\_insert()

```
function my_module_node_insert($node) {
  // Get ids for all Paragraph references stored in your field.
  $paragraph_ids = $node->get('field_paragraph')->getValue();
  // Get Paragraph storage handler.
  $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
  // Load Paragraphs from their IDs.
  $paragraphs = $paragraph_storage->loadMultiple( array_column($paragraph_ids, 'target_id') );

  // Iterate through your loaded Paragraph instances...
  foreach($paragraphs as $paragraph) {
    // Do your stuff to the paragraph.
  }
}

```

Similarly, if you need to update `field_paragraph` when you update your node, implement hook\_ENTITY\_TYPE\_update().

# Answer
> 2 votes
In Drupal 8, routes and hooks have different purposes. Routes are for rendering a page containing information, while hooks are used to react to an event or to alter the information returned from other modules.

I assume you need to show information, and a controller is really what you need. (The rest of the answer will consider the case you really need a hook.)

The first point to keep in mind is that each path can only have a single controller. When Drupal is showing the page at /node/123, for example, only the controller that renders the node view is called. No other controllers will be used.
That doesn't mean the node can just be viewed and not, for example, edited, deleted, or translated. Drupal shows tabs that allow to take different actions on that node, or to show information that is related to that node.

(The screenshot is taken from the Drupal Umami Demo.)

Defining a tab controller it's done in two steps. (I will show what Drupal core does for /node/{node}/revisions.)

* The route is defined in the .routing.yml file

```
entity.node.version_history:
  path: '/node/{node}/revisions'
  defaults:
    _title: 'Revisions'
    _controller: '\Drupal\node\Controller\NodeController::revisionOverview'
  requirements:
    _access_node_revision: 'view'
    node: \d+
  options:
     _node_operation_route: TRUE

```

(Some of the values are very specific for that route.)
* The .links.task.yml file define the route as tab link and where it should be shown (the *base\_route* property)

```
entity.node.version_history:
  route_name: entity.node.version_history
  base_route: entity.node.canonical
  title: 'Revisions'
  weight: 20

```

If instead what you need is really a hook, then you just need to implement it. As for using a more OOP approach, the *Content Moderation* module shows how to achieve that, for example, in its `content_moderation_entity_insert()`.

```
function content_moderation_entity_insert(EntityInterface $entity) {
  return \Drupal::service('class_resolver')
    ->getInstanceFromDefinition(EntityOperations::class)
    ->entityInsert($entity);
}

```

The `EntityOperations` class is merely a class implementing `ContainerInjectionInterface` and it can therefore use Dependency Injection.

---
Tags: routes, paragraphs
---


# Question
Title: Semver, core_version_requirement and update hooks
I have read a little bit about using semver for contrib modules in the updated documentation Transitioning from 8.x-\* to semantic versioning and Drupal.org release version numbers allow semantic versioning. While I do understand that we need to tag these branches & releases incrementally based on your current `8.x` version, how is this taken into practise?

My module for example is considered compatible for both Drupal 8 and 9, tagged with a release `8.x-2.1` on branch `8.x-2.x`. So would I switch to a new branch `3.x` and tag `3.0.0`, or can this tag be on the same `8.x-2.x` branch as they are essentially running the same codebase? Otherwise I have to apply all bug fixes and changes onto 2 branches.

How would this work in conjunction with the `core_version_requirement` key, as I believe semver is only supported starting from Drupal `8.7.7` core version?

And finally if I am able to use the same codebase for either semver or without, how would this work with update hooks or are they maintaining the same format?

# Answer
> 1 votes
I wouldn't use semantic versioning just for the sake of using it, especially since using it on drupal.org forces you to increase the major version number. Changing major version number means the new version is not compatible with the previous one, which also means the code base diverges significantly (or it will diverge significantly).

If the module uses semantic versioning, it should require Drupal 8.8.3 or any later version, since previous versions don't handle correctly semantic versioning.
For a module that is also compatible with Drupal 9, I would use `core_version_requirement: ^8.9 || ^9`.

As a side note, `core_version_requirement` is handled starting from Drupal 8.7.7. For those versions, using `core` isn't anymore necessary. It is also completely ignored in Drupal 10.x, as described in The 'core' key is completely ignored in .info.yml files.

---
Tags: 8
---


# Question
Title: Can't get drush to work after moving to Acquia Dev Desktop
I installed Acquia Dev Desktop. Most things work but drush does not. I get an error: Drush was not able to start (bootstrap) the Drupal database.

Because I had previously installed php and mysql on my local, I removed those old versions and adjusted my ~/.bash\_profile to ensure I was loading the Acquia Dev Desktop version of php, mysql, and drush. To test, I run "which php", "which mysql", and "which drush" all of which returned the Acquia Dev Desktop version.

To test mysql, from my drupal site directory I entered the mysql cli with "mysql". I ran "show databases" and confirmed the Acquia Dev Desktop Database is in this Mysql server.

To test the php, from my drupal site directory I ran "php -r 'phpinfo();'". I confirmed the PHP version/config loaded is the Acquia Dev Desktop version.

I see in drush looks for aliases in ~/.acquia/DevDesktop/Drush/Aliases/aliases.drushrc.php I inspected that file and see the alias configured as loc.mysite.dev. I tried my drush commands using that alias. "drush @loc.mysite.dev status". This made no difference.

My drupal install is setup like a multisite. Maybe that is an issue though I always use multisite and have no issue with this same site and drush in a vagrant box (not using Acquia Dev Desktop). I am running my drush commands from my site directory (sites/mysite.org) which is where my settings file is (sites/mysite.org/settings.php).

Here are some drush debug outputs This is the issue after installing Acquia Dev Desktop https://gist.github.com/maestrojed/78ff27cfae1f65821ce8 This is the issue after installing Acquia Dev Desktop AND my attempts to get drush to use the correct Acquia Dev Desktop versions of Drush and PHP. https://gist.github.com/maestrojed/45c1635f5d1d88d4bd9e

I have to use Acquia Dev Desktop and I don't think I can live without drush. I am happy to provide any other info to help debug. Any tips are greatly appreciated! Thanks. \- See more at: https://forums.acquia.com/acquia-products-and-services/dev-desktop/cant-get-drush-work#sthash.bZJBgcc0.dpuf

# Answer
When using Acquia and Acquia Dev Desktop the settings.php is autogenerated by Acquia. If you review that settings.php file you will noticed there are no databases credentials but instead an Acquia config file is included within a conidtional. That conditional and file are:

```
// <DDSETTINGS>
// Please don't edit anything between <DDSETTINGS> tags.
// This section is autogenerated by Acquia Dev Desktop.
if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) && file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/cld_devcloud_mysite_dev_mysite_org.inc')) {
  require $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/cld_devcloud_mysite_dev_mysite_org.inc';
}
// </DDSETTINGS>

```

This included file contains the database connection info. It seems that Drush doesn't include this file. I assume because when run by drush the conditional is not satisfied.

I added my own additional include to the bottom of settings.php to include a local file if it exists.

```
/**
 * Include a local settings file if it exists.
 */
$local_settings = dirname(__FILE__) . '/local.settings.php';
if (file_exists($local_settings)) {
  include $local_settings;
}

```

I added the exact same content from the cld\_devcloud\_mysite\_dev\_mysite\_org.inc file into this local.settings.php file.

Now drush works. My conditional is satisfied. Site continues to run fine locally in Acquia Dev Desktop.

Seems drush should load those Acquia includes and it must for most people as I didn't find many others with this issue. Not sure why my setup acted differently.

maestrojed
> 2 votes

# Answer
Use the console coming with ADD - launch the console from the ADD client. Using that console everything is correct setup. You might of course get everything to work inside your "Bash" (which it think you are using since you talk about the "which" command), but it kind of removes the whole point of using ADD - that everything is working out the box.

PS! I use Git Bash for my Git work and the ADD (cmd) console for Drush work. Then I don't have to think ;-)
> 2 votes

# Answer
Maestrojed's own answer identifies the settings file, and hansfn has already pointed out you may need to launch the terminal session via DevDesktop itself.

Other things you can do:

* First, check `drush status` (which'll show if it has the correct db name)
* Run drush commands with the `--verbose` switch, which'll show bootstrap status (but beware the bootstrap debug messages can be misleading)
* Try using Drush to launch a MySQL console – `drush sqlc`
* if you're using a Drupal 8 composer setup (recommended), install the latest version of Drush with composer, rather than relying on the version that comes with DevDesktop (run `composer require drush/drush`). One odd situation I had was the `drush updb` command connecting to a different database to everything else (I found this out by adding the `--verbose` option), and upgrading fixed that.
* beware of a ~/.my.cnf file forcing the wrong username
> 1 votes

# Answer
Drush is not picking up the acquia site settings.
Add the acquia settings to your .bash\_profile or path so drush can access them.

```
export DEVDESKTOP_DRUPAL_SETTINGS_DIR="$HOME/.acquia/DevDesktop/DrupalSettings"

```
> 0 votes

---
Tags: drush, acquia-dev-desktop
---


title: Not able to execute Drush commands

text:
# Question
Title: Not able to execute Drush commands
I am trying to setup a Drupal 8 Environment on Virtual Machine (Ubuntu) and when I am trying to clear cache, I've got the error:

```
drupal8@drupal8-VirtualBox:/var/www/drupal-8.0-alpha5$ drush cc all
Command cache-clear needs a higher bootstrap level to run - you will [error]
need invoke drush from a more functional Drupal environment to run
this command.
The drush command 'cc all' could not be executed.                    [error]
A Drupal installation directory could not be found                   [error]
drupal8@drupal8-VirtualBox

```

I have installed Drush, but getting this error. Can anybody help me with this?

# Answer
> 4 votes
There are a few possible reasons for the issue you're facing, as further detailed below ...

# Drush commands need to be issued from within the correct subfolder

A "possible" reason might be because Drush commands must be issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

So try navigating to the sites/default folder (assuming this is NOT a multi-site), and then retry your Drush comand.

# Use the Drush version that supports your Drupal version

It could well be an issue with the version of Drush that you are using. Check if it is an option to downgrade to a lower version of Drush? FYI: Drush 7.x does support D8 also ...

**Note**: in one of the comments in the question, the OPer wrote "***Drush version is 4.5***". Haven't double checked it yet, but that appears to be an extremely old version of Drush. I wouldn't be surprised if that version doesn't support D8 "yet". And since the D8 folder structure changed quite a bit, that would also explain the error like "A Drupal installation directory could not be found" ... More research (and clarifications from OPer) are seems appropriate here ... (I might update my answer here later on with some relevant pointers about "which version of Drush supports which version of Drupal".

# Answer
> 1 votes
drush is not recognizing your site settings.
Run `drush -d` to see where is it failing.
For anyone having this problem using acquia dev desktop, see this answer.

# Answer
> 0 votes
The issue may be that you are using an old version of Drupal 8 (alpha-5). At this time Drupal 8 is at Beta 12. Upgrading may solve this issue but keep in mind there were major changes happening during development so upgrading won't be that simple. If you don't have a lot of nodes it might be easier just to start fresh.

# Answer
> 0 votes
drush command for Drupal 8 is 'drush cr' or 'drush cache-rebuild'. Cache is no longer only being cleared, as in the cache tables truncated in the databases, but the site was being rebuilt as well.

---
Tags: 8, drush
---


# Question
Title: How to preload a css/js library programmatically after module installation? is there api for changing *.library.yml file?
i would like to develop a module where i cached internally html,css,js statically for pages. 1) in a admin setting page i can add a bundle with 1 html page + css/js files. 2) for each bundle i have different path 3) Normally in drupal8 i can define a file \*.library.yml where i can set css/js but in this case is not defined statically when i install the module, but is changed every time in admin section i add a bundle.

Is there drupal API for loading programmatically the register where there are saved libraries and where i can change and save again the configuration? it is not possible do you have other suggestions?

# Answer
> 1 votes
Drupal allows modules to add dynamic library definitions by implementing `hook_library_info_build()`. Drupal core doesn't implement this hook, except in a test module.

```
function common_test_library_info_build() {
  $libraries = [];
  if (\Drupal::state()->get('common_test.library_info_build_test')) {
    $libraries['dynamic_library'] = [
      'version' => '1.0',
      'css' => [
        'base' => [
          'common_test.css' => [],
        ],
      ],
    ];
  }
  return $libraries;
}

```

If you instead need to alter the library definitions given from another module, `hook_library_info_alter()` is the correct hook to use.

```
function locale_library_info_alter(array &$libraries, $module) {
  if ($module === 'core' && isset($libraries['jquery.ui.datepicker'])) {
    $libraries['jquery.ui.datepicker']['dependencies'][] = 'locale/drupal.locale.datepicker';
    $libraries['jquery.ui.datepicker']['drupalSettings']['jquery']['ui']['datepicker'] = [
      'isRTL' => NULL,
      'firstDay' => NULL,
    ];
  }

  // When the locale module is enabled, we update the core/drupal library to
  // have a dependency on the locale/translations library, which provides
  // window.drupalTranslations, containing the translations for all strings in
  // JavaScript assets in the current language.
  // @see locale_js_alter()
  if ($module === 'core' && isset($libraries['drupal'])) {
    $libraries['drupal']['dependencies'][] = 'locale/translations';
  }
}

```

---
Tags: theming, javascript
---


# Question
Title: How to force a running migration to stop
I created a migration with a query that seems to have broken my migration. I added two groupBy on a query, instead of two orderBys. As a result, running drush mi MyMigration got stuck in what appeared to be an endless loop.

I CTRL-C'd the process and then ran a drush mst --all, but now the status is reporting as "Stopping" in the UI, and the drush ms command does not return.

I tried stoping and restarting MAMP, but to no effect.

Is there someway to force my migration to get unstuck?

# Answer
Did you try `migrate-reset-status`, and possibly with `--force`: https://www.drupal.org/node/1561820

Otherwise I typically restart PHP manually once (restart your webserver) and then use Drush to `rollback` all the migrations to try again fresh.

**EDIT**

I rarely use the UI as everything is usable and scriptable via `drush` when using Migrate. And trying to use a webserver to check the status of long-running tasks can be error-prone.
> 11 votes

# Answer
This worked for me:

```
drush php-eval "var_dump(Drupal::keyValue('migrate_status')->set('migration_id', 0));"

```
> 4 votes

---
Tags: drush, migrations
---


# Question
Title: Twig escapes tags when using raw value in template
I am printing fields in a node template, but Twig is escaping my tags and ruining my day.

My `.tpl` looks like this:

```
  <blockquote>
    <p class="title">{{ content.field_myfield.0 }}</p>
  </blockquote>

```

I want to strip all tags from the original field and then "wrap" the field in a paragraph tag with the `title` class. I found out how to get the raw value without tags based on this question.

However, this is the HTML that is actually output:

```
<blockquote>
  <p class="title"></p><p>When you wish upon a star</p><p></p>
</blockquote>

```

What am I doing wrong?

# Answer
You can use the following code below:

```
{{content.field_myfield.0|render|striptags|trim}}

```

> render: The striptags filter strips SGML/XML tags and replaces adjacent whitespace by one space. You can also provide tags which should not be stripped:

```
{{ content.field_myfield.0|striptags('<br><p>')}}

```

trim: The trim filter strips whitespace (or other characters) from the beginning and end of a string:

```
{{ '  I like Twig.  '|trim }}

{# outputs 'I like Twig.' #}

{{ '  I like Twig.'|trim('.') }}

{# outputs '  I like Twig' #}

{{ '  I like Twig.  '|trim(side='left') }}

{# outputs 'I like Twig.  ' #}

{{ '  I like Twig.  '|trim(' ', 'right') }}

{# outputs '  I like Twig.' #}

```

The example above used from the twig website.
> 2 votes

---
Tags: theming
---


title: How to access twig object values?

text:
# Question
Title: How to access twig object values?
I have an object called 'attributes' available to me in a twig template. Given that the following:

```
{{ dump(attributes) }}
{{ dump(attributes.storage) }}
{{ dump(attributes.storage['data-quickedit-field-id']) }}

```

dumps this:

how do I access the value property:?

```
'paragraph/3/field_section_title/en/default'

```

I've tried the obvious:

```
{{ dump(attributes.storage['data-quickedit-field-id'].value) }}

```

The following methods are available to me:

# Answer
You can pipe it to `render`:

```
{{ attributes.storage['data-quickedit-field-id']|render }}

```
> 3 votes

# Answer
You can use `offsetGet` and `render` :

```
{{ attributes.offsetGet('data-quickedit-field-id')|render  }}

```

Source : https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Template%21Attribute.php/function/Attribute%3A%3AoffsetGet/8.2.x
> 0 votes

---
Tags: theming, 8
---


title: Major module update with Composer

text:
# Question
Title: Major module update with Composer
I have some modules in 8.8.5 that need an **major update**. What is the **best practice without loosing data or settings?**

**For example:** drupal/admin\_toolbar 1.27.0 2.2.0

* Do I need to uninstall the module in de admin backoffice Drupal?
* If so, I first need to uninstall both modules: Required by: admin\_toolbar\_tools, adminimal\_admin\_toolbar
* Finally uninstall admin\_toolbar
* Composer **remove** drupal/admin\_toolbar
* Composer **require** drupal/admin\_toobar
* Drush updatedb
* Drush cr

Is that the correct way? Or can I simply remove the old version with composer and require the new one?

# Answer
> 3 votes
No you don't uninstall the module first. You want to have the module enabled when updating to let possible database updates kick in. Which may be performed to update existing data/entities. If you already have the latest 1.x version installed you could simply do

1. `$ composer require drupal/admin_toolbar` to upgrade the module.
2. `$ drush cr && drush -y updb` to perform database updates.
3. And finally `$ drush -y cex` to export any eventually updated config.

If you don't have the latest 1.x version installed yet, it's better to upgrade incrementally. And to play really safe to also do two consecutive releases for that.

1. `$ composer update drupal/admin_toolbar --with-dependencies && drush cr && drush -y updb && drush -y cex` to first update to the latest 1.x version, followed by a release.
2. And then `$ composer require drupal/admin_toolbar && drush cr && drush -y updb && drush -y cex` to get the latest major upgrade, followed by another release.

---
Tags: 8, updating
---


# Question
Title: How do I hide a view's field based on role?
In /admin/people, I want to hide the display name (i.e. the *Display name* must not appear in the user list), but only for a specific role.

In my .module file, I have tried following hooks:

```
function hook_views_data_alter(array &$data) {
  kint($data['users']);die;
}

function hook_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view->id() == 'myview'){
    print_r($view->result);die;
      // kint($value->_entity->get('title')->value);
  }
}

function hook_views_post_render(\Drupal\views\ViewExecutable $view) {
   if ($view->id() == 'viewid') {
    // Set the view title.
    $field_name = $view->getFields();
  }
}

function hook_field_views_data_views_data_alter(array &$data, \Drupal\field\FieldStorageConfigInterface $field) {
  $field_name = $field->getName();
  echo 'hjsjhwd';
  print_r($field_name);die;
  }

```

None of them helped me. I thought of getting fields of the view "user" and after that I will unset it for particular role. But in views listing, Name field is still appearing. How can I hide it for a particular role?

Is there any way to achieve this?

# Answer
> 19 votes
The most efficient way would be using hook\_views\_pre\_view(), which allows you to alter a View at the very beginning of the process i.e. before any query is built/run and before any rendering takes place. You can remove the 'name' field handler from the View based on the desired logic.

```
/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view($view, $display_id, array &$args) {
  if ($view->id() !== 'user_admin_people') {
    return;
  }

  $user_roles = \Drupal::currentUser()->getRoles();
  if (!in_array('my-special-role', $user_roles)) {
    $view->removeHandler($display_id, 'field', 'name');
  }
}

```

This solution assumes that you are only interested to serve this very specific use case - remove the field only from this specific View. Users might still be able to see the Display Names of users in other areas of the website.

# Answer
> 3 votes
You can hide fields using hook\_entity\_field\_access, you can hide field based on user account (role is one of its properties), operation and entity which contain the field.

You also can use Field Permissions module to hide a field from certain roles.

# Answer
> 0 votes
When you need to delete the table header \< td \> and also rows \< td \> you can use template\_preprocess\_views\_view\_table

```
/**
 * Implements template_preprocess_views_view_table().
 */
function TEMPLATE_preprocess_views_view_table(&$variables) {
  // @TODO: You should use $variables['view']->name and $variables['view']->current_display to apply this only one specific view.

  // Let's assume your field name is node status.
  // Remove header label.
  if (isset($variables['header']) && isset($variables['header']['status']) {
    unset($variables['header']['status']);
  }

  // Remove row columns.
  foreach($variables['rows'] as $key => $row) {
    if (isset($variables['rows']) && isset($variables['rows'][$key]) && isset($variables['rows'][$key]['status'])) {
      unset($variables['rows'][$key]['status']);
      unset($variables['result'][$key]->node_status);
    }
  }

  // You can always print_r($variables['rows']) to know what is exact field name that you need to delete.
  // print_r($variables['result']).
  // print_r($variables['header']).
}

```

*Note: For any needs like this, try not to use more than two hooks to do your needs. Since Drupal always will do anything you want using one or two hooks no more.*

---

Update: For Drupal 7 also using the same hook name on this URL template\_preprocess\_views\_view\_table

# Answer
> 0 votes
Use the Views Field Permissions module. No custom code required!

Support for roles was added about a month ago.

---
Tags: views, 8, users
---


# Question
Title: How do I change the admin toolbar search input box to type=search?
I'd like to change the attribute "type" to "search". The search icon goes over the top of the text making it hard to see what you are typing. The themes are a combination of Adminimal for admin and Bulma for the front end. The Bulma front end is the problem.

The source html is as follows.

```
<input id="admin-toolbar-search-input" aria-labelledby="toolbar-item-administration-search" type="text" size="60" maxlength="128" class="form-text input ui-autocomplete-input" autocomplete="off" tabindex="-1">

```

I want the type attribute to be search so that the icon is hidden when you enter text.

I've tried overriding the bulma template input--bulma.html.twig. Not ideal from a scope perspective and setting these attributes here doesn't work.

{{ attributes.setAttribute('type', 'search') }}

Ideally I would find a theme pre-process function. I can't see to find one that works. How do I go about it?

# Answer
The following hook works. I found it by text searching the project

```
function mytheme_preprocess_input(&$variables, $hook) {
 if ($hook == "input" && $variables['attributes']['id'] == "admin-toolbar-search-input") {
   $variables['attributes']['type']  = "search";
 }
}

```

It does not solve the icon problem in this case. The icon is in a different DOM element.

The fix to the search icon being over the text was

```
#admin-toolbar-search-tab input:focus + .icon.is-left {
 display: none;
}

```
> 0 votes

---
Tags: toolbar
---


title: Clean Deleted Field from Database

text:
# Question
Title: Clean Deleted Field from Database
I have created fields deleted them. Tables for the fields are gone upon deletion, but they are still in `field_config` and `field_config_instance`

Is there anyway to clean them?

Thanks

# Answer
> 12 votes
The entries in `field_config` and `field_config_instance` will probably have had a value of `1` in the `deleted` column.

This means they're marked for deletion, but won't actually be deleted until you run cron (deleted field data is purged in `field_cron()`).

# Answer
> 14 votes
using drush:

```
$ drush eval "field_purge_batch(500)"

```

you might have to run a few times, or increase the $batch\_size then there might still be field\_deleted and field\_deleted\_revision tables, even after running cron

query

```
SELECT * FROM `field_config` WHERE `deleted` = 1
SELECT * FROM `field_config_instance` WHERE `deleted` = 1

```

if you come up empty, you can safely delete those leftover tables

# Answer
> 6 votes
As an alternative to running cron to remove deleted data, you can manually run field\_purge\_batch($batch\_size).

To manually run the function you can either:

* Bootstrap Drupal in a php file
* Create a menu hook page callback
* If you have the devel module installed visit /devel/php

The $batch\_size to use will vary depending on your server environment and needs. I've used values as low a 5 and as high as 10000.

# Answer
> 5 votes
For those Drupal 8 users,

I experienced this also, dig down the code. I found this all reason why fields not deleted after you did, the following:

* executing cron gazillion times
* run drush eval "field\_purge\_batch(500)" million times

The fields are persist not going away, this due to a piece of logic in here, in field\_purge\_batch

```
  // We cannot purge anything if the entity type is unknown (e.g. the
  // providing module was uninstalled).
  // @todo Revisit after https://www.drupal.org/node/2080823.
  if (!isset($info[$entity_type])) {
    continue;
  }

```

The modules which is the dependent, is uninstalled. that is the reason why the fields are not removed.

How to solve this? It is recommended approach to reinstall the module first and purge those fields and uninstall back. To find out which module you need to reinstall:

```
$fields = entity_load_multiple_by_properties('field_config', array(
  'deleted' => TRUE,
  'include_deleted' => TRUE,
));
dpm($fields); // this is devel module of var_dump

// check the protected member called "dependencies"

```

In case you dont want to go that approach of reinstall the module, you can also do right away delete, I am not sure what is the behaviour but it should do the job.

**Backup first!!!**

Yes, dont be lazy, it will save your ass, if something goes wrong.

```
$fields = entity_load_multiple_by_properties('field_config', array(
  'deleted' => TRUE,
  'include_deleted' => TRUE,
));

foreach ($fields as $field) {
  $field->delete();
}

// Retrieve all deleted field storages. Any that have no fields can be purged.
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ? : array();
foreach ($deleted_storages as $field_storage) {
  $field_storage = new FieldStorageConfig($field_storage);
  $fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
  if (empty($fields)) {
    field_purge_field_storage($field_storage);
  }
}

```

Do the cron for the last time. I hope it will fix the issue :)

# Answer
> -1 votes
Can't seem to find any solution. So I ended up deleting them from those two tables manually.

# Answer
> -1 votes
If you run several times the drupal cron, drupal will delete the field tables and its content. You can follow the next steps for run several times the cron easily, but this steps can block your system, web or hosting, but you can do if you control your system.

1. Go to Drupal status page (admin/reports/status).
2. Down in the page, you can see something like "run cron manually" and a link like "run cron from outside" and a link with a cron\_key parameter. Copy this link.
3. Go to a terminal (linux or mac terminal).
4. Write the next bash command:

while true; do curl \[put here the copied link, deleting the brackets\]; done;
5. Press enter. The command will be executed unlimited times.
6. You can go your database, like phpmyadmin, and look for "delete" named tables. You can see how the rows are being deleting and go down. When all tables with "delete" in the name are empties, it will be dropped. When you can't see any deleted tables in the database you can go to the final 7 step.
7. Stopped the bash command in the terminal. You can press ctrl + c keys. If you can't, close the terminal.

As I commented before, not is the best solution, but is simple, it work, you will not do anything wrong, because you are only running the drupal cron, so, you can break anything with some wrong php code. Otherwise, you can saturate the server, system, hosting or anything else in your web, because this steps run a lot of times the cron and this make web resources consumption, but if you have the control of the resources, there are no to much tables or rows to clean or you know is safe to do it for you system, you can do it.

And I know, it is not the best solution. But it work. Maybe it is the easy and best solution for your situation.

---
Tags: entities
---


# Question
Title: drupal_http_request() with POST returns a 405 error
I am trying to call an external API with a POST method which is working fine on Postman, but when trying to implement it in a custom module using `drupal_http_request()` I am getting a strange error.

> The requested resource does not support http method 'GET'.

This is the extracted cURL command from Postman: `curl --location --max-time 2000 --request POST 'https://example.com/api' --header 'Authorization: [token]' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'subject=Lead XXX' --data-urlencode 'firstName=XXX' --data-urlencode 'lastName=XXX' --data-urlencode 'Email=test@test.test' --data-urlencode 'Mobile=XXX' --data-urlencode 'Interest=XXX ' --data-urlencode 'meetingdate=2020-04-20T13:00:00.000'`.

This is the code I am using.

```
$url = 'https://example.com/api';
$data = [
    'subject' => 'XXX',
    'firstName' => 'XXX',
    'lastName' => 'XXX',
    'Email' => 'test@test.test',
    'Mobile' => 'XXXX',
    'Interest' => 'Testing',
    'meetingdate' => '2020-04-20T13:00:00.000',
];
$options = [
    'method' => 'POST',
    'headers' => array(
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Authorization' => [token],
    ),
    'data' => json_encode($data),
];
$request = drupal_http_request($url, $data);

```

I have the feeling this must be easy, but I couldn't figure out what I'm doing wrong. I search the documentation, searched here with no luck.

Any hit will be appreciated.

# Answer
In your post request you have specified

```
'Content-Type' => 'application/x-www-form-urlencoded'

```

but your post data is in JSON format.

Perhaps you need

```
'Content-Type' => 'application/json'

```

alternatively, pass the raw $data array as the post data for key=value&key1=value2 form encoding.

You also need to pass the function parameter $options instead of $data

```
$request = drupal_http_request($url, $options);

```
> 1 votes

---
Tags: 7
---


# Question
Title: Convert Database object into database URL string
I've define my own database connection in my Drupal settings file as follow:

```
$databases['migrate']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupal',
  'username' => 'root',
  'password' => 'root',
  'host' => 'localhost',
  'prefix' => '',
);

```

To read that in Database object format, you can run:

```
drush eval 'print_r(Database::getConnectionInfo("default", "migrate"));'

```

And now I would like to have the string representation (similar to $db\_url in Drupal 6) to use it in some drush commands on that database e.g. `drush --db-url=${DB_URL} status`.

So I would like to convert above Database array format into database URL string format (e.g. `mysql://root:root@localhost/drupal`).

Is there any easy way of doing that via function, PHP code or drush?

---

Additional info:

* There is update\_parse\_db\_url() function, but it's converting database connection URLs and return D7 compatible array.

# Answer
Using Drush:

```
drush sa @site --with-db-url

```

Or, to isolate just the db-url:

```
drush sa @site --with-db-url --format=csv --fields=db-url --field-labels=0

```
> 5 votes

# Answer
Here is one-liner:

```
drush eval '$db = Database::getConnection("default", "migrate")->getConnectionOptions();  echo $db["driver"] . "://" . $db["username"] . ":" . $db["password"] . "@" . $db["host"] . ":" . $db["port"] . "/" . $db["database"];'

```

---

For the long-term solution, this can be achieved by defining drush command in your module (foo.drush.inc):

```
/**
 * Implements hook_drush_command().
 */
function foo_drush_command() {
  $items = array();
  $items['get-db-uri'] = array(
    'callback'  => 'foo_drush_get_db_uri',
    'arguments' => array(
      'name' => array(
        'description' => dt('Database name.'),
        'required'    => TRUE,
      ),
      'key' => array(
        'description' => dt('Key.'),
        'required'    => TRUEs,
      ),
    ),
    'description' => dt('Returns database URI for a specified name and key.'),
    'examples' => array(
      'drush get-db-uri migrate default' => dt('Will return db uri in format: driver://user:pass@host:port/dbname'),
    ),
  );

  return $items;
}

/**
 * Implements hook_drush_help().
 */
function foo_drush_help($section) {
  switch ($section) {
    case 'get-db-uri':
      return dt("Returns database URI.");
  }
}

/**
 * Drush command (get-db-uri).
 *
 * Returns database URI for a specified name and key.
 *
 * @param string $name
 *   Database name.
 * @param string $key
 *   Key.
 */
function foo_drush_get_db_uri($name, $key) {
  $connection = Database::getConnection($key, $name);
  $info       = $connection->getConnectionOptions();

  echo $info['driver'] . '://' . $info['username'] . ':' . $info['password'] . '@' . $info['host'] . ':' . $info['port'] . '/' . $info['database'];
}

```

Example usage:

```
drush get-db-uri migrate default

```
> 0 votes

# Answer
In case you have bootstrapped drupal instance, drush and jq installed

```
drush status --fields="db-driver,db-hostname,db-port,db-username,db-password,db-name" --format="json" | jq '."db-driver"+"://"+."db-username"+":"+."db-password"+"@"+."db-hostname"+":"+."db-port"+"/"+."db-name"'

```
> 0 votes

---
Tags: 7, drush, uri, database
---


title: Database error with migration

text:
# Question
Title: Database error with migration
I am trying to migrate users and a few other entities from a Drupal 7 site to Drupal 8 with the built-in migration modules and Migrate Plus. I have added a database array in settings.php but something is missing to get the migrations to "see" the right database. I am getting this error.

\[Mon May 11 22:22:56.025896 2020\] \[php7:error\] \[pid 6389:tid 140003403929344\] \[client 62419\] PHP Fatal error: Method Drupal\user\Plugin\migrate\source\d7\Role::\__toString() must not throw an exception, caught Drupal\migrate\Exception\RequirementsException: No database connection configured for source plugin d7\_user\_role in /var/www//web/core/lib/Drupal/Component/Utility/Unicode.php on line 595, referer:

I have tried adding

```
shared_configuration:
 source:
   key: database_key

```

But it did not work.

Any help is greatly appreciated.

Thanks, Josh

# Answer
It's impossible to troubleshoot this remotely but there are a couple of things you can try to get connected to your source DB.

1. In your group's `shared_configuration.source` config you can manually add a `database` key with the same DB setting array properties that the migration module also looks for. For example:

```
shared_configuration:
 source:
   key: database_key
    database:
      driver: mysql
      username: user
      password: pass
      ...

```
2. Use the migrate update module to template out an initial working migration config rather than manually add your source DB. For example, run: `drush migrate:upgrade --legacy-db-key database_key ...`.
> 0 votes

---
Tags: 8, migrations
---


title: Add custom orderBy in ViewsSort plugin

text:
# Question
Title: Add custom orderBy in ViewsSort plugin
I'm attempting to sort the results of a View by matching one of the Entity IDs in the result set to the referring URL Entity ID. I'm trying to do this in a custom Views Sort plugin. I did some research on Custom Views Sort plugins and came across this link:

https://medium.com/oleksandr-trotsenko/drupal-8-views-tutorial-for-developers-part-iii-sorts-filters-49baa40418de

Following the tutorial, I arrived at the simplest `hook_views_data()` entry:

```
$data['node_field_data']['nid'] = array(
    'title' => t('Custom trials sort'),
    'group' => t('Content'),
    'help' => t('Sort events by by referral source.'),
    'sort' => array(
      'id' => 'trials_sort'
    ),
  );

```

I added this sort to the View in question. In the class with the id `trials_sort` I've added this method:

```
public function query() {
  $this->ensureMyTable();
  $has_custom_sort_id = $this->detectCustomSorting();
  if($has_custom_sort_id !== FALSE){
    $id_to_top = $has_custom_sort_id;

    $sql_snippet = <<<EOF
CASE $this->tableAlias.nid
  WHEN nid = $id_to_top THEN 1 ELSE 2
END
EOF;
    $this->query->addOrderBy(NULL, $sql_snippet, $this->options['order']);
    dd($this->query);
  }

}

```

The goal was to get an `ORDER BY` like:

```
ORDER BY (CASE WHEN nid = $id_to_top THEN 1 ELSE 2 END);

```

All of this is executing on the appropriate view. However, Drupal is adding the SQL in an odd way. In the above code, my `ORDER BY` looks close to right:

But my `fields` array looks very wonky:

I'm clearly missing something that tells Drupal to interpret this additional orderBy as a formula. How do i do that?

# Answer
> 1 votes
As shown in this SO answer:

How to sort on different columns in the same view?

the views SQL object uses -\>addField instead of -\>addExpression. This code ended up working for me:

```
  public function query() {
    $this->ensureMyTable();
    $has_custom_sort_id = $this->detectCustomSorting();
    if($has_custom_sort_id !== FALSE){
      $id_to_top = $has_custom_sort_id;
      $this->query->addField(NULL,
        "nid = ".$id_to_top, 'is_match');
      array_unshift($this->query->orderby,['field' => 'is_match', 'direction' => 'DESC']);
    }
  }

```

The `array_unshift` just moves the is\_match sort before the draggableviews sort which is also on this View. For some reason, re-arranging them in the View UI caused the draggableviews sort to drop off. Hope this helps someone in the future.

---
Tags: views, 8, plugins
---


# Question
Title: How to check if block is empty in page.html.twig
In my page.html.twig I have

```
<h2>{{ 'Block title'|t }}</h2>
<div class="">
  {{ drupal_block('leftblock') }}
  {{ drupal_block('rightblock') }}
</div>

```

I want to display **Block title** only if my custom leftblock and rightblock are filled.

Thanks.

---

**I tried**

If I do in my my\_module.module

```
function my_module_preprocess_page(&$variables) {
  $block = Block::load('leftblock');
  if ($block) {
    $variables['leftblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
  $block = Block::load('rightblock');
  if ($block) {
    $variables['rightblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
}

```

and in my page.html.twig

```
{% if leftblock or rightblock %}
  <h2>{{ 'Block title'|t }}</h2>
{% endif %}
<div class="my-class">
  {{ leftblock }}
  {{ rightblock }}
</div>

```

This {{ rightblock }} display the real content of the block in twig( when is filled ), but It always display **Block title** because the block have always something

if I do {{ dump(rightblock) }} i got this when the block is empty or filled.

array(3) { \["#cache"\]=\> array(4) { \["keys"\]=\> array(3) { \[0\]=\> string(11) "entity\_view" \[1\]=\> string(5) "block" \[2\]=\> string(22) "rightblock" } \["contexts"\]=\> array(2) { \[0\]=\> string(28) "languages:language\_interface" \[1\]=\> string(8) "url.site" } \["tags"\]=\> array(2) { \[0\]=\> string(10) "block\_view" \[1\]=\> string(41) "config:block.block.rightblock" } \["max-age"\]=\> int(-1) } \["#weight"\]=\> int(0) \["#lazy\_builder"\]=\> array(2) { \[0\]=\> string(42) "Drupal\block\BlockViewBuilder::lazyBuilder" \[1\]=\> array(3) { \[0\]=\> string(22) "rightblock" \[1\]=\> string(4) "full" \[2\]=\> NULL } } }

I have two themes :

block-myLeft.html.twig

block-myRight.html.twig

# Answer
> 0 votes
I couldn't solve my issue like that. What I did was to use only one block and pass 2 variables with a list of content in each. And then in twig I check if there any elements in each variable. So I display the title in that moment.

Block/myBlock.php

```
$build[] = [
  '#theme' => 'my_block',
  '#left_content' => $itemsL,
  '#right_content' => $itemsR,
];

```

My my-block.html.twig

```
{% if left_content is not empty or right_content is not empty %}
  <h2>{{ 'Block title'|t }}</h2>
{% endif %}

```

# Answer
> 2 votes
There is an EASY Solution for this. You need to save the rendered html of drupal\_block into a twig variable first and then check the value of the variable :

```
{% set leftblock %}
  {{ drupal_block('leftblock') }}
{% endset %}
{% if leftblock|striptags|trim %}
  {{ leftblock }}
{% endif %}

{% set rightblock %}
  {{ drupal_block('rightblock') }}
{% endset %}
{% if rightblock|striptags|trim %}
  {{ rightblock }}
{% endif %}

```

# Answer
> 0 votes
You could preprocess your template

```
function mytheme_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('leftblock');
  if ($block) {
    $variables['leftblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
  $block = \Drupal\block\Entity\Block::load('rightblock');
  if ($block) {
    $variables['rightblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
}

```

Than you can do this in your template

```
{% if rightblock or leftblock %}
  <h2>{{ 'Block title'|t }}</h2>
{% endif %}
<div class="">
  {{ leftblock }}
  {{ rightblock }}
</div>

```

# Answer
> 0 votes
It seems this is an issue discussed elsewhere. Perhaps one of those proposals will help you?

Without knowing exactly what a "full" lazybuilder array is supposed to look like, I can only offer a speculative suggestion based on the assumption regarding what the lazybuilder array's null value might imply. If it means there's no data, then perhaps you could try:

```
{% if leftblock['#lazy_builder'][1][2] is not null or rightblock['#lazy_builder'][1][2] is not null %}
    <h2>{{ 'Block title'|t }}</h2>
{% endif %}

```

For clarity, here is the variable dump formatted:

```
array(3) {
    ["#cache"]=> array(4) {
        ["keys"]=> array(3) {
            [0]=> string(11) "entity_view"
            [1]=> string(5) "block"
            [2]=> string(22) "rightblock"
        }
        ["contexts"]=> array(2) {
            [0]=> string(28) "languages:language_interface"
            [1]=> string(8) "url.site"
        }
        ["tags"]=> array(2) {
            [0]=> string(10) "block_view"
            [1]=> string(41) "config:block.block.rightblock"
        }
        ["max-age"]=> int(-1)
    }
    ["#weight"]=> int(0)
    ["#lazy_builder"]=> array(2) {
        [0]=> string(42) "Drupal\block\BlockViewBuilder::lazyBuilder"
        [1]=> array(3) {
            [0]=> string(22) "rightblock"
            [1]=> string(4) "full"
            [2]=> NULL
        }
    }
}

```

---
Tags: 8, theming, blocks
---


# Question
Title: How do I send an email from a module using an Easy Email module email template?
I am creating a form that needs to send an email upon form submission. I want to use the Easy Email module to send HTML emails. I want to send an email from my module, using an Easy Email template. How can I send an email from my custom module using an Easy Email template?

# Answer
> 3 votes
Sending an email from a custom module using an Easy Email template requires the following steps:

1. Create a new Easy Email template
2. Implement \[MODULE\].emails.yml
3. Tell the system to use the template from step 1 when sending the mail from your module
4. Send the mail from your module
5. (Optional) - Export and save configuration to your module

This example will show how to send an email to admins with the role `site_admin` when a group (using the Groups module) has applied for a review of some kind. The email requires the Group entity, to provide the group name and a link to the group.

**1) Create a new Easy Email template**

The email in this example will require a new template, with an entity reference field on the template for the Group entity that the email will refer to.

1. Navigate to `Admin -> Structure -> Email Templates` and click 'Add Email Template'.
2. Enter a name for the template, and make note of the machine name (the email template key). Save and proceed
3. In the template, set the following field values:

* From Name: \[site:name\]
* From Address: \[site:mail\]

3. Save.
4. Find the template you just created in the list, and under 'Operations', click 'manage fields'
5. Add an entity reference field to the Group entity and save
6. Back on the email templates listing page, edit the email. Group fields are available as tokens in the template body due to the entity reference to the group. The recipient of the mail is also available, and `[easy_email:recipient_uid:0:entity:display-name]` will provide the name of the recipient. Example email:

```
<p>[easy_email:recipient_uid:0:entity:display-name],</p>

<p>The group <a href="[easy_email:field_group:entity:url]">[easy_email:field_group:entity:title]</a> has submitted an application for something. Please review it.</p>

<p> </p>

<p>Thank you,</p>

<p>--  [site:name] team</p>

```

**2. Implement \[MODULE\].emails.yml**

Next, `[MODULE].emails.yml` needs to be implemented, so that the Easy Email module knows to override the email.

Note that this will require an arbitrary key for the email, that will be used to send the email from the module in step 4. In this example, the email key is `group.something_application_received`.

```
# This is the ID of the email override. I have keyed it by
# [ENTITY TYPE].[MAIL KEY].
group.something_application_received:
  # Re-use of the same ID above.
  id: 'group.something_application_received'
  # A label to be shown on the email override interface.
  label: 'Group: Custom domain application received'
  # This should be replaced with the machine name of the module.
  module: 'example'
  # The email key. This will be used by the module to send the email.
  key: 'group.something_application_received'
  # An array of parameters. At a minimum, account will be required for
  # the recipient of the email. In this example, Group is also required
  # to fill in the group values of the template.
  params:
    account:
      type: 'entity:user'
      label: 'Account'
    group:
      type: 'entity:group'
      label: 'Group'

```

**3) Tell the system to use the template from step 1 when sending the mail from your module**

The next thing is to link the email the module will send to the template created in step 1.

1. Navigate to `Admin -> Structure -> Email templates`
2. Click the 'Overrides' tab (note - requires the Easy Email Override module to be enabled)
3. Click 'Add Email Override'
4. Give it a label. Under 'Email to override', select the value entered for 'label' in \`\[MODULE\].emails.yml'. Under 'Easy email template', select the template created in step 1. Save.

**4) Send the mail from your module**

Finally, emails can be sent using the system default email manager. The Easy Email manager will handle the rest of it. In this example, the email is being sent from the submission handler of a form that stored a Group object in the form state.

```
/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
  $group = $form_state->get('group_entity');

  // Do some submission stuff (not shown).

  // Get the UIDs of all users with the site admin role.
  $uids = $this->entityTypeManager->getStorage('user')->getQuery()
    ->condition('status', 1)
    ->condition('roles', 'site_admin')
    ->execute();

  // Load the admins.
  $admins = User::loadMultiple($uids);
  // Loop through the admins, and send the email:
  foreach ($admins as $admin) {

    // Send an email to the admin using the mail manager.
    \Drupal::service('plugin.manager.mail')->mail(
      // The module machine name:
      'example',
      // The email machine name (use the same one declared in [MODULE].emails.yml)
      'group.something_application_received',
      $admin->getEmail(),
      $admin->getPreferredAdminLangcode(),
      // Populate the parameters declared in [MODULE].emails.yml:
      [
        'account' => $admin,
        'group' => $group,
      ]
    );
  }
}

```

**5) (Optional) - Export and save configuration to your module**

This step is optional insofar as the module will send mail after completing step 4. However, if the module is to be used in multiple systems, default configuration should be exported from the system and saved to the `[MODULE]/config/install` directory. The configuration exported should be:

1. Template configuration for the easy email template
2. Override configuration for the email override

Note that if you wanted your module to easy-email compatible, but not dependent, you can put the configuration in `[MODULE]/config/optional`, and do not declare the Easy Email module a dependency. This way your configuration will be used if the Easy Email module is already installed on the system, but will not require it. If you do take this path, you'll also need to implement hook\_mail() in your module and react to the key `group.something_application_received` to create the email text that will be sent when the Easy Email module is not installed.

---
Tags: 8, emails
---


# Question
Title: Custom module interfering with CSS on /user page
I am having trouble with a custom module. When my site is working properly, the /user page loads 4 CSS files. After rebuilding the cache, only three files load. It's not a 404, Drupal doesn't even try to load the last file.

If I disable the module and load the /user page, the CSS loads properly. I can then re-enable the module and the /user page continues to work. Doing a cache rebuild breaks it again. I'm wondering how that CSS file is generated, and how I can make it load properly when my module is enabled.

Oddly, this issue occurs even if I remove all implementation details from the module: the xyz.services.yml file and the src folder. The only remaining files are README.md and the barebones xyz.info.yml file:

```
name: XYZ Customizations
description: XYZ-specific additions and modifications.
package: Custom
type: module
version: 1.0
core: 8.x

```

I'm very confused why this might be happening. Any insight would be appreciated. Thanks!

# Answer
As it turns out, my custom module folder had the same name as my site's active theme. I believe this was causing the error. Renaming the module appears to have resolved the issue.
> 0 votes

---
Tags: caching, redirection
---


title: JSON API Filter by URL path

text:
# Question
Title: JSON API Filter by URL path
I am implementing a headless drupal website with json:api as the gateway to get all the data. I am able to get data by their node ids, but that is only if I knew the node id and type beforehand. Is there anyway to get the content by just using the url path?

For example, if one visits the url **https://mywebsite/article/test** I need to be able to use jsonapi to get all the data from that url, but because I don't know what the node id is for that url, I won't be able to retrieve those data. So, is there a filter I can use for url path using jsonapi?

Edit: I tried it by using the filter:

https://localhost:8080/jsonapi/node/blog\_article?filter\[path\]=/us/articlepage/testpage&include=field\_custom\_container

and it gives the following error:

> Invalid nested filtering. The field `path`, given in the path `path` is incomplete, it must end with one of the following specifiers: `alias`, `pid`, `langcode`.

Any ideas?

Thanks

# Answer
With JSON:API you can't filter by path because of technical limitations; JSON:API filters translate to entity queries on field values; because Drupal path aliases aren't fields you can't use the filter query param to look up articles by their alias.

A couple of different Drupal projects have cropped up around this limitation:

* Decoupled Router: Provides a new endpoint where a client can query a path for any possible JSON:API resources.
* Fieldable Path: Provides a new entity field (and thus queryable via the filter query param) that is designed to mimic the entity's path (with Pathauto support).

You can assess the tradeoffs from both modules and choose the one that makes the most sense for your use scenario.
> 6 votes

---
Tags: 8
---


# Question
Title: How to load a view via ajax without breaking ajax functionality?
What ist the correct way to load a View via Ajax and not breaking the view ajax functionality like the pager?

I tried it this way:

In a template:

```
<a href="/example-module/15?token=ugi2XH02Cumb3lsbSrOutwzRYSMXmn_bRKJI3FQ-hhk" class="btn use-ajax" role="button" rel="nofollow">
  {{- 'Load View' -}}
</a>

```

In the routing file:

```
example_module.example:
  path: '/example-module/{node_entity}'
defaults:
  _controller: '\Drupal\example_module\Controller\LoadViewController::render'
  _title: 'Load View'
options:
  parameters:
    node_entity:
      type: entity:node
requirements:
  _permission: 'access content'
  _csrf_token: 'TRUE'

```

In the Controller:

```
public function render(NodeInterface $node_entity, Request $request) {
  $node_id = $node_entity->id();
  if ($request->get(MainContentViewSubscriber::WRAPPER_FORMAT) == 'drupal_ajax') {
    $views_block = views_embed_view('load_view', 'block_1', $node_id);

    $response = new AjaxResponse();
    $selector = '#example-id';
    $replace = new ReplaceCommand($selector, \Drupal::service('renderer')->render($views_block));
    $response->addCommand($replace);
    return $response;
  }
  else {
    // For entities that don't have a canonical URL (like paragraphs),
    // redirect to the front page.
    $front = Url::fromUri('internal:/');
    $response = new RedirectResponse($front);
  }
  return $response;
}

```

This code works well. With two exceptions:

* The view is not working with ajax (e.g. Pager). But the option "use AJAX" is checked in the UI --- I also tried it with the Views::getView() method and add explicit the $view-\>setAjaxEnabled(TRUE) option. No success.
* The Pager of the View has the URL of the controller in it, not the URL from the current rendered page.

So if you click on the Pager of the new loaded Views, the page reloads and show you on a white screen the Ajax command, but no specific error, not in the console and not in the logs.

Is this way not working or what I'm doing wrong?

# Answer
> 6 votes
After examining the `ViewAjaxController.php` `ajaxView()` function, I came up with the following solution, which seems functioning for me. I created an ajax endpoint which extends `ViewAjaxController` and sets the requested view and display in the Request object then calls the parent `ajaxView()` method.

# 1. Define the route

**`my_module.routing.yml`**

```
my_module.views_ajax:
  path: '/admin/views/{nojs}/{view_id}/{display_id}/{args}'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleViewAjaxController::ajaxView'
  requirements:
    _permission: 'access content'

```

# 2. Create the controller

**`src/Controller/MyModuleViewAjaxController.php`**

```
namespace Drupal\my_module\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AppendCommand;
use Drupal\views\Controller\ViewAjaxController;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MyModuleViewAjaxController
 */
class MyModuleViewAjaxController extends ViewAjaxController {

  public function ajaxView(Request $request) {
    $view_name = $request->get('view_id');
    $display_id = $request->get('display_id');
    $dom_id = "{$view_name}__{$display_id}";

    $request->request->set('view_name', $view_name);
    $request->request->set('view_display_id', $display_id);
    $request->request->set('view_args', $request->get('args'));
    $request->request->set('view_dom_id', $dom_id);

    return parent::ajaxView($request);
  }

}

```

# 3. Create a wrapper `<div>` to embed the view

The `<div>` where you want to load a view via ajax has to have a specific css class in form of: `.js-view-dom-id-{view_id}__{display_id}`. Here replace the placeholders for view and display ids with the actual ones you want to embed.

```
<div class="js-view-dom-id-{view_id}__{display_id}"></div>

```

# 4. Load the view via ajax link

Now you can load the view creating links like:

```
<a href="/admin/views/ajax/{view_id}/{display_id}/{args}" class="use-ajax">
    This link will load the view {view_id} display {display_id} with the
    arguments {args}
</a>

```

---
Tags: views, 8, ajax
---


# Question
Title: With a WSOD upon deployment of a site, should I first clear the cache, check watchdog logs, or check the Apache logs?
With a WSOD upon deployment of a Drupal 8 site, should I first clear the cache, check watchdog logs, check the Apache logs, or something else?

I read the Drupal WSOD triage information here But it doesn't seem to share which solution should first be done in this situation.

This seems to indicate that it could be with the DB, so would I need to check that first?

I just noticed Fixing white screens step by step. It seems to suggest that I should look at the system (Apache) logs first. Am I interpreting this correctly?

# Answer
Yes. Because of the variety of possible Drupal stack configurations, it's impossible to say you'll always find your error in an Apache log. However, a WSOD generally means PHP has hit a fatal error and it's configured not to dump sensitive debug info to screen.

If that's the case, you might not even have a working Drupal app to make use of its tools like cache clearing, watchdog, etc., so it's best to find where those PHP errors are dumped so you can get Drupal into a bootstrapped state.

Of course, you should know your stack better than anyone else so a cache clear *could* eliminate the issue if you know the source of the problem. But if you're unsure, Apache logs are a good first start.
> 3 votes

# Answer
Assuming that your site and Apache has worked just fine before the deployment, and since this happens during a code update I'd suggest to **always clear the caches first**.

```
$ drush cr

```

And since data/entities might have changed during the update this then should be followed by database updates.

```
$ drush -y updb

```

Then re-check.

Your environment might simply be configured to suppress on-screen error messages. And you very likely get a hint on what's wrong on the command line when performing Drush commands.

I'd also always have a look at Watchdog then before starting to dig through any other logs.

```
$ drush ws

```
> 1 votes

---
Tags: 8, wsod
---


title: error from drupalroot

text:
# Question
Title: error from drupalroot
We have a live system.

```
define('DRUPAL_ROOT', getcwd());
define ('DRUPAL_ROOT', getcwd ());

```

I couldn't log in with the command

```
define('DRUPAL_ROOT', 'D:/www/webhosting/o3800_7Z55V5Hop2Ff/wwwroot/vts/')

```

I changed it this way

I entered the site but the page is broken as it appears in the photo

I request help on this subject, thanks.

# Answer
Firstly, will be better if you host a Drupal site on the separate domain/subdomain.

About your error, seems you forget copy all files (for example a folder with themes).

About the DRUPAL\_ROOT constant, you shouldn't change it.
> 0 votes

---
Tags: 7
---


# Question
Title: How to include media documents in search
Is there any way to include documents I created with the media core module into the search form of the page? I only found the categories "users" and "nodes".

# Answer
As I understand, you want to search by Media entities/records.

If you use the standard Search module from Core, then it impossible.

But you can install the Search API module, configure the search server (search server can use current drupal Database or Apache Solr, or smth other).

In the Search API you can create indexes and include the documents into the index.

To display a page with search results you can use a Views module (using content from Search API index) or you can try to use the Search API Pages module
> 1 votes

---
Tags: 8, media, search
---


# Question
Title: How to configure the gzip compressor for JSON response?
I am implementing REST resource endpoints to expose drupal content. Request to fetch this content is accepting gzip compressor but in response headers, this is not available.

I confirmed whether gzip is enabled in the server or not by viewing any content. In node view I can see the `Content-Encoding: gzip` in the Response headers. I tried manually to add headers in REST resource like below:

```
$response->headers->set('Content-Encoding', 'gzip');

```

But this is leading to below error:

Can anybody help me in this regard?

# Answer
> 0 votes
A little bit of research on this site lead me to this answer, which should help you setting up your server.

The header are just a declaration of a capacity, but if compression is not set up on the server(apache, nginx...), you will have this error.

How and where would I be able to enable/disable gzip compression?

---
Tags: 8
---


# Question
Title: Show external mysql database data in webform field
External database. - I want to allow drupal webform users to choose data from an external mysql database table. They would have the option to choose a region and an associated locality when completing the webform. What is the best way to expose this data in webform?

I have created a view using the entity reference but can't seem to expose this in the form field? What is the simplest

# Answer
> 0 votes
It seems you need Webform Views Select module. But it works for D7 only.

---
Tags: webforms
---