# Question
Title: How to filter Search API index view by taxonomy parent
I am using the default database server that comes with search api. I have the Hierarchy Index ticked and I also have the taxonomy field that I want selected.

Could someone give me instructions on how to configure the view to have it filtered by the taxonomy parent/show only the children of the selected parent term? I just want a drop down like you would have with a regular view.

(I got this to work in D7 a while ago but I think that was because the field still retained its taxonomy data type when indexed but now with D8 it has none of that.)

* I can add a field that has a parent relationship but that does nothing.
* I tried adding a field `Vocabulary » Taxonomy term » Term Parents` and tried to filter by that but nothing.

# Answer
> 0 votes
I just figured this out the answer was simpler than I thought.

I was trying to use contextual filters & relationships like other answers said but what worked was just simply adding the `Taxonomy Field` to `Filter Criteria` then selecting the desired `parent`. That's it. No need to add a relationship to it.

**Edit:** There is still a problem: it doesn't work when using a grouped exposed filter it gives this error:

> A value is required if the label for this item is defined.

Log Message:

> PHP - Warning: trim() expects parameter 1 to be string, array given in ...

I tried changing the filter to `Combined field filter` with the Taxonomy as a field so the input would be string but I still get another error.

> PHP - Error: Call to undefined method ...

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


# Question
Title: Display Suite vs. EVA for displaying a view as field
I want to display a specific view as a field in nodes. It’s the same view for all nodes of this type, making use of the contextual filter "Content ID from URL".

I found two solutions using contributed modules:

* **EVA: Entity Views Attachment**: it’s specifically for this use case
(there is also Viewfield, but that’s still in alpha)
* **Display Suite**: it’s not its primary use case, but makes it possible by adding a "block field", where you can select the block generated by the view

Assuming that Display Suite is installed anyway (installing it just for this use case would be overkill, I guess), **is one solution better than the other?** Both seem to work fine, but I’m thinking of possible issues I can’t foresee now, like performance impact or compatibility with the Drupal ecosystem.

# Answer
> 2 votes
I think the best contender for EVA is Views Reference Field:

Both have stable releases. Main difference is the workflow. EVA is perfect if you want to impress your co-workers with the ability to attach a View to a content type like magic. Views Reference Field gives content editors the power to add Views to content themselves. Both modules don't need a block display, EVA provides its own and Views Reference Field can use any display type.

# Answer
> 2 votes
We have found viewfield 8.x-3.0-alpha2 to be pretty stable even in `alpha`. Based on your description, here is how you can use it.

1. Add field where `type = viewfield`
2. select a view to be added to the content type.
3. if you are wanting to use the `node id` as a filter, you need to set the filter on the field settings. It allows you to do use all the tokens, even custom one. In your case it should be `[node:id]`. I believe it would be under `Arguments to be passed to the display`
4. Under `Manage Display` for the content type, ensure it is enabled and in the location you need it to be.
5. the `viewfield` comes with two twig templates that you can override as needed with relate `template_preprocess_viewfield()` and `template_preprocess_viewfield_item()` hooks.

Considerations:

1. Since it is a field on the content type, remember to add the field to either the twig template or display suite view so that it displays on the screen.
2. Views have different displays so when you select what View to add to the field, remember to select the display you need. For example, `master,`block`,`page\`, etc. can all be selected.
3. You can reuse the field on multiple content types. Just remember to check that all the important field settings are set such as `[node:nid]` as a filter, the View display is enabled, and the correct view is selected.

---
Tags: views, 8, entities, display-suite
---


title: How do I clear the order cache?

text:
# Question
Title: How do I clear the order cache?
I manually update an order using the following code.

```
db_update('uc_orders') // Table name no longer needs {}
  ->fields(array(
    'order_status' => 'payment_received',
  ))
  ->condition('order_id', $order->order_id)
  ->execute();

```

Then I visit /admin/store/orders/view, but the value for the order still shows a *Pending*. If I clear the cache, the new status is *Payment received*, as it should be.

How do I clear the specific order cache so that it updates immediately?

The following code does what I want, but I would prefer clearing the cache for the specific order that is manually updated.

```
$orderEntity = Order::load($order_id);
$orderEntity->setStatusId('payment_received');
$orderEntity->save();

```

# Answer
> 1 votes
```
\Drupal::service('entity_type.manager')->getStorage('commerce_order')->resetCache([ORDER_ID]);

```

This service which used in `OrderReassignTest.php` will help you to `Reload the order` based on `Order ID`.

---
Tags: 8, caching, ubercart
---


# Question
Title: Override formatting for paragraph edit view
I have a paragraph type defined as two fields, which are Person and Role.

I can customize the structure of the paragraph fine to view. However, I am stuck in editing how the form elements sit in the Edit screen.

Debugging the twig files indicates that the Theme Hook around these components is 'container' and not anything to do with 'paragraph'.

Is there either:
a. A way to specify a 'container.html.twig' file to render the paragraph's form?
b. A way to specify how the paragraph should render forms?

Is there something else I may have missed?

# Answer
Most edit forms utilize your current admin theme and form render arrays with according widget subforms.

So - in theory - you have several options:

(1) Provide your own admin theme with templates for your single forms. Using a contrib admin theme as base theme would make up for an easy start.

(2) Create a custom module and implement one of the many hooks that allow to alter your forms (e.g., hook\_form\_FORM\_ID\_alter, hook\_field\_widget\_WIDGET\_TYPE\_form\_alter, ...).

(3) If suitable, choose your front-end theme for editing your content. Then you can implement your templates there. For this, you'd want to implement a custom theme negotiator in a custom module.

**In most cases however, the above methods are overly time-consuming.**

To improve usability of back-end forms for content authors, have a look into the field\_group module. It allows you to structure your back-end editable forms and displays. You can add groups like detail wrappers, horizontal/vertical tabs, and/or containers with custom HTML-elements and classes.
> 0 votes

---
Tags: 8, theming, paragraphs
---


title: Where are backups stored?

text:
# Question
Title: Where are backups stored?
I have used https://github.com/drupal-composer/drupal-project to install a new website. I have now updated the core with the same information on the above link.

I was wondering where the backups are stored and how to use the "`git diff`" because I don't now where the old vs new files are located on my server (ie: .htaccess and robots.txt).

# Answer
The guide you are referring to assumes that you will be tracking your website as a git project. This is the best way to develop locally before deploying on the server.

The workflow for that is to use composer create-project, then initializing the git repository and adding everything. The default .gitignore should ensure that the installed code isn't added. However, the scaffolding files like index.php and autoload.php are. Once that is done, you can deploy the site on any server by cloning the repository and running composer install.

When the guide says that after updating you should

> Run git diff to determine if any of the scaffolding files have changed. Review the files for any changes and restore any customizations to .htaccess or robots.txt.

it means that updating may have replaced these files, and you may need to re-add custom changes and then commit the new files to git.

composer doesn't create any "backups" when overwriting the scaffolding files - this is why it is important to track the scaffolding files in git, especially if you have custom modifications.
> 4 votes

---
Tags: 8, composer
---


title: How to add dynamic field labels?

text:
# Question
Title: How to add dynamic field labels?
I have a "medical records" content type which has a "medical process" field embedded (type=paragraphs bundle, number of values unlimited). In the paragraph bundle its has visit time, diagnosis, treatments, images, etc., so the paragraph can record every visit.

Everything works well, however, if we have a lot of paragraphs, in the view page, it looks ugly, so I would like to add some labels to each visit record enter image description here(paragraph), such as "the first visit", "the second visit","the % visit)...as I know the field group can only show a static label, token not available. Do anybody know how to realize this?

# Answer
You can use hook\_node\_view to change the view before rendering.

```
/**
 *
 * @param type $node
 * @param type $view_mode
 * @param type $langcode
 * Implements hook_node_view().
 * To change paragraph title in node view.
 */
function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
  if ($node->type == 'CONTENT-TYPE-ID' && $view_mode == 'full') {
    foreach ($node->content['field_medical_records'] as $key => $paragraph_values) {
      if (is_numeric($key)) {
        $item_key = key($paragraph_values['entity']['paragraphs_item']);
        $node->content['field_medical_records'][$key]['entity']['paragraphs_item'][$item_key]['field_visit_time']['#title'] = numToOrdinalWord($item_key) . ' Visit';
      }
    }
  }
}

/**
 *
 * @param type $num
 * @return string
 * Implement to get Ordinal word from number.
 */
function numToOrdinalWord($num) {
  $first_word = array('eth', 'First', 'Second', 'Third', 'Fouth', 'Fifth', 'Sixth', 'Seventh', 'Eighth', 'Ninth', 'Tenth', 'Elevents', 'Twelfth', 'Thirteenth', 'Fourteenth', 'Fifteenth', 'Sixteenth', 'Seventeenth', 'Eighteenth', 'Nineteenth', 'Twentieth');
  $second_word = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty');
  if ($num <= 20) {
    return $first_word[$num];
  }
  $first_num = substr($num, -1, 1);
  $second_num = substr($num, -2, 1);
  return $string = str_replace('y-eth', 'ieth', $second_word[$second_num] . '-' . $first_word[$first_num]);
}

```

You can change field names as per your requirement.
> 0 votes

---
Tags: entities, paragraphs
---


title: Pseudo field show/hide setting per node

text:
# Question
Title: Pseudo field show/hide setting per node
I have created a pseudo field using `hook_entity_extra_field_info()` and displaying markup using `hook_entity_view()`.

How can I create a checkbox setting in node create form so that I can show / hide this pseudo field per node?

# Answer
> 0 votes
In `hook_ENTITY_TYPE_view` which you use to render your pseudo field there already is the `$entity` available. Which in your case must be a node object. You simply can get any field value from there.

So all you need to do is to add a Drupal default checkbox/boolean field to your content type, from the UI probably, hide it from display, and then output your pseudo field depending on its value, per node.

```
/**
 * Implements hook_entity_extra_field_info().
 */
