title: Extending block configuration schema

text:
# Question
Title: Extending block configuration schema
I'm using the Configuration Inspector module module, and I'm finding a missing schema error.

The configuration is for block.block.pminbox.settings.thread\_count

The block itself is a plugin, created in my module. I've tried:

* Adding the settings to the block annonation
* Creating block.block.pminbox and adding settings as a mapping with thread\_count as a property of that mapping
* Creating block.block.pminbox.settings and adding thread\_count in there
* Adding the config to mymodule.schema.yml

Here is where I am at as of now. Submit handler for class extending BlockBase:

```
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['thread_count'] = (int) $form_state->getValue('thread_count');
  }

```

mymodule.schema.yml:

```
block.settings.pminbox:
  type: block_settings
  label: 'Private message inbox block settings'
  mapping:
    thread_count:
      type: integer
      label: 'Thread count'

```

The rest of the schema in this file is being picked up, however, I'm still getting a 'schema undefined' error from the configuration inspector for this block.

# Answer
> 1 votes
It would really help to knowing how your data is saved (e.g. providing a snippet from your `BlockBase::blockSubmit()` implementation that shows this value), or what exactly you tried adding to your yml files.

However, in theory a working example that assumes, you are saving the value like this:

**PmInboxBlock.php**

```
/**
 * @Block(
 *   id = "pminbox",
 *   admin_label = @Translation("PmInbox"),
 *   category = @Translation("PmInbox"),
 * )
 */
class PmInboxBlock extends BlockBase {

  // ... Your Form definition here ...

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['thread_count'] = $form_state->getValue('thread_count');
  }

}

```

Then you provide the schema definition in a schema file named after your module:

**mymodule.schema.yml**

```
block.settings.pminbox:
  type: block_settings
  label: 'PmInbox Block'
  mapping:
    thread_count:
      type: string
      label: 'Thread count'

```

# Answer
> 0 votes
I was on the right path, thanks to Mario's answer. The problem was I was looking at the wrong ID for the block. When looking at the config file for the block (block.block.pminbox), there are two IDs. The first is the block ID (pm\_inbox), and the second is in the settings array (settings.id), which is the plugin ID of the block. The value for settings.id (the plugin ID for the block) is the value to be used here (pm\_inbox\_block):

```
block.settings.pm_inbox_block:
  type: block_settings
  label: 'Settings for the private message inbox block'
  mapping:
    thread_count:
      type: integer
      label: 'The number of threads shown when block is loaded'

```

---
Tags: 8, configuration
---


# Question
Title: Is Drupal doing something to JQuery delegate or click() that causes the binding to fail?
I am trying to implement a simple mobile menu, but using Nice Menus as my base. So to get things the way the snippet's CSS is set up, I'm using JQuery to dynamically add a `<button>` element that can be clicked.

