# Question
Title: Preprocess SCSS with Zen Theme on MS Server
I'm getting familiar with the official documentation of **Zen Theme** on **Drupal 7**. I'm wondering about the *SASS*\- and *SCSS*-Files. The *CSS*-Interpreter can't understand these files ofcourse. I read about `gulp.js` which is the *preproccessor* for *SCSS*-Files. I also read about the server **nodejs** \- what I used years before - that `gulp.js` needs for action. I read it here: getting started SASS and Compass

Can someone explain me, how dose **MS Server** with no **Drush** works to handle *SCSS* with `gulp.js`-File - what is not been found in the **Zen Theme**-Folder by me - to preprocess clean *CSS*-Files?

# Answer
I don't have experience with MS server but I expect the entire process to be the same as described.

This applies to themes in general, not only Zen:

Using Sass preprocess to compile CSS is independent from Drupal, or Drupal themes. This is just an outside tool that you can use to make your CSS life easier, if you are familir enough with CSS and Sass. The end output that themes use will always be CSS, because that is what browsers understand.

Some themes have opted to integrate Sass preprocessing into their workflows. You don't have to use Sass, you can always just override the base CSS that was generated through Sass with your own CSS. But some themes have Sass so tightly integrated that it would a pitty not to take advantage of it. It's entirely your call.