function MYMODULE_entity_extra_field_info() {

  $extra['node']['article']['display']['foo_bar'] = [
    'label'       => t('My pseudo field'),
    'description' => t('My pseudo field description.'),
    'weight'      => 0,
    'visible'     => TRUE,
  ];

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->bundle() == 'article') {

    // Get the choice.
    $editors_choice = $entity->field_editors_choice->first()->getValue();
    $editors_choice = isset($editors_choice['value']) ? $editors_choice['value'] : FALSE;

    // And fire accordingly.
    if ($display->getComponent('foo_bar') && $editors_choice) {
      $build['foo_bar'] = [
        '#markup' => 'This is my custom content',
      ];
    }
  }
}

```

---
Tags: 8, nodes
---


title: How to regenerate xmlsitemap to https?

text:
# Question
Title: How to regenerate xmlsitemap to https?
I'm new to Drupal community and I wonder if there is a solution to regenerate all urls from http to https?

I have already tried to just regenerate and try to update `$base_url` in setting, nothing helped.

# Answer
> 3 votes
There is a setting in the XMLSitemap admin configuration that lets you set the base domain. Update that value, clear cache, and regenerate the sitemap.

---
Tags: xml-sitemap
---


title: Few content types in a View

text:
# Question
Title: Few content types in a View
I use Drupal 8 and I need to create a view with few content types. When I navigate to a specific path, I need to list all of them at the same time, but I need something like a filter so that in this view only particular content type is displayed. How can I do it?

# Answer
It sounds like you're looking for a Contextual filter.

You create a Page Display with a path of your choosing that is displaying many Content types. This is your page that lists all of them, for example `my-content-types`.

Then you add a Contextual filter to that View called **Content type** from `Content` Category.

Configure it with these options:
`When the filter value is NOT in the URL`
**Display all results for the specified field**
`When the filter value IS in the URL or a default is provided`
**Specify validation criteria**
`Validator` **Content type**
`Case in path` **Lower case**
`More`
**Transform spaces to dashes in URL**

You can leave other options as default, although you should read them all and adjust to your needs, for example what Views should do in case your argument doesn't validate, or you need more than one content type filter on the same page.

This Contextual filter adds options to your path based on the content types you have on your system. If you add the name of a content type to your path (in your browser Location bar): `my-content-types/article` the Views results will reduce the list to only show Article nodes.

If you enter a path `my-content-types/page` it will list only Basic page nodes.

There is also an option to override the Title if you need to correct it to name only the content types filtered out.

If you set your Contextual filter to allow multiple values (there are two places for that) you can construct the path with two or more content types to filter them out: `my-content-types/page+article`.

To test that your Contextual filter is working you can enter the argument for it in the `Preview with contextual filters:` field and hit the `Update preview` button if you don't have it set automatically. To view all the results without filtering simply delete the argument or enter `all` at the Preview or at the end of your path.
> 0 votes

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


# Question
Title: How do I create a list of Nodes within a list of taxonomy terms, within a node?
I want to make an awards event where users can log in and nominate their products in specific categories.

* I have a node: "Awards Event" where the details of the event are defined
* I have a taxonomy: "Awards Event Categories" - these are the categories which can contain multiple nominated products. These categories will be used for multiple awards events. Within 'Awards Event' node the admin defines which of these categories will be available in this particular event.
* I have nodes: "Products" - these are controlled by the users who'll assign them to a category

Basically what I want is a way to build a list of which products are nominated in each category within each Award Event.

Is there an easy way to accomplish this? I could just simply add a new field within the product node where the taxonomy term can be selected - but this would require me to add that new field each time an awards event is created. I'd prefer if there was a more automated way.

# Answer
> 0 votes
You could create a view which will display content filtered by a category, note that the category filter should be a contextual one.

In the node, you should have a taxonomy term reference field and then in preprocess, you can create your own variable by rendering the view with a contextual filter. The contextual filter in this case will be the value of the taxonomy term reference field.

This will handle the desired behavior but won't be as flexible. It will cover choosing a different term for each node, but you will be stuck to the same view.

# Answer
> 0 votes
It is a very common request to list entites that share the same Taxonomy terms as the page you're currently viewing. You can solve it by creating a Views Block with a Contextual filter that passess the Taxonomy term information of the current page to the Views Block for filtering.

In your case here is what you do:

## Filter according to Taxonomy term of the current page

1. Create Views of type Content that shows `Product` nodes and create a Block Display.
2. Add the field that references "Awards Event Categories" Taxonomy from the Product nodes
3. Add a new Contextual filter **Has Taxonomy term ID** from the `Content` Category and configure it with these options:
`When the filter value is NOT in the URL`
**Provide default value**
**Taxonomy term ID from URL**
**Load default filter from node page, that's good for related taxonomy blocks**
**Limit terms by vocabulary**
\[Awards Event Categories\]
`Multiple-value handling`
**Filter to items that share any term**

`When the filter value IS in the URL or a default is provided`
**Specify validation criteria**
**Taxonomy term ID**
\[Awards Event Categories\]
`Multiple arguments`
**One or more IDs separated by , or +**
`More`
**Allow multiple values**
4. To test that the Contextual filter is working correctly you can use the `Preview with contextual filters:` field where you enter the term ID and see if the results below get filtered appropriately.

If you enter `1` and press `Update preview` the results below will only show Products that have been tagged with the term that has TID `1` (check for your term IDs on the Vocabulary list terms page by hovering over the Operations links).

If you enter `1+2` the results will be reduced to show only Products that have *either* term 1 or term 2.

If you enter `1,2` the results will be reduced to show only Products that have *both* the term 1 and term 2.

## Group results by Taxonomy term ID
5. Under your `Format` settings enable grouping by choosing **Awards Event Categories** (or whatever your field name is) under `Grouping field Nr.1`
6. Edit the "Awards Event Categories" field and set **Exclude from display** so it's not repeated because the Grouping will render it above its batch of results (you still control the Grouping Label and output here in the Field settings)

You now have the Views results grouped by the Taxonomy term they're tagged with, so you basically see more than one set of results, depending on how many tags there are in the results.

## Place the Block
7. Now place the Block in a region of your theme, don't forget to adjust the Block settings for the Contextual filter, set it to only show on "Awards Event" content type.

Now when you visit an "Awards Event" node you will see the list of existing Products that share the same terms as that node, and they will be grouped in batches by each term.

---
Tags: nodes, taxonomy-terms
---


title: How do I upload a background image?

text:
# Question
Title: How do I upload a background image?
I want to insert a background image in the *IBM API Connect* theme. I first googled, and I found how to insert an image in a node; then I downloaded the Background Images, the Background Images Formatter, and the ImageCache Actions modules, but to no avail.

I found out the CSS for it.

```
   body #main-wrapper {
   background-color: #FFFFFF !important;
   background-image: url('sites/all/BackgroundWallpapers/pink1.jpg')
   !important;
   background-repeat: no-repeat !important;
   background-attachment: scroll !important;
   background-position: left top !important;
   background-size: cover !important;
   -webkit-background-size: cover !important;
   -moz-background-size: cover !important;
   -o-background-size: cover !important;
    }

```

I don't know how to insert a URL/path for the background image in the background-image attribute. Where do I store the image?

# Answer
> 2 votes
You can store image in your drupal theme.

for example, you are using custom theme then you can store image in project\_name/sites/all/themes/custom\_theme/images/image\_name.jpg

And reference this path in your css file of your theme as below

background-image: url(../images/image\_name.jpg);

# Answer
> 0 votes
As for the Background Image Formatter, what you want to do is:

* Determine which element should get the background image you want to print
* Provide said element with a custom CSS class
* In the CSS selector field of the Background Image Formatter settings, input your custom CSS class, then setup the other parameters

It can be ANY valid CSS selector, and you can use token replacement, providing you with things like the current NID allowing it to be used in a view with custom text where you dynamically create your class in the text and call it from the formatter.

You can also provide it with pseudo selector allowing you to put the background image on a ::after or a :hover for additional control

---
Tags: theming, media
---


# Question
Title: Taxonomy terms with numeric names and views filtering within range
I have a very large taxonomy vocabulary with numeric taxonomy term names like: 10123,10124,10125,... etc. My node have a min value field and max value field. Both fields are taxonomy referenced fields with this vocabulary. How I can create views filter to find a nodes, where exposed filter value is between these two fields?

Example 1.

* Node field min: Taxonomy term with name "10500"
* Node field max:Taxonomy term with name "11000"
* Exposed filter value: 10800

This is TRUE, so this node must be in views result.

Example 1.

* Node field min: Taxonomy term with name "10500"
* Node field max: Taxonomy term with name "11000"
* Exposed filter value: 11500

This is FALSE, so this node should not be in views result.

Exposed filter value can be as taxonomy term autocomplete widget.

Any ideas, how it can realize?

I'm looking a solution in \_views\_query\_alter, but I still can not understand is this right way?..

# Answer
> 4 votes
I believe a numeric range can be filtered using regular expression.

The following regex can effectively filter values within the range 10500 - 11000 (both ends inclusive)

```
(10[5-8][0-9]{2}|109[0-8][0-9]|1099[0-9]|11000)

```

Here is a sample view that works as expected with the above regular expression

You can create any numeric range as a regex using this generator http://gamon.webfactional.com/regexnumericrangegenerator/

**Alternativelly** what you can do is to add an extra numeric field to populate with term name (as a number) and than using that field to filter the view **OR** create a more complex function using `hook_views_query_alter` as you mentioned

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


title: How to get fields of media_entity?

text:
# Question
Title: How to get fields of media_entity?
We have a view that returns a `Media_entity (Drupal\media_entity\Entity\Media)` using the following in a `hook_preprocess_view_views` hook. When we try to access the `field_media_type` variable, I get a `NULL`. `field_media_type` is a custom field (taxonomy field) on all the `Media` bundles.

How do we get the fields from a `Media_entity`?

```
use Drupal\media_entity\Entity\Media;