Problem is, nothing happens when I click the button. I've checked that my code works fine when the user clicks a `<p>` element. And I have also confirmed with code that the element to which I'm attaching the click function exists. (But it wasn't working with a `$(document)` scope either.)

Doesn't work:

```
$('.nice-menu-main-menu').before('<button class="nav-button">Toggle Navigation</button>');

if ( $('.nav-button').length > 0 ) {
    console.log("nav-button element exists"); // console shows this message
    $('.nav-button').click( function() {
        console.log("menu button clicked"); // never see this message
    });
}

```

Doesn't work:

```
$( document ).delegate('.nav-button', 'click', function() {
    console.log("button clicked"); // never see this message
});

```

Does work:

```
$( document ).delegate('p', 'click', function() {
    console.log("button clicked"); // console shows this, no problem
});

```

What magic am I missing? I figure the issue *must* be with the dynamic aspect of the element, but everything I'm finding in the documentation of JQuery and similar code online suggests this *should* be working.

# Answer
`Drupal.behaviors` ensures that the JavaScript code is executed again whenever there are any changes in DOM Elements.

Most JavaScript works by manipulating elements in the HTML DOM. As Such, JavaScript code generally does some extra work to ensure that DOM is fully loaded and elements we want to interact with are available.

The most common way to do this in jQuery is using the $(document).ready() syntax. Placing our code inside this statement will ensure that it is not executed until the DOM has finished loading.

Drupal takes this a step further by using Drupal.behaviors. Along with ensuring that code is not executed until the dom has finished loading, It also ensures that the code is executed again whenever there are any changes in DOM Elements.

So, the Drupal way of handling the click event of a newly added element with a class of `nav-button` looks like this:

```
Drupal.behaviors.exampleBehavior = {
  attach: function (context, settings) {
    $('.nav-button',context).click(function(){
      console.log("button clicked");
    });
  }
}

```
> 1 votes

---
Tags: javascript, navigation
---


# Question
Title: Fixing configuration inspector missing schema errors
I'm using the configuration inspector to fix schema issues before I put a module live as a full release.

I'm finding the following error, but I'm unclear on how to fix it.

The module provides a new entity type, private\_message. In config/install, I have the file:

*core.entity\_form\_display.private\_message.private\_message.default.yml*

This file has the following contents (trimmed):

```
content:
  message:
    type: string_textarea
    label: hidden
    settings:
      placeholder: Message
      rows: 5
    region: content
    third_party_settings: {  }
    weight: null

```

The configuration inspector for core.entity\_form\_display.private\_message.private\_message.default is telling me that the schema for content.message.label has a missing schema:

> content.message.label Undefined undefined hidden missing schema

In the raw data for the inspection, I see:

```
'core.entity_form_display.private_message.private_message.default:content.message.label' => 'missing schema',

```

Does anyone know how I can fix this error?

# Answer
Yes, remove that line. Form displays have no label control, only view displays do. Maybe this was copy & pasted somehow by hand when creating that config.
> 2 votes

---
Tags: 8, configuration
---


title: The vendor class doesn't autoload

text:
# Question
Title: The vendor class doesn't autoload
I am trying to port the Infusionsoft module to Drupal 8 and I need to load the infusionsoft/php-sdk library. I have been racking my brain all day trying to figure this out, but I cannot get the class to autoload. I do not know if this is because it is a custom module and not hosted on drupal.org yet or what.

I have added the requirement to a composer.json file in the module:

```
{
  "require": {
    "infusionsoft/php-sdk": "dev-master",
  },
}

```

And told the root composer.json file to include the module's composer.json file:

```
{
  "extra": {
    "merge-plugin": {
      "include": [
        "core/composer.json",
        "modules/infusionsoft/composer.json"
      ],
      "recurse": true,
      "replace": false,
      "merge-extra": false
    },
  },
}

```

Ran

```
composer update

```

and also tried

```
composer install

```

Both give me the vendor files. I have uploaded those files to the remote server's vendor directory, yet they are still not being loaded.

I have read several other posts on here and many other sites, but none of the answers are up-to-date with Drupal 8.5.2. And the composer manager module method is depreciated.

I don't know if this is an issue with their sdk's structure or if I need to upload a another/different file(s) to the server, but instantiating the class breaks.

```
use Infusionsoft\Infusionsoft;
$infusionsoft = new Infusionsoft([
  'clientId'     => $id,
  'clientSecret' => $secret,
  'redirectUri'  => $redirect,
]);

```

Any help is greatly appreciated! Thanks!

# Answer
> 1 votes
> Both give me the vendor files. I have uploaded those files to the remote server's vendor directory, yet they are still not being loaded.

What files did you upload exactly? It's not enough to upload just the new files from your package, installing packages with composer also updates its own autoloading files to make sure it knows where to load that and you probably forgot to upload those, that's the only explanation I have at least.

Try uploading all the files in vendor/composer as well or to be sure, all the files in vendor.

---
Tags: 8, composer
---


title: Drush can not find settings.php

text:
# Question
Title: Drush can not find settings.php
I use two shared hosts at present. One, webhostinghub.com, already has drush installed and it works. The other, 1and1.com, did not come with drush pre-installed so I installed composer and then drush with composer as recommended on drupal.org.

This puts a symlink to drush in `~/.composer/vendor/bin` which points to `../drush/drush/drush`. In the `~/.composer/vendor/drush/drush` folder that this points to is a file drush which requires drush.php which is in the same folder.

So as recommended, I set up an alias for drush that runs this with php-cli. Because 1and1.com sets up php and php-cli to default to php4, I also set up an alias for both php and php-cli to the php7.1 versions.

When I go to the root folder of one of my drupal sites and type in simply drush, I get the non Drupal specific commands listed and then the message:

> NOTE: Drupal root not found. Pass --root or a @siteAlias in order to see Drupal-specific commands.

I did see some posts saying that for this to work you have to just have one `settings.php` in the `sites/default` folder of the drupal tree. I have searched and have not found any stray settings.php files - just the one in the `sites/default` folder.

Does any one have an idea about why this is not working? Let me know if you need more information about my setup or the process that I went through.

# Answer
I was right in my comment earlier. The issue was compatibility between drush 9 and drupal 7. Once I downgraded to drush 8.1.10 it worked fine. Note there is also an oddity with 1and1 specifically where in SSH they default to php4.4 which is too old! So I also had to set up an alias for php and php-cli to refer to a more modern php. Also I had to ensure drush used it by adding 'export DRUSH\_PHP=' followed by the full path and filename for the more recent version of php.

If anyone reading this does not know how to downgrade drush with composer you have to remove and re add it with the following commands:

composer global remove drush/drush

composer global require drush/drush:8.1.10

Replace the 8.1.10 with the version that you want.

Also, anyone new to composer might get fooled as I did by the prompt 'Discard changes? (y/n/v/d/s/?). Yes actually means 'discard and apply changes'! I found details of this in the following post: https://stackoverflow.com/questions/25828102/composer-discard-changes-what-do-the-y-n-v-d-s-do

I hope this helps anyone else new like me stumbling across this issue!

Once again thanks for the comments - the one question from @Christia about drupal version triggered me to look in the right direction!

Rory
> 2 votes

---
Tags: drush
---


# Question
Title: Get variable from controller in twig using template
I have a php variable in my controller and i want to use it in twig. So i do this :

Controller :

```
$firstLetter = '2017'; //dynamic variable but for the test it's a constant

$build ['list'] = array(
      '#theme' => 'liste-adh2',
      '#content'=>$result,
      '#filters'=>$ListApport,
      '#filters2' =>$Listline,
      '#test' => $firstLetter,  //sending to my template
   );

return $build;

```

Template :

```
function adh_apport_theme($existing, $type, $theme, $path)
{

    return [
        'liste-adh2' => [
            'variables' => ['content' => NULL, 'filters' => NULL,
                            'filters2' => NULL,], ['test' => NULL,],
                        ],
            ];
}

```

Twig :

```
{{ test.firstLetter }}

```

i got nothing in twig and i don't know why.

Thanks for helping.

# Answer
I’m not sure why you’re expecting `test` to be an object, you declared it as a string.

Assuming the value of “2017” from your example is what you’re trying to get the variable is just:

```
{{ test }}

```
> 0 votes

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


# Question
Title: How can I check and set user status in Rules Action?
I am using a REST API that creates a user without password. And doing so, the user is successfully created but the status is set to `blocked` \- meaning it is not actually logged in.

So im planning to create a custom Rules Action that will set the status into `Active`.

# Answer
Okay, there is actually a Rules Action that does this functionalities. I was thinking of a custom Rules Action but glad Drupal 8 Rules supports my use case.
> 0 votes

---
Tags: 8, rules
---


# Question
Title: Why is this property of the Cron service initialized in this manner?
I wish someone could help me understand this code statement found on the core cRON service (`\Drupal\Core\Cron`), especially in the constructor method for this class.

```
public function __construct(ModuleHandlerInterface $module_handler, LockBackendInterface $lock, QueueFactory $queue_factory, StateInterface $state, AccountSwitcherInterface $account_switcher, LoggerInterface $logger, QueueWorkerManagerInterface $queue_manager, TimeInterface $time = NULL) {
  // Omissis
  $this->time = $time ?: \Drupal::service('datetime.time');
}

```

What does this line do? Why isn't `$this->time = $time;` instead used?

The service is already injected using arguments.

```
class: Drupal\Core\Cron
arguments:
  - '@module_handler'
  - '@lock'
  - '@queue'
  - '@state'
  - '@account_switcher'
  - '@logger.channel.cron'
  - '@plugin.manager.queue_worker'
  - '@datetime.time'
lazy: true

```

# Answer
It's backward compatibility.

Strictly speaking, constructors are excluded from BC, but the reality is that it is fairly common that one has to override them to inject additional dependencies.

The fallback to the global service means that if such a child class calls the constructor without that argument, it is not going to fatal.

That's especially common for base classes like ContentEntityForm, ControllerBase and other base classes that are specifically designed to be subclassed.

It can also be helpful during updating from an old version, because when running update.php in the UI, the class might be instantiated before Drupal has a chance to rebuild the container and provide the new arguments.
> 3 votes

---
Tags: 8, datetime, cron
---


# Question
Title: How to add existing product variations to a new product?
I have products with the same variation. From product edit form I can only add new variation. In variations field form setting i haven't "Allow users to add existing products."

how can i have this option or How can add existing variations?

# Answer
> 1 votes
The option you're looking for is not present on purpose (and the widget itself is different despite how it worked in Drupal 7). Every product has its own variations that cannot be shared, so there's no way to reference the same variation from multiple products.

If you need to sell the same thing from multiple contexts, what you probably need is some other entity that references the same product, not a standalone variation. Products:variations have a very clear parent:child relationship ... they're "variations" of the main "product".

# Answer
> 0 votes
I'm not as familiar with D8 commerce but should be the same. If you edit the product field on your product display content type you can tick "Allow users to add existing products."

That will allow the option to add existing variants

---
Tags: 8, commerce
---


# Question
Title: Use taxonomy path for a node's path alias
Is it possible to use a token to reference the alias of a taxonomy term in the pattern of an automatic alias for a node type where that term has been selected, in Drupal 8? (Let's assume a single taxonomy term is selected.)

For example: If one has a taxonomy of *Names* where the values are *James*, *Margaret*, *Daniel* and each name has a path assigned to it (`/news/jim`, `/news/peggy`, `/news/dan`) is it possible to construct an automatic path for "News" node types where the pattern is something like `[taxonomy:Names:path]/[node:title]` so that if one selects "*Margaret*" from the *Names* list and gives the node a title of "*Summer Vacation 2017,*" it will result in the automatic node path of `/news/peggy/summer-vacation-2017`?

All the references to path aliases based on taxonomy that I have found use the entity value of the term, which I don't want. I don't want `/news/margaret/summer-vacation-2017` as the result of the above example.

# Answer
> 6 votes
Using pathauto, it should be quiet easy with a pattern like :

Normal way :

```
news/[node:{NAME_OF_TAXONOMY_FIELD}:entity:name]/[node:title]

```

With hierarchy :

```
news/[node:{NAME_OF_TAXONOMY_FIELD}:entity:parents:join-path]/[node:{NAME_OF_TAXONOMY_FIELD}:entity:name]/[node:title]

```

In your case, this should work

```
[node:{NAME_OF_TAXONOMY_FIELD}:entity:url]/[node:title]

```

# Answer
> 2 votes
You could implement hook\_pathauto\_alias\_alter:

```
/**
 * Implements hook_pathauto_alias_alter().
 */
 function MYMODULE_pathauto_alias_alter(&$alias, array &$context) {

  if ($context['module'] != 'node') {
    return;
  }

  $node = $context['data']['node'];

  // here you can write your logic to get the taxonomy term url alias
  // something like:
  //read out the taxonomy term field of your node
  // get the term $term
  // get the URL Alias of it
  $options =
    [
      'absolute' => false,
    ];
    $termUrl = \Drupal\Core\Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()], $options);

    if ($termUrl && strpos($termUrl,'/taxonomy/term/' === false)) {
      $aliasPath = str_replace('/' . $languageId . '/', '/',$termUrl->toString());
    }
    $alias = $aliasPath . $alias;

  }

```

---
Tags: 8, taxonomy-terms, path-aliases
---


title: redirect to custom page

text:
# Question
Title: redirect to custom page
In my custom module, I created a custom link using

```
function MYMODULE_menu() {
$items['addcontent'] = array(
    'title'
    => 'Confirmation page',
    'page callback'
    => 'add_content_confirmation',
    'access callback' => TRUE,
);
return $items;
}
function add_content_confirmation() {
return 'Thank you';
}

```

When I check **mydrupal/addcontent**, this link works fine

In my **template.php**, I added

```
function MYTHEME_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'my_form_id'){
    $form['actions']['submit']['#submit'][] = 'my_custom_submit';
}
function my_custom_submit()
{
  $form_state['redirect'] = 'addcontent';
}

```

wich redirects me to my home page.

if I write

```
$form_state['redirect'] = 'node/add/mycontent';

```

That works fine.

How can I fix it?

Thank you

# Answer
> 0 votes
This:

```
function my_custom_submit()

```

Should be this:

```
function my_custom_submit($form, &$form_state)

```

Right now you are setting redirect on a variable that doesn't exist.

---
Tags: 7, hooks, redirection
---


# Question
Title: Why do some webforms have their elements value in translation UI (/admin/config/regional/translate)?
I have enabled webform module on a Drupal 8 installation.

For some reason, there are default webform templates such as "Donation" and "Contact Us" which have their `elements` values translated in the translation UI at **/admin/config/regional/translate**. The problem is that some webforms templates have HTML markup in their `elements` value like the following:

```
    '#prefix': '<div class="container-inline">'
    '#suffix': '</div>'

```

This will prevent saving any value, drupal telling the user that there are translations with invalid HTML tags:

> The submitted string contains disallowed HTML: *information: '#title': 'Your Information' '#type': fieldset first\_name: '#title': 'First Name' '#type': textfield '#required': true last\_name*
>
> etc...

Regarding this issue, I have a few questions:

1. what actions trigger the `elements` value availability in this interface? On install, on config save...?
2. do the **webform** module really uses this interface to translate the content of the forms?
3. and if yes, am I missing a module or something to make it work?
4. and if not, should this be considered as a bug? The closest issue I have found is this one: https://www.drupal.org/project/webform/issues/2913548

It looks like this is this template: https://cgit.drupalcode.org/webform/tree/modules/webform\_templates/config/install/webform.webform.template\_job\_application.yml?id=a988217057ed5ba842a3722de01f2d07df59e5e1

# Answer
Apparently, this was a side effect of the "translatability" of the elements value. A patch has been created by jrockowitz on the drupal issue tracker which will prevent having those values editable in the translation UI: https://www.drupal.org/project/webform/issues/2965060#comment-12587556
> 0 votes

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


# Question
Title: Using background images formatter for taxonomy in views
I have an image field per taxonomy vocabulary that I want to set as background to each views-row. I have the view filtered by taxonomy term, and I have set the taxonomy\_image field as background.

However, I don't know which CSS selector would be appropriate. The tokens available are c.date, c.page, c.user, random, site info, and users.

# Answer
> 0 votes
If you have not disabled **Add default classes** under **Style Settings** of image field then you can use views\_field\_FIELD\_MACHINE\_NAME class to play with css.

For example If you have a field with machine name **field\_book\_category\_icon** then after adding this field to your view you can get a class **views-field-field-book-category-icon** on front end when ever you render that view on your page.

---
Tags: views, media
---


# Question
Title: Exception in worker callback prevents queue item from being removed
I have created a Drupal 7 module that utilizes hook\_cron() and hook\_cron\_queue\_info() to process some data, as well as use the module Ultimate Cron to handle scheduling when each runs.

hook\_cron() is run every 15 minutes and it's job is to determine how much data needs to be processed and split it up into batches, creating a queue for each batch. As an example, say 1000 records, split into batches of 25, so you get 40 queues of 25 records each.

The queue is then processed every minute, so every minute it will process one queue item of 25 records.

The problem I am running into is that occasionally during the worker callback for a queue, when processing one or more of the 25 records, a record may result in an exception being thrown.

The exception is possible and expected, so I am handling the exception in a simple try/catch, so the queue is able to continue on and processes all 25 records. However it seems that if any of the 25 had an exception, the queue item does not get removed at the end like it does when there no problems. Ultimate Cron shows the queue as having started, but never finished and is still running (though really it is not, it got through all 25), and this prevents any further queue items from running.

This is not the behavior I would like, I want the queue item to be removed or "finished" regardless if an exception happened, because I have handled the exception(s).

I am unsure of what is deciding the queue should not be removed, is it drupal's queue api? Ultimate cron? Is there a way I can have it remove the queue manually at the end of the batch if there happened to be an exception?

Basic code:

```
/**
 * Implements hook_cron().
 */
function MODULENAME_cron() {
  MODULENAME_queue();
}

/**
 * Implements hook_cron_queue_info().
 */
function MODULENAME_cron_queue_info() {
  $queues['MODULENAME_queue'] = array(
    'worker callback' => 'MODULENAME_process_batch',
  );

  return $queues;
}

/**
 * Queue up batches.
 */
function MODULENAME_queue() {
  // Get the queue.
  $queue = DrupalQueue::get("MODULENAME_queue");

  // Only run if there are no items in the queue.
  if (!$queue->numberOfItems()) {
    // Get the full list of records.
    $records = MODULENAME_get_records();

    // Split the list of records into batches to process.
    $pager = 25;
    $batches = array_chunk($records, $pager);

    // Queue the batches.
    foreach ($batches as $batch) {
      $queue->createItem($batch);
    }
  }
}

/**
 * Process a batch.
 */
function MODULENAME_process_batch($data, &$context = NULL) {
  // Process a batch of 25 records.
  foreach ($data as $record) {
    MODULENAME_process_record($record);
  }
}

/**
 * Process a single record.
 */
function MODULENAME_process_record($record) {
  // Processing code here, this is where an exception can happen.
}

```

# Answer
I have the same issue. For me putting everyhing inside the worker callback function in a `try` block solved the issue.
> 1 votes

---
Tags: cron, queue
---


# Question
Title: Include OR Group With Exposed Filters in View
I have a view where I need to include an OR group for example (a + b) OR (C) as well as using Exposed Filters that will apply to both groups, giving something like (Ex1 + Ex2 + ((a + b) or c))). Is there any way I can make the exposed filters apply to both groups at the same time?

I thought it may be possible using nested or sub groups but I know it is not possible to create nested or sub groups in filters through the UI.

# Answer
I think you can achieve it by adding new filter group from views UI.

**Edit:** If your case is more special then you can achieve it using `hook_views_query_alter`.

```
if (!$new_feed) {
  $query->where[0]['conditions'][1]['field'] = 'node.nid';
  $query->where[0]['conditions'][1]['value'] = array();
  $query->where[0]['conditions'][1]['operator'] = 'IN (' 3, 4 5')';
}
else {
  $query->where[2]['conditions'][1]['field'] = 'node.nid';
  $query->where[2]['conditions'][1]['value'] = array();
  $query->where[2]['conditions'][1]['operator'] = 'IN (1, 2, 3);
}

```

You can unset where condition as per your use case.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Uploaded images classified as files rather than under the media tab
In Drupal 8 if you go to admin/content there is a tab for Files and a tab for media.

I believe it is the media entity browser what distinguishes what area an uploaded file will be placed, but I could be wrong on this.

My question is, as well as that, is there an easy way to move files which have been uploaded and placed under the files tab by accident into the media tab without having to re-upload them all?

Thanks for any help on this

# Answer
**Files** tab is a view you can add filter by editing this view and based on your filter they can be removed from files tab. Then you can again work on filter of Media tab so that they can display under media tab.

It is up to you what filter criteria you have to move them from one tab to another tab.
> 0 votes

---
Tags: media
---


# Question
Title: Solr server URL needs to include a scheme?
Recently I am facing a issue with all my D7 websites which I have migrated to a new server. The case is as follows

-\> All Sites have been setup with Apache Solr and working fine on my old server

> After I migrated the sites to new server I am getting this error

URL Format Used :

> http://USERNAME:PASSWORD@XXX.XXX.XXX.XXX:8983/solr/CORE\_NAME

Note: I migrated to new server with latest version of LAMP. Also I use remote Solr server.

OLD Server : Ubuntu 12.04, PHP 5.3.10, Nginx 1.8.0, MySql 5.5.X

New Server : Ubuntu 16.04, PHP 7.0.28, Nginx 1.10.3, MySql 5.7.X

# Answer
The issue was with the '#' character in the password which was failing the parse\_url called in the module.
> 0 votes

---
Tags: 7, search
---


# Question
Title: Manually invoking Ajax Commands when an ajax callback is not an #ajax form callback
My original post caused some confusion, so I'm re-writing it for clarity.

In Drupal, if you have an #ajax callback in a form, you can do something like this:

```
function my_ajax_callback(array &$form, FormStateInterface $form_state)
{
  $response = new AjaxResponse();
  $response->addCommand(new AlertCommand(t('This is from an ajax callback'));
  return $response;
}

```

This in turn triggers Drupal.ajaxCommands.prototype.alert(), which is located in ajax.js.

Alternatively, I can create an ajax callback of my own, that has nothing to do with a form. example.routing.yml:

```
mymodule.ajax
  path: '/mymodule/ajax'
  defaults:
    _controller: 'Drupal\my_module\Controller::ajaxCallback'
  # (remainder not shown)

```

I can create an AjaxResponse in this callback:

```
class Controller extends ControllerBase
{
  public function ajaxCallback()
  {
    $response = new AjaxResponse();
    $response->addCommand(new AlertCommand(t('This is from an ajax callback'));
    return $response;
  }
}

```

In this case, debugging has shown me that the AjaxResponse returns my command to the browser, but Drupal.ajaxCommands.prototype.alert() is not triggered.

Further debugging has shown me that ajax commands are only triggered if the AjaxResponse comes from an #ajax callback in a form, not if it's from a non-form ajax callback.

So my question is, does anyone know how to invoke ajax commands when the commands are returned from non-form ajax callback?

# Answer
Like @Gaius I don't know exactly what @Jaypan wants to achieve. This example might help to make this clearer:

```
        var response = JSON.parse(content);
        // Create a Drupal.Ajax object without associating an element, a
        // progress indicator or a URL.
        var ajaxObject = Drupal.ajax({
          url: '',
          base: false,
          element: false,
          progress: false
        });
        // Then, simulate an AJAX response having arrived, and let the Ajax
        // system handle it.
        ajaxObject.success(response, 'success');

```

Normally you set an URL in `Drupal.ajax()` and then use `ajaxObject.execute()` to run the Ajax request. This example from big\_pipe.js only simulates the Ajax request and then runs the Ajax commands contained in content.
> 11 votes

# Answer
It might not be related and is also a rather old post, but for anybody like myself desperately searching for some hint on the Drupal 8 ajax api:

```
Drupal.ajax({url: '/some/url'}).execute().done(
    function(comands, statusString, ajaxObject){
        console.log("we're done ;-)");
})

```

This tutorial might also be helpfull: https://www.thirdandgrove.com/rendering-view-ajax-drupal-8
> 6 votes

# Answer
If your Ajax request is triggered by a link, just add the "use-ajax" CSS class to your link. And remove all the JS manually added for sending your Ajax request. It will be automatically handled by drupal.ajax .

The problem is on the front end side. Drupal return an Ajax response, but JS doesn't know it and just do nothing with it.
> 0 votes

---
Tags: 8, ajax
---


title: Select DISTINCT on a particular field

text:
# Question
Title: Select DISTINCT on a particular field
I want to return distinct values based on a particular column - 'company\_code'. How do I achieve this? My code is as below.

```
$query = \Drupal::database()->select('actuarial_bases', 'bases')
                    ->fields('bases', ['company_code','basis_id','mortality','commission','initial_expenses','recurring_expenses','date_saved','discount_rate'])
                    ->condition('approved_by',!"")
                    ->orderBy('date_saved', 'DESC')
                    ->distinct();

```

# Answer
Searching, I found ROW\_NUMBER() in MySQL.

I created a view to include 'row\_count' using the following query.

```
SELECT `company_code`, `basis_id`, `mortality`, `commission`, `initial_expenses`, `recurring_expenses`, `discount_rate`, `date_saved`,
  (
    SELECT COUNT(0) FROM `actuarial_bases` `b` WHERE
      (
        (`a`.`date_saved` <= `b`.`date_saved`) AND ( `a`.`company_code` = `b`.`company_code`)
      )
  ) AS `row_number`
  FROM `actuarial_bases` `a`

```

I then used the following code do programmatically execute the query.

```
$query = \Drupal::database()->select('bases_in_force', 'b')
  ->fields('b', ['company_code','basis_id','mortality','commission','initial_expenses','recurring_expenses','date_saved','discount_rate'])
  ->condition('row_number',1)
  ->orderBy('date_saved', 'DESC');
$results = $query->execute();

```
> 0 votes

---
Tags: 8, database
---


# Question
Title: How to check for view mode in twig template?
We have one field (field\_tabs) that is used on Basic and Article content type. On the Basic page content type, it has a custom view mode (view\_mode\_vertical) and on the Article content type it has a different custom view mode (view\_mode\_horizontal).

Basic Page (default view mode) Manage Display

* field\_tabs (view mode = view\_mode\_vertical)
* title
* body

Article (default view Mode) Manage Display

* field\_tabs (view mode = view\_mode\_horizontal)
* title
* body

In a field.html.twig, how can we detect the view mode?

Our two options we explored was either a node template or field template (we went with field). We would like to do this in a way that we only need add the logic for detecting the view\_mode in one place. In case we add a third or fourth view\_mode, we can simply add another elseif (or switch case) to the code.

Sample Twig code we were looking for:

```
{% if view_mode == 'view_mode_vertical' %}
  <div class="tabs__vertical">...</div>
{% else %}
  <div class="tabs__horizontal">...</div>
{% endif %}

```

# Answer
> 8 votes
> In a field.html.twig, how can we detect the view mode?

In a field template there is no top level variable for the view mode like in the node template. You can create one and then your twig code should work:

```
{% set view_mode = element['#view_mode'] %}

```

Another option is to add a template name suggestion, see Field template for display mode.

Both are valid options. There are many projects heavily depending on Twig logic while other projects prefer PHP in preprocess and template name suggestion hooks.

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


# Question
Title: How can I display the field in the tab that was active on save?
I'm using Drupal 8 paragraphs. I have a banner\_header paragraph that contains three fields,

field\_active\_callout\_tab (boolean)

field\_banner\_header\_single (entity reference revision: paragraph)

field\_banner\_header\_multi (entity reference revision: paragraph)

two of which are displayed in tabs like so:

Here is how the banner\_header paragraph shows up on the content type edit form:

When I save the content, I want the page to render with the paragraph from the tab that was active on save.

What I've done so far:

I added classes to the tabs which you can see in the image of the form display: .single-link and .multi-link. I was told that I also needed to create a boolean field to manage the display behavior, which I did with field\_active\_callout\_tab. The way that was suggested this to work is, the bool will change depending on which tab is selected, and then I can use the bool value to determine which field is to be displayed in the twig template. The default class for this boolean seems to be '.option'.

I created a custom js file to check the status of the tab:

```
(function($, Drupal) {

/* Add span to wysiwyg button classes for alignment
------------------------------------ */
Drupal.behaviors.calloutControl = {
      attach: function (context, settings) {
            $('.single-link').click(function () {
                  $('.option').prop('checked', true);
            });
            $('.multi-link').click(function () {
                  $('.option').prop('checked', false);
            });
      }
};

})(jQuery, Drupal);

```

And here is the banner\_header template:

```
<div class="callout-options">
     {% if content.option == true %}
          {{ content.field_banner_header_single }}
     {% else %}
          {{ content.field_banner_header_multi }}
     {% endif %}
</div>

```

The bool does *not* change depending on the tab selection. It appears to not be impacted at all. The page will *only* render with the multi link paragraph, despite single link setting tab being open on save.

1. Is the bool necessary? If so, what am I missing?
2. If the bool is not necessary, what should I do next?

How can I get the paragraph field in the tab that was active on save, to render on the page?

# Answer
> 1 votes
Three things that immediatly come to my eye:

1) If you want to check the value of a field, don't use the render array `{% content.field_whatever %}`, because this returns HTML markup and not the value of the field. Most fields types can be checked with something like `{% entity_type.field_name.0.value %}`, in your case `{% paragraph.option.0.value %}`.

