# Question
Title: How to bootstrap a custom script and retrieve the session object?
I'm writing a custom script that requires a proper Drupal 8 user session to work. This is the current version:

```
<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$drupal_root = __DIR__;
define('DRUPAL_DIR', $drupal_root);

// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->handlePageCache($request);
$kernel->prepareLegacyRequest($request);

// get session handler and retrieve session details
$session_handler = \Drupal::getContainer()->get('session_handler.storage');
$session_id = $session_handler->getId();
$logged_in = (bool) $session_handler->read($session_id);

// inspect values
var_dump($request->getSession());
var_dump($session_id);
var_dump($logged_in); exit;

```

I'd expect `$request->getSession()` to return something, `$session_id` to be the Drupal's session id, and the `$logged_in` variable to be truthy. Instead I keep getting this output:

> ```
> NULL string(0) "" bool(false)
>
> ```

---

**Update 1:** I executed this on a browser, which I have an active session with my Drupal. This script is placed in a subfolder of the Drupal installation, so it should not be a cookie path issue.

**Update 2:** Added `var_dump($request->getSession())` to the script.

# Answer
This is the code I came up with in the end. It works.

Feel free to suggest a more concise version :-)

```
<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$drupal_root = realpath(__DIR__ . '/../');
$autoloader = require_once $drupal_root . '/autoload.php';

// Make sure Drupal operates correct when handle request instead of internal server error and twig error
chdir($drupal_root);

$kernel = new DrupalKernel('prod', $autoloader);

// Note: The session_name is generated from the string "{domain}/{script basepath}".
// Need to override the script filename and script name before creating request.
$_SERVER['SCRIPT_FILENAME'] = $drupal_root . '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$request = Request::createFromGlobals();
// Note: may restore script_name and script_filename after this line.

// This handle process would chain up and initialize all services
// in container, include the session handler.
$kernel->handle($request);

// now we can use session normally
$session_handler = \Drupal::getContainer()->get('session_handler.storage');
$session_id = $session_handler->getId();
$logged_in = (bool) $session_handler->read($session_id);

// restore app
chdir(__DIR__);

```
> 1 votes

---
Tags: 8, sessions, bootstrapping
---


# Question
Title: How to allow HTML attribute with namespace using filter
One of the analytics providers requires all the links to have a specific attribute `sc:linkname` to track details. Drupal 8 filter works for `linkname` but not with `sc:` prefix. From https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 it looks like all attributes have default namespace (e.g. href =\> `xlink:href`).

# Answer
> 1 votes
One way to solve this problem is to have a custom filter which processes the `linkname` and convert to `sc:linkname`.

```
<?php

namespace Drupal\my_module\Plugin\Filter;

use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Provides a filter to correct faulty and chopped off HTML.
 *
 * @Filter(
 *   id = "filter_html_attribute_namespace_fixer",
 *   title = @Translation("Add 'sc' namespace to HTML attribute 'linkname'"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE,
 *   weight = 10
 * )
 */
class FilterHtmlAttributeNamespaceCorrector extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    return new FilterProcessResult($this->addNamespace($text));
  }

  protected function addNamespace($text, $namespace = 'sc') {
    $html_dom = Html::load($text);
    $xpath = new \DOMXPath($html_dom);
    foreach ($xpath->query('//a[@*]') as $element) {
      foreach ($element->attributes as $name => $attribute) {
        if ($name == 'linkname') {
          $element->setAttribute('sc:linkname', $attribute->value);
          $element->removeAttribute($name);
        }
      }
    }
    $text = Html::serialize($html_dom);
    return trim($text);
  }

}

```

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


# Question
Title: How can I programmatically import configuration?
I try to import specific configuration. I use this :

```
$config_path = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
$source = new FileStorage($config_path);

$config_storage = \Drupal::service('config.storage');
$config_factory = \Drupal::configFactory();
$uuid_service = \Drupal::service('uuid');

$configs = [
  'field.storage.config_pages.field_areas',
  'field.field.config_pages.configuration_implantation_page.field_areas',
  'core.entity_form_display.config_pages.configuration_implantation_page.default',
  'core.entity_view_display.config_pages.configuration_implantation_page.default',
];

$config_storage->write('field.storage.config_pages.field_areas', $source->read('field.storage.config_pages.field_areas'));
$config_storage->write('field.field.config_pages.configuration_implantation_page.field_areas', $source->read('field.field.config_pages.configuration_implantation_page.field_areas'));
$config_storage->write('core.entity_form_display.config_pages.configuration_implantation_page.default', $source->read('core.entity_form_display.config_pages.configuration_implantation_page.default'));
$config_storage->write('core.entity_view_display.config_pages.configuration_implantation_page.default', $source->read('core.entity_view_display.config_pages.configuration_implantation_page.default'));

```

If the field is created, the table is not created.

How to create the tables associated?

# Answer
You should save the config like `$config_storage->save();` :
As @4K4 mentioned :

> The important thing is not simply store config, but create and save config entities and so run CRUD methods/hooks like https://api.drupal.org/api/drupal/core%21modules%21field%21src%21Entity%21FieldStorageConfig.php/function/FieldStorageConfig%3A%3ApreSave/8.7.x
> 2 votes

---
Tags: 8, configuration
---


# Question
Title: SMTP Authentication Support address/from name overwritten by Site Information
Pretty much as the title says really. I'm using the SMTP Authentication Support module to try and send account notification e-mails through our G Suite account. I've filled in a name and e-mail address in the E-mail Options section, but whenever I send a test mail it arrives from the e-mail address given in Drupal's main Site Information options, and without a from name at all.

How do I get it to display a from name in the e-mails it sends?

Using Drupal 7.67 and SMTP Authentication 7.x-1.7.

# Answer
> 0 votes
So, it turns out that you can't actually send a test though the module without turning the module on for everything. That was the problem. The test e-mail still gets sent if the module is turned off, and arrives with a message saying it was sent through SMTP, but on inspection of the headers it's clear it came through Drupal's regular mail system.

It would be nice if the test system would work independently of everything else, so you could establish if it works before turning it on for everything. Or if there was some warning that the test won't be sent via SMTP if the module's not turned on. But apparently that's not how it works.

# Answer
> 1 votes
You can use the Mail System module to configure how to send different emails.

---
Tags: emails
---


# Question
Title: Show active taxonomy term as title of product category view
Commerce kickstart comes with a view named **Collection products** that shows: a **Collection of products (Product display)**.
In the relationship's tab of this view there are 2 relationships:
1. Product category `field_product_category`
2. Belongs to Collection `field_collection`.
The contextual filter is set to: `Indexed Node: Product category` (`field_product_category`) and the path to this page is *`product_category/%`*.
There is a menu block showing above this view that comes from the same view showing all the category terms as links.
When you click them, you see that the view shows correctly all the products referring to that term.
My problem is that the term that is active (e.g. url: *category/beef*) doesn't show as a title right above the view or in the block.
How can I achieve that?

# Answer
Edit your Contextual filter and you'll see the option to override the title in the section for when the filter argument is present or a default is provided.

You can use tokens from the Replacement patterns section to construct the title text.

Your "menu" is likely also coming from the Contextual filter, set to the "Summary" option.

Another way is to add the title in the Views Header, you can see how it's implemented in the "Taxonomy term" Views.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How can I rewrite a content link and replace spaces with dashes?
In D8, I am struggling to build a link in Views. I keep running into either a missing option or checkboxes ignored.

I have three fields pulled into views:

1. **Content: Title \[hidden\]** .... token is {{ title }}
2. **Content: Resource Type \[hidden\]** .... token is {{ field\_resource\_type }} Pulls values from Taxonomy
3. **Content: Link to Content** .... token is {{ view\_node }}

I want to rewrite the Content: Link to pass variables. So I'm outputting the URL as text

I essentially want: "**{{ view\_node }}?title={{ title }}&type={{ field\_resource\_type }}**

I also want to replace the spaces with dashes, so my end result is: **/resource/article-one-url?title=article-one-title&type=white-paper**

But... if I override the output, and make my own URL, the system ignores if I check the box to Replace spaces with dashes

I do this by first checking "Output this field as a custom link," so that I can see and check the "Replace spaces with dashes" option.

I would try to rewrite the URL in the "Output this field as a custom link" section, but the field I thought was supposed to be there, is not.

UPDATE: I also tried this with a custom text field. Within the field settings I checked "Output this field as a custom link" and put the same tokens in, but this does the same thing. Spaces exist in the url.

# Answer
> 1 votes
The field `Link to Content` can only link to content lol, it doesn't seem you can override the link URL *there* (that is why there is no `Link path` field there, Views interface and features can be confusing at times, you have to know a bit of background to understand the less polished parts).

You should `Exclude from display` the `Link to Content` field, move the `Title` field down so it's the last field, and unhide it.

Then you will be able to contruct what you want using the Title field, using the `Output this field as a custom link` option.

The option `Override the output of this field with custom text` doesn't provide the option to `Replace spaces with dashes`.

Make sure that the `Link to the Content` in the Title field is *not* ticked, and the Formatter is set to Plain text to avoid clashing between different features when Drupal is constructing the output.

---
Tags: views, 8
---


# Question
Title: How can I access individual form elements for theming?
I have overridden the default user login form in Drupal 8 using a different template in my sub theme, but it isn't of much use because when I access it in twig template, all I can do is

```
<form {{attributes}}>
{{children}}
</form>

```

Doing this I get the elements in same order, and there is not lot of modification option. I can put them in container but that is it. I was wondering there was instead a way to call elements like username field, password field individually instead of doing a bulk call using `{{children}}`.

# Answer
That's a case for the new Formdazzle! module.

> ### Drupal form theming with less pain
>
> Theming drupal forms can be difficult and time-consuming. This module provides a set of utilities that make form theming easier.
>
> Currently, this module provides theme suggestions for forms that are much more useful than those provided by Drupal core.
>
> * Theme suggestions for all form elements (including buttons)
> * Theme suggestions for all form element labels
> * All theme suggestions include the form ID and the form element name; e.g. `[element-type]--[form-id]--[form-element-name].html.twig`
>
> While Drupal core only provided these two theme suggestions:
>
> ```
> input.html.twig
> input--textfield.html.twig
>
> ```
>
> Formdazzle adds the following two theme suggestions to the list:
>
> ```
> input--textfield--webform-contact-form.html.twig
> input--textfield--webform-contact-form--first-name.html.twig
>
> ```
> 1 votes

