# Question
Title: How can I fix a migration input format mess?
I did a migration from Drupal 6 to Drupal 8 and now I have two *Full HTML*, two *Plain text*, and all other individual for both versions of Drupal default text formats. Of course when I try to modify the duplicates I have warning that it is not possible to have the same human readable names so I have *Full HTML* and *Full HTML2* now. I want to get rid the one of them. It looks like that all the migrated by me content is with a text format with a machine name 2 while the other Full HTML text format with no any content in the website is with the machine name *full\_html*. Also the default Plain Text, the one that it is not possible to be removed is with a machine name 3.

As far as understand by the research I did, even if I disable the *full\_html* text format, I cannot use its machine name for the other one. I don't mind what the name is, but can I safely change somehow the text format machine name 2 to something more meaningful?

Is it necessary to do so, or it will be fine if I leave it this way and just remove the *full\_html* one as far as I do not need it?

# Answer
One option is in the migration template, to add the input format value.

I found the `default_value` plugin worked well there e.g, to set default `full_html`:

```
field_subheading:
  plugin: sub_process
  source: field_subheading
  process:
    value: value
    format:
      plugin: default_value
      default_value: full_html

```

Another option, could be to run an SQL query to update the field data and revision data tables

```
update node__field_subheading set field_subheading_format = 'full_html' where field_subheading_format = 'other_format';
update node_revision__field_subheading set field_subheading_format = 'full_html' where field_subheading_format = 'other_format';

```

then clear cache.

However fixing as part of the migration template mapping is recommended.
> 1 votes

---
Tags: 8, migrations, input-formats
---


# Question
Title: How to configure trusted patterns for localhost:8082/d8multisite.com?
I have my drupal site running on localhost:8012. My url looks something like this : localhost:8012/d8multisite.com/ . I tried the following for enabling trusted\_host\_patterns.

```
$settings['trusted_host_patterns'] = array(
  '^d8multisite/.com$',
  '^localhost:8012//d8multisite/.com$',
  '^localhost/:8012//d8multisite/.com$',
  '^localhost/:8012//d8multisite/.com//$',
);

```

I don't have much knowledge of regular expressions. I have been following the official Drupal 8 documentation for reference. Please guide me as to where am I going wrong. Any help would be much appreciated. Thanks.

# Answer
The *trusted\_host\_patterns* settings is only for the domain name used to access the site. The regular expression you use must not include neither the port used to access the site, nor any path. If you access the site using as localhost, then the setting you should use is the following one.

```
$settings['trusted_host_patterns'] = array(
  '^localhost$',
);

```

If the site is accessible either as localhost or d8multisite.com, and you want to be able to access the site using both of them, then you should use the following setting.

```
$settings['trusted_host_patterns'] = array(
  '^localhost$',
  '^d8multisite\.com$',
);

```

Since the dot has a special meaning in a regular expression (it matches any single character), you need to escape it, so it is considered a normal character. To do so, you need to use *.* not */.*.
> 2 votes

---
Tags: configuration
---


title: Change field access per user

text:
# Question
Title: Change field access per user
I am trying to customize the access of user fields. We have an internal list of all users, which all members can access (for things like mail/address/phone number). However, due to privacy, each user should be able to manage these field, and can hide certains fields from showing to particular members or groups.

For this, I created a database table which stores all preferences, and fetch them using dynamic query. For the field access, I use

```
function MY_MODULE_has_access($operation, $field_machine_name, $uid){
  Code for determining access here
  return if $uid has access
}
function MY_MODULE_entity_field_access($operation, $field_definition, $account, $items = NULL) {
  if ($field_definition->getName() == "field_address") {
    $user = \Drupal::currentUser();
    $result = AccessResult::forbiddenIf(!MY_MODULE_has_access($operation, "field_address", $user->id()));
    $result->addCacheableDependency($user);
    return $result;
  }
  return AccessResult::neutral();
}

```

However, due to caching, this only works one time. If the user changes its preferences, the field access still remains unchanged. How can I fix this?

# Answer
The variable `$user` should probably be the parent entity of the field:

```
$user = $items->getEntity();

```

Which then when used as cache dependency should solve the caching issue:

```
$result->addCacheableDependency($user);

```

BTW you find the current user already in `$account`. If your access check depends on it then don't add it as object but use this predefined method for caching:

```
$result->cachePerUser();

```

But most times access code depends only on the current user roles and the resulting permissions, then you could use instead

```
$result->cachePerPermissions();

```

which is much better for cache performance.
> 1 votes

---
Tags: entities, hooks, caching
---


title: How do I upgrade the PHP version used?

text:
# Question
Title: How do I upgrade the PHP version used?
I've been away from Drupal a few years. I now want to develop a site. I see it's up to version 9. However, when I tried to install Drupal 9 in DevDesktop to get a feel for it, I got the message *PHP version too old.* I'm selecting the highest PHP version, 7.1.12, and still get this message. I know D9 likes PHP 7.5 or something, but how do I get that?

Should I simply upgrade PHP locally, independent of DevDesktop? Or is DevDesktop now old school, replaced by something better?

# Answer
> 1 votes
The latest version of Acquia Dev Desktop (released on May 21, 2020) is compatible with Drupal 9: It added support for MySQL 5.7 and Drush 10; PHP has been updated to versions 7.2.28 and 7.3.15.

Since Drupal 9 requires PHP 7.3 or higher, you need to select version 7.3.15 for Drupal 9, or you will get the error message you saw.

### References

---
Tags: acquia-dev-desktop, 9
---


# Question
Title: How to make loadByProperties or entityQuery case sensitive for field value
Neither loadByProperties or entityQuery are case sensitive. How to make it case sensitive? I'm using MySQL as a database but would rather have a portable solution if possible.

**With LoadByProperty**

```
$nodes = $this->entityTypeManager()
              ->getStorage('node')
              ->loadByProperties(['field_myfield' => $value]);

```

**With entityQuery**

```
    $entity_ids = \Drupal::entityQuery('node')
        ->condition('field_myfield',$value)
        ->execute();

```

You can, of course, build your own query as explained in this answer. But my question is specifically about using loadByProperties or entityQuery API.

# Answer
> 3 votes
It was `this` long issue thread, they add **sensitive case** support to **entityQuery**.

So instead of `=` operation you can use `= BINARY` or instead of `LIKE` you can use `LIKE BINARY`.
Try this:

```
$entity_ids = \Drupal::entityQuery('node')
  ->condition('field_myfield',$value, '= BINARY')
  ->execute();

```

---
Tags: 8, entities, database
---


title: Registered custom block not showing up

text:
# Question
Title: Registered custom block not showing up
I tried to register two custom block in my custom\_blocks module with the following code.

```
function custom_blocks_block_info(){
  $blocks = array();
  $blocks['featured_items'] = array(
    'info' => t('Featured Items'),
    'status' => TRUE
  );
  $blocks['workflow_illustration'] = array(
    'info' => t('How it works'),
    'status' => TRUE
  );
  return $blocks;
}

function custom_blocks_block_view($delta = ''){
  $block = array();
  switch ($delta) {
    case 'featured_items':
      $block['content'] = featured_items();
      break;
    case 'workflow_illustration':
      $block['content'] = workflow_chart();
      break;
  }
  return $block;
}

```

But the problem is 'Featured Items' block is shown in the block administer page. But the 'How it Works' block is not shown (may be not registered :?) in the block administer page.

I tried deactivating the module \>\> clear drupal cache \>\> clear browser cache (?) \>\> activate the module again.

Still the 'Featured Block' is the only block showing up. Please help me to get my block accessible via block administer page.

# Answer
> 1 votes
First, try to provide `$block['subject']`. Second, omit `status` in hook\_block\_info implementation, it may cause problems when there is no region assigned.

# Answer
> 1 votes
Double check if:

1. Module is enabled.
2. Module is not duplicated and `system` table points to the right file:

```
drush sqlq "SELECT * FROM system WHERE name = 'foo'"

```
3. You cleared all caches (in *Development/Performance*).

### Troubleshooting

* Check if `hook_block_info()` is called after clearing caches (add `exit('foo');` to see if that break the site). If it's not called, then:

+ check for typos,
    + restart external caches (such as `memcached` or `redis`) if in use,
    + restart Apache server (it could be `OPCache`/`XCache`)
* use `drush` to see if the hook is called:

```
drush cc all

```
* install `drush_extras` (via `drush dl drush_extras`) and check if the block is on the list when running from CLI:

```
drush block-show | less +/my_block

```
* if you've Devel enabled, try load the block at `/devel/php` and check if does exist:

```
print_r(block_load('foomodule', 'foodelta'), TRUE);

```

# Answer
> 0 votes
I remove status from info block. disable the my module and click uninstall tab and did uninstall for same module. after disabling the module it comes in uninstall list. clear cache and it's working now.

changed code:

```
function module_block_info() {
 $blocks = array();
 $blocks['hnavigation'] = array(
   'info' => t('Homepage Naviagation'),
 );
 $blocks['hslider'] = array(
   'info' => t('Homepage Banner Slider'),
 );

 return $blocks;
}

```

Previous code :

```
function module_block_info() {
 $blocks = array();
 $blocks['hnavigation'] = array(
   'info' => t('Homepage Naviagation'),
   'status'=>1,
 );
 $blocks['hslider'] = array(
   'info' => t('Homepage Banner Slider'),
   'status'=>1,

 );

 return $blocks;
}

```

# Answer
> 0 votes
If you're an eejit like me this can occur when you name a custom block something which matches a flagged #id tag in an adblocker.

---
Tags: 7, blocks
---


# Question
Title: Filter by specific field when webform exports
I have a webform with a field\_custom field. I need to download the submissions filter by this field.

I saw in the download page this:

Can I do the same programmatically with a plugin or something else to filter by my field(field\_custom)?

# Answer
> 0 votes
You need to use the Webform View Integration and create a custom Views Data Export.

---
Tags: 8, webforms
---


title: Paragraphs Grid module settings ignored

text:
# Question
Title: Paragraphs Grid module settings ignored
I'm using the Paragraphs grid module to display multiple paragraph entities in a grid. I followed the getting-started video and created a test page (see below for the source it generated), but it seems to be ignoring the grid settings I've chosen. I started by setting my first paragraph to full-width, and the next two to "2 columns" as shown in the video.