Most of Sass preprocessing situations define which folder on your system contain Sass files, and which folder stores the compiled CSS, they are usually different folders (it's a cleaner practice not to keep the compiled CSS in the same folder as its source Sass). This is what you will find in most themes that use Sass, you will have a dedicated folder for Sass, and another one for compiled CSS, so you can continue using that structure. This structure is then recorded in the gulp.js file, so the preprocessor software knows which files to use as sources, and where to save the compiled code.

If you're not using Sass, but only pure CSS, you should keep your CSS in the third place! Don't keep it in the folder with the compiled CSS, because if a preprocessor is ever triggered, the contents of that folder might be deleted! Keep your dry CSS in a dedicated folder that doesn't have anything to do with Sass. You will add the CSS files to your Drupal theme configuration, so they are applied *after* all the theme code. This is how you can bypass dealing with Sass if a theme is using it.

Nodejs isn't the only way to get Sass working on your computer, there are other technologies that have it, but either way you'll have to install some engine that makes the Sass processor available.

Once you install nodejs, and the preprocessor packages as noted in the Zen tutorial, you will be able to start compiling CSS out of Sass files "anywhere" on your computer, given the correctly configured gulp.js.

You will probably just want to work on your Zen subtheme, which already comes with a great gulp.js, so if you have the preprocessor installed correctly you can start compiling the Zen subtheme Sass into CSS.

This can be done manually, you edit the Sass files to edit/add new Sass/CSS code, then (through terminal) use nodejs and Sass commands to execute Sass to CSS compiling. So you manually execute the compile command each time you want to compile your Sass changes and test them in browser.

More commonly it is done automatically by using a command to start watching Sass folder (a process is opened on your computer in your terminal). This way when you save changes to a Sass file the processing starts automatically, old CSS files get overwritten with the new CSS that contains the changes. There is also the Browsersync option that refreshes CSS automatically in the page where you're developing (local environment server) but it's more complicated with caching...

So this is what the development steps are with Sass, once you have the preprocessor installed:

1. Open terminal, go to your subtheme folder
2. Start watching (there's a command for that, the process is started and is kept active)
3. Edit the Sass files to make your changes (in what ever editor you usually use)
4. Save Sass file(s), this is when the preprocessor will compile the CSS, you will see the output in terminal, if you have any errors you need to fix them etc. The output will tell you when the CSS is compiled so you can check your changes in browser (it can be miliseconds or seconds depending on circumstances)
5. Repeat
6. When you're done with development you stop watching the subtheme folder after your latest compile (you stop the process you started in step 2)

What is also usually involved in development is commiting changes to Git once you have a meaningful piece to commit (not after every Sass file save). For this I keep another terminal (shell) open, one for keeping an eye on CSS compiling with the watch command, the other for "regular" commands and git.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Overriding the User entity list_builder handler
I'm trying to override the User entity list\_builder handler to add another column to the table and implement some JavaScript search functionality.

The code I'm using is below which is in my modules mm.module file.

```
function mm_user_override_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setHandlerClass('list_builder', 'Drupal\mm_user_list_builder\UserListBuilder');
}

```

The issue I'm having is this code gives me the following error

```
Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException</em>: The "user" entity type did not specify a list_builder handler.

```

Which from what I can tell is not correct, even `$entity_types['user']->getHandlerClasses()` tells me the `list_builder` handler exists.

Why is this error happening & how best to resolve it? Or is there a better way for me to add a column & search to the user list page?

# Answer
> 1 votes
my\_module.module :

```
<?php

use Drupal\my_module\MyModuleListBuilder;

function my_module_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setHandlerClass('list_builder', MyModuleListBuilder::class);
// $entity_types['user']->setListBuilderClass(MyModuleListBuilder::class); // Other solution possible
}

```

my\_module\src\MyModuleUserListBuilder.php :

```
<?php

namespace Drupal\my_module;

use Drupal\user\UserListBuilder;

class MyModuleListBuilder extends UserListBuilder {
    // Implement the function you want to edit
}

```

---
Tags: 8, users
---


title: How can I set up a "blog" area?

text:
# Question
Title: How can I set up a "blog" area?
I am very new to Drupal and Twig.

I've a custom Drupal theme I've built, but my client now wants a "blog" system as well. This includes the following features:

* Show most recent article in a blurb on the home page
* List out articles with pagination on an archive page
* Assign categories and/or tags to articles which when visited list out articles similar to the main archive page
* Show "posted on" date on article page

I've got the last item working just fine, but I can't find anything useful Googling around for the first three items.

I'm using Drupal 8 and twig templates if that makes a difference.

# Answer
Everything you listed is super common, almost basic in Drupal projects. So you can find plenty of tutorials and introductory articles about how to do those features.

1. You can create the latest article blurb Block using Views module (it's in D8 core), then place the Block in a theme region and adjust its visibility to only show on the front page
2. You can create "Archive" page using Views (pagination is also a feature in Views)
3. Tag articles with the Taxonomy module (create a Vocabulary with terms inside, then add a Taxonomy reference field on Article Content type). There is a out-of-box View "Taxonomy term" that automatically creates pages for each term and lists the articles tagged with that term
4. Submitted by and on can also be controled through the interface by editing the Content type settings (you only need twig if you need to override the HTML output)

So get yourself some Drupal Views and Taxonomy tutorials ;)
> 1 votes

---
Tags: 8
---


title: Force download string as text file

text:
# Question
Title: Force download string as text file
I'm trying to return the results of a db\_query as a raw text file. The php solution uses header() to instruct browsers to download content. I've attempted using header() in an AJAX callback function, but the following error code is always returned:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText: this is just a test

```

I'm looking for a way to save a php string value to a file client-side, ideally without requiring the file to first be saved on the server. Alternatively, if I could pass a value from an AJAX callback directly to javascript for post-processing, that would work too (haven't found an AJAX callback with this capability).

Here's my test code (that produces the above error):

```
<?php

function test_download_form($form, &$form_state) {

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

  $form['form_wrapper']['download_submit'] = array(
    '#type' => 'button',
    '#value' => 'test download',
    '#id' => 'download_submit',
    '#ajax' => array(
      'callback' => 'test_download',
    ),
  );

  return $form;
}

function test_download($form, $form_state) {
  $dateFile = rand(10000000, 99999999)."_test.txt";
  $dataString = "this is just a test";

  //header() and drupal_add_http_header() behave the same
  header('Content-Type: application/text');
  header('Content-Disposition: attachment; filename="'.$dateFile.'"');
/*
  drupal_add_http_header('Content-Type', 'application/text; utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="'.$dateFile.'"');
  drupal_send_headers();
*/
  echo $dataString;
  exit;
}

```

# Answer
> 0 votes
I ended up making some modifications to the Drupal CSV module (code). The module code demonstrates that you can stream information directly to the client with header() designations. From what I was able to find, you aren't able to use form headers within form callbacks. An alternative method involved passing information with sessioning to an empty page (that doesn't have header restrictions). This had several undesirable consequences:

1.) Session information is saved temporarily server-side, increases time to load to client due to having to write twice.

2.) Finite memory allotment for sessions.

The solution below does not have these limitations:

```
<?php

function test_download_form($form, &$form_state) {

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

  $form['form_wrapper']['download_submit'] = array(
    '#type' => 'submit',
    '#value' => 'test download',
    '#name' => 'retrieve',
  );

  return $form;
}

function test_download_form_submit($form, &$form_state) {
  $characters = 'ACGT';
  $randomString = '';
  $n = 50000000;

  for ($i = 0; $i < $n; $i++) {
    $index = rand(0, strlen($characters) - 1);
    $randomString .= $characters[$index];
  }

  //https://git.drupalcode.org/project/csv/blob/7.x-1.x/csv.module
  drupal_add_http_header('Content-Type', 'text; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="test_header_method.txt"');
  $fp = fopen('php://output', 'w');
  fwrite($fp, $randomString);
  fclose($fp);
  drupal_exit();
}

```

---
Tags: 7, ajax, files
---


# Question
Title: Markup being stripped from form element title
I need to add links to checkbox titles, I can see the link in the render array but when it renders the markup is stripped. How can I get the links to not be stripped?

I am doing this in a form alter, the checkboxes are added to the user registration form in the Drupal UI, i.e. they are form fields.

```
$tc_link = Link::fromTextAndUrl(new TranslatableMarkup('terms and conditions'), Url::fromRoute('<front>'))->toString();
$tc_link_label = t('You agree to the ') . $tc_link;
$form['field_terms_and_conditions']['#title'] = $tc_link_label;

```

The markup is like this:

```
<div class="form-checkboxes" id="edit-field-terms-and-conditions"><div class="js-form-item form-item js-form-type-checkbox form-type-checkbox js-form-item-field-terms-and-conditions-agree-terms-conditions form-item-field-terms-and-conditions-agree-terms-conditions">
        <input name="field_terms_and_conditions[agree_terms_conditions]" class="form-checkbox" id="edit-field-terms-and-conditions-agree-terms-conditions" type="checkbox" value="agree_terms_conditions" data-drupal-selector="edit-field-terms-and-conditions-agree-terms-conditions">

        <label class="option" for="edit-field-terms-and-conditions-agree-terms-conditions">You agree to the terms and conditions</label>
      </div>
</div>

```

But if I inspect it with kint the links are clearly there.

# Answer
In Drupal, strings need to be passed through the t() function for translation. This function uses string replacement to sanitize text. When passing links, the HTML should be put in the string, and the URL passed as a variable prefixed with a colon:

```
$tc_link_label = t('You agree to the <a href=":url">terms and conditions</a>', [':url' => Url::fromRoute('<front>')->toString()]);
$form['field_terms_and_conditions']['#title'] = $tc_link_label;

```
> 2 votes

---
Tags: 8
---


title: Rendering plain HTML in a form

text:
# Question
Title: Rendering plain HTML in a form
I have HTML markup which is externally generated but I need to display in a form.

I've got the following code in a form controller:

```
public function buildForm(array $form, FormStateInterface $form_state){
    $form['phone_number'] = [
        '#type' => 'tel',
        '#title' => 'Example phone',
    ];

    $form['TEST-Cloze']   =   [
        '#markup'   =>  "<p><select><option value='[Walter]'>[Walter]</option><option value=' Hank'> Hank</option><option value=' Gus'> Gus</option><option value=' Jessie'> Jessie</option><option value=' Mike'> Mike</option></select> was diagnosed with cancer in his 50th year. He began working with <select><option value='Badger'>Badger</option><option value=' Skinny Pete'> Skinny Pete</option><option value=' [Jessie]'> [Jessie]</option><option value=' Tortuga'> Tortuga</option><option value=' Bogdan'> Bogdan</option></select> to produce <select><option value='cocaine'>cocaine</option><option value=' heronie'> heronie</option><option value=' opiods'> opiods</option><option value=' [amphetamines]'> [amphetamines]</option><option valu\nhis death. He eventually became involved with hardened criminal <select><option value='[Tuco]'>[Tuco]</option><option value=' Gomie'> Gomie</option><option value=' Bogdan'> Bogdan\noption><option value=' Todd'> Todd</option><option value=' Gale'> Gale</option></select> to help with the distribution of his illegally manufactured product.</p>"
        // '#markup'   =>  $question->processed
    ];

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

    return $form;
}

```

However, the output is completely stripped of markup and displays as plain text, as shown below:

How can I get the markup printed?

**UPDATE:**

I am attempting to add my form element markup because of the complexity of having multiple drop-down lists in a single paragraph, such as displayed below:

I struggled to achieve this type form output using other form components which is why I began looking into the **#markup** component.

# Answer
If this was just content I would replace `#markup` with `#prefix`. It will automatically render without escaping your HTML.

However, it seems like you don't just want to render this HTML. You actually want it to interact with the Drupal Forms API. As such, I would recommend that you parse the data you need from the source and construct the form element the recommend way:

```
form['example_select'] = [
  '#type' => 'select',
  '#title' => $this
    ->t('Select element'),
  '#options' => [
    '1' => $this
      ->t('One'),
    '2' => [
      '2.1' => $this
        ->t('Two point one'),
      '2.2' => $this
        ->t('Two point two'),
    ],
    '3' => $this
      ->t('Three'),
  ],
];

```
> 1 votes

# Answer
You can pass a FormattableMarkup element as #markup:

```
$markup = new Drupal\Component\Render\FormattableMarkup("<p>Some string with <em>HTML markup</em></p>");

$form['TEST-Cloze'] = [
  '#markup' => $markup,
];

```

Note that I didn't use the text from your example, as you would be better off using the Form API to build your elements. Rather the example I gave is one that can be used for other string that has HTML in it. But even with my example, I would still do it like this, to allow the string to be translated:

```
$form['TEST-Cloze'] = [
  '#prefix' => '<p>',
  '#suffix' => '</p>',
  '#markup' => t('Some string with <em>HTML markup</em>'),
];

```
> 1 votes

---
Tags: 8, forms
---


# Question
Title: How can I customize the header and footer from a custom page controller?
I have a module named `some_module`.

This is my `some_module.routing.yml`:

```
some_module.index:
 path: '/this/is/the/path'
 defaults:
   _title: 'Some Title'
   _controller: '\Drupal\some_module\Controller\SomeController::index'
 requirements:
   _permission: 'access content'

```

This is my `SomeController.php`:

```
namespace Drupal\some_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class SomeController extends ControllerBase {
    public function index()
    {
        return [
            '#theme' => 'some_template',
          ];
    }

```

When I go to `/this/is/the/path` in my browser. It's showing my theme's header and footer. How can I customize header and footer when I access `/this/is/the/path`?

# Answer
It depends on how you have built these. Generally you will set any blocks in the header and footer to only show on the paths they are meant to show on, in the block visibility settings. If you need completely different headers and footers altogether, you can build a new theme with those headers and footers, and create a custom theme negotiator (https://www.webomelette.com/choose-your-theme-dynamically-drupal-8-theme-negotiation) to set the theme for those pages.
> 1 votes

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


# Question
Title: How can I make a response cachable by browsers?
I am working on a Drupal Controller implementation that would return a generated image as response. I used Symfony's Response and I was trying to add ETag header to it:

```
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class MyController extends ControllerBase {

  public static function viewGraph(string $id, Request $request) {
    $response = new Response();
    $response->setEtag($etag); // some etag genrated from $id
    if ($response->isNotModified($request)) {
      return $response;
    }
    // ...
    return $response;
  }

}

```

I expected to see the `"ETag"` header in my response. But there is nothing. I've even tried CacheableResponse and it didn't work as well.

What's wrong with my approach? What is the right approach to it?

# Answer
Thanks to 4k4's answer. I took a deeper dive into the issue. Here is something that might benefits others who want to do the same thing.

# ETag Header Setting

The class FinishResponseSubscriber will check if response is cacheable. If it is, you're good to go. Then it will also check if the response is customized by checking if you have setup `"Cache-Control"` header to `"public"`:

* If it is "customized", it will assume you have properly setup your header yourself.
* If not it will call setResponseCacheable and rewrites the ETag header with whatever timestamp it think is suitable (either your `"Last-Modified"` header value or the request time).

## Customized Header

As 4k4 pointed out, you can achieve the ETag setup by this:

```

use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;

class MyController extends ControllerBase {

  public static function viewGraph(string $id, Request $request) {
    // ... generate $etag
    $response = new CacheableResponse();
    $response
      ->setPublic()
      ->setMaxAge(60)
      ->setEtag($etag);
    if ($response->isNotModified($request)) {
      return $response;
    }
    return $response;
  }

}

```

## Hands off to Drupal

```

use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;

class MyController extends ControllerBase {

  public static function viewGraph(string $id, Request $request) {
    // ... get $last_modified
    $response = new CacheableResponse();
    $response->setLastModified($last_modified);
    if ($response->isNotModified($request)) {
      return $response;
    }
    return $response;
  }

}

```

Similarly, if it found that the response is not cacheable, it would call FinishResponseSubscriber::setResponseNotCacheable and unset ETag header.

So unless you were to override FinishResponseSubscriber somehow, you can only stick with the ETag generated by Drupal.

And the ETag header will be generated by your `Last-Modified` header automatically.

# Wait, there's more...

Oh right. Even you got the header right, it **does not** mean your response is **cacheable**! It's because that cache header is not the only requirement for you to see ETag and have browser cache.

As of Drupal 8.7, to have a cached response, the FinishResponseSubscriber checks both the request and response to see if both are cacheable.

The below points are the extra criterias for browser cache to work.

## Setup Browser Cache Max Age

As 4k4 mentioned, you need to setup the browser / proxy cache maximum age to a non-zero value in order to have any browser cache. The setting is in "Home \> Administration \> Configuration \> Development \> Performance".

## Make sure your Request is cacheable

The request, unless otherwise configured / programmed, will be checked by DefaultRequestPolicy, which contains 2 rules:

1. Drupal\Core\PageCache\RequestPolicy\CommandLineOrUnsafeMethod
Denies cache if Drupal is run in CLI or by unsafe method (i.e. request method is neither `GET` nor `HEAD`); and
2. Drupal\Core\PageCache\RequestPolicy\NoSessionOpen
Denies cache if the Drupal user has a login session.

## Make sure your Response is also cacheable

The response cache policy in my installation includes these rules:

1. Drupal\Core\PageCache\ResponsePolicy\KillSwitch
A policy evaluating to static::DENY when the kill switch was triggered.
2. Drupal\Core\PageCache\ResponsePolicy\DenyNoCacheRoutes
Cache policy for routes with the 'no\_cache' option set.
This policy rule denies caching of responses generated for routes that have the 'no\_cache' option set to TRUE.
3. Drupal\Core\PageCache\ResponsePolicy\NoServerError
A policy denying caching of a server error (HTTP 5xx) responses.
4. Drupal\image\PageCache\DenyPrivateImageStyleDownload
Cache policy for image preview page.
This policy rule denies caching of responses generated by the entity.image.preview route.
5. Drupal\node\PageCache\DenyNodePreview
Cache policy for node preview page.
This policy rule denies caching of responses generated by the entity.node.preview route.

Besides, your Response object would also need to implement the CacheableResponseInterface. The simplest way to implement it would be to use the CacheableResponse class

# Summary

To summarize. For a custom controller to have browser cache, you need to meet these criteria:

1. The controller method of the endpoint needs to return an object that implements the CacheableResponseInterface (e.g. a CacheableResponse instance)
2. Have correct cache header setup.
3. Have non-zero cache's maximum age.
4. Have the browser / client calling the controller's endpoint with `GET` or `HEAD` method.
5. Make sure no kill switch nor error is trigger during the rendering process.
6. The route does not match the preview page of node or image.

When the criterias are met, the ETag setup would be effective.

---

**Update:** Correct my "You cannot set ETag" claim. Thanks 4k4 for correcting me.
> 1 votes

# Answer
FinishResponseSubscriber overwrites the ETag header, unless your response meets certain conditions. That is it has to be cacheable and provides a custom Cache-Control header. When testing the code make sure you have browser caching enabled (in the performance settings).

Example:

```
  public function view() {
    $response = new CacheableResponse();
    $response->headers->set('Cache-Control', 'public, max-age=60');
    $response->setEtag('123');
    return $response;
  }

```

Besides browser caching you might also want to set Drupal caching data to invalidate the cached response when the content becomes outdated, see for example Invalidate cache on a REST endpoint.
> 6 votes

---
Tags: 8, caching, symfony-services
---


# Question
Title: Where is the configuration actually saved in the system?
I am new to Drupal 8. I installed the Drupal webform module. I am able to export the configuration file but unable to figure out where the configuration is actually is saved in the Drupal system.

# Answer
Nowhere, most of configuration is located in database including webform.

With config module, you may find webform configuration in admin (yml) : `/admin/config/development/configuration/single/export`

First, select webform in configuration type, then the configuration you need to export.

NB : have a look at sources https://github.com/drupalprojects/webform/blob/8.x-5.x/src/Entity/Webform.php , most of drupal contributions are built the same way, webform extends `ConfigEntityBase` and these are typically stored in database (`config` table as a blob)
> 2 votes

---
Tags: 8, webforms, configuration
---


# Question
Title: Why is my view for Solr indexing is not showing any results?
I have installed solr 8.2.0 for drupal 8.7.6.

My Solr server and index are enabled and indexed. But when try to search via views, the results are not showing up. Please help me in solving this.

My New view

# Answer
> 0 votes
You need to export the solr conf from drupal and import it into solr server.

The export button is on your server conf in drupal.

The readme of the search api module can guide you about that.

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


# Question
Title: How do I need to configure my site on AWS with Elastic Load Balancing to force HTTPS everywhere?
my site is up and running, but all my form submits get redirected to an http:// link. The redirect from http to https on my Server (Apache on EC2) is configured and you don't see any effect as a user. If i create baseurls directly on the server it also returns http:// links.

It causes troubles on the intern side:

* Google Analytics can't track this redirects as the same user and sees every form submit as an new user from a direct source.
* the redirect causes a delay for the user (mostly millisecs)

Config:

* running an Drupal 8.7.7 on an Apache Server.
* http-redirect:

```
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```
* settings.php:

```
  $settings['reverse_proxy'] = TRUE;
  $settings['reverse_proxy_addresses'] = array($_SERVER['PROXY_ADDRESS']);

  $settings['reverse_proxy_trusted_headers'] = \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_AWS_ELB;

```

This config for setting.php was introduced in 8.7.0: https://www.drupal.org/node/3030558

I really don't have any clue what to do now, since i tried like thousands of possibilities.

Best Regards FirstSanny

# Answer
Got it myself.

Configuration is absolutly correct, but i set the wrong reverse\_proxy\_adresses to be allowed. I thought, that i can use the beanstalk-url, but it worked perfectly fine with one of the internal IP Configs for AWS: 172.16.0.0/12
> 1 votes

---
Tags: 8
---


# Question
Title: Send welcome email on one time login via admin UI
I am Importing all my users into drupal but I don't want to send the welcome emails now.

When the site goes Live I want to be able to push a button or perform an action which sends all the users the welcome email and one time login URL so they can login and reset their password.

Thanks

# Answer
Once imported, on the /admin/people page you can select all users and deactive the accounts. If you activate them again, they get the e-mail.
> 0 votes

---
Tags: users, emails, importing-exporting
---


title: Display the day of the week

text:
# Question
Title: Display the day of the week
I have a date field (field\_date) and on the right of this field I have to display the day of the week

# Answer
> 1 votes
You can change how dates from date fields are displayed by changing it on the `Manage display` (/admin/structure/types/manage/\[my\_CT\]/display) page for that Content type.

## Custom date format for individual field

The quick and dirty way of doing it is by choosing `Custom` for Formatter and entering the code for the date, for example:

```
Y-m-d\TH:i:s, l

```

will give you "2019-09-09T17:30:19, Monday".

You can lookup the various date and time codes in the PHP manual: https://www.php.net/manual/en/function.date.php

Overriding individual fields displays with custom date formats isn't the best way to go because you can't reuse it throughout the site, for other fields, or translate into other languages (different countries have different conventions about how to write dates).

---

## Reusable Custom date format

The best way is to first add the new Date format to your site. This way you will be able to use anywhere where you can format Date output.

Go to `Configuration > Regional and language > Date and time formats` and Add a new format.

Name it so it makes sense to your case, enter the PHP date code you want into the `Format string`, select Language and add the format.

Now visit your Content type's `Manage display` page and change the `Formatter` of the Date field you want to affect to `Default`, and the `Date format` to the one you have just created.

# Answer
> 0 votes
If your question is for showing the day on the content create/edit form, and not displaying after saving that form (which I answered in the previous answer), you'll have to change the **widget** for the date field.

You can do that through some custom code, but I believe the Bootstrap Datepicker module can do that too (I haven't tried it).

That module has the `Date format` option where you can enter for example

`mm/dd/yyyy DD`

to get

`09/10/2019 Tuesday`

in the Date input field after selecting a date from the calendar popup.

---
Tags: 8, nodes
---


# Question
Title: How can I create two blocks at once from the same custom module?
I have figured out how to create a block from a custom module, by creating a ./src/Plugin/Block folder, then creating a PHP script inside it, with the following code:

```
<?php
namespace Drupal\MY_MODULE_NAME\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a block with a simple text.
 *
 * @Block(
 *   id = "BLOCK_MACHINE_NAME",
 *   admin_label = @Translation("BLOCK_DISPLAY_TITLE"),
 * )
 */
class MyBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {

    $html = "MY_BLOCK_CONTENTS_HERE";
    return [
      '#markup' => $this->t( $html ),
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access content');
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this->getConfiguration();
    return $form;
  }

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

```

My question is, if I want my Custom Module to create a second block, how would I do that?

Do I just create a second script under ./src/Plugin/Block using this same format, and change the BLOCK\_MACHINE\_NAME and BLOCK\_DISPLAY\_NAME values?

If I change the line:

```
class MyBlock extends BlockBase { ... }

```

to

```
class MySecondBlock extends BlockBase { ... }

```

... can I keep all the functions under it the same, eg:

```
class MySecondBlock extends BlockBase {
    public function build() { ... }
    protected function blockAccess() { ... }
    public function blockForm() { ... }
    public function blockSubmit() { ... }
}

```

Or is it more complicated than that? Do I need to try and build both Blocks from within the same script, and a single set of functions?

Any advice is greatly appreciated, thanks!

# Answer
> 3 votes
You can a create as many block plugins as you want within a single module. Each of these plugins must have a unique ID in annotation. In order to reduce code duplication you can create an abstract class that would hold all common functionality. Other classes can extend it and override methods that need a different implementation.

# Answer
> 0 votes
Don't forget to add a block category as well.

```
/**
 * Provides a block with a simple text.
 *  * @Block(
 *   id = "BLOCK_MACHINE_NAME",
 *   admin_label = @Translation("BLOCK_DISPLAY_TITLE"),
 *   category = @Translation("SUCH_AS_VIEWS_MENU ETC")
 * )
 */

```

---
Tags: 8, blocks
---


# Question
Title: How to add a theme preprocess function for published state?
I want to create a body class for the published state of a node. I found some suggestions below for Drupal 7, but this code is not working for my Drupal 8 theme.

Add class based on published state

How can I acheive this?

# Answer
> 6 votes
You can fetch the node using `routeMatch` and add the class like this:

```
function THEME_NAME_preprocess_html(&$variables) {
  $routeMatch = \Drupal::routeMatch();
  $node = $routeMatch->getParameter('node');
  if (isset($node) && $routeMatch->getRouteName() == 'entity.node.canonical') {
    if ($node->isPublished()) {
      $variables['attributes']['class'][] = 'class-name-published';
    }
    else {
      $variables['attributes']['class'][] = 'class-name-unpublished';
    }
  }
}

```

This only adds the body class if you're on the `entity.node.canonical` route, to make sure that we always get a node object from the route parameter.

---
Tags: 8, theming, entities
---


title: Replacing a pdf

text:
# Question
Title: Replacing a pdf
I am looking to delete a file permanently.

It says that is is not being used in any places and I have deleted it, but it is still showing up. I want to replace it, but Drupal just keeps making a new version.

I've even tried to redirect to a newer version of the file but it still doesn't work.

Please advise.

# Answer
You can use a php function (via devel, Drush or DrupalConsole) `file_delete($fid)` to remove the file from the server. Then your redirect will work. Also it's helpful to read through this ticket if you have the time and the patience.
> 0 votes

---
Tags: files
---


title: How to prevent cart from being emptied

text:
# Question
Title: How to prevent cart from being emptied
In my Drupal 7 site I have inserted an extra page in the checkout process (using a custom module), after the review page, where the customer can choose between 2 custom payment methods. My problem is that if the customer **decides to leave the checkout process** after reaching the custom payment page, all line items are cleared from the cart.

If he/she only goes one step back to the review page the cart is still intact. Also if he/she leaves the checkout process from the review page, the cart is not emptied, even after going back from the custom payment page. So it does not seem as though the cart is emptied when clicking Continue on the review page, after all.

Now, I need to change this behaviour so that the cart is not cleared if the visitor leaves the checkout process when on my custom payment page.

What do I need to do?

# Answer
> 0 votes
Turns out I needed to update the order state on the new checkout page. Since the user is supposed to choose a payment method on this custom page it suffised to create a simple Rule that fires on that event.

In case anyone else have the same problem (as described in the question), here it is:

```
{ "rules_keep_order_state" : {
    "LABEL" : "Keep order state",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_payment" ],
    "ON" : { "commerce_payment_methods" : [] },
    "DO" : [
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce_order" ], "order_state" : "checkout" } }
    ]
  }
}

```

---
Tags: 7, commerce
---


# Question
Title: User Locked out after 5 failed login attempts - how to help him?
I have a user with 5 failed login attempts...and now he's locked out. We reset his password...but is there something else we need to do to unlock his account on a basic Drupal 8 setup?

I'd rather not have to get into using drush on this remote server and messing around with db tables...especially since this is just one user out of thousands. I just want a simple UI solution.

Or does he have to wait 6 hours or something crazy?

# Answer
If you use flood\_unblock module you can just flush the flood for the specific user or ip.
> 4 votes

# Answer
There's a default config for flood settings in `core/modules/user/config/install/user.flood.yml`:

```
uid_only: false
ip_limit: 50
ip_window: 3600
user_limit: 5
user_window: 21600

```

This means, that your user is locked for 21600 secs by default. Be patient :-) Unfortunately, there's no UI for that config currently. A workaround would be to import a single config in the Config-Sync UI.

All flood info is stored in table "flood". It's save to delete * from flood to reset all floodings. A flood info is by default ip-based like "uid-ip". So, if your user can change his client IP, she may be able to login before 21600 secs have passed.
> 0 votes

---
Tags: 8, users
---


# Question
Title: How to grant create and update permissions to a custom role?
I have a new role as "Publisher". I want to grant Publisher 'create' and 'update' permission using code.

My .permissions.yml file looks like this :

```
'delete contact entity':
  title: Delete entity content.
'add contact entity':
  title: Add entity content
'view contact entity':
  title: View entity content
'edit contact entity':
  title: Edit entity content
'administer contact entity':
  title: Administer settings
'publisher contact entity':
  title: Publisher settings

```

I've used 2 functions to allow permissions. The functions are:

```
 protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
// Check the admin_permission as defined in your @ContentEntityType
// annotation.
$publisher_permission = $this->entityType->getPublisherPermission();
if ($account->hasPermission($publisher_permission)) {
  return AccessResult::allowed();
}
switch ($operation) {
  case 'edit':
    return AccessResult::allowedIfHasPermission($account, 'edit contact entity');

  case 'update':
    return AccessResult::allowedIfHasPermission($account, 'update contact entity');
}
return AccessResult::neutral();  }

protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
// Check the publisher_permission as defined in your @ContentEntityType
// annotation.
$publisher_permission = $this->entityType->getPublisherPermission();
if ($account->hasPermission($publisher_permission)) {
  return AccessResult::allowed();
}
return AccessResult::allowedIfHasPermission($account, 'edit contact entity');   }

```

Now, If check sitename/admin/people/permissions, the role is created by it doesn't have a tick in the checkbox for `edit contact entity.`

PS: In @ContentEntityType, I've defined publisher permission as:

```
publisher_permission = "publisher contact entity"

```

# Answer
> 0 votes
You may grant your permissions on install time of your module with a simple config in config/install/user.role.publisher.yml (about this):

```
langcode: en
status: true
dependencies: {  }
id: publisher
label: Publisher
weight: 3
is_admin: null
permissions:
  - 'add contact entity'
  - 'edit contect entity'

```

Your code above is not a "grant", it's a runtime-check of users permissions.

---
Tags: 8, users, hooks
---


# Question
Title: Forgot to do config ignore before building webform. How to correct it and ignore the webform from the export?
Complete newbie to Drupal here. I forgot to configure my config ignore before I built a webform. I have now managed to do add webform.webform\* to the config ignore but that doesn't solve my problem since the webform has already been exported. How do I fix the import/export settings in order to remove the webform?

# Answer
> 1 votes
Thanks all for your reply and apologies for my late response. Yes, I am using config\_ignore and config\_split module. I just added webform to config\_ignore and then deleted the files from the git repository so next time they will not be added to git. Worked.

---
Tags: webforms
---


# Question
Title: Webform Submission Using Rest API POST method
I just created the webform and added fields.

I need to create a Webform Submission Using Rest API POST method. I just installed Rest & Rest UI modules for this.

But when I try to test my API using API tester its showing the error like this :

```
{"message":"Could not determine entity type bundle: \u0022webform_id\u0022 field is missing."}

```

But I have already determined the webform\_id and here is my configuration

POST URL : http://example.com/entity/webform\_submission?\_format=json

**Headers :**

Content-Type : application/json

**POST Data :**

```
{
  "type": {
      "webform_id": "my_form"
    },
"your_mobile":[{"value":"123456789"}],
"your_name":[{"value":"Test"}],
"your_email":[{"value":"test@gmail.com"}]
}

```

Drupal Version : 8.6.4 Webform Module version : 8.x-5.1

Can anyone let me know Why its not working?

# Answer
> 6 votes
Looking at the examples on the Webform REST project page, you should be using something like…

```
{
  "webform_id": "my_webform",
  "checkboxes_field": [
    "Option 3",
    "Option 5"
   ],
   "integer_field": 3,
   "radio_field": "Mail",
   "email": "myemail@mydomain.com.au"
}

```

# Answer
> 2 votes
Don't forget to enable required services under `/admin/config/services/rest`:

1. Enable REST resource "Webform Submit"
2. Enable REST resource "Webform Elements"
3. Enable REST resource "Webform Submission"

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


# Question
Title: Setting a Twig to a specific Form Container
As the title says,

There is a specific Form Container that I would like to add a twig to that is on a page having its own twig. No theme hook name suggestion is provided when I inspect its element.

My purpose is to style the specific form to be a credit card form.

# Answer
> 1 votes
You could try to add your own template suggestion via hook\_theme\_suggestions\_HOOK\_alter, which would mean hook\_theme\_suggestions\_container\_alter. There you might target the container by id or some other attribute (id does not seem promising here).

The container.html.twig does only provide a wrapping div around other content. While you could add more html to this, you might have to think about if container.html.twig is the right place to start here.

---
Tags: 8, theming
---


title: Add Fields to View page

text:
# Question
Title: Add Fields to View page
I have a view that is a page and I'd like to be able to add a a field to this page.

My other pages are content type pages and they have the option to assign a top hero banner content type to them. How can I assign a hero banner content type to a view page?

# Answer
> 3 votes
In your view's edit screen do the following:

1.) Under Format, **Change Show: Content** to **Show: Fields**

* By clicking on Content and then selecting Fields

2.) Under Filter Criteria add **Type** and then check mark your content type name.

# Answer
> 0 votes
You can add an header field in your view.

---
Tags: views, 8
---


title: Prevent login except from Services

text:
# Question
Title: Prevent login except from Services
I would like to prevent my users to login except for those who login through my REST Service.

Is that possible?

# Answer
> 1 votes
It sounds like the login\_disable module will do exactly what you need.

> Prevent users from logging in to your Drupal site unless they know the secret key to add to the end of the login form page. ( default: http://example.com/?q=user/login&admin )
>
> If your site has clean urls enabled you may use http://example.com/user/login?admin instead.

That way you can set a secret key so only users who know that key are able to log in using the login form.

Another possible solution would be to disable the login form completely, like this:

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['#access'] = FALSE;
  }
}