---
Tags: 8, theming, forms
---


title: hamburger menu moved after update

text:
# Question
Title: hamburger menu moved after update
We use we-mega-menu. After performing an update the mobile (hamburger) menu changed its alignment to the left as well as some other things I was able to fix the other things but I can't seem to figure out how to align the menu to the right within the container. Any ideas?

# Answer
> 1 votes
Looks like that styling is being driven by the flex display on `div.region-we-mega-menu`. Creating a style that overrides `justify-content: flex-start;` to `justify-content: flex-end;` should do the trick.

---
Tags: theming, navigation
---


# Question
Title: The security danger of publicly exposing an upload field
On older drupal 7 websites I once faced security patches for the webform module, because file upload fields were considered insecure. There was en exploit where people could end up uploading .html files (via ajax) to your files storage and started spamming to those links.

I'm currently working on a drupal 8 project where anonymous users can fill in a form and upload their resume in a file field. I chose to create a content type and a custom form mode. Now the form is shown in a custom controller on the site.

**My questions**:

* How (un)safe is the public exposure of a file upload field?
* Are you aware of any steps taken in drupal 8 to further secure this?
* Any suggestions to do this even more securely?

Thanks in advance.

# Answer
Drupal places an .htaccess file in the files directory to prevent files inside from being executed. Check the status report on your site to ensure that this is correctly configured.
> 1 votes

---
Tags: forms, files, security
---


title: Block not showing input fields

text:
# Question
Title: Block not showing input fields
I have a block as part of my custom module, I was it to show 2 text boxes (Input & Output) and have a generate button. I cant get it to show the input boxes! It seems they are being stripped out for some reason? I have tried with and without twig but my example below is without twig to keep it simple:

```
    <?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Block\GenerateBlock.
 */

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'generateblock' block.
 *
 * @Block(
 *   id = "generate_block",
 *   admin_label = @Translation("Generate Code"),
 *   category = @Translation("mymodule")
 * )
 */
class generateblock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    // $twig = \Drupal::service('twig');
    // $template = $twig->loadTemplate(drupal_get_path('module', 'mymodule') . '/templates/generatecode.html.twig');
    // $output = $template->render([]);
    $output='<div id="GenerateCodeBox" class="featured-boxes featured-boxes-style-8">
    <div class="col-md-12">
    <div class="featured-box featured-box-primary featured-box-text-left" style="height: 301px;">
    <div class="box-content">
    <div class="row">
    <div class="col-md-9">
    <h2>Generate <strong>Access Code</strong></h2>
    </div>

    <div class="col-md-3">
    <div class="align-right">
    <h2><i class="fa fa-twitter"></i></h2>
    </div>
    </div>
    </div>

    <div class="row">
    <div class="col-md-12">
    <div class="input-group">
    <input class="form-control" id="codeToCheck" placeholder="Enter Input" type="text" value="" /> <span class="input-group-btn" id="generateMe"><button class="btn btn-default mr-xs mb-sm" type="button">Set</button>
    </span>
    </div>

    <div class="input-group"><input class="form-control" id="validationCode" placeholder="" readonly="readonly" type="text" value="" /> <span class="input-group-btn" id="copyCode"><button class="btn btn-default mr-xs mb-sm" type="button">Copy</button></span></div>
    <a class="btn btn-lg btn-primary mr-xs mb-lg" href="#" type="button">Learn More</a></div>
    </div>
    </div>
    </div>
    </div>
    </div>';

    return array(
      '#type' => 'markup',
      '#markup' => $output,
    );
  }

}

```

I do not know why the inputs are being stripped out? What am i missing

\**** Update \****

I have changed my code to the following and it is no longer stripping out the input boxes but it feels a bit "hacky" Do I need to specify a different render type or something:

```
class AccessCode extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $twig = \Drupal::service('twig');
    $template = $twig->loadTemplate(drupal_get_path('module', 'mymodule') . '/templates/accesscode.html.twig');
    $output = $template->render([]);

    return array(
      '#markup' => $output,
      '#allowed_tags' => ['input','span','div','a','button','h2','strong','i',],
    );
  }

```

# Answer
try to follow best practises: as no need to render anything on your get the twig template as drupal core handles this.

module structure:

mymodule

* mymodule.module
* mymodule.info.yml
* mymodule.libraries.yml
* templates (dir) -- templates/accesscode.html.twig
* src (dir) -- src/Plugin/Block ----- AccessCode.php

in mymodule.module

```
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
    return [
      'accesscode_block' => [
        'variables' => [
          'test' => null,
         ],
         'template' => 'accesscode',
//no need for full accesscode.html.twig as drupal knows.
      ],
    ];
}

```

then in your src/Plugin/Block/ AccessCode.php

```
 /**
 * {@inheritdoc}
 */
public function build() {
  $build = [];
  $build['my-block'] = [
      '#theme' => 'accesscode_block',
      '#test' => 1234,
  ];
  // Attach js or css easier.
  $build['#attached']['library'][] = 'mymodule/mymodule-accesscode';

// Could even add a form element like ..
 $build['some_field'] = [
   '#type' => 'textfield',
   '#title' => 'My Field:',
 ];
  return $build;
}

```

then in your accesscode.html.twig you can use the twig var {{test}}
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: Rename "-none-" option for select list field type
I have several list fields, one of which is a list (text) field. The default value for the form, where no value is stored if nothing is selected, is "-None-". Is there some way to alter this to say "-Select-" instead? The reason is that in the context of the field, the option of "-None-" doesn't make any sense. In this particular field, one of the actual selections being stored in the database is "None". Here's images of a few fields where -None- doesn't make any sense.

So, is there any way to change these aside from making them required fields?

# Answer
> 1 votes
Have you tried to override the default translation string? It can either be done by editing settings.php or with the module "String Overrides"

Here are some instructions for settings.php here, or download String Overrides

# Answer
> 10 votes
Implement hook\_form\_alter() or hook\_form\_FORM\_ID\_alter() and use the following code:

```
$form['field_name'][LANGUAGE_NONE]['#options']['_none'] = t('Select');

```

example:

```
function MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    $form['field_name'][LANGUAGE_NONE]['#options']['_none'] = t('Select');
}

```

The () function is for translation. It may not be required, but it is good practice to use instead of hard-coded strings.

To remove - None - as a choice all together, you could unset the key using hook\_form\_alter as well.

example:

```
function MODULE_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    unset($form['field_name'][LANGUAGE_NONE]['#options']['_none']);
}

```

If you're not using it already, be sure to install the Devel module so you have access to the dpm() and dd() functions. They are incredibly valuable when playing with Drupal forms.

# Answer
> 5 votes
You can override the theme\_options\_none theme function. Follow the example from the Drupal API. If you want to replace "- None -" with "- Select -" everywhere, this theme implementation should do the trick:

```
/**
 * Returns HTML for the label for the empty value for options that are not required.
 *
 * The default theme will display N/A for a radio list and '- None -' for a select.
 *
 * @param $variables
 *   An associative array containing:
 *   - instance: An array representing the widget requesting the options.
 *
 * @ingroup themeable
 */
function MYTHEMENAME_options_none($variables) {
  return t('- Select -');
}

```

Place this function in your theme's `template.php`.

# Answer
> 3 votes
In Drupal 8, this worked for me:

```
  $form['field_name']['widget']['#options']['_none'] = t('- Select -');

```

Re: @Citricguy's answer, as I understand it since then:

* LANGUAGE\_NONE was changed to LANGUAGE\_NOT\_SPECIFIED
* LANGUAGE\_NOT\_APPLICABLE and LANGUAGE\_MULTIPLE were also added
* they were all then renamed from LANGUAGE\_\* to LANGCODE\_\*

This means you do something like:

```
use Drupal\Core\Language\Language;
$form['field_name'][LANGCODE_NOT_SPECIFIED]['#options']['_none'] = ...

```

…however I couldn't get that to work with hook\_form\_alter(): the actual values of those constants are three letter alphanumeric codes which don't appear to exist in the form field array.

So I reverted to the line at the top of my answer. If anyone can clear that up...?

# Answer
> 2 votes
If you already have some jquery/javascript included in your system, eg a custom theme or module, you can add something like:

```
$('select option:contains("- None -")').text("- Select -");

```

and it will change it up for you. You can cascade more in there if you want to be specific to just a certain select/option as the above will change all of them.

Otherwise, on the php side of things, the `- None -` is passed through `t('- None -')` so you could use one of the many localize or customtext modules to change the text, but this would be systemwide as well.

# Answer
> 0 votes
Implement hook\_form\_alter() or hook\_form\_FORM\_ID\_alter() and identify the dropdown field and add this:

e.g.

```
$form['field_name'][$form['field_name']['#language']]['#options']['#empty_option'] = t('- Select -');

```

The key thing is to set the #empty\_option attribute on your select list.

# Answer
> 0 votes
Similar to Drupal 7's theme\_options\_none(), Drupal 8 actually has hook\_options\_list\_alter() that can be used to accomplish this task.

```
function MY_MODULE_options_list_alter(array &$options, array $context) {
  if ($context['fieldDefinition']->getName() === 'field_option') {
    $options['_none'] = t('- Select -');
  }
}

```