Looking at the elements in Chrome's inspector, the only classes set on these paragraphs contain only seemingly non-grid-related types: `paragraph paragraph--type--basic-paragraph paragraph--view-mode--default paragraph--id--14`. The source from what I can tell contains no grid-related markup or classes.

What could be causing the module not to behave as expected?

```
<!DOCTYPE html>
<html lang="en" dir="ltr" prefix="content: http://purl.org/rss/1.0/modules/content/  dc: http://purl.org/dc/terms/  foaf: http://xmlns.com/foaf/0.1/  og: http://ogp.me/ns#  rdfs: http://www.w3.org/2000/01/rdf-schema#  schema: http://schema.org/  sioc: http://rdfs.org/sioc/ns#  sioct: http://rdfs.org/sioc/types#  skos: http://www.w3.org/2004/02/skos/core#  xsd: http://www.w3.org/2001/XMLSchema# ">
  <head>
    <meta charset="utf-8" />
<meta name="Generator" content="Drupal 8 (https://www.drupal.org)" />
<meta name="MobileOptimized" content="width" />
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<link rel="shortcut icon" href="/Logo.png" type="image/png" />
<link rel="canonical" href="https://wilmettewatch.com/test-page" />
<link rel="shortlink" href="https://wilmettewatch.com/node/10" />
<link rel="revision" href="https://wilmettewatch.com/test-page" />

    <title>Test page | Wilmette Watch</title>
    <link rel="stylesheet" media="all" href="/sites/default/files/css/css_P_uhd9uFXz_crbPUanUYUW0d_XlQPVaT82ZcQeKjcms.css" />
<link rel="stylesheet" media="all" href="/sites/default/files/css/css_r6feGj8LSqa2_hg-aKcSQjNSMnct7c5IB_xVe2Y_oiQ.css" />
<link rel="stylesheet" media="all" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" />
<link rel="stylesheet" media="all" href="/sites/default/files/css/css_gudi_owL-2YsUCuS-NBbZM4ARsPDs4DIxZH-Z_rFxFM.css" />
<link rel="stylesheet" media="print" href="/sites/default/files/css/css_Y4H_4BqmgyCtG7E7YdseTs2qvy9C34c51kBamDdgark.css" />
<link rel="stylesheet" media="all" href="//fonts.googleapis.com/css2?family=Merriweather" />
<link rel="stylesheet" media="all" href="//fonts.googleapis.com/css2?family=Poiret+One" />

<!--[if lte IE 8]>
<script src="/sites/default/files/js/js_VtafjXmRvoUgAzqzYTA3Wrjkx9wcWhjP0G4ZnnqRamA.js"></script>
<![endif]-->

  </head>
  <body class="layout-no-sidebars page-node-10 path-node node--type-page">
    <a href="#main-content" class="visually-hidden focusable skip-link">
      Skip to main content
    </a>

      <div class="dialog-off-canvas-main-canvas" data-off-canvas-main-canvas>
    <div id="page-wrapper">
  <div id="page">
    <header id="header" class="header" role="banner" aria-label="Site header">
                      <nav class="navbar navbar-expand-lg" id="navbar-main">
                              <a href="/" title="Home" rel="home" class="navbar-brand">
              <img src="/Logo90.png" alt="Home" class="img-fluid d-inline-block align-top" />
            Wilmette Watch
    </a>

                                          </nav>
          </header>
          <div class="highlighted">
        <aside class="container-fluid section clearfix" role="complementary">
            <div data-drupal-messages-fallback class="hidden"></div>

        </aside>
      </div>
            <div id="main-wrapper" class="layout-main-wrapper clearfix">
              <div id="main" class="container-fluid">

          <div class="row row-offcanvas row-offcanvas-left clearfix">
              <main class="main-content col order-last" id="content" role="main">
                <section class="section">
                  <a id="main-content" tabindex="-1"></a>
                    <div id="block-wilmettewatch-page-title" class="block block-core block-page-title-block">

      <div class="content">

  <h1 class="title"><span property="schema:name" class="field field--name-title field--type-string field--label-hidden">Test page</span>
</h1>

    </div>
  </div>
<div id="block-wilmettewatch-content" class="block block-system block-system-main-block">

      <div class="content">

<article data-history-node-id="10" role="article" about="/test-page" typeof="schema:WebPage" class="node node--type-page node--view-mode-full clearfix">
    <div class="node__content clearfix">

<div class="field field--name-field-body field--type-entity-reference-revisions field--label-hidden">

  <div>
          <div class="field__item">

<div class="paragraph paragraph--type--basic-paragraph paragraph--view-mode--default paragraph--id--14">
  <div class="paragraph__column">

            <div class="clearfix text-formatted field field--name-field-body-text field--type-text-with-summary field--label-hidden field__item"><p>Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? </p>

<p>Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? </p>

<p>Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? Why isn't this working? Also, where's the summary? </p></div>

  </div>
</div>
</div>
          <div class="field__item">

<div class="paragraph paragraph--type--image paragraph--view-mode--default paragraph--id--16">
  <div class="paragraph__column">

            <div class="field field--name-field-image field--type-image field--label-hidden field__item">  <img src="/sites/default/files/2020-05/Logo90.png" width="90" height="90" alt="ww" typeof="foaf:Image" />

</div>

  </div>
</div>
</div>
          <div class="field__item">

<div class="paragraph paragraph--type--basic-paragraph paragraph--view-mode--default paragraph--id--17">
  <div class="paragraph__column">

            <div class="clearfix text-formatted field field--name-field-body-text field--type-text-with-summary field--label-hidden field__item"><p>More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? More text here. How does it look? </p></div>

  </div>
</div>
</div>
          <div class="field__item">
  <div class="paragraph paragraph--type--figure paragraph--view-mode--paragraphsgridtest landscape-photo">
          <figure class="article-figure">

        <figcaption> </figcaption>
      </figure>
      </div>

      </div>
      </div>

</div>

  </div>
</article>

    </div>
  </div>

                </section>
              </main>
                                  </div>
        </div>
          </div>
        <footer class="site-footer">
              <div class="container-fluid">
                            </div>
          </footer>
  </div>
</div>

  </div>

    <script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"node\/10","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"en"},"pluralDelimiter":"\u0003","suppressDeprecationErrors":true,"user":{"uid":0,"permissionsHash":"adf817ccf74d3c1df22405e040258050699cca41f71f33f2578ae311d9993ecb"}}</script>
<script src="/sites/default/files/js/js_ZjI08cC2AozgNCXBnZB5IuaaWKY0ilO1iDRLKNND_-E.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="/sites/default/files/js/js_qgveMN0dDH03r-aWKzJyg-TqpRxn6ZJGYKDT9jdAlpk.js"></script>

  </body>
</html>

```

# Answer
Paragraphs won't render markup for a particular content type if you don't set the format for its Paragraphs fields to `Paragraphs Grid (rendered entity)` as shown below.

Remember to make sure that if you have any custom display settings, that you also go to their tab and set the Paragraphs fields similarly. If you have the format set to the default (Rendered entity), Paragraphs will not generate the necessary markup.
> 0 votes

---
Tags: paragraphs
---


title: Ajax callback never called / triggered

text:
# Question
Title: Ajax callback never called / triggered
I'm working on a payment gateway, so I've created a BasePaymentOffsiteForm form where I'm trying to make an ajax callback, but it is not working. Can you help me to know what is wrong with my code?

```
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['content'] = [
      '#type' => 'container',
      '#prefix' => '<div id="validate-phone-number">',
      '#suffix' => '</div>',
    ];

    $form['content']['mobile_phone'] = [
      '#type'   => 'textfield',
      '#title'  => $this->t('Mobile phone'),
    ];

    $form['content']['validate_client'] = [
      '#type' => 'button',
      '#value' => $this->t('Validate Client'),
      '#ajax' => [
        '#callback' => [get_class($this), 'clientValidateForm'],
        'event' => 'click',
        'wrapper' => 'validate-phone-number',
      ],
    ];

    $form['content']['cancel'] = [
      '#type' => 'link',
      '#title' => $this->t('Cancel'),
      '#url' => Url::fromUri($form['#cancel_url']),
    ];

    return $form;
  }

  public static function clientValidateForm(array $form, FormStateInterface $form_state) {
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Pay',
    ];
    return $form['submit'];
  }

```

It never gets in cientValidateForm method.

# Answer
You're never making it to your callback because you don't have your `#ajax` array defined correctly, `callback` should not be defined as a hashed key. Take a look at the Adding an AJAX event example on d.o.

This should work:

```
$form['content']['validate_client'] = [
  '#type' => 'button',
  '#value' => $this->t('Validate Client'),
  '#ajax' => [
    // Change the callback key and update your callback value.
    'callback' => [$this, 'clientValidateForm'],
    'event' => 'click',
    'wrapper' => 'validate-phone-number',
  ],
];

```

Also note that Jaypan is right, you can't define new elements in your validation callback so you'll have to change that too. You may want to set a `$form_state` value in your validation handler and use that to add your element inside your build method. You may also need to update the wrapper value in your `#ajax` definition to align with the other changes.
> 1 votes

---
Tags: commerce, ajax, payment-gateways
---


# Question
Title: Count how many children have a reference to the parent
**Explanations:**

1) I have a node "parent"

2) I have 2 nodes "child"

3) Each child has a reference field (filled with a reference to the node "parent")

Now, I'm trying to create a list with the Views module.

**First problem:** This list is a list of "parent" nodes AND should include a column with the following result: COUNT(child with a reference to the parent).

**Second problem:** The count result should include only published children.

**Example 1 with 2 children published (2 children have a reference to the parent):**

Title of parent node | 2

---

**Example 2 with 1 child published (2 children have a reference to the parent):**

Title of parent node | 1

---

Sorry if it's not totally clear, it's hard to explain

Above all of this, if the result could be sortable it will be a good news but I don't think it will be possible...

# Answer
After a long time I finally found a solution to do that and it's a little bit complicated but it works.

1. I added a new custom field (which returns the count of children published with a parent reference)

