# Question
Title: How to render translated node body in two languages?
I use entity\_translation to translate node body field, so in a fully loaded node object `body` is an array of 2 languages ('en' and 'ru').

For specific node type I would like to render body in both languages one after another:

> Russian version of node body
>
> English version of node body

so switching between translations will not be needed.

What hook can I use to achieve this?

In implementation of `hook_node_load()` body is an array of 2 languages, but in `hook_node_view_alter()` body already contains only the current language value.

When using `node_load()` in `hook_preprocess_node`, it retrieves the node object from cache and its body has only one (current) language value.

# Answer
I found a solution: call `field_attach_view` with the required language.

```
/**
 * Implements hook_preprocess_node().
 */
function MYMODULE_preprocess_node(&$vars) {
  if ($GLOBALS['language']->language == 'ru') {
    $original_langcode = 'en';
    $content_original = field_attach_view('node', $vars['node'], $vars['view_mode'], $original_langcode);

    // need to check if languages match, it may be a language fallback
    if ($content_original['body']['#language'] == $original_langcode) {
      $vars['content']['body_original'] = $content_original['body']
    }
  }
}

```
> 1 votes

---
Tags: 7, nodes, hooks, i18n-l10n
---


title: Views date filter yesterday

text:
# Question
Title: Views date filter yesterday
I want to show yesterday's posts on a block with views. So I added two date filters. They should be:

```
<today midnight

>yesterday midnight

```

(-1 day is not ok for me because it spans exactly 24 hours back)

According to the manual: http://php.net/manual/en/datetime.formats.relative.php I added the two filters as: Less than "today" (I also tried less than "midnight" or "today 00:00") Greater than "yesterday" (I also tried greater than "yesterday 00:00")

But they are all showing the items from yesterday and today together.

Is there a way to show items from yesterday 00:00 to yesterday 23:59 ?

# Answer
I ended up using contextual filter instead of filters. I added:

Content: Created date

Provide default value - php code

```
return date("d", strtotime("-1 day"));

```
> 4 votes

# Answer
I had the same problem, but unfortunately for me, the field didn't appear in contextual filters, so I still had to use the normal date filter. This worked perfectly for me:
> 2 votes

# Answer
I always end up forgetting I need to have "two filters" in order to accomplish this... At least that's what works for me.

I just got done messing with it trying to show some posts from yesterday and came up with:

```
Content: Authored on (>= yesterday)
Content: Authored on (<= today)

```

I think the OP had the filters reversed and that's why they weren't working. Since the filters work top to bottom, "today" was filtered first so there was no real end time to capture.

Love the "is between" method suggested tho. That's boss.

Update: On a side note to get the same result as the "is between" suggestion, this should also work:

Is Between:

```
Min = yesterday
Max = today -1 second

```

Keep in mind, **yesterday** is the exact same thing as **yesterday midnight**

https://www.php.net/manual/en/datetime.formats.relative.php

Here's a great way to test the strototime:

https://strtotime.co.uk/

And on a final note, Drupal 8 as of 8.7.7 has a bug where the datetime does not properly execute the right strtotime, resulting in "yesterday" actually being "now -24 hours" instead of "yesterday 00:00". See the following issue for a patch:

https://www.drupal.org/project/drupal/issues/2647292
> 0 votes

---
Tags: views, datetime
---


# Question
Title: How do I use sendmail on Debian/Ubuntu to send emails without SMTP or other modules?
I have a Drupal 8 installation and it's not sending emails. I've configured postfix and tested using sendmail command line. PHPMailer module is installed via composer. When I submit passowrd reset request, error message is "Unable to send email. Contact the site administrator if the problem persists."

I checked the /var/log/mail.log file and the following error is shown: "Recipient addresses must be specified on the command line or via the -t option"

How can I use sendmail with Drupal 8? This seems like it "should" be easy, but all documentation I've found says install an SMTP module.

Thanks for any clues / advice.

# Answer
> 1 votes
OK, thanks to Clive I stopped assuming things and checked the php.ini file. Sure enough the sendmail\_path option just had "/usr/sbin/sendmail".

I've updated php.ini with "sendmail\_path = /usr/sbin/sendmail -t -i" and it's working beautifully.

Doh!

---
Tags: 8, emails
---


title: Filter excludes date in end date field

text:
# Question
Title: Filter excludes date in end date field
I have a view in Drupal 8 as below. \[The date column in below list, is not an event. its order item. so date showing is order complete date only\]

When I filter with start and end date, the data shown excludes the end date. It just shows the in-between records, but it does not include the end date. I am unable to figure it out from the code.

Any help?