2) CSS class names and Twig variable names are completly different things. Are you sure the field name (machine name) of your boolean field is `option`? Drupal by default prefixes every field with `field_`, so the name should be something like `field_whatever`. In your twig you should use something like `{% if paragraph.field_whatever.0.value %}`.

3) A selector like `$('.option')` is super-generic and will almost certainly include other elements anywhere on the page. I don't know your theme, but in my admin theme `.option` is not included in the classes of checkbox. Better use something like `$('input[name*="[field_whatever]"]')`

# Answer
> 1 votes
I think it is being called multiple times. To avoid that try Change your **JS** as below

```
$(context).find('.single-link').click(function () {
  $(context).find('.option').prop('checked', true);
});
$(context).find('.multi-link').click(function () {
  $(context).find('.option').prop('checked', false);
});

```

**OR**

change the on `click()` event to `hasClass()` the will be classes added to the active tab

---
Tags: 8, theming, entities, javascript, paragraphs
---


# Question
Title: list users informations who flagged an entityform with views
I'm using drupal 7 with entityform, views, rules

All is in the title, i need to list some profils fields (name, mail etc..) of users who flagged an entityform.

Exemple : User X send an entityform. User Y and Z are interested and click on a button(flag) "TAKE". When user x come in his list of entityforms submitted he can click on one of them and then he got all informations of users who clicked on "TAKE" flag.