```
  public function render(ResultRow $values)
  {
    /** @var Node $educational_institution */
    $educational_institution = $values->_entity;
    $educational_institution_id = $educational_institution->id();

    $connection = Database::getConnection();
    $query = $connection->select('node__field_educational_institution', 'n_educational_institution');
    $query->join('node_field_data ', 'n_data', 'n_educational_institution.entity_id = n_data.nid');
    $query->condition('n_educational_institution.field_educational_institution_target_id', $educational_institution_id);
    $query->condition('n_data.status', TRUE);
    $query->fields('n_educational_institution', ['entity_id']);

    return $query->countQuery()->execute()->fetchField();
  }

```
2. I added the possibility to sort by clicking the column header (in the same file)

```
  function clickSort($order) {
    /* Count educational_institution_requests whose have "published" status
     * - node_field_data.nid -> used by the "view" for listing educational institution entities
     * - node_field_data as n_data -> define an alias to avoid using the table from the main query
    */
    $subquery = '(
      SELECT COUNT(*)
      FROM node__field_educational_institution, node_field_data as n_data
      WHERE node__field_educational_institution.field_educational_institution_target_id = node_field_data.nid
      AND n_data.nid = node__field_educational_institution.entity_id
      AND n_data.status = 1
    )';
    $this->query->addOrderBy(NULL, $subquery, $order, "educational_institution_request_count");
  }

```
3. I added a custom filter

```
class EducationalRequestCount extends NumericFilter {

  /**
   * Helper function that builds the query.
   */
  public function query() {
    $this->ensureMyTable();
    /* Count educational_institution_requests whose have "published" status
     * - node_field_data.nid -> used by the "view" for listing educational institution entities
     * - node_field_data as n_data -> define an alias to avoid using the table from the main query
    */
    $subquery = '(
      SELECT COUNT(*)
      FROM node__field_educational_institution, node_field_data as n_data
      WHERE node__field_educational_institution.field_educational_institution_target_id = node_field_data.nid
      AND n_data.nid = node__field_educational_institution.entity_id
      AND n_data.status = 1
    )';
    $this->query->addField(NULL, $subquery, 'educational_institution_request_count');
    if(in_array($this->operator, ['between', 'not between'])) {
      $this->query->addHavingExpression(0, 'educational_institution_request_count ' . $this->operator . ' ' . $this->value['min'] . ' AND ' . $this->value['max'], []);
    } else {
      $this->query->addHavingExpression(0, 'educational_institution_request_count ' . $this->operator . ' ' . $this->value['value'], []);
    }
  }

}

```
4. Don't forget to declare the custom filter in the hook\_views\_data

```
    'filter' => array(
      'title' => t('Title'),
      'help' => t('Help'),
      'id' => 'educational_institution_request_count'
    )

```
5. My custom filter extends NumericFilter, we need an extra step

5.1. Create config/schema/my\_module.views.schema.yml file

5.2. Add this

```
views.filter.educational_institution_request_count:
  type: views_filter
  label: 'educational_institution_request_count numeric'
views.filter_value.educational_institution_request_count:
  type: views.filter_value.numeric
  label: 'educational_institution_request_count numeric'

```

Reference: https://drupal.stackexchange.com/a/238894/84848
> 0 votes

# Answer
**Second problem:** the views results will only include published entities if you add the filter: `Published (= True)`.

It's a lot more difficult if you want unpublished node to show in view results, but not be counted.

**First problem:**
The easiest way to solve this is by using the `Summary` option of a Contextual filter.

List the Child nodes in your Views, then add the Contextual filter for the Entity reference field to the Parent, and set it to display the Summary (adjust Validation and other options to your needs).

The Summary will list the Parents links, with the Children count next to them. When you click through the Parent links you will see the original Views Children list (but only for that clicked-on parent).

Don't forget the base path if the Views Display you're working on isn't the first Page Display in your Views.

The Summary also gives you the option to sort according to the Count :)

Your Contextual filter options should looks something like this:

```
When the filter value is NOT in the URL
Display a summary
Sort order: Descending
Sort by: Number of records
Format: List
Display record count with link

```

̣̣̣̣̣̣̣\_______________

Alternativelly you could count with the Agreggation option (under Advanced settings). You would count the children title field for example, their Entity IDs, while grouping the Parent reference field.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to conditionally change email content from Webform submissions
Reading the docs I can see that you can conditionally change the recipient of a webform email based on a field value, but that's not quite what I want to do. I want to modify the *content* of the message based on a form input. For example, based on a webform field like:

**Favorite Color:** \[\] Blue \[\] Yellow \[\] Red

Upon submission the user should receive totally different email messages saying either:

> You probably like the sky...

or

> You probably like bananas...

etc. (you get the idea).

Note: it would be clever and would solve this minimalistic example to create the options like

```
the sky|Blue
bananas|Yellow

```

and then use their tokens, but that's not an option in this case as it's multiple paragraphs of text I want to be different in the conditional messages.

# Answer
> 2 votes
This is more of a coding solution but you could implement hook\_webform\_submission\_presave() in a custom module and use that to save the appropriate text to a hidden webform field type, then see if the token for that field will work in the email.

Alternatively, you could implement hook\_webform\_submission\_insert() and send the email programmatically there, which would give you full conditional control of the email recipients and contents.

# Answer
> 1 votes
I haven't tried this, but looking to do the same I hope to go with

http://www.drupalcontrib.org/api/drupal/contributions%21webform%21templates%21webform-mail.tpl.php/7

That is, write your own webform-mail-\[nid\].tpl.php and have php logic there.

# Answer
> 0 votes
in drupal 8 it can be set in the handlers parameters

```
/admin/structure/webform/manage/contact/handlers

```

---
Tags: 7, webforms, emails
---


# Question
Title: Remove entity type without module uninstall
I created entity type my\_entity in my module. But now I don't need this entity anymore and I want to completely remove it without module's uninstall. I want to remove both definition and all database related tables or data. I thought about using `\Drupal::entityDefinitionUpdateManager->uninstallEntityType('my_entity')` in `hook_update_N`, but I can't use it because entity's definition will be removed.

Could anyone help me, and give advice how to delete both definition and database data?

*UPD*: I created an issue on drupal.org about this https://www.drupal.org/node/2655162

# Answer
The argument for entityDefinitionUpdateManager-\>uninstallEntityType() is an EntityTypeInterface, not a string.

Drupal stores the last known state of an entity type, you can get it like this:

```
$entity_update_manager = \Drupal::entityDefinitionUpdateManager();
$entity_type = $entity_update_manager->getEntityType('your_entity_type_id');
$entity_update_manager->uninstallEntityType($entity_type);

```

Note that this is using the enitty definitions update manager to get the entity type definition, not the runtime entity type manager.

The field definitions are also read from state and both the entity type and field definitions are purged afterwards.
> 11 votes

# Answer
You can also try

```
function MODULE_NAME_post_update_8104(&$sandbox) {
  // Making sure the entities are deleted.
  try {
    $storage_handler = \Drupal::entityTypeManager()
      ->getStorage('ENTITY_TYPE');
    $entities = $storage_handler->loadMultiple();
    $storage_handler->delete($entities);
  }
  catch (PluginException $e) {
    \Drupal::logger('MODULE_NAME')->error($e->getMessage());
  }
  catch (EntityStorageException $e) {
    \Drupal::logger('MODULE_NAME')->error($e->getMessage());
  }
  // Uninstalling the entity afterwards.
  $entity_update_manager = \Drupal::entityDefinitionUpdateManager();
  $entity_type = $entity_update_manager->getEntityType('ENTITY_TYPE');
  $entity_update_manager->uninstallEntityType($entity_type);
}

```
> 2 votes

# Answer
1. Delete all the entities of that type.
2. Remove the entity type declaration
3. Rebuild the caches
> 0 votes

---
Tags: 8, entities
---


# Question
Title: In custom install profile How to delete the "Footer" menu that core provides by default?
I am writing custom Drupal 8 install profile to be used in our organization.

The core creates the "Footer" menu as default system menu listed in menu admin page.

I want to delete or disable this menu during installation execution.

I already found that I can make it manually delete able if I add system.menu.footer.yml with

`locked: false`

But how can I eliminate it in the first place, via install profile ?

# Answer
Solved.

Following https://drupal.stackexchange.com/a/186322/8938 I added the code below to my\_profile\_install() function inside my\_profile.install file.

`\Drupal::configFactory()->getEditable('system.menu.footer')->delete();`

Reinstalled and yes, footer menu is not around anymore :)
> 3 votes

# Answer
*Edit: the OP asked how to do this in an install profile. For that please see the other answer.*

Using Drush:

```
drush config-delete 'system.menu.footer'

```

The Drupal console should work the same:

```
drupal config:delete 'system.menu.footer'

```

The same commands could be used to delete other system menus as well. E.g., `drush config-delete 'system.menu.main'`
> 0 votes

---
Tags: 8, distributions, installation-profiles
---


title: Tokens in field widget don't work

text:
# Question
Title: Tokens in field widget don't work
I am using drupal 8. I want to add tokens to the paragraph image field widget as data-attribute, but it doesn't work. What can be caused by this problem? Is it need some modules? Here screenshot:

Thanks!

# Answer
> 1 votes
I have used the wrong token field for the paragraph image field. Instead of \[media...\] token need to use \[paragraph:...\] token, as the field is paragraph field.

---
Tags: 8, tokens
---


# Question
Title: Categorized view for an entity reference content
I am trying to implement a Magazine in Drupal 9. I am confused about whether to use taxonomy term or content type since the data I want to handle is used for both categorizations and storing of content.

I have the following content structure.

A Magazine will have a number of articles, which are categorized under Topics.

* Magazine 1
    + Topic 1
        - Article 1
        - Article 2
    + Topic 2
        - Article 3
* Magazine 2
    + Topic 2
        - Article 4
        - Article 5
    + Topic 1
        - Article 6

At present, I am trying the following:

* Magazine - content type
* Article - content type
* Topic - Taxonomy term

Should I use taxonomy term or content type for *Magazine*? The *Magazine* content type is used for storing content (for example, cover image, description, and date) and also can be thought of as categorizing the articles and topics.

Please note: A topic can be used in multiple magazines. I have already gone through the following:

I hope someone can guide me through the correct path.