# Answer
Time also matters (date fields also has time, usually it's set to 0 am). Check in your database what time is associated with the date. If the time is i.e. 11 am or even 00:00:01 am (H.m.s), it will be excluded. It also can be changed the base date by your settings. (i.e. when you create a new date it can be created by default to 0 o'clock and to 12 o'clock too. Or even it can be the node creation time too.

Please note, when you compare date/time most probably the UNIX timestamp will be compared (in views at least)! Reason: drupal save UNIX timestamps into the database, when you create a view you will see the relation is in the query, so the inputed date will be converted to timestamp and a default time. And this default time can be mess up the things.
> 0 votes

---
Tags: views, 8, datetime
---


title: Delete user and change Content Author

text:
# Question
Title: Delete user and change Content Author
Is it possible to Delete the user and keep its content as created by the one who deleted the user.

Suppose, **abc** is a user as *content creator/editor* only and have created 2 contents.

**abc** got fired as editor and his boss **xyz** wants to delete his user account.

**xyz** not only wants to delete **abc** but while deleting **abc** transfer all the content created by **abc** to his name, so that it'd be like created by **xyz**.

Drupal has only 4 options while deleting user account which doesn't satisfy this need.

If it is possible then how? please elaborate how to achieve that....

# Answer
While canceling user account choose either `Disable the user account and keep its content` or `content belong to anonymous user`

---

**To bulk Update author for node you could use Views Bulk Operation**

* Create a view listing the content that you want to edit.
* Add a bulk operation in fields

* Select change the author of the content

* Go to your view to select the nodes for which you want to change the author

* Select the author who should be made the new other for all these content.
> 2 votes

# Answer
There is an option while deleting a user that `Cancel the user account and keep its content`.

To change the author you may need to implement hook\_user\_delete.
> 1 votes

# Answer
You can implement `hook_user_cancel_methods_alter()` to add your own cancellation methods. Add the cancellation methods using this hook, then implement `hook_user_cancel()`.

In the hook\_user\_cancel implementation, you will be able to use a switch/case on the method selected and create your custom cancellation logic:

* Load the entities
* Change the uid for each one the user owned/created
* Change the uid for fields pointing at this user
* Save the entities
> 0 votes

---
Tags: 7, users
---


# Question
Title: Webform Select Element Optgroup / hierarchy
Hello fellow Drupal users, I have created an advanced HTML element in my webform. When the form is submitted the advanced html element reverts back to the default setting, which in this case is option A1. The users selection and data for this element is not in the submission.

This is the YAML an example form:

```
processed_text:
  '#type': processed_text
  '#display_on': both
  '#text': |
    <select  name="processed_textone" id="processed_textone" style="width: 570px;">
    <optgroup label="A">
        <option value="A1">A1</option>
        <option value="A2"> A2</option>
        <option value="A3"> A3</option>
    </optgroup>

    <optgroup label="B">
        <option value="B1">B1</option>
    </optgroup>

    <optgroup label="C">
        <option value="C1">C1</option>
        <option value="C2">C2</option>
    </optgroup>

  '#format': full_html

```

I would like to get the data of the selection upon submission. I tried using a computed twig and Ajax, but that doesn't seem to work either. I think I might be able to add a javascript file to get this data into the submission, but I'm not sure. I'm pretty new at subtheming and js in general.

# Answer
> 0 votes
@jrockowitz suggested I look here; drupal.org/project/webform/issues/2783937

This solved my question. Thank you jrockowitz.

---
Tags: forms, webforms
---


title: Multiple products on add to cart?

text:
# Question
Title: Multiple products on add to cart?
E.g. node contains a product Poster for $5 and e.g. a checkbox saying "+ Cup" which is another $5. So it's two different products, how do I let user select if they want just a poster of if they want the poster + the cup, so check the box for the cup and on add to cart it adds both items?

If you create a product reference field with Unlimited, it won't let to choose multiple items, it renders as a dropbox/select list for one item to choose and add to cart.

https://www.drupal.org/project/commerce\_product\_kit is locked to total products set for the page in the product reference field, so it always adds both products on Add to cart, no select option.

So basically how to add 1 to 2 products on same page clicking Add to cart only once.

# Answer
Have you already tried the Commerce Product Add-On module? That sounds like exactly what you're describing.
> 1 votes

---
Tags: 7, commerce
---


title: Add js with custom type

text:
# Question
Title: Add js with custom type
How can i add a script file with `type='module'`, like this :

```
<script src="site/test/test/index.js" type="module"></script>

```

I tried with :

```
  drupal_add_js(drupal_get_path('module', 'my_module') . '/assets/js/my_script.js', [
    'attributes' => ['type' => 'module'],
    'type' => 'module',
  ]);

```

But Drupal 7 only accept 'file', 'inline', 'external' or 'setting' as type.

Do you have any idea ?

Thanks.

# Answer
> 1 votes
You can do this in hook\_preprocess\_html():

```
function theme_preprocess_html(&$var) {
  $script = [
    '#tag' => 'script',
    '#attributes' => [
      'type' => 'module',
      'src' => 'path/to/script.js',
    ],
    '#value' => '',
  ];
  drupal_add_html_head($script, 'script');
}

```

---
Tags: javascript
---


# Question
Title: PHPUnit Test run Error with ConfigFactory
I'm running an error with the following test I wrote including some config. I don't know if my test is even properly written so any advice in improving that code is welcomed. Since my test is not finish yet, dont mind the `self::assertTrue(TRUE);`

Here is my Test :

```
namespace Drupal\mymodule\Tests\Service;

use Drupal\Component\Serialization\Json;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Url;
use Drupal\Tests\UnitTestCase;
use Drupal\mymodule\Service\MyClass;

/**
 * MyClass Test.
 *
 * @group mymodule
 */
class MyClassTest extends UnitTestCase {

  private $params;
  protected $configFactory;
  protected $loggerFactory;
  protected $container;
  protected $myClass;

  /**
   * Set Up.
   */
  public function setUp() {
    parent::setUp();
    $this->configFactory = $this
      ->getConfigFactoryStub([
        'mymodule.settings' => [
          'api' => [
            'hostname' => 'https://example.com',
            'periodbars_uri' => '/api/v2.0/articles',
            'api_key' => 'aaabbbcccdddeeefffzzz',
          ],
        ],
      ]);
    $this->container = new ContainerBuilder();
    $this->container
      ->set('config.factory', $this->configFactory);
    \Drupal::setContainer($this->container);
    $this->loggerFactory = $this
      ->getMockBuilder('Drupal\Core\Logger\LoggerChannelFactoryInterface')
      ->disableOriginalConstructor()
      ->getMock();
    $this->params = [
      'criteria' => [
        'id' => '1',
      ],
    ];
    $this->myClass = new MyClass($this->configFactory, $this->loggerFactory);
  }

  /**
   * Test API Accor Fetcher.
   */
  public function testMyClass() {
    $params = Json::encode($this->params);

    $url = 'https://example.com/api/v2.0/articles';

    $this->myClass->myClassRequest($url, $params, 'FR');

    self::assertTrue(TRUE);
  }

}

```

And here is the class I test :

```
namespace Drupal\mymodule\Service;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Pool;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use Drupal\Core\Url;

/**
 * Provides all the functions to call MyClass Webservices.
 */
class MyClass {

  protected $configFactory;
  protected $loggerFactory;

  /**
   * AccorWebService constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config Factory.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
   *   Logger Factory.
   */
  public function __construct(ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory) {
    $this->configFactory = $config_factory;
    $this->loggerFactory = $logger_factory;
  }

  /**
   * The Guzzle Request.
   *
   * @param string $url
   *   The url of the webservice to call.
   * @param string $params
   *   The params to be sent to the webservice formatted in JSON.
   * @param string $langcode
   *   The langcode to call the webservice.
   *
   * @return \Psr\Http\Message\StreamInterface|null
   *   The response from the webservice.
   */
  public function myClassRequest($url, $params, $langcode = 'FR') {

    $api_key = $this->configFactory->get('mymodule.settings')->get('api.api_key');
    $headers = [
      'apikey' => $api_key,
      'Content-Type' => 'application/json',
      'Accept-Language' => $langcode,
    ];

    $client = new Client();

    $response = NULL;
    try {
      $request = $client->request('POST', $url, [
        'headers' => $headers,
        'body' => $params,
      ]);
      $response = $request->getBody();
    }
    catch (ClientException $e) {
      $this->loggerFactory->get('mymodule')
        ->error($e->getMessage());
    }
    catch (ServerException $se) {
      $this->loggerFactory->get('mymodule')
        ->error($se->getMessage());
    }

    return $response;
  }

```

When I run the Test in PHPStorm, I get `Call to a member function get() on null` on the line where the code is : `$api_key = $this->configFactory->get('mymodule.settings')->get('api.api_key');`

# Answer
I know it's been quite some time, but did you ever figure out how to appropriately fix this?

I had exactly the same issue over the last couple of days, and I did kind of work out why and a way to get around it.. Though depending on what config data you need to return I'm not sure my "workaround" would be suitable.

In an attempt to explain what I've found and how I prevented the `Call to a member function get() on null` error - the `$api_key = $this->configFactory->get('mymodule.settings')->get('api.api_key');` isn't actually being overridden by the configFactory mock because it's part of the class function you're testing and for some reason isn't overridden by your mock return call. Adapting my workaround to your implementation:

In your class

1. Move `$api_key = $this->configFactory->get('mymodule.settings')->get('api.api_key');` to it's own function (example name **getApiConfig**)
2. Call it in the `myClassRequest` function with `$api_key = getApiConfig();`

In your test

1. Stub `getApiConfig` in your class mock
2. Return the required value(s)/array/object as required from a class stub return

Unfortunately I can't provide an update to your provided code as I'm unsure how my "workaround" impacts your implementation of `new MyClass` but hopefully this helps you, or others who come across this!
> 0 votes

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


title: Config split ignore dependencies

text:
# Question
Title: Config split ignore dependencies
I'm using the `config_split` module to split configuration to an installation profile, that I use in multiple Drupal sites.

I have 2 sites using the same installation profile, both using the same config split settings.

Here's a list of configuration that I have split to the profile.

* The content type (article)
* Taxonomy vocabularies
* Media types
* Media library views and settings

I have 4 content types on one of the sites, but I only want to split the article content type.

The problem is that some fields from the other content types are automatically split because they depend on either media or taxonomy.

This is the node configuration that I'm splitting:

> * core.base\_field\_override.node.article.\*
> * core.entity\_form\_display.node.article.\*
> * core.entity\_view\_display.node.article.\*
> * core.entity\_view\_mode.node.article.\*
> * field.field.node.article.\*
> * field.storage.node.article\*

All fields from the article content type are all named `article_FIELD_NAME`.

How can I avoid that config split also splits depending configuration?

# Answer
> 2 votes
I solved that problem using `Features` for Drupal 8 as suggested by @leymannx.

I have exported media, taxonomy and the article content type to one feature that I can now use across multiple sites.

The cool thing is that configuration still lives in the config\_sync directory, so other content types that depend on media and taxonomy don't need to be exported to features as well.

---
Tags: 8, configuration
---


title: Using once method on event listener

text:
# Question
Title: Using once method on event listener
In the series of problems I have with the usage of once method, I wonder how I can refactor simply that code with the once method and be able to toggle local storage on a set of clickable elts:

```
(function ($, Drupal) {
  'use strict';
  /**
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.recherche = {
    attach: function (context) {

 const els = document.querySelectorAll(".block-facet-blocktype h2, .block-facet-blockaxe h2, .block-expertisescientifique h2, .block-domainedapplication h2");
    for (const el of els) {
      el.addEventListener("click", handler);
    }

    function handler(event) {
      event.preventDefault();
      var selector = $(this);
      toggleLocalStorage(selector, 'expanded');
    }
}}
})
(jQuery, Drupal);

```

What happens at the moment is one click call the toggle function 6times and have then no effect.

# Answer
`once` is a jQuery plugin; it doesn't really make sense to mix it with vanilla JS event handlers, as you're already using jQuery by that point, and it's easier to attach events with jQuery.

After you've refactored your code to use jQuery, its usage is well explained, with examples, in the Drupal javascript docs. There are many permutations, here is one example for attaching an event handler:

```
$('a.foo', context).once('bar').each(function () {
    // You could also use this.addEventListener here, but as you're already in a jQuery context it doesn't really make sense to.
    $(this).click(function() {
      // ...
    });
});

```
> 2 votes

---
Tags: 8, javascript
---


# Question
Title: Output taxonomy term in views unformatted using twig
I'd like to output taxonomy terms as html classes for view-rows in the views unformatted template for Drupal 8.

My code:

```
    {% if title %}
       <h3>{{ title }}</h3>
    {% endif %}
    {% for row in rows %}
       <div class="taxonomy-term-{{ term.id }}">
          <div{{ row.attributes }}>
             {{ row.content }}
          </div>
       </div>
    {% endfor %}

```

What am I missing?

# Answer
You're a little light on details about your setup, but I can make a suggestion based on what I see. I don't know how you're settings the `term` variable, but `row` will have access to the node (assuming this is a node view) that represents the row being displayed. You can do something similar to

`{{ row.content['#node'].field_tags.getValue().0.target_id }}`

(assuming `field_tags` is your term reference field) to print the referenced term ID.

Edit: just realized how long ago this was asked... Not sure why it was showing at the top of my list. Anyhow, hopefully helpful to someone!
> 1 votes

# Answer
You seem to be missing `<div class={{ row.attributes }}>`
> 0 votes

# Answer
You need to copy existing

> `views-view-unformatted.html.twig`

file from views module directory

> `core/modules/views/templates/views-view-unformatted.html.twig` (**As You already did**)

Then You need to **Add Field From (Taxonomy Term) View** in order to get that field's value in your twig's `{{ row }}` variable
> 0 votes

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


title: Extend core modernizr library

text:
# Question
Title: Extend core modernizr library
I am noticing `objectFit` is not part of Drupal 8 `core/modernizr` library. How do I add `objectFit` detection without overriding core modernizr?

# Answer
I'm pretty sure you have to override core/modernizr with a later version in order to get objectFit.

1. Download an updated modernizr.js and include objectFit.
2. Place the file somewhere in your theme's path (js/ or scripts/)
3. In your theme's info file (*theme-name*.info.yml) , override the existing modernizr library

```
libraries-override:
  core/modernizr:
    js:
      assets/vendor/modernizr/modernizr.min.js: scripts/modernizr.js

```

You should now have access to objectFit.
> 0 votes

---
Tags: 8
---


# Question
Title: How to open file in new tab instead of download when submitting form?
The code below downloads the current file, I need it to open the file in a new tab, what needs to be added in order to do so?

```
public function submitForm(array &$form, FormStateInterface $form_state) {
     $filename = '/var/www/html/web/modules/custom/custom_module/sample.pdf';
     $response = new BinaryFileResponse($filename);
     $response->setContentDisposition(
          ResponseHeaderBag::DISPOSITION_ATTACHMENT,
          'sample.pdf'
     );
     $form_state->setResponse($response);

```

# Answer
As @clive points out, this cannot be done on the server side. Check this post for a javascript based solution. You need to attach the javascript to your form during build. See below for an example of form build with a javascript attached to the submit element:

```
/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
  // Assuming you are extending core \Drupal\Core\Form\FormBase class
  // and prior the lines below you built your form elements.
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Download file'),
    '#button_type' => 'primary',
    '#attached' => [
      'library' => 'your_module/submitToNewTab'
    ]
  ];

  return $form;
}

```
> 0 votes

# Answer
I was able to open the results of a form in a new tab, like this:

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#attributes'] = ['target' => '_blank'];
  ...
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  ...
  $form_state->setRedirect(
    'skilling.calendar_planner',
    ['node' => $calendarNid, 'startDate' =>  $startDate]
  );

```

}
> 0 votes

---
Tags: 8, files
---


# Question
Title: How can I determine in the body of a hook implementation what hook it is implementing?
I have a functional understanding of what the hook system is and how to use it in Drupal, but would like to deepen my knowledge. Normally when writing a hook, I know exactly what hook I'm using, because I've looked up what hooks were available, chosen one that suits my need, and implemented it. Sometimes though, I have a situation where I look at the `THEME HOOK` provided by the debugging output in the HTML, and I write a hook for that, and maybe add a couple of specifiers. For example, if I see this debugging output:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   x page--user--edit.html.twig
   * page--user--555.html.twig
   * page--user--%.html.twig
   * page--user.html.twig
   * page.html.twig
-->

```

I might implement a hook for `page__user__edit`. If I am in my theme called `my_theme`, I know I can go into my theme file `my_theme.theme` and implement the hook there, and that if I do I should begin the hook with `my_theme_preprocess`. So all together my hook should be `my_theme_preprocess_page__user__edit`, and I test it, and it works, and that part is all good.

Where my confusion comes in is when I go to specify parameters or document the function. What parameters does the function take? What hook does it implement? I am usually able to guess on the parameters, since usually it is `(&$variables)`, but sometimes they are different. Ideally I would like to look up exactly what parameters the function takes based on the documentation for the hook, rather than trying to guess, but looking up the documentation for the hook can require some guesswork itself if you don't know what hook you are implementing. Some hooks are `hook_preprocess_whatever`, others are `template_preprocess_whatever`. Other times, like for a block, I wrote the hook `my_theme_preprocess_block` but it turns out this is not implementing `hook_preprocess_block`, it is implementing `hook_preprocess_HOOK` (or so I believe). So, once I have written a hook implementation (i.e. `my_theme_preprocess_block` or `my_theme_preprocess_page__user__edit`), how can I definitively know what hook I have just implemented?

Currently, I just Google a few different plausible-seeming hooks that I might be implementing, and if one of my guesses is correct or I get close enough that Google gives me a suggestion, I'm all set. In the case of the hook above, I'm able to find documentation for a `template_preprocess_page` function, and no such `hook_preprocess_page` function. Sometimes the results of this Googling process are less clear though, and leave me uncertain of what hook I have just implemented (like for the block - `hook_preprocess_HOOK` is very generic, how can I be sure I'm not implementing something more specific that I just missed in my Googling?). So if there does exist a way to definitively tell what hook you are implementing using a debugging tool or something, I would very much like to know about it.

I've tried using `kint($variables)` inside of my hook implementation (e.x.

```
function my_theme_preprocess_page__user__edit(&$variables) {
  kint($variables);
}

```

) but the closest thing I could find in there was `theme_hook_original`, which for the above gives `'page'`, so doesn't resolve these ambiguities about what hook I'm implementing.

Or, if there doesn't exist a way to tell what hook you are implementing with a debugging tool, is there a better way to figure out what hook I'm using other than what I'm doing? I'm open to suggestions on any level, including ways I should revise my workflow, something I should know about the difference between `template_preprocess_whatever` and `hook_preprocess_whatever` functions that if I knew that thing I wouldn't be confused, or whatever else. Thanks!

# Answer
> 3 votes
> Where my confusion comes in is when I go to specify parameters or document the function. What parameters does the function take? What hook does it implement?

Preprocess hooks are only provided a single parameter: `$variables`. The hook that you're implementing is literally `hook_preprocess_HOOK`. The `HOOK` part of it is the identifier for the theme entry, as defined in a `hook_theme()` implementation somewhere.

So if you have this:

```
function MODULE_theme() {
  return [
    'foo' => [
      'variables' => [],
    ],
  ];
}

```

Then, by convention, you can implement `hook_preprocess_hook` like so:

```
/**
 * Implements hook_preprocess_HOOK() for foo templates
 */
function MODULE_preprocess_foo(&$variables) {
  // ...
}

```

Note the docblock; the convention is to use *for XXX templates*, where *XXX* is a description of the item being preprocessed. If you search for \_implements hook\_preprocess\_ in the core folder, you'll find a lot of these as examples.

> So, once I have written a hook implementation (i.e. my\_theme\_preprocess\_block or my\_theme\_preprocess\_page\__user\__edit), how can I definitively know what hook I have just implemented?

By definition, you already know :) *You* created the function with a certain name, so you know which theme entry you're preprocessing variables for.

