# Question
Title: Is it possible autoload PHP classes in themes?
Does the namespace, class name and naming convention work like it does for modules?

These links don't seem to mention it:

# Answer
> 1 votes
I believe it should but looking at bootstrap they seem to be needing a fix https://git.drupalcode.org/project/bootstrap/blob/8.x-3.x/autoload-fix.php

# Answer
> 5 votes
There's an interesting development going on regarding themes and OOP. Look at Allow themes to provide services.yml which finally got closed as Won't Fix. From Mark Carver's closing comment:

> I really don't think we should be opening up themes to services anymore.
>
> A lot has changed (for the better) in the 5 years I've been following this issue (closely).
>
> If this were to happen... there wouldn't be any real delineation between what a module is vs. what theme is, would there?

Instead as a result Allow themes to declare dependencies on modules is the route to go now. To move all the OOP stuff out of themes as *the theme layer is for theming things*, as JayPan said in the comments.

My answer to that problem is that I now always create a `themename_companion` module where I provide Drush 9 commands, helper functions, services etc. for my themes.

---
Tags: 8, theming
---


title: Date/Time not saved correctly?

text:
# Question
Title: Date/Time not saved correctly?
I made a date range field, and after entering some values and saving on first glance it looks ok, if i entered 20:00:00h it will display the same, but in the DB when i look at the stored values it's -2h (so 18:00:00). Anyone know why?

Also this is a huge problem when manually retrieving the values from the node, i fiddled around the time zones etc but i always get the value stored in the DB.

```
$node = Node::load($node_id);
$date = $node->get('field_date_ept2')->getValue()[0];
$result = \Drupal::service('date.formatter')->format($date['value'], 'custom', 'Y-m-d\TH:i:s', 'Europe/Berlin);
echo $result; // 2019-12-12T18:00:00

```

p.s. the timezone in my drupal 8 site is "Europe/Berlin" and the same as in my `php.ini` file.

# Answer
> 1 votes
The datetime value stored in DB is the UTC value. Any built in date formatter should give you the correct local time on the page. However if you need to manually get it from DB you'll have to convert the timezone yourself.

# Answer
> 0 votes
All dates are stored in UTC timezone. So your drupal account has a timezone set which is +2hours from UTC and drupal is converting that back to UTC before storing the date.

Here's how you can get the timezone back into the correct format in code. Elsewhere in views and stuff it should happen automatically:

```
$start_date = $v->field_MY_FIELD->start_date;
\Drupal::service('date.formatter')->format($start_date->getTimestamp(), 'custom', 'Y-m-d H:i:s');

```

That will return it in whatever the current user/default site timezone is set as. Or you can specify the timezone:

```
\Drupal::service('date.formatter')->format($start_date->getTimestamp(), 'custom', 'Y-m-d H:i:s', 'Europe/London');

```

---
Tags: 8, datetime
---


# Question
Title: How to get more info on error during clone?
When cloning one of my sites I get the following error:

> SQLSTATE\[HY000\]: General error: 1267 Illegal mix of collations (utf8\_general\_ci,IMPLICIT) and (utf8\_unicode\_ci,IMPLICIT) for operation '=' \- error

I am unsure how to find where this is happening. I would appreciate any help!

# Answer
> 1 votes
This looks like an SQL error and not an Aegir one so I'd recommend searching for that error specifically. However, the conventional way to get more output for a failed Aegir task would be to run the following on the CLI:

```
drush @hostmaster hosting-task --force --verbose --debug TASK_ID

```

---
Tags: aegir
---


title: Change Aegir Log Level?

text:
# Question
Title: Change Aegir Log Level?
The log messages for tasks seems pretty uninformative when you have an error. Is it possible to change the log level for task logs in Aegir? If so, how?

Thanks!

# Answer
> 2 votes
Navigate to *Hosting » Settings » Task Logs to Display* and you can check/uncheck the boxes for the different types of log messages.

As Add proper UX to the selector for choosing logs types to show is fairly new (see that issue for background), it hasn't made it into a release yet so you'll probably still see the text area.

---
Tags: aegir
---


# Question
Title: Undo/redo drupal console generate:plugin:block?
I ran drupal console generate:plugin:block and made a mistake. I'd like to run it again, but I get this error:

```
 'block' entity with ID 'my_block' already exists.

```

I've removed the source file that the command created, but this error still persists. I'm guessing the block was added to the site's actual configuration. How can I undo/overwrite it?

# Answer
I think I found the answer myself:

```
 drupal config:delete active block.block.my_block

```

(For my specific case) Good luck finding the configuration name. There's no listing from the console. I had to export the whole damn thing to a directory and grep for it.
> 3 votes

---
Tags: console
---


# Question
Title: session_unset logs out user when viewing the page
We have an application that we developed in Drupal 7 and I am tasked with migrating this form to Drupal 8. I have a question about the session behavior which seems to have changed from Drupal 7 to 8.

Our application is a node and whenever that node is navigated to, or refreshed, the session is unset and restarted (for security purposes).

```
function fu_preprocess_node__application(&$vars) {
    session_unset();
    if(session_id() == ''){
        ini_set('session.gc_maxlifetime','28800');
        session_start();
    }
}

```

In Drupal 7, if I am logged in as an admin user and working on the form and I navigate to the application node to view it, I am fine. However, in Drupal 8, when I am logged in to Drupal and I wish to view this page, the session\_unset() logs me out and gives access denied errors for contentual/render and history/23/read.

What do I need to change so that we can unset the session for the application form but not get logged out as drupal user? For the typical user of this form, who does not log in as a drupal user, this is not an issue. But as an admin working on the form, it is an issue.

# Answer
I was able to combine two of the responses to solve my problem. I indeed updated it to use the symfony that is now part of drupal 8. (Comment #3). Reading https://www.drupal.org/docs/7/security/safely-impersonating-another-user gave me an idea to test for anonymity. So I ended up changing the original code to:

```
if(\Drupal::currentUser()->isAnonymous()) {
    $request = \Drupal::request();
    $session = $request->getSession();
    $session->clear();
    if($session->getId() == '') {
        ini_set('session.gc_maxlifetime','28800');
        $session->start();
    }
}

```

This seemed to make my problem go away. Not sure if this is the *best* solution, or a band-aid, but it worked for me.
> 0 votes

---
Tags: 8, nodes, sessions
---


# Question
Title: I can see the changes I made (as an administrator) but as an anonymous user, I can't
***Have you had any problems like this before? I appreciate your help.***

When I'm an admin and update a node (custom module), I can see the changes I made (as `an administrator`). However, when I'm an `anonymous user`, just to check the data, I can't see the changes I made. (note: I have flushed the site, it will work, but only when I run flush)

I thought it was something related with the permission, from a Custom module I created, but I'm not sure of that. I included a `permission.yml` file and gave full access. It didn't work.

find the attached images:

I had built the code in the Controller folder/file: I have two public functions called retrieveArrayOne and retrieveArrayTwo. Each one has different data for me to query later (retrieving the data from these two functions).

```
public function mainviewlist() {
  $array1 = array($this->retrieveArrayTwo());
  $array2 = array($this->retrieveArrayOne());
  $retrieveData = array_merge($array1, $array2);
  $content = "<H2></H2>";
  foreach ($retrieveData as $key1 => $finalValues) {
    if ($key1 == 0) {
      foreach ($finalValues as $disCrop) {
        $content .= "<details>";
        $content .= '<summary>' . $disCrop . '</summary>';
        $content .= "</details>";
      }
    }
  }
  return array(
    '#type'     => 'markup',
    '#markup'   => $content,
    '#attached' => array(
      'library' => array(
        'modulename/modulename',

      ),
    ),
  );
}

```

Here is the function from the $array1 and array2. Both are similar.

```
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'content-type-name');
$query->sort('title', 'ASC');
$entity = $query->execute();
$options = array();

foreach ($entity as $n) {
  $node = \Drupal\node\Entity\Node::load($n);
  $options[$node->id()] = $node->getTitle();
  $elementA[] = [//
    'nid'        => $node->get('nid')->value,
    'title'      => $node->get('title')->value,
    'body'       => $node->get('body')->value,
    'field_crop' => $node->get('field_crop')->value,
  ];
}

return $elementA;

```

# Answer
OK, I found the problem.

In my routing file, I was missing:

```
  options:
    no_cache: TRUE

```

That fixed it.
> -1 votes

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


# Question
Title: How do I export the list of URL alias into an excel or csv?
I am beginner and have recently started to work on Drupal website that has been implemented at my work place.

I would like to export the list of URL alias to an excel or csv file so that we can look at the various url aliases that we have set and eliminate or update those that aren't required.

How can I achieve this?

# Answer
This is easy with a query:

```
select source, alias from url_alias INTO OUTFILE '/tmp/url_aliases.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

```

If you are good with mysql, you can run this directly from mysql with your drupal database selected.

If you are using drush you can run the query this way from the command line when in your site's root directory:

```
drush sqlq "select source, alias from url_alias INTO OUTFILE '/tmp/url_aliases.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';"

```

If you have the developer module installed, you can run this with db\_query in /devel/php:

```
db_query("select source, alias from url_alias INTO OUTFILE '/tmp/url_aliases.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';");

```

You can also run the above code anywhere in the code base that runs on page execution, and then remove it once you have gotten your csv.
> 5 votes

# Answer
To further expand oknate's answer, yet another solution is to use Forena (disclosure: I'm a co-maintainer). Below are the required steps, which typically takes a few minutes (at max) to complete.

### Step 1: Create a data block

* Navigate to `admin/structure/forena/data/add`.
* Select the desired "Data Source" (eg: *Custom Drupal Reports*), and enter the machine name of the block to be created (eg `path_aliases`, no need to specify the .sql suffix).
* Enter your SQL, in this case all that's needed is `select source, alias from url_alias`, and optionally (within "Advanced"), enter a value for the data security you want to apply to this data block, eg: `access administration pages`.
* After saving this, an SQL file will be saved in something like `files/private/forena/datablocks/path_aliases.sql`, with a content that looks like so:

> --ACCESS=access administration pages
>
> select source, alias from url\_alias

### Step 2: Create a report

* Create a new report, by navigating to `reports/add`.
* Enter some values for the report to be created, ie:
    + Report title (required), e.g. "Path aliases".
    + Report name (required), e.g. `path_aliases`.
    + Report category (optional, to group various reports together, e.g. "Demo").