# Answer
> 2 votes
Drupal 8 taxonomies are entities so you can add custom fields, images (magazine covers), icons, as well as using for classification.

It doesn't sound like the Magazine "content type" is that complex, more of a catch-all for a listing of all your various articles and content related to each magazine, so that (Magazine as a taxonomy) would be my inclination in this situation.

The classification features of taxonomy work better out of the box than if you were do something custom with your content type.

I'd have 2 taxonomies for organising topics by:

(1) Magazine (2) Topic

If you are doing - or envisage possibly doing - something more complex with your Magazine type at a later stage then content type rather taxonomy may be the way to go.

As always with Drupal, there's more than one way to do it and you have to weigh up the pros and cons taking into account: ease-of-use, navigation, theming, scaleability, overhead, etc.

# Answer
> 1 votes
## categorize the articles based on the categories

1. Create a `Magazine view` page instead of the Magazine content type.
2. Create these filter criteria:

* Content-type: Article
    * Topic: is one of ( all)
3. expose the `Topic(field_catogry)` filter If you want to enable a user to select a specific category, or don't expose it and select the category that you want to display automatically.

## show a table of contents under a Magazine

1. Create another view, name it **'Content Table** (type: block)
2. use the filters to select the content that you want to display in this view, and change other parameters if you need to.
3. return to **Magazine** view in front of the **Footer** section click on **Add** button
4. search for **View area** --\> check it --\> click **Add an configure footer**
5. from view insert select **View: content\_table ...** view

---
Tags: taxonomy-terms, 9
---


# Question
Title: After selecting "My billing information is the same...." an Edit button is shown
QQ - When registered user goes through their cart to their payment information the "My billing information is the same as my shipping information. - Optional" is shown as default checked.

When they uncheck this box an **Edit** button appears. Is there any way to stop the edit button from appearing and simply show the fields? This happens when the user has NO address stored. So it's not very intuitive what the next step is.

In the CSS, on a working site I notice `id="shipping-information-wrapper"`

On my broken site, that div is not on the page. Instead, this is provided:

```
<div data-drupal-selector="edit-shipping-information-shipping-profile" id="edit-shipping-information-shipping-profile" class="js-form-wrapper form-wrapper">

```

# Answer
> 1 votes
Figured it out - The commerce Autosku module had a bug which is fixed here: https://www.drupal.org/project/commerce/issues/3086575

I decided to remove it entirely though as it doesn't work as well in D8 as it did in D7.

# Answer
> 0 votes
Given the screenshot you've shared, it appears your theme is adding that "- Optional" suffix to the checkbox label. I'm not sure if the theme is getting in the way of anything else, but it's worth looking into.

Out of the box, there's no way to have it show form fields first. We opted for the "Edit" button approach based on fairly extensive usability research. Making the edit operation explicit ensures we don't accidentally create duplicate addresses when the address book select list is present. I don't know what it isn't visible in your screenshot, to be honest. It should be, and if the customer doesn't have any addresses yet, then they should be seeing the form fields immediately like so:

---
Tags: commerce
---


title: How to append css class to menu link?

text:
# Question
Title: How to append css class to menu link?
We have a custom menu `mymenu` where we use menu\_link\_attributes to add CSS classes per menu link.

The problem we are running into is that we have one generic css class that we always want added regardless of whether it is entered through the Menu link attributes. In the twig template, it is using `{{ link(item.title, item.url) }}`.

We tried the following, but it will only replace `myCssClass` with whatever was their before and I cannot seem to find the right array when calling `mymodule_preprocess_menu()`.

`{{ link(item.title, item.url, item.attributes.addClass('myCssClass')) }}`

How can I append a CSS class to a menu link to the `item.attributes` array?

**menu--mymenu.html.twig**

```
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('menu') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

```

# Answer
> 3 votes
This is an easy one, I'm pretty sure you might have figured out yourself in a short while.

You see that `set classes` directive?

```
{%
  set classes = [
    'menu-item',
    item.is_expanded ? 'menu-item--expanded',
    item.is_collapsed ? 'menu-item--collapsed',
    item.in_active_trail ? 'menu-item--active-trail',
  ]
%}

```

This is where the magic happens and the classes array is built for all CSS classes to attach to your link item(s).

And this is also the place where you should add your additional CSS class that should be used in every link item, like so:

```
{%
  set classes = [
    'myCssClass',
    'menu-item',
    item.is_expanded ? 'menu-item--expanded',
    item.is_collapsed ? 'menu-item--collapsed',
    item.in_active_trail ? 'menu-item--active-trail',
  ]
%}

```

Leaving the rest of the template untouched (especially the `{{ item.attributes.addClass(classes) }}`) gives you the desired behavior.

Some further reading, that might be of interest for you: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

# Answer
> 3 votes
This is a little bit trickier because — as you can see — there are no anchor tags in the template. But there is the link() function instead. We have to add the class to this.

We also have to remove the menu item classes because they are leaking.

```
{% for item in items %}

      <li{{ item.attributes.addClass('nav-item') }}>
        {{ link(item.title, item.url, item.attributes.addClass('nav-link').removeClass('nav-item') ) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}

```

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


# Question
Title: I can't change permissions for text filters
I performed a pretty massive 50,000+ node migration a few weeks ago (from Drupal 7.70 to Drupal 8.9), and just noticed today that some of the Text Filters aren't visible in content creation pages (in particular, Plain text filter, which is what I like to make the default for most fields).

I tried creating a similar filter called "Plain", but when defining the default filter for content types on text fields, though at least now the new filter is visible as on option from the select box, it won't save (it reverts back to Full HTML filter on save). Furthermore, the filter permissions page shows that something is awry as well...as I am unable to assign ANY permissions for the new filter or two of the migrated filters to any custom roles.

Clearly the migration didn't go smoothly. It took me 2 weeks to get ANY migration to work properly...so I really do no want to roll back and try again if possible. Is there any way I an fix the text filters and their respective permissions problem here?

I have full access to the server, mysql, etc. Is there something I should be looking for in particular? Or at least a DB model that I can copy?

Thanks in advance for your help.

EDIT: I just noticed that I can go into the individual user roles, and "see" the checkboxes that aren't showing up on the Permissions matrix (where you can select permissions for all users at once). Is this maybe just a rendering bug for the main permissions display page? Here's another screenshot:

# Answer
This is a usability quirk of D8, in the Drupal Form UI the default format type for formatted text fields isn't configurable; it's dynamic based off form element properties (set by a developer), user role permissions, and the filter module settings (see form code)

By default, the fallback format (`Plain text` here) won't show as an option. There are a few things you can do here:

* Set `Plain text` as the highest priority filter, if you want it to be the default for all formatted text fields.
* Enable the `always_show_fallback_choice` config option (e.g. `drush config-set filter.settings always_show_fallback_choice true`), if you just want the format to be available.
* Use the Allowed Formats module, if you need some type of per-field configuration.
> 2 votes

# Answer
If you want to set "Plain text" to be the default format on new posts in your browser, go to "admin/config/content/formats" and put "Plain text" at the top of your text formats list.

From that page click on the configure button to set the text "filters" on your "Plain text format", for line breaks, HTML, etc.

When you create a new post it should be using the "Plain text" filter by default.

With regard to why certain text formats aren't available in the permissions settings after migrating to D8, you should check the Known Issues when upgrading page. For example, the PHP code filter is not supported in D8 core.
> 1 votes

---
Tags: 8, migrations, input-formats
---


title: Programmatically validate a user

text:
# Question
Title: Programmatically validate a user
I have created a webform which when submitted will create a new user for my Drupal 8 site.

The user must enter his username, email, and some additional data.

I am using below code to create & validate a user:

```
namespace Drupal\my_module\Plugin\WebformHandler;

use Symfony\Component\HttpFoundation\RedirectResponse;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;

use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
// use Drupal\taxonomy\Entity\Term;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Create New User Account when a webform submission is submitted.
 *
 * @WebformHandler(
 *   id = "Create New User Account",
 *   label = @Translation("Create New User Account"),
 *   category = @Translation("Entity Create"),
 *   description = @Translation("Create New User Account when a webform submission is submitted."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class CreateNewAccountHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

// Function to be fired while submitting the Webform.
public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

// Build Drupal DateTime & set correct format for your query.
  $current_time = \Drupal::time()->getCurrentTime();

// Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get 'Username' Value.
    $username = $values['username'];

    // Get 'Password' Value.
    $password = $values['password'];

    // Get 'Full Name' Value.
    $FullName = $values['full_name'];

    // Get 'Phone Number' Value.
    $PhoneNumber = $values['phone_number'];

    // Get 'Email' Value.
    $email = $values['email'];

// Create user object.
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $new_user = \Drupal\user\Entity\User::create();

    //Mandatory fields.
    $new_user->setPassword($password);
    $new_user->setEmail($email);
    $new_user->setUsername($username);    // Alphanumeric (abc, 123), space ( ), period (.), hyphen (-), apostrophe ('), underscore ( _ ), and the @ sign are only allowed.
    $new_user->set("langcode", $language);
    $new_user->set("preferred_langcode", $language);
    $new_user->set("preferred_admin_langcode", $language);
    $new_user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object.

    //Optional Fields
    $new_user->set("init", 'email');

    // Custom Fields
    $new_user->set("field_full_name", $FullName);
    $new_user->set("field_ph_nbr", $PhoneNumber);

    // Validate the user for possible errors.
    $violations = $new_user->validate();
    if (count($violations) > 0) {
      $property = $violations[0]->getPropertyPath();
      $msg      = $violations[0]->getMessage();

    // Show a custom message to user.
        \Drupal::messenger()->addError(t("$msg"));

      return FALSE;
    }

    // Activate the user Object (Status = Active).
    $new_user->activate();

    //Save user
    $new_user->save();

    // Get the new user ID.
    $new_user_id = $new_user->id();

    // Log in the user.
    user_login_finalize($new_user);

```

However, every time I try to create a new user using the webform, I got the below error:

```
This value is not a valid email address.

```

I have tried with:

* someone@hotmail.com
* someone@outlook.com
* someone@gmail.com

What is wrong with my code ?

# Answer
> 1 votes
The error message doesn't specify which field caused the validation error. In this case, the error is caused by setting the *init* field with a value that isn't a valid email address.