So for each entity form the result can be different.

\**Edit : More informations : For now i have a view who list all the entityforms of my user X, on each of these items i have a link called "access folder" who show the entityform details page.

What i try to do in the entityform details page is to add a block who list all Users who clicked on the "TAKE" Button.\**

\** Edit 2 : What i did for now, \- i created a view block of type "entityform type" \- I gave a name for the block and added it in my left sidebar \- in the option of the block i specified "entityform/\*" in "only in this pages list"

* comming back in view i added a relationship with "Entityform Type: Entityform Submission" who is the entityform i'm using, and "(Entityform Submission) Flags: TAKE (by any user)"
* in contextual filters i added : "(Entityform Submission) Entityform Submission: Entityform submission ID" and specified "Provide default value" : "Content ID from URL"

I don't rly know whats wrong if someone can tell me \**

*Edit 3 : i think, in contextual filter, the "content ID from URL" does not work with entity forms. Am i right ?*

Thanks in advance guys !

# Answer
You're on a good track with creating the Entityform type of View. When you first created this View you chose which Entityform this is about, you can see it (change it) under Filter criteria. This view is now listing all submissions for that form.

You have also setup a Flag "Take" that users can use on Submissions of that form. And you want to show a list of all users who flagged a submission, on the submissions page.

When you create a fresh Entityform view you'll have only the field "Entityform: Entityform ID" and the Filter "Entityform: Entityform Type".

If you create a Page in that view you can list all the flags for all submissions for that Entityform. You can maybe use this page as a test, to see the user info correctly listed on submission, and delete it later.

You'll have to create a Block display to be added to submissions pages, this is what you're after.

Here is what you have to do to your Entityform view to show info about users who flagged a submission:

1. **Add Relationship `Flags: flag_take`** (or however your flag is called). Configure that Relationship to show **`Any user`**, and not `Current user`. This will list flags from all users who flagged it, not only the flags from the user currently looking at the page.
2. **Add a new Relationship `Flags: User` that uses the previous Relationship `flag`**. This introduces info about users who flagged the submission with "take" to be available in this Views.
3. To actually display the user info **Add a new Field `User: Name` and set it to use the Relationship `Flag user`**. This will show the name of the user who flagged the submission. To show other user info add different user fields and make them use the Relationship `Flag user` (otherwise you'll show info for the user who submitted the form, and not the one who flagged the submission).
4. Add a new Contextual filter `Entityform: Entityform ID` and configure it so that

When the filter value is NOT available:
**Provide default value**
Type: **Raw value from URL**
Path component: **2**

When the filter value IS available or a default is provided:
**Specify validation criteria**
\** - Basic validation - \** **Hide view** (or whatever makes sense to you)

And set that Contextual filter to **`This block (override)`** because it doesn't make sense to have it on a page display, for example.
5. Save the view and place the block in a region you want, you can specify the path where to show the block, like you mention in your question, this is good for performance. The Contextual filter that will make sure to only list results relevant to the particular entityform submission.

If you need to check the Block while working on it in Views enter an ID number of one submission that got flagged, to preview the result.
> 0 votes

---
Tags: views, flags
---


# Question
Title: How to add button to a form that calls custom JavaScript when clicked?
I want to create a button on a form that when clicked:

1. Calls some custom JavaScript
2. Does not submit the form

Is this possible with Drupal 8 Forms?

# Answer
In this example, I've added a custom button action to a Drupal 8 Form. When the button is clicked, it prevents the form from being submitted and allows custom JavaScript to do some work.

Here are the 3 pieces:

1. The form button element, with an `#attached` library
2. Your custom module's library declaration
3. The library's `.js` file

And here is the example code:

in **ExampleForm.php**

```
$form['actions']['clear'] = [
  '#type' => 'button',
  '#value' => $this->t('Clear'),
  '#attributes' => [
    'onclick' => 'return false;'
  ],
  '#attached' => array(
    'library' => array(
      'example/foo',
    ),
  ),
];

```

**example.libraries.yml**

```
foo:
  js:
    js/foo.js: {}

```

**js/foo.js**

```
Drupal.behaviors.example_hello = {
  attach: function (context, settings) {

    // Attach a click listener to the clear button.
    var clearBtn = document.getElementById('edit-clear');
    clearBtn.addEventListener('click', function() {

        // Do something!
        console.log('Clear button clicked!');

    }, false);

  }
};

```

Don't forget to clear all your caches to ensure your new `foo.js` library is picked up by Drupal 8.
> 7 votes

# Answer
Set the button\_type to button:

```
$form['js_action'] = array(
  '#type' => 'button',
  '#value' => t('Click me'),
);

```

Custom JS you would attach, like:

```
$form['js_action']['#attached'] => array(
  'js' => array(
     drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
);

```

Invoking ajax looks like this:

```
$form['js_action']['#ajax'] => array(
  'callback' => 'poll_choice_js',
  'wrapper' => 'poll-choices',
  'method' => 'replace',
  'effect' => 'fade',
),

```

With a menu callback like this:

```
/**
 * Menu callback for AJAX additions. Render the new poll choices.
 */
function poll_choice_js($form, $form_state) {
  return $form['choice_wrapper']['choice'];
}

```

Check the API for more infos ..
> 4 votes

# Answer
Setting button\_type to 'button' won't change the 'type' attribute of the resulting tag, just will add a class. There is no way to create a button with type other than 'submit' if you use 'button' or 'submit' form elements. You can always attach a javascript that prevents default behaviour of such a button, but I wouldn't recommend so.

My preferred way is to create a dedicated button by means of general-purpose html\_tag element:

```
$element['nosubmit_button'] = [
  '#type' => 'html_tag',
  '#tag' => 'input',
  '#attributes' => [
    'type' => 'button',
    'value' => t("It won't trigger submit"),
    'class' => ['button'], // an array of class names
    'name' => 'nosubmit_button',
  ],
  '#attached' => [
    'library' => [
      'mylibrary',
    ],
  ],

```

Please also note that in Drupal 8 you should attach libraries, not individual js or css files.

There are other ways to achieve the same goal, for example, you may use 'markup' element type and supply desired html markup of the button as '#markup' property. Pay attention then to #allowed\_tags property also, because markup is filtered and not any tag will pass through by default (eg button tag will not).
> 4 votes

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


title: Has my site been compromised?

text:
# Question
Title: Has my site been compromised?
Edit
apparently they belong in the includes folder, were they also are. could it be of any use for a hacker to have these two folders in the root?

---

I've been checking my drupal site and noticed in the root folder were two folders, database and filetransfer:

I dont know if this is hacked or belonging to some module or stuff, does anyone know something about this?

# Answer
I don't know if you've been hacked, or just accidentally copied those folders to root, but they shouldn't be in root by default.
> 1 votes

---
Tags: 7, security
---


# Question
Title: Suppress form_id, op and other similar values from the query string on a GET form submission
When building a custom form with Form API and making it a GET, how can one suppress form build id, token, form id, op and other special Drupal variables from getting into the URL on submit, without breaking the form (e.g., caching or other mechanisms) for users (anonymous or otherwise)?

Views is able to do this via the `ViewsExposedForm` class, but I don't quite understand what it is doing.

Edit: here is one form I am talking about:

```
<?php

namespace Drupal\mymodule_search\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Component\Utility\Xss;
use Drupal\Component\Utility\Unicode;

/**
 * Contains the custom Solr search form.
 *
 * @package Drupal\mymodule_search\Form
 */
class KeywordForm extends FormBase {

  /**
   * Symfony\Component\HttpFoundation\RequestStack definition.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructor for our class.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'mymodule_search_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $keywords = Xss::filter($this->requestStack->getCurrentRequest()->get('keywords'));
    $site_ids = $this->requestStack->getCurrentRequest()->get('site_id');
    $sort_by = $this->requestStack->getCurrentRequest()->get('sort_by');
    $sort_order = $this->requestStack->getCurrentRequest()->get('sort_order');
    $search_config = $this->config('mymodule_search.settings');
    $site_id = $search_config->get('site_id');

    $form['#attributes']['class'][] = 'search-result__form';

    if (!is_array($site_ids) || empty($site_ids)) {
      $site_ids = [$site_id => $site_id];
    }

    $input = $form_state->getUserInput();

    if (!empty($input['sort_by'])) {
      $sort_by = $input['sort_by'];
    }
    else {
      $sort_by = 'score';
    }

    if (!empty($input['sort_order'])) {
      $sort_order = $input['sort_order'];
    }
    else {
      $sort_order = 'DESC';
    }

    $form['keywords'] = [
      '#type' => 'textfield',
      '#default_value' => Unicode::strlen($keywords) ? $keywords : '',
      '#prefix' => '<div class="search-box__input js-search-input">',
      '#suffix' => '</div>',
      '#attributes' => [
        'placeholder' => Unicode::strlen($keywords) ? $keywords : t('Search for...'),
      ],
    ];

    $form['site_id'] = [
      '#type' => 'hidden',
      '#value' => $site_ids,
    ];

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

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

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      '#attributes' => [
        'class' => [
          'search-box__button',
        ],
        'data-twig-suggestion' => 'search_results_submit',
      ],
    ];

    $form['#cache']['contexts'][] = 'session';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirect(
      'mymodule_search.search',
      [
        'keywords' => $form_state->getValue('keywords'),
        'site_id' => $form_state->getValue('site_id'),
        'sort_by' => $form_state->getValue('sort_by'),
        'sort_order' => $form_state->getValue('sort_order'),
      ],
      [
        'query' => [
          'keywords' => $form_state->getValue('keywords'),
          'site_id' => $form_state->getValue('site_id'),
          'sort_by' => $form_state->getValue('sort_by'),
          'sort_order' => $form_state->getValue('sort_order'),
        ],
      ]
    );
  }

}

```

I don't think I need to have `setRedirect` in the submit method, but it was the only way to get a "clean URL" query string. When I change to a GET type, kiamlaluno below says you can call $form\_state-\>cleanValues() to remove Drupal specific things from being in the URL, but that has no effect either, and a bunch of stuff is still in the URL.

At the same time, the form is POSTing to the same URL, which triggers buildForm again - the form state will be empty and I can't see what the user just entered, which is undesirable. I can see this with xdebug, buildForm is called twice, the first time you can see all $form\_state values, and the second time is empty.

# Answer
> 1 votes
This D7 approach also works in D8:

```
   $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Make Payment',
      '#name' => '',
  );

  $form['#after_build'][] = 'mymodule_form_modify';

  function mymodule_form_modify($form){
    unset($form['form_token']);
    unset($form['form_build_id']);
    unset($form['form_id']);
    return $form;
  }

```

Credits: https://www.drupal.org/node/821932#comment-6017528

# Answer
> 1 votes
I got this to work by copying the search form from core. The key is in `search_form_search_block_form_alter`

```
/**
 * Implements hook_form_FORM_ID_alter() for the search_block_form form.
 *
 * Since the exposed form is a GET form, we don't want it to send the form
 * tokens. However, you cannot make this happen in the form builder function
 * itself, because the tokens are added to the form after the builder function
 * is called. So, we have to do it in a form_alter.
 *
 * @see \Drupal\search\Form\SearchBlockForm
 */
function search_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['form_build_id']['#access'] = FALSE;
  $form['form_token']['#access'] = FALSE;
  $form['form_id']['#access'] = FALSE;
}

```

This approach works with `$form['#method'] = 'get';` and you don't need a redirect or processing in submitForm.

# Answer
> 0 votes
The `FormState` class has a method for that, `FormState::cleanValues()`, which by default cleans out these values:

* form\_id
* form\_token
* form\_build\_id
* op
* The value associated with every button in the form

If then you need to clean out more values, you can use `FormState::addCleanValueKey()`.

FormState::cleanValues() returns the FormState object, so you can use that method in chained calls, like in the following code, for example.

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

```

---
Tags: forms
---


# Question
Title: How can I run Drush 8 and Drush 9 together on same machine to test some module on it?
As in my earlier environment I was running Drush 6 and Drush 8 together.

I need help with the Drush 8 and Drush 9 installation. Is there any possible way to achieve it?

I tried to do porting command following Porting Commands to Drush 9, without success.

Any help would be appreciated.

# Answer
> 0 votes
Install Drush 8 by downloading the phar file as recommended in the documentation. Rename the phar file to drush8, not drush.

Install Drush 9 as recommened in the documentation. I strongly recommend to install Drush Launcher globally using a phar file as documented and only install Drush site local. This is very easy if you are already using Composer to maintain your Drupal site. If you aren't using Composer to maintain your site, you can just as well install Drush 9 globally using Composer and forget about Drush Launcher.

---
Tags: drush
---


# Question
Title: Limiting number of multiples in a drupal webform in an ajax callback
I have a form with a select element to choose the number of guests you want to add to an event. This select has an ajax callback that updates a container that holds a contact composite element.

I am trying to in my ajax callback update the number of multiple contact elements to the value of the number of guests select box. Anyone have any thoughts? If I use a form alter like below on initial load the number of elements updates correctly.

# My alter attempting to just set multiple number outside ajax

```
function lebow_events_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['elements']['guest_info']['guest_contact']['#type'] = 'webform_multiple';
  $form['elements']['guest_info']['guest_contact']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#multiple'] = 10;
  $form['elements']['guest_info']['guest_contact']['#cardinality'] = 10;
  $form['elements']['guest_info']['guest_contact']['#sorting'] = FALSE;
}