* After hitting the `Create` button, the WYSIWYG report editor shows up. For the purpose of this report, IMO it's sufficient to use these options in it:
    + Use the `+Data` button to select the data block created in Step 1. Note how it already shows a preview of the data contained in that data block. Use the `Select` button to move on to the next part of adding a data block in a report: select "`Simple Table`" as the report template (no need for another template such as an SVG Graph or CrossTab table in this case). Specify the "Text format" (within Setting), e.g. use "`Full HTML`". For this case just accept the defaults for all other facilities on this screen and use the `Add` button to complete adding this data block to your report.
    + Use the tab `Document Types` to indicate that you want to enable the CSV option (so that anybody who browses this report, can use the link "CSV" to export the report data to a CSV file).
    + Use the `Save` button to save the specifications of your report. After doing so, you will be redirected to a path to browse your actual report, and which should include an hyperlink (upper right) to export your report data to a "CSV".

### Sample report

After you complete the steps as above, a so called `.frx` file will be saved somewhere in your files directory, which contains the entire report configuration (= specification). Its actual location depends on how you configured your report specification directory.

Here is a sample of how the `path_aliases.frx` file for the above example looks like:

```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY nbsp " ">
]>
<html xmlns:frx="urn:FrxReports">
<head>
<title>Path aliases</title>
<frx:category>Demo</frx:category>
<frx:options/>
<frx:parameters>
</frx:parameters>
<frx:docgen>
  <frx:doc type="csv"/>
</frx:docgen>
<frx:fields>
</frx:fields>
<frx:menu/>
<frx:cache/>
<style/>
</head>
<body>
<div id="path_aliases_block" class="FrxTable" frx:block="drupal_cust/path_aliases">
    <table>
      <thead>
        <tr>
          <th>source</th>
          <th>alias</th>
        </tr>
      </thead>
      <tbody>
        <tr id="path_aliases" frx:foreach="*">
          <td>{source}</td>
          <td>{alias}</td>
        </tr>
      </tbody>
    </table>
</div>
</body>
</html>

```

Note that everything above was created using a WYSIWYG report editor (no custom coding, etc). And anybody with the relevant permissions (to design reports, and/or to create data blocks, or both) can use this.

If you want to deploy it to another site, just copy/transfer the content of the above `.sql` (from Step 1) and `.frx` (from Step 2) to the appropriate files subfolder in that other site.
> 1 votes

# Answer
A more simpler method would be to use a tool like HeidiSQL or SequelPro sql clients, connect to your database, open the url\_alias table and then do File \> Export or in SequelPro, there is a gear icon at the bottom of the table. You can click on it and hit "Export to CSV".
> 1 votes

# Answer
A really simple way : Use `phpMyAdmin`. Select the table `url_alias`. Click export tab. You can choose format : sql, CSV, CSV for Excel, etc.
> 0 votes

---
Tags: path-aliases, importing-exporting
---


# Question
Title: How do I attach JS and CSS on Slick Views
I would like to attach a CSS file and a JS library on Slick Views module from a custom module. Is there a hook function for Slick Views or any solution?

# Answer
Picking up from @leymannx (and copy/pasting from the linked answer) here's a more spelled-out solution:

You could use the `template_preprocess_views_view()` hook to do this:

```
function THEME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'my_slick_view') {
    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'your-theme') . '/your-js.js');
    // add needed stylesheet
    drupal_add_css(drupal_get_path('theme', 'your-theme') . '/your-css.css');
  }
}

```
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: How to clear page cache without rebuilding other caches
I have a large site which uses Drupal cores 'page caching for anonymous users'. I have made some javascript changes which I need to deploy. Since pages are currently cached I will need to clear the page cache.

I am wondering if there is a way of only clearing the page cache? If possible I don't want to have to rebuild any other caches (e.g. menu).

I know Drush provides a certain level of granularity when it comes to caching; however, it would appear that Drush is not capable of only clearing the page cache

```
$ drush cc

Enter a number to choose which cache to clear.
 [0]   :  Cancel
 [1]   :  all
 [2]   :  drush
 [3]   :  theme-registry
 [4]   :  menu
 [5]   :  css-js
 [6]   :  block
 [7]   :  module-list
 [8]   :  theme-list
 [9]   :  registry
 [10]  :  metatag
 [11]  :  token
 [12]  :  views

```

# Answer
You can use Flush Page Cache or Cache Actions module.

See if either of them solves your problem.

**Flush Page Cache:**

> Easing the pain when you need to flush...Drupal's cache.
>
> Flushing Drupal's cache on a large site can feel like you're waiting to takeoff on the tarmac at JFK. The delay comes from the fact that when you clear Drupal's cache, it clears everything. Most of time you just want to flush the cache for specific object on a page.
>
> The Flush page cache module solves this problem by flushing only the cached objects for a single page. Additionally, you can define custom objects and cache tables to be cleared on specific pages.

**Cache Actions:**

> Cache actions provides rules actions for clearing drupal caches.
>
> It currently provides actions for:
>
> * Clearing Drupal cache bins
> * Clearing CSS/JS cache
> * Clearing The cache of specific views
> * Clearing The cache of specific panel pages
> * Clearing The cache of specific mini panels
> 3 votes

# Answer
Using only drush, you can use `php-eval` to run this:

```
drush php-eval "cache_clear_all(NULL, 'cache_page');"

```
> 0 votes

---
Tags: drush, caching
---


# Question
Title: How do I remove the colon from my field labels?
I simply want to be able to remove the colon from my rendered field labels, for example:

Hotel name: to Hotel name

I copied field.tpl.php and removed the colon there, but no matter what Drupal refuses to accept it and is pulling the colon from elsewhere.

How can I do this with a template.php function?

# Answer
The answer is definitely to use field.tpl.php. If you look at the source for that file you can see the offending lines:

```
<?php if (!$label_hidden): ?>
  <div class="field-label"<?php print $title_attributes; ?>>
    <?php print $label ?>:
  </div>
<?php endif; ?>

```

(spacing and indentation mine for clarity).

Removing the colon is as simple as replacing the above lines with:

```
<?php if (!$label_hidden): ?>
  <div class="field-label"<?php print $title_attributes; ?>>
    <?php print $label ?>
  </div>
<?php endif; ?>

```

I've just tested that on a blank Drupal installation and it works perfectly; no more colons after field labels.

If you're already doing the same thing, but not getting the correct results, then I can think of one or two things that could be going awry:

* You've put your custom version of field.tpl.php into a module folder, rather than in your site's active theme folder (it needs to be in the theme folder).
* Another module/element in the system is also overriding field.tpl.php, in a more robust manner than you currently are. Seeing if this is the case will involve the always-tedious disabling of each enabled module to determine where the problem is coming from.

You won't be able to make the change with a template preprocess function, as the colon is hard-coded into the template file.
> 16 votes

# Answer
I just created a module which does exactly this, removes colons (on a per field basis) from field labels on output: Colectomy
> 9 votes

# Answer
If it is a View with fields, just click on the field and uncheck "Place a colon after the label" under "Create label".
> 2 votes

# Answer
Display suite provides the same functionality as well:

If you enable display suite extras there's an option to remove colons before labels:

The path for that is: `/admin/structure/ds/list/extras/`
> 2 votes

# Answer
I couldn't find an answer to this question for Drupal 8 anywhere. With Drupal 8 the colon is added with a CSS file (field.css) in the Classy core theme if you're using it as your base theme. All you have to do is override it in your own CSS file in your theme.

So from the original field.css file:

```
.field--label-inline .field__label::after {
    content: ':';
}

```

In my theme CSS file to remove the colon:

```
.field--label-inline .field__label::after {
    content: '';
}

```
> 1 votes

# Answer
In my case it worked by overriding `theme_field()` (`field.module`) by copying the entire function to my `template.php` file and changing the line that reads

```
$output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ' </div>';

```

Clear caches before trying.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Where is the `Drush` command specific documentation?
To be more specific than the title, I want to know what `drush cim` exactly does, like:

* where is the `drush cim` command specific documentation?
* Does `cim` command remove the files after they are imported, or not?
* where are the setting files imported from, can you provide me with a path relative to the root (I mean, relative to where the main `index.php` file of `drupal` is)?
* can we change the import path?
* can we tell `drush` to just delete any (previously exported) setting files ?

# Answer
> where is the drush cim command specific documentation?

https://drushcommands.com/drush-9x/config/config:import/

> Does cim command remove the files after they are imported

No.

> where are the setting files imported from, can you provide me with a path relative to the root (I mean, relative to where the main `index.php` file of `drupal` is)?

The path to the configuration folder is set in `settings.php` file. It will look like `$configuration_directories = "path/to/config/folder"`. This is relative to the `Drupal` root directory.

> can we change the import path?

Yes, you can change the path in the `settings.php` file.

> can we tell `drush` to just delete any (previously exported) setting files ?

Anytime you export configuration, all the old configuration files will be wiped out, and new ones created from the current active configuration in the database.
> 7 votes

---
Tags: drush, configuration
---


title: Installation on OpenSuse Leap

text:
# Question
Title: Installation on OpenSuse Leap
I get following two warnings:

> Due to the settings for ServerTokens in httpd.conf, it is impossible to accurately determine the version of Apache running on this server. The reported value is Apache, to run Drupal without mod\_rewrite, a minimum version of 2.2.16 is needed.

> PHP OPcode caching can improve your site's performance considerably. It is highly recommended to have OPcache installed on your server.

It would be nice if someone could help me with some pointers about how to solve this problem.

# Answer
> 2 votes
The first error message is saying that, basing on headers returned from Apache, Drupal is not able to determine which Apache version the server is using. If you have access to the httpd.conf file, you can set ServerTokens to at least `ServerTokens Min`, so Drupal will be able to check which Apache version the server is using.
If you know your server is using at least Apache 2.2.16, you can go forward and proceed with the installation. What you are getting is just a warning for you to check the Apache version, since Drupal cannot find out that.

The other message is telling you that it should preferable to install the OPcache extensions, which means you need to have access to the php.ini file, and being able to install extensions on your server.
If you aren't able to do that, don't do anything. That is not an error message, but a warning message telling you it is preferable to have OPcache enabled to make Drupal faster, but Drupal 8 works also without it.

# Answer
> 0 votes
For me editing /etc/apache2/sysconfig.d/global.conf didn't work because global.conf gets overwritten when Apache2 is re-started, and apache needs to be re-started for the change to take effect. To overcome this I found I needed to edit the file '/etc/sysconfig/apache2' the line 247;

> APACHE\_SERVERTOKENS="ProductOnly"

becomes

> APACHE\_SERVERTOKENS="Min"