Differently from Drupal 7, in Drupal 8 the *init* field for the User entity is created using the email datatype. (See `User::baseFieldDefinitions()`.)

```
$fields['init'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Initial email'))
  ->setDescription(t('The email address used for initial account creation.'))
  ->setDefaultValue('');

```

Differently from the *mail* field, it doesn't get further constrains. (Compare the code used to create the *init* field with the following code.)

```
$fields['mail'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Email'))
  ->setDescription(t('The email of this user.'))
  ->setDefaultValue('')
  ->addConstraint('UserMailUnique')
  ->addConstraint('UserMailRequired')
  ->addConstraint('ProtectedUserField');

```

Still, as any entity field whose datatype is *email*, it has a constrain defined in the annotation of that datatype.

```
@DataType(
   id = "email",
   label = @Translation("Email"),
   constraints = {"Email" = {}}
)

```

(The classes defining that constraint are `EmailConstraint` and `EmailValidator`.)

Setting the *init* field for the User entity is optional, but it's generally used from administrators of a site when users claim they created an account for which they cannot retrieve the password they lost.
Depending on the purpose of the code you are using, you can either set the *init* field, or not. If you set it, it must set to a valid email value.

---
Tags: 8, users
---


title: Trusted host patterns not working

text:
# Question
Title: Trusted host patterns not working
I have an issue where I'm trying to make it a "Trusted host patterns" on settings.php. It gets an issue of "The provided host name is not valid for this server."

I have tried many times to get it to work, the issue work with:

```
$settings['trusted_host_patterns'] = array(
  '^',
);

```

**But will not get the following to work**

```
$settings['trusted_host_patterns'] = array(
  '^sandbox\.dev$',
);

```

Thanks

# Answer
According to your screenshot, your hostname is `localhost`, not `sandbox.dev`, so the correct regex would be `^localhost$`
> 1 votes

---
Tags: 8, configuration
---


# Question
Title: How do I override ajax-progress-throbber in a theme?
In my Drupal 7 site, I created a custom theme. In my theme, I want to change the AJAX progress throbber HTML structure, which by default is the following one.

```
<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div><div class="message">Please wait...</div></div>

```

I searched a lot about this issue, but I couldn't find any useful document or sample.

# Answer
It looks like this is mostly contained within `misc/ajax.js` file. For example in the `beforeSend` method:

```
  else if (this.progress.type == 'throbber') {
    this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>');
    if (this.progress.message) {
      $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>');
    }
    $(this.element).after(this.progress.element);
  }

```

What I think you would need to do is override this. Clive provides an answer here on how to do just that.

```
(function($) {
  // In mymodule.js, which appears after ajax.js in the page build
  Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
    // Replacement code.
  }
})(jQuery);

```

So your custom file would have to load last or at least after the core file does in order to override it.

Myself, I would probably attempt to create a new progress type, but it looks like other areas override aspects of AJAX callbacks to force throbber as the default, which means you'd have to override more functions and handle that.

Of course, this change above means the throbber would be overridden everywhere it appears in your theme, which may or may not be desired (think Views using AJAX paging, Form AJAX, etc).
> 2 votes

# Answer
For **Drupal 8** there is a new way of doing this as per this change record

add the following into the respective files

`THEMENAME.info.yml`

```
libraries-extend:
  core/drupal.ajax:
    - THEMENAME/throbber

```

`THEMENAME.libraries.yml`

```
throbber:
  css:
    css/throbber.css: {}
  js:
    js/throbber.js: {}
  dependencies:
    - core/jquery
    - core/drupal

```

`js/throbber.js`

```
/**
 * @file
 * Replaced Drupal cores ajax throbber(s), see: https://www.drupal.org/node/2974681
 *
 */
(function ($, Drupal) {
  Drupal.theme.ajaxProgressThrobber = function () {
    return "<div class=\"ajax-spinner ajax-spinner--inline\"><span class=\"ajax-spinner__label\">" + Drupal.t('Loading …', {}, {
      context: "Loading text for Drupal cores Ajax throbber (inline)"
    }) + "</span></div>";
  };

  Drupal.theme.ajaxProgressIndicatorFullscreen = function () {
    return "<div class=\"ajax-spinner ajax-spinner--fullscreen\"><span class=\"ajax-spinner__label\">" + Drupal.t('Loading …', {}, {
      context: "Loading text for Drupal cores Ajax throbber (fullscreen)"
    }) + "</span></div>";
  };
    // You can also customize only throbber message:
    // Drupal.theme.ajaxProgressMessage = message => '<div class="my-message">' + message + '</div>';
})(jQuery, Drupal);

```

`css/throbber.css`

```
// optional code of your ajax-spinner classes

```

An **alternative** would be to use the ajax\_loader module which lets you customize the throbber.
> 7 votes

---
Tags: ajax
---


title: How do I theme the teaser?

text:
# Question
Title: How do I theme the teaser?
As shown in the picture, I have the teaser view of a taxonomy term (*Virtual Tour*) which shows the node title, the node summary, the submission date, and an image added in an image field.

What I would like to achieve is to let the image float to the left of the summary. Is there a way to achieve it?

>

# Answer
The teaser view mode display is controlled on the display modes of the given entity type, in this case, node. You can control the field order and formatters used there, and other modules like Display Suite can enhance the options here.

With that, you can also provide a twig template to change the markup and classes of this view mode being displayed for the node. From there, you can style it all you want once you have the markup and fields the way you want them.

More:
> 5 votes

# Answer
You should already have a template suggestions available like :

```
<!-- FILE NAME SUGGESTIONS:
   * node--2--teaser.html.twig
   * node--2.html.twig
   x node--BUNDLE--full.html.twig
   * node--BUNDLE.html.twig
   * node--teaser.html.twig
   * node.html.twig
-->

```

Make sure you have settings.yml set to `twig.config: { debug: true ...` and you will see the `suggestions` in the source. You can set suggestions for any hook like:

```
function MODULE_theme_suggestions_node_alter(array &$suggestions, array $variables, $hook) {
 $node = $variables['elements']['#node'];
 $type = $node->bundle();
 $view_mode = $variables['elements']['#view_mode'];

 $suggestions[] = 'node__'.$type;
 $suggestions[] = 'node__'.$type.'__'.$view_mode;
}

```
> 7 votes

# Answer
In the template file, you can render the teaser in view mode.

```
{% if view_mode == 'teaser' %}
  <!-- Start Display article for teaser page -->
  <div class="portfolio-v1">
    {{ content.field_some_portfolio_images }}
  </div>
{% elseif view_mode == 'teaser_2' %}
  <!-- Start Display article for teaser 2 page -->
  <div class="portfolio-v2">
    {{ content.field_some_portfolio_images }}
  </div>
{% else %}
  <!-- Start Display article for detail page -->
  <article{{ attributes.addClass(classes).addClass('node-detail') }}>
    <div class="post-block portfolio-single">
      {% if content.field_some_portfolio_images %}
        {{ content.field_some_portfolio_images }}
      {% endif %}
    </div>
  </article>
{% endif %}

```
> 0 votes

---
Tags: theming, 8, taxonomy-terms
---


# Question
Title: How to exclude a module from being uninstalled during import?
On my local I have installed my custom module which depends on a contrib module.

I have removed both modules from the `core.extensions.yml` and added the following to settings.local.php.

```
$settings['config_exclude_modules'] = ['contrib_module', 'mymodule'];

```

But when I execute `drush cim`, both of the modules get uninstalled.

But I can read this specifically.

> When syncing configuration, if an excluded module is already installed, it will not be uninstalled by the configuration synchronisation, and dependent configuration will remain intact.

Do I need to execute some command after adding it to the settings.php? Why it is not working.

# Answer
This will only work with drush 10. So drush should be updated to version 10.

With drush version lower than 10, it will work only from the UI.
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: How do I change the limit of user accounts gets blocked or suspended?
After entering the wrong password for 5 time, a user account gets locked/suspended.

How do I change this? Instead of 5, I need the accounts are blocked after 10 tentatives.

I already seen the Flood Unblock module, but it unblocks the already blocked users who entered the wrong password more than 5 times.

# Answer
This is a configuration setting. You can run the drush command:

```
drush cset user.flood user_limit 10

```
> 4 votes

# Answer
Drupal uses code similar to the following one, to check if the user entered the wrong password too much times.

```
    // Don't allow login if the limit for this user has been reached.
    // Default is to allow 5 failed attempts every 6 hours.
    if (!$this->flood->isAllowed('user.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
      $form_state->set('flood_control_triggered', 'user');
      return;
    }

```

`$flood_config` is initialized with the following code.

```
$flood_config = $this->config('user.flood');

```

The value you need to change is *user\_limit*; *user\_window* is the time (in seconds) after which the number of attempts is reset. (The default values are reported in the code comment.)

Since those values aren't exposed in an administrative settings page, you can use code similar to the following to alter them.

```
$config = \Drupal::service('config.factory')->getEditable('user.flood');
$config->set('user_window', 10)->save();

```

Similarly, you could alter the *user\_window* value, which is the time expressed in seconds.

Note that Drupal core has also a limit for the attempts to log in from the same IP, which is checked from the user login form.

```
  // Do not allow any login from the current user's IP if the limit has been
  // reached. Default is 50 failed attempts allowed in one hour. This is
  // independent of the per-user limit to catch attempts from one IP to log
  // in to many different user accounts.  We have a reasonably high limit
  // since there may be only one apparent IP for all users at an institution.
  if (!$this->flood->isAllowed('user.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
    $form_state->set('flood_control_triggered', 'ip');
    return;
  }

```

As the code comment says, by default 50 failed attempts are allowed in one hour.
That value needs to be considered, since when the value of *user\_limit* is set higher than the *ip\_limit* value, it's the latter value that is used. Since a module could change the value for *ip\_limit*, even change it to a value lower than *user\_limit*, I would check the value for *ip\_limit* and eventually correct it.
> 1 votes

---
Tags: 8, users
---


title: How do I maintain API versions?