```

# My webform source

```
registration_type:
  '#type': select
  '#title': 'Registration Type'
  '#options': registration_types
guests_container:
  '#type': container
  '#states':
    invisible:
      ':input[name="registration_type"]':
        value: ''
  number_of_guests:
    '#type': select
    '#title': 'Number of guests'
    '#options':
      - '0'
guest_info:
  '#type': container
  '#title': 'Guest Info'
  guest_contact:
    '#type': contact
    '#title': 'Contact Info'
    '#multiple': 2
    '#multiple__add_more': '2'
    '#company__access': false
    '#phone__access': false
    '#address__access': false
    '#address_2__access': false
    '#city__access': false
    '#state_province__access': false
    '#postal_code__access': false
    '#country__access': false

```

# My alter to add ajax callback (and try setting number of multiples)

```
function lebow_events_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

  $form['elements']['guests_container']['number_of_guests']['#options'] = ['' => '- None -'];
  $form['elements']['registration_type']['#ajax'] =
    array(
      'callback' => 'lebow_events_registration_change',
      'wrapper' => 'edit-guests-container',
    );
  $form['elements']['guests_container']['number_of_guests']['#ajax'] =
    array(
      'callback' => 'lebow_events_guests_change',
      'wrapper' => 'edit-guest-info',
    );

  $form['elements']['guests_container']['number_of_guests']['#validated'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#type'] = 'webform_multiple';
  $form['elements']['guest_info']['guest_contact']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#multiple'] = 10;
  $form['elements']['guest_info']['guest_contact']['#cardinality'] = 10;
  $form['elements']['guest_info']['guest_contact']['#sorting'] = FALSE;
}

```

# My ajax callback

```
function lebow_events_guests_change(&$form, \Drupal\Core\Form\FormState $form_state) {

  $form['elements']['guest_info']['guest_contact']['#type'] = 'webform_multiple';
  $form['elements']['guest_info']['guest_contact']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#multiple'] = $form_state->getValue('number_of_guests');
  $form['elements']['guest_info']['guest_contact']['#cardinality'] = $form_state->getValue('number_of_guests');
  $form['elements']['guest_info']['guest_contact']['#sorting'] = FALSE;
  $form['elements']['guest_info']['guest_contact']['#element']['#webform_multiple'] = TRUE;
  $form['elements']['guest_info']['guest_contact']['#element']['#multiple'] = $form_state->getValue('number_of_guests');

  $message = $form['elements']['guest_info'];

  $response = new \Drupal\Core\Ajax\AjaxResponse();
  $response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('[data-drupal-selector=edit-guest-info]', $message));

  return $response;

}

```

# Answer
It is very difficult and sometimes impossible to alter a form via an Ajax callback. Generally, an Ajax callback just returns the updated form element from the $form render array.

The Examples for Developers module includes several Ajax form examples that you can use as a starting point.
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: What is the purpose of Views "Attachment", "Content pane" & "Context"?
I've just made a Views for a content type.

In one views, I need a page for the content type and a preview of 4 newest posts on the front page.

Page is not the problem. For front page preview, I just confused about the purpose of "Attachment", "Content pane" & "Context". I don't know which one to use for front page preview.

"Context" does not have more link, and "Content pane" is not for Panels pane since Panels module is disabled.

# Answer
> 13 votes
The Attachment option is to create yet another view that you can attach before and/or after any of the displays on your current view.

An example of its use is if you enable the taxonomy views the taxonomy pages are overwritten by the view and if you were to add a couple of extra fields like images, description, etc to your taxonomy term you can the use an attachment to display it as the header of each taxonomy page.

The EVA module extend this functionality by allowing you to attach views to content types and other entities.

The other two I have never use, but:

Here is an explanation about "Content pane":

http://drupalize.me/videos/basics-views-content-panes

# Answer
> 3 votes
Content pane is usually used inside a panel (Panels module). You can think of it as a block, but usable inside Panels, than can get arguments, etc from the panel.

# Answer
> 1 votes
For **drupal 8**, when using a **pager** and you want the attachment to show **only on the first page**:

Create a new template for your view (views-view-unformatted.html.twig) and add this code:

```
{% if view.pager.current_page == 0 %}
    {% if attachment_before %}
    <div class="attachment attachment-before">
      {{ attachment_before }}
    </div>
  {% endif %}
{% endif %}