```

---
Tags: 7, users, services
---


title: How to get fields from taxonomy terms?

text:
# Question
Title: How to get fields from taxonomy terms?
I am able to retrieve taxonomy terms programmatically, (as long as I only want to reference the default fields, 'tid' and 'name'). But how do I access custom taxonomy fields?

```
$vid = 'MACHINE_NAME';
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
    $tid = $term->tid;
    $term_name = $term->name;

    // REFERENCE CUSTOM FIELD VALUES HERE...

}

```

I have tried all manor of ways I have seen, but can't get any of them working, eg:

```
$value = $term->FIELD_NAME->value;
$value = $term->get('FIELD_NAME')->getValue();

```

How do I reference custom taxonomy term fields by their machine name, from what is returned by getStorage('taxonomy\_term')-\>loadTree($vid)?

# Answer
> 3 votes
The entities aren't loaded by default (for performance reasons), but `TermStorage::loadTree` takes a `$load_entities` parameter:

> If TRUE, a full entity load will occur on the term objects. Otherwise they are partial objects queried directly from the {taxonomy\_term\_data} table to save execution time and memory consumption when listing large numbers of terms. Defaults to FALSE.

That will give you access to the fields. E.g.

```
$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadTree($vid, 0, NULL, TRUE);

```

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


# Question
Title: Call to undefined function Drupal\Component\Utility\imagecreate()
I got this error on a server I setup and was confused:

> Error: Call to undefined function Drupal\Component\Utility\imagecreate() in Drupal\Component\Utility\Random-\>image() (line 282 of /var/lib/jenkins/src/grls/docroot/core/lib/Drupal/Component/Utility/Random.php

# Answer
> 2 votes
The imagecreate function is part of php's gd library. If a server has been set up manually it's possible it doesn't have the gd library.

First, figure out which version of php you are using, for example with this command:

`dpkg -l | grep '^ii' | grep php`

Look for a line like:

```
ii  php7.2     7.2.19-0ubuntu0.18.04.2           all          server-side, HTML-embedded scripting language (metapackage)