text:
# Question
Title: How do I maintain API versions?
I have different REST End points in my Drupal 8 instance, some of them are exposed from REST Views and some are custom controllers. I have a situation where I want to maintain versioning with my end points.
I have replaced some fields in the new version and the users relying on the older API version must not be impacted by the change.
In the case of a controller, how can I manage different output for different API versions?
Also, in the case of REST Views, where the URL is directly exposed, how can new data be added to that?

For example, the */rest/taxonomy-list* endpoint gives a certain set of terms as JSON output. In the new API version, I have to add/remove/replace one term which is present in same vocabulary.

# Answer
One approach to version the API is to add a version number to the URL. So, for example your Views REST display URL `/rest/taxonomy-list` would become `/rest/v1/taxonomy-list` or `/rest/v2/taxonomy-list`

You could duplicate the existing Views display to adjust the fields and new URL in a new REST display.

For custom REST API plugins, you can extend the existing RestResource and give it a new URL, e.g:

```
use Drupal\my_module\MyRestResource;

/**
 * Sample Rest Resource
 *
 * @RestResource(
 *   id = “my_rest_resource_v2”,
 *   label = @Translation(“My Rest Resource (v2)“),
 *   uri_paths = {
 *     "canonical" = "/api/rest/v2/endpoint”
 *   }
 * )
 */
class MyRestResourceV2 extends MyRestResource {

  // Extend and override functions here

}

```
> 2 votes

---
Tags: 8
---


# Question
Title: How to change the value of a user field through Restfull?
I can’t change the value of field\_motherid field through restfall. GET running, PUT disabled, PATCH enabled and configured. When I do GET there is no user field.

# Answer
> 0 votes
Assuming the user rest resource is enabled and `PATCH` requests are configured, also that the requesting user is authenticated to update the user, then:

send a `PATCH` request to: https://example.com/user/$uid?\_format=json

Where `$uid` is the user id to update (e.g 12)

The request body should look something like this (json format):

```
{ "field_motherid":
  [
    {"value": "new_value"}
  ]
}

```

---
Tags: users, 9
---


# Question
Title: Load the node as EntityInterface not NodeInterface
`hook_node_insert(NodeInterface $node)` gets a `NodeInterface` parameter. I need to pass it to `mymodule_node_operations(EntityInterface $entity)` which accepts an `EntityInterface` parameter.

How do I load this node as `EntityInterface` type? Basically I need to downcast to the parent class which is Entity.

This is the error I get when attempting to pass `$node` to the function as `NodeInterface`.

> TypeError: Argument 1 passed to mymodule\_node\_operations() must be an instance of EntityInterface, instance of Drupal\node\Entity\Node given

# Answer
> 1 votes
The problem was that I did not include the required class. I added the following to get it to work:

```
use Drupal\Core\Entity\EntityInterface;

```

# Answer
> 0 votes
Node has EntityBase in its hierarchy. EntityBase implements EntityInterface. This means you can pass a Node to a function that expects EntityInterface, since Node extends a class that implements that interface. This is how OOP works, and why classes are type hinted with interfaces (eg. EntityInterface) rather than a specific class (eg. EntityBase).

---
Tags: nodes
---


# Question
Title: Javascript file is being included but console.log wont work
So I THINK I have configured my javascript right in that i want to inlude two files. leaflet.js and mappingsource.js and currently on the page source there exists this:

```
<script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/web\/","scriptPath":null,"pathPrefix":"","currentPath":"hello\/world","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"en"},"pluralDelimiter":"\u0003","suppressDeprecationErrors":true,"ajaxPageState":{"libraries":"bartik\/global-styling,big_pipe\/big_pipe,classy\/base,classy\/messages,contextual\/drupal.contextual-links,contextual\/drupal.contextual-toolbar,core\/drupal.active-link,core\/html5shiv,core\/normalize,helloworld\/leaflet,helloworld\/mappingsource,quickedit\/quickedit,shortcut\/drupal.shortcut,system\/base,toolbar\/toolbar,toolbar\/toolbar.escapeAdmin,tour\/tour,user\/drupal.user.icons","theme":"bartik","theme_token":null},"ajaxTrustedUrl":{"\/web\/search\/node":true},"bigPipePlaceholderIds":{"callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages\u0026args%5B0%5D\u0026token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA":true,"callback=user.toolbar_link_builder%3ArenderToolbarLinks\u0026\u0026token=xssKdKFVFD7N0FUPPcC1C7LrqMHpQFVzUhrI4cOeEgs":true,"callback=user.toolbar_link_builder%3ArenderDisplayName\u0026\u0026token=-MH2NzEnTzbzMk0ZGfGgoiw7G3j_-Q1ILWBRVhIOKLI":true,"callback=shortcut.lazy_builders%3AlazyLinks\u0026\u0026token=N1997Wch59v-LxHku3-dD44wjkSNmhegNzlZ8jS0L5I":true},"toolbar":{"breakpoints":{"toolbar.narrow":"only screen and (min-width: 16.5em)","toolbar.standard":"only screen and (min-width: 38.125em)","toolbar.wide":"only screen and (min-width: 61em)"},"subtreesHash":"fFW4IHdcFxAYeqwFjFGFpjKbwADtToCo9LEGFmDLWwY"},"user":{"uid":"1","permissionsHash":"3e05456fe0e0014e93091ef2c6ad9fbbe0e5c07d9303f114c638bbc071d789d2"}}</script>

```

Whih both have settings? for the files that i want however the file mapping source looks like this

```

$( document ).ready(function() {
    console.log( "ready!" );
});

window.onload = "test()";

function test() {
    console.log('123');
}
console.log('test');
var map = L.map('map', {
    center: [51.505, -0.09],
    zoom: 13
});

```

Which should be console logging SOMETHING surely? Is there something I'm missing?

Additional files look like this

helloworld.libraries.yml

```
helloworld:
  version: 1.x
  js:
    js/leaflet.js: {}
    js/mappingsource.js: {}

```

```
<?php

/**
 * @file
 * Contains helloworld.module.
 */

helloworld.module
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function helloworld_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the helloworld module.
    case 'help.page.helloworld':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Hello World example module') . '</p>';
      return $output;

    default:
  }
}

function helloworld_page_attachments(array &$attachments) {

  // Unconditionally attach an asset to the page.
  $attachments['#attached']['library'][] = 'helloworld/leaflet';
    $attachments['#attached']['library'][] = 'helloworld/mappingsource';

}

/**
 * Implements hook_theme().
 */
function helloworld_theme() {
  return [
    'helloworld' => [
      'render element' => 'children',
    ],
  ];
}

```

```

```

# Answer
> 3 votes
You need to attach complete libraries, not single library files. Your module has the name `helloworld`, this is the first part before the slash. In your libraries.yml you have defined the top key `helloworld`, this is the library name and the second part after the slash:

```
$attachments['#attached']['library'][] = 'helloworld/helloworld';

```

This line will attach all JS and all CSS listed under that specific library.

Sidenote: Try to use Drupal.behaviors instead of `$(document).ready`, this is the Drupal-way to do stuff like this. Otherwise you might run into problems with Ajax-calls or lazy-rendered blocks rendered with BigPipe module.

---
Tags: javascript
---


title: I am unable to post image references

text:
# Question
Title: I am unable to post image references
I have had this module working for years. Recently, it has stopped working. I'm using Services 3 to:

* Log in and get a token
* Create an image file and get its file ID
* Create a node, using the file ID from the previous step for the image field

The JSON I'm posting for the image field on the node is similar to the following.

```
   "field_image":{
      "und":[
         {
            "fid": 10279
         }
      ]
   }

```

Suddenly, I can't get the node I'm creating to reference an existing field via the file ID. The node and the image are created without issues, but the image field is empty.

Is there some other way I should be doing this?
This seriously worked for years, so I'm not sure what changed.

I am using the Services module 7.x-3.27.

# Answer
> 0 votes
Turns out you need a patch. Field was multi-value. https://www.drupal.org/project/services/issues/2224803

---
Tags: 7, services
---


# Question
Title: Include referenced term's custom fields in node view with content display
I have a taxonomy term reference field in a node (D8).

I have a content (node) view that needs to use a content display rather than fields.

The term is selected, but not the custom fields that have been added to the vocabulary (see the query, below).

The display settings for the vocabulary have all the fields being displayed.

I thought perhaps there was a relationship that I could add that would result in the fields being selected. The only applicable option is for Taxonomy term, which I have added. It results in the taxonomy\_term\_field\_data being joined, but not the custom fields.

Do I actually need to hook the query before execution to add joins for the additional fields?

```
SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid, taxonomy_term_field_data_node__field_tags.tid AS taxonomy_term_field_data_node__field_tags_tid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_tags} node__field_tags ON node_field_data.nid = node__field_tags.entity_id AND (node__field_tags.deleted = '0' AND node__field_tags.langcode = node_field_data.langcode)
LEFT JOIN {taxonomy_term_field_data} taxonomy_term_field_data_node__field_tags ON node__field_tags.field_tags_target_id = taxonomy_term_field_data_node__field_tags.tid
WHERE (node_field_data.status = '1') AND (node_field_data.type IN ('article'))
ORDER BY node_field_data_created DESC
LIMIT 1 OFFSET 0

```

# Answer
The Default Content View mode is controlled through the `Manage display` page of the related Content Type.

Check that page and make sure that the Taxonomy Term reference field is set to `Rendered entity` and not `Label` or some other option.

The Rendered entity option will make sure that all the Vocabulary fields set to be displayed for terms will also appear under Content rendering of the Content type.
> 1 votes

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


# Question
Title: Change Views BETWEEN min/max filter to a cleaner URL format?
Is there an easy way to change the default exposed BETWEEN filter to work with:

`price=1000-2000`

Instead of:

`price[min]=1000&price[max]=2000`?

Would it be reasonable to create my own Numeric filter or am I looking at a lot of modification?

# Answer
You can always create redirects with rewrite rules outside of Drupal, in your server configuration. You can add them in Drupal settings too.

There is a module that did this for Views in D7 but it needs more help with D8, help if you can:

Query Parameters To URL
> 1 votes

---
Tags: views, 8
---


title: CKEditor adds extra <p> tag

text:
# Question
Title: CKEditor adds extra <p> tag
CKEditor inserts extra `<p>` tags when users enter a newline.

How do I disable this automatic paragraph tag?