```

---
Tags: 7, views
---


# Question
Title: cache_form error: myisam_sort_buffer_size is too small
After running `mysqlcheck -udbuser -p --auto-repair --optimize --databases mydrupaldb`, I got the following error.

> cache\_form error: myisam\_sort\_buffer\_size is too small

Someone has suggested that it should be solved by increasing sort\_buffer\_size parameter, for example with `myisamchk -r -q cache_form.MYI --sort_buffer_size=2G`. Executing this command causes the following error.

> myisamchk: error: File 'cache\_form.MYI' doesn't exist

How can I fix it?

# Answer
**mysqlcheck** is a client utility that actually logs into mysql

**myisamchk** is a client utility that does not require logging in. It does require

* access the raw file(s) needed, provided the datafile is not in use by the mysqld process
* your current directory is wherever the datafile is located

For the table mydrupaldb.cache\_form, here is what you must do:

* Step 01) Run this query : `SHOW VARIABLES LIKE 'datadir';` In most instances, this will be /var/lib/mysql. For the sake of this example, let's assume it is /var/lib/mysql.
* Step 02) `cd /var/lib/mysql/mydrupaldb`
* Step 03) `service mysql stop`
* Step 04) `myisamchk -r -q cache_form.MYI --sort_buffer_size=2G`
* Step 05) `service mysql start`

Give it a Try !!!

CAVEAT : The error message probably means you were not standing in the proper directory where cache\_form.MYI is located at the time you first ran myisamchk.
> 2 votes

# Answer
## Try shrinking the cache\_form table

On high-traffic sites, cache\_form can get overly large. See this core issue: Make cache\_form expiration configurable, to mitigate runaway cache\_form tables.

I've posted more information in this Drupal stackexchange answer on what to do when "Cache Form table size is enormous".
> 0 votes

---
Tags: database
---


# Question
Title: How to change the system path of a taxonomy vocabulary to correspond a view
I'm using Drupal 8 and i want different vocabularies to be displayed by different views. Each view should have a different path with a contextual filter but when i define my path on pathauto the alias will be pointed to the system path.

I know there's modules that solve this like Taxonomy Display and Entity Path but because i'm using version 8 i really can't afford these modules.

Can you help me to change the default system path of each taxonomy vocabulary to correspond to a custom view?

Thank you for reading

# Answer
I solved my problem installing the module: Taxonomy Views Integrator - https://www.drupal.org/project/tvi.

It's easy to set a view to display both taxonomy terms and vocabularies.
> 2 votes

---
Tags: views, taxonomy-terms, path-aliases
---


# Question
Title: Where is the module registry stored outside the database?
As a long time Drupal dev, I should probably know the answer to this question, but I'm stumped by the behavior I'm seeing.

Let's say I have a local and a remote site. On the remote site a module is uninstalled properly and the module code is removed from the file system (git tracks the deletion, etc).

Then to get my local installation up to date, I completely drop all tables in my database (it's completely empty) and I do a git pull, so the local module files are deleted. I then get the remote database and load it into my local.

In that situation there are no database remnants from my old local install and the file system is updated with the deleted modules. It should reflect the remote site completely.

However, when I load up the local site I get all the 'XXXX module is missing" and everything breaks. I run the registry rebuild via drush rr, and it fixes everything. But then, going forward into the future, I continue to see this broken registry each time I reload the site from the remote database (meaning I have to rr each time).

This strikes me as so odd...because where are those old registry records stored outside the database? Why, if I have a fully clean database, does it recognize old modules as missing?

And of course...how can I 'clean them up' permenantly?

# Answer
> 1 votes
Common causes:

* External cache (Memcache, etc) that is not purged on rebuild
* Your SQL import contains cache from prod (I tend to make sure backups make cache tables structure-only).
* Your SQL is imported into a DB which contains tables, but does not drop some of them (such as cache). (I personally drop and create the DB before each import).
* The module is still enabled/present in the system table (confirm in your SQL that the row in the system table is gone/disabled & uninstalled).
* Something else on your site depends on it and is re-enabling it (eg master module, feature dependencies, etc (although dependencies usually block things from being disabled)).
* Sometimes worth doing a `drush cc drush` after importing the SQL. When in doubt, clear caches ;)

---
Tags: 7, caching
---


# Question
Title: How do I apply patch in vendor directory using composer?
Background:

* Drupal 8
* Managing dependencies with compose

I want to apply one patch to `vendor/behat/web_api_extension` project.

I tried with this in `composer.json` but it doesn't works or no error.

```
"extra": {
    "enable-patching": true,
    "patches": {
        "drupal/better_formats": {
           "Settings have no affect on the field if it is in a Paragraph bundle - https://www.drupal.org/node/2754029": "https://www.drupal.org/files/issues/better_formats_paragraphs-2754029-15.patch"
        },
        "vendor/behat/web-api-extension": {
            "behat web api definition conflicts with mink extensions": "patches/behat_web_api/alter-definitions-text.patch"
        }
    }
}

```

# Answer
> 6 votes
You will need `cweagans` vendor to make composer able to parse the extra-\>patches lines.

This line is wrong I think: `"vendor/behat/web-api-extension"` You always need the package name (without version) and not the relative path. In your case it should be `"behat/behat"`

# Answer
> -1 votes
You need to have `cweagans/composer-patches` as a requirement on your project, so you need to:

```
composer require cweagans/composer-patches

```

Then in your composer.json you need to add your patches under extra:patches, which you already had:

```
...
"extra": {
    "enable-patching": true,
    "patches": {
        "drupal/better_formats": {
           "Settings have no affect on the field if it is in a Paragraph bundle - https://www.drupal.org/node/2754029": "https://www.drupal.org/files/issues/better_formats_paragraphs-2754029-15.patch"
        },
        "vendor/behat/web-api-extension": {
            "behat web api definition conflicts with mink extensions": "patches/behat_web_api/alter-definitions-text.patch"
        }
    }
}
...

```

---
Tags: 8, composer, testing
---


# Question
Title: How can I sort Labels in config entity list builder?
I have a very simple config entity with a few fields. In the list builder I want to sort the `label` field by creation date rather than by alphabetical order.

I originally thought this should be fairly easy, but it's proving way more difficult than I expected.

Can anybody point me in the right direction?

# Answer
> 3 votes
To answer my own question I guess.

Config entities list builder extends the `ConfigEntityListBuilder` class, which comes with a few built in methods, among which

```
  /**
   * Loads entity IDs using a pager sorted by the entity id.
   *
   * @return array
   *   An array of entity IDs.
   */
  protected function getEntityIds() {
    $query = $this->getStorage()->getQuery()
      ->sort($this->entityType->getKey('id'));

    // Only add the pager if a limit is specified.
    if ($this->limit) {
      $query->pager($this->limit);
    }
    return $query->execute();
  }

```

To sort, in whichever you ones desires, the display list itself all that needs to be done is overwrite the function in the child class.

In my case it was something like this:

```
protected function getEntityIds() {
  $query = $this
    ->getStorage()
    ->getQuery()
    ->sort('notification_creation_date', 'DESC');

  // Only add the pager if a limit is specified.
  if ($this->limit) {
    $query->pager($this->limit);
  }
  return $query->execute();
}

```

---
Tags: 8
---


# Question
Title: Do these options affect other modules and possibly core?
I have a question about downloading an unstable version of a module using composer. I run `composer require 'drupal/page_manager:^4.0'` but I get this error message.

> The requested package drupal/page\_manager ~4.0 is satisfiable by drupal/page\_manager\[4.x-dev, 4.0.0-beta3, 4.0.0-beta2, 4.0.0-beta1\] but these conflict with your requirements or minimum-stability.

I looked at the repository, and they don't seem to have a stable version. So I read that in my composer.json file I should put the following lines.

```
"prefer-stable" : true,
"minimum-stability": dev,

```

If I set these options to composer, will this affect other modules and possibly Drupal core? when I update core, could it download a development snapshot higher than the current version? If so, how do I downloading the development snapshot only for a module without affecting other modules/core?

# Answer
> 1 votes
It is fine to set `minimum-stability` to `dev`. Error: Conflict with your requirements or minimum-stability describes it is there by default.

You can set `minimum-stability` because `prefer-stable` prefers stable packages over unstable.

# Answer
> 2 votes
See prefer stable's documentation

> When this is enabled, Composer will prefer more stable packages over unstable ones when finding compatible stable packages is possible. If you require a dev version or only alphas are available for a package, those will still be selected granted that the minimum-stability allows for it.

See minimum-stability's documentation

> This defines the default behavior for filtering packages by stability. This defaults to stable, so if you rely on a dev package, you should specify it in your file to avoid surprises.
>
> All versions of each package are checked for stability, and those that are less stable than the minimum-stability setting will be ignored when resolving your project dependencies. (Note that you can also specify stability requirements on a per-package basis using stability flags in the version constraints that you specify in a require block (see package links for more details).
>
> Available options (in order of stability) are dev, alpha, beta, RC, and stable.

These will do exactly as they sound, they will prefer a stable release, if there is one that satisfies your composer requirements, otherwise they'll look to unstable releases that are at least in "dev".

---
Tags: 8, composer
---


# Question
Title: Change the url path of /sites/default/files/myfile.pdf
When you click to view a pdf file on a page the url is always this: http://yoursite.com/sites/default/files/myfile.pdf. You can modify this path in the field setting and add tokens, dates. But what if you wants the url to be simple and not give out the fact that this is a Drupal site. Can you change it to be this: http://yoursite.com/files/myfile.pdf. Does this require htaccess url rewrite or Apache redirects?

# Answer
Go to this path `/admin/config/media/file-system`, and change the public file system path.

It might be this, `sites/default/files`, change it to `files`.

Then create a writeable folder in your webroot called files.

This could also be done by adding this line in the settings.php file:

```
$settings['file_public_path'] = 'files';