```

That indicates the server is using php7.2. To install gd library for php7.2 on a system managed with apt you need a command something like:

`sudo apt install php7.2-gd`

And then the error will be gone.

---
Tags: 8
---


# Question
Title: How to remove white space from a field using Search API module
I'm using Search API and Search Views to search the Drupal user database.

One of the fields is phone number where users are able to enter free text.

I can include this field in the search, but the search will not pick up part words.

E.g. 6162 5555 - does not display when I search for 25555 because the index sees these terms as separate words.

Is there a way to strip all the site space (and maybe then brackets) from the field before it is indexed by Search API?

# Answer
> 1 votes
I would use Computed Fields. Store and display user input with spaces, but index and search computed field too.

> These computed fields are populated with values that you define via PHP code.

So you can simply remove white spaces, or re-format phone number in any way you please, and store a standardised copy of user's phone number. That way both representations will be searchable.

As a small bonus, other modules (like Views, various exporters and connectors or phone integration) would be able to benefit from this too. Bad thing is a slight overhead on reads and saves.

# Answer
> 1 votes
You need to disable Tokenizer. Then it should work.

---
Tags: search
---


title: How run a view in MySQL

text:
# Question
Title: How run a view in MySQL
From a view, I get the following in the Auto preview Preview with contextual filters:

```
SELECT node.nid AS nid, node.created AS node_created, node_field_data_field_title.title AS node_field_data_field_title_title, field_data_field_it_ac.field_it_ac_value AS field_data_field_it_ac_field_it_ac_value, field_data_field_clon.field_clon_nid AS field_data_field_clon_field_clon_nid, field_data_field_ts_year.field_ts_year_value AS field_data_field_ts_year_field_ts_year_value, field_data_field_it_volume.field_it_volume_value AS field_data_field_it_volume_field_it_volume_value, field_data_field_it_cl.field_it_cl_value AS field_data_field_it_cl_field_it_cl_value, 'node' AS field_data_field_it_ac_node_entity_type, 'node' AS field_data_field_clon_node_entity_type, 'node' AS field_data_field_taksithetiko_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_title} field_data_field_title ON node.nid = field_data_field_title.entity_id AND field_data_field_title.entity_type = 'node'
LEFT JOIN {node} node_field_data_field_title ON field_data_field_title.field_title_nid = node_field_data_field_title.nid
LEFT JOIN {og_membership} og_membership_node ON node.nid = og_membership_node.etid AND og_membership_node.entity_type = 'node'
LEFT JOIN {field_data_field_deleted} field_data_field_deleted ON node.nid = field_data_field_deleted.entity_id AND field_data_field_deleted.field_deleted_value = '1'
LEFT JOIN {field_data_field_it_ac} field_data_field_it_ac ON node.nid = field_data_field_it_ac.entity_id AND field_data_field_it_ac.entity_type = 'node'
LEFT JOIN {field_data_field_clon} field_data_field_clon ON node.nid = field_data_field_clon.entity_id AND field_data_field_clon.entity_type = 'node'
LEFT JOIN {field_data_field_ts_year} field_data_field_ts_year ON node.nid = field_data_field_ts_year.entity_id AND field_data_field_ts_year.entity_type = 'node'
LEFT JOIN {field_data_field_it_volume} field_data_field_it_volume ON node.nid = field_data_field_it_volume.entity_id AND field_data_field_it_volume.entity_type = 'node'
LEFT JOIN {field_data_field_it_cl} field_data_field_it_cl ON node.nid = field_data_field_it_cl.entity_id AND field_data_field_it_cl.entity_type = 'node'
WHERE (( (og_membership_node.gid = '20' ) )AND(( (node.status = '1') AND (node.type IN  ('item')) AND (field_data_field_deleted.field_deleted_value IS NULL ) )))
ORDER BY field_data_field_it_ac_field_it_ac_value ASC, field_data_field_clon_field_clon_nid ASC, field_data_field_ts_year_field_ts_year_value ASC, field_data_field_it_volume_field_it_volume_value ASC, field_data_field_it_cl_field_it_cl_value ASC
LIMIT 20 OFFSET 0