function mymodule_preprocess_views_view(&$variables) {
  $results = $variables['content']['#view']->result;
  foreach($results as $row){
    $media_entity = $row->_entity;
    ksm($media_entity->get('field_media_type'); // returns null.
  }
}

```

I also tried the following:

```
use Drupal\media_entity\Entity\Media;

function mymodule_preprocess_views_view(&$variables) {
  $results = $variables['content']['#view']->result;
  foreach($results as $row){
    $mid = $row->mid;
    $media_entity = Media::load($mid);
    ksm($media_entity); // null
  }
}

```

**content array**

**iterator contents**

# Answer
An alternative solution I found was to use get the `target_id` and use `Term::load($term_id)->getName()` to get the value we wanted.

```
use Drupal\media_entity\Entity\Media;
use Drupal\taxonomy\Entity\Term;

function mymodule_preprocess_views_view(&$variables) {
  $results = $variables['content']['#view']->result;
  foreach($results as $row){
    $media_entity = Media::load($row->mid);
    $media_target_id = $media_entity->get('field_media_type')->target_id;
    $media_type_name = Term::load($media_target_id)->getName();
  }
}

```
> 2 votes

# Answer
What you are looking for is `$media_entity->label()` and that will give you the name. The reason `$media_entity->get('name')` is not working is because the name is a property of the class and not a field.

One little trick you can use to work out which methods you can use on the object is `get_class_methods(media_entity)`.
> 0 votes

---
Tags: 8, media
---


# Question
Title: Why is the page content always rendered after blocks displayed on the same page?
I have a Static Page node at, say, `/my-page`. It has a title and body. I have also placed a block (pointing to a View) in the "Main content" region, at the very bottom of the list.

However, when viewing /my-page, the block is displayed above the `<article>` element that contains the page content. An example can be seen below.

Why is this the case? What can I do to always show the page content *above* everything else that is placed in the same region?

# Answer
> 4 votes
You need to adjust the display order of the blocks through configuration. Navigate to `Manage >> Structure >> Block layout` (relative path: `/admin/structure/block`), click the handle icon next to the "Main page content" block and use it to drag the block to the top of the "Content" region.

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


title: Updating core from 8.5.4 to 8.5.6

text:
# Question
Title: Updating core from 8.5.4 to 8.5.6
I'm trying to update Drupal core to lasted version with `composer update drupal/core --with-dependencies`. I followed the instructions given on Update core via Composer, but Composer claims there is nothing to install or update. It also prints the following message.

> Package "drupal/core" listed for update is not installed. Ignoring.

# Answer
1, in file `composer.json` add

```
"require": {
"drupal/core": "~8.5"
}

```

Remove line

```
"replace": {
    "drupal/core": "^8.5"
}

```

remote folder `vendor` remove file `composer.log`

alter run

```
composer update --with-dependencies

```
> 1 votes

---
Tags: composer
---


# Question
Title: How to create a link from node view and pass information to a webform
In Drupal 8, I have a webform field attached to a node with the *Link to form* formatter enabled.

Can I add the ID of that node in the *Link custom attributes (YAML)* textarea to display a block view of some node fields?

My goal is to be able to use a contextual filter on the block view to display the node information like title and some other fields around the form

>

# Answer
> 1 votes
I don't think `webform link` field can be used to accomplish this as the purpose of `Link custom attributes (YAML)` is for HTML TAG attributes like

```
target: _blank

```

**You can use** field\_token\_value to create a field on the node that has tokens as input. Install and enable the module and then add a token field.

The value of this field would be an HTML link with query parameters added (`nodetitle` in this example) you can browser for all available tokens under field value.

Then on the webform side you have to enable query parameter to populate fields by going to the `settings of the webform > form > form behaviours > prepopulate > Allow all elements to be populated using query string parameters.`

And then on the field to display the query parameter include the appropriate token. Here adding the `nodetitle` to the subject field default value.

For token field to be populated a node needs to be saved.

---
Tags: 8, webforms
---


# Question
Title: Change the format of 'Authored on' date in views filter
In Drupal 8, I want to remove the timestamp on 'Authored on' date in views filter. Any Idea how to do this?

# Answer
> 1 votes
As @prkos said enable better\_exposed\_filters and in `Exposed form style` change it as `Better Exposed Filters`. Open setting and under `Authored On` select `jQuery UI Datepicker`. It will enable to give only date format.

**BEF Settings:**

---
Tags: 8, datetime
---


title: Revert views missing. Any workarounds?

text:
# Question
Title: Revert views missing. Any workarounds?
In Drupal 8 reverting views to their original (in the core, custom or contributed module) became difficult. Supposedly the module config\_update would allow reverting a view, but that promises to be a more laborious than simply clicking a link like we were used to in Drupal 7.

I was wondering if it would be possible to make selected views read-only? That way administrators with Views UI permission would have no edit link forcing them to work with a duplicate.

Hints on how to accomplish this? Any other possible workarounds?

# Answer
A simple workaround without an additional module would be to copy and paste the content of the yaml file `views.view.[view-id].yml` you find in the module's /config/optional folder to *www.mysite.com/admin/config/development/configuration/single/import*.

Select the configuration type "View" and add the first line containing the UUID from the active configuration (switch to Export - Single item).

If you have to do this on a regular basis then the recommend way is to manage the configuration with Git, see this tutorial Using Configuration Management and Git to Track Drupal 8 Configuration.
> 4 votes

---
Tags: views, 8
---


# Question
Title: How to pass the node id from a View Block to an associated Views Attachment for use in filters so that both operate on same content node id?
What would I need to do to pass the node id from a View Block to an associated Views Attachment for use in the filters in the Attachment View so that both operate on same content node id?

My specific example is for generating preview/teaser output from a media gallery with a certain tag:

1. The title of the latest gallery with that tag
2. The latest 3 thumbnails of that gallery

(I know how to build a block view to fetch thumbnails from *galleries* (i.e plural) that have a certain tag - my solution is here: https://drupal.stackexchange.com/a/13559/1082 I am using the Acquia Media module)

BUT what I don't know how to do is to get the title latest gallery (singular) with a certain tag followed by the latest 3 thumbnails of that gallery.

I attempted to create a block view that fetched the title of the gallery with the certain tag and I also created an view attachment to fetch the thumbnails of that gallery. But I could not work out how to pass the node id of the gallery from the block view to the attachment for it to use in its filters when fetching the thumbnails.

I tried various options including enabling the attachment to inherit arguments and filters from the block view and also contextual filters but no success so far.

Further to this, I may wish to out put more than one gallery in the teaser/preview but if I set the count to more than one on the view block I get the other gallery titles listed together followed by the thumbnails. I would want each gallery in turn to display the title followed by thumbnails that belong to it.

I would prefer to do this all withing Views i.e. not have to use PHP. I would want the solution to be as forward compatible as possible, i.e. not break with future updates - if we can stay within Views then the migration to those might be easier.

# Answer
> 1 votes
Since the attachment is linked to a specific view block, it should gain access to the information in the block. You can inform the block of the node ID by using contextual filters. 1. In the block add a contextual filter of the type content:nid. 2. Since blocks do not have paths you must explicitly tell the block to find the display node, so under form heading of "When the filter value is not available", choose "Provide default value" and select "Content ID from the URL". This should provide the Node ID to the view block.

# Answer
> 0 votes
you can try this

```
$my_arg = 1;
print views_embed_view('my_test_view', 'block_1', $my_arg);

```

views\_embed\_view('VIEWS\_MACHINE\_NAME', 'DISPLAY\_ID');

---
Tags: 7, blocks, views
---


# Question
Title: Can we add different class to first row and last row of view?
Can we add different classes to first row and last row of view only ?

I have created a view of products listing in which i need to add unique class only in first row and last row of view.

I need to implement it for creating different designs layout of each row. In drupal 7 i did it by using below code :

```
 end($rows);
$last = key($rows);
?>
<?php if (!empty($title)): ?>
<h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id == $last): ?>
<?php $classes_array[$id] .= ' last-element'; ?>
<?php endif; ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php print $row; ?>
 </div>