> like for the block - hook\_preprocess\_HOOK is very generic, how can I be sure I'm not implementing something more specific that I just missed in my Googling?

Because there can only ever be one theme entry for a given identifier, you won't run into this problem.

> something I should know about the difference between template\_preprocess\_whatever and hook\_preprocess\_whatever functions that if I knew that thing I wouldn't be confused

Hopefully, along with the above, this will clear things up:

* `template_preprocess_HOOK` is, again by convention, used by the module implementing the theme entry, to provide the base variables. It's always run first, before `hook_preprocess_HOOK` is invoked, so it helps those defining theme entries to ensure important variables and processing are done up front before the rest of the system gets involved.
* `hook_preprocess_HOOK` is essentially for other modules to preprocess the variables, rather than for the module implementing the theme. There's nothing to stop that module from implementing `hook_preprocess_HOOK` as well (it's just a naming convention and no special checking is made), but it could be undesirable to do that if some initial processing needs to be done, *a la* `template_preprocess_HOOK`.

---
Tags: 8, hooks
---


# Question
Title: How can I call custom javascript on successful webform submissions through hook_form_alter?
I have some custom js code which should be executed after successful webform's submission.

JS Code :

```
jQuery('document').ready(function(){
    form_submit_telium();
});

```

below approaches, I already tried

1.

```
$commands = array();
$commands[] = ajax_command_invoke(NULL, 'form_submit_telium');
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

```

-\> It's not working, due to my webform is not submitted through ajax call.

2.

```

$form['#attached']['js'] = array(
                drupal_get_path('module', 'module_name') . '/js/form_submit.js',
            );

```

3.

```

drupal_add_js("jQuery('document').ready(function(){
      form_submit_telium(); });",'inline');

```

**Webform alter code:**

```
function module_form_alter(&$form, &$form_state, $form_id){
    $form['#submit'][] = 'telium_form_submit';
}

function telium_form_submit(&$form, &$form_state){
    // above three approaches
}

```

Please let me know if you have any other approach to do the same thing.

# Answer
> 1 votes
Your 2nd option will work in that :

.Module

```
function hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "webform_client_form_id"){
        $form['#attached']['js'][] = drupal_get_path('module', 'c1') . '/c1.js';
    }
}

```

Js Code:

```
jQuery(document).ready(function(){
    jQuery( "#webform-client-form-id" ).submit(function( event ) {
      alert( "Handler for .submit() called." );
    });
});

```

---
Tags: 7, javascript, webforms
---


# Question
Title: How can I move a node type's configuration into a custom module?
I still a bit new to D8 and loving the new configuration management system that has replaced Features.

I am looking for the best technique for containing particular configurations in my custom modules.

I have a node type called **quiz** and a module called **quiz\_module**. By default, when I execute **drush cex -y** the output yaml files are deposited into **../config/sync**.

**Is it the correct thing to do to move all the yaml files relating to the quiz node type in to my quiz\_module?** When do that, the same files are recreated whenever I execute *drush cex -y*.

To counter that duplication, I created a softlink of the files from *quiz\_module* to '*../config/sync*' but that didn't seem to update the yaml files as I expected.

Any help, please?

# Answer
Configuration Management did not replace Features completely, Features still has its place.

My understanding is that:

* Configuration Management should be used to manage your configuration for a specific site/project.
* Features should be used to export configuration to custom modules as you develop them *if* they're going to be re-used on another site.

The configuration in your custom module goes into 2 directories (install or optional).

* Configuration in the install directory is considered required and only gets imported when your module is installed.
* Configuration in the optional directory is optional and will import during your module install if all the dependencies are present. (I think it also gets imported if all dependencies are later installed.) E.g. If you define a View in your module's optional directory, that configuration would be installed *only* in two instances: 1. when you install your module, if Views is installed, or 2. when Views is installed later, sometime after your module is installed.

The Features module page lists several additional resources to help understand the differences between Configuration Management and Features.
> 1 votes

# Answer
The most efficient way to move a content type into a custom module is from the command line:

```
drupal config:export:content:type page \
  --module="demo" \
  --optional-config \
  --remove-uuid \
  --remove-config-hash

```

Source: https://drupalconsole.com/docs/en/commands/config-export-content-type
> 1 votes

---
Tags: 8, configuration
---


# Question
Title: When attempting to run drush ": No such file or directory"
I've been bashing my head against the wall all day trying to figure out why Drush has suddenly stopped working.

I've re-installed via composer, tried different versions, always the same error.

If I type `which drush` I get `/home/user/.composer/vendor/bin/drush` which is correct.

If I type `sh -vx drush` in an attempt to debug what's happening with the script, I get the following output:

```
#!/usr/bin/env sh
#
# This script is a simple wrapper that will run Drush with the most appropriate
# php executable it can find.
#
# Solaris users: Add /usr/xpg4/bin to the head of your PATH
#

+
: not found/.composer/vendor/bin/drush: 8: /home/user/.composer/vendor/bin/drush:
# Get the absolute path of this executable
SELF_DIRNAME="`dirname -- "$0"`"
+ dirname -- /home/user/.composer/vendor/bin/drush
+ SELF_DIRNAME=/home/user/.composer/vendor/bin
SELF_PATH="`cd -P -- "$SELF_DIRNAME" && pwd -P`/`basename -- "$0"`"
+ cd -P -- /home/user/.composer/vendor/bin
/home/user/.composer/vendor/bin/drush: 1: cd: can't cd to /home/user/.composer/vendor/bin
+ basename -- /home/user/.composer/vendor/bin/drush
+ SELF_PATH=/drush

+
: not found/.composer/vendor/bin/drush: 12: /home/user/.composer/vendor/bin/drush:
# Decide if we are running a Unix shell on Windows
if `which uname > /dev/null 2>&1`; then
  case "`uname -a`" in
/home/user/.composer/vendor/bin/drush: 15: /home/user/.composer/vendor/bin/drush: Syntax error: word unexpected (expecting "in")

```

wut

Ok, maybe something wonky is returned with `uname -a`? The response from my server is:

`Linux servername 3.2.0-58-generic #88-Ubuntu SMP Tue Dec 3 17:37:58 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux`

There are no directory permission issues... everything is owned by the user. I'm at a complete loss. I've tried drush 5, 6, and 7 - same sort of error in each.

The server is running Ubuntu 12.04.2 LTS

# Answer
I was getting this same error when running drush commands on a remote computer via a drush alias. I could run the same drush commands on the remote system directly with no problems but when I would try to run them via a drush alias (@remotesystem) I would get this error.

I found that the user on the remote systems default shell was sh and not bash. Because the bash configuration file ~/.bashrc contains the line that adds the location of drush to the path the sh shell was not able to find drush as ~/.bashrc will not be sourced by the sh shell only by bash.

The drush installation instructions on docs.drush.org state:

> Now add Drush to your system path by placing export **PATH="$HOME/.composer/vendor/bin:$PATH"** into your ~/.bash\_profile (Mac OS users) or into your **~/.bashrc** (Linux users).

You can check what your current shell is set to by running:

```
export |grep SHELL
```

This will print a line with your current shell in it like this:

```
declare -x SHELL="/bin/bash"
```

On Ubuntu the default shell is sh but the default user shell is bash. This happened on a Ubuntu Server install (no GUI).

To fix this change your default shell to bash.

For current users run the following to change the default shell:

```
sudo -u <USERNAME> chsh -s /bin/bash

```