# Answer
You need to modify these settings to CKeditor.

```
// The writing rules for the <p> tag.
writer.setRules( 'p', {
// Inserts a line break after the <p> opening tag.
        breakAfterOpen : true,
}

```

This can either be set programmatically, via JS or I believe you should be able to add it directly via the UI, if you visit the Ckeditor settings page, there should be a box where you can enter ckeditor settings.

For more info see ckeditor docs: https://docs-old.ckeditor.com/CKEditor\_3.x/Developers\_Guide/Output\_Formatting
> 0 votes

# Answer
Edit the Text format your users use and disable the option that turns new lines into paragraphs or breaks.

You can find the Text formats under `Configuration > Content authoring > Text formats and editors`.

When you edit the one your users are using you will see that option enabled, you have to **disable it**:
> 0 votes

---
Tags: 8, wysiwyg
---


title: How to set user flood limit role wise?

text:
# Question
Title: How to set user flood limit role wise?
If user account is locked after entering wrong password 5 times. That's a default setting.

That can be changed via

```
drush cset user.flood user_limit 10

```

I have different roles. I need to set flood user\_limit role wise

```
Role A, It will be 10
Role B, It will be 7

```

Can we achieve same thing via CLI?

# Answer
> 1 votes
No you can't.

The `user.flood user_limit` config setting feeds into the `DatabaseBackend::isAllowed()` method as the `$threshold` arg, which is used to compare the row count for this query:

```
  $number = $this->connection
      ->select(static::TABLE_NAME, 'f')
      ->condition('event', $name)
      ->condition('identifier', $identifier)
      ->condition('timestamp', REQUEST_TIME - $window, '>')
      ->countQuery()
      ->execute()
      ->fetchField();

```

It only compares the threshold login count against a unique user ID, `$identifier`.

You'd have to do some sort of modification to the `flood` core service to make some sort of per-role flood limit.

---
Tags: 8, users
---


# Question
Title: How do I trigger group membership was granted for a user - Group module
I try to use group module in d8.

**1. I created a new group type named `test`**

**2. I added 2 group as demo with admin is default `group_membership`.**

**3. in group 1 (name `okok`) I edited and added new user to group.**

**4. When I click the add member, the site redirect to another add form**:

* I enter the user as normal.
* then click save button.

**5. The result is User was added into that group.**

---

So, What I wonder is how to know an user:

* Was added to a group.
* Was removed from a group.

Because I want to call another service every time that action/event was executed. For example, I want to log in to the watchdog like:

* "User A has been added into group X"
* "User B has been remove from group Y"

Is there any way to trigger that action/event in code.

Thanks for all your helps.

# Answer
> 0 votes
as @Jaypan suggested to me, I used hook\_ENTITY\_TYPE\_insert() so my code is:

```
function hook_group_content_insert(GroupContentInterface $group_content) {
  if ($group_content->hasField('entity_id')
    && !$group_content->get('entity_id')->isEmpty()) {
    $users = $group_content->get('entity_id')->referencedEntities();
    $user = reset($users);
    if ($user instanceof UserInterface) {
      // Do your code here.
    }
  }
}

```

---
Tags: group
---


# Question
Title: How do I make a link to a flag edit page?
I'm using Drupal 8 with Flag 4.0-beta1.

On my flag, I have several fields. I want users to be able to edit these fields after making the flag.

How can I make a link to the flag edit page?

I found this comment on using VBO for Drupal 7, but on Drupal 8, VBO doesn't have the "modify entity" option for flaggings suggested in that post.

I tried various things in Views (making a view of flaggings; making a view of nodes with flaggings as a relationship), but I can't find a way to get an edit link.

EDIT: I got confused by the terminology and mixed up **flags** (the "type") and **flaggings** (the instance of the type) are different. I'm leaving this question as is, and I created a new question for flaggings.

# Answer
I'm not sure about any view field for an edit link, but you can link to the flag's edit screen, like most entities, in a number of ways.

Looking at the module's `flag.routing.yml` file, we see the edit route defined like:

```
entity.flag.edit_form:
  path: '/admin/structure/flags/manage/{flag}'
  defaults:
    _entity_form: flag.edit
    _title: 'Edit Flag'
  requirements:
    _entity_access: 'flag.update'

```

The flag argument here is for the flag's id.

You can build out the link to the flag manually, e.g.

```
<a href='/admin/structure/flags/manage/MY_FLAG_ID'>Edit MY FLAG</a>

```

Or if you're working with twig, e.g. rewriting a view's field, make sure you're also including the flag's id in the view then rewrite doing something like:

```
<a href='/admin/structure/flags/manage/{{ flag_id }}'>{{ "Edit"|t }}</a>

```

Or you can use PHP to build the url directly from the route. It's recommended to use one of the following methods if you're working in PHP.

To get just the url text or object in PHP, use Url::fromRoute():

```
use \Drupal\Core\Url;

$my_flag_url_object = Url::fromRoute('entity.flag.edit_form', ['flag' => MY_FLAG_ID]);
// $my_flag_url_string returns something like "/admin/structure/flags/manage/123"
$my_flag_url_string = $my_flag_url_object->toString();

```

To build the whole link in PHP, use Link::createFromRoute():

```
use \Drupal\core\Link;

$my_flag_edit_link = Link::createFromRoute('MY FLAG EDIT TEXT', 'entity.flag.edit_form', ['flag' => MY_FLAG_ID]);

```
> 3 votes

---
Tags: 8, flags
---


title: How can I change a field cardinality?

text:
# Question
Title: How can I change a field cardinality?
I have two content types: *Person* and *Office* with existing content. The *Person* content type has an entity reference field to *Office* nodes, which only allows a single reference. I need to change this to allow an unlimited number of *Office* nodes to be selected.

Drupal 8 prevents changing the cardinality of the field, and it gives the following error message.

> There is data for this field in the database. The field settings can no longer be changed.

At first, I thought I needed to write a migration, but they seem to be aimed at bringing data into a Drupal instance. Then, I read about writing update functions (also this documentation).

I discovered a *migrate-plus* plugin that adds a couple pages me to export the field storage settings, change the cardinality, and re-import the settings.
Given that I'm going from cardinality of 1 to unlimited, I could imagine this change wouldn't destroy data. And my empirical data suggests this is the case. I've now made this change via the *migrate-plus* screens as well as via configuration export and import and the data is still in the field.

Is this a safe operation, or should I write an update function?

# Answer
> 10 votes
> There is data for this field in the database. The field settings can no longer be changed.

That message is misleading, it will actually *not* limit the ability to increase the cardinality. The only limitation is that it won't allow you to set the cardinality to a value lower than the highest amount of items you currently have.

# Answer
> 1 votes
For those looking for an update hook solution, the following example in the entity\_test module in core works well. Note that you must do the retrieve, delete, insert method of moving data around if you have any existing data in there.

https://git.drupalcode.org/project/drupal/-/blob/8.8.x/core/modules/system/tests/modules/entity\_test/update/entity\_definition\_updates\_8001.inc#L13

# Answer
> 0 votes
The Field Config Cardinality module can help in resolving the issue.

> \[It\] Allows the cardinality of specific config\[uration\] fields to be overridden \[by the\] cardinality of \[the\] Storage field.

---
Tags: 8, entities
---


# Question
Title: How can I display filter guidelines/tips below field for text formats?
I want reverse of these https://www.drupal.org/project/drupal/issues/2098071 https://www.drupal.org/project/drupal/issues/1340860

It can be achieved by hacking core i,e removing line

> $element\['format'\]\['guidelines'\]\[$format\_id\]\['#access'\] = FALSE;

in Element.php but I want proper drupal solution.

# Answer
> 2 votes
```
namespace Drupal\my_module;

use Drupal\editor\Entity\Editor;
use Drupal\editor\Element;

/**
 * Defines a service for Text Editor's render elements.
 */
class CustomElement extends Element {

  /**
   * Additional #pre_render callback for 'text_format' elements.
   */
  public function preRenderTextFormat(array $element) {

    $element = parent::preRenderTextFormat($element);

    $format_ids = array_keys($element['format']['format']['#options']);

    // Early-return if no text editor is associated with any of the text formats.
    $editors = Editor::loadMultiple($format_ids);

    // Hide the text format's filters' guidelines of those text formats that have
    // a text editor associated: they're rather useless when using a text editor.
    foreach ($editors as $format_id => $editor) {
      // Display filter guidelines.
      $element['format']['guidelines'][$format_id]['#access'] = TRUE;
    }

    return $element;

```

---

```
function my_module_core_element_info_alter(&$types) {

  $types['text_format']['#pre_render'][] = 'my_module.element.editor:preRenderTextFormat';
}

function my_module_module_implements_alter(&$implementations, $hook) {
  switch ($hook) {
    case 'element_info_alter':
      $group = $implementations['my_module'];
      unset($implementations['my_module']);
      $implementations['my_module'] = $group;
      break;
  }
}

```

Above piece of code worked me and defined this service.

---
Tags: 8
---


# Question
Title: How to rename a view returned by REST API
Very new to Drupal (running 8.5.6) and inherited some code I need to tweak. We invoke the API request like so (which may wrap the Drupal API..I am not sure)

https://api.mysite.org/backend/api/constants/en?\_format=json

I get a fairly large JSON object returned. There is a view I created called myview that is returned in the json with the name of view\_35. I have two other test instances where I created the same view by name referencing the same fields. But in one instance the name is returned in the JSON as view\_38 and in the other view its view\_31. I noticed that I could alias the fields. Is there a feature like that for views? In other words, I want to name the view so it can be consistently referenced in the code that consumes the JSON. The client side of the app that invokes the api is Angular, if that makes any difference.

# Answer
> 0 votes
The answer was already in the question. Turns out the option to add aliases is exactly the same for other fields...it's just a little counter intuitive. Go to Administration--\>Structures--\>Views--\> Constants view --\> Edit --\> then select "Constants" from the "Displays" Then select "Settings" next to Show... All the aliases can be entered there. Then save the changes. Now you can reference the view by alias rather than the view\_\[ID\] reference.

---
Tags: views
---


# Question
Title: How can I install a specific core version?
Composer always installs the latest version of Drupal core, but I want Drupal 8.6, not Drupal 8.7.