```

Just note that this is only for local development if you want to deploy this change you might use the above solution and then export the configuration.
> 2 votes

---
Tags: 8, uri
---


# Question
Title: '"media_edit_action" plugin does not exist' error when performing update
I get the following error after a database update. It looks like it completes the update by displaying *Completed 8 of 8* but it doesn't run the updates. Any help is appreciated.

> Failed: Drupal\Component\Plugin\Exception\PluginNotFoundException: The "media\_edit\_action" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 52 of /srv/bindings/ae21023ced6d43099409c0fbbeded25e/code/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

This is what the updates need to run.

### System module

> Change plugin IDs of actions.
> Clear caches due to schema changes in core.entity.schema.yml.

### Views module

> Update dependencies for moved bulk field plugin.
> Add additional settings to the entity link field and convert node\_path usage to entity\_link.
> Add placeholder settings to string or numeric filters. Fix cache max age for table displays.
> Include views data table provider in views dependencies.

# Answer
I believe that action at some point became deprecated and was removed from the media\_entity module. However, the configuration lingered and is blocking Drupal update from completing successfully.

What worked for me was to go the the `Admin > Configuration > Development > Configuration Synchronization > Updates Report` (menu tab).

If you view the Full Report, then you can see that the config for the `media_edit_action` is still present.

Use the pulldown menu on the right to delete that config.

When you run update again, then it should complete successfully.

Hope this helps!
> 1 votes

---
Tags: updating
---


# Question
Title: Specific role can only change status (active/blocked) of any user
I've created a views page (holding all users information) for role **ONE**. Now I would like to give permission to that role he can change status (active/blocked) without editing the other fields (email, phone, username etc.) of the users.

I tried with Editable Fields module but it doesn't provide "editable formatter" in Users views field so it won't work for user's built-in field.

Is there a way to do so?

# Answer
> 0 votes
As I mentioned in the question,

> I would like to give permission to that role he can change status (active/blocked) without editing the other fields...

I've done it without giving permission (Administer users) to role **ONE**.

I had to do configurations between tree modules Flag, Views and Rules. I created `new flag`, `get flag in views using relationship` and the `add two simple rules`. That's all

Let me post the answer, may be someone will need in the future.

* Above mentioned three modules should be enabled with their UIs.

## **Creating Flag**

* Go to `/admin/structure/flags/add`, create a new flag and choose User as **Flag Type**, example
* After saving the Flag Type, fill next form like this, you may choose options as you like.

## **Creating Views**

* Now, create a views page/block as you like with showing Users category and your all fields you want to show and add a **Relationship** for the flag you just created (in my case it was "Block User").
* Now, add a new field as **Flag link** in the views and add relationship if its already not and choose settings
* Save the views

## **Creating Rule**

We have to add to rules one for block the user and other for activate the user.

**Block User**

**Activate User**

There are same steps to activate users using rules. You just only to change event as *"A user has been unflagged, under Block User"*, check the status as blocked instead of active and finally add action Unblock User instead of Block user.

All done...

Now, go to view the views you just created check if it works.

I hope it'll help someone.

---
Tags: 7, views, users
---


# Question
Title: I want to add css class to a field inside hook_field_widget_form_alter, but it doesn't work!
in this link https://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook\_field\_widget\_form\_alter/7

it describes that we can add css class to an element in a form via this code

```
function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

```

I tried to use it but it seems `$element['#attributes']['class'][] = 'myclass';` doesn't add any css class to form after rendering.

So how can I add css class to a form element inside `hook_field_widget_form_alter()` ?

# Answer
Old issue but it might help future viewers. Try this: `$element['value']['#attributes']['class'] = 'myclass';`

See `field_multiple_value_form()` which creates the render array. Then main theme function for rendering fields in forms is `theme_field_multiple_value_form()` and the parent theme function is `theme_form_element()`
> 0 votes

---
Tags: hooks, entities
---


# Question
Title: Features versus Configuration Management
I am building a Drupal 8 site and I have done some research whenever I should use Configuration Management or Features to export configuration and include it in my profile. In order to export and import configuration with Configuration Management from one site to another, sites have to have the same UUID. It means that they have to be a clone of each other. There are two ways to achieve this:

1. Clone the DB from one site to the other in order to have the same UUID
2. Programmatically modify the UUID to match the one in configuration

The site I am going to build will have its own profile installation and my intention is to keep configuration or features within the profile. I have already created my profile installation but now I have to include configuration in a way it does not depend on UUID so I can:

1. Spin up a fresh development environment using profile installation
2. Develop new functionalities
3. Export new functionalities in the profile
4. Deploy it to prod and apply new functionalities without re-installing the site

How can I export configuration and add it to my profile? Should I use Configuration Management and manually remove the UUID or should I use Features and add it to my profile?

Using the Features module, I am not able to set the destination for my features. I would like to put all my features under profiles/my\_profile/feature. When I create it I am not able to set a destination so it gets saved under modules/custom. I manually moved it from modules/custom to profile/my\_profile/features. If I update it, it will not update the features I moved but instead it will create a new feature with the same name under modules/custom. How can I setup a custom destination?

# Answer
I would advise using Features. This would allow not only exporting functionality and compartmentalizing it a lot easier, but you could also have the ability to bring in features later from an external source, and/or, use certain features here on a different site that didnt start with your installation profile.

Currently there is an issue to support custom path generation for Features: https://www.drupal.org/node/2693123

When that is addressed, you can generate the features to the path of your choice. For now, you can generate the result, grab it out of modules/custom and place the generated feature module into your profile.
> 4 votes

# Answer
Adding some counter-argument info for assimilation/consideration:

Features module maintainer Mike Potter is encouraging folks to stop using the features module as ...

> Features module is really no longer needed and shouldn’t be used to deploy configuration. However, Features still provides a powerful UI and plugin system for managing configuration and in combination with new modules such as Config Actions it might finally achieve its dream of packaging reusable functionality.
> 1 votes

---
Tags: 8, features, configuration, installation-profiles
---


# Question
Title: How do I access the property of an object in an array?
I need to get the the "companyId" but am not sure of the syntax

# Answer
It might be:

```
$invite_requests[20]->companyId

```

However, that's only if $companyId has been declared as a public variable. If it has not, there should be a method (function) of retrieving it. You'll need to find the file that contains the class ApigeeCompanyInvitationEntity, and look for a method there if this is the case.
> 2 votes

# Answer
I should have been more specific but I was able to access and adjust the property in `$invitation` via a `foreach loop`

```
foreach ($invite_requests as $invitation) {
         'do something here'}

```
> 0 votes

# Answer
Just an FYI, but with PHPStorm (I am guessing that is what that is) you can right click on things in the debugger and do "Copy Path" which would give you the path. But I also think you would want to loop `$invite_requests` which would probably make your inner loop have:

```
$companyIds = [];

foreach ($invite_requests => $invitation) {
  $companyIds[] = $invitation->companyId;
}

```

That only works if that property is public, what you are likely after is a getter method i.e. `getCompanyId()` for that object.

Either way, this question is more generic PHP than Drupal.

Use the IDE to inspect the class methods.
> 0 votes

---
Tags: 7
---


# Question
Title: How to set up a text format that replaces the tokens?
In the custom Drupal 8 block, there are no tokens.

```
/admin/structure/block/block-content

```

How to set up a text format that replaces the tokens ?

I need to use in a custom block, the title of the current page, the creation date of the current page, ...

# Answer
Token Filter is a very simple module to make token values available as an input filter.

This doesn't mean that all tokens will work in every location. For example, if you use a \[node:field\_foo\] token in the text of a block, the token system will not know which node you are referring to and will not replace the token. It is up to you when you are implementing this module to be aware of the context for token usage and use them appropriately

https://www.drupal.org/project/token\_filter
> 3 votes

---
Tags: 8, blocks, tokens
---


title: Passing variables to a block template

text:
# Question
Title: Passing variables to a block template
I am using the following code, but it doesn't work.

### drupal\_block.module

```
function custom_blocks_theme($existing, $type, $theme, $path) {
  return [
    'custom_blocks__front_apps' => [
      'variables' => [
        'app' => NULL
      ],
    ],
  ];
}

```

### BlockTest.php

```
  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#theme' => 'custom_blocks__front_apps',
      '#app' => 'test value',
    ];
  }

```

### custom\_blocks\__front\_apps.html.twig

```
<p>Hello: {{ app }}</p>

```

My block is empty.

>

What is wrong with the code?

# Answer
> 1 votes
Finallly i solved my own problem... but i don't know what exactly it is... Drupal follow strictly their names theme and if i get wrong in something small the block crashes.. but i'll show you how it is working now the code.

blocktest.module

```
/**
 * Implements hook_theme() to add the template definition.
 **/
function blocktest_theme($existing, $type, $theme, $path) {
    return array(
        'block-test' => array(
            'variables' => array('test_var' => NULL),
        ),
    );
}

```

Plugin/Block/BlocktestController.php

```
namespace Drupal\blocktest\Plugin\Block;
use  Drupal\Core\Block\BlockBase;

/**
 * @Block(
 *   id = "block_test",
 *   admin_label = @Translation("Block Test"),
 * )
 */
class BlocktestController extends BlockBase
{

    /**
     * Builds and returns the renderable array for this block plugin.
     *
     * If a block should not be rendered because it has no content, then this
     * method must also ensure to return no content: it must then only return an
     * empty array, or an empty array with #cache set (with cacheability metadata
     * indicating the circumstances for it being empty).
     *
     * @return array
     *   A renderable array representing the content of the block.
     *
     * @see \Drupal\block\BlockViewBuilder
     */
    public function build()
    {
        return array(
            '#theme' => 'block-test',
            '#test_var' => $this->t('Test Value'),
        );
    }
}

```

block-test.html.twig

```
<p> This is the lotus template with a value of {{ test_var }} </p>
<button>it works</button>

```

Thanks!

# Answer
> 3 votes
I think you should write it like below code.

```
   /**
    * Implements hook_theme() to add the template definition.
    **/
    function lotus_theme($existing, $type, $theme, $path) {
      return [
        'lotus_template' => [
          'variables' => ['test_var' => NULL],
        ],
      ];
    }

```

In your controller file

```
public function build() {

    return array[
      '#theme' => 'lotus_template',
      '#test_var' => $this->t('Test Value'),
    ];

  }

```

Then in your lotus-template.html.twig

```
<p> This is the lotus template with a value of {{ test_var }} </p>

```

# Source Define a custom template for module output

---
Tags: theming, blocks
---


# Question
Title: Calculate difference between two dates in Webform
I am trying to calculate a difference in days between (a) the date a Webform was completed and (b) an "Event Date" field on the Webform. I have added a Computed Twig field to the webform and attempted to use this code (similar to https://stackoverflow.com/a/27205095/1357555):

```
{% set difference = date(data.event_date).diff(date(completed)) %}
{% set leftDays = difference.days %}

```

However, I am getting an error message when attempting to save the field.

> *Computed value/markup* is not valid.
>
> * Calling "diff" method on a "DateTime" object is not allowed in "{# inline\_template\_start #}{{ completed|date }} {{ data.date\_needed|date }} {% set difference = date(data.event\_date).diff(date(completed)) %} {% set leftDays = difference.days %}" at line 4.
>
> Failed to render computed Twig value due to error.

# Answer
This is a bug in the Webform module. I created the below ticket to address this issue.

Improve Computed Twig element validation to support complex calculations
> 2 votes

---
Tags: 8, theming, webforms
---


# Question
Title: Load a custom block and render with subset of data
I am loading a block programmatically in a theme preprocess function, and trying to render that block in twig using `without` to remove some fields. However, the block is still printed in full.

This is the code I am using.

```
function my_preprocess_node(&$variables) {
    $footer_narrow = \Drupal\block\Entity\Block::load('my_block');
    $variables['my_block'] = \Drupal::entityManager()
      ->getViewBuilder('block')
      ->view($my_block);
}