For future users, if you use useradd, edit the /etc/default/useradd skeleton file (don't forget to make a backup though). Change the line:

```
SHELL=/bin/sh
```

to

```
SHELL=/bin/bash
```

This will set bash as the shell for new users that are created.
> 6 votes

# Answer
My issue was caused by the .bashrc not being fully processed by non interactive shells https://stackoverflow.com/a/941995/980921
> 1 votes

# Answer
Drush cannot be found due to $PATH not providing the path to where Drush is, so the error `env: drush: No such file or directory` results. In the accepted answer that's due to a different shell being used, but there are other possible causes and solutions in addition to that.

In running Drush on a remote site via Drush aliases, for example, there might be problems with SSH and the non-interactive non-login nature of that shell connection... so if your $PATH is defined `~/.bash_profile` and it doesn't get loaded, **moving the $PATH definition to `~/.bashrc`** can be a solution in that case.
> 1 votes

# Answer
To solve this specific issue that I was also having, all you need to do is to provide a `drush-aliases` configuration as shown in the following example ...

```
$aliases['prod'] = array (
  'uri' => '...',
  'root' => '...',
  'remote-host' => '...',
  'remote-user' => '...',
  'os' => '...',
  'path-aliases' => array(
    '%drush-script' => '/home/user/.composer/vendor/bin/drush', // <-- This is what you need
  ),
);

```

After that, you might need to clear the cache using `drush cc drush` and try again.

This worked for me.
> 1 votes

# Answer
If you are confident that the path to Drush is correct, Try giving execute permission to drush binary.

```
chmod a+x drush

```
> 0 votes

# Answer
May be it's caused by dos line endings. you can fix it by editing this file drush in vim and executing ":set ff=unix" with reference from your question on github

If the above solution dose not works then try this:

```
sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

```

Additionally, you may need to adjust your php.ini settings before you can use drush successfully. here is the reference
> 0 votes

# Answer
In my case I removed drush crom **vendor** directory, and it helped.

In my PATH there were many instances of drush.
> 0 votes

---
Tags: drush
---


# Question
Title: Alter granularity in date exposed filter from Y-m to Y if only year is selected
I am trying desperately to get the following working:

**Goal**: I have a views that displays a list of events. To this views is a date exposed filter attached, with granularity Y-m(year month). I want this filter to filter with Y granularity if only the year is selected, and by Y-m if both are selected. In addition to that, the view is set so that: when no date filter is selected, then filter by upcoming events, else, use the exposed filter value

**Issue**:

The month is required, even if I alter the form I am suprised by the fact that exposed\_form\_alter as well as the validation fct are called multiple times, before the view is pre-build and before it is pre-executed, but this might be normal behavior. See here: http://cl.ly/image/1C0t3Z3O0D3W (hook\_views\_\*** dpms the function's name)

**Draft**:

The solution was inspired by this thread

```
function lezoo_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form['#id'] == 'views-exposed-form-teaser-list-panel-pane-1')
  {
   $form['#validate'][] = 'lezoo_views_exposed_form_validate';

  }
}

function lezoo_views_exposed_form_validate(&$form, &$form_state) {

  $handlers = &$form_state['input'];
  foreach ($handlers as $key => $handler) {
    if (
      isset($form[$key]['value']['#type'])
      && $form[$key]['value']['#type'] == 'date_select'
      && $form[$key]['value']['#date_format'] == 'Y-m'
      && $form_state['input'][$key]['value']['month'] == '') {
      $form[$key]['value']['#date_format'] == 'Y';
    unset($form[$key]['value']['#granularity'][2]);
    unset($form_state['input'][$key]['value']['month']);
  }
}
dpm('form validation');
   // dpm($form);
   // dpm('form_state');
   // dpm($form_state);
}

function lezoo_views_query_alter(&$view, &$query) {
  //If a date was selected in the exposed filter, ignore the default date filter '> today'
  $conditions = $view->query->where['1']['conditions'];
  $date_index = 3;
  if(isset($view->query->where['1']['conditions'][$date_index]) &&
    //if a date exposed filter was set
   $view->query->where['1']['conditions'][$date_index]['field'] != 'node.nid')
  {
    unset($view->query->where['1']['conditions'][2]);
  }
}

```

I am really stuck here, IRC is not helping unfortunately, and i would really appreciate more insights on this!

Thanks in advance!

# Answer
> 0 votes
So, I ended up going the very ugly way.

First, my module is now reduced to:

```
    function lezoo_views_query_alter(&$view, &$query) {
  //If a date was selected in the exposed filter, ignore the default date filter '> today'
  $conditions = $view->query->where['1']['conditions'];
  $date_index = 3;
  dpm($conditions);
  if(isset($view->query->where['1']['conditions'][$date_index]) &&
    //if a date exposed filter was set
   $view->query->where['1']['conditions'][$date_index]['field'] != 'node.nid')
  {
    unset($view->query->where['1']['conditions'][2]);
  }
}

```

which is needed because the default filter on dates(not exposed) is **after today**, but if you select a date, then ignore that filter.

And I added a second date\_exposed\_filter, so that I now have date1-\>granularity:Y, and date2-\>granularity:Y-m. I then use css to hide the Y of Y-m, and js to mirror both Year fields. if anyone is interested, here is the code I use:

```
            var year = $('.views-widget-filter-field_date_value_2 select.date-year');
            var ymonth = $('.views-widget-filter-field_date_value_1 select.date-month');
            var yearm = $('.views-widget-filter-field_date_value_1 select.date-year');

            ymonth.change(function(e){
                var value = $(this).val();
                //var value = e.target.value;
                var empty = value == "";
                if(!empty)
                {
                    yearm.val(year.val()).trigger("chosen:updated");
                }
                else
                {
                    yearm.val("");
                }
            });

            year.change(function(e){
                if(ymonth.val() != '')
                {
                    yearm.val(year.val()).trigger('chosen:updated');
                }
                else
                {
                    month.val('');
                }
            })

```

# Answer
> 0 votes
Old thread now, but I encountered a similar problem and ended up breaking apart the date field to solve it. The solution has been working well and opened up other opportunities across the site to select and search content by any date combination.

My original question and answer is here: How to create a filter in Views for filtering dates by day, month, or year?

---
Tags: views, datetime, forms
---


# Question
Title: Run feeds importer crons one after another
I have two feeds importers. I wanted to run the 2nd importer when the first is finished.

I have written a cronapi hook for those two importers.

```
/**
 * Implements hook_cronapi().
 */
function mymodule_cronapi($op, $job = NULL) {
  $items = array(
    'cron_one' => array(
      'description' => 'import feeds one',
      'rule' => '4 0 * * *',
      'callback' => 'mymodule_import_feeds_one',
    ),
    'cron_2' => array(
      'description' => 'Import feeds two',
      'rule' => '4 0 * * *',
      'callback' => 'mymodule_import_feeds_two',
    ),
  );

  return $items;
}

```

In the `hook_enable` I am executing the first importer

```
function mymodule_enable() {
  mymodule_import_feeds_one();
}

function mymodule_import_feeds_one() {
  $src = feeds_source('import_feeds_one');
  $src->save();
  // Set the directory path.
  $source = 'directory-path';
  $config = array('FeedsFileFetcher' => array('source' => $source));
  $src->addConfig($config);
  $src->save();
  try {
    $src->import();
    $src->schedule();
  }
  catch (Exception $e) {
    return FALSE;
  }
  // Prevent notices from being thrown.
  $src->state(FEEDS_FETCH);
  $src->state(FEEDS_PROCESS);
  $src->state(FEEDS_PROCESS_CLEAR);

  return FALSE;
}

```

In `hook_feeds_after_import`

```
/**
 * Implements hook_feeds_after_import().
 */
function mymodule_feeds_after_import(FeedsSource $source) {
  if ($source->id == 'import_feeds_one') {

    mymodule_import_feeds_two();
  }
}

```

The problem is, when I enable the module, it schedules both importers on next cron run.

I want to schedule only the first one and when the first one is completed then schedule the 2nd one.

How can I do that?

# Answer
Your approach is already heading in the good direction. If you don't want to schedule the import of both importers, then you should only schedule the first one in `mymodule_cronapi()`.

Then, in `mymodule_feeds_after_import()`, you'll schedule the next one by calling `startImport()` on the second source object (or by doing something similar as you did in `mymodule_import_feeds_one()`). If you configure your importer to import in the background, then `startImport()` will result into the source being imported during cron. If your import task is large, it may be divided in multiple chunks (depends on the implementation of the parser) so PHP wouldn't exceed the maximum runtime. In this case the import may take multiple cron runs to complete.

```
/**
 * Implements hook_cronapi().
 */
function mymodule_cronapi($op, $job = NULL) {
  $items = array(
    'cron_one' => array(
      'description' => 'import feeds one',
      'rule' => '4 0 * * *',
      'callback' => 'mymodule_import_feeds_one',
    ),
  );

  return $items;
}

/**
 * Implements hook_feeds_after_import().
 */
function mymodule_feeds_after_import(FeedsSource $source) {
  if ($source->id == 'import_feeds_one') {

    feeds_source('import_feeds_two')->existing()->startImport();
  }
}

```

I'm not sure why you want to start an import in `mymodule_enable()`. This code is only called once, when enabling your custom module (unless you disable the module and enable it again).
> 0 votes

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: Make view exposed filter shows results related to previous filter in view
About my form: In my project, i'm having a form where project name field is select(drop down) and i have to enter a field(example "sub-project"). Then i will submit the form with project name from select(drop down) and i will type my sub-project name.

View Form: Here, while showing the form results as table i want two exposed filters. they are 1. Project name(As select box in filter field)(\**No problem in this part) 2.Sub-project name(As select box in filter field)(\**Problem)

Question: Now, if i select project name in filter(Example: Project Auro) then automatically i want the sub-project field(2nd exposed filter) to show the sub-projects as drop-down which are only related to Project Auro, that i submitted in form.

Please assist me, and Thanks in advance if you guide me in this problem.

# Answer
As always there are many ways to solve a problem in Drupal.

The easiest way here is probably the Views Dependent Filters module.

This way the "sub-project" form field will only appear after a user chooses the "project" filter.
> 0 votes

---
Tags: views
---


# Question
Title: "drush up" fails with "pm-updatestatus failed."
When I execute `drush up`, it returns the following error message.

> The command could not be executed successfully (returned: *The filename, directory name, or volume label syntax is incorrect*, code: 1) pm-updatestatus failed.

`drush pm-updatestatus` runs without errors.

Similarly, `"C:\\Users\\user1\\AppData\\Roaming\\Composer\\vendor\\drush\\drush\\drush"
 --backend=2 --verbose --debug --root="C:\\website\\drupal7"
 --uri=http://default pm-updatestatus 2>&1`, which I extracted from the debug output of `drush -d up` (see below) also successfully runs.

What could I try?

The debug output is the following.

> Calling hook drush\_pm\_updatecode\_validate \[11.27 sec, 17.04 MB\]
> Returned from hook drush\_pm\_updatecode\_validate \[11.27 sec, 17.04 MB\] Calling hook drush\_pm\_updatecode \[11.27 sec, 17.05 MB\]
> Cache MISS cid: 8.1.2-alias-path--59067c616e8e4f3b7078e0502d77bf35 \[11.27 sec, 17.06 MB\] Backend invoke:
> "C:\Users\user1\AppData\Roaming\Composer\vendor\drush\drush\drush" --backend=2 --verbose --debug --root="C:\website\drupal7" --uri=http://default pm-updatestatus 2\>&1 \[11.61 sec, 17.09 MB\] "C:\Users\user1\AppData\Roaming\Composer\vendor\drush\drush\drush" --backend=2 --verbose --debug --root="C:\website\drupal7" --uri=http://default pm-updatestatus 2\>&1 \[11.61 sec, 17.09 MB\] The command could not be executed successfully (returned: The filename, directory name, or volume label syntax is incorrect., code: 1) \[11.79 sec, 17.09 MB\] pm-updatestatus failed. \[11.79 sec, 17.08 MB\]

I am using Drush 8.1.2, Drupal 7.50 running on Windows 7, PHP 5.6.23, and Apache 2.4.23.

# Answer
I was able to fix the problem by editing the file `/path/to/drush/includes/exec.inc` and changing line 331 from

```
return _drush_escapeshellarg_windows($arg, $raw);

```

to

```
return _drush_escapeshellarg_windows($arg, TRUE);

```

as described by peterromero here https://github.com/drush-ops/drush/issues/2152
> 1 votes

# Answer
My issue went away when I unlinked my PHP@5.6 and linked PHP@7.2 that MAMP is using. Then I run source ~/.bash\_profile (didn't need to reload Terminal).Restarted apache.
> 1 votes

# Answer
In my case I was getting a Drupal error

```
Error: Call to undefined function Drush\UpdateService\simplexml_load_file() in                 Drush\UpdateService\Project::getInstance() (line 74 of phar:///usr/local/bin/drush/vendor/composer/../../lib/

```

which indicated that the php-xml extension was not installed.

```
sudo aptitude install php7.2-xml

```

fixed the problem.
> 0 votes

---
Tags: drush, updating
---


title: Webform Group Member Composite

text:
# Question
Title: Webform Group Member Composite
I need to create a Webform element that has a list of group members, each with their own checkboxes and text fields ('job description'). I figured out how to display checkable group members through a view, but there's no option for an entity reference-able composite element. Any advice would be appreciated!!

Looking for something like this:

**Group**:

\[X\] group1

\[ \] group2

**Members**:

\[X\] Sarah \[Example Job Description\]

\[ \] Johnny \[\_______________________\]

\[ \] Bobby \[\_______________________\]

Also, a little off topic, but is it possible to use a same page checkbox/whatever element value as a contextual filter for an entity reference element (through the arguments box)? I tried the webform tokens but I couldn't get it to work.

# Answer
> 1 votes
The cleanest solution was just going into modules/webform/modules/ and extending WebformCompositeBase to create a custom composite with an entity reference sub-element. It's super intuitive if you go off of the webform\_example\_composite module (included in core webforms I think).

You only really need to alter webform\_example\_composite/src/Element/WebformExampleComposite.php. If you create the entity reference you want to add as an individual, non-composite element in the webform ui, you can look in build-\>source and translate the form of it from yml to php. A basic Group entity element looked something like this:

```
    $elements['group_members'] = [
      '#type' => 'webform_entity_select',
      '#title' => t('Group Member'),
      '#target_type'=> 'group_content',
      '#selection_handler' => 'default:group_content',
      '#selection_settings' => [
        'target_bundles' => [
          'research_leader-group_membership' => 'research_leader-group_membership'
        ],
      ],
      '#attributes' => ['data-webform-composite-id' => $html_id . '--group_members'],
    ];

```

In the webform\_example\_composite module, the Submission data is generated by again extending WebformCompositeBase in Plugin/WebformElement/WebformExampleComposite.php and overriding the formatHtmlItemValue and formatTextItemValue functions. If you need custom formatting for an entity reference, you'll have to look through WebformCompositeBase and figure out what to call. I was happy with the standard formatting. Just comment out the custom formatHtmlItemValue and formatTextItemValue functions in Plugin/WebformElement/WebformExampleComposite.php to see what standard formatting looks like for your composite.

---
Tags: views, 8, webforms, group
---


title: call a custom JS function once

text:
# Question
Title: call a custom JS function once
I understand once() can be used on a jquery selector method to make sure it is triggered only once.

How to do the same with custom functions?

My function `wakeUpAndRemember` is called 5 times which is problematic.

```
(function ($, Drupal) {
  Drupal.behaviors.recherche = {
    attach: function (context) {
      ...
      wakeUpAndRemember(mapObj);
    }
  };
(jQuery, Drupal);

```

# Answer
> 1 votes
You could set a global variable and then set it in your wakeUpAndRemember function

```
var do_once = false;
function wakeUpAndRemember() {
  console.log('test');
  do_once = true;
}
Drupal.behaviors.recherche = {
    attach: function (context, settings) {
      if (do_once == false){
        wakeUpAndRemember();
      }
   }
}

```

# Answer
> 3 votes
Another option is to use underscore's once function.

```
# your_theme_or_module.libraries.yml
global-styling:
  js:
    js/main.js: {}
  dependencies:
    - core/underscore

// js/main.js
(function ($, _, Drupal) {

  "use strict";

  Drupal.behaviors.example = {

    attach: _.once(function(context, settings) {
      // do stuff once.
    })

  }

})(jQuery, _, Drupal);

```

Underscore comes bundled in Drupal 8 by default.

# Answer
> 1 votes
I don't think this is possible using `.once()`, but you can do it by setting a variable in your function and only running the function if that variable is not set.

Your function shall look like this:

```
var wakeUpAndRemember = (function(mapObj) {
  var executed = false;
  return function() {
    if (!executed) {
      executed = true;
      // The code from your function goes in here.
    }
  };
})();

```

---
Tags: 8, javascript
---


# Question
Title: How do I get the menu block choice "Expand all menu items" to stay checked
I have 2x menu blocks. One in the header and one in the footer. I'd like the header one to stay unexpanded, but expand all the items in the footer.

When I check "Expand all menu items" in the footer, save the result and come back to the block settings it is unchecked when I review.

8.7.6

# Answer
That is not the default behavior. I suppose you have installed Menu Block module.

In that case the "expand all" option from Drupal Core does not seem to work, you will need to use the "expand all" option from the Menu Block module. You can find this at "Advanced options" in the block configuration.
> 2 votes

---
Tags: 8, blocks, navigation
---


title: 500 error during installation?

text:
# Question
Title: 500 error during installation?
Trying to install the new Drupal-COD Drupal 7 distribution, but got this error:

> An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows

Is this the sort of error one can overcome by increasing my `memory_limit` in the php.ini file?

# Answer
> 0 votes
Removing the comment sign at "RewriteBase /" fixes my problem on migration of Drupal 7. in the .htaccess file to fix.

---
Tags: 7, installation
---


# Question
Title: Is there a way to run hook_form_alter after themes implementation?
I'm using the material\_admin theme, which has a `hook_form_alter()` implementation.

I see that my module's `hook_form_alter()` is executed before the theme hook. Both hooks are editing the same form property, so the change done in my code is always overridden.

In my `hook_module_implements_alter()` implementation I see only the modules that implement `hook_form_alter()`. The theme's implementation is not there.

How can I control its execution?

# Answer
I think you cannot have a module hook executed the same hook implemented by a theme. If we look at the hook invoking code, we see that the theme hooks are invoked separately and after the module hooks.

The best bet would be to remove it from the theme and put it in a module, or trying with `#after_build`.

FormBuilder.php contains the following code.

```
$this->moduleHandler->alter($hooks, $form, $form_state, $form_id);
$this->themeManager->alter($hooks, $form, $form_state, $form_id);

```
> 5 votes

---
Tags: 8, forms, hooks
---


# Question
Title: Show form errors before opening AJAX modal
I have a form that adds a product to the cart.

The form uses AJAX to open a modal when the form is submitted.

I want to show form errors (if any) before the modal opens and avoid opening it if there are errors.

Here's my form submit element:

```
$form['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#ajax' => [
    'callback' => '::submitAjaxForm'
  ],
  '#attached' => [
    'library' => ['core/drupal.dialog.ajax'],
  ],
];

```

My `submitAjaxForm`:

```
public function submitAjaxForm(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new OpenModalDialogCommand(
    $this->t('Product added to cart!'),
    [
      '#theme' => 'some_theme',
    ]
  ));

  return $response;
}

```

And my `submitForm`:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  // Add product to cart.
}

```

I have tried by adding this code to the AjaxSubmit but it only shows the error messages once the page has been reloaded.

```
if ($form_state::hasAnyErrors()) {
  foreach ($form_state->getErrors() as $error) {
    $this->messenger()->addError($error);

    $message = [
      '#theme' => 'status_messages',
      '#message_list' => $this->messenger()->messagesByType(MessengerInterface::TYPE_ERROR),
    ];

    $messages = $this->renderer->render($message);

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#result-message', $messages));
    $form_state->setRebuild(TRUE);

    return $response;
  }
}

```

How can I show the errors without having to reload the page?

# Answer
> 0 votes
I see two things that stand out to me:

1) Setting the '#name' attribute on the submit button. You should never do that. I've learned over the days that there is always a better way to do whatever you're trying to do when setting the #name attribute, and setting it causes some wonkiness. This may be why your form is not rebuilding.

2) You are rendering your status messages in a D7 way. Use this instead:

$messages = \['#type' =\> 'status\_messages'\]; $response-\>addCommand(new PrependCommand('#target-div', \Drupal::service('renderer')-\>renderRoot($messages))); It looks weird, because the messages aren't being retrieved, but by setting the #type to status messages, Drupal will handle the retrieval in the background. This is probably why you are seeing some funkiness with the messages.

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


# Question
Title: How to get the View Header and Footer in Custom Module?
I've made a custom view and display for it like this:

How do I get the Views Header (Global Summary here) ? I'm able to get the Views title like this:

```
$views = Views::getView('items_list','page_2');
$views->setOffset($page_id);
$views->execute();
$view_results = $views->result;
print_r( $views->getTitle());exit;

```

Hope someone could help me out.

# Answer
> 0 votes
Step1 - You will create two files header.php and footer.php. Step2 - Create a folder "include" in your theme directory. Step3 - Suppose that your theme directory is "abc" sites/all/themes/abc. Put header.php and footer.php file in "sites/all/themes/abc/include" theme folder. Step3 - By using html and php you can write code in header.php and footer.php. Step4 - Now you can include both files in page.tpl.php in header area and footer area like PHP.

```
  include_once($theme_path.'/include/header.php');
  include_once($theme_path.'/include/footer.php');

```

hope this will help

---
Tags: views
---


# Question
Title: How do I increase the character limit for the default "Fixed value" of a contextual filter?
I'm trying to make a view of my new products using the *Content: Nid* contextual filter.

In this filter I opted to provide a default value, with a type of "Fixed value". On the "Fixed value" field, only 27 values are added, after which no more are accepted.

Apart from the character limit for the text field, is there another reason I can't add more values here? If not, how do I increase the character limit so I can add all the values I wish to?

# Answer
Why don't you write a small code snippet and pass contextual filters using hook\_views\_pre\_view(), that allows altering a view at the very beginning of processing a preview.

```
function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'YOUR_VIEW_MACHINE_NAME' && $display_id == 'page_1') {
    $nids= get_nids(); //write a custom function to get nids.
    $args[] = implode('+', $nids);
  }
}

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: Error when trying to upload a Configuration Synchronization file
I want to create a local copy of a production website. I read that I could use Configuration Synchronization to copy some of the settings of the production website over to my local website. When I try to upload the exported .tar file from the production website to my local website, I get this error:

```
Could not extract the contents of the tar file. The error message is Invalid checksum for file "Y3drj:+uT}vG|59ooc&{C:BS1@/f/" : 65255 calculated, 0 expected

```

I'm using lando to host the website locally. I also had to delete some of the characters in the error message above because stack exchange wouldn't let me post them.

# Answer
> 0 votes
what you need to do is make few changes on settings.php file

$config\_directories = array(

CONFIG\_SYNC\_DIRECTORY =\> 'sites/default/files',

);

On production sites, and if your account has permission to do so, it's a good idea to move the configuration sync directory outside of the webroot entirely. As your sync directory should be under version control, this means having your version control repository's root be one level higher than your webroot. please check out more details at https://www.drupal.org/docs/8/configuration-management/changing-the-storage-location-of-the-sync-directory

---
Tags: configuration
---


# Question
Title: How to use apostrope in meta description
Whenever I use an apostrophe in a meta description the browser prints the code as `'`. Is there a way to prevent this?

These are coming trough a custom module that builds out the page.

# Answer
> -1 votes
When using apostrophe in a taxonomy it is displayed as `&amp#039;` in the html-tittle of the page

The problem could be fixed by disabling the module "Metatag: Views" or updating the `metatag.inc` accordingly: replacing the `check_plain()` by `filter_xss()`