> Note: this alter is only invoked in modules; this will not work in a theme (theme alter isn't invoked). Also, the API documentation uses `$context['fieldDefinition']->id()` and will not match against just a field name. This is the config identifier and is prepended with the entity type. Instead, you should use `$context['fieldDefinition']->getName()` which actually returns the field name.

---
Tags: entities
---


# Question
Title: How to override the default search block and make a button with Font Awesome?
I want to override the default search block of Drupal and create a button like the image below:

However, I do not know how to do it. I have tried using **hook\_form\_alter** as well but it is not working:

```
function hook_form_search_block_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#value'] = html_entity_decode('');
  $form['actions']['submit']['#attributes']['class'][] = 'search-button';
}

```

I wanted to know if there is a way to make these changes. I am still quite new to Drupal so I'm a bit lost and confused about these types of things. Any kind of help would be greatly appreciated

# Answer
why not Learn how to make a custom block

as the search form only post to "/search/node?keys=SEARCHTERM" so this will be easy to do:

lets first point you in the direction of making a block read - https://www.webwash.net/programmatically-create-block-drupal-8/ or google "drupal 8 create block programmatically"

or if you have Drupal console (https://drupalconsole.com/) installed you can just run

"drupal generate:plugin:block"

Now lets also learn how to make a custom twig template file to use in your block

see Block not showing input fields

here showing the basic structure of the module

```
mymodule (dir)
 - mymodule.module
 - mymodue.info.yml
 - templates (dir)
 -- mymodule-my-search-form.html.twig
 - src (dir)
 -- Plugin (dir)
 --- Block (dir)
 --- MySerchForm.php
(aka mymodule/src/Plugin/Block/MySerchForm.php)

```

in your blocks (mymodule/src/Plugin/Block/MySerchForm.php) build method:

```
/**
 * {@inheritdoc}
 */
public function build() {
   $build = [];
   $build['my_search_form'] = [
     '#theme' => 'my_custom_search_form',
   ];
   return $build;
}

```

then in your module file (mymodule/mymodule.module)

```
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'my_custom_search_form' => [
      'variables' => [],
      'template' => 'mymodule-my-search-form'
    ],
  ];
}

```

Then in your template file (templates/mymodule-my-search-form.html.twig)

```
<form action="/search/node" method="get">
  <input type="text" name="keys">
  <input type="submit" value="Submit">
</form>

```

then style the heck out of it ... aka google "how to add css in drupal 8 module how to add css in module"

hint, add a file "mymodule.libraries.yml" (mymodule/mymodule.libraries.yml) add a css file (mymodule/css/mymodule.css)

in mymodule.libraries.yml

```
mymodule-search-form:
  version: 1.x
  css:
    theme:
      css/mymodule.css: {}

```

then in your block

```
$build['#attached']['library'][] = 'mymodule/mymodule-search-form';

```

clear cache lots

with all the above should put you on the right path figuring out a heck of alot more then just changing a search block :)
> 1 votes

---
Tags: theming, search
---


# Question
Title: How to access to form field in views-exposed-form.html.twig (exposed filters)
I am trying to customize the template for the exposed filters of a view.

I have created the `views-exposed-form.html.twig` and Drupal loads it fine, following How do I theme exposed filters?.

For now, I have the standard code:

```
/**
 * @file
 * Theme override of a views exposed form.
 *
 * Available variables:
 * - form: A render element representing the form.
 *
 * @see template_preprocess_views_exposed_form()
 */
#}
{% if q is not empty %}
  {#
    This ensures that, if clean URLs are off, the 'q' is added first,
    as a hidden form element, so that it shows up first in the POST URL.
  #}
{{ q }}
{% endif %}
{{ form }}

```

and that works fine. Nevertheless, if I try to show only one field of the form (e.g., `{{ form.field_city }}`) nothing is shown in the filter block, though the page loads fine and there are no apparent errors.

I am working with Drupal 8.7.7 and PHP 7.3.9.

Any help will be more than welcome.

Thank you in advance.

# Answer
Solved. The problem seems to be an incompatibility with Better Exposed Filters module.

Thanks!
> 0 votes

---
Tags: views, theming
---


title: Installation issue (drush problem?)

text:
# Question
Title: Installation issue (drush problem?)
I was trying to install Aegir following the Automatic install guide, but I get an error. I've tried to install Aegir 2, then tried also Aegir 3, but the error is the same. Any clues?

Here's the message:

> The following settings will be used: Aegir frontend URL: site.dev.local Master server FQDN: site.dev.local Aegir root: /var/aegir Aegir user: aegir Web group: www-data Web server: apache Web server port: 80 Aegir DB host: localhost Aegir DB user: root Aegir DB password: Aegir DB port: 3306 Aegir version: 7.x-3.x Aegir platform path: /var/aegir/hostmaster-7.x-3.x Admin email: aegir@site.dev.local
>
> Aegir install profile: hostmaster
>
> Do you really want to proceed with the install (y/n): y Enabling hosting-queued daemon
>
> The drush command '@hostmaster pm-enable hosting\_queued' could not be found. Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions. \[error\] A Drupal installation directory could not be found \[error\]
>
> dpkg: error processing package aegir3-hostmaster (--configure): subprocess installed post-installation script returned error exit status 1 dpkg: dependency problems prevent configuration of aegir3: aegir3 depends on aegir3-hostmaster (\>= 3.0.1); however: Package aegir3-hostmaster is not configured yet.
>
> dpkg: error processing package aegir3 (--configure): dependency problems - leaving unconfigured No apport report written because the error message indicates its a followup error from a previous failure. Errors were encountered while processing: aegir3-hostmaster aegir3 E: Sub-process /usr/bin/dpkg returned an error code (1)

Thanks!

# Answer
> 1 votes
The most common problem that could cause this is a broken mail setup.

Please the if you can sent an email from the server's cli to aegir@site.dev.local

# Answer
> 0 votes
Ran into this today, here's how I solved it:

**Set `-x` in the script which is failing.**

You can do this by editing the `.postinst` script, eg `/var/lib/dpkg/info/aegir3-hostmaster.postinst` in my situation. Replace `#! /bin/sh` with `#! /bin/sh -x` at the top of the script; when executed, the postinst script will then print out each line as it's executed.

**Set `DPKG_DEBUG=developer`.**

```
export DPKG_DEBUG=developer

```

This will activate debug output in various script commands.

**Re-run the installation.**

For me, this was `dpkg --configure --pending` as I'd already attempted to install the package and it had failed during configuration.

**Read the output.**

Seems obvious, but the first couple times I didn't read back far enough, and there *was* a useful error message further up.

In my case (quite possibly not yours, dear reader), the issue was that the permissions of `/var/aegir/platforms` in my Vagrant environment did not permit the aegir user to create the directory to install its hostmaster install. Thus no `@hostmaster` alias, no way to enable `hosting_queued`, and an error message which didn't clearly point to a resolvable situation.

**Fix the root problem.**

This will vary, as the error in this question is associated with many different causes documented across the internet, including:

* MySQL validate password plugin not accepting the generated password. (Generate a better password, or reconfigure / disable that plugin.)
* The aegir hostname not being resolvable, so the site being inaccessible. (Add the aegir hostname in `/etc/hosts`)
* Filesystem permissions preventing installation. (Make sure aegir owns the platforms directory.)

HTH

---
Tags: aegir
---


# Question
Title: Block won't appear on specific language pages
I have a view with a filter to show entries based on chosen language (Configure filter criterion: Content: Translation language = Interface text language selected for page). The view is placed into a block, and that block is set to show for all languages. The block's placement is restricted to the page node and all its translations, for example /node/1234, /company, /empresa, and /enterprise.

Then when I go to some of the pages, it doesn't show. It's only appearing for Global default language and ES-US, randomly. French and US English it doesn't appear for, even though the alias is exactly what I've got: /company and /enterprise.

I cannot, for the life of me see any reason this should be happening. Every setting I know of is set, and the exact same thing is working for every other block I've set up like this.

# Answer
Disregard the question above. After my 'frustration post' I realized the most obvious thing. It wasn't Showing French because I didn't have French translations... I had FR-CA - French CANADIAN translations.

Doh!
> 0 votes

---
Tags: views, 8
---


title: How to decrypt the password?

text:
# Question
Title: How to decrypt the password?
I want to decrypt the password by drush in drupal . is there any way for decrypt it or i have to decrypt with some command or use php code to solve it?

# Answer
Passwords cannot be decrypted, as they are not encrypted. Passwords are hashed. They are different processes.

Encryption encodes data using a key, that can later be used to decrypt the data. The encrypted data is scrambled, and can later be unscrambled.

Hashing encodes the data, but it is one way. The data cannot be unscrambled. There is no way to find out the unscrambled data.

This may seem like it makes it useless - if you cannot unscramble the data, how could it be used? Well, the hashing process, the 'scrambling' as it were, is consistent. Any given input will always give the same output every time it is used. So the password is hashed, and stored in the database. When users log in, the password they enter is hashed, and that value is compared to the hashed value stored in the database, to see if they are the same. Since the hashing process always produces the same output for a given input, if the user enters the same password they entered when creating their account, the hashed values will be equal, allowing the system to determine that the user has entered the correct password.
> 3 votes

# Answer
No. Its not possible to decrypt. Only possible to change passwords with:

drush user-password USERNAME --password="password"
> 1 votes

---
Tags: drush
---


title: Form rebuild without using buttons

text:
# Question
Title: Form rebuild without using buttons
I'm trying to figure out how to rebuild a form without using a button click trigger. Instead, I'm looking to rebuild whenever a blur event occurs on a textfield. All non-button form types lack the #submit value. It doesn't seem possible to trigger a form rebuild with `$form_state['rebuild'] = TRUE;` unless the submit callback is triggered. Demo code below.

```
function test_form($form, &$form_state) {
  $form['form_wrapper'] = array(
    '#prefix' => '<div id="form_wrapper">',
    '#suffix' => '</div>',
  );

  if (isset($form_state['textfield_vale'])) {
    $textfield_vale = $form_state['textfield_vale'];
  }
  else {
    $textfield_vale = 'not set';
  }

  //will not trigger page rebuild
  $form['form_wrapper']['test_textfield'] = array(
    '#type' => 'textfield',
    '#value' => 'Value = '.$textfield_vale,
    '#ajax' => array(
      'callback' => 'test_result',
      'wrapper' => 'form_wrapper',
      'event' => 'blur',
     ),
  );

  //will trigger page rebuild, changing the textfield value
  $form['form_wrapper']['trigger_rebuild'] = array(
    '#type' => 'submit',
    '#value' => 'I don\'t want to press it',
    '#submit' => array('submit_rebuild'), //has #submit value unique to buttons
    '#ajax' => array(
      'callback' => 'test_result_with_button',
      'wrapper' => 'form_wrapper',
    ),
  );

  return $form;
}

function test_result($form, &$form_state) { //unable to set $form_state['rebuild'] = TRUE
  $form_state['textfield_vale'] = 'textfield trigger'; //TRUE;
  $form_state['rebuild'] = TRUE;
  return $form['form_wrapper'];
}

function submit_rebuild($form, &$form_state) {
  $form_state['textfield_vale'] = 'button trigger'; //TRUE;
  $form_state['rebuild'] = TRUE;
}

function test_result_with_button($form, $form_state) {
  return $form['form_wrapper'];
}

```

Is there a way to trigger a form rebuild without clicking a button (perhaps with an ajax command)? Alternatively, how can I change my code to allow an ajax callback to change $form\_state values?

# Answer
> 0 votes
I've found that jQuery can be used to click a Drupal submit button (source). I can use an event listener to trigger a submit event by interacting with a specific button that can be hidden anywhere on the form. Below is my solution based off of my original demo code.

```
<?php

function test_form($form, &$form_state) {
  drupal_add_js('
(function ($) {
  Drupal.behaviors.test_form = {
    attach: function() {
      $("#test_textfield").blur(function() {
        $("#trigger_rebuild").mousedown();
      });
    }
  }
}(jQuery))', 'inline');

  $form['form_wrapper'] = array(
    '#prefix' => '<div id="form_wrapper">',
    '#suffix' => '</div>',
  );

  if (isset($form_state['textfield_vale'])) {
    $textfield_vale = $form_state['textfield_vale'];
  }
  else {
    $textfield_vale = 'not set';
  }

  //will not trigger page rebuild
  $form['form_wrapper']['test_textfield'] = array(
    '#type' => 'textfield',
    '#value' => 'Value = '.$textfield_vale,
    '#id' => 'test_textfield',
  );

  //will trigger page rebuild, changing the textfield value
  $form['form_wrapper']['trigger_rebuild'] = array(
    '#type' => 'submit',
    '#value' => 'I don\'t want to press it',
    '#id' => 'trigger_rebuild',
    '#submit' => array('submit_rebuild'), //has #submit value unique to buttons
    '#ajax' => array(
      'callback' => 'test_result_with_button',
      'wrapper' => 'form_wrapper',
    ),
  );

  return $form;
}

function submit_rebuild($form, &$form_state) {
  $form_state['textfield_vale'] = 'button trigger'; //TRUE;
  $form_state['rebuild'] = TRUE;
}

function test_result_with_button($form, $form_state) {
  return $form['form_wrapper'];
}

```

# Answer
> 0 votes
I've always handled changing form values in the form build or form\_alter function itself. I can't remember where I saw to do this, but I've never been able to alter the form in the ajax callback itself.

Have your form trigger an ajax callback. This should return the form or piece of the form in question, like your `test_result_with_button()` function.

When an ajax callback is triggered, the build method and alters are run again. Add logic in your build / form\_alter to make updates to the form or form\_state based on whichever action was triggered. Information about how the rebuild was triggered will be available in $form\_state\['triggering\_element'\].

---
Tags: 7, forms, ajax
---


title: Adding checkbox in admin table display

text:
# Question
Title: Adding checkbox in admin table display
I'm trying to add a checkbox column in the admin table part of my module. The idea is to add checkboxes at the beginning of each row, like in the normal admin content management form.

My table is build in a form function with the following code :

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

$query = db_select('form_xml', 'f');
$query->join('form_xml_status', 's', 's.id = f.id');
$query->join('users', 'u', 'u.uid = f.uid');
$result = $query
        ->condition('s.status', 'todo', '=')
        ->fields('f')
        ->fields('u', array('name'))
        ->execute()
        ->fetchAll();

$header = array(
array('data' => t('ID')),
array('data' => t('Name')),
array('data' => t('User')),
);

foreach($result as $key){
$rows[] = array(
array('data' => t($key->id)),
array('data' => t($key->name)),
array('data' => t($key->user))
);
}

$form['table'] = array(
'#type' => 'tableselect',
'#header' => $header,
);

$output = theme('table', array('header' => $header, 'rows' => $rows));
$output .= $form;

return $output;

}