Then re-start your apache server and /etc/apache2/sysconfig.d/global.conf should be overwritten as required. Hope this helps.

---
Tags: 8, installation
---


# Question
Title: Inserting the value from Datetime field form
I have a form where the user can input datetime and then I want to store it in the database. Here's my schema :

> 'start' =\> array( 'type' =\> 'varchar', 'mysql\_type' =\> 'datetime', 'not null' =\> FALSE, ),

The form :

> $form\['add'\]\['start'\] = array( '#type' =\> 'datetime', '#default\_value' =\> $date, );

When I hit submit button, it shows me :

> db\_insert failed. Message = SQLSTATE\[22007\]: Invalid datetime format: 1292 Incorrect datetime value:...

What I got out of it was that the DateTime in Drupal is incompatible with MySQL's. Any suggestions or how should I process the value from the form so I can insert it into the db?

Alternatively, any way to convert DrupalDatetime into string?

(For what it's worth I also tried 'timestamp' as the MySQL type but it throws me the same error).

# Answer
> 16 votes
Datetime fields in Drupal 8 are stored as strings, partially because date support between databases isn't consistent and partially to make them easy to manipulate to extract parts where there aren't proper date functions.

The date is stored with the format DATETIME\_DATETIME\_STORAGE\_FORMAT, and the timezone is implicitly DATETIME\_STORAGE\_TIMEZONE.

You would need to do something like:

**Before Drupal 8.5**

```
/** @var \Drupal\Core\Datetime\DrupalDateTime $date */
$date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
$string = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);

```

**In Drupal 8.5 and after, as per https://www.drupal.org/node/2912980**

```
/** @var \Drupal\Core\Datetime\DrupalDateTime $date */
$date->setTimezone(new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE));
$string = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);

```

There are better ways to handle this, though. It is best to use the date formatter service to format the dates, rather than the `::format()` method (I'm being lazy here). It is also probably best to use proper entities and add this as a field, and not just stuff it into a database table.

# Answer
> 2 votes
> any way to convert DrupalDatetime into string?

Yes, use the `format` method, e.g.

```
$formatted_date = $date->format('Y-m-d H:i:s');

```

# Answer
> 1 votes
I am not really sure what you are trying to do and on what API level you work. But if you try to store a **timestamp** in a sql **datetime** field you should use `date('c')` to handover the ISO 8601 date as string to mysql.

Regards,

Rainer

# Answer
> 0 votes
The complete answer above did not work for me, be gave me the clue to look for the storage formats.

My date was a **DATE** format (and note **DATETIME** as in the given example), so just use the right constant.

```
constant DATETIME_STORAGE_FORMAT :: string(12) "Y-m-d\TH:i:s"
constant DATE_STORAGE_FORMAT :: string(5) "Y-m-d"

```

Working example.

```
$dtime = DateTime::createFromFormat("m/d/Y - G:i", $row->Date); // not needed
$dtime->setTimezone(new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE));
$dtimeFormat = $dtime->format(DateTimeItemInterface::DATE_STORAGE_FORMAT);

$article->set('field_date', $dtimeFormat);

```

---
Tags: 8, database, datetime
---


title: Why cannot I get the path of a video?

text:
# Question
Title: Why cannot I get the path of a video?
I can't manage to get the video link of a media, I can achieve this with a picture but with videos it doesn't work.

This is the code I am using.

```
function slider_get_uri_by_media($media, $style = 'background'){
  // kint(isset($media->file_media_video_file));
  if (isset($media->field_media_image)){
    $file = $media->field_media_image->entity;
    if ($file && $fid = $file->id()) {
      $image = File::load($fid);
      if ($image_style = ImageStyle::load($style)) {
        return ['url' => file_url_transform_relative($image_style->buildUrl($image->getFileUri()))];
      }
    }
  }
  elseif (isset($media->file_media_video_file)) {
    $file = $media->file_media_video_file->entity;
    if ($file && $fid = $file->id()) {
      $video = File::load($fid);
    }
  }
}

```

Why cannot I get the path for the video stored in `$media->field_media_video_file`?

# Answer
I think that you have a typo in the field name, you should replace `$media->file_media_video_file` with `$media->field_media_video_file` (2 times)
> 1 votes

---
Tags: 8, media
---


# Question
Title: Changing a Profile type Machine Name broke the Admin/People search
I'm working on a Drupal 7 website in which there are several Profile types. As part of a task, I had to change the "Label Name" and the "Machine Name" of one of them: specifically Professional Courses was changed in Professional School.

Later on, I've realised that this substitution have broken the search in the Admin/People page. Precisely, if the Administrator, from the Admin/People page, searches the users with the Profile type just mentioned, the search shows no results.
I've discovered that the View managing this page (Admin/People), has kept the old Machine Name in the query, which means that role has been cut out.

I’ve tried to fix this error by changing the query using the following code inside a `views_pre_execute` function in a custom module I've developed:

```
$query = db_select('users', NULL);
$query->condition('users.uid', array('0'), 'NOT IN');
$query->fields('users', array('uid', 'name', 'mail', 'status', 'created', 'access'));
$query->addJoin('INNER', 'profile', NULL, 'users.uid = profile.uid AND (profile.type IN ( \'master_school\', \'employee\', \'summer_school\', \'professional_courses\', \'digital_friend\', \'phd_school\', \'professional_school\' ))');
$query->orderBy('users.access', 'DESC');
$query->range(0, 100);

$view->build_info['query'] = $query;

```

However, this code changes the query inside the View, but didn’t fix the problem.
How can I fix this bug? Should I go back to the old Machine Name?
Thanks!

P.S. I'm using Profile2 and Administration Views modules.

# Answer
I think this is a bug in Profile2 module.
I recreated your issue on a test installation and the same results happened. After I inspected the database itself I found that the machine name was not changed in the table `profile` but correctly changed in `profile_type` table.
What you could try is to manually change the machine name in the `profile` table and see what happens then.
Also, it might be helpful to post your issue in Profile2 issue tracker, maybe they can fix this for other users.

Good luck.
> 0 votes

---
Tags: views, users
---


# Question
Title: How to rewrite the field of a view with Twig
I created a view with the machine name `cgv_product`.

This view contains the fields "Product Name" and "Custom Text".

In the "Custom Text" field, the `{{ name }}` Twig code is available to display the product number.

I created a template with the name `views-view-fields--cgv_produit.html.twig` it works but if I put the Twig code `{{ name }}` in it it's not rendered.

How to display the product name in my template via Twig?

```
views-view-fields--cgv_product.html.twig

```

I tested the following codes in Twig and it does not work :

```
    <div class="flex-grow-1 bd-highlight"><i class="fas fa-signature fa-lg"></i>
      {{ fields.name.content }}
      {{ fields.field_name.content }}
      {{ row.content.name }}
      {{ name }}
    </div>

```

# Answer
> 0 votes
In the "Custom Text" field, `{{ name }}` is only available to render the "Product Name" field inside the "Custom Text" field (in the view UI), not in a twig template.

You should try to access your fields in the twig template like this `{{ row.content.name }}` (check the available fields using devel/kint).

---
Tags: views, 8, theming
---


title: main menu disappears only on home page

text:
# Question
Title: main menu disappears only on home page
I have a site online engcorrect.net and for some reason my menu on my homepage disappears. On all other pages, it shows. The weird thing is that on my localhost (local machine) it shows correctly but not on the production site and it also shows if I use private browsing. What am I missing here? I am using Drupal 7 and bootstrap 3 theme with a subtheme called paper.

There is a css line that I cannot allocate:

```
body.front ul.menu { display:none;}

```

The inspector shows that it originates from engcorrect.net:1 where is that and who set it?

resizing doesn't fix the issue either. Who can help me with this?

# Answer
Ok. It's resolved. I cleared the browsers cache in Safari under: Preferences/Privacy/Manage Website Data and there I searched for my site name, selected it and hit "remove all". Therefore I presume it was my Safari browser's cache.
> 0 votes

---
Tags: 7, theming, navigation
---


# Question
Title: Show terms in view filtered from another view
I have two views, first one is block, second one is page. I have vocabulary, let's call it "food". In the food vocabulary we have that hierarchy:

* Fruit
    + Apple
    + Banana
* Meat
    + Chicken
    + Pork

Both views goal is to show taxonomy terms, but first one shows ONLY parent terms, then we click on parent Fruit, we get second view, which shows ONLY terms from Fruit, so Apple and Banana. If we clicked on Meat term, we get terms Chicken and Pork. My question is how to do it?

# Answer
> 0 votes
You don't need two Views Display for that, you can do that one with one Page Display.

1. Create Views of type Taxonomy term and add Page Display
2. Add Filter for Food Vocabulary
3. Add the Parent Relationship. It is called `Taxonomy term` but look at the Description `The parent term of the term. This can produce ...`.

If you Require it the results will only show terms that have Parent items, so you'll probably want that.
4. Add Contextual filter `Name` from the Taxonomy term Category and configure it:
**Relationship**: `Parent`
`When the filter value is NOT available`
**Display a summary**
`Format` **List**
`Base path` (you *must* enter the Page path if this isn't the first Page Display in your Views)
**Display record count with link**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term name**
\[Food\]
**Transform dashes in URL to spaces in term name filter values**
`More`
**Transform spaces to dashes in URL**

You will see a list of your parent items in the results (as a Summary), then when you click on one you will see Views results terms that are its children.

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


# Question
Title: Test class could not be found, namespace/autodiscovery issue?
I've got the following tests written for `/core/modules/migrate_drupal_ui/src/Controller/MigrateController.php` with a new test file `/core/modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest.php`.

```
<?php

namespace Drupal\Tests\migrate_drupal_ui\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Provides a base class for testing the Migrate Controller.
 */
abstract class MigrateControllerTest extends BrowserTestBase {
  /**
   * {@inheritdoc}
   */
  public static $modules = ['migrate_drupal_ui', 'views'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $account = $this->drupalCreateUser(['administer views']);
    $this->drupalLogin($account);
  }

  public function testRedirectDestination() {
    $this->drupalGet('admin/reports/upgrade');
    $this->assertUrl('admin/reports/dblog?type%5B%5D=migrate_drupal_ui');
  }

  public function testRedirectDestinationWithoutView() {
    // Delete the watchdog view
    $this->drupalGet('admin/structure/views/view/watchdog/delete');
    $this->assertResponse(200);

    $this->submitForm([], 'Delete');
    $this->assertResponse(200);

    $this->testRedirectDestination();
  }
}

```

Following https://www.drupal.org/docs/8/phpunit/phpunit-browser-test-tutorial, an existing test runs as expected with `../vendor/bin/phpunit --filter testMigrateUpgradeReviewPage modules/migrate_drupal_ui/tests/src/Functional/MigrateUpgradeFormStepsTest.php`.

However, when I do the same for my above test -- `../vendor/bin/phpunit --filter testRedirectDestination modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest.php` -- I get

```
PHP Fatal error:  Uncaught PHPUnit\Runner\Exception: Class 'modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest' could not be found in '/Users/MrWeiner/Sites/DockerSites/testing/web/core/modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest.php'. in /Users/MrWeiner/Sites/DockerSites/testing/web/vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php:102

```

It looks like a namespace issue but I do not understand why it'd be looking for `Class 'modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest'` instead of `Class 'Drupal\Tests\migrate_drupal_ui\Functional\MigrateControllerTest'`. Do I need to register my test somewhere or do something else to ensure that it's autodiscovered?

**Original Question:** We've got https://www.drupal.org/files/issues/2019-04-12/adding-custom-access-2904546-24.patch posted in https://www.drupal.org/project/drupal/issues/2904546 with the request "for a functional test with and without that view enabled". The patch itself is very simple so I'd assume that the test would be very simple as well. I just don't have any experience writing tests so I don't really understand what I'd be testing for/asserting here or how to test for both the view existing and not existing.

# Answer
> 0 votes
It turns out that the issue was that `MigrateControllerTest` was defined as an abstract class. Defining it as a regular class cleared this up.

---
Tags: testing
---


# Question
Title: Drush command to run cron won't work in Crontab
I am attempting to run two Drush commands from my crontab:

```
# m h  dom mon dow   command
*/2 * * * * drush -r /path -l https://www.domain.com/ cron
*/2 * * * * drush -r /path -l https://www.domain.com/ -u civicron civicrm-api job.execute

```

Both of these commands work when I run them manually on the server, however they do not appear to work through crontab, even though the log shows them running:

```
Apr 17 20:16:01 ip-000000000000 CRON[3736]: (ubuntu) CMD (drush -r /path -l https://www.domain.com/ -u civicron civicrm-api job.execute)
Apr 17 20:16:01 ip-000000000000 CRON[3737]: (ubuntu) CMD (drush -r /path -l https://www.domain.com/ cron)

```

Any suggestion as I cannot see why these would not be running?

# Answer
I ran into a similar issue multiple times. I think in all cases cron was running a different version of php. To fix I ended up having to define my php path in my drush call:

```
*/5 * * * * /usr/local/bin/php /home/myuser/bin/drush elysia-cron run --root=/home/mysite/public_html --uri=www.mysite.com

```

Also, another thing that helped me debug the issue is by adding a log path `> path/to/file.log` like this and then looking at the exact error:

```
*/5 * * * * /usr/local/bin/php /home/myuser/bin/drush elysia-cron run --root=/home/mysite/public_html --uri=www.mysite.com > /home/mysite/cron.log 2>&1

```
> 4 votes

---
Tags: 7, drush, cron, civicrm
---


# Question
Title: How do I properly detect if region is empty?
I have condition for printing regions in my page template as *is not empty*, but it will always print empty regions no matter what. What is the proper way to detect empty regions?

For example, `{% if page.local_tasks is not empty %}{{ page.local_tasks }}{% endif %}` prints out `<div class="region region-local-tasks"></div>`.

If I render the region in `themename_preprocess_page()` with `var_dump(drupal_render($variables['page']['highlighted']));` I will get SafeString with placeholder token:

```
<div class="region region-highlighted"><drupal-render-placeholder callback="Drupal\Core\Render\Element\StatusMessages::renderMessages" arguments="0" token="a8c34b5e"></drupal-render-placeholder></div>

```

So, *technically* the region is not empty but I can do nothing about it.

# Answer
try to apply filters after render, like this :

```
{% set has_sidebar_first = page.sidebar_first|render|striptags|trim is not empty %}
{% if has_sidebar_first %}
    {# ... #}
{% endif %}

```
> 14 votes

# Answer
TL;DR for this is that there is no way to reliably check if region is empty or not in the template.

In Drupal 8 at the point when we are at the template level we are unable to tell whether the region has content or not because the content is rendered lazily. There is open Drupal 8 issue for this.

What you probably will have to do to achieve this is to write CSS that tests whether the region is empty. You can try using using :empty pseudo-selector.
> 12 votes

# Answer
This worked for me.

```
{% if page.sidebar_first|render|striptags %}
<aside id="sidebar-first" class="sidebar sidebar-first layout-sidebar-first" role="complementary">{{ page.sidebar_first }}</aside>
{% endif %}

```

Simple enough.
> 4 votes

# Answer
In twig you should really be able to do:

```
{% if page.local_tasks %}{{ page.local_tasks }}{% endif %}

```

However perhaps there is something within page.local\_tasks (like empty markup). Please try the following:

```
{% if page.local_tasks|striptags|trim %}{{ page.local_tasks }}{% endif %}

```
> 3 votes

# Answer
try this :

```
 {% if page.local_tasks|render|striptags|trim  is not empty %}
    {{ page.local_tasks }}
 {% endif %}

```
> 1 votes

# Answer
This actually works in my case

```
{% if page.sidebar_second|render|striptags('<drupal-render-placeholder>')|trim|length > 0 %}

```

striptags accepts a string of tags to keep, so you can also add whatever *contentless* tags you expect to have, like `<form><img>` etc.
> 1 votes

# Answer
You should use `Renderer` service instead of ~~`drupal_render()`~~ which is deprecated, so:

```
$output = \Drupal::service('renderer')->renderRoot($some_array)

```

This will avoid generating `drupal-render-placeholder` tag in the output.

Similar issue: How to replace drupal-render-placeholder manually?
> 0 votes

# Answer
The following does also work when twig debugging is enabled:

```
{% set sidebarLength = page.sidebar_first|render|trim|striptags|length %}
{% if sidebarLength > 1 %}
  {% set has_sidebar_first = page.sidebar_first %}
{% else %}
  {% set has_sidebar_first = null %}
{% endif %}

```
> 0 votes

# Answer
To detect if region is empty or not code like this:

```
{% if page.local_tasks %}
   {{ page.local_tasks }}
{% endif %}

```

In above code it checks if local\_tasks region is empty or not and if empty then it will not print that region
> -2 votes

---
Tags: 8, theming
---


# Question
Title: How to make a theme hook suggestion for menu according to region?
I'm placing the **same menu block in two different regions** whereas different html markup for the list is needed. So analog to my previous question "How to make a theme hook suggestion for blocks according to region?" I need to know, **how to get the current region** inside the function MYMODULE\_theme\_suggestions\_menu\_alter, to add my own suggestion.

# Answer
> 2 votes
Joery Lemmens posted an answer to a similar question on Drupal's forums:

```
use Drupal\block\Entity\Block;

/**
 * Implements hook_preprocess_HOOK().
 *
 * Pass block region value to content so this can be used in
 * MYTHEME_theme_suggestions_menu_alter.
 */
function MYTHEME_preprocess_block(&$variables) {
  if (isset($variables['elements']['#id'])) {
    $region = Block::load($variables['elements']['#id'])->getRegion();
    $variables['content']['#attributes']['region'] = $region;
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * Provide region based menu suggestions.
 */
function MYTHEME_theme_suggestions_menu_alter(&$suggestions, array $variables) {
  if (isset($variables['attributes']['region'])) {
    $suggestions[] = 'menu__' . $variables['menu_name'] . '__' . $variables['attributes']['region'];
  }
}

```

All credit to Joery for this elegant solution.

# Answer
> 0 votes
This is a bit of a hacky solution, but it worked for me. Only difference is that I needed to do it to search forms, but it should be equally applicable to your situation.

```
use Drupal\block\Entity\Block;

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MODULE_theme_suggestions_form_alter(array &$suggestions, array $variables) {

  if($variables['element']['#form_id'] === 'search_block_form') {

    if(isset($variables['element']['#id']) && !empty($variables['element']['#id'])) {

      if($variables['element']['#id'] === 'search-block-form') {
        $block = Block::load('searchform');
      }
      else if($variables['element']['#id'] === 'search-block-form--2') {
        $block = Block::load('searchform_2');
      }

      if(isset($block) && !empty($block)) {
        $suggestions[] = 'form__' . $block->getRegion();
        $suggestions[] = 'form__' . $block->getRegion() . '_searchform';
      }
    }
  }

  return $suggestions;
}

```

---

**Explanation of code:** *Remember to change the function name to use the correct hook!*

```
if($variables['element']['#form_id'] === 'search_block_form') {
  ...
}

```

I do this, so that my suggestions only affect the search block form, you should change this to a check for the right menu, so your suggestions only affect the menu you need it for.

```
if(isset($variables['element']['#id']) && !empty($variables['element']['#id'])) {
  ...
}

```

This is just to prevent errors in case I hit a form that doesn't have an id.

```
if($variables['element']['#id'] === 'search-block-form') {
  $block = Block::load('searchform');
}
else if($variables['element']['#id'] === 'search-block-form--2') {
  $block = Block::load('searchform_2');
}

```

This is what I consider the "hacky" bit, basically I check for the id's of the forms (in this case search-block-form and search-block-form--2), and then proceed to load the appropriate block (the block id's used for loading the blocks, are just the machine names give to the blocks).

```
if(isset($block) && !empty($block)) {
  $suggestions[] = 'form__' . $block->getRegion();
  $suggestions[] = 'form__' . $block->getRegion() . '_searchform';
}

```

Here I just add the suggestions, I add 2 suggestions, but you can probably justify only adding one.

---

I really hope this helps, feel free to suggest changes to my code.

---
Tags: 8, theming
---


title: Drush: How do I change the Drupal root

text:
# Question
Title: Drush: How do I change the Drupal root
My Drush commands doesn't work because my Drupal files are in another directory than the one set in Drush. Everything is set up to this path so I can't just change the folder name.

```
Drush status
  [..]
  Drupal root   : /Users/nicklas/Documents/SourceTree/Drupal/web

```

How can I change the path to `/docroot` instead of `/web`?

> /Users/nicklas/Documents/SourceTree/Drupal/docroot

# Answer
You can pass it in via the `--root` argument

`drush status --root=/Users/nicklas/Documents/SourceTree/Drupal/docroot`
> 2 votes

---
Tags: 8, drush
---


# Question
Title: Send email to all users that are tagged with the same tag a node is when created
There is a lot of similar questions here but I am having a hard time wrapping my head around this.

I have a taxonomy term reference field called field\_category. This field is available on user/\*/edit and on node/add.

Category

* 1
* 2
* 3

What I would like to do is send an email when a node is created that has the same taxonomy term(s) that a user has specified in their profile.

I have tried to wrap my head around using the rules and view\_rules module but every configuration I have tried fails.

Can anyone provide me with some direction? Thanks!

Drupal 7.65

Rules: 7.x-2.12

Views Rules 7.x-1.0

Edit

Using pinueve answer, here is where I am at. The actions/conditions section of his answer is still unclear to me. My holdup is trying to match his example in the actions section.

```
{ "rules_area_of_expertise" : {
    "LABEL" : "area of expertise",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "mail" ],
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_insert--answers_question" : { "bundle" : "answers_question" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_category" } }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_category" } },
            "DO" : []
          }
        ]
      }
    ]
  }
}

```

# Answer
install: views-rules-module, and rules-conditional module. Add in views a rules-view (is a new display type added by rules-view-module) of type USERS, add your category-field, hide from display, add relationship to taxonomy-vocabulary, add field: term-ID and UID. Both fields in views middle column set your fields as type: INTEGER. If you want you can delete user-field\_category from this view. If needed, filter users by role or whatever to shorthen your view results, and important: no-pager, display all rows.

Now in rules: react-on: new content of type: your-content-type, conditions: entity-has-field: node-created-content: your field\_category, actions: fetch-entity-by-id: taxnomony-term: value: drill in node until you find node-term-ID.

Add your new view-rule (find link at bottom settings in actions), now you have term-ID from user & UID, inside view-loop and a conditional, add an if, data-comparision, your NODE-term-ID vs USER-term-id, if equal, fecth USER by ID, with your variable UID, and send email. Done. Note: is possible that you will need to transform your NODE-term-ID as an integer.

Your rule will look like something like this:

EDIT: first install rules Version: 7.x-2.11, i can see that you do not see 'conditional label' in rules action. To avoid to update rules module, install disable-updates-module

FIRST action should be 'fetch entity bt ID: tanonomy term', select your new node, and drill until you find term-ID.

SECOND action: add your users-views-rule. all following actionts take place inside rules-view-loop.

THRID action: inside rules view, data compare: your variable term-id from rules-view-users with NODE-term-ID (first action), if values match (are equal) then fetch USER by ID with your variable value UID from rules-view, now you have user object avilable, do send email to that user, rules-view will compare next user, and so on. here is another img of how will look your rule, notice how actions are taking place inside rules-view-loop.

and here is an img where you can find how to add your rules-view, it says "Add a view loop" at the bootom of img.

And this is how you set your fields inside rules-view, this is located in middle colum of your view.
> 0 votes

# Answer
I also wanted something similar. What I did was that I captured the node creation event using node\_submit() hook and then triggered the mail based on the node value when it satisfied my required conditions. Maybe you can try something like that.
> 0 votes

---
Tags: 7, rules, emails
---


# Question
Title: How can I get form values in hook_user_update?
```
function custom_user_update($account) {
  $user = \Drupal\user\Entity\User::load($account->id());
  $level = user->get('field_account_participation')->entity->tid->value;
}

```

Now I need to check my `$level` equals the post value of `field_account_participation`. How we can do this in Drupal8?

# Answer
As stated in the documentation of hook\_entity\_update() one could use $entity-\>original:

> Get the original entity object from $entity-\>original.

So you could use this object to find out if your field value has changed by writing something like this:

```
function custom_user_update($account) {
  $user = \Drupal\user\Entity\User::load($account->id());
  $original_value = $account->original->get('field_account_participation')->entity->tid->value;
  $updated_value = $user->get('field_account_participation')->entity->tid->value;

  if ($original_value != $updated_value) {
    // Do something here...
  }
}

```
> 4 votes

---
Tags: 8, users
---


title: Inserting a view in node edit form

text:
# Question
Title: Inserting a view in node edit form
In a node edit form i want to display an editable view, so an author can not only edit the node itself but also can alter some values of other nodes represented by the view, which is editable via the editable views module. How can i alter the node edit form in order to display that view?

# Answer
> 4 votes
It took me a while to find out how to do it in Drupal 8, and since this post is one of the first google hits I'll add the solution here:

```
function MODULE_form_node_NODETYPE_alter(&$form, FormStateInterface $form_state, $form_id) {
    ...
    $form['my_embedded_view'] = [
        '#type' => 'view',
        '#name' => 'my_view_name',
        '#display_id' => 'block_1',
        '#arguments' => [
            'arg1' => $arg_1,
            'arg2' => $arg_2,
        ],
        '#weight' => 30,
    ] ;
...
}

```

I used a block display for the view, I don't know if it's relevant.

# Answer
> 3 votes
The EmbeddedViewField module is able to render a view, regardless of whether the user is editing or displaying the entity (node) that has the EmbeddedViewField. Here is a quote about that module (from its project page):

> ... will allow you to render a view as any other field.
>
> It is based on keithm's ViewField module, except that it will always render the view, regardless of whether the user is editing or displaying the entity that has the EmbeddedViewField. The view used for displaying is controlled by the default value set for the view.
>
> This is useful in situations where you don't want end users to control the content being displayed by the view, but you still want a flexible way to insert content (views with text, images, media etc.) along with the rest of the fields in the form.
>
> Context, Panels and Blocks could be used to place views and edit forms in the same page, but not to embed views between specific fields.

# Answer
> 1 votes
There are a few ways you can do this - if you are using Drupal 7 - take a look at this module: https://drupal.org/project/token\_embed\_views Another less desireable way would be to use your PHP filter and the views\_embed\_view function https://api.drupal.org/api/views/views.module/function/views\_embed\_view/7

If you are looking to actually load this view in the edit side, you could possibly do a "hook\_form\_alter" to allow you to put your own content in the form...

# Answer
> 1 votes
I solved the problem showing the view in the node edit form only by writing a tiny module containing this code:

```
<?php

/*
 * Implementation of hook_form_alter()
 */

function mymodulname_form_alter(&$form, &$form_state, $form_id){
     // target a single form only
  if($form_id == "mynodeform_node_form"){
      $form['html_markup'] = array(
        '#markup' =>views_embed_view('machinenameofmyview','default'),
        '#weight' => 1
        );
  }
}

```

---
Tags: views, forms
---


title: Adding a view to node edit form

text:
# Question
Title: Adding a view to node edit form
How to attach programmatically a view to the edit node form in Drupal 8?

In D7 I could achieve this by using this code

```
/**
 * Implements of hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id){

  // target a single form only
  if ($form_id == "form_id") {

    $form['html_markup'] = [
      '#markup' => views_embed_view('name_of_view','default'),
      '#weight' => 1
    ];
  }
}

```

I'm looking for a way how can it implemented in D8.

Any tips will be appreciated!

# Answer
> 1 votes
I researched this for a while, then I found a sample implementation in `modules/views/tests/modules/views_test_data/src/Form/ViewsTestDataElementEmbedForm.php`:

```
$form['view'] = [
  '#type' => 'view',
  '#name' => 'test_view_embed',
  '#display_id' => 'embed_1',
  '#arguments' => [25],
  '#embed' => TRUE,
];

```

In that file it is used in `FormBase::buildForm`, but it works nicely also in `hook_form_FORM_ID_alter()`; I reported another example in this comment to a similar post.

# Answer
> 0 votes
In drupal 8 you can embed a view in two simple steps ,first get your desired view using `$myView = Views::getView('VIEW_NAME');` and then make a rendered output using `$rendered_view = $myView->buildRenderable('block_1',array($your_arguments));`, then you can attach it to your node edit form.

---
Tags: views, 8, forms
---


# Question
Title: How do I add an extra "Add content"-link to the admin toolbar dropdown
I am trying to add some improvement to the workflow of the webmasters. Right now they have to click "Content", and then click once more on the "Add content" button. Since I am working with the "Admin toolbar" module, I want to add a "/node/add" link below the "Content" link in a dropdown. But no success yet.

# Answer
This is fairly simple. First, create a **your\_module.links.menu.yml** file in your custom module and add the following:

```
your_module.admin:
  title: 'Add content'
  parent: system.admin_content
  url: internal:/node/add

```

Clear cache and you're done!
> 3 votes

---
Tags: 8, navigation
---


# Question
Title: Convert address to multi value during migration
I have a migration that imports data into my address field and it works perfect.

```
  field_address/locality:
    -
      plugin: get
      source: city
  field_address/postal_code:
    -
      plugin: get
      source: postalcode

```

The problem I am running into is that some data from my source has multiple values in the city so I need to add some logic that if it has multiple cities, create 2 address field values (multi-value).

I was thinking to make a destination plugin. As a proof of concept I tried to edit `Drupal\migrate\Plugin\migrate\destination\Entity::getEntity()` with the below options but none of them worked:

```
$row->setDestinationProperty("field_address/locality", ['Chicago', 'Oakbrook']);

```

```
$row->setSourceProperty("field_address/locality", [0 => ['value' => 'Chicago'], 1 => ['value' => 'Oakbrook'], []]);

```

```
$row->setDestinationProperty("field_address/0/locality", 'Chicago');
$row->setDestinationProperty("field_address/1/locality", 'Oakbrook');

```

# Answer
I was able to accomplish this by creating a custom process plugin for the address field.

```
  field_address:
    -
      plugin: myaddress
      source:
        locality: city
        administrative_area: state
        postal_code: postalcode

```

```
<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * Maps values for address.
 *
 * @MigrateProcessPlugin(
 *   id = "myaddress"
 * )
 */
class MyAddress extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $parsed = [];
    // If city name has `and` or `or` it will create multiple address items.
    $cities = preg_split("/ (or|and) /", $value[0]);
    foreach ($cities as $city) {
      $data['country_code'] = 'US';
      $data['locality'] = $city;
      $data['administrative_area'] = $value[1];
      $data['postal_code'] = $value[2];
      $parsed[] = $data;
    }

    return $parsed;
  }

}

```

My plugin checks to see if there is a string `and` or `or` and if there is it converts it multiple values. Of course, this works out for me because all are US and the cities are for the same state.
> 1 votes

---
Tags: migrations
---


# Question
Title: How to store your own key-value pairs in Redis using PhpRedis with D7 Redis module
We have the D7 Redis module installed, which is being used as the cache mechanism for D7 caching. That module uses PhpRedis as the underlying library.

I would like to use that same Redis instance to cache a large amount of non-Drupal data that is retrieved from an external API, then will be rendered on a specific Drupal page. I'm wondering how I can get ahold of the Redis object instance that Drupal is already using, so I can use PhpRedis functions like $redis-\>set(key,value)?

# Answer
> 1 votes
Once configured/initialized, the module has a wrapper class/interface `Redis_Client` that contains the library object. It can be retrieved with the `getClient()` method:

`$redis = Redis_Client::getClient()`

---
Tags: caching
---


# Question
Title: Rendered markup different than template markup
I am using drupal 7, and the bootstrap base theme to make a simple theme for a website I am working on. I am having issues with Drupal forcefully changing my html5 hierarchy and it's causing the site to break.

Is there anyone that would know what would cause the issue?

I have attached the code snippet in particular that is causing issues, as well as a screenshot from Chrome's inspector showing the misplacement. I have confirmed it's doing it on at least 4 browsers, so I do believe it's a drupal issue.

```
<section>
  <a id="main-content"></a>
  <div class="container">
    <section class="<?php print $column_width; ?>">
      <?php if (!empty($tabs)): ?>
        <?php print render($tabs); ?>
      <?php endif; ?>
      <?php if (!empty($page['help'])): ?>
        <?php print render($page['help']); ?>
      <?php endif; ?>
      <?php if (!empty($action_links)): ?>
        <ul class="action-links"><?php print render($action_links); ?></ul>
      <?php endif; ?>
      <?php print render($page['content']); ?>
    </section>

    <aside class="col-sm-4 col-lg-4" role="complementary">
      <?php print render($page['sidebar_second']); ?>
    </aside>  <!-- /#sidebar-second -->
  </div>
</section>

```

As you can see from the image, the `<aside>` is being placed outside of the root `<section>` instead of inside of it (and underneath the other `<section>`), like the template is telling it to do.

EDIT: The 5 console errors are from image files not being found because I haven't uploaded them yet.

# Answer
> 0 votes
The comments in this question were helpful, but I can't credit both people so I will post the answer.

My default views-view-unformatted.tpl.php had an extra closing tag inside of it somehow. Not sure how since it's a default views display. Removing the tag fixed the issue.

---
Tags: 7, theming, bootstrap-theme
---


# Question
Title: Is there a generic method to retrieve entity IDs?
I have seen this code suggesting how to return a list of entity IDs:

```
$query = \Drupal::entityQuery('node');
$query->condition('type', $bundle);
$entity_ids = $query->execute();

```

but this requires the knowledge of when to use "type" or what "type" is. For example, for user entity i would think setting type to $bundle = 'user' would work - but it gives error.

for terms from a vocab i would expect type to be set to the name of the vocab; but that also gives an error.

Is there a generic method to call for entity\_type that would hint at what is required to do a query for entity ids?

# Answer
> 1 votes
You're looking for the bundle key, which can be obtained from the entity type:

```
$entity_type = 'node';

// Load the entity type definition and get its keys.
$keys = \Drupal::entityTypeManager()
  ->getDefinition($entity_type)
  ->getKeys();

$query = \Drupal::entityQuery($entity_type);

// 'bundle' is optional, if not provided it will be the same as the entity type ID,
// but obviously you won't need to use it as a condition.
if (mb_strlen($keys['bundle'])) {
  $query->condition($keys['bundle'], $bundle);
}

$entity_ids = $query->execute();

```

See `EntityType::getKeys()` for more information.

---
Tags: 8, entities
---


# Question
Title: Webform Issue with Drop Down and Key not Equaling Value
I have written a custom handler in Drupal 8 D8 that grabs submitted data from a webform and reformats it and sends it to a JSON webservice. That is all working perfectly. My issue is that the submitted data from 2 of the dropdowns is an integer (the key of the dropdown), rather than the value of the drop down, like it was when in D7 I called:

```
$components = $node->webform['components'];

```

which gave me the value of the data from the dropdowns. Now I am calling:

```
$values = $webform_submission->getData();

```

Which gives me the submission data. However, what I need to do is translate the number to the value. For example:

for a component (or element) drop down called 'numbers' the options are: 1|One 2|Two 3|Three

When I grab the submission data I get "1" but I want to send the word "One".

How do I load the dropdown element to translate the value '1' to the word "One" in Drupal 8?

Thanks.

# Answer
> 0 votes
> When I grab the submission data I get "1"

This is standard in Drupal for select & radio fields, you always get the key.

So all we have to do is use the key to retrieve the value.

```
$key = $webform_submission->getData()['field_select'];

// retrieve webform fields.
$webform_fields = $webform_submission->getWebform()->getElementsDecoded();

// use key to retrieve value of field_select.
$value = $webform_fields['field_select']['#options'][$key];

```

---
Tags: 8, webforms
---


# Question
Title: Programmatically added block doesn't appear in block admin page
First of all, this is not a duplicate of this question, as I can't see my block even though I click Place Block.

Below is my block class. To the best of my knowledge, it should appear in the list, but it doesn't. What am I doing wrong? There is another block class, and that can be discovered.

```
<?php

namespace Drupal\tcmb\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Tcmb Currency' block.
 *
 * @Block(
 *  id = "tcmb_currency_block",
 *  admin_label = @Translation("Tcmb: currency"),
 *  category = @Translation("Tcmb")
 * )
 */

/**
 * Display TCMB currencies as a block.
 */
class TcmbCurrencyBlock extends BlockBase {

```

# Answer
The problem was me creating a document block above the class, creating an interference between the class and annotation. Another lesson learned the hard way.
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: How to prevent Cross Site Scripting when input using "Full HTML" mode of CKEditor
I am using Drupal version 8.3.7 and ckeditor 4.11.3. I create a basic page contains some scripts as following:

In the detail page, I can see that the script in `onmouseover="alert('222222')"` is executed when I move my mouse over the "click" text.

Hacker can easily add a malicious script by this way. How can we avoid this ?

Issue is not only for "Full HTML" mode, but also other modes if we configure a proxy between browser and server to change the encoded value to the raw value.

For example, if we select the "Unfiltered HTML" mode and we input `<a href="#" onmouseover="alert('111111')">click</a>` to the body field. When we save the page, the body value will be sent with a POST request that it is HTML encoded: `<a href="#" onmouseover="alert('111111')">click</a>`. But in the proxy above, we configure to change the encoded value to the raw value. Then the raw value `<a href="#" onmouseover="alert('111111')">click</a>` is saved into DB which will cause the same issue with "Full HTML" mode.

A solution that we can encode the output in theme preprocessing hook. But it seems require us to add a lot of codes because our system may have many entity types and fields.

# Answer
> 3 votes
See the documentation:

> Finally, it should be obvious that the Full HTML input format, which does not use the HTML Filter, is insecure and should be offered only to those users who can be trusted not to ruin your site. Most sites will be better off deleting this input format.

https://www.drupal.org/node/213156

---

"A solution that we can encode the output in theme preprocessing hook. But it seems require us to add a lot of codes because our system may have many entity types and fields."

Don't do this in preprocessing. You can configure your own safe text format containing as many text filters as you want. If the built in text filters don't provide the security you need then add a custom filter.

---

Core ships with Full HTML so that site owners are able to create basic pages in CKEditor using almost all HTML features, which they can do anyway when they have access to the template files.

---
Tags: security
---


# Question
Title: Select the same number of results for every group
I have views where I select nodes and group all results in 3 groups by field. When I select for example a limit to 30 I get results but with the different count in every group (for example 20/7/3). What I can use to select for example 10 most relevant results in every group. I can do it with query alter or maybe need to create some plugin?

# Answer
> 1 votes
Yes, query alter helps. Views flexible pager might serve as an inspiration for the code changes. Do contribute back if you find a solution, it has been requested before.

This problem is usually "solved" by creating different Views displays, as many as you have Groups, and filter each field value in its own display. Then show all 3 displays one after another and use styling to make them seem like they're from the same Views.

---
Tags: views, 8
---


# Question
Title: Programmatically specifying pathauto alias
I am working on a custom module to specify the pathauto alias of a new node, based on taxonomy terms that a user sets when they create the node. For instance, for my `blog post` content type, the alias would be auto-generated as `/blogs/this-is-a-new-blog-post`. However, if the `category` taxonomy is set to be `special-project`, I want to change the alias to be `/special-project/blog/this-is-a-new-blog-post`.

I'm able to load the node using `hook_entity_insert()`. However, I haven't been able to figure out how to set the alias.

I've found examples of how to set the path when creating a new node, but I already have an existing node object in this hook. I've tried debugging the path from the entity using `$entity->toUrl()->getInternalPath()`, but that just gives me the default URL (`/node/123`), not the alias. Trying to debug `$node->path`, I get an enormous `stdClass` object that I can't really suss out. Trying to debug `$node->path->alias` using `drupal_set_message("alias: " . $node->path->alias);`, I get this: `alias:`.

How can I see and alter the path alias on an existing node?

# Answer
As Shawn Conn pointed out, there are pathauto hooks that I can use instead. What I wound up using was `hook_pathauto_alias_alter(&$alias, array &$context)`. The `$context` has the node entity object in `$context['data']['node']`, and `$alias` is the literal alias string. Since it's passed by reference, no need to perform any save function after changing it. Very easy to do what I need to in there.
> 3 votes

# Answer
Pathauto 8.x is already hooking into the `hook_entity_$CRUD_OP()` hooks of D8 to do its work. Thus, trying to do this via a `hook_entity_insert()` means your module hook might fire before/after pathauto has set its alias (depending on module weight).

Instead of doing this, you should use the API functions of pathauto to alter its behavior. For example, `hook_pathauto_pattern_alter()` or `hook_pathauto_alias_alter()` will let you alter the pattern/alias prior to generation/saving.

See `pathauto.api.php` for more info.
> 5 votes

---
Tags: 8, path-aliases
---


# Question
Title: CSV migration always returns "id is defined as a source ID but has no value"
I have a freshly composer installed Drupal 8.6.13. I tried to migrate csv sources and allways got the error message

> \[error\] Migration failed with source plugin exception: id is defined as a source ID but has no value.

I switched to an example that is running in another installation https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins/migrating-data-from-a-csv-source, but still get this error.

My versions: migrate 8.6.13, migrate\_plus 8.x-4.1, migrate\_source\_csv 8.x-2.2, migrate\_tools 8.x-4.1

Does anyone have an idea what causes the error?

This are the files:

CSV:

```
id,title,body
1,title 1,some body text 1
2,title 2,some body text 2
3,title 3,some body text 3

```

Migration configuration:

```
id: article_csv_import
label: Import articles
migration_groups:
  - ACME import
source:
  plugin: csv
  path: 'public://articles.csv'
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
  column_names:
    0:
      id: 'Unique Id'
    1:
      title: 'Title'
    2:
      body: 'Post body'
process:
  title: title
  body: body
  type:
    plugin: default_value
    default_value: article

destination:
  plugin: entity:node

```

# Answer
I already had the same error you've got; in fact it's a mistake : Please double check that the delimiter set in the yml file is the same as in your source file (edit it with notepad++ to be sure). Sometimes Excel change delimiter when reopening csv file before resave it without settings file format.

Also, note the `column_names` key is not mandatory, as the plugin will automagically extract column from your file (see `migrate_source_csv\src\Plugin\migrate\source\CSV.php` line 110 ... 123). Here you can also print the `$column_names` array to check if it contains same number of items as your file columns.

BR
> -1 votes

---
Tags: 8, migrations
---


# Question
Title: How to pass Webform elements from controller to custom twig template
I'm pretty new to Drupal and probably this is simple but I got stuck with this.

What I'm trying to do: I have created a custom module where I have defined a custom route to display my webfrom in custom twig template.

How and what to return from Controller so my webform elements will be available in custom twig template.

my\_module.module

```

/**
 * Implementation of hook_theme
 *
 * Since we have a lot to explain, we're going to use Twig to do it.
 */
function my_module_forms_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'variables' => ['test_var' => NULL],
      'render element' => 'form'
    ],
  ];
}

```

my\_module/src/Controller/MyModuleController.php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyModuleController extends ControllerBase {

public function content() {
    $my_form = \Drupal\webform\Entity\Webform::load('my_form_id');
    $form = \Drupal::entityManager()
      ->getViewBuilder('webform')
      ->view($my_form);

```
$build = [
  '#theme' => 'my_template',
  '#form' => $form,
];
return $build;

```

}
}

In my twig template, I want to be able to use form elements like below. Please let me know how to achive this.

my-template.html.twig

```

{{ form.element.name }}
{{ form.element.email }}

```

Thanks

# Answer
my\_module.module:

```
/**
 * Implementation of hook_theme
 *
 * Since we have a lot to explain, we're going to use Twig to do it.
 */
function my_module_forms_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'template' => 'my-template',
      'variables' => ['form' => NULL],
    ],
  ];
}

```
> 0 votes

---
Tags: webforms
---


# Question
Title: Exporting results with Views Data Export not working as intended
I have a view-based search (drupal 7, newest version of Views) with several exposed filters. By default it shows all results and users have to use the filters to narrow down their search.

I've added 'Views Data Export' module to allow users to download search results via CSV export, if they wish. However it's not working as intended.

I created the export view and attached it to the search view fine. I made sure pager in the export view was set to 'display all items' (otherwise it only shows around 10 results).

I set batched export to yes. I also set each filter to 'remember last selection'.

However, no matter which filters are selected, the data export still shows every record in the database on export.

Anyone know how to fix this? Ideally the export would just show the records displayed on the screen after using the various filters.

# Answer
A possible alternative to consider for the fix you are looking for, is to consider an alternative module that can possibly address all of your requirements, such as the Forena module. Here are a few features of it, which seem to be part of your requirements:

There are many more features that come with Forena, as detailed also in its Community documentation. Refer to the demo site for some sample reports (shipped with the module), or the documentation included with the module (such as the supported document types, of which CSV is just one of them).

Disclosure: I'm a **co**-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.
> 0 votes

# Answer
As @seb alluded to in his comment on the original post, you need to make sure the export display has the same exposed filters as the display you attach it to. If it does, it should automatically inherit the current exposed filter values when the user hits the export button.
> 0 votes

---
Tags: 7, views, importing-exporting
---


# Question
Title: Custom drupal module does not appear on the extend page
I have created a custom module, yet it does not appear on the extend page. I have my\_new\_block.info.yml file in modules/custom/my\_new\_block/:

```
name: My New Block
description: Create own blocks.
package: Garage

type: module
core: 8.x

dependencies:
  - block

```

In addition, when I try to install any drupal module with composer, it also is not recognised in the extend page. What can be wrong?

# Answer
> 0 votes
There was a preceding issue with installation, I had several drupal projects under Projects folder, the newer project tried to access modules in the directory of the older one. Probably, the paths have somehow mixed, leading to the problems with modules installation and database connection(it was not described in a settings.php file). After the disabling of the previous projects and reinstallation of the current one, everything has been working properly.

# Answer
> -1 votes
You can use this example Hello World Module and then change it for your case and do not forget to delete a Drupal cache.

---
Tags: composer
---


title: View filter based in text not in number

text:
# Question
Title: View filter based in text not in number
I have a field in an entity that is an Entity Reference with widget Select list.

I have created a view and I want to be able to filter by that field in text format, but when I try to configure the filter I get the options to do it as if it were a number (is less than, is equal to...) and not as a text (contains, start with...).

Any idea of what I am doing wrong?

Edited: Here is screenshot of the filter:  Thanks!

# Answer
Entity reference fields store the ID of the referenced entity. They don't store anything else about the referenced entity.

You have an Entity reference towards nodes and the data that the ER field stores is the node ID. That is why when you add a filter for that ER field you get the "number" options, because the ID is a number/integer.

But there is a way to add a filter that filters results based on other properties of the referenced entity. When you need extra information you add the Relationship based on the ER field. This introduces all other available info about that entity into your Views.

In your case, you want to add the Relationship for your ER field (`Content referenced from fiscal_certificates`). Require it if you only want results that don't have that field empty.

After you add the Relationship you can add the `Title` filter, but make it use the Relationship for the ER field. Title is a text field so you'll get the text options (Contains...).

If you don't use a Relationship on that filter it will search through Titles of your "original" items, but if you use the ER Relationship it will search through the referenced node titles.
> 2 votes

---
Tags: views
---


title: Add banned words list to the site

text:
# Question
Title: Add banned words list to the site
I want to add a banned words list to the site. and if a user used one of the banned word in node form (title and body), comment form (title and body), user username in the registration form, then the user should get an error message that you are using a banned word in your {field-name}.

And the form should not be submitted if the banned words are present.

How can I do this?

I have checked some modules like wordfilter but it does not provide the functionality for usernames and also it replaces the strings not giving the error message.

# Answer
> 3 votes
Try the Profanity module, here is a quote about it from its project page:

> An alternative to Wordfilter and Phonetic Word Filter, this module provides...
>
> * Filters any Entity!
> * The ability to create multiple word lists.
> * Features exportable.
> * An input format filter for either replacing matched words with a repeated character or phrase.
> * Super quick no regex processing (for simple matching).
> * A function to use for custom form item validation/detection.
> * Tokens for title/label properties per Entity allowing you to specify which lists to process with.
> * A rule condition for "Text contains profanity" so you can do clever things when bad words are detected (add to moderation queue).
> * Ability to filter Entity titles before view/render.
> * A view field for each Entity title, profanity filtered.
> * Validation to prevent users registering with a username containing profanity.
> * Works with Search API by providing a filtered entity title property to be indexed.
> * Integration with Search API Views to provide a field for profanity filtered Excerpt.

Note that it has Rules integration so you can send emails etc.

# Answer
> 1 votes
Try using Rules Module.

```
{ "block_user_on_banned_words" : {
    "LABEL" : "Ban user when used banned words",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : {
      "node_insert--page" : { "bundle" : "page" },
      "node_update--page" : { "bundle" : "page" },
      "comment_insert--comment_node_page" : { "bundle" : "comment_node_page" },
      "comment_update--comment_node_page" : { "bundle" : "comment_node_page" }
    },
    "IF" : [
      { "data_is" : {
          "data" : [ "node:body" ],
          "value" : { "value" : {
              "value" : "your_banned_words0\r\nyour_banned_words1\r\nyour_banned_words2\r\nyour_banned_words3",
              "format" : "filtered_html"
            }
          }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "You are using one or more banned words(your banned words)",
          "type" : "error"
        }
      }
    ]
  }
}

```

Change the words and content type of node and comment

# Answer
> 0 votes
Why not just hook the forms:

* `my_module_form_node_form_alter(&$form, $form_state)`
* `my_module_form_commt_form_alter(&$form, $form_state)`

and add custom validators, like

```
function my_module_form_node_form_alter(&$form, &$form_state, $form_id) {
  // There will already be some validate handlers added so you need to add to the
  // array rather than overwrite it.
  $form['#validate'][] = 'mymodule_node_form_validate';

}

function mymodule_node_form_validate($form, &$form_state) {
  // Random example, if the title is 'test' throw an error
  if ($form_state['values']['title'] == 'test') {
    form_set_error('title', 'Title cannot be "test"');
  }
}

```

Your banned words could be a vocabulary, and you could check every word with *`taxonomy_get_term_by_name($name, $vocabulary = NULL)`*

# Answer
> 0 votes
try the dev version of moduleprofanity

---
Tags: 7
---


# Question
Title: Create one-off page with specific fields and template
I'm new to Drupal and trying to add a single new page to an existing Drupal website. It has its own design (with its own css) and its own content requirements separate from the rest of the site.

I'd like to be able to define a set of custom fields for the page, and then use a specific twig template to render those fields.

Is this possible? I'm struggling to find a way to do this.

I get most of the way there with a custom content type. I can create all the fields I need for the page. But, I don't want it to function as a repeatable content type, but rather as a one-off page that has a specific, single path.

When I try using Page Manager to create a page, I get presented with what looks like a WYSIWYG kind of editor for laying out blocks/panels on the page. I'm hoping to rather simply be able to define a set of fields and use the template to arrange everything on the page.

# Answer
Use the Empty Page module and create an empty page.

Just like node content types, you can create a custom block type in `/admin/structure/block/block-content/types`

Add fields to your block type, and then in `/admin/structure/block/block-content` create a block of your block type.

Place block in content region and for Visibility \> Pages put the URL for your empty page, so the block is only visible at this page.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to pass contextual id value from one view page to another through Drupal menuing system
1. I use a view to display a list of books.
2. The view has three pages: `/books/title`, `/books/date`, and `/books/popularity`.
3. The pages are essentially the same with different sort criteria.
4. The pages use a contextual filter to select books by topic based on a taxonomy.
5. The contextual filter is set to use the query parameter `topic` when the filter value is not in the URL.
6. Each page of the view includes a Drupal menu block with the items "By Title", "By Date", and "By Popularity" and links `/books/title`, `/books/date`, and `/books/popularity`.
7. If I invoke `/books/title?topic=5` (where 5 is the tid for the "health" topic)
    * A list of health books is correctly displayed.
    * The "By Title" `<li>` element in the menu is given the `active` and `active-trail` classes by the menuing system (which allows the use of CSS to highlight the active menu entry on-screen).
8. When I'm at `/books/title?topic=5` and click the "By Date" menu entry, `/books/date` is invoked, so the topic id 5 is not passed to the "By Date" view (unsurprisingly), resulting in a list of all books sorted by date instead of just health books sorted by date.

QUESTION:

How can I pass the contextual filter value (5 in this example) from one page to another via the menu? For example, if at `/books/title?topic=5` I click "By Date", I want to go to `/books/date?topic=5`. How can I set that up?

NOTES

1. This post is similar to an earlier one where I asked how to get the value coming through the contextual filter. I solved that. There is a twig variable available, in this case, {{ arguments.field\_topic\_target\_id }}.
2. I used this twig value to rig up my own menu. But having done that, I find that I need the goodness of the Drupal menuing system, both because it makes it easy for editors to change menu items and because it handles the addition of the `active` and `active_trail` classes to the proper menu entry.
3. I have read and tried dozens of approaches to passing the filter value received on to another page via a menu, but none have been effective.

BONUS

Assuming this problem can be solved, I'd really like to use clean URLs. So instead of `/books/title?topic=5` I want to use `/books/title/5`. This works to correctly display a list of health books sorted by title, but when used, the menuing system does NOT set the `active` and `active_trail` classes on the active menu `<li>`, which I need it to do.

# Answer
> 1 votes
The "connected" exposed sorting criteria is implemented in the Facets module and Search API. Here's a tutorial that can help get you started: Creating a Faceted Search View in Drupal 8 using the Search API Modules

---

Before you start testing new modules maybe the "ordinary" **Exposed** Sort criteria in Views can help. Create only one Page display, but add all 3 Sort criteria you want and Expose them. You can use the `Expose form in Block` to show those options in some region of your theme instead of above the results.

The Better exposed filters module allows you change the widgets from drop-downs to Radio buttons or links. You can also rewrite the filter options to make them more relevant for your cases, and combine the "sort order" with "sort by".

Having an exposed form block can serve like Menu items, showing the user what has been selected, which is what the active menu trail does.

---

To clean up the URLs there is the Query Parameters To URL module but it's still being ported to Drupal 8. (Help advance it if you can.) Without it I guess you can set up some path redirects manually, although it might be tedious if you have a lot of combinations to cover. You can do that in .htaccess or with the Redirect module.

---

Yet another approach I can think of is the Views Global Filter module. You might use the "topic" globally, then sort links might work with menu trails (I haven't tried it).

---
Tags: views, 8, theming
---


# Question
Title: How to import OAI or REST API url data in a specific content type node?
I have a OAI/REST API url having thousand of records. How do I import these records in my content type node. Which module should I use? or I have to write custom module for this. Suggest some solution. Thanks in advance.

# Answer
There are several options depending on your needs. Do it once or frequently? Do you want to refresh the data/edit it.

Search on https://www.drupal.org/project/project\_module for Import/export

A different type is external\_entities which does keep a cached version of the remote content.

Hope this helps a little.
> 0 votes

---
Tags: importing-exporting
---


# Question
Title: Prevent form regeneration when a callback function is called through ajax
Here is the code for the custom form with a field(field\_B) that calls an function through **ajax**.

The issue is that I want the function (`MY_MODULE_XYZ_function()`) to be executed only once, when the page loads for the first time. But the function(`MY_MODULE_XYZ_function()`) is being executed for each ajax call through `field_B` because the whole form is being regenerated.

How can I prevent whole form regeneration(so that the function won't be called more than once) for each ajax call? Thanks in advance.

```
function MY_MODULE_menu(){
    $items['abcd/xyz'] = array(
        'title' => 'ABCD',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('xyz_custom_form'),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function xyz_custom_form($form, &$form_state){

    MY_MODULE_XYZ_function($arg1, $arg2);

    $form['field_A'] = array(  .... );

    $form['field_B'] = array(
        '#type' => 'radios',
        '#options' => array("a"=>"A", "b"=>"B", "c"=>"C"),
        '#prefix' => "<div id='customDiv'>",
        '#suffix' => "</div>",
        '#ajax' => array(
        'callback' => 'MY_MODULE_custom_ajax_callback',
            'wrapper' => 'customDiv',
            'progress' => array( 'type' => 'throbber', 'message' => NULL),
            'effect' => 'fade',
        ),
    );
}

function MY_MODULE_XYZ_function($arg1, $arg2){
    //Some Query Execution
}

function MY_MODULE_custom_ajax_callback($form, &$form_state){
    //Some Callback code
}

```

# Answer
> 0 votes
If you need a entity (which could be a node) to be created whenever the form is loaded, can create the enitiy, and pass it to your form, rather than creating it within your form. Then you can also use the same form for editing the entity.

For example, in a module called nodeform:

```
function nodeform_menu() {
  $menu['nodeform/add'] = [
    'title' => 'Nodeform add',
    'page callback' => 'nodeform_add_page',
    'access arguments' => ['some_create_permission'],
  ];

  // Note: using %node will call node_load(), passing it
  // the value given in that index of the path. If no node
  // is loaded, or the user does not have access, a page
  // not found error is returned (or maybe access denied)
  $menu['nodeform/%node'] = [
    'title' => 'Nodeform add',
    'page callback' => 'nodeform_edit_page',
    // The page argument is the 1st index of the path
    // which is %node. So the page argument will be a
    // node object.
    'page arguments' => [1],
    'access arguments' => ['some_edit_permission'],
  ];

  return $menu;
}

function nodeform_add_page() {
  global $user;

  $node = (object) array(
    'uid' => $user->uid,
    'name' => isset($user->name) ? $user->name : '',
    'title' => t('Default title'),
    'type' => 'some_node_type',
    'language' => LANGUAGE_NONE,
  );

  return [
    '#prefix' => '<div id="nodeform_add_form_page">',
    '#suffix' => '</div>',
    'form' => drupal_get_form('nodeform_default_form', $node),
  ];
}

// The edit page receives a loaded node as its argument:
function nodeform_edit_page(array $node) {
  return [
    '#prefix' => '<div id="nodeform_edit_form_page">',
    '#suffix' => '</div>',
    'form' => drupal_get_form('nodeform_default_form', $node),
  ];
}

// The form then receives a node:
function nodeform_default_form($form, $form_state, $node) {
  // Get the node from the form state if it exists, or use
  // the node passed to the form if it does not.
  $node = isset($form_state['nodeform_node']) ? $form_state['nodeform_node'] : $node;
  // Save the nodeform to the node
  $form_state['nodeform_node'] = $node;

  // Add your form elements:
  $form['title'] = [
    '#title' => t('Title'),
    '#type' => 'textfield',
    '#default_value' => $node->title,
  ];

  return $form;
}

function nodeform_default_form_submit($form, $form_state) {
  $node = &$form_state['nodeform_node'];
  $node->title = $form_state['values']['title'];
  node_save($node);
}

```

You may not need all of the above example, but if you look at the nodeform/add menu path, it shows how you can always create a node when the form is called, and it will only happen once, rather than every time the form is built. If you don't need to use it in the form, then call `node_save()` on the node in `node_add_page()`.

# Answer
> 0 votes
Simply create a key inside `$form_state` that will keep track if ajax has ran.

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

  if (empty($form_state['ajax_ran']) {
    $form_state['ajax_ran'] = FALSE;
  }

  $form['field_B'] = array(
    '#type' => 'radios',
    '#options' => array("a"=>"A", "b"=>"B", "c"=>"C"),
    '#prefix' => "<div id='customDiv'>",
    '#suffix' => "</div>",
    '#ajax' => array(
      'callback' => 'MY_MODULE_custom_ajax_callback',
        'wrapper' => 'customDiv',
        'progress' => array( 'type' => 'throbber', 'message' => NULL),
        'effect' => 'fade',
      ),

  if ($form_state['ajax_ran']) { // if TRUE
    unset($form['field_B']['#ajax']): // remove ajax
  }

}

function MY_MODULE_custom_ajax_callback($form, &$form_state){
    $form_state['ajax_ran'] = TRUE;
    // Some Callback code
  }
}

```

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


# Question
Title: How to extend ArgumentPluginBase and have it recognized by Views?
I'm wanting to create a Views argument plugin that extends ArgumentPluginBase in order to overrides one of the form elements in the buildOptionsForm(). I've pasted my plugin below. However, it doesn't seem to be recognized by Views. How do I make Views aware of this plugin and to make use of it?

```
<?php

namespace Drupal\my_custom_taxonomy_validation\Plugin\views\argument;

use Drupal\views\Plugin\views\argument\ArgumentPluginBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Resize the override text field.
 *
 * @ingroup views_argument_handlers
 *
 * @ViewsArgument("my_custom_taxonomy_validation_argument")
 *
 */
class MyCustomTaxonomyValidationArgument extends ArgumentPluginBase {

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['title'] = [
      '#maxlength' => 355,
    ];

   }

}

```

# Answer
> 1 votes
register it with hook\_views\_data\_alter() in mymodule.views.inc

Something like this:

```
/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(&$data) {

  $data['node_field_data']['my_custom_taxonomy_validation_argument'] = [
    'help' => t('Hello world'),
    'real field' => 'title',
    'argument' => [
      'title' => t('Hello world'),
      'id' => 'my_custom_taxonomy_validation_argument',
      'accept depth modifier' => TRUE,
    ],
    'filter' => [
      'title' => t('title'),
      'id' => 'my_custom_taxonomy_validation_argument',
    ],
  ];

```

}

---
Tags: views, 8
---


# Question
Title: No such file or directory in Drupal\Component\DependencyInjection\PhpArrayContainer->createService()
I installed a fresh D8 (Drupal 8.6.15) site on my local dev and I am unable to use drush.

After I installed the site, I also did a `composer install`. My dev is set up on php 7.1 using AMMPS and drush 8.1.18.

> No such file or directory in Drupal\Component\DependencyInjection\PhpArrayContainer-\>createService() (line 79 of /Applications/AMPPS/www/commerce/docroot/core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php).

# Answer
I needed to use drush 9.6 and updated that by `composer require drush/drush:"^9.6"`. Thanks drugan!
> 1 votes

---
Tags: 8, drush
---