```

The template code is the following one.

```
{{ my_block|without('field_1', 'field_2') }}

```

I also noticed while debugging, that while the result in twig of `my_block` is a render array, it does not include the keys I'm expecting (the problem, I assume?).

This is the `dump()` output.

```
array(3) {
  '#cache' =>
  array(4) {
    'keys' =>
    array(3) {
      [0] =>
      string(11) "entity_view"
      [1] =>
      string(5) "block"
      [2] =>
      string(17) "my_site_footer"
    }
    'contexts' =>
    array(3) {
      [0] =>
      string(28) "languages:language_interface"
      [1] =>
      string(17) "my_theme_section"
      [2] =>
      string(14) "my_theme_site"
    }
    'tags' =>
    array(2) {
      [0] =>
      string(10) "block_view"
      [1] =>
      string(36) "config:block.block.my_block"
    }
    'max-age' =>
    int(-1)
  }
  '#weight' =>
  int(0)
  '#lazy_builder' =>
  array(2) {
    [0] =>
    string(42) "Drupal\block\BlockViewBuilder::lazyBuilder"
    [1] =>
    array(3) {
      [0] =>
      string(17) "my_site_footer"
      [1] =>
      string(4) "full"
      [2] =>
      NULL
    }
  }
}

```

# Answer
One way to do this is with a new view mode for blocks. You can add one at `/admin/structure/display-modes/view/add` (Manage \> Structure \> Display Modes \> View Modes \> Add new view mode). Then, you have two options, 1. go to your custom block type and configure this view mode display to only have the fields you want, or 2. create a template file with a name like `block--BLOCK-TYPE--MY-NEW-VIEW-MODE.html.twig`, then remove the fields you don't want to print like you were trying to do in the node template. (Replace `BLOCK-TYPE` with your block type's machine name, and `MY-NEW-VIEW-MODE` with the machine name of the new view mode you created. Convert all underscores in these machine names to dashes.) After you've done this you can update your preprocess hook's `view()` call like `->view($my_block, 'MY_NEW_VIEW_MODE')`(keep the underscores in the machine name of your view mode here). This will make your preprocess hook look like:

```
function my_preprocess_node(&$variables) {
  $footer_narrow = \Drupal\block\Entity\Block::load('my_block');
  $variables['my_block'] = \Drupal::entityManager()
    ->getViewBuilder('block')
    ->view($my_block, 'MY_NEW_VIEW_MODE);
}

```

Lastly, because you add your block to the variables array with the `my_block` key, update your node's twig template to simply be:

```
{{ my_block }}

```
> 2 votes

---
Tags: theming, blocks
---


# Question
Title: How to configure Trusted_Host_Settings for subdomains?
How to configure Trusted\_Host\_Settings for subdomains?

The documentation does not give an example of a subdomain.

For example, I have an Add-On domain that points to website.info, but the subdomain is mainsite.com/website.info

# Answer
It's actually documented in `settings.php` file as in examples:

Drupal 8.5.x
https://cgit.drupalcode.org/drupal/tree/sites/default/default.settings.php?h=8.5.x#n712

```
<?php
$settings['trusted_host_patterns'] = [
  '^example\.com$',           // Matches naked domain only.
  '^.+\.example\.com$',       // Matches any subdomains.
  '^subdomain\.example\.com', // Matches a specific subdomain.
];

```

You can easily define any naked or sub-domain, as long as defined regex pattern matches them correctly.
> 6 votes

---
Tags: configuration
---


# Question
Title: how to create a view with recent item also display catagary name
I want a block on my home page called (recent files addit) but I want to display catagary name also like file name (how to create a folder) catagary: (basic computer learning) you can find same example on this website home page www.blindhelp.net

# Answer
> 0 votes
The key to create a Views block showing recently uploaded Files and Taxonomy terms the nodes where files are attached belong to is to add a Relationship to the content the file is attached to. You can start with `Files` Views type (assuming Drupal 7):

1. Create a new View of type `File`, set the Format to `Table`
2. Add a new `Relationship` **File Usage: Content**. This will introduce info from the node the file is attached to into this View
3. Now you can add the usual Filters (for example **Content: Type (= Article)** and **Content: File:fid (not empty)**). They will automatically be configured to use the Relationship you created in the previous step
4. **File: Name** field should already be there. Add a new field: **Content: All taxonomy terms (All taxonomy terms)**
5. Add `Sort criteria` **File: Upload date (desc)**, adjust the Pager, and other relevant Views properties you want.

---
Tags: taxonomy-terms
---


# Question
Title: When rendering paragraphs in a theme, is there a way to look at the last rendered paragraph while rendering the current one?
I have about two dozen paragraph types. One of them inserts an `h2`, and generates a jump menu at the top of the page (I am generating that myself).

The pattern lab has the content that comes next (whatever the next Paragraph inserted may be) with a special CSS class on the container, because of the particular aforementioned type being used.

Is there a way in `theme_preprocess_paragraph` or `theme_preprocess_field` to 'look back' and add the CSS class if the current one is a certain paragraph type?

# Answer
Yes, you can do something like this in preprocess:

```
    <?php
    // Get entity reference revision item that points to this paragraph.
    /** @var \Drupal\entity_reference_revisions\Plugin\Field\FieldType\EntityReferenceRevisionsItem $item_reference */
    $item_reference = $paragraph->_referringItem;

    // Get entity reference revision field items list that holds all
    // paragraphs.
    /** @var \Drupal\entity_reference_revisions\EntityReferenceRevisionsFieldItemList $items_list */
    $items_list = $item_reference->getParent();

    // Get next index position of current paragraph in entity ref. revision
    // field items list.
    $next_delta = $item_reference->getName() + 1;

    // Check if there is a paragraph on the next delta.
    if ($items_list->offsetExists($next_delta) && $items_list->get($next_delta)->entity) {

```

That special property is set in \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView(). And because paragraphs themself are not render cached on their own and not used in multiple places means that you can actually rely on it. (It would also be set on a node, but due to render caching, you can not rely on it being there, at least not by default).
> 4 votes

---
Tags: 8, paragraphs
---


title: Getting URL alias of a term

text:
# Question
Title: Getting URL alias of a term
I am writing a module, and am confused about the term's URLs. because, if pathauto moduel is installed, then the alias of that module should be provided. How to achieve this?

Default drupal's URL: `taxonomy/term/30` Pathauto's probable pattern:

```
category/30
category/[title]
category/[title]/[id]
...and millions of other possible patte

```

Using `drupal_get_path_alias()` returns drupal's default path.

How should I get the path used by pathauto? I have seen pathauto's module, but it does not provide an API for this purpose as it seems.

# Answer
Just use the `url()` function. It will return aliased path if you have pathauto installed.

Example:

```
$link = url('taxonomy/term/1');

```
> 10 votes

# Answer
You can either use `url()` or `drupal_get_path_alias()` but make sure that your path argument doesn't have leading slash.

Example:

```
drupal_get_path_alias('/taxonomy/term/1');
url('/taxonomy/term/1');

```

Returns path `'/taxonomy/term/1'`

```
drupal_get_path_alias('taxonomy/term/1');

```

Returns `'tags/some-tag'`

```
url('taxonomy/term/1');

```

Returns `'/tags/some-tag'`
> 2 votes

---
Tags: taxonomy-terms, path-aliases
---


# Question
Title: Programmatically render a panels page variant
There is a Page with id: `front_page`, and a number of variants.

I want to programmatically load the page, evaluate the context and render the appropriate variant.

I have the following code to load the page:

```
$page_id = 'featured_content';
$page_storage = \Drupal::entityTypeManager()->getStorage('page');
$variant_storage = \Drupal::entityTypeManager()->getStorage('page_variant');
$page = $page_storage->load($page_id);
// ...

```

How can I build or render the `$page`?

# Answer
Here is how :

```
$page = \Drupal\page_manager\Entity\Page::load('featured_content');
//all variants ids, for the example
$variants = $page->getVariants();
// last variant... could have been $page->getVariant('{VARIANT_ID}');
$pageVariant = end($variants);
$viewer = new \Drupal\page_manager\Entity\PageVariantViewBuilder();
$arr = $viewer->view($pageVariant);
\Drupal::service('renderer')->render($arr);

```
> 3 votes

---
Tags: 8, panels
---


# Question
Title: Check if user registration field is set to visible or hidden on the registration form
In the user registration form, I have set a certain field say surname as hidden i.e. I have unchecked the checkbox saying "Display on user registration form." as shown below:

Now I want to disable the server side validation for this field. When I print the `$form` array, the surname field is still displayed. However I am not able to find any such value in the `$form` array which checks if the value is unchecked or not. **Is there any way to figure out if the said field is not displayed on the registration form?** Hope I am clear enough.

# Answer
If you look at the code of `user_register_form()`, you will notice it uses the following code.

```
  foreach (field_info_instances('user', 'user') as $field_name => $instance) {
    if (empty($instance['settings']['user_register_form'])) {
      $form[$field_name]['#access'] = FALSE;
    }
  }

```

If you are implementing `hook_form_alter()` (or other similar hooks), it's quite easier to look at the #access property. If you need that in other functions, you can use code similar to the following one.

```
  foreach (field_info_instances('user', 'user') as $field_name => $instance) {
    if (empty($instance['settings']['user_register_form'])) {
      // $field_name is not supposed to be added to the account registration form.
    }
  }

```

Clearly, checking for the #access property in a `hook_form_alter()` implementation is the safer method, since it consider the field can be made accessible from third-party modules (or third-party modules can hide a field that should be visible).
The other method is more for getting a specific field setting.
> 0 votes

---
Tags: users
---


# Question
Title: How do I programmatically find the core version?
How do I programmatically find the Drupal core version running a site?

# Answer
> 4 votes
I found this example in MetatagNodeTranslationTest.

To find the drupal version in your code,

```
\Drupal::VERSION

```

will return it.

If you need to compare

```
if (floatval(\Drupal::VERSION) <= 8.3) {
  // do some stuff.
}

```

---
Tags: 8
---