```

My tableselect doesn't display at all, but "Array" appears at the bottom of the table. Is it possible to add checkboxes in a table like this ?

# Answer
> 0 votes
Although there's actually no question, I've noted the last part of your code should look like:

```
<?php

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $rows,
);

return $form;

```

# Answer
> 0 votes
I have worked on some similar script using Drupal 8 version I was working on some same sort of code where I wanted to output a listing of nodes after form submit and the listing should have checkbox in each row.

```
$form['mytable'] = array(
    '#type' => 'table',
    '#title' => 'List of Nodes',
    '#header' => ["Checkbox","Title","Author"],
);

$nids = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
$nids = array_keys($nodes);

// Add input fields in table cells.
$i=0;
foreach($nids as $nid)
{

  $node = \Drupal\node\Entity\Node::load($nid);
  $contenttitle=$node->title->value;
  $receivername = $node->getOwner()->getDisplayName();
  \Drupal::entityManager()->getStorage('node')->resetCache(array($nid));

    $form['mytable'][$i][''] = array(
                                        '#type' => 'checkbox',
                                        '#return_value' => $nid,
                                    );

    $form['mytable'][$i]['Title'] = array(
                                        '#type' => 'label',
                                        '#title' => t($contenttitle),
                                    );
    $form['mytable'][$i]['Author'] = array(
                                        '#type' => 'label',
                                        '#title' => t($receivername),
                                    );
    $i++;
}
// Add a submit button that handles the submission of the form.
$form['actions']['submit'] = [
                                '#type' => 'submit',
                                '#value' => $this->t('Submit'),
                            ];
return $form;

```

Hope that Helps.

---
Tags: theming, forms
---


# Question
Title: How to pass multiple values in setArguments() and render view?
I want to pass multiple values in setArguments() and render view. I'm using below code but it's showing only 1 value instead of multiple.

```
 public function _ajax_generate_request_view(array $form, FormStateInterface $form_state) {
  $view = \Drupal\views\Views::getView('play_center_generate_request');
  $view->setArguments(array('23','46'));
  $view->execute();
  $render_view = $view->render();
  $ajax_response->addCommand(new HtmlCommand('#view_wrappers', $render_view));
  return $ajax_response;
}

```

# Answer
Depends if you need OR or AND clause :

```
$view->setArguments(array('23,46'));
$view->setArguments(array('23+46'));

```

One string for each argument.
> 4 votes

---
Tags: views, 8
---


# Question
Title: AJAX form doesn't use ajax until cache clear
I'm defining an ajax form in my custom module (#ajax for submit). It is shown in custom block. But it works fine only on cache clear (on Drupal clear all caches or on ctrl+r in chrome). If I just use a link in navbar to navigate to another page or insert an url to browser my ajax callback stops being used. If I ctrl+r it starts working. I thought it's a cache issue but any cache disabling (form or block) doesn't take an effect. Please help.

UPD:

Here is the code for the form:

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

    // Add a wrapper div that will be used by the Form API to update the form using AJAX
    $form['#prefix'] = '<div id="my_ajax_form">';
    $form['#suffix'] = '</div>';
    $form['#disable_inline_form_errors_summary'] = TRUE;
    $form['#cache'] = ['max-age' => 0];
    $form['#cache']['contexts'][] = 'session';

    $form['left'] = [
        '#type' => 'fieldset',
        '#prefix' => '<div class="group-left">',
        '#suffix' => '</div>',
    ];
    $form['left']['image'] = [
        '#type' => 'item',
        '#markup' => '<img src="some img url"
            class="my-form-image" alt="image">',
    ];

    $form['right'] = [
        '#type' => 'fieldset',
        '#prefix' => '<div class="group-right">',
        '#suffix' => '</div>',
    ];
    $form['right']['headline'] = [
        '#type' => 'item',
        '#markup' => $this->t('some text1'),
    ];
    $form['right']['description'] = [
        '#type' => 'item',
        '#markup' => $this->t('some text2'),
    ];
    $form['right']['first_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('First Name'),
    ];
    $form['right']['last_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Last Name'),
    ];
    $form['right']['email'] = [
        '#type' => 'email',
        '#title' => $this->t('Email address'),
    ];
    $form['right']['cta'] = [
        '#type' => 'item',
        '#markup' => $this->t('some text3'),
    ];
    $form['right']['actions'] = [
        '#type' => 'actions',
    ];
    // Add a submit button that handles the submission of the form.
    $form['right']['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('SUBMIT'),
        '#attributes' => [
            'class' => [
                'myCustomBehavior',
            ]
        ],
        '#ajax' => [
            'wrapper' => 'my_ajax_form',
            'callback' => '::submitCallback',
            'event' => 'click',
            'progress' => [
                'type' => 'none',
            ],
        ],
    ];

    return $form;
}

/**
 * Validate the title and the checkbox of the form
 *
 * @param array $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *
 */
public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    $first_name = $form_state->getValue('first_name');
    if (empty($first_name)) {
        // Set an error for the form element with a key of "first_name".
        $form_state->setErrorByName('first_name', $this->t('Please enter your first name'));
    }

    $last_name = $form_state->getValue('last_name');
    if (empty($last_name)){
        // Set an error for the form element with a key of "last_name".
        $form_state->setErrorByName('last_name', $this->t('Please enter your last name'));
    }

    $email = $form_state->getValue('email');
    if (empty($email)){
        // Set an error for the form element with a key of "email".
        $form_state->setErrorByName('email', $this->t('Please enter your email'));
    }
    else {
        $connection = \Drupal::database();
        $query = $connection->select('my_table', 'm')
            ->condition('m.email', $email, '=')
            ->fields('m', ['email']);
        $count = $query->countQuery()->execute()->fetchField();
        if (0 != $count) {
            $form_state->setErrorByName('email', $this->t('This email already exists.'));
        }
    }
}

/**
 * Form submission handler.
 *
 * @param array $form
 *   An associative array containing the structure of the form.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
    $field = $form_state->getValues();
    $field_arr = [
        'first_name' => $field['first_name'],
        'last_name' => $field['last_name'],
        'email' => $field['email'],
    ];
    $query = \Drupal::database();
    $query->insert('my_table')
        ->fields($field_arr)
        ->execute();
    $form_state->setRebuild(TRUE);
}

/**
 *  Ajax callback for the form submit
 */
public function submitCallback(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    if (!$form_state->hasAnyErrors()) {
        $form['right']['#prefix'] = '<div class="group-right group-right-processed">';
        $form['right']['headline']['#markup'] = $this->t('<h1 class="my-form-headline">thank you</h1>');
        $form['right']['description']['#markup'] = $this->t('some text4');
        unset($form['right']['first_name'], $form['right']['last_name'], $form['right']['email'], $form['right']['cta'], $form['right']['actions']);
        $response->addCommand(new ReplaceCommand(NULL , $form));

        return $response;
    }
    else {
        $form_state->setRebuild();
        return $form;
    }
}

```