```

Which brings in the preview the results I need.

In order to get the same results in MySQL, I run the same query without the brackets {}, and I get irrelevant results... How should the brackets be replaced, how should I alter the above query in order to get the same result I get from the view?

# Answer
> 0 votes
You should remove the square brackets, but also do some other modifications. As this wuold take me too long to debug, you can use hook\_views\_pre\_execute() to view the exact query:

```
function MYMODULE_views_pre_execute(&$view) {
  dpq($view->build_info['query']);
}

```

Make sure the Devel module is enabled for this.

---
Tags: 7, views
---


# Question
Title: How can I exclude some entities in "drush entity:delete" command?
I want to delete all content of custom entity type except some specific items, I found `drush entity:delete CUSTOM_TYPE` command to delete all contents but couldn't exclude some items from deletion in this command, does it have any option like `--exclude ID1, ID2, ID3, ...`?

Or is there any other way to do this?

# Answer
```
$ drush entity:delete node --bundle=article --exclude=9,14,81

```

or

```
$ drush entity:delete CUSTOM_TYPE --exclude=1,2,3

```

I added the `--exclude` option as a pull request #4175 to Drush. It also works in Drush 9, so you could use this pull request to patch your local Drush like that:

```
"patches": {
    "drush/drush": {
        "Add option to exclude entities by ID to entity:delete command.": "https://github.com/drush-ops/drush/pull/4175.patch"
    }
}

```
> 4 votes

# Answer
ok mate you want other options and here is the answer:

if you look at

vendor/drush/drush/src/Drupal/Commands/core/EntityCommands.php

you can see the what the function does....

now you need to learn how to make a custom drush commands i assume you are using drush 9 so you can just run:

"drush generate drush-command-file"

or read: https://www.axelerant.com/resources/team-blog/how-to-write-custom-drush-9-commands-for-drupal-8

this will create: modules/custom/YOURMODULE/drush.services.yml and modules/custom/YOURMODULE/src/Commands/YOURMODULECommands.php

now have a look at the following working example ...

```
<?php
/**
 * Command delete some stuff
 *
 * @param $entity_type
 *   Argument for entity type.
 * @param $exclude
 *   Argument for exclude delete of ids.
 *
 * @param array $options
 *   An associative array of options whose values come from ...
 *
 * @option option-name
 *   Description
 *
 * @usage deletethings-commandName foo
 *   Usage description
 *
 * @command deletethings:commandName
 * @aliases delete-my-stuff
 */
 public function commandName($entity_type, $exclude,  $options = ['option-name' => 'default']) {
$this->logger()->success(dt($entity_type));
$this->logger()->success(dt($exclude));
$exclude_ids= [];
if ($exclude !== 'none') {
  $exclude_ids = explode(',', $exclude);
}

// now do the delete stuff
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
if (is_object($storage)) {
  $all = $storage->loadMultiple();
  if (count($all) !== 0) {
    foreach ($all as $entity) {
      $id = $entity->id();
      if (!in_array($id, $exclude_ids)) {
        // kill with fire.
        $entity->delete();
      }
    }
  }
}
}

```

With that you can run:

drush delete-my-stuff ENTITY\_TYPE 5,6,10

example: drush delete-my-stuff node 5,6,10

this would then allow you to delete all items of your entity except for "5,6,10" - which are ids you want to keep

or drush delete-my-stuff ENTITY\_TYPE none (to delete all)

remember to run drush cr and drush cc (1) so drush will recognise the new command
> 3 votes

---
Tags: 8, drush
---


# Question
Title: How can I debug adding libraries via hooks?
I am trying to attach simple css via hooks in the themes and it does not work? The code looks correct to me. It doesn't attach. What am i doing wrong?

```
global-styling:
  version: 8.x
  header: true
  css:
    base:
      css/main.css:

  js:
    js/main.min.js: {}
    js/scrollreveal.js: {attributes: { defer: true} }
    src/js/vendor/picturefill/picturefill.min.js: {attributes: { defer: true} }
    js/custom.js: {attributes: { defer: true, async: true} }
    js/tp.widget.bootstrap.min.js: {attributes: { defer: true} }
    js/js.cookie.min.js: {attributes: { defer: true} }
    js/api.js: {attributes: { defer: true} }

  dependencies:
    - core/drupal
    - core/jquery

content-styling:
  css:
    base:
      css/content.css: {}

carousel-styling:
  css:
    base:
      css/carousel.css: {}

```

I am trying to attach css/content.css only when an entity reference to a paragraph is displayed. I am trying to attach css/carousel.css only when an certain paragraph type (slider) is displayed

```
function porto_sub_preprocess_field(array &$variables, $hook) {

  if(  $variables['element']['#entity_type'] == 'paragraph' ) {
     \Drupal::logger('my_module')->notice('content should be');
        // tried both these on all
        $variables['element']['#attached']['library'][] = 'porto_sub/content-styling';
        $variables['#attached']['library'][] = 'porto_sub/content-styling';
  }
}

function porto_sub_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  if($paragraph->getParentEntity()->bundle()=='slider') {
    \Drupal::logger('my_module')->notice('carousel should be');
    $variables['element']['#attached']['library'][] = 'porto_sub/carousel-styling';

  }
}