```
class DrupalTitleMetaTag extends DrupalTextMetaTag {

  public function getElement(array $options = array()) {
    $element = array();
    $value = filter_xss($this->getValue($options));
    $element['#attached']['metatag_set_preprocess_variable'][] = array('html', 'head_title', $value);
    $element['#attached']['metatag_set_preprocess_variable'][] = array('html', 'head_array', array('title' => $value));
    return $element;
  }
}

```

---
Tags: 7, meta-tags
---


# Question
Title: Translatable image field gets replaced when adding content
I have added an image field with Translatable Content enabled. My content type has enabled translations too. But when I add an image in the translation, the english contents field get replaced with the newly added translated image. (English is my base language, and I have Japanese and Chinese as translations). This happens vise versa too. What could be the issue?

# Answer
By default only the image alt and title are translatable and the file itself isn't. By the default the file is always the same in all languages. You can simply make the file to be translatable as well under https://example.com/admin/config/regional/content-language.

Note: After you've done this, all your existing translations will need to have the file re-uploaded (or a new file uploaded), as the default only gets added once when translating content through the UI.

---

Taken the above Hero image field this can be done manually be editing `field.field.node.page.field_hero_image.yml` (which translates to `field.field.ENTITY_TYPE.BUNDLE.FIELD_NAME.yml`):

Before file checked:

```
third_party_settings:
  content_translation:
    translation_sync:
      alt: alt
      title: title
      file: '0'

```