Here is the code for the block:

```
public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm');
    return $form;
}

public function getCacheMaxAge() {
    return 0;
}

```

# Answer
Actually, @Kevin was almost right. There was the search form that does not use AJAX but somehow Drupal gave the same id to both submit buttons (it was edit-submit--2. Is it a Drupal core bug?). So I had to gave custom id to my submit button and now it works fine.
> 2 votes

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


title: Hook theme path to template in a folder

text:
# Question
Title: Hook theme path to template in a folder
For my template I need to point to a subfolder in templates folder: templates/sub-folder/my-wall1.html.twig, the file is there, but nothing works.

What are the rules?

1. translate minus (-) to underscore (\_)
2. ...

```
function my_module_theme() {
  return [
    'wall1' => [
      'template'  => 'sub_folder/my_wall1',
      'variables' => [
        'w1' => NULL
      ],
    ],
  ];
}

```

Update: According to the answers, I tried the following:

1. test/test.html.twig \< does not work
2. test.html.twig \< works, without subfolder and a name like this

An example or point to documentation would be great too?! Thanks.

# Answer
> 1 votes
Drupal uses filenames only for theme suggestions `'template' => 'my_wall1'`. But you can still place the template in a subfolder below `templates` and Drupal will still discover it.

Not tried this myself, but according to hook\_theme() documentation: You can add a drupal root relative `path` if you want a very specific directory for the Twig file:

```
function my_module_theme() {
  return [
    'wall1' => [
      'template'  => 'my_wall1',
      'variables' => [
        'w1' => NULL
      ],
      'path' => 'DRUPAL_ROOT_RELATIVE_PATH'
    ],
  ];
}

```

# Answer
> 0 votes
According to the documentation:

**path:** Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.

**template:** If specified, the theme implementation is a template file, and this is the template name. Do not add 'html.twig' on the end of the template name. The extension will be added automatically by the default rendering engine (which is Twig.) If 'path' is specified, 'template' should also be specified. If neither 'template' nor 'function' are specified, a default template name will be assumed. For example, if a module registers the 'search\_result' theme hook, 'search-result' will be assigned as its template name.

So if your file is called my-wall1.html.twig you just need to pass my-wall1 as template value in your return array. And you can specify the path relative to the root directory so it should be something like this: `/modules/custom/my_module/templates/sub_folder`.

---
Tags: theming
---


title: Content appearing under specific tabs

text:
# Question
Title: Content appearing under specific tabs
My site will be divided into multiple areas, or tabs, for example, Music, Politics, News, etc. Under each tab I'd like to display a different sidebar (my sidebar will contain menus representing categories, for example, in the Music tab, the sidebar should show Rock, Classical, Jazz, but in the News tab it should show National, International, Sport, etc). I'm hoping that all my content could be of the same content type, but that they exist under one tab or another.

How should I set this up? So far I have tried similar content types, one for each tab, and a theme for that type which shows the appropriate sidebar. But it'd be nicer to use just the one content type overall, with a field indicating which tab it belongs to. Is that possible?

# Answer
A multi-level taxonomy could accomplish this for you. Something like:

* Music
    + Rock
    + Classical
    + Jazz
* Politics
* News
    + National
    + International
    + Sport

Create this, and then add a field for it on your single content type. Then use the Taxonomy Menu module to create a menu from your taxonomy, and the Menu Block module to place both a top level navigation, and the sidebar navigation. You can adjust what level the menu starts at for this.

Your taxonomy menu will link to each taxonomy term listing page, which is a default view. Further, if you setup URL aliases for your taxonomy, and then rebuild links, each page will have a meaningful URL (home/news/international). You can take it a step further by adding URL aliases for your content type as well, and use the taxonomy term path in that so you end up with (home/news/international/title-of-article).
> 3 votes

---
Tags: theming
---


# Question
Title: what are the css files with question marks - like modules/system/system.theme.css?pywps6u?
I am new here, starting to find my way around a Drupal site I inherited. I am trying to work out if I can safely ignore all the @import css files with question marks like `system.theme.css?pywps6u` . I notice that the appended string of letters changes every so often, and I assume this is resulting from the caching.

What's going on here and can I safely ignore these files and just edit the normal files with standard filenames like MyStyleSheet.css?

# Answer
> I assume this is resulting from the caching

You are correct. It is for caching; especially to prevent browsers from thinking they have already downloaded a certain file.

If the file was named `system.theme.css`, and your browser already downloaded that file several days ago, it won't download it again. This results in an outdated site. The suffix changes every time the CSS files change and forces your browser to download the file again.

You can safely edit the 'regular' CSS files on the filesystem. Take care though that is discouraged to edit system and module files, as they will be overridden during updates. Instead create a custom module or theme to implement the changes you need.
> 2 votes

---
Tags: theming
---


# Question
Title: Combining Date Start and Date End in Drupal 8 Views Block
I am new to Drupal 8 Views - How do you concatenate Event Start Date Sept 1, 2019 with Event end Date ie: Sept 4, 2019? The end result is they just want the Month and Day to show up like this Sept 1-4.

# Answer
> 0 votes
You can create a custom field formatter plugin for the `daterange` field type and you can use it at other places on the website too.

---
Tags: views, theming, datetime
---


# Question
Title: Print Title, Header and in Different divs
I have created a view and called content types `events` from FILTER CRITERIA , created template `page--events.html.twig` to override design. Problem is here I have called `{{ page.content }}` which prints header, content and other footer parts eg: bread crumb so I want to call them in different div like header in other `div`

# Answer
> 0 votes
A simple solution to this would be to create a new view, with a block display, and add a contextual filter to get the current node ID from the url. Then select a field you would like and add it to the view, for example; "Header". Once you've done that then save.

Visit the "Blocks" admin page and add the block to the "Header" region of your page. Your theme should already have these. Restrict the block to display only for that content type, and then repeat this whole process for your footer field.

There are more dynamic solutions, I'm partial to Display Suite these days, something to think about if your looking to make more complex displays.

---
Tags: views, 8
---


title: How do I load an entity?

text:
# Question
Title: How do I load an entity?
How can I load the entities shown in the following screenshot?

# Answer
Use loadMultiple():

```
$storage = \Drupal::entityTypeManager()->getStorage('default_entity');
$config_entities = $storage->loadMultiple();
$list = [];
foreach ($config_entities as $id => $entity) {
  $list[$id] = $entity->label();
}

```
> 1 votes

---
Tags: entities
---


title: Search using view and facet as block

text:
# Question
Title: Search using view and facet as block
In my project I need facet search as block view that need to be included in content region. So I created View as block and added facet block in header of the view. Also need infinite scroll, so enabled ajax in view. So issue is that facet search ajax and View ajax causing conflict so that the query parameters are duplicating in URL.

http://localhost.com/sample-page?q=/sample-page?q=/sample-page?filter\[0\]=category\_filter:171&\_wrapper\_format=drupal\_ajax&filter\[0\]=category\_filter:171&filter\[1\]=category\_filter:173&filter\[2\]=category\_filter:174

Is there any workaround to fix this? Any patch is available for this ?

# Answer
I applied this patch https://www.drupal.org/files/issues/2019-07-31/facets-3070461-3-Facet-links-break-in-modal\_0.patch and issue resolved. Hope this will be helpful for others.
> 0 votes

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


# Question
Title: How should jcarousel be installed and configured?
To achieve a slider with 5 slides in sight and sliding 1 at a time, I thought https://www.drupal.org/project/views\_slideshow\_jcarousel would be a good choice. Also, because I already use views\_slideshow. However the installation instructions are a bit confusing. They seem to relate to Drupal 7 and/or combined with Drupal 8.

At first I installed through Composer and activated the module in Drupals' User Interface. This did not work. Then I downloaded the zip and tried to place files in different locations. Because it is not clear to me where I should place files, this also failed.

Anybody knows how I could get this to work?

Update: as was noticed by Stefan, the dist folder should be in an other location than the docs (sites/all/libraries/jcarousel/dist) indicate. I moved the contents of the dist folder to that new location (/libraries/jcarousel/lib), this didn't make it work yet. I can see the carousel options in the view that I made, but it doesn't function yet.

I'm setting the view \> slideshow settings \> widgets \> pager type to jcarousel pager. At that point there's a select list for skin without options to choose from. The output of the slider is an unformatted list with the slider below that. Perhaps I'm still doing something wrong?

# Answer
> 2 votes
From looking at the code you need to put the jcarousel library here:

```
/libraries/jcarousel/lib/jquery.jcarousel.min.js

```

This means install the module as usual and then put the library like given above in the folder libraries

But it seems that there is truly a flaw in setup instructions: The module page states like this:

> Download and extract the jCarousel library to libraries folder of drupal root. The source code can be found here:
>
> https://github.com/jsor/jcarousel/releases
>
> the folder name you create for this will need to be "jcarousel". the full path should be: libraries/jcarousel
>
> and when you are done, the following path will need to be available: sites/all/libraries/jcarousel/dist

This is a mixup of D7 and D8 as TO already stated and in addition if you do it like so, the path given in views\_slideshow\_jcarousel.libraries.yml will not be available.

I created an issue to maybe get this fixed: https://www.drupal.org/project/views\_slideshow\_jcarousel/issues/3084864

---
Tags: 8
---


title: Resizing a block on a drupal 7 website

text:
# Question
Title: Resizing a block on a drupal 7 website
I have three blocks A, B and C on the home page on location Content Bottom. I have another block D I want to place at location A+B and I want to keep C at the same location. I will move A and B to another location on the layout. How to do that? Currently when I place block D at Content Bottom it only takes the space (and width) of block A and other two columns look Odd. Block D now shows up as a single long column. Not a developer, using Drupal for three years, always learning more about Drupal. I know a little bit about css files and css injector.

If I place block D at Tertiary Content location, it takes the whole width of the screen. It shows below the region for A, B and C.