```

How we can do the same in drupal 8?

# Answer
> 6 votes
You would probably be fine with just doing this with css ( see Beebee's comment on your post), but I will answer the question.

You can use loop.first and loop.last in twig. Here is an example I used to make it work in a menu.

```
<ul class="menu">
    {% for item in items %}
        {%
            set classes = [
            'menu-item',
            item.is_expanded ? 'menu-item--expanded',
            item.is_collapsed ? 'menu-item--collapsed',
            item.in_active_trail ? 'menu-item--active-trail',
        ]
        %}
        {% if loop.first %}
            <li {{ item.attributes.addClass('first-element') }}>
               {{ link(item.title, item.url) }}
               {% if item.below %}
                  {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
               {% endif %}
            </li>
        {% endif %}
        {% if loop.last %}
            <li{{ item.attributes.addClass('last-element') }}>
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            </li>
        {% else %}
            <li{{ item.attributes.addClass(classes) }}>
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            </li>
        {% endif %}

    {% endfor %}
</ul>

```

---
Tags: views, 8
---


# Question
Title: How to display result of a View in a specific block?
I have a View displaying the content of a Custom Content Entity.
The first output I created is a Page display (accessible with a path and an option in a menu).
As expected, this is displayed in the 'Content' region of the default theme (see capture below).
I'd like to output the result in a full width region of the theme, i.e. without the content of 'Sidebar First' (User account menu, Search).
I duplicated the Page Display as a Block Display and placed it. But, of course, it appears on every page of the site :-(
So I created a single basic page (node/xx) and I configured the block to show only in this page. But I had to hide 'User account menu' and 'Search' on this page too. Is there a more simple way to achieve this?

# Answer
You are going about this the wrong way. Start again with a page display for your view.

Now you want to remove the sidebar from that page. Two ways you might do that:

There are other approaches but these are probably the simplest to implement.
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: I am not able to override the form #access setting
I cerated a form alter with the file entity media upload browser. I studied this answer of how to alter this form. I then debugged and found that for what I wanted to do, I am in step 4 of the file upload browser as evidenced by the var: `$var['#step'] (Integer) 4`.

Thus my code so far is:

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Form ID = file_entity_add_upload.
 */
function MYMODULE_form_file_entity_add_upload_alter(&$form, &$form_state, $form_id) {
  // Check that this is the fields step.
  if ($form['#step'] == 4) {
  echo 'This is step 4';
  // yep the above prints out.

  // Set access false for the specified field.
  $form['field_usage_restricted']['#access '] = FALSE;

  // Add a dsm after to see what's going on
  dsm($form);
  }
}

```

You'd think this would get rid of the form field, yet, it's still present. See the dsm below:

I would think that my custom alter `FALSE` setting would override the `TRUE` setting but no such luck, the field is still there.

I can use an `unset($form['field_usage_restricted']);` and that works fine to get rid of the field, but I've learned that `['#access '] = FALSE;` is a better way to go, especially when there's ajax in use such as the case here. I do see in the debug that there's a form after build so I wonder if I need to do that?

I tried this on the off chance it would work but still no joy:

```
if ($form['field_usage_restricted'][LANGUAGE_NONE]['#after_build'][0]) {
  // Set access false for the specified field.
  $form['field_usage_restricted']['#access '] = FALSE;
}

```

(Note, my field, `field_usage_restricted` is not a required field.)

# Answer
> 1 votes
`$form['field_usage_restricted']['#access ']` the `#access` key has a space in it. Only reason I can think of you would get two items in the array like that. Remove that space, and dump the item out again. It should be overwritten and have `FALSE` for a value.

---
Tags: 7, forms, media
---


# Question
Title: Having multiple Drush instances for different core versions
So in my environment, I have some websites on Drupal 7 and some on Drupal 8, and since the latest Drush 9 works with Drupal 8.4+ I was wondering if there's a way to be able to have both Drush 9 and (put another version here) to work on both major Drupal versions.

I'd like to be able to just use `drush` as my main alias and not define different aliases for different Drupal versions.

# Answer
> 6 votes
Ideal way would be to use Composer to set up your projects. I'd recommend Composer templates for Drupal projects. Then add Drush to your project: `composer require drush/drush`.

Now install Drush Launcher on your machine, globally. Drush Launcher provides a `drush` command that always finds and uses the locally installed Drush from the `/vendor` folder.

```
$ cd MYDRUPAL
$ drush --version
Drush Launcher Version: 0.6.0
Drush Commandline Tool 9.3.0

```

---

But probably you can not simply rebuild your projects. Then you may want to install two different global Drush versions. See https://github.com/drush-ops/drush/releases for all available versions.

### `drush8`

```
$ sudo git clone https://github.com/drush-ops/drush.git /usr/local/src/drush8

$ cd /usr/local/src/drush8

# Check the latest Drush 8 version at https://github.com/drush-ops/drush/releases
$ sudo git checkout 8.4.10

# Linux:
$ sudo ln -s /usr/local/src/drush8/drush /usr/bin/drush8

# Mac:
$ sudo ln -s /usr/local/src/drush8/drush /usr/local/bin/drush8

$ sudo composer install

$ drush8 --version
Drush Version   :  8.4.10

```

### `drush9`

```
$ sudo git clone https://github.com/drush-ops/drush.git /usr/local/src/drush9

$ cd /usr/local/src/drush9

# Check the latest Drush 9 version at https://github.com/drush-ops/drush/releases
$ sudo git checkout 9.3.0

# Linux:
$ sudo ln -s /usr/local/src/drush9/drush /usr/bin/drush9

# Mac:
$ sudo ln -s /usr/local/src/drush9/drush /usr/local/bin/drush9

$ sudo composer install

$ drush9 --version
Drush Version   :  9.3.0

```

Source: Installing & Using Drupal Drush on Debian 7 (Bookmark this!)

# Answer
> 4 votes
I do a slightly different method than @leymannx outlined.

I have Drush 8 installed globally. In my case, I have a git clone and I periodically fetch and checkout one of the 8.x.y tags. This is on my bash $PATH. This is what I use to manage my Drupal 7 sites.

All of my Drupal 8 sites use drupal-composer/drupal-project, and include a dependency on `drush/drush`. I also put

```
"config": {
    "bin-dir": "bin/"
},

```

in my composer.json. Then I use direnv to set up a path for the root directory in drupal project. My .envrc will contain a line like

```
PATH_add /var/www/prod/bin

```

This prepends $PATH with this directory, so this version of drush will be picked up for that project. This ensures that drush is pulling the same dependencies as that particular drupal install.

---
Tags: drush
---


# Question
Title: Node reference solution for a content type which referenced to two fields. (company, product & review)
My website has three content types: company, product & review.

1). The product has a field referenced to a company node using Node URL Reference module.

2). The review has two fields, one referenced to company node, another referenced to product node.

The question is how to implement the item 2) following the behaviours described below:

1. While creating review node from company node, the product field should be updated to the products which belongs to that company.
2. While creating a review from product node, the company & product fields should be auto-filled.

Could you help me? I research this issue for several days but haven't resolved completely. Thanks a lot.

# Answer
> 0 votes
Try entityreference\_prepopulate

This will allow you to create a link with query string to pre-fill selections on an entity reference form field.

---
Tags: nodes, entities
---