After file checked (alt and title are mandatory if file is checked, that's why they have `'0'` now):

```
third_party_settings:
  content_translation:
    translation_sync:
      file: file
      alt: '0'
      title: '0'

```
> 2 votes

---
Tags: 8, nodes, i18n-l10n
---


# Question
Title: How to call method of controller in .module file with dependency injection
I have class named Book.

```
class Popups
{
  private $entityQuery;
  private $entityTypeManager;

  public function __construct(QueryFactory $entityQuery, EntityTypeManagerInterface $entity_type_manager) {
    $this->entityQuery = $entityQuery;
    $this->entityTypeManager = $entity_type_manager;
  }

public function read($cid)
  {
    $nodes = $this->entityTypeManager->getStorage('node')->loadByProperties(['type' => 'book', 'cid' => $cid ]);

    return $nodes;
  }

}

```

Now I have books.module file where I need to call read method; how to call that method

```
$book = new Book();  // what param should i pass here
$book->read($cid)

```

# Answer
> 7 votes
Add the class to *mymodule.services.yml* and inject the core services there:

*mymodule.services.yml*

```
services:
  mymodule.book:
    class: Drupal\mymodule\Book
    arguments: ['@entity.query', '@entity_type.manager']

```

Then use the service in procedural code:

```
\Drupal::service('mymodule.book')->read($cid)

```

---
Tags: 8, dependency-injection
---


# Question
Title: Can I set a theme's logo_path programmatically?
When adding a logo file to a custom theme, I can either

1. save my logo in the theme folder as `logo.png` (replacing the default logo.png from the theme starterkit I'm using), or
2. save my logo in the theme's images folder, using the filename I choose, and use the theme settings page at admin/appearance/settings/themename to set the logo path.

I'm looking for a way to save the logo file in the images folder, while setting the logo path programmatically. This would make sure that the logo is automatically set when enabling the theme. Wouldn't it make sense if that could be done in themename.info, using something like `settings[logo_path] = path/to/my/logo-image.png`?

# Answer
> 3 votes
In Drupal 6, I believe what you are looking for is

```
variable_set('logo_path', '/path');

```

At first glance though, I'm wondering why there is only one such on my site, and not one per theme. theme\_get\_settings appears to be grabbing defaults first, and then merging in theme specific settings on top of that.

In D7, the variable is called 'theme\_themename\_settings'.

# Answer
> 0 votes
The above answer is incorrect for Drupal 6. The variable for the logo path in 6 is the same as the one listed for 7, namely `theme_<theme name>_settings` and the logo path has the key `logo_path`, so for Garland, the logo path would be in `theme_garland_settings['logo_path']`. There is also a flag for whether the theme uses the default logo or not, which should also be set. From PHP, you can accomplish this by:

```
$new_logo="path/to/logo";
$theme_name="theme_name";
$property="theme_" . $theme_name ."_settings";
$settings = variable_get($property, array());
$settings['logo_path'] = $new_logo;
$settings['default_logo'] = 0;
variable_set($property, $settings);

```

Or from a bash script using drush:

```
new_logo="path/to/logo"
theme_name="theme_name"
property="theme_${theme_name}_settings"
drush php-eval "\$settings = variable_get('${property}', array());
\$settings['logo_path'] = '${new_logo}'; \$settings['default_logo'] = 0;
variable_set('${property}',\$settings);"

```

# Answer
> 0 votes
For Drupal 7, in case you need to change the logo from configs.

```
$conf['theme_my_theme_settings'] = [
  'default_logo' => 0,
  'logo_path' => 'sites/my_theme/themes/mytheme/logo.png',
  'default_favicon' => 0,
  'favicon_path' => 'sites/my_theme/themes/mytheme/favicon.ico'
];

```

---
Tags: 6, media
---


# Question
Title: How can I let authenticated users rebuild caches?
Is there a way for authenticated users to clear the cache without giving them the administer site permission?

# Answer
Yes, that's what I created Rebuild Cache Access for.

> This module provides a new permission: `rebuild cache access`. Every role with this permission set will have a nice and big "Rebuild Cache" admin toolbar button. Clicking this button simply fires `drupal_flush_all_caches()`. That's all.
> 5 votes

---
Tags: 8, caching
---


# Question
Title: Add modifier class to module block on custom content type
I'm trying to alter the display of a social media share block module im using on my site on a custom content type. All throughout the site the share block looks like this, floating on the left side of page.

however, on my custom content type I want it to look like this instead

How would I go about adding a modifier class to module block on **only** my custom content type? I'm also using Layout builder for display of content type too.

# Answer
I suppose your social media block is independent from the node and appears on all pages (except maybe some).

In the preprocess of your block, you can get the current route, verify if it's a node and which type of content. You can look this article for an example https://www.computerminds.co.uk/drupal-code/get-entity-route

After that, you can change your variables pass to your twig file and display an additional class or a different class depending your condition.
> 1 votes

---
Tags: 8, layout-builder
---


# Question
Title: make more rare content type appear in result
I've made a view that pulls together results from two different content types - "blog posts" and "resources." This resources content type also has a field to further break down resource type (white paper, webinar, case study, etc.)

The problem: There are far more blog posts than resources. So resources get buried, several pages deep in results. How can I ensure that there's a better mix. I considered adding a weight field and grouping by it, but that doesn't seem like it would solve the problem so well. I don't want one weighted over the other. Just a better mix of the newest content, to always include those more rare resources.

I want each results page to show at least one latest 'white paper' resource, one latest 'case study' resource, one latest blog post, etcetera. Something that breaks up blog posts so they don't overpower other needed content.

Or maybe there's a way to force 'for every 2 blog posts, show a resource' ... anything that organically gets results to appear. I can't/don't want to do this manually.

Maybe something 'groupwise' but I'm not sure where/how to accomplish that.

# Answer
> 0 votes
AFAIK you'll have to manually modify the query to get such advanced conditional sorting.

You could group by the type (under Format), and set the Pager to such a high number that you can always be sure there will be at least one Resource there, so the second group will appear for it. But it's not a very reliable method if you can't predict the longest range of blog entries without Resources.

Usually, this is handled by creating two Views displays, one for blog entries, and the other for resources. You can set the Resources one to be Attachment type, and attach it to the blog one so they display one below the other. In that case you will be able to override the number of items in the Pager to show less Resources than Blog entries, to show Blog entries are more frequent.

---
Tags: views, 8
---


title: Entity reference and associated data

text:
# Question
Title: Entity reference and associated data
Assuming I have two distinct entities A and B, with B having an Entity Reference field to A, how can I associate other data (=other fields) with the Entity Reference?

For example, assume that A is "Political parties" and B "Politicians", and I'd like to store a date range field for the politician's membership in said party.

# Answer
> 1 votes
You can create a paragraph type (paragraph module replaces field collection in Drupal 8) which contains a reference to your entity type A and a (or more) date and in your entity type B, have a reference to this paragraph.

You can also create a custom field which contains a reference to your entity type A and a date if you want have particular behavior (for example, don't allow users to sort items and sort them automatically by date).

---
Tags: entities
---


title: Hide title if 404 error

text:
# Question
Title: Hide title if 404 error
I have a custom 404 error page, and I just want a quick module that hides the 404 page title, if the user arrives at a 404 error.

I've found a D7 function that looks like it would work, checking for '404 Not Found' in the http header, and adding a class that I can target with CSS. But I'm not sure how I'd do something like this for D8.

Here's what I've got:

```
function MYMODULE_preprocess_html(&$variables) {
  $headers = drupal_get_http_header();

  if (isset($headers['status']) && $headers['status'] == '404 Not Found') {
    $variables['classes_array'][] = 'page-404';
  }
}

```

# Answer
I don't think you need a custom module for something like this... This should be as easy as:

1. Go to `Configuration -> System -> Basic Site Settings`, get the page URL you have for the 404 page.
2. Go to `Structure -> Block Layout`, edit the 'Page Title' block, and exclude it under the `Visibility` section, by page URL from step1.
> 4 votes

# Answer
This should work:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function modulename_preprocess_html(&$variables) {
  $status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
  if($status && $status->getStatusCode() == '404') {
    if(!$variables['attributes']) {
      $variables['attributes'] = new Attribute();
    }
    $variables['attributes']->addClass('page-404');
  }
}

```

credits go to: How to check if the current page is a 404 error from a module/template?
> 2 votes

---
Tags: 8, theming, http-request
---


# Question
Title: Where might I place code to programmatically update nodes?
I want to update or set value of specific node/entity with one button that have function to update specific field on that node / entity?

And put in on view tab on that specific node on a button?

How can I achieve that?

I found that simple code will achieve that:

```
use Drupal\node\Entity\Node;

$nodeObj = Node::load(10); // Loading the Node by its Id.
$nodeObj->set('title', 'New title updated');
$nodeObj->set('body', 'The body text has been updated');
$nodeObj->set('field_date', '2017-10-25');
$nodeObj->save(); // Saving the Node object.

```

But how do I use it, I am new to drupal. Sorry if the question is not good.

# Answer
> 0 votes
The two most obvious places to run the piece of code you shared probably are:

1. In a form submit handler, that's been fired upon pressing a submit button.
2. In an update hook, that's been fired upon performing database updates.

---

For creating custom forms with their own submit handler under your own URL see the Form API Example module.

> Demonstrates the Drupal Form API.

---

For running the code inside an update hook, learn about `hook_update_N`.

> Perform a single update between minor versions.

---
Tags: 8, nodes, hooks
---


# Question
Title: Is there any PHP package that's very similar to the Plugin API?
I really like the Drupal 8 plugin system. I am now also working on a non-Drupal related project and am wondering if there's any similar solution to that on packagist.org? Was trying to find one but without success (maybe wrong keywords).

Does anyone know where the idea was coming from? Or is it original Drupal thing?

# Answer
Drupal 8 Plugin API can be installed as a standalone package like follows: `composer require drupal/core-plugin` To make use of it you will have to develop a bunch of integration code. Unfortunately there is no much documentation on how to use Drupal components without Drupal core.
> 1 votes

---
Tags: 8, plugins
---


# Question
Title: How can I change the Webform module date picker calendar icon?
* How to create a custom module?
* Which files should be there in the custom module?
* How to get the form\_id and the exact location of the attribute for which the change is required?

# Answer
* First we need to create a custom module called admissionform, follow this path **modules/custom/admissionform**
* We need to create 2 files inside the custom module called **admissionform.module** and **admission.info.yml**

**admissionform.info.yml**

```
name: admissionform
description: To change the calander icon.
package: Custom

type: module
core: 8.x

```

**admissionform.form.module**

```
<?php
use Drupal\Core\Form\FormStateInterface;

// Hook to change the calendar button image
function admissionform_form_alter(&$form, FormStateInterface $form_state, $form_id) {
 if($form_id=="webform_submission_collateral_form_add_form"){
    // var_dump($form);
    $form['elements']['date_of_event_']['#attached']['drupalSettings']['webform']['datePicker']['buttonImage'] = '/modules/custom/admissionform/images/elements/date-calendar-1.png';
  }
}

```

The icon image should be put at this path **modules/custom/admissionform/images/elements/date-calendar-1.png**

To know form\_id, we can do `var_dump($form_id)` and to get the attributes of the form we can do `var_dump($form)`
> 2 votes

# Answer
The webform below shows how to alter the datepicker options without using a custom module via `Drupal.webform.datePicker.options`

```
uuid: 164b1057-cb1f-4329-abcf-5f85e49c5049
langcode: en
status: open
dependencies: {  }
open: null
close: null
weight: 0
uid: 1
template: false
archive: false
id: datepicker_icon
title: 'How can I change the calendar icon?'
description: ''
category: ''
elements: |
  date:
    '#type': date
    '#title': date
    '#datepicker': true
    '#datepicker_button': true
css: ''
javascript: |
  Drupal.webform = Drupal.webform || {};
  Drupal.webform.datePicker = Drupal.webform.datePicker || {};
  Drupal.webform.datePicker.options = Drupal.webform.datePicker.options || {};
  Drupal.webform.datePicker.options.buttonImage = 'https://cdn3.iconfinder.com/data/icons/database-line/128/calendar_date_schedule_datepicker-128.png';
settings:
  ajax: false
  ajax_scroll_top: form
  ajax_progress_type: ''
  ajax_effect: ''
  ajax_speed: null
  page: true
  page_submit_path: ''
  page_confirm_path: ''
  page_admin_theme: false
  form_title: both
  form_submit_once: false
  form_exception_message: ''
  form_open_message: ''
  form_close_message: ''
  form_previous_submissions: true
  form_confidential: false
  form_confidential_message: ''
  form_remote_addr: true
  form_convert_anonymous: false
  form_prepopulate: false
  form_prepopulate_source_entity: false
  form_prepopulate_source_entity_required: false
  form_prepopulate_source_entity_type: ''
  form_reset: false
  form_disable_autocomplete: false
  form_novalidate: false
  form_disable_inline_errors: false
  form_required: false
  form_unsaved: false
  form_disable_back: false
  form_submit_back: false
  form_autofocus: false
  form_details_toggle: false
  form_access_denied: default
  form_access_denied_title: ''
  form_access_denied_message: ''
  form_access_denied_attributes: {  }
  form_file_limit: ''
  submission_label: ''
  submission_log: false
  submission_views: {  }
  submission_views_replace: {  }
  submission_user_columns: {  }
  submission_user_duplicate: false
  submission_access_denied: default
  submission_access_denied_title: ''
  submission_access_denied_message: ''
  submission_access_denied_attributes: {  }
  submission_exception_message: ''
  submission_locked_message: ''
  submission_excluded_elements: {  }
  submission_exclude_empty: false
  submission_exclude_empty_checkbox: false
  previous_submission_message: ''
  previous_submissions_message: ''
  autofill: false
  autofill_message: ''
  autofill_excluded_elements: {  }
  wizard_progress_bar: true
  wizard_progress_pages: false
  wizard_progress_percentage: false
  wizard_progress_link: false
  wizard_start_label: ''
  wizard_preview_link: false
  wizard_confirmation: true
  wizard_confirmation_label: ''
  wizard_track: ''
  preview: 0
  preview_label: ''
  preview_title: ''
  preview_message: ''
  preview_attributes: {  }
  preview_excluded_elements: {  }
  preview_exclude_empty: true
  preview_exclude_empty_checkbox: false
  draft: none
  draft_multiple: false
  draft_auto_save: false
  draft_saved_message: ''
  draft_loaded_message: ''
  draft_pending_single_message: ''
  draft_pending_multiple_message: ''
  confirmation_type: page
  confirmation_title: ''
  confirmation_message: ''
  confirmation_url: ''
  confirmation_attributes: {  }
  confirmation_back: true
  confirmation_back_label: ''
  confirmation_back_attributes: {  }
  confirmation_exclude_query: false
  confirmation_exclude_token: false
  confirmation_update: false
  limit_total: null
  limit_total_interval: null
  limit_total_message: ''
  limit_total_unique: false
  limit_user: null
  limit_user_interval: null
  limit_user_message: ''
  limit_user_unique: false
  entity_limit_total: null
  entity_limit_total_interval: null
  entity_limit_user: null
  entity_limit_user_interval: null
  purge: none
  purge_days: null
  results_disabled: false
  results_disabled_ignore: false
  token_update: false
access:
  create:
    roles:
      - anonymous
      - authenticated
    users: {  }
    permissions: {  }
  view_any:
    roles: {  }
    users: {  }
    permissions: {  }
  update_any:
    roles: {  }
    users: {  }
    permissions: {  }
  delete_any:
    roles: {  }
    users: {  }
    permissions: {  }
  purge_any:
    roles: {  }
    users: {  }
    permissions: {  }
  view_own:
    roles: {  }
    users: {  }
    permissions: {  }
  update_own:
    roles: {  }
    users: {  }
    permissions: {  }
  delete_own:
    roles: {  }
    users: {  }
    permissions: {  }
  administer:
    roles: {  }
    users: {  }
    permissions: {  }
  test:
    roles: {  }
    users: {  }
    permissions: {  }
  configuration:
    roles: {  }
    users: {  }
    permissions: {  }
handlers: {  }

```

The key is adding the JS snippet below to your webform CSS/JS (admin/structure/webform/manage/WEBFORM\_ID/settings/assets)

```
Drupal.webform = Drupal.webform || {};
Drupal.webform.datePicker = Drupal.webform.datePicker || {};
Drupal.webform.datePicker.options = Drupal.webform.datePicker.options || {};
Drupal.webform.datePicker.options.buttonImage = 'https://cdn3.iconfinder.com/data/icons/database-line/128/calendar_date_schedule_datepicker-128.png';

```
> 2 votes

---
Tags: 8, webforms
---


# Question
Title: Drupal 8 REST add custom error messages to existing core /entity/user/ resource
I am using drupal 8 rest and I want to be able to do a few computations and return custom json messages as per the defined condition when posting a user. I am using the already existing `/entity/user/` resource provided by core out of the box. I tried to create a custom module and tried to use the `Drupal\rest\ResourceResponse` class in the module file like below:

```
function magri_rest_user_presave($account) {

    if (isset($account->field_region->value)) {

        $taxonomy_query = \Drupal::entityQuery('taxonomy_term');
        $taxonomy_query ->condition('vid', "region")
            ->condition('name', $account->field_region->value);
        $tids = $taxonomy_query->execute();

        $tid = array_values($tids)[0];

        if($tid){
            //set taxonomy ref field on user entity
            $account->field_region_tax->target_id = $tid;

        }else{
            die;
            $response = ['message' => 'Region not found'];
            return new ResourceResponse($response);
        }
    }
}

```

This does not stop the rest call to return the custom message. Is there a way I can archive this withouts creating my own custom rest plugin?

# Answer
You can't return a response from a presave hook. You can however throw an exception, which in a json route will return a json error message:

```
throw new NotFoundHttpException('Region not found!');

```

If you want to change the default error response, implement an exception subscriber to catch this exception and return your own response.

For reference the default exception handler: ExceptionJsonSubscriber::on4xx
> 2 votes

---
Tags: 8
---


# Question
Title: Alternative #markup in a block's build function
Version: Drupal 8.7.x

I am adding some canvas element to my page, and it gets ignored by Drupal. I can't even see it in the source page of browser.

If I have something like this in my code:

```
public function build(){
   $content = "<span>Something</span><canvas id='12' width='100' height='100'>
               </canvas>"
   return ['#markup'=>$content];
}

```

View page source will only shows

```
 <span>Something</span>

```

I was thinking that this might be an issue with the `#markup`. I was wondering if there are any alternative way to work with canvas.

# Answer
> 0 votes
You can use #allowed\_tags on the markup.

So put it like that:

```
  $content = "<span>Something</span><canvas id='12' width='100' height='100'>
               </canvas>"
   return [
     '#markup' => $content,
     '#allowed_tags' => [
       'canvas',
       'span'
     ]
   ];

```

not exactly sure if you need to add the span tag.

But also note that following is suggested as Drupal Best Practice from https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/group/theme\_render/8.7.x:

> #markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup

And this is the explanation from Drupal regarding #markup and tags:

> Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (For example, and are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of allowed tags. If your markup needs any of the tags not in this whitelist, then you can implement a theme hook and/or an asset library. Alternatively, you can use the key #allowed\_tags to alter which tags are filtered.

---
Tags: 8, blocks
---


# Question
Title: Entity wrapper save using db_transaction()?
I am using a `db_transaction()` for some data updates. I am using some `EntityMetadataWrapper`s, modify some data, then save.

The thing is, the wrapper `->save()` function doesn't have a parameter for `$transaction` like the entity controller does: `entity_get_controller($entity_type)->save($entity, $transaction)`.

If I don't pass in a transaction, it will call `db_transaction()` when one already exists.

* What will happen in this case during commit or rollback of the outer transaction?
* If a new transaction is created, does this commit the one that already existed?
* If a rollback of the outer one won't rollback the inner one, or if it messes up stuff when a new one is created, then is there a way to do it all in one transaction?

Note: I'm using MariaDB.

# Answer
I finally found an explanation of what happens in this case in the Transactions documentation.

> While we cannot declare functions "transactional" in PHP, we can emulate Java's nesting logic by using objects with constructors and destructors. A function simply calls "$transaction = db\_transaction();" as its first (or nearly first) operation to make itself transactional. If one transactional function calls another, our transaction abstraction layer nests them by performing no transactional operations (as far as the database sees) within the inner nesting layers.
>
> To start a new transaction, simply call `$transaction = db_transaction();` in your own code. The transaction will remain open for as long as the variable $transaction remains in scope. When $transaction is destroyed, the transaction will be committed. If your transaction is nested inside of another then Drupal will track each transaction and only commit the outer-most transaction when the last transaction object goes out out of scope, that is, all relevant queries completed successfully.

### Drupal 8+ works the same way

The current Database Transactions documentation contains a similar paragraph to the above Drupal 7 information.
> 1 votes

---
Tags: 7, entities, database
---


# Question
Title: How to add custom php field views that returns my custom functions value?
I'm designing a form that creates a user on sign in. After that I'm displaying the data in a view for an admin to approve. I need to add custom PHP code that calls a function that performs approval of users. How can I do that?

In D7, we can add **Global:views PHP** field to custom php code. Likewise I need that in D8 also.

# Answer
> 0 votes
yes in d7 we had php but in d8 (for good reason) this is not the case. You can however create a controller to do the approval functionality,

then in the view create a button or link that passes the user id to it

such as in view make sure you have the user id field then make a new filed with custom text

```
<a href="/your-controller-path-to-approve-user/{{uid}}>Approve user</a>

```

then in a custom module create a controller see:

1) https://www.drupal.org/docs/8/creating-custom-modules/adding-a-basic-controller

2) https://www.drupal.org/docs/8/creating-custom-modules/add-a-routing-file

then change the route to use your path and better permission

yourmodule.content:

path: '/your-controller-path-to-approve-user/{user\_id}'

....

\_permission: 'Administer users'

then in your controller method example

```
   public function content($user_id) {
     //do the stuff to approve the user here.
   }

```

for bonus points you can look in to making it use ajax. eg https://api.drupal.org/comment/62725#comment-62725

and if this is still not your thing then you will need to look in to

creating custom Twig extensions but far better to go the controller route.

---
Tags: views, 8
---


# Question
Title: Create a simple download link using twig
I want to create a simple download link on twig using Drupal8 but as easy as it can seems, I didn't find anything that was matching for me, it will always be the same file to download, it will be stock directly on the server so I don't need something that change up to parameters.

Thank you

# Answer
> 3 votes
Twig files take up Html markup. If its not something dynamic, just use the link tag.

```
<a href="/server_path/filename.jpg" download>

```

---
Tags: 8, theming
---


# Question
Title: How to Determine a View Row's Content Type
I'm putting together a view with multiple content types. In my my\_theme.theme file I want to set the template suggestion based on the item's content type (e.g. Content-Type-A gets Template-A.twig and Content-Type-B gets Template-B.twig). Digging through the $variables\[\] array I can't find if or where there is an element that specifies the content type for the current view row.

Does any know how I may determine the content type of view row in the $variables\[\] array? If it's not in there what's the best way of adding it?

Thanks!

# Answer
> 0 votes
Create a new display mode and use this display mode on the view. then each of this display mode can be altered in admin or custom template can be made.

---
Tags: views, 8
---


# Question
Title: Programatically get the webform submission "sid" on submitForm
I am trying to programatically get the webform submission sid on submitting a webform but failed to get it !

On my **customwebformhandler.php** file i have the below:

```
public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
// Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get the Webform submission "Sid".
    $sid = $webform_submission->id();

// Show a success message.
    \Drupal::messenger()->addMessage(t("$sid"));

}

```

but i am not getting any sid value.

any help please ?

# Answer
> 1 votes
So it turns out i will have to save the webform before i can get its sid since i am using the `public function submitForm` which is fire in submitting the webform but before saving it.

**Final code will be:**

```
public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
// Get an array of the values from the submission.
    $values = $webform_submission->getData();
    // ...
    $webform_submission->save();

    // Get the Webform submission "Sid" after saving the webform submission.
    $sid = $webform_submission->id();

// Show a success message.
    \Drupal::messenger()->addMessage(t("$sid"));

}

```

---
Tags: 8, webforms
---


# Question
Title: Fetching node field values programmatically
I have figured out how to query the node table programmatically without using the deprecated db\_query() function. However, I soon discovered that the actual content fields are not held in the node table, but in a separate revisions table.

I can't figure out how to select fields from the content nodes.

So for example, I can get a count of the number of nodes of type "entity", by using the following code.

```
use Drupal\Core\Database\Database;
$connection = Database::getConnection();

$sth = $connection->select('node', 'x')
->fields('x', array('nid', 'type'));

$executed = $sth->execute();
$results = $executed->fetchAll(\PDO::FETCH_OBJ);

$type_entities = array();

foreach ($results as $row) {

    // COUNT ONLY ENTITIES
    if ( $row->type == "entity" ) {
        $type_entities[] = $row->nid;
    }
}
echo "Total: ".count( $type_entities );

```

This code works fine, because I am not referencing any data from the node, just counting the node id's.

But say I also have a field entitled "color", and I want to return that field too, so I can count the number or red, green, blue, etc? The following code won't work, because the "color" field is not in the node table, so can someone please help me to create a working version of the following:

```
use Drupal\Core\Database\Database;
$connection = Database::getConnection();

$sth = $connection->select('node', 'x')
->fields('x', array('nid', ['type', 'color'] ));  // <-- ADDED color FIELD

$executed = $sth->execute();
$results = $executed->fetchAll(\PDO::FETCH_OBJ);

$type_entities = array();
$is_red = array();
$is_greed = array();
$is_blue = array();

foreach ($results as $row) {

    // COUNT ONLY ENTITIES
    if ( $row->type == "entity" ) {
        $type_entities[] = $row->nid;

        // COUNT COLOURS
        if ( $row->color == "red" ) {
            $is_red[] = $row->nid;
        } else if ( $row->color == "green" ) {
            $is_green[] = $row->nid;
        } else if ( $row->color == "blue" ) {
            $is_blue[] = $row->nid;
        }
    }
}
echo "Total: ".count( $type_entities );
echo "Red: ".count( $is_red );
echo "Green: ".count( $is_green );
echo "Blue: ".count( $is_blue );

```

So how do I do that, only fetching the "color" field properly using -\>fetchField() or -\>fetchCol() maybe?

Thanks for looking!

# Answer
> 2 votes
I think you should leave the database structure and focus on the entities concept.

This brings you to a simpler approach using entityTypeManager to get nodes and filter them by whatever you want.

```
$query = $this->entityTypeManager()->getStorage('node')->getQuery();
$nids = $query->loadByProperties(
    [
        'type' => 'content_type',
        'status' => 1,
        'field_name' => 'value'
    ])
    ->execute();

```

---
Tags: 8, nodes, database
---


title: Sub tabs similar to Media library

text:
# Question
Title: Sub tabs similar to Media library
I am trying to replicate the user interface Media library provides in 8.8.

I've created a view with 2 displays:

View 1:

Menu tab where Parent is "Content"

`/admin/content/media-image`

View 2:

`/admin/content/media-image-shared`

No menu in the Views UI.

I've then defined:

```
custom_media.image_space:
  title: 'Images'
  route_name: view.media.page
  parent_id: view.media.page
  weight: 20

custom_media.image_shared:
  title: 'Shared images'
  route_name: view.media.shared
  parent_id: view.media.page
  weight: 20

```

The main tab next to Content / Media / Files / Images is present. However, the subtabs on my view Images are not displayed.

What am I missing?

# Answer
> 0 votes
Figured it out!

The parent must be the Views local task id for both definitions.

So `parent_it` should be `views_view:view.media.page`

---
Tags: views, 8
---