# Answer
The block widths are most likely controled by the theme CSS and it seems each block is given a third of the width of the container.

To change that and make one block take up two thirds of the container width you have to override the theme CSS. Exactly which selector and declarations to use depends on your particular case. You enter your overrides in the CSSinject or a similar module that overrides CSS through the interface.

If your theme is using floats, then you can find with your browser dev tools which selector was used to set that and the width, then use that same selector but with your own declaration override, something like:

```
.special-region .block {
  width: 60%;
}

```

If the layout method isn't floats then you'll have to adjust accordingly.

One other thing to consider is that this is most likely only code for wide screens, and it should be different for mobiles. Usually the mobile styles stack blocks one on top of the other so you won't have to do anything there, but you'll have to restrict your float to the same `@media` query as used by the theme, for example:

```
@media screen and (min-width: 900px) {
  .special-region .block {
    width: 60%;
  }
}

```

You can find out about which media query is being used through the browser dev tools.
> 0 votes

---
Tags: theming, blocks
---


# Question
Title: Views date range filter adds weird condition
I have a view for a content type. This content type has a date field (only date) and I have added and exposed a filter for this field ("date is between" option). I have added and exposed a filter for other text field.
If I put a condition on the text field in the filter of the view, then it generate a weird SQL for the date field.

```
SELECT node_field_data.nid AS nid, node_field_data_node__field_liq_club.nid AS node_field_data_node__field_liq_club_nid
FROM
node_field_data node_field_data
LEFT JOIN node__field_liq_club node__field_liq_club ON node_field_data.nid = node__field_liq_club.entity_id AND node__field_liq_club.deleted = '0'
INNER JOIN node_field_data node_field_data_node__field_liq_club ON node__field_liq_club.field_liq_club_target_id = node_field_data_node__field_liq_club.nid
LEFT JOIN node__field_liq_ejercicio node__field_liq_ejercicio ON node_field_data.nid = node__field_liq_ejercicio.entity_id AND node__field_liq_ejercicio.deleted = '0'
LEFT JOIN node__field_liq_fechaliq node__field_liq_fechaliq ON node_field_data.nid = node__field_liq_fechaliq.entity_id AND node__field_liq_fechaliq.deleted = '0'
LEFT JOIN node__field_liq_fechapago node__field_liq_fechapago ON node_field_data.nid = node__field_liq_fechapago.entity_id AND node__field_liq_fechapago.deleted = '0'
WHERE
(node_field_data.status = '1') AND (node_field_data.type IN ('liquidacion')) AND (node__field_liq_ejercicio.field_liq_ejercicio_value = '2010') AND
((DATE_FORMAT(node__field_liq_fechaliq.field_liq_fechaliq_value, '%Y-%m-%d') BETWEEN DATE_FORMAT('2019-01-01T00:00:00', '%Y-%m-%d') AND DATE_FORMAT('2019-12-31T00:00:00', '%Y-%m-%d')))
AND ((DATE_FORMAT((node__field_liq_fechapago.field_liq_fechapago_value + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') BETWEEN DATE_FORMAT(('2018-12-31T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') AND DATE_FORMAT(('2019-12-30T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s')))
LIMIT 25 OFFSET 0

```

My text field add the condition:
`node__field_liq_ejercicio.field_liq_ejercicio_value = '2010'`

But, although I don't fill any condition for date-range, it adds:

```
    and ((DATE_FORMAT(node__field_liq_fechaliq.field_liq_fechaliq_value, '%Y-%m-%d') BETWEEN DATE_FORMAT('2019-01-01T00:00:00', '%Y-%m-%d') AND DATE_FORMAT('2019-12-31T00:00:00', '%Y-%m-%d')))
AND ((DATE_FORMAT((node__field_liq_fechapago.field_liq_fechapago_value + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') BETWEEN DATE_FORMAT(('2018-12-31T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s') AND DATE_FORMAT(('2019-12-30T23:00:00' + INTERVAL 7200 SECOND), '%Y-%m-%d\T%H:%i:%s')))

```

I don't know why it is added, and how to solve this issue. Why this INTERVAL 7200 SECOND?. Any suggestion?

# Answer
> 0 votes
After some test I have found that a module was changing filter form states, and then the filter fields were wrong when the query were constructed. I fix that and now it works good.

---
Tags: views, 8
---


# Question
Title: Queue Implementation for third party api
In my website I have a form and which submits data to third party website. that api is available some time and not available some time. I need to create a queue mechanism to insert failed api calls and show them in admin panel.

Once admin wants to process the queue then that data needs to be resubmit to the third party site.

I need to know how to setup a cron job for the same , if we have more records then we can run cron for every 10 mins.

Any suggestions? I am new to this drupal8 queues.

# Answer
I think this is what you want:

'If any failure occurs, you can revert the item back to queue to process that again'

The queue API of Drupal 8 which is known as Queue Worker

http://www.tothenew.com/blog/how-to-implement-queue-workerapi-in-drupal-8/
> 0 votes

---
Tags: 8, hooks, queue
---


# Question
Title: Taxonomy Terms More than one level and Clean Class throws error
I am using clean\_class and clean\_id in twig. It was working with Parent Taxonomy Terms fine, but when I use Child Taxonomy Terms and try to render to Twig Template, I get this error message:

```
Recoverable fatal error: Object of class Drupal\Core\Field\FieldItemList could not be converted to string in Drupal\Component\Utility\Html::getClass() (line 72 of **core\lib\Drupal\Component\Utility\Html.php).**

Drupal\Component\Utility\Html::getClass(Object) (Line: 259)
__TwigTemplate_4f47122ce7aa9a8c20dea186eff4ea8b5e46cc06c44f4f280e0f32c345504034->doDisplay(Array, Array) (Line: 455)
Twig\Template->displayWithErrorHandling(Array, Array) (Line: 422)
Twig\Template->display(Array) (Line: 434)
Twig\Template->render(Array) (Line: 64)
twig_render_template('themes/custom/cpv3/templates/page--node--community-plan-update--actualizacin-del-plan-comunitario-de-boyle-heights.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('page', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 501)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 109)
__TwigTemplate_0352d110804239c4a7412c9a9a76a1e3fccf9ff4943b7c48bf7ef5beaa137b28->doDisplay(Array, Array) (Line: 455)
Twig\Template->displayWithErrorHandling(Array, Array) (Line: 422)
Twig\Template->display(Array) (Line: 434)
Twig\Template->render(Array) (Line: 64)
twig_render_template('themes/custom/cpv3/templates/html.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('html', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 147)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 148)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

Line 72 in Html.php is the function regarding Clean Classes

```
* @param mixed $class
   *   The class name to clean. It can be a string or anything that can be cast
   *   to string.
   *
   * @return string
   *   The cleaned class name.
   */
  public static function getClass($class) {
    $class = (string) $class;
    if (!isset(static::$classes[$class])) {
      static::$classes[$class] = static::cleanCssIdentifier(mb_strtolower($class));
    }
    return static::$classes[$class];
  }

```

Is this a bug in Drupal Core or could it be my theme? How can I debug this?

# Answer
> 0 votes
The error message:

> Recoverable fatal error: Object of class Drupal\Core\Field\FieldItemList could not be converted to string

Unfortunately the field object FieldItemList can't be casted to a string, it doesn't have a magic `__toString()` method, but it does have a magic `__get()` method. So you can provide a property name, which is for most field types `value`, to get the field value as string:

> **class FieldItemList**
>
> Represents an entity field; that is, a list of field item objects.
>
> An entity field is a list of field items, each containing a set of properties. Note that even single-valued entity fields are represented as list of field items, however for easy access to the contained item the entity field delegates \__get() and \__set() calls directly to the first item.

Source: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldItemList.php/class/FieldItemList/8.7.x

---
Tags: theming
---


# Question
Title: How can I register an already uploaded unmanaged file as managed file?
I am stuck in a point that should be easy but I couldn't figure it out.

To make a long story short; I uploaded manually some images to the public directory and now I want to register them as managed files but I am stuck for some time where I couldn't figure out how to do it.

I tried using `system_retrieve_file` but it seems to accept only URLs not local paths `public://` as it uses cURL to get the file

Also, I tried using `file_save_data` with no luck as well for the same mentioned points.

Any ideas?

# Answer
I ended up creating a new managed file, pretty easy as the following:

```
$user = \Drupal::currentUser()->id();
    $image = File::create([
    'uri' => $image_local_path,
    'uid' => $user,
    'status' => FILE_STATUS_PERMANENT,
  ]);
  $image->save();

```
> 0 votes

---
Tags: 8, files
---


title: HTTP error 500 after migration

text:
# Question
Title: HTTP error 500 after migration
I was able to successfully take a back up of D7 site and then restore to target D7 site. When I visit the site, I get an error

> This page isn’t working. ...com is currently unable to handle this request. HTTP ERROR 500.

Added the code in settings.php:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

> Fatal error: Cannot redeclare views\_views\_plugins() (previously declared in /home/.../public\_html/sites/all/modules/views/includes/plugins.inc:15) in /home/.../public\_html/sites/all/modules/hjhkjhj/views/includes/plugins.inc on line 402

How can I fix the error to bring my site back up?

# Answer
You need to run YourDomain/update.php and here you can find why.

If the problem is not resolved and (hjhkjhj) is a custom module, then you can't have the same function with the name twice. In your case `views_views_plugins`.
> 0 votes

---
Tags: migrations
---


title: Programmatically disabling menu item

text:
# Question
Title: Programmatically disabling menu item
I have been trying to disable a menu item "standard.front\_page" using the following code:

```
db_query("UPDATE {menu_tree} SET enabled = 0 WHERE id LIKE 'standard.front_page';");
db_query("DELETE FROM {cache_menu};");

```

It works fine till I do a cache rebuild using `drush cr`. Once I do a cache rebuild the menu item again comes back.

Can anyone please suggest a good way of doing the above?

# Answer
You can retrieve the Drupal menu link & cache services to programmatically change the menu link status. Something like this example function:

```
function menu_state_toggle($menu_id, $enabled = TRUE) {
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $front_page_link = $menu_link_manager->getDefinition($menu_id);
  $front_page_link['enabled'] = $enabled ? 1 : 0;
  $menu_link_manager->updateDefinition($menu_id, $front_page_link);
  $cache = \Drupal::cache('menu');
  $cache->deleteAll();
}

menu_state_toggle('standard.front_page', FALSE);

```
> 7 votes