How can I install a specific core version?

# Answer
Now Drupal recommended project supports version as command line option. If you want to install version 8.8.5 via Composer then command will like as shown below.

`composer create-project drupal/recommended-project:8.8.5 <INSTALL_DIR>`
> 8 votes

# Answer
Create drupal-project with --no-install option:

```
composer create-project drupal-composer/drupal-project:8.x-dev my_site_name_dir --no-interaction --no-install

```

Change directories to my\_site\_name\_dir and edit the version contraints in the composer.json file:

```
"require": {
    ...
    "drupal/core": "8.6.*",
    ...
},

```

Also for

```
"require-dev": {
    "webflo/drupal-core-require-dev": "8.6.*"
},

```

> webflo/drupal-core-require-dev provides the require-dev dependencies of drupal/core as a standalone package. It follows the same release cycle and versioning scheme as Drupal core. You should use the same version constraint for it as you use for Drupal core.

Run `composer install`

---

### Warning

Since answering the question the de-facto standard for installing Drupal via composer has changed from drupal-composer/drupal-project to drupal/recommended-project. Now you can append the version directly to the package. See Vinod Singh's answer.
> 6 votes

# Answer
My mistake was not setting the correct webflo/drupal-core-require-dev version along it the drupal/core version, so composer.json should look like this:

```
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "php": ">=5.6",
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6.5",
        "drupal-composer/drupal-scaffold": "^2.5",
        "drupal/console": "^1.0.2",
        "drupal/core": "8.6.17",
        "drush/drush": "^9.0.0",
        "vlucas/phpdotenv": "^2.4",
        "webflo/drupal-finder": "^1.0.0",
        "webmozart/path-util": "^2.3",
        "zaporylie/composer-drupal-optimizations": "^1.0"
    },
    "require-dev": {
        "webflo/drupal-core-require-dev": "8.6.17"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": ["load.environment.php"]
    },
    "scripts": {
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "composer-exit-on-patch-failure": true,
        "patchLevel": {
            "drupal/core": "-p2"
        },
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/Commands/{$name}": ["type:drupal-drush"]
        },
        "drupal-scaffold": {
            "initial": {
                ".editorconfig": "../.editorconfig",
                ".gitattributes": "../.gitattributes"
            }
        }
    }
}

```
> 0 votes

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


# Question
Title: How to use ajax callback on auto complete field inside a block settings form?
```
public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $selected = 'value of a field';
    $form['node'] = [
      '#type' => 'entity_autocomplete',
      '#title' => $this->t('My content type'),
      '#target_type' => 'node',
      '#selection_settings' => [
        'target_bundles' => ['bundle'],
      ],
      '#ajax' => [
        'callback' => [$this, 'my_ajax_callback'],
        'wrapper' => 'my-specializations',
      ],
    ];

    $form['first_select'] = [
      '#type' => 'select',
      '#options' => [0 => 'x', 1 => 'y'],
      '#title' => 'doctor',
      '#ajax' => [
        'callback' => [$this, 'my_ajax_callback'],
        'wrapper' => 'my-specializations',
      ],
    ];

    $form['specializations'] = [
      '#type' => 'select',
      '#title' => $this->t('Specializations'),
      '#options' => $this->specialization($selected),
      '#prefix' => '<div id="my-specializations">',
      '#suffix' => '</div>',
    ];

    return $form;
  }

 private function specialization($selected) {
    if (!empty($selected)) {
      return ['1' => 'a', '2' => 'b'];
    }
    else {
      return [];
    }
  }

  public function my_ajax_callback(array &$form, FormStateInterface $form_state) {
    return $form['specializations'];
  }

```

The ajax call back function is not working on auto complete field. How can I make it working on the auto complete field?

And on the `first-select` it is working but I am getting an error:

`TypeError: Argument 1 passed to Drupal\Core\Render\MainContent\AjaxRenderer::renderResponse() must be of the type array, null given, called in /var/www/web/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php on line 89 in Drupal\Core\Render\MainContent\AjaxRenderer->renderResponse() (line 53 of /var/www/web/core/lib/Drupal/Core/Render/MainContent/AjaxRenderer.php)`

Can you someone tells me, what I am doing wrong?

# Answer
To answer the title's question

```
  '#ajax' => [
    'callback' => '::my_ajax_callback',
    'wrapper' => 'my-specializations',
    'event' => 'change', // run ajax on change
    'keypress' => TRUE, // if set to TRUE, then the element's #ajax['event'] will be triggered if the ENTER key is pressed while the element has focus.
  ],

```
> 0 votes

---
Tags: 8, forms, blocks, ajax
---


# Question
Title: Simple Sitemap using default instead of website URL
https://www.drupal.org/project/simple\_sitemap/

I am using above module

**abc.com/admin/config/search/simplesitemap**

When I am generating sitemap via UI or `drush simple_sitemap-generate` command.

It is using

```
 <url>
  <loc>http://default/ja</loc>
  <xhtml:link rel="alternate" hreflang="en" href="http://default/ja"/>
  <xhtml:link rel="alternate" hreflang="ja" href="http://default/ja"/>
  <changefreq>daily</changefreq>
  <priority>1.0</priority>
 </url>

```

On my Website I am using only English language. Other languages are configured. But not using that.

How to remove those?

# Answer
> 4 votes
This happenes when generating the sitemap via CLI cron without `--uri` parameter. Either pass the Domain into the CLI

```
drush --uri=https://www.example.com simple-sitemap:generate

```

or use the web interface to generate the sitemap.

---
Tags: 8, xml-sitemap
---


# Question
Title: Redirect with POST and parameters in a controller
I want to redirect to a url (Sermepa/Redsys) with POST and some form parameters in a Controller. The process is I submit a form that collect some data, and when the user submit this form, it redirect to my controller. In this controller I prepare the post data and then I want to redirect to bank gateway with POST.

```
<?php

namespace Drupal\mymodule_sermepa_redsys\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\mymodule_sermepa_redsys\RedsysAPI;
use Drupal\node\NodeInterface;

/**
 * Class DoPaymentController.
 */
class DoPaymentController extends ControllerBase {

  public function doPayment(NodeInterface $node = null) {

    if ($node!==null) {

      $redsys = new RedsysAPI();
      $config = \Drupal::config('sermepa_redsys.settings');

      // Completamos los datos para la petición
      $redsys->setParameter("DS_MERCHANT_AMOUNT", $config->get('ammount'));
      $redsys->setParameter("DS_MERCHANT_ORDER", $node->id());
      $redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $config->get('merchant_code'));
      $redsys->setParameter("DS_MERCHANT_CURRENCY", $config->get('currency'));
      $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE", $config->get('transaction_type'));
      $redsys->setParameter("DS_MERCHANT_TERMINAL", $config->get('terminal'));
      $redsys->setParameter("DS_MERCHANT_MERCHANTURL", $config->get('url'));
      $redsys->setParameter("DS_MERCHANT_URLOK", $config->get('merchant_url_ok'));
      $redsys->setParameter("DS_MERCHANT_URLKO", $config->get('merchant_url_ko'));

      $version= $config->get('version');
      $kc = $config->get('merchant_password');

      $params = $redsys->createMerchantParameters();
      $signature = $redsys->createMerchantSignature($kc);

      $post_data['Ds_SignatureVersion'] = $version;
      $post_data['Ds_MerchantParameters'] = $params;
      $post_data['Ds_Signature'] = $signature;

      $client = \Drupal::httpClient();
      $response = $client->request('POST', $config->get('url_webservice'), ['form_params' => $post_data]);
      return $response;

    }
    else {
      return [
        '#markup' => t('Error. No nid'),
      ];
    }
  }
}

```

What I expected is after sumbit the form, controller was called, and then the user was redirected to bank payment page. The form is a "create node" of a custom content type. In my .module file I have added a custom submit:

```
function mymodule_form_node_mycustomtype_form_alter(&$form, FormStateInterface &$form_state) {
...
$form['actions']['submit']['#submit'][]  = '_mycustom_form_submit';
}

function _mycustom_form_submit(array &$form, FormStateInterface $form_state) {
    $url = Url::fromRoute('mymodule_sermepa_redsys.payment_controller_doPayment');
    $url->setRouteParameters(array('node' => $form_state->getValue('nid')));
    $form_state->setRedirectUrl($url);
}

```

My routing file:

```
mymodule_sermepa_redsys.payment_controller_doPayment:
  path: '/doPayment/{node}'
  defaults:
    _controller: '\Drupal\mymodule_sermepa_redsys\Controller\DoPaymentController::doPayment'
    _title: 'Do Payment'
  requirements:
    _permission: 'access content'

```

Note: The class RedsysAPI is a helper class to prepare the data to POST, but It's irrelevant in the context of this question.

# Answer
You can't redirect with Post properties. You can only do a request, which you've done. The `$response` you've created in the controller will contain the results of your HTTP request to the remote service. You'll have to retrieve the the relevant data from that object, and do something with it. You are currently returning that from your function. `$response` is a Psr\Http\Message\ResponseInterface object. If you just return this, your controller will not know what to do with it.
> 1 votes

---
Tags: 8, redirection
---


# Question
Title: Error: "module does not exist" after I removed a module from the file system without disabling and uninstalling it
I removed a module from the file system without disabling and uninstalling it. And now I have error:

**Drupal\Core\Extension\Exception\UnknownExtensionException: The module drupalweather does not exist. in Drupal\Core\Extension\ExtensionList-\>getPathname() (line 522 of core\lib\Drupal\Core\Extension\ExtensionList.php).**

How to solve this error? I use **windows operating system** and local server **open server**.

# Answer
@Leigh comment:

> It's fairly straight forward - put the files back and then uninstall it before deleting again

## Solved the error
> 2 votes

---
Tags: 8, database, installation
---


# Question
Title: How to hide "Log in or register to post comments" when I've already disabled displaying comments?
I already disabled comments. How can I remove the "Log in or register to post comments" text at the bottom of articles or other content types?

# Answer
> 2 votes
You also have to disable the "links" section or you'll see this message.

Go to the `Administration > Structure > Content types > Article` page. Drag comments and links to the disabled section. Repeat for any other content types where you want to hide this message.

---
Tags: comments
---