```

Then i tried....still nothing

```
function porto_sub_page_attachments(array &$attachments) {
      $attachments['#attached']['library'][] = 'porto_sub/content-styling';
    $attachments['#attached']['library'][] = 'porto_sub/carousel-styling';

```

x }

Is there some way i can debug? I get no information regarding what's wrong here.

# Answer
> 1 votes
To attach a library to a certain paragraph type you could use `template_preprocess_paragraph__PARAGRAPH_TYPE()` like following. Note how it's just added to the `$variables` array not the element.

```
function MYTHEME_preprocess_paragraph__slider(&$variables) {
  $variables['#attached']['library'][] = 'MYTHEME/carousel-styling';
}

```

Same with the field. Simply use `template_preprocess_field__FIELD_NAME()` and attach the library directly to the `$variables` array.

---

Your `content-styling` and `carousel-styling` libraries probably should look more like following. Note how it's added as `theme` category, not as base. See the docs on File Structure for some info about SMACSS.

```
content-styling:
  css:
    theme:
      css/content.css: {}

```

---

**And finally**: Flush cache, flush cache and flush the cache again!!!!!!!

---
Tags: 8, theming
---


# Question
Title: views_pre_render add class item to a row
When pre-rendering a view row is there a way to add an HTML class into a single row of the markup, allowing me to add a new background colour to the event item highlighting its importance? This is for the calendar module monthly view

For example,

```
<div class="row"></div>
<div class="row this-item-was-added-using-view-views_pre_render"></div>
<div class="row"></div>

```

Below the is the what I have so far.

```
function pnc_views_overrides_views_pre_render(\Drupal\views\ViewExecutable $view)
{
      if ((int)\Drupal::currentUser()->id() === 1) {
        foreach ($view->result as $key => $value) {
          try {
            $field_result_value = $value->_entity->field_display->getValue();
            if (isset($field_result_value[0]) && (int)$field_result_value[0]['value'] === 1) {
              // add a class to the change the background color to hi-light its importance
            }
          } catch (Exception $e) {
            \Drupal::logger('viewoveride_pnc_cal_views_overrides')->error($e->getMessage());
          }
        }
      }
}

```

# Answer
> 0 votes
Because you do not want to alter some data, you should use a preprocess function for this. Check this out:

```
function MYMODULE_preprocess_views_view_unformatted(&$variables) {
  $view = $variables["view"];
  $viewId = $view->id();
  if($viewId == 'my_view_id'){
    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {
      $important = $row['content']['#row']->_entity->get('field_result_value')->getString();
      $custom_row_class = 'views-row-' . $important;
      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }
  }
}

```

---
Tags: views, 8
---


# Question
Title: Create a View that Displays a group of Taxonomy Terms
I have a proposed data structure like this:

**Asset:**

* Title
* Image
* Description
* Taxonomy term: Campaign

**Campaign** (taxonomy dictionary):

* term
* image
* description

I am trying to make a view block that displays only the Campaign group, represented by the Campaign image. The farthest I can get is defining a relationship to tax. terms on node, and displaying all Assets with that tag. I can even Group them, which is really close to what I need. How do I solve the problem of displaying "Campaigns" as groups of assets (not the list of assets tagged with this taxonomy).

I thought I could show a list of (non-duplicate) fields where that tax. image exists (which should be once per group/aka "Campaign"). But not so far..

How do I achieve this? Have I overlooked something? I am open to different approaches or ideas..

# Answer
> 0 votes
If you want to group Assets just by the Campaign (taxonomy) image, you can easily set the Grouping feature under `Format` to the Image field.

You have to add the Relationship for the taxonomy field first, as you have found out, then you get all the information related to the referenced taxonomy term into the Views. Without that Relationship you only have the Taxonomy term ID available, as the Taxonomy reference field only stores that info.

When you add the Relationship you can add the Taxonomy image field (Campaign image). Each Asset will then show its associated campaign image in its row.

That's when you can use `Group by field` and set it to the Campaign image. This will split the Asset results into Campaign groups with the image field as the "group header". You will still see the image displayed in each row, which you probably don't want, so you edit the Campaign field setting in Views and choose `Exclude from display`. This way the image will only display in the "group header" and won't display next to each Asset result.

---

If you need to display more info about the Taxonomy (Campaign) in the "group header", for example the name, image, and the description, you can add all those fields to your Views, Exclude them from display, and set them all to group by.

But sometimes the styling that comes out of this strategy isn't good enough, the HTML can be a bit unexpected. You can solve that by using `Custom text` field after all the Taxonomy fields where you enter your own HTML with the taxonomy field values printed out through tokens. And Group only by the Custom text field.

I've written an article about this if you need more detail: Grouping by multiple Fields in Drupal Views

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


title: Add content screens from the front end

text:
# Question
Title: Add content screens from the front end
I am building a web application (for trusted users), so the logged in user will have the ability to add content. However currently, when the user wants to add a record, they move from the frontend theme to the Admin UI, (the "Content \> Add Content \> Article" page).

This looks unprofessional, and I don't really want non-technical users let loose on the Admin UI.

How can I create "frontend" pages to let the user Add New Nodes or Edit Nodes?

(Essentially, I want to mimic the Add Article and Edit Article screens, but on the frontend of the site).

I'm not afraid of a bit of custom coding if necessary, but need to be pointed in the right direction!

# Answer
Go to /admin/appearance, uncheck the box name 'Use the administration theme when editing or creating content', and save.
> 1 votes

---
Tags: views, 8, nodes
---


title: hook_menu() item never reached?

text:
# Question
Title: hook_menu() item never reached?
I have a module where hook\_menu() was already used to process ajax calls, like this:

```
function bizaudit_menu() {
  return [
    'bizaudit/ajax' => [
      'page callback'     => '_bizaudit_ajax_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
    'bizaudit/autoexec' => [
      'page callback'     => '_bizaudit_autoexec_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
  ];
}

```

That works pretty well from times, then I just added another item, now to handle some precise route, like this:

```
function bizaudit_menu() {
  return [
    'bizaudit/ajax' => [
      'page callback'     => '_bizaudit_ajax_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
    'bizaudit/autoexec' => [
      'page callback'     => '_bizaudit_autoexec_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
    'navigate' => [
      'page callback'     => '_bizaudit_navigate_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
  ];
}

```

But this route seems to be never recognized!
To be sure I changed the callback function like this:

```
function _bizaudit_navigate_handle() {
  $query_params = drupal_get_query_parameters();
  echo implode('<br>', print_r($query_params, true));
  exit;
}

```

Using this url `127.0.0.1/apim/navigate` should cause the query params to be printed (here empty, but no matter), and nothing else to happen.
Instead I get the normal content of the involved page displayed!
(I didn't omit to clear the cache)

Maybe I'm missing someting obvious?

# Answer
> 0 votes
I think I see your problem

hook\_menu is for defining your own page paths in code. It's not for hooking into the processing of a page that already exists. So you've got a conflict where you have 2 pages with the same url and the latter (the node/view page or whatever is it with the same url) is taking precedence over your bizaudit\_menu definition. So your code created path is never triggered as Drupal has found another route for your "apim/navigate" path

---
Tags: 7, hooks, routes, navigation
---


# Question
Title: How to stop CKEditor 3.6.3.7474 from stripping <script> tags
With `Full HTML` enabled and related filters off, CKEditor will strip any `<script>` tags from content it is editing. The editors who create content for this particular site need to be able to embed things like this in the content they are creating:

```
    <img src="http://s2.thingpic.com/images/TD/zKWJQJiFBsp3oP1etNC1.png" width="560" class="alwaysThinglink"/>
<script charset="utf-8" src="//www.thinglink.com/jse/embed.js#286861458501795840"></script>

```

In theory we can make this work by disabling CKEditor and working directly with HTML, but in practice it doesn't work: the editors are not HTML-savvy. They know enough to temporarily drop out of rich-text mode, paste in the above, and then switch back to rich-text mode. But if they go to edit that content again, CKEditor strips the `<script>` tags when opening the content.

How can I stop that behavior and have CKEditor leave the `<script>` tags in place? Is there a hidden setting somewhere for that?

BTW, we are using CKEditor in conjunction with `Wysiwyg 7.x-2.1` module.

And yes, in general allowing `<script>` is very bad, but in this case the only people who have access to the Full HTML format are the editors (who are trusted).

Thanks!

# Answer
> 14 votes
You can resolve this by going to the "Advanced Options" section of your CKEditor profile and adding the following string into the text area: config.allowedContent = true;

This resolved the issue for me.

# Answer
> 9 votes
I was running into this too, and it was very frustrating.

For me, the problem was with the Teaser Break plugin that's bundled with the Wysiwyg module. Disabling that button for my Wysiwyg profile solved the problem for me.

You can disable the Teaser Break wysiwyg plugin in Administration › Configuration › Content authoring › Wysiwyg profiles (/admin/config/content/wysiwyg).

I'm very interested to know if this solves your problem also, or if you were running into a different issue. I just filed a new bug for this at http://drupal.org/node/1801166.

# Answer
> 2 votes
I think you are looking for the setting:

* page admin/config/content/ckeditor/edit/advanced (replace advanced with your profile name).
* tab Advanced content filter.
* set to Disabled.

Alternatively you can set it to Enabled and add the script tag in "Extra allowed content", but with scripting allowed, you can as well allow anything.

This setting is from the CKEditor module thus this holds for when you are not using the Wysiwyg module. When using wysiwyg\< I guess you have to find out what this setting does, probably setting some options in the CKEditor.

BTW: Why use wysiwyg in between instead of going for the full feature set of CKEditor. I stopped using wysiwyg when CKeditor 4 came out and wysiwyg could not offer support for that for a long time after. As I always and only use CKEditor, what's the point of having wysiwyg in between?

# Answer
> 0 votes
Have you checked the Textformat Settings? So that not "limit HTML Tags" is checked? Anyway i think the Ckeditor Module without WYSIWYG Module is more stable.

# Answer
> 0 votes
Old old question, but another way to handle this is to disable the WYSIWYG by default. If the WYSIWYG doesn't engage (turn on/whatever) in edit mode, then the script tag isn't stripped. In my use case this works out.

---
Tags: 7, wysiwyg
---


title: Custom remote video thumbnail

text:
# Question
Title: Custom remote video thumbnail
I'm using the media entity from Drupal core together with the media library, to handle media on my site.

I have `Remote Video` and `Image with crop` media types. I'm using the `crop` and `image_widget_crop` modules to manually crop images on my site.

Remote video supports `YouTube` and `Vimeo`.

Right now the thumbnail is automatically generated, but I want to be able to upload a custom thumbnail. If no custom thumbnail is provided, it will just use the auto generated one.

I found this guide, but it is for Drupal 7.

Has anyone done something similar to this in Drupal 8?

# Answer
> 4 votes
I solved the problem by adding an image field on the remote video media entity and then altering the media entity on presave, like this:

```
/**
 * Implements hook_entity_presave().
 */
function MY_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'media' && isset($entity->field_media_image->entity)) {
    $entity->thumbnail->target_id = $entity->field_media_image->target_id;
  }
}

```

The image field is called `field_media_image`.

---
Tags: 8, entities, media
---


# Question
Title: Remove an item from list of taxonomy terms prior to rendering
What is the correct way to remove an item from a list within `hook_entity_view` or `hook_preprocess_node`?

I am trying to remove a taxonomy term from a list of terms `EntityReferenceFieldItemList`. I calculate two boolean values, if both are true then the item should be removed from the list.

I've tried removing the second item in the list. That works, but removing the first item results in all the items being removed. Is this because the list keys are no longer sequential?

```
function mymodule_node_view(&$variables) {
  # calculate $field_hide_term and $node_in_past

  foreach($build['field_terms']['#items'] as $key => $term) {
    if ($field_hide_term && $node_in_past) {
      unset($build['field_terms'][$key]); # This also removes other items in the list if key is 0.
    }
  }
}

```

# Answer
Instead of using `unset()`, you can use `#access = FALSE`, like this:

```
$build['field_terms'][0]['#access'] = FALSE;

```
> 1 votes

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


# Question
Title: Make my view the default for content type
I am probably doing this the wrong way, so please correct me if I am wrong!

I have created a new content type, called "Entities". My content type has many fields, and the default view when you visit "/node/123" is ugly, and doesn't permit much customization. So I created a new View with all my fields displayed exactly how I want, and set the path to be "entity/%", so when you visit "/entity/123" you get my new, prettier version.

However, the default view at "/node/123" still exists, and is the default display when you click on a link in the search results, or admin interface, etc.

How can I make it so "/entity/123" (my view) completely replaces "/node/123" (default view) everywhere? Eg. becomes the default view for the "entity" content type?

# Answer
Your main concern is you don't want the /node/123 link to be available publicly or in search results? You could unpublish the node and then make a Boolean field in your content type and for your view choose to show the piece of content based on your new boolean field INSTEAD Of the stock published/unpublished checkbox. So your view by default will only show "published" content but you can change that so that it shows "live" content (new boolean field you created for that content type) or like that and ignores the published/unpublished field. So node/123 won't show up for anonymous users or in search results but will still be processed by your view. Assign the view to the path of your choice /contact-page or whatever and you're golden.
> 0 votes

---
Tags: views, 8, nodes
---


# Question
Title: Where to programmatically enable a Feature module
I created a Drupal 7 feature and usually I would enable it with Drush, but someone suggested that I enable it with an update hook (which I assume means it gets enabled on updb or update.php).

I saw this discussion on enabling modules programmatically How do I programmatically install and enable a module?, but it blithely skips over where to write the code. Does it go somewhere in the installation profile? Does it have to be called from another custom module that is already enabled?

I'm actually an experienced Drupaler that has somehow managed to miss this one crucial lesson, I've just been using Drush to enable modules but I want to do this the best way.

# Answer
A feature module is just another module. And you can enable it programmatically using the linked code from another enabled module's `hook_update_N` placed in this another enabled module's `*.install` file. This even can be another feature module. Then have this hook fired via `drush updb` on the command line or by visiting your site's `/update.php`.

You also could do that from a form submit handler. Or even from a menu callback providing some custom endpoint you can access with cURL for example.

It's safe to use other feature modules' `*.install` files. Since Features never touches `*.module` and `*.install` files during regeneration. So you are free to use them to your needs.
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: How do I programmatically install and enable a module?
There is a lot resource for doing it in Drupal 6, but I didn't find a solution for Drupal 7.

How can I install and enable selected modules?

# Answer
> 30 votes
There's just one step, using `module_enable()`:

```
$modules = array('module1', 'module2'); // Array of module names
$enable_dependencies = TRUE; // Whether or not to enable dependant modules

module_enable($modules, $enable_dependencies);

```

# Answer
> 12 votes
Here is how you would do it with a database update using `hook_update_N` from another enabled module's `*.install` file. Then you can visit `/update.php` in the browser or run `$ drush updb` on the command line to have this code fired.

```
/**
 * Enable module1 and module2.
 */
function MYMODULE_update_7101() {

  // Array of module names.
  $modules = ['module1', 'module2'];

  // Whether or not to enable dependant modules.
  $enable_dependencies = TRUE;

  module_enable($modules, $enable_dependencies);
}

```

# Answer
> 4 votes
For drupal 8 you can use the following:

```
\Drupal::service("module_installer")->install(["my_custom_module"]);

```

In drush:

```
drush php-eval '\Drupal::service("module_installer")->install(["my_custom_module"]);'

```

# Answer
> 2 votes
In Drupal 7 there is no more drupal\_install\_modules(), therefore if you want to force the module installation process programmatically (if it's already enabled), you can use:

```
module_invoke('module_name', 'install');

```

To enable, it's simply:

```
module_enable(array('module_name'));

```

Or using `drush` as part of the deployment process:

```
drush -y en module_name

```

---
Tags: 7, installation
---


# Question
Title: How can we just apply the updates to a single module using composer without apply patches for other modules?
We have the following `composer.json` file. When we want to update a module such as Environment Indicator, we run the suggested composer command `composer require drupal/environment_indicator:^3.7'`.

In doing so it also applies the patches for core and other modules because the `patches` is defined in our `composer.json` file.

What we tried this as well but it had the same results.

`composer update drupal/environment_indicator --with-dependencies`

composer.json

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "require": {
        "composer/installers": "^1.0.24",
        "drupal/core" : "^8.6",
        "wikimedia/composer-merge-plugin": "^1.4"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        },
        "enable-patching": true,
        "patches" : {
            "drupal/core": {
               "issuenumber1" : "path/to/patch.patch",
             },
            "drupal/eck": {
               "issuenumber2" : "path/to/patch.patch",
             },
        }
    },
}

```

# Answer
Unfortunately, composer is always going to apply any patches you have defined that are not already applied whenever it runs. You can comment out the patches, run your composer command, and then uncomment them.
> 1 votes

---
Tags: 8, hooks, composer
---


# Question
Title: Multi-page wizard webform that posts to external URL?
I've got a multi-page wizard webform whose results I need to post to a specific URL. I see in the webform settings that you can set a Custom POST url. However, this appears to break the muti-page behavior. After setting this option the button that normally takes me from the first page of my webform to the second page instead posts to the given URL.

The option also appears to break the post-submission page that I've set in the webform settings. Any suggestions on how to remedy these issues?

# Answer
It would appear that this needs to be done using a Remote Post handler (which can be added at site.com/admin/structure/webform/manage/form\_id/handlers) instead of selecting the custom POST setting, as described at https://www.drupal.org/project/webform/issues/2961835
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: Font Awesome not working in my sub theme of the Open Framework theme
I have created a sub theme of Open Framework and everything seems fine, except for the Font Awesome feature. I add the following HTML in a block, but no icon shows up.

```
<i class="fa fa-facebook-square"></i>

```

Is there something I need to do in order to enable Font Awesome?

**Edit:** I can see the following in the source of my page, and I have verified that the path to `font-awesome.css` is valid.

```
<style type="text/css" media="all">@import url("http://www.example.com/sites/all/themes/open_framework/bootstrap/css/bootstrap.min.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework/bootstrap/css/bootstrap-responsive.min.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework/fontawesome/css/font-awesome.min.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework/css/open_framework.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework/css/ie.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework_triangle/css/frontpage.css?n2r8cn");
@import url("http://www.example.com/sites/all/themes/open_framework_triangle/css/views.css?n2r8cn");</style>

```

# Answer
Your html is perfect - I think you probably just need to include the font-awesome.css library file itself.

There are a few ways to do this. I usually just include this in my pages `<head>` section:

```
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

```

But some people prefer to actually download the font-awesome.css from fontawesome.com, place it in their theme folder and point to that.
> 1 votes

# Answer
The Drupal 8 way of attaching an external library is by manipulating the THEMENAME.libraries.yml that lives on the root of your custom theme or subtheme. You can add a call for that library like this:

```
fontawesome:
  version: VERSION
  css:
    component:
      //use.fontawesome.com/releases/v5.1.0/css/all.css: {}

```

Where "//use.fontawesome.com/releases/v5.1.0/css/all.css" is the path for the library on Font Awesome's CDN.

Also, you have to update your base theme configuration file (THEMENAME.info.yml) in order to add a pointer for that specific library you have just added:

```
libraries:
  - THEMENAME/font-awesome

```

That is it... Clean the cache and enjoy!
> 1 votes

---
Tags: theming
---


# Question
Title: Hook form alter to check date field is empty or not
I'm using `hook_form_alter()` to add some custom validations. I have to check if a date field is empty or not; when the field is empty, I need to display an error message.

I don't know how to get the value from date field after a form is submitted and check it with `empty()`.

I have tried the following lines, but none of them worked.

* `$form_state['input']['field_start_date']['und'][0]['value']`
* `$form['field_start_date']['und'][0]['#default_value']['value']`
* `$form_state['values']['field_start_date']`

What am I doing wrong?

# Answer
> 0 votes
If the form contains a *field\_start\_date* form element, `$form_state['values']['field_start_date']` is the only correct way to get the submitted values for that field.
Neither `$form_state['input']['field_start_date']['und'][0]['value']` nor `$form['field_start_date']['und'][0]['#default_value']['value']` is the correct way to fetch the submitted values.

Keep also in mind that, if you need to show a validation error when the value submitted for a form element is an empty value, probably you just need to set that form element as required. In that way, Drupal would require users enter a value and show a validation error to the users who don't enter a value. (Drupal would also show a red asterisk close to the form element, to let users know that form element is required.)
For this, it's enough to set `#required` to `TRUE` in `hook_form_alter()`. It doesn't require to write validation code, as that is done from Drupal core.

---
Tags: 7, forms
---


# Question
Title: How to use multiple values for an exposed filter via url
On my current setup I'm exposing a view that outputs json through a service.

The view can be called like this: `http://domain.com/api/books.json`.

I also exposed a filter to a referenced content type "Author". I'm **NOT** using `context filters`, I'm using the regular `Filters` and exposed that particular filter to the user, this way I can give my filter a nice argument name `author_nid`.

So now I can call this: `http://domain.com/api/books.json?author_nid=38`. And this returns all books of the author with that nid.

But I can't seem to figure out how to get the list of books of both author 38 or author 32.

The things i tried:

`http://domain.com/api/books.json?author_nid=38,32`

`http://domain.com/api/books.json?author_nid=38+32`

`http://domain.com/api/books.json?author_nid[]=38,32`

`http://domain.com/api/books.json?author_nid[]=38+32`

`http://domain.com/api/books.json?author_nid[0]=38&author_nid[1]=32`

I seem to have the feeling that this isn't supported right now. Am I correct? If so, what are my options? I'd like to give my arguments a name because I'm about to expose 10 to 15 filters (some optional, others required). Using context filters and filtering like this: `args[]=2&args[]=43,23&args[]=44` isn't very readable/maintainable.

# Answer
> 4 votes
If using `?author_nid[]=38&author_nid[]=32` as suggested by milkovsky doesn't work you may need to look at using contextual filters. Or, as I think might be your only option, use hook\_views\_query\_alter where you can build your own views query WHERE clause based on $\_GET parameters.

# Answer
> 0 votes
Maybe it's just a problem with encoding. I've the same construction (views with multivalued field in exposed filter), and here is the result when I apply the submit button:

http://mywebsite.com/search-housing?field\_rooms\_value%5B%5D=1&field\_rooms\_value%5B%5D=2

Could you try this and tell me if it's working?

http://domain.com/api/books.json?author\_nid%5B%5D=38&author\_nid%5B%5D=32

# Answer
> 0 votes
I agree with Christian and MPD, there is no "is one of" option for NID. Christian's answer about hook\_views\_query\_alter will work.

As alternative solution - you can replace filter handler with a custom one. Here is solution for search API query. Next handler will use "Allow multiple selections" option:

```
class MYMODULESearchApiViewsHandlerFilter extends SearchApiViewsHandlerFilter {

  /**
   * Extends query to handle multiple values.
   */
  public function query() {
    if (!empty($this->options['expose']['multiple'])) {
      $values = array();
      // ...
      // DO YOUR CODE HERE TO GET VALUES FROM $this->value
      // E.g. $values = explode(',', $this->value);
      // ...
      if (!empty($values)) {
        $or = $this->query->createFilter('OR');
        foreach ($values as $value) {
          $or->condition($this->real_field, $value, $this->operator, $this->options['group']);
        }
        $this->query->filter($or);
      }
    }
    else {
      parent::query();
    }
  }

}

```

You can add your handler using hook\_views\_data\_alter().

```
/**
 * Implements hook_views_data_alter().
 */
function MYMODULE_views_data_alter(&$data) {
  $data['search_api_index_MYINDEX']['MYFIELD']['filter']['handler'] = 'MYMODULESearchApiViewsHandlerFilter';
}

```

# Answer
> 0 votes
You can pass multiple values using contextual filter,

Select Raw Value from Url and select PathComponent/arugument.

Below we have **More section from that you can check Allow multiple values** in the form of 1+2+3 (for OR) or 1,2,3 (for AND).

http://example.com/some-path/24+25

or

http://example.com/some-path/24,25

---
Tags: views, services
---


title: Can I add a menu link with a parameter?

text:
# Question
Title: Can I add a menu link with a parameter?
I would like to add a menu link using the "Link"-Field with Autocomplete, but I would like to add a parameter afterwards.

Pretty much like this:

...which is not working.

Is that possible? Thanks!

# Answer
> 0 votes
I didn't find a direct answer, but I used the module "Menu Link Attributes" to add a class and used JS to add the parameter:

```
$('#menu ul li a.parameter').each(function() {
    $(this).attr("href", $(this).attr("href") + "?p=parameter");
});

```

Maybe that's helpful.

---
Tags: 8, navigation
---


# Question
Title: How can I run a Views SQL query in PhpMyAdmin?
i go to admin/structure/views/settings, check Show information and statistics about the view during live preview and then Show the SQL query checkbox that will appear below.

I have a field which is field\_col the field type is Node reference and the widget is a Select list.

this field can have only one value, and in its settings, it is set as to reference a content type named col. Also in the field settings, there is the following:

VIEWS - NODES THAT CAN BE REFERENCED The list of nodes that can be referenced can provided by a view (Views module) using the "References" display type. There a view is set, whose sql query is the below code:

```
SELECT node.title AS node_title, node.nid AS nid
FROM
{node} node
INNER JOIN {og_mm} og_mm_node ON node.nid = og_mm_node.etid AND og_mm_node.entity_type = 'node'
WHERE (( (og_mm_node.gid = '20' ) )AND(( (node.status = '1') AND (node.type IN  ('col')) )))
ORDER BY node_title ASC

```

In the view, where in the live preview i get the results i want, the sql query looks like:

```
SELECT node.nid AS nid, node.created AS node_created, node_field_data_field_title.title AS node_field_data_field_title_title, field_data_field_it_ac_nr.field_it_ac_nr_value AS field_data_field_it_ac_nr_field_it_ac_nr_value, field_data_field_col.field_col_nid AS field_data_field_col_field_col_nid, field_data_field_t_year.field_t_year_value AS field_data_field_t_year_field_t_year_value, field_data_field_it_vlm.field_it_vlm_value AS field_data_field_it_vlm_field_it_vlm_value, field_data_field_it_cn.field_it_cn_value AS field_data_field_it_cn_field_it_cn_value, 'node' AS field_data_field_it_ac_nr_node_entity_type, 'node' AS field_data_field_col_node_entity_type, 'node' AS field_data_field_tak_node_entity_type
FROM
node node
LEFT JOIN field_data_field_title field_data_field_title ON node.nid = field_data_field_title.entity_id AND field_data_field_title.entity_type = 'node'
LEFT JOIN node node_field_data_field_title ON field_data_field_title.field_title_nid = node_field_data_field_title.nid
LEFT JOIN og_mm og_mm_node ON node.nid = og_mm_node.etid AND og_mm_node.entity_type = 'node'
LEFT JOIN field_data_field_deleted field_data_field_deleted ON node.nid = field_data_field_deleted.entity_id AND field_data_field_deleted.field_deleted_value = '1'
LEFT JOIN field_data_field_it_ac_nr field_data_field_it_ac_nr ON node.nid = field_data_field_it_ac_nr.entity_id AND field_data_field_it_ac_nr.entity_type = 'node'
LEFT JOIN field_data_field_col field_data_field_col ON node.nid = field_data_field_col.entity_id AND field_data_field_col.entity_type = 'node'
LEFT JOIN field_data_field_t_year field_data_field_t_year ON node.nid = field_data_field_t_year.entity_id AND field_data_field_t_year.entity_type = 'node'
LEFT JOIN field_data_field_it_vlm field_data_field_it_vlm ON node.nid = field_data_field_it_vlm.entity_id AND field_data_field_it_vlm.entity_type = 'node'
LEFT JOIN field_data_field_it_cn field_data_field_it_cn ON node.nid = field_data_field_it_cn.entity_id AND field_data_field_it_cn.entity_type = 'node'
WHERE (( (og_mm_node.gid = '20' ) )AND(( (node.status = '1') AND (node.type IN  ('product')) AND (field_data_field_deleted.field_deleted_value IS NULL ) )))
ORDER BY field_data_field_it_ac_nr_field_it_ac_nr_value ASC, field_data_field_col_field_col_nid ASC, field_data_field_t_year_field_t_year_value ASC, field_data_field_it_vlm_field_it_vlm_value ASC, field_data_field_it_cn_field_it_cn_value ASC

```

but it returns the node id of the node that is referenced, and not the value i need. How the two above should be made, combined, in order to get the results i want?

# Answer
> 1 votes
Always use the API to load entity data; getting it directly from the database is not recommended.

Once you have your node IDs from the initial query:

```
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  foreach (field_get_items('node', $node, 'field_col') as $item) {
    // Do something with $item['value'], for example
  }
}

```

---
Tags: 7, views, database
---


# Question
Title: How do I return a Twig template inside the build method of a block class?
Am new to Drupal and this week I learned quite a bit about module development, and for today the case is:

For my new module, I create a custom block that renders a markup, and from the folder structure, the class looks like this:

Note: fax is the module's machine name.

fax/src/Plugin/Block/FaxBlock.php

```
<?php
namespace Drupal\fax\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;

/**
 * Provides a 'Fax' block.
 *
 * @Block(
 *   id = "fax_block",
 *   admin_label = @Translation("Fax block"),
 * )
 */
class FaxBlock extends BlockBase implements BlockPluginInterface {

    public function build() {

        return array(
            '#markup' => $this->t('This is just a text initially'),
        );
    }

}

```

I know that in the build method we can also return a form for instance:

```
 public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\rsvplist\Form\RSVPForm');
 }

```

And that we can put HTML inside the array if we want.

Question: how can I instead create a template a return that inside the array?

so, instead of returning a markup like this:

```
'#markup' => $this->t('This is just a text initially'),

```

I could have a template somewhere:

```
<div>
  <p>This is a great example</p>
</div>

```

and then return the template in the build function.

How can I return a template inside the build method of my block?

# Answer
In your modules `*.module` file you must implement hook\_theme() like this:

```
/**
 * Implements hook_theme().
 */
function fax_theme() {
  return [
    'fax_custom_theme' => [
      'variables' => [
        'test' => NULL, # Makes the {{ test }} variable available in the template.
      ],
    ],
  ];
}

```

Then you can return this in your block:

```
$test = 'My custom variable';
return [
  '#theme' => 'fax_custom_theme',
  '#test' => $test, # Assigns a value to the {{ test }} variable.
];

```

This makes the `{{ test }}` variable available in your theme.

Then add your template to the module under `fax/templates/fax-custom-theme.html.twig`.

Template names are using dashes instead of undercores.
> 3 votes

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


# Question
Title: Format for webform submission node tokens?
I have a field on my webform node which is an entity reference to a taxonomy term. I'm printing it in the webform using the token `[webform_submission:node:field_sports]`, which prints the field output, but formatted as a link to the term page, whereas what I want is plain text. For webform submission values, there is the :raw format, but trying to use this with the node field token results in the error "Computed value/markup is using the following invalid tokens: \[webform\_submission:node:field\_sports:raw\]."

This token does not seem to respect the display settings on the content type, either; removing the link there does nothing for the display on the webform.

# Answer
If you use `[webform_submission:node:field_sports:0:entity]` you can get field values form the taxonomy term.

So to get the name, you can use:

```
[webform_submission:node:field_sports:0:entity:name]

```
> 1 votes

---
Tags: 8, webforms, tokens
---


# Question
Title: Is there a way to list permissions for a given module?
Using Drush 9, I am trying to automate the creation of a role and I need to assign permissions to it. I see that I can use `drush role-add-perm` to do the assignment itself, but I can't find a command to actually give me the permissions supplied by the enabled modules.

It looks like this was doable in older versions of Drush, but I'm not sure Drush 9 has equivalent commands.

Thanks!

# Answer
> 5 votes
You could use `drush cim` and create a yml for your role like for example

```
langcode: en
status: true
dependencies: {  }
id: myrole
label: 'My super Role'
weight: 1
is_admin: false
permissions:
  - 'whatever 1'
  - 'whatever 2'

```

And if you don't know what perms your module brings, you could use that simple eval code with drush:

```
drush php-eval '$p = Drupal::service("user.permissions")->getPermissions(); foreach ($p as $k => $x) print $k." : ".$x["provider"]."\n";'

```

---
Tags: drush
---