# Answer
As a post-migrate cleanup step, I needed to remove a few nominated items from our main menu. Other settings (views, imported via config management) were going to take over the role that used to be static pages. Here is how it went:

```
/**
 * Startup changes for upgrading from the migrated base site to D8 version.
 */
function drupalorgnz_upgrade_install() {
  // From the base upgrade, remove the static pages that were in the main menu
  // as they were replaced with proper views pages.
  // The 'pages' still exist, and are used as intro text blocks in the
  // news views blocks,
  // but relinquish their menu items and paths.
  // Zap the legacy /companies and /showcases nodes.
  $old_nids = [517,518];
  foreach ($old_nids as $nid) {
    $node = \Drupal\node\Entity\Node::load($nid);
    // Zap out the path_alias and the menu item to anonymize this node.
    $node->path->delete();

    // That was easy.
    // Next hugely trickier.
    // This is BS. Eventually found the method in menu_ui_node_predelete()
    /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
    $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
    $result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', ['node' => $node->id()]);
    if (!empty($result)) {
      foreach ($result as $id => $instance) {
        if ($instance->isDeletable() && strpos($id, 'menu_link_content:') === 0) {
          $instance->deleteLink();
        }
      }
    }
    $node->save();
  }
}

```
> 2 votes

# Answer
If you simply want to disable a link, but still have it appear on the menu, use `route:<nolink>` as link path in the menu item.
> 1 votes

---
Tags: 8
---


# Question
Title: Cannot add new release for new contrib project
* I've recently promoted my project from sandbox
* My project's "default branch" is set as `8.x-1.x`
* I've got a tag on my latest commit -- `8.x-1.0-alpha1` -- which is listed on my project's "git tags" area
* As far as I can tell, I've followed the release naming conventions outlined on https://www.drupal.org/node/1015226

However, when I try to follow https://www.drupal.org/node/1068944, I do not see an "add new release" option at the bottom of my project page (or anywhere else). Any suggestions for what I may be doing wrong?

I see that dev releases appear to be generated every 12 hours, but the above has all been set up for longer than 24 hours.

# Answer
> 2 votes
It happens because on Media Entity Remote Image (the project you linked):

* You **aren't** the project owner

>
* The project owner didn't give you the permission to administer releases

>

As you see in the second screenshot, the checkbox for the *Administer releases* for the *mrweiner* account isn't selected.

If it were, you would see an *Add new release* link right after the *Downlaods* table, which is empty, for the given project.

>

If you want to be able to create new releases, you need to get the permission to administer releases too. Otherwise, the project owner needs to create the new release.

*\[**Disclaimer**: On Drupal.org I have more permissions than a normal user; that is why I see what project owners would see for their own projects.\]*

---
Tags: community-official-site
---


# Question
Title: How can I position two elements next to each other in the admin area?
how can I position two elements next to each other in the admin area of Drupal 8.6.10?
I want to position the element **Channel Additional** next to the element "CHANNEL".
So that **Channel Additional** is next to **CHANNEL**.
How can I position this?
This positioning should only take place in the admin area.

Greetings

# Answer
> 0 votes
This could be placed inside a region to block. The admin ui has its own theme so any css changes should probably be in a sub theme to that.

In your theme you can define regions or blocks that can be styled or laid out with css. Drupal 8 is much more mobile friendly so you should probably consider how it should respond.

You can also define custom regions within your theme and place content accordingly if that is required.

Looking at your example it could be as simple as a couple of lines of css but as mentioned previously do consider how this will work on smaller viewports as well.

---
Tags: theming
---


# Question
Title: How can I theme the markup for the labels in a set of radio options on a specific form item?
Given this form item defined in a custom module;

```
$form['my_items'] = [
  '#type' => 'radios',
  '#title' => $this->t('Items'),
  '#options' => $optionsSet // array of options pulled from a data source
];

```

How can I modify the label of each option to include a small image to the right of the text? In my case, the image is stored in the same dataset alongside each label.

I'm going to guess this has something to do with adding a '#theme' attribute, but I haven't been able to determine the entire process for setting that up.

# Answer
> 0 votes
You'll need to massage the `$optionsSet` array so it's structured like this:

```
$optionsSet = [
  'option1' => '<img scr="../images/option1.jpg"/>option 1',
  'option2' => '<img scr="../images/option2.jpg"/>option 2',
];

$form['my_items'] = [
  '#type' => 'radios',
  '#title' => $this->t('Items'),
  '#options' => $optionsSet,
];

```

---
Tags: 8, theming, forms
---


title: Alter the "From" address contact form

text:
# Question
Title: Alter the "From" address contact form
I'm trying to alter the email and change the default "From" address to a different email address.

```
function mymodule_mail_alter(&$message){
   $message['from'] = 'myemail@gmail.com';
}

```

When I test send a test email through my site Contact Form. The email "From" address is still using the default site email not the one I altered in my module.

Is there another way to make this work?
Thanks for your help.

# Answer
I ran into this issue myself. I got it to work in the following way:

```
function mymodule_mail_alter(&$message){

  $message['from'] = "do-no-reply@example.com";
  $message['headers']['From'] = 'Name TO SHOW <do-no-reply@example.com>';
  $message['headers']['Sender'] = $message['headers']['Return-Path'] = $message['from'];
}

```

However, like you, I thought adding `$message['from'] = 'myemail@gmail.com';` is the way to go and I think it should -Perhaps other folks can chime in and let us know if this is a bug?

In any case, it seems drupal does more processing and checks to verify the `from` email address and if it does not pass all the checks it sets it to the sitemail, or the mail library just use the other headers. Note I think this behavior may differ based on which mail library you are using. In my case, and I presume in yours, its PhpMail.php.

The solution above worked but I am not sure if it's the most appropriate or if it would work for others who are using different mail managers..
> 2 votes

---
Tags: 8, emails
---


title: Embedded View Form Ajax not working

text:
# Question
Title: Embedded View Form Ajax not working
I have a an embedded view display (type = embed) with an exposed form and pager. Ajax is enabled for the display. The pager reloads the display via ajax, however the form does not. I'm all but certain the form used to trigger an ajax reload, but no longer does, and I'm not sure why.

I have used the viewsreference module, viewfield module, and straight views\_embed\_view() to embed the display and none produce a display where the form reloads via ajax. I have other sites using all three of these methods and those sites all have properly functioning views with ajax forms.

I have used the "Duplicate this display as Block" option in the views ui, placed the block on a page, and that form **does** reload via ajax properly.

I have tried different themes, including core themes, and the form still doesn't reload the display via ajax.