# Question
Title: How do I examine an entity's update SQL statement in order to write a unit test?
I have a core patch (https://www.drupal.org/node/2342699) which ensures that SQL updates do not include the primary key in the field list. I need to write a unit test for this issue and EntityApiTest.php looks like the ideal place for this. This test class has a section

```
$entities = array_values($storage->loadByProperties(['name' => 'test']));
$entities[0]->name->value = 'test3';
$entities[0]->save();

```

The way I see it, I will need to examine the entity schema to find the database column name of the 'id' entity key, and then examine the SQL update object to ensure that the entity key is not in the field list. Any advice on how to do either of these steps?

# Answer
> 0 votes
Just write a test that attempts to update a primary key, and assert that it fails to do so.

There's no need to test the SQL generation mechanism of the storage class.

---
Tags: 8, entities, database, testing
---


# Question
Title: Customizing the display of properties on a rendered entity
I have a custom entity with a large amount of properties on it.

We want to format these entity properties to look a certain way, without modifying the underlying data in the table.

What is the most idiomatic (the most Drupal) way of doing it?

We're trying to put an Entity Reference of this custom entity on a node and render only a few fields - with a form of preprocessing or something along those lines so that we can control the ultimate output.

I can get the fields to show with this key =\> value pair in the entity array in hook\_entity\_info():

```
'extra fields controller class' => 'EntityDefaultExtraFieldsController',

```

But it doesn't seem to give me any control over the output.

Alternatively, I can put all of the properties into $entity-\>content in hook\_entity\_view() as such:

```
foreach ($entity as $field_name => $property) {
  if (in_array($field_name, $properties)) {
    $entity->content[$field_name] = array("#markup" => $property . "<br />");
  }

```

But this doesn't seem very idiomatic.

This seems like a problem that I can't find a lot of resources on.

# Answer
> 0 votes
> We're trying to put an Entity Reference of this custom entity on a node and render only a few fields - with a form of preprocessing or something along those lines so that we can control the ultimate output.

Sounds like hook\_entity\_view is what you want. Use "teaser" or create a new view mode, and attach the reference using the given view mode, then implement your logic to render the properties as you like.

Alternatively / additionally, you could look at Display Suite and DS Extras which will give you more flexibility to expose properties via DS custom fields or in field templates.

---
Tags: 7, entities
---


# Question
Title: Can you override a library per environment?
In my libraries.yml file, I have something like this, being used to define "foo-bar" as a library that can be pulled in from various parts of the site:

```
foo-bar:
  version: 0.0.x
  js:
    js/foo-dev.js: {}

```

This works well on my local environment, but on our production and QA environments, I would like for it to look more like this:

```
foo-bar:
  version: 0.0.x
  js:
    js/foo-prod.js: {}

```

(The prod version will include optimizations that normally don't appear with minification alone).

Currently, we are using the sites/\<site\>/settings.\*.php files and the config-split module to have different configurations based on the environment, but is there a way to have the foo-bar library reference the dev-friendly version on one environment, and the production version on all others?

# Answer
Look at `hook_page_attachments`. In the sample snippet provided behind that link there is a simple if-request which attaches a certain library only when a certain condition is met. Do the same.

**MYTHEME/MYMODULE.libraries.yml**

```
foo-bar-dev:
  version: 0.0.x
  js:
    js/foo-dev.js: {}
foo-bar-prod:
  version: 0.0.x
  js:
    js/foo-prod.js: {}

```

**MYTHEME.theme/MYMODULE.module**

```
function MYTHEME/MYMODULE_page_attachments(array &$attachments) {

  // Conditionally attach an asset to the page.
  if (\Drupal::request()->getHost() == 'example.com') {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-prod';
  }
  else {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-dev';
  }
}

```

---

More info on base URL: how to get base url of a site?.
> 4 votes

---
Tags: 8, javascript
---


title: How do I expose a contextual filter?

text:
# Question
Title: How do I expose a contextual filter?
I have created a view that shows few entities. To be able to see only a particular entity, I created a contextual filter.

How can I expose the contextual filter I added?

# Answer
Contextual filter is an an argument to the view, for example through the path or block/plugin context.

It is not visible to the user, it's visible to Drupal.

If you want something to be visible to the user, you need to instead add a filter and then tick the checkbox to expose it, creating a so called "exposed filter". That should then show up in a filter form.
> 1 votes

---
Tags: views, 8
---


title: Rest login cookie token explanation

text:
# Question
Title: Rest login cookie token explanation
When logging in via a POST to `user/login?_format=json` I'm sent back a response that looks like this

```
{
    "current_user": {
        "uid": "233",
        "name": "test"
    },
    "csrf_token": "XXXXXR5HQwidW7CKIDL52tOg4JGKi7Pa-j87KKlr8Mg",
    "logout_token": "XXXX-G35feFznaapSggzlUQEhYKXqom6yYVDwCH5Zxc"
}

```

I'm also sent back a session cookie that looks like this

name: `SESS95f37088bf4f23c4304d24270b7xxxxx`

value: `rqAupOwS2ieqwClBkwEaWj8-ywLqnQEcAL2xOG-xxxx`

When I send a GET to `session/token`

I receive a seperate token that looks like this `_XXXXXnX8k_prCNfdrHp6XeHOUx7DcuouqiLKBBn-Go`

I understand that the logout token is used with `/user/logout` in order remove the cookie and log the user out.

My questions are as follows.

The Cross Site Request Forgery token doesn't seem to be required by any of my end points by default. Is this something I should have the backend require them on specific paths using `_csrf_token: 'TRUE'` (and be passing with each request using the `X-XSRF-TOKEN` header?) Is this automatically passed with the cookie by chance?

The same question goes for the session token from `session/token` should this be being passed with each request, or in general what is the purpose for this token? I've seen this token referenced in docs as another CSRF token. If this is the case why is it different than the one provided by the login POST?

# Answer
You are logging in correctly by POSTing the username and password. After you've logged in, a Drupal session is created.

The `csrf_token` can be used to authorise future requests requests by sending it as a header:

```
X-CSRF-Token: XXXXXR5HQwidW7CKIDL52tOg4JGKi7Pa-j87KKlr8Mg

```

You can send this instead of a cookie if you've configured the backend to allow it. I've only used the CORS contrib module as CORS in Drupal core doesn't have the same flexibility.

> I understand that the logout token is used with /user/logout in order remove the cookie and log the user out.

Correct.

Also see my answer here: https://drupal.stackexchange.com/a/235712/34673
> 3 votes

---
Tags: 8, users, sessions, cookies
---


# Question
Title: What core configurations should be used in settings.php for a production site?
Can someone please share Drupal core configurations that should be included and/or excluded from settings.php to make the site both performant and secure?

# Answer
> 1 votes
Drupal 8 has a default settings.php you can use:

```
sites/default/default.settings.php

```

Just copy it as `sites/default/settings.php`, add your DB connection array - and you are pretty much ready to go. Then use the UI to turn on caching and CSS/JS aggregation.

For security you may want to add in your Trusted Host Pattern

```
# TRUSTED HOST PROD
$settings['trusted_host_patterns'] = [
  'mysite\.com$',
];

```

If you really want to you can lock down your caching & preprocessing settings in the settings.php file, rather than setting it through the UI

```
# CACHING & JS/CSS AGGREGATION PROD
$config['system.performance']['css']['preprocess'] = 1;
$config['system.performance']['css']['gzip'] = 1;
$config['system.performance']['js']['preprocess'] = 1;
$config['system.performance']['js']['gzip'] = 1;
$config['system.performance']['cache']['page']['max_age'] = 86400;

```

---
Tags: 8, configuration
---


title: Comments filter by Last in Twig

text:
# Question
Title: Comments filter by Last in Twig
I try to render the last comment from a list of comments.

I try `{{ comments|last }}` ---\> no result.

Then `{{ comments|reverse }}` ---\> this render them

Then `{{ comments|reverse|first }}` ---\> no result

The above part is solved.See anser 1. Pls if annyone have a solution for rendering the last comment in views.

I like to achieve the same in a view. There is a relation filter that output the last comment. But I think I do something wrong.

# Answer
The last item in `comments` is the pager, which you have to remove first to get to the last comment. Then you can build a new render array with the single comment and the pre-render callback:

```
{% set last_comment = comments|without('pager')|last %}
{% set pre_render = comments['#pre_render'] %}
{% set last_comment_build = { '#pre_render': pre_render, '0': last_comment } %}
{{ last_comment_build }}

```
> 1 votes

---
Tags: views, theming
---


title: Using the powr.io countdown plugin

text:
# Question
Title: Using the powr.io countdown plugin
So I am trying to use the powr.io countdown plugin and it says I should simply have to paste their tag and tag into the body of a Drupal body field and it should work. But it is only spitting out the code as plain text though I am using WYSIWYG text format which shouldn't filter anything. Any suggestions? thank you

# Answer
> 1 votes
As Beebee mentioned, "don't use Text format" I ended up changing my body field to plain text editor and this allowed it to work.

---
Tags: views, javascript
---


# Question
Title: What is the difference between a Drupal session variable and a cookie?
When you set a Drupal session variable (i.e. a "magic" variable you may set like this):

```
$_SESSION['mymodule'] = array('key' => 'value');

```

the value goes away when the user logs out.

If you set a cookie, using the function

```
user_cookie_save(array('key'=>'value'))

```

the value saved survives the user session.

However, I wonder if they just two of a kind (i.e. a Drupal session variable is just a cookie, but with the lifetime restricted to the duration of a the session.

Or is a Drupal session variable *not* implemented using a session cookie?

# Answer
> 8 votes
Seeing this has two votes, I'll try to explain it.

Drupal uses the built-in PHP session mechanism, which as you rightly suspect is based on a cookie. The cookie name is SESS followed by a long string of characters, and its value is another long string of characters. PHP detects this cookie and makes it available to Drupal's session implementation, which by default uses the database table `sessions` for storage, with the value of the cookie as the key `sid`.

The session entry also records the user ID: early in the Drupal bootstrap sequence the session is loaded and then the corresponding user object, which is subsequently used to govern access to resources, based on the user's roles and other attributes.

Data stored in the PHP global array $\_SESSION is automatically saved to the current session's database entry by Drupal at the end of a page request. This is typically used to store relatively transient data such as items in a shopping cart.

Other cookies can be saved and retrieved in code (including JavaScript) and they will not be affected by logout unless you specifically write code to delete them when that happens. Confusingly, cookies with an expiry time of 0 are also often termed "session cookies" - these are deleted when you shut down your browser.

There's a lot more that could be said and I'll add some good references when I have a chance.

---
Tags: sessions, cookies
---


title: Big pipe and behaviors context

text:
# Question
Title: Big pipe and behaviors context
I have problem with drupal behaviors and context in combination with big pipe. It seems like `context` variable sometimes contains same part of page. I have tried:

```
(function ($, Drupal) {
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      console.log(context);
    }
  };
})(jQuery, Drupal);

```

When I load page and watch browser console contexts there is `div` with main menu block but there is also whole `#document` element which contain menu block also (see screen).

##

This behaviour is for me real problem because I use zurb foundation and I have to initialize all components and I do it:

```
(function ($, Drupal) {
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      $(context).foundation();
    }
  };
})(jQuery, Drupal);

```

I think this is correct way how to initialize foundation for all elements and it should be compatible with big pipe. But if I get same html part in context twice (some sub elements in context are same) I initialize some zurb foundation plugin twice (see next image).

This breaks zurb foundation plugins. I'm not sure what to do. I read lot of Drupal documentation about js, behaviours and big pipe and according to documentation there should not be problem.

When I disable big pipe everything works as expected but that's not solution.

Do anybody knows what am I doing wrong?

# Answer
Alternately, using once:

```
(function ($, Drupal) {
  Drupal.behaviors.foundationInit = {
    attach: function (context, settings) {
      $(body, context).once('foundation-init').each(function() {
        $(document).foundation();
      });
    }
  };
})(jQuery, Drupal);

```
> 1 votes

# Answer
Try this

```
(function ($, Drupal) {
  Drupal.behaviors.foundationInit = {
    attach: function (context, settings) {
      if (document === context) {
        $(document, context).foundation();
      }
    }
  };
})(jQuery, Drupal);

```
> -1 votes

---
Tags: 8, javascript
---


title: How can I get the mappings from feeds

text:
# Question
Title: How can I get the mappings from feeds
I want to get programmatically the mapping which was set by the user on the feeds config page (`/admin/structure/feeds/<name>/mapping_en`). But how can I do it?

# Answer
> 0 votes
I've fount a working solution:

```
$f = feeds_importer('your-importer-machine-name');
$m = $f->processor->getMappings(); // This returns the mapping.

```

It's just needed one day to find it...

---
Tags: 7, feeds
---


title: How to load an entity definition?

text:
# Question
Title: How to load an entity definition?
I need to load an entity definition to add a constraint and test it, I found that this is possible with the following code:

```
$manager = \Drupal::entityDefinitionUpdateManager();
$entity_definition = $manager->getEntityType('node');
$entity_definition->addConstraint(‘name’);

```

But I wonder if this is the correct way or if exists another.

# Answer
> 0 votes
The only case where you want to work with entityDefinitionUpdateManager() in update and post update hooks, to update an entity type definition on existing installations to the one defined on the annotation.

To add a constraint to an entity type that's not yours use hook\_entity\_type\_alter()

---
Tags: 8, entities
---


title: What is my next step?

text:
# Question
Title: What is my next step?
I have drupal core installed on my web host server and would like to install a panopoly distribution to it now. I have uploaded and extracted the tar.gz file to my docroot and can't seem to figure out how to install panopoly now. What should my next steps be? How do I install the install.php from panapoly? When I run the www.domain.com/install.php I get the message, "Drupal has already been installed"

# Answer
> 1 votes
If your website is not configured and you just has installed a pure drupal core without any modification , then you can forget about it and install a panopoly distribution instead, I mean you don't need a drupal installed before installing that distribution. Installation is pretty easy and straight forward in this case, you can read about it here.

In the other case if you have a website installed and running using drupal and you want to add panopoly to it , then the module itself has provided a documentation about how to get it done. just follow the steps.

---
Tags: installation, distributions
---


title: Link image to new tab

text:
# Question
Title: Link image to new tab
I have a problem trying to link image teaser to open in a new tab when clicked. How do i go about that? I know in html is target="\_blank" attribute.

# Answer
One way you can do this is with `mytheme_preprocess_field` where `mytheme` is the name of your theme, inside of `mytheme.theme` file:

```
/**
 * Implements hook_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
      if ($variables['field_name'] == 'field_mylink') {
        foreach ($variables['items'] as $key => $item) {
          $variables['items'][$key]['content']['#options']['attributes']['target'] = '_blank';
        }
      }
}

```

This would add `target="_blank"` to each value entered for the link field. But you don't mention if the field is a link field or image field though.
> 1 votes

---
Tags: 8, media
---


# Question
Title: Is there a way to supress particular messages or a class of messages on the screen?
Is there a way of suppressing a particular class of messages from being displayed on the screen, such as the one displayed below?

> Deprecated function: Methods with the same name as their class will not be constructors in a future version of PHP; GeSHi has a deprecated constructor in require\_once() (line 837 of {site\_root}/sites/all/modules/libraries/libraries.module)

It comes up all the time and it belongs to the `php` and severity `debug` class of error messages.

I don't want to turn off the display of messages on the screen, just a particular class of message which come so often they are a nuisance.

It is possible to toggle their display on and off when required but still log them to the database?

# Answer
You can use Disable Messages or look how they do it. Among other features you'll get a permission to specifically hide all messages **of a given type** from any role.

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.
>
> **Features**
>
> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.

---

Apart from that I found this little gem:

```
function MYMODULE_preprocess_status_messages(&$variables) {

  // The exact message you want to filter.
  $message = 'Further instructions have been sent to your e-mail address.';

  if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $type => $messages) {

      // Limit it to a certain type if you want to.
      if ($type == 'status') {

        $pos = array_search($message, $messages);

        if ($pos !== FALSE) {
          unset($_SESSION['messages'][$type][$pos]);
        }
      }
    }
  }
}

```

Source: https://api.drupal.org/comment/51793#comment-51793

---

Here's another alternative to filter all messages of a certain type.

```
/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  $hide_types = ['status', 'error', 'warning'];

  if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $type => $messages) {
      if (in_array($type, $hide_types)) {
        unset($_SESSION['messages'][$type]);
      }
    }
  }
}

```

You could also easily get the `$account = global $user` and check its roles to tighten this request if you need.

---

Last but not least – **not recommended** \- you can remove or if-wrap the `<?php print $messages; ?>` variable in your theme's `page.tpl.php`. But editing templates for this kind of logic should be considered bad practice.
> 1 votes

---
Tags: 7, debugging
---


title: Cannot update checkbox with services

text:
# Question
Title: Cannot update checkbox with services
I have been trying several configurations for trying to update a user account checkbox to uncheck it, with no success. I have been able to check it without issue.

```
updateCharType = function (token) {

    var obj = {
        "uid": "1",
        "name": "admin",
        "field_character_type": {"und": [{"value": 0}]}
    };
    return $.ajax({
        url: 'www.example.com/endpoint/1.json',
        crossDomain: true,
        type: 'PUT',
        data: obj,
        dataType: 'json',
        headers: {
            'X-CSRF-Token': token
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log('user edit - failed to edit ' + textStatus);
            console.log(errorThrown);
        },
        success: function (data) {
            alert(success!);
        }
    });
}

```

Now, it always gets to the success portion of the code, and it *seems* like it is working correctly.

However the checkbox never gets unchecked. I've read a bunch of documentation, and tried a million different iterations of how the JSON should be formed - putting null, removing the \[\], removing the und - for some reason I am having absolutely zero luck updating this checkbox!

How do I update a checkbox on a user account with services?

EDIT:

I WAS able to get it working with a list of values for a different field:

```
 var fontSize = jQuery('#font-size').val();

    var obj = {
        "uid": "1",
        "name": "admin",
        "field_font_size": {"und": fontSize}
    };
    return $.ajax({
        url: 'http://example.com' + "/users/user/1.json",
        crossDomain: true,
        type: 'PUT',
        data: obj,
        dataType: 'application/json',
        headers: {
            'X-CSRF-Token': token
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log('user edit - failed to edit ' + textStatus);
            console.log(errorThrown);
        },
        success: function (data) {
            alert("Success for user save!:) ");
        }
    });
};

```

Differences:

How to be a list of values, and I needed to set it to application/json

Boolean field still not working under any variations.

Also, whenever I try to uncheck the checkbox I get the following error:

```
Notice: Array to string conversion in DatabaseStatementBase->execute() (line 2227 of /Users/username/Desktop/Projects/example.com/includes/database/database.inc).

```

# Answer
To un-check a check box with Services in Drupal 7 (aka setting false on a boolean field), try this:

```
"field_character_type": {"und": null}

```

I've just verified this works on my localhost (for both users and nodes), here's the payload for the **PUT**:

```
{
  uid: 1,
  name: "admin",
  field_character_type: { und: null }
}

```

And here's the path:

`api/user/1.json`

Make sure you include the `[my-endpoint-path]/user/[uid].json` for the call.

You only need to cast the data payload into a string if you're using vanilla .js and an xhr object, otherwise jQuery's `ajax` does it automatically for you.
> 2 votes

# Answer
Ultimately, the value coming through was always empty string, never null, even when I directly set it null.

The solution to my problem was this:

```
function MY_MODULE_services_request_preprocess_alter($controller, &$args, $options) {
  if(!is_null($args[1]['field_character_type']) && $args[1]['field_character_type']['und'] == "") {
      $args[1]['field_character_type']['und'] = null;
  }
}

```

That was with sending this JSON object to the server:

```
    var obj = {
        field_character_type: { und: null }
    };

```

And the services call:

```
    return $.ajax({
        url: 'http://example.com' + "/users/user/1.json",
        crossDomain: true,
        type: 'PUT',
        data: obj,
        dataType: 'json',
        headers: {
            'X-CSRF-Token': token
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log('user edit - failed to edit ' + textStatus);
            console.log(errorThrown);
        },
        success: function (data) {
            //alert("Success for user save!:) ");
        }
    });
};

```
> 0 votes

---
Tags: 7, javascript, services
---


# Question
Title: hook_views_data join table on multiple columns
I have 3 tables **lms\_user**, **lms\_answer\_initial** and **lms\_model\_answer** and need to join them to display a view on certain columns.

I can successfully join the first 2 tables (**lms\_user**, **lms\_answer\_initial** ) by using 'relationship'

```
$data['lms_answer_initial']['uid'] = array(
    'title' => t('Drupal user ID'),
    'help' => t('The Drupal user ID.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'relationship' => array(
      'title' => t('User(LMS)'),
      'help' => t('Relate content to the LMS user.'),
      'base' => 'lms_user',
      'base field' => 'uid',
      'label' => t('user'),
      'handler' => 'views_handler_relationship',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_equality',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument',
    ),
  );

```

but I has no idea how to join the third table on 3 columns.

Here is my complete code in hook\_views\_data:

```
$data['lms_answer_initial']['table']['group'] = t('LMS Answer Initial');
$data['lms_answer_initial']['table']['base'] = array(
    'title' => t('Answers (Report)'),
    'help' => t('Answers for the Learning Management System.'),
    'weight' => -10,
  );
$data['lms_answer_initial']['table']['join'] = array(
    'lms_model_answer' => array(
        'left_table' => 'lms_model_answer',
        'left_field' => 'fid',
        'table' => 'lms_answer_initial',
        'field' => 'fid',
    ),
);

  $data['lms_answer_initial']['uid'] = array(
    'title' => t('Drupal user ID'),
    'help' => t('The Drupal user ID.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'relationship' => array(
      'title' => t('User(LMS)'),
      'help' => t('Relate content to the LMS user.'),
      'base' => 'lms_user',
      'base field' => 'uid',
      'label' => t('user'),
      'handler' => 'views_handler_relationship',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_equality',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument',
    ),
  );
  $data['lms_answer_initial']['fid'] = array(
    'title' => t('File ID'),
    'help' => t('EPUB File ID.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'relationship' => array(
      'title' => t('LMS Model Answer'),
      'help' => t('Relate activity model answer.'),
      'handler' => 'views_handler_relationship',
      'base' => 'lms_model_answer',
      'base field' => 'fid',
      'label' => t('model answer'),
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_equality',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument',
    ),
  );
  $data['lms_answer_initial']['book_id'] = array(
    'title' => t('Book ID'),
    'help' => t('The book ID.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  $data['lms_answer_initial']['unit_id'] = array(
    'title' => t('Unit ID'),
    'help' => t('The unit ID.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  $data['lms_answer_initial']['activity_id'] = array(
    'title' => t('Activity ID'),
    'help' => t('The activity ID.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'relationship' => array(
      'title' => t('LMS Model Answer'),
      'help' => t('Relate activity model answer.'),
      'handler' => 'views_handler_relationship',
      'base' => 'lms_model_answer',
      'base field' => 'activity_id',
      'label' => t('model answer'),
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  $data['lms_answer_initial']['question_id'] = array(
    'title' => t('Question ID'),
    'help' => t('The question ID.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'relationship' => array(
      'title' => t('LMS Model Answer'),
      'help' => t('Relate activity model answer.'),
      'handler' => 'views_handler_relationship',
      'base' => 'lms_model_answer',
      'base field' => 'question_id',
      'label' => t('model answer'),
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );
  $data['lms_answer_initial']['answer'] = array(
    'title' => t('Answer'),
    'help' => t('The answer.'),
    'field' => array(
      'handler' => 'views_handler_field',
    ),
  );
  $data['lms_answer_initial']['is_correct'] = array(
    'title' => t('Correct'),
    'help' => t('Indicates whether the answer is correct.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
  );
  $data['lms_answer_initial']['changed'] = array(
    'title' => t('Change date'),
    'help' => t('The date when the answer was changed.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );

```

And here is the resulting query

> SELECT lms\_answer\_initial.uid AS lms\_answer\_initial\_uid, \>lms\_answer\_initial.book\_id AS lms\_answer\_initial\_book\_id, lms\_answer\_initial.unit\_id AS lms\_answer\_initial\_unit\_id, lms\_answer\_initial.activity\_id AS lms\_answer\_initial\_activity\_id, lms\_answer\_initial.question\_id AS lms\_answer\_initial\_question\_id, lms\_answer\_initial.answer AS lms\_answer\_initial\_answer, lms\_answer\_initial.is\_correct AS lms\_answer\_initial\_is\_correct, lms\_answer\_initial.fid AS lms\_answer\_initial\_fid
>
> FROM {lms\_answer\_initial} lms\_answer\_initial
>
> LEFT JOIN {lms\_user} lms\_user\_lms\_answer\_initial ON lms\_answer\_initial.uid = lms\_user\_lms\_answer\_initial.uid
>
> LEFT JOIN {lms\_model\_answer} lms\_model\_answer\_lms\_answer\_initial ON lms\_answer\_initial.fid = lms\_model\_answer\_lms\_answer\_initial.fid
>
> LIMIT 30 OFFSET 0

How to add the following condition to the query?

**lms\_answer\_initial.activity\_id = lms\_model\_answer\_lms\_answer\_initial.activity\_id and lms\_answer\_initial.question\_id = lms\_model\_answer\_lms\_answer\_initial.question\_id**

Appreciate any help on this.

# Answer
I finally get this done by following the solution here: http://eworldproblems.mbaynton.com/2014/04/drupal-views-join-on-multiple-columns/

Here is what I have actually do. In **hook\_views\_data**, add **join\_handler**:

```
'relationship' => array(
          'title' => t('Model answer relationship on fid'), //Title shown when adding the relationship
          'base' => 'lms_model_answer', //name of table to join with
          'base field' => 'fid',        //name of the field on the joined table
          'handler' => 'views_handler_relationship',
          'join_handler' => 'lms_reports_join_lms_answer_initial_lms_model_answer',
          'label' => t('model answer fid'),
          'type' => 'LEFT',
        ),

```

Then implement my own customized handler, in **\*.views.inc**:

```
class lms_reports_join_lms_answer_initial_lms_model_answer extends views_join
{
  public function build_join($select_query, $table, $view_query) {
    $select_query->addJoin('INNER', $this->table, $table['alias'], "lms_answer_initial.fid = ${table['alias']}.fid AND lms_answer_initial.activity_id = ${table['alias']}.activity_id AND lms_answer_initial.question_id = ${table['alias']}.question_id");
  }
}

```

Hope this help anyone else who encounter the same problem.
> 1 votes

# Answer
In Drupal 8 I used the following code:

```
  $data['table_a']['table_a_some_field'] => [
    'field' => [
      'id' => 'standard',
    ],
    'filter' => [
      'id' => 'numeric',
    ],
    'relationship' => [
      'id' => 'standard',
      'label' => t('Table B'),
      'base' => 'table_b',
      'base field' => 'table_b_some_field',
      'extra' => [
        [
          'left_field' => 'table_a_field_2',
          'field' => 'table_b_field_2',
        ],
      ],
    ],
  ],

```

Of course, `table_b` should be defined separately with its fields as well.
> 2 votes

# Answer
You can use hook\_views\_query\_alter(&$view, &$query).

And in this hook you can write:

$query-\>add\_where\_expression(0,'lms\_answer\_initial.activity\_id = lms\_model\_answer\_lms\_answer\_initial.activity\_id');
> 0 votes

---
Tags: database, views
---


title: Views Export button to block

text:
# Question
Title: Views Export button to block
I have a view with `Data Export`, where it creates a button to download the view's content, depending on a filter supplied by URL query parameters. I'm able to edit the the button using `THEME_views_data_export_feed_icon` in my theme's `template.php`. That's all good and works as intended.

How can I create a Drupal 7 Block that behaves just as that export button? Is it best to manually create a php block picks up the page URL/query to set as the export block link, or is there an easier way?

# Answer
If I am correct, you should have a path/url to your Data Export Views (second column, at the top, Data Export Settings \> Path). So you just need to create a block with a link to this URL in its body and it will directly launch the export procedure (no filters considered though). You may add CSS/Bootstrap class to your link and here is your nice export button in a block, which you can add anywhere in your website.
> 0 votes

---
Tags: views, blocks
---


# Question
Title: How to autoload classes from a 3rd party PHP library
I would like to use a 3rd party PHP library in my module and I wanted to ask what I need to do to autoload the classes?

Example: Drupal\my\_module\MyClass wants to instantiate ThirdPartyNamespace\Something\Else\Class1

The official Drupal 8 documentation doesn't really deal with more complex namespacing scenarios.

# Answer
> 4 votes
Drupal use composer to manage the 3rd party libraries (Symfony, guzzle, etc...). The problem is Drupal has versioned the vendor folder into the core directory; it is a problem because, if you added a new library in the root composer, you change the vendor directory and change the composer.json/composer.lock. So, if Drupal releases a new version, your changes will be deleted.

The Composer Manager module is created to solve the problem. You need to include a composer.json file in your module; the Composer Manager module downloads the library and registers a new autoload file (the second autoload).
The problem with this is only when you need use a middle-ware library, since the Composer Manager module registers a new autoload in the Request Kernel Event. This event is called after the middle-ware so this library is not available in the middle-ware layer.

In most cases, the Composer Manager module is the best solution to add new vendors.

There is the issue Remove external dependencies from the core repo and let Composer manage the dependencies instead.

# Answer
> 2 votes
I edited the composer.json in the root of my Drupal project and in the module that relies on the library. Then I loaded the main class using a fixed path:

```
require_once (\Drupal::root() . '/vendor/campaignmonitor/createsend-php/csrest_general.php');

```

Then I noticed having an issue with instantiating an object of the class:

```
$wrap = new CS_REST_General($auth);

```

So apparently you need to add a '\\' eg:

```
$wrap = new \CS_REST_General($auth);

```

# Answer
> 2 votes
Seems that the current answers are all outdated. When you use Composer to manage your project's dependencies, preferably with `drupal-composer/drupal-project`, all you need to do is to require a package in your project-root's `composer.json` and then load it's classes wherever you need them.

```
$ cd MYPROJECT
$ composer require ramsey/uuid

```

Then in your custom module just `use` it.

```
use Ramsey\Uuid\Uuid;

```

---

To let your custom module provide its own `composer.json` you can add `wikimedia/composer-merge-plugin` to your project-root's `composer.json` and in the `"extra": {}` section configure it to include other `composer.json` located at a certain directory pattern.

```
"merge-plugin": {
    "include": [
        "web/modules/custom/*/composer.json"
    ]
},

```

---

Everything else is taken care of by Drupal.

---
Tags: 8
---


title: Redirect after updating nodes

text:
# Question
Title: Redirect after updating nodes
I've to redirect users, after updating a node, to `/node/NID` path and not to `/node/NID/latest` (I'm using content moderation).

I've tried to add this on hook\_node\_update() but have been ignored (without warning or errors):

```
if (!$entity->isNew()) {
    $path = URL::fromUserInput('/node/' . $entity->id())->toString();
    return new RedirectResponse($path);
}

```

# Answer
> 1 votes
```
use \Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

function MYMODULE_node_update(Drupal\node\NodeInterface $node) {
  $path = Url::fromUserInput('/node/'.$node->id())->toString();
  $response = new RedirectResponse($path);
  $response->send();
}

```

You have to use like above. You are just returning the redirect response. You need to send redirectresponse to given path.

---
Tags: 8, redirection
---


# Question
Title: On hook_entity_presave how do I know if it is a new node?
I'm using the hook

```
function nvgh_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
}

```

but I only need to do something when the node is new (not when it is edited). How to do this? I'm inspecting the entity with kint but cannot find a good indicator for this... also kint is disappearing as the node view is redirected into view modes.

How to do this?

# Answer
Use the `Entity::isNew()` method:

```
if ($entity->isNew()) {
  // ...
}

```
> 8 votes

---
Tags: 8
---


# Question
Title: Is there a way to search Drupal's and contrib modules configuration settings?
With so many different modules in use with configuring Drupal it is hard to keep track of which settings are configured where, such as whether some CSS is set by the Code per Node or CSS Injector.

It would be nice to have search pinpoint what configuration settings contain some keyword. Does search have such a facility? I understand that the search module is mainly used by content such as nodes and entities.

But is there some way something like this can be accomplished, even by some module, or do module developers need to configure their modules settings to be indexable by search?

# Answer
Useful fact: `drush vget abc` lists all variables with 'abc' in their name. So if you are looking for settings related to css, `drush vget css` might provide you with a clue. Likewise you can use the name of a module in your search to see all the settings from that module.

Some modules have complex settings that are stored in separate database tables. In that case I recommend using a tool such as SQLyog that has a search facility which will scan an entire database, or just specific tables, for a given input string.
> 1 votes

---
Tags: 7, search, configuration
---


# Question
Title: How to restrict a view to display only 2 content types?
I have created a view (/page\_view), which displays two content types.

This view contains a contextual filter for user to be able to see only one particular content type (/page\_view/content\_type\_1 and /page\_view/content\_type\_2).

But in my case the user by typing for example /page\_view/content\_type\_3 is able to see other content types which should not be included into the current view.

How can I restrict a view to display only 2 content types?

# Answer
> 1 votes
Sounds like you need to set a filter type as well instead of just your contextual filters. So under filters choose "Content Type" and choose ONLY the content types you wish the user to see. Then the contextual filter set it to "No results found" (see screen shots)

---
Tags: views, 8
---


title: Get current URL inside ajax callback?

text:
# Question
Title: Get current URL inside ajax callback?
I have created custom module called `mymodule`.

In this URL **localhost/mymodule/name**, I have this field:

```
$form['name'] = array(
  '#title' => t('Enter name'),
  ...
  '#ajax' => array(
    'event' => 'blur',
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'my-wrapper',
    'method' => 'replace',
  ),
  ...
);

```

My ajax callback is successfully called:

```
function mymodule_ajax_callback($form, &$form_state) {
  ...
  return ...
}

```

However, inside 'mymodule\_ajax\_callback', I need to get the current URL of the page which is **localhost/mymodule/name**. Currently it returns **system/ajax** which is how Drupal works by nature.

How to get the current URL inside the ajax callback?

# Answer
As said by @Jayendra Kainthola
You need to store current path value in a session

```
$_SESSION['current_path'] = current_path();

```

Then use it inside your callback function as follows :

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

$current_path = $_SESSION['current_path']  ;//gives the current path

}

```
> 3 votes

# Answer
**$form\['#action'\]** can be used in order to meet the requirement of the **Url**. And then used as one want.

```
$form['#action']

```

Like:

```
function xyz_ajax_function($form, &$form_state){
  if(strpos($form['#action'], YOUR_URL_WANT_TO_CHECK)){
    echo 'yes';
  }else{
    echo 'no';
  }
}

```
> 1 votes

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


# Question
Title: How can I get the content type for which a certain comment belongs?
I have a comment type that's associated to various content types.

I have the comment entity but I want to get which content type(s) it belongs to.

How can I do that? Given that I can in the first place.

# Answer
You can use `Comment::getCommentedEntity()` to get the entity, and if it's a node, grab the type:

```
$entity = $comment->getCommentedEntity();
if ($entity instanceof \Drupal\node\Entity\Node) {
  $type = $entity->getType();
}

```
> 3 votes

---
Tags: 8
---


title: REST API doesn't seem to work

text:
# Question
Title: REST API doesn't seem to work
Login with CURL:

```
curl --header "Content-Type: application/json" \
--request POST \
--data '{"name":"admin", "pass":"admin"}'
http://d8.local/drupal-8.5.6/user/login?_format=json

```

Then the result:

```
{"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"LUa3_xAXC8CgDkCoDoKonAmJ8hYFF6gZTak_LpaHFco","logout_token":"90jJUh08H437-F5fU25eq7rS2b8FS22eVVy_Fcsk2TA"}

```

Look good. But when I tried to check login status:

```
curl --header "Content-Type: application/json" \
--header "X-CSRF-Token: LUa3_xAXC8CgDkCoDoKonAmJ8hYFF6gZTak_LpaHFco" \
--request GET \
http://d8.local/drupal-8.5.6/user/login_status?_format=json

```

The results is: 0. So it failed.

Same result when I did with Vue resource.

Note: Postman seems to work, but it's working like real browser without CSRF token need.

Any idea?

Thank you.

# Answer
REST API doesn't work with CURL because you don't send cookie after login. By default, Drupal 8 using HTTP Basic Authentication after the login user has a cookie. Browser (include postman) will store this cookie and send to the server any request. So It works normally.

If you want REST API working with CURL. You need to store cookie when request login, and send this cookie to check status login like this:

```
curl -c ~/cookie.txt
--header "Content-Type: application/json" \
--request POST \
--data '{"name":"admin", "pass":"admin"}'\
https://dfs3w.ply.st/user/login?_format=json

```

in line

```
-c ~/cookie.txt

```

mean that write cookie to file **cookie.txt**.

After login successfully, I will read cookie and send cookie to check status login:

```
curl -b ~/cookie.txt
--header "Content-Type: application/json" \
--header "X-CSRF-Token: -LSxwKsxEnupbeM4NANfV1JLtlGeqK0dRPxhRRSFvkU"\
--request GET \
https://dfs3w.ply.st/user/login_status?_format=json

```
> 4 votes

---
Tags: 8
---


# Question
Title: How can I show referenced terms on other term page with view
My web site has two vocabularies for event content type.
Vocabularies: City and Dance School.

School terms use city terms. I want to show school terms as a list on city term page ( Eg. Newyork Dance Schools).

My city url is ../city/newyork/145

145 is term id. I changed city/newyork url to /city/newyork/145.But it didn't work.

I tried many combinations with views & Conceptual filter&relationships but no result.

I tried this but empty results.(https://drupal.stackexchange.com/a/74605/88821).

I'm stuck on how to handle it. Any advice please..Thanks

# Answer
> 0 votes
You have to create a list of all School terms, and then use a Contextual filter to feed Views with information about the City term you're currently viewing (City page), so the School terms results can be reduced to show only the School terms that are related to that particular City.

## Build Views that list Terms that reference another Term

1. Create a View of type **Taxonomy term**, you only need the Block Display, and choose only the School terms vocabulary
2. Add a Contextual filter from `Taxonomy term` Category named after the reference field you're using on the School term Vocabulary to reference Cities
3. Configure it with these options:
`When the filter value is NOT available`
**Provide default value**
**Taxonomy term ID from URL**
**Load default filter from term page**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term**
**City**
`Filter value type`: **Term ID**
4. Save the View (adjust other options if you wish) and place the Block in a region of your theme, limit Visibility to show only on City term pages.

You should now see the list of School terms on city pages that relate to that City.

## Test Contextual filter from Views UI

To test the Contextual filter while building Views you can use the `Preview with contextual filters:` field.

Enter `all` and press the `Update preview` button to see all results irrespective of the Contextual filter.

Enter the number of a City term TID to see the School terms related to it. For example if the term `newyork` has the TID 16 enter `16` into the Preview field, and you'll see the School term list is reduced to only those which reference newyork.

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


title: Dynamic Menu with Views

text:
# Question
Title: Dynamic Menu with Views
Background: This is not the first question asked around here. I thought I found a solution but nothing worked in the end.

I have 2 content type: **Parent** and **Child**

**Child** possess 2 Entity Reference(ER) fields, **Section** and **Parent(ER)**

**Section** is linked to a **Parent** node, **Parent(ER)** is linked to another **Child** node, allowing for 3 level of Hierarchy, level 1 being a **Parent** node, level 2 being a **Child** node with a **Section**, level 3 being a **Child** node with a **Section** and a **Parent(ER)**. I have created a **Child** node name NONE and use it as default for **Parent(ER)** to easily distinguish between level 2 (with no **Parent(ER)**) and level 3 (with a **Parent(ER)**) nodes.

I'm currently trying to build the menu for **Child** pages using multiple views providing data. Currently, I have the **Parent(ER)** section of said menu down, as it's pretty easy to build. The problem comes when I try to create the Siblings. Here is the requirement for this view:

* I need to list all level 2 **Child** nodes, so the ones with a **Section** but no **Parent(ER)** (already dealt with using a conditional filter on **Parent(ER)** and checking for all pages with the NONE nid.)
* I need to remove the currently displayed **Child** node as it's already present elsewhere
* I need to print **ONLY** **Child** with the same **Section** as the current node

I can't find the contextual filter/relationship combination to achieve my goal.

How can I achieve this?

# Answer
Your levels are a bit confusing, I'm guessing it's to do with your project structure and doesn't provide relevant information about the reference hierarchy, so I'll just rely on the information you provided about which entity references which.

## list all Child nodes with a ref to Section but no Parent(ER)

Even though you already solved this the solution that first comes to my mind is to list all Child pages where the ER field to Section isn't empty, and the ER field towards Parent(ER) is empty. No need for special NONE nodes.

You can do this by adding a Filter for each of those ER Fields and setting the Operator to `Is empty (NULL)` and `Is not empty (NOT NULL)` respectively.

## Remove the current node from the list

Add a Contextual filter **ID** from the `Content` Category and configure it with these options:
`When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`More`
**Exlude**

## List siblings relating to same node through ER

To list siblings you first need one Relationship to get to the parent of the ER relationship (in your case Section), then another Relationship in reverse direction that is using the first one to find all other children of the parent. Then configure a Contextual filter to use the second Relationship, that is the one that is identifying siblings.

1. Add a Relationship **Content referenced from field\_section** (or however it's called in your particular case), you can require it, this introduces the Section into the Views.
2. Add another Relationship **Content using field\_section**, set it to **use the Relationship from the previous step**, you can require it. This is the reverse direction, pointing to all children that are pointing to this parent (Section).
3. Add a Contextual Filter **ID** from **Content** Category and set it to use the **second relationship** (field\_section) and configure:
`When the filter value is NOT available`
**Provide default value**
**Content ID from URL**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Child**
4. If this is a Block Display place it on Child nodes and it will show other children that relate to the same Section.

To check the Contextual filter with Views Preview, enter the NID of the Child node you want to simulate, and enter it for each Contextual filter.

If you have both the contextual filter that identifies siblings and the one that excludes the current node from the list (and the Child NID is 24) enter `24/24`.

If you want to see all the results, unaffected by Contextual filters enter `all/all`.
> 1 votes

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


# Question
Title: How to make mymodule_preprocess_node run only once?
We have a custom `mymodule` that calls `mymodule_preprocess_node(&$variables)` hook. When we add `ksm($variables);` to the hook, we are finding the message is printed multiple times (average has been 5x).

How to make `mymodule_preprocess_node` run only one time?

I am needing to run this hook because I want to check to see if a field is populated with some value then perform some other logic.

Example:

```
function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  if(isset($node->get('field_link'))) {
    // perform some logic.

   ksm('in here'); // printed multiple times.
  }
}

```

# Answer
> 2 votes
I found the issue. As @Kevin mentioned, it was being called for every node being rendered. I added a condition to check the view more as well and it is being called just one time now.

```
function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  if(isset($node->get('field_link')) && $variables['elements']['#view_mode'] == 'my_view_mode') {
    // perform some logic.

   ksm('in here'); // printed once as expected
  }
}

```

---
Tags: 8, hooks
---


title: How do I render a form with JavaScript?

text:
# Question
Title: How do I render a form with JavaScript?
I'm trying to render a Drupal 8 modal dialog form through JavaScript, so it can appear on multiple pages across my site. In the controller class, I create an `AjaxResponse` object with an `openModalDialogCommand` for the modal form. I want to render the modal dialog through JavaScript, so that I can control in which pages it displays.

```
$(document).ready(function() {
  $('body').append('<div id="ao-interstitial-modal"></div>');
  console.log(Drupal);
  jQuery('#ao-interstitial-modal').load('/aao_additions/modal_form');
});

```

This the JavaScript code I write so far, but it renders a textarea in the body tag with the AJAX command object as text inside it.

What do I need to do to render the form as a dialog popup?

# Answer
Loading a form via ajax is no different then loading any other page with ajax. The quick answer is that you should create a route to display the form and then call that route via ajax but for a detailed description you should take a look here: https://www.drupal.org/node/2046693
> 1 votes

---
Tags: 8, javascript, ajax
---


# Question
Title: Editing text above downloadable products
I am trying to change the intro text above a form for downloadable products in Drupal Commerce, it needs a privacy policy link. I didn't create the website and I can't find where the text is generated.

I've tried a plugin that integrates a checkbox, but this website doesn't use commerce checkout. I've been trying for hours adding fields, fieldgroups, modules and what not.. but I can't even find where the intro text is! I'm used to Wordpress, Joomla, Grav and Open cart - complete Drupal newb though.

Can anyone point me in the right direction or tell me what steps I should take?

# Answer
> 0 votes
Unfortunately, we won't be able to help you solve this. The interface on that site for purchasing products has been custom developed for you, and it's likely that the text in there is hard coded in a site-specific customizations module. If you have access to the codebase, you can confirm this by searching all the files (via a command line tool called grep) for a unique phrase like *"UV and EB"*.

---
Tags: commerce
---