As far as I can tell, there's no markup difference between displays where views exposed forms are processed via ajax and those that aren't. (Comparing with another site. It seems that all embed display forms on this site won't filter the view via ajax.)

I don't have any custom code interacting with the views or their forms.

Does anyone have any idea what may cause Drupal views exposed forms to not process via ajax? Or can anyone recommend a way to further debug this?

# Answer
Thanks @4k4. Your comment started me poking around in ajax\_view.js which ultimately led me to the cause. My issue was that my display ids had multiple underscores in a row, e.g. `listing__large`. If I update the display id to `large_listing` everything works fine. I guess multiple underscores in a row aren't supported in the display ids, and I'm guessing also with view ids.
> 0 votes

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


# Question
Title: Is it possible to invoke cron within a hook or route class?
I'm using the Deploy suite, which requires cron to be run after a deployment is created. However, when I try to execute `\Drupal\Core\Cron::run();` from `hook_entity_create()` or from a route Class, it doesn't work. It dies after hitting `$this->accountSwitcher->switchTo(new AnonymousUserSession());`, throwing the error `Using $this when not in object context in Drupal\Core\Cron::run()`.

Is this just simply not possible? Is there a way around these errors?

# Answer
The reason why you get that error is because `run` is not expected to be called statically. `\Drupal\Core\Cron` is a service class managed by Drupal, registered in `core.services.yml`. To get a reference to the instance of this service, you'll need to inject the dependency to your controller.

```
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\CronInterface;

class MyController extends ControllerBase {

  protected $cron;

  public function __construct(CronInterface $cron) {
    $this->cron = $cron;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('cron')
    );
  }

  public function myPage() {
    $this->cron->run();
  }

```

To call it from a hook, if you'll need to use `\Drupal::service()` to get a reference to the instance:

```
$cron = \Drupal::service('cron');
$cron->run();

```

A full example of how to manually run cron can be found in the implementation of the Cron settings page (Configure -\> System -\> Cron). In that page, you have a button to manually run the cron. See the `runCron` method, which is attached as the submit handler of the "Run cron" button.
> 3 votes

---
Tags: 8, routes, cron
---


# Question
Title: How can I loop through all article content types and get the content of each
I created a new article content and am overriding that by creating a template for it (ie: node--4.html.twig).

Then inside this template, I want to loop through all nodes that belong to article content type; and to achieve that, I created my .theme file and added the following code based on the answer for this question here:

```
<?php
  function capoeira_preprocess_page(&$variables) {
  $articles = \Drupal::entityQuery('node')->condition('type', 'article')->execute();
  $nodes = \Drupal\node\Entity\Node::loadMultiple($articles);
  $variables['articles'] = $nodes;
}

```

Inside the template I do have:

```
{{ kint(articles) }}

```

inside my template and I go refresh the page I show article as NULL.

How do I loop through the articles?

EDITED:

None of the below work:

```
function capoeira_preprocess_page(&$variables) {
  $articles = \Drupal::entityQuery('node')->condition('type', 'article')->execute();
  $nodes = \Drupal\node\Entity\Node::loadMultiple($articles);
  $variables['name'] = $nodes;
}

function capoeira_preprocess_node(&$variables){
  $variables['name'] = 'My name comes here';
}

function capoeira_preprocess_node_article(&$variables){
  $variables['name'] = 'My name comes here';
}

```

# Answer
> 0 votes
you can use

```
function YOURTHEME_preprocess_node_article(&$variables){
  $node = $variables['node'];
   $nid = $node->id();
   // similarly you can fetch other fields
}

```

then override article content type as `node--article.html.twig` and pass data to twig file

---
Tags: theming, nodes
---


# Question
Title: How to change payment state programmatically?
I had created a custom module to update order state and payment state. In my controller I used the following code to change the order state of order.

```
 $order = \Drupal\commerce_order\Entity\Order::load($order_id);

 if ($payment_status === 'payment.captured'){
   $order->set('state', 'completed');
   $order->save();
 }
 else {
   $order->set('state', 'pending');
   $order->save();
 }

```

**How can I now change the payment state of a payment which comes inside that order?**

This is the screenshot of my payment. Now the payment state is pending. I want to change it to something else by using code, for example completed.

# Answer
Clive method doesn't work, probably he wanted to write

```
 $payments = \Drupal::entityTypeManager()->getStorage('commerce_payment')->loadByProperties(['order_id' => $order->id()]);

```

the other method would be to load it with loadMultiple

```
$payments = \Drupal::entityTypeManager()->getStorage('commerce_payment')->loadMultipleByOrder($order);

```

also @Interdruper method works and is slimmer as it first loads ids and not whole payments.
> 3 votes

# Answer
Try this:

```
use Drupal\commerce_payment\Entity\Payment;

$payments = \Drupal::entityQuery('commerce_payment')
  ->condition('order_id', $order->id())
  ->execute();

foreach ($payments as $value) {
  $payment = Payment::load($value);
  $payment->setState('completed')->save();
}

```
> 2 votes

# Answer
Load up the payments:

```
$payments = \Drupal\commerce_order\Payment\Payment::loadByProperties(['order_id' => $order->id()]);

```

Then loop through and save what you want to:

```
foreach ($payments as $payment) {
  $payment->setState('completed')->save();
}

```
> 0 votes

---
Tags: 8, commerce, payment-gateways, page-controller
---


title: List of replacement tokens?

text:
# Question
Title: List of replacement tokens?
Where can I find a list of the available tokens, so I can write things like {{ node.title }} in my templates?

The documentation says the best way to find a list of them is to use this: https://www.drupal.org/docs/8/modules/d8-rules-essentials/data-selection

Can anyone provide something more useful?

# Answer
Those are variables, not tokens. They're arbitrary, and can/will change depending on what template you're in, what modules/themes you have installed, and how you have them configured.

The easiest way to see what variables you have available in context is to use the dump() method:

```
{{ dump() }}

```

See Discovering and Inspecting Variables in Twig Templates for full details.
> 1 votes

---
Tags: theming
---


# Question
Title: VBO: "Change owner" Vs "Change the author of content"
I would like to change the author of a content for a bunch of nodes. So I've chosen Views Bulk Operations (VBO) module to achieve it.

Part of it, created a VBO view, but in the VBO options I see "Change owner" and "Change the author of content" (shown below).

What's the difference?

# Answer
> 1 votes
*Change owner* is an action implemented by the *Views Bulk Operations* module, while *Change the author of content* is an action implemented by the Node module. (See `views_bulk_operations_change_owner_action_info()` and `node_action_info()`.)

The VBO module implements that action for any entity for which that action makes sense. (In other words, if the entity doesn't have an owner, the action is not implemented for that entity.) Apart that, the underline code doesn't change much.

```
// This is the function for the VBO action.
function views_bulk_operations_change_owner_action($entity, $context) {
  $entity->uid = $context['owner_uid'];
}

```

```
// This is the function for the Node module action.
function node_assign_owner_action($node, $context) {
  $node->uid = $context['owner_uid'];
  $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(
    ':uid' => $context['owner_uid'],
  ))
    ->fetchField();
  watchdog('action', 'Changed owner of @type %title to uid %name.', array(
    '@type' => node_type_get_name($node),
    '%title' => $node->title,
    '%name' => $owner_name,
  ));
}

```

The obvious difference is that the VBO action implementation doesn't log for which node the owner has been changed. When changing the owner for many nodes, its implementation could be faster than the Node module one.

---
Tags: 7, views
---


# Question
Title: Can't uninstall module that depends on custom field type in use
**Drupal 8**

Using Yoast, I've removed it from all my content types but I can't uninstall because it says --\> `The Yoast SEO status & focused keywords field type is used in the following field: taxonomy_term.field_yoast_seo`, which I did not create nor is it visible via `Structure > Taxonomy`.

Looking into the DB, there's over 51 matches for 'field\_yoast\_seo', but I can see where it is created:

It's a table. I don't know if I can just go ahead and delete it without it backfiring on me. Has anyone tried it?

# Answer
**Be sure to backup your database before you try out what I did, just in case.**

After looking everywhere I decided to go for it and delete it from the database. I also opened an issue in the Drupal Project for Yoast SEO.

I used PHPMyAdmin to search any occurrences of `"field_yoast_seo"`, these are the steps (and order) I took:

* Deleted appearances in `cache_` tables
* Deleted rest of appearances
* Emptied the table `taxonomy_term_field_yoast_seo`
* Deleted the table `taxonomy_term_field_yoast_seo` (I checked there were no dependencies to the rest of the data base)
* Cleared Caches
* Ran cron manually
* Uninstalled Yoast Seo (after all of the above, the check box was available and I could uninstall)
* Manually removed the module from `/httpdocs/modules`

Leaving the answer here in case anyone else runs into this.
> 0 votes

# Answer
If a module define a field type, it can't be uninstalled if you have a field of this type. This is not related which tables are in the database, and deleting tables in the database wont resolve this.

What you need to do, is to delete the field yourself. Drupal doesn't want to this automatically, as it could mean data loss. From the message you get the field name `taxonomy_term.field_yoast_seo`. This machine name is structured as `ENTITY_TYPE.FIELD_NAME`, so the field you need to delete is on a taxonomy term. It doesn't tell which vocabulary it's located on, but hopefully you can find it manually and resolve it
> 2 votes

# Answer
I managed to uninstall this module by going to admin/config/yoast\_seo Unselecting everything under: Configure Real-time SEO by bundles running Cron Then the tick box for Real-time SEO became available in Uninstall
> 2 votes

---
Tags: 8, entities, installation
---


title: Create nodes unlimited times

text:
# Question
Title: Create nodes unlimited times
I've been trying to ajaxify the node creation form, the purpose?

* Save the node and remains in the node creation page (Done)
* If the user clicks the save button again save a new node

The second point is not working yet because once the Ajax request is sent again the previous created node is updated.

I tried with:

```
function saveAjaxForm(&$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new AlertCommand('Saved'));

  return $response;
}

```

It works, but other #submit callbacks in the form aren't called again.

How can I "execute again" all the submit functions in the form?

# Answer
> 1 votes
For some weird reason the Ajax response wasn't updating the ***form\_build\_id*** value and the request takes it as the same form, so I added a new Ajax Command:

```
function saveAjaxForm(&$form, FormStateInterface $form_state) {
  $old_form_build_id = $form['#build_id'];
  $new_form_build_id = $old_form_build_id.rand();

  $response = new AjaxResponse();

  $response->addCommand(new UpdateBuildIdCommand($old_form_build_id, $new_form_build_id));
  $response->addCommand(new AlertCommand('Saved'));

  return $response;
}

```

It solves the issue.

---
Tags: nodes, forms, ajax
---


# Question
Title: Setting up an exposed filter to only filter conditionally
I am trying to build a D7 view, and I have the view correctly only showing results using a contextual filter, but I am trying to build one more filter (an exposed one), to drill down even more.

I have a list of students, each students assigned to different districts. A user is assigned to one (or multiple) districts, but should never be assigned to all (but could be). The contextual filter is checking the assigned\_user field of the district using the logged in user, and that works.

I have the student and district relationship setup, and it pulls all data from both entities correctly.

Now I am trying to build an exposed filter so that the user can select which district they want to filter by, but ONLY list the districts they are assigned to. When using the 'expose filter' option on the district name, if I use 'Single Filter' it makes it a textbox instead of a select box, and if I use 'group filter', it makes a select box, but I have to manually put in each district.

I am trying to #1, get the exposed filter to be a select list, and #2 ONLY the districts the user has access to (via the assigned\_user contextual filter). The views UI doesn't appear to have a way to do this, so is it possible for me to write a hook to create the filter myself?

# Answer
> 2 votes
If the district is a term, entity reference, or a list field value, then you should be able to do this. Otherwise, You'll need to do something more involved (and honestly, at that point, you're probably better off just restructuring that data to work with views.

As far as only exposing options that will provide valid results, I'd recommend taking a look at Views Selective Filters (https://www.drupal.org/project/views\_selective\_filters). Be wary though, as the views\_selective\_filters module does an additional query, **per selective filter** as the view is loaded. Not a huge problem for 1 or 2 filters. But can start to cause performance issues if you're not careful.

**Edit** The question as I (now) understand it: How do you change the options of a select list exposed filter based on an arbitrary value set against the currently logged in user?

First, hook into the exposed filter form and modify the district filter.

```
function mymodule_form_FORM_ID_alter(&$form, &$form_state) {
  $district_options = mymodule_get_district_options();

  if (!empty($district_options)) {
    $form['field_district']['#type'] = 'select';
    $form['field_district']['#options'] = $district_options;
  }
}

```

Next, you need to actually write `mymodule_get_district_options()`.

```
function mymodule_get_district_options() {
  // Load the current user.
  global $user;
  $account = user_load($user->uid);

  // Default to loading all districts.
  $district_ids = FALSE;

  // Get the districts value from the loaded account.
  if (!empty($account) && !empty($account->field_districts)) {
    $district_values = $account->field_districts;
    foreach ($district_values[LANGUAGE_NONE] as $delta => $value) {
      $district_ids[] = $value['target_id'];
  }

  // Load the districts set on the current user, or ALL districts if none are set.
  $districts = entity_load('district', $district_ids);

  $options = [];
  if (!empty($districts)) {
    foreach ($districts as $district) {
      $options[$district->id] = $district->title;
    }
  }

  return $options;
}

```

Something along those lines should work. I haven't tested this.

# Answer
> 0 votes
I ended up achieving this. The exposed filter was defaulting to a textbox instead of a select list, so I used hook\_form\_alter to change it to a select list, and since I was already altering the form I used that time to use EntityFieldQuery to pull in only the 'options' available to the user (based on the assigned\_user entityreference field on the district entity). In the end, it achieved exactly what I needed it to.

---
Tags: 7, views
---