# Question
Title: Form API + AJAX - Form doubles itself on submit
I've been looking for an answer to this for hours now.

A) No matter what I do, the form will always be visible again after submit. How can I stop the from from displaying after a successful submit?

B) If there are validation errors, the form will attach to the existing form, resulting in 2,3,4,5,.. forms on the page. How to stop that?

This is the code:

```
function agals_support_form($form, &$form_state) {
$form['wrapper'] = array("#markup" => "<div id='status'></div>");

$form['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
  '#default_value' => '',
  '#maxlength' => '128',
  '#required' => TRUE,
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('submit'),
  '#ajax' => array(
    'callback' => 'agals_support_form_ajax_handler',
    'effect' => 'fade',
    'wrapper' => 'status',
  ),
);

if(isset($form_state['values']['name'])) { //output
  $form['form_output'] = array(
    '#prefix' => '<p>',
    '#suffix' => '</p>',
    '#markup' => t('You entered @value', array('@value' => $form_state['values']['name'])),
  );
} } return $form; }

function agals_support_form_submit(&$form, &$form_state) {
  watchdog('agals_support', 'submitted');
  drupal_set_message('Form submitted');
  $form_state['rebuild'] = TRUE;
}

function agals_support_form_validate(&$form, &$form_state) {
  watchdog('agals_support', 'validation');
  if (empty($form_state['values']['name'])) {
    watchdog('agals_support', 'name missing');
    form_set_error('name', t('Please enter your name.'));
  }
}

function agals_support_form_ajax_handler(&$form, &$form_state) {
  watchdog('agals_support', 'ajax_handler');
  return $form;
}

```

# Answer
The issue you are facing is that you are not wrapping your form with the wrapper div, you're prepending a div to your form. When the ajax form is loaded, it is inserted into this wrapper div, rather than replacing the contents of the form.

Change this:

```
$form['wrapper'] = array("#markup" => "<div id='status'></div>");

```

To this:

```
$form["#prefix"] = "<div id='status'>";
$form["#suffix"] => "</div>";

```

This will wrap your form in the #status div.
> 0 votes

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


# Question
Title: How to split money between the site owner and the vendor
It have complete multi vendor system with each vendor registering and adding products(Drupal8+commerce). The total sell amount was to be splitted between the site admin and the vendor account. Admin should have right to set commision(Globally 20% commision amount I have imposed on each vendor) also admin can change the commision amount for specific vendor.

The main feature I needed to implement was the money splitting between the site owner and the vendor.

Users can checkout and buy products, typically from multiple vendors at one go. Upon successful checkout and payment, the entire payment is to be taken into the site admin’s account. Then from the total account, each merchant’s sales amount is calculated (as per products that has been checked out) and then from that site admin’s sales commission is calculated. Rest, will be paid to the vendor after the deduction of the site’s commission.

If the order value of the product is 100rs then site owner must have 20rs and vendor 80rs.

Any idea about how to proceed with it?

# Answer
Maybe have a look at affiliate systems to see if they can guide you in the direction of a solution, e.g. https://www.drupal.org/project/commerce\_affiliate. The issue here is that you haven't defined what your actual end goal is - if you simply want to know what the 80/20 split of the sale value is, you can just use https://www.drupal.org/project/computed\_field. Do you want to add the split values up? Maybe use the Computed Field module, and a view? Or is the intention to automate the payouts to each party? Because that is a whole different story...
> 1 votes

# Answer
It's on the plan. I am waiting for some customer to request this feature: https://www.drupal.org/project/commerce\_marketplace/issues/3017762
> 0 votes

---
Tags: 8, commerce
---


title: Dynamic local tasks - caching problems

text:
# Question
Title: Dynamic local tasks - caching problems
I try to create some local second level tasks depending on some settings for a custom entity. But unfortunately sometimes these local tasks do not appear - they appear again when rebuilding caching and first level tabs appear but not these dynamically created second level tabs.

What I have done (the entity type name is "parliament\_period"):

In mymodule.links.task.yml

```
entity.parliament_period.canonical:
  route_name: entity.parliament_period.canonical
  base_route: entity.parliament_period.canonical
  title: 'Overview'

entity.parliament_period.edit_form:
  route_name: entity.parliament_period.edit_form
  base_route: entity.parliament_period.canonical
  title: 'Edit'

entity.parliament_period.local_tasks:
  deriver: 'Drupal\mymodule\Plugin\Derivative\ParliamentPeriodDynamicLocalTasks'
  weight: 100

```

The class looks the following:

```
class ParliamentPeriodDynamicLocalTasks extends DeriverBase  implements ContainerDeriverInterface {

  /**
   * @var \Drupal\Core\Routing\CurrentRouteMatch
   */
  protected $currentRouteMatch;

  /**
   * @var ParliamentPeriod|null
   */
  protected $parliamentPeriod;

  /**
   * DynamicLocalTasks constructor.
   *
   * @param \Drupal\Core\Routing\CurrentRouteMatch $current_route_match
   */
  public function __construct(CurrentRouteMatch $current_route_match) {
    $this->currentRouteMatch = $current_route_match;
    $this->parliamentPeriod = $this->currentRouteMatch->getParameter('parliament_period');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('current_route_match')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    if (!$this->parliamentPeriod instanceof ParliamentPeriod) {
      return [];
    }

    // Implement dynamic logic to provide values for the same keys as in example.links.task.yml.
    $this->derivatives['entity.parliament_period.default']['title'] = 'Details';
    $this->derivatives['entity.parliament_period.default']['provider'] = $base_plugin_definition["provider"];
    $this->derivatives['entity.parliament_period.default']['route_name'] = 'entity.parliament_period.canonical';
    $this->derivatives['entity.parliament_period.default']['parent_id'] = "entity.parliament_period.canonical";

    if ($this->parliamentPeriod->isElection()) {
      $this->derivatives['entity.parliament_period.candidacies']['title'] = "Candidacies";
      $this->derivatives['entity.parliament_period.candidacies']['provider'] = $base_plugin_definition["provider"];
      $this->derivatives['entity.parliament_period.candidacies']['route_name'] = 'entity.parliament_period.candidacies';
      $this->derivatives['entity.parliament_period.candidacies']['parent_id'] = "entity.parliament_period.canonical";

      $this->derivatives['entity.parliament_period.constituencies']['title'] = "Constituencies";
      $this->derivatives['entity.parliament_period.constituencies']['provider'] = $base_plugin_definition["provider"];
      $this->derivatives['entity.parliament_period.constituencies']['route_name'] = 'entity.parliament_period.constituencies';
      $this->derivatives['entity.parliament_period.constituencies']['parent_id'] = "entity.parliament_period.canonical";
    }

    if ($this->parliamentPeriod->isLegislature()) {
      $this->derivatives['entity.parliament_period.committees']['title'] = "Committees";
      $this->derivatives['entity.parliament_period.committees']['provider'] = $base_plugin_definition["provider"];
      $this->derivatives['entity.parliament_period.committees']['route_name'] = 'entity.parliament_period.committees';
      $this->derivatives['entity.parliament_period.committees']['parent_id'] = "entity.parliament_period.canonical";

      $this->derivatives['entity.parliament_period.committees']['title'] = "Mandates";
      $this->derivatives['entity.parliament_period.committees']['provider'] = $base_plugin_definition["provider"];
      $this->derivatives['entity.parliament_period.committees']['route_name'] = 'entity.parliament_period.mandates';
      $this->derivatives['entity.parliament_period.committees']['parent_id'] = "entity.parliament_period.canonical";
    }

    return $this->derivatives;
  }

```

}

# Answer
Derivatives are only rebuilt on a cache clear or when you call

```
\Drupal::service('plugin.manager.menu.local_task')->clearCachedDefinitions()

```

on changed configuration or content, but not on a regular request, this would be too slow.

Fully dynamical would be a LocalTaskDefault plugin, which you add to the yaml file:

*mymodule.links.task.yml*

```
mymodule.my_example_tab:
  route_name: default.static.route.name
  title: 'Default Static Title'
  base_route: example.base_route
  class: '\Drupal\mymodule\Plugin\Menu\MyLocalTask

```

The plugin class:

```
class MyLocalTask extends LocalTaskDefault {

  public function getRouteName() {
    return 'dynamic.route.name';
  }

  public function getTitle() {
    return 'Dynamic Title';
  }
}

```

The plugin doesn't need to have annotations, because it is discovered through the yaml file.

A local task can be assembled by information of all three methods at the same time, for example you could define the base route in a static yaml, the title in a derivative depending on a content entity and the route name in a plugin depending on dynamic conditions of the request.
> 3 votes

# Answer
An alternative approach for your use case: Instead of using a deriver for the local tasks that is trying to evaluate the entity, just add all the local tasks statically. The evaluation of whether to show these tasks on your entity will then be delegated to the access check of their routes. If the current user doesn't have access to the routes, the local task won't be shown.

So your `mymodule.links.task.yml` may contain local tasks for all possible tabs including default, your candidacies, constituencies, committees and mandates.

For brevity, below just an example for the candidacies. You may extend it for all your remaining local tasks/routes:

```
entity.parliament_period.candidacies:
  route_name: entity.parliament_period.candidacies
  base_route: entity.parliament_period.canonical
  title: 'Candidacies'

```

When checking the access, you can use a custom controller or a dedicated EntityAccessControlHandler with according operations, if you defined your local tasks' links/forms as such within your entity annotation.

Here an extendable example with a custom controller. Define a custom access callback for your routes in `mymodule.routing.yml`:

```
entity.parliament_period.candidacies:
  path: '/my-path/{parliament_period}/candidacies'
  defaults:
    [...]
  options:
    parameters:
      parliament_period:
        type: 'entity:parliament_period'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\ParliamentPeriodController::accessCandidacies'

```

The access callback `accessCandidacies` receives the very same URL parameters as your route callback/form. Above options specify the `{parliament_period}` parameter as placeholder for your custom entity.

The callback checks the condition on the parliament period and returns an according AccessResult object. To cache it for your entity and in below example the current user only, you can add both as cache context dependency.

`src/Controller/ParliamentPeriodController.php`:

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\mymodule\Entity\ParliamentPeriodInterface;

/**
 * My parliament controller.
 */
class ParliamentPeriodController extends ControllerBase {

  /**
   * Check access to candidacies.
   *
   * @param \Drupal\mymodule\Entity\ParliamentPeriodInterface $parliament_period
   *   My parliament period.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   Access check result.
   */
  public function accessCandidacies(ParliamentPeriodInterface $parliament_period) {
    $account = $this->currentUser();

    return AccessResult::allowedIf(
      // Your original condition.
      $parliament_period->isElection()
      // Optional check for user permissions.
      && $account->hasPermission('view parliament_period')
    )
      ->addCacheableDependency($parliament_period)
      ->cachePerUser();
  }

}

```

(I made the assumption, that you defined an interface for your custom entity as well. You need to adapt the controller, if not.)
> 2 votes

---
Tags: 8, navigation, caching
---


title: Alter add to cart message

text:
# Question
Title: Alter add to cart message
How to alter the message shown - "xyz" added to your cart, when we add an item to cart in Drupal 8 Commerce 2x.

I saw `Drupal\commerce_cart\EventSubscriber` where the function `displayAddToCartMessage(CartEntityAddEvent $event)` is written which is responsible for showing the message, is there any method to override it.

# Answer
Install the *Commerce Extended Quantity* module and then implement a **HOOK\_xquantity\_add\_to\_cart\_qty\_prices\_msg\_alter()**: https://github.com/drugan/commerce\_xquantity#an-item-added-to-your-cart-message-alter
> 0 votes

---
Tags: commerce
---


title: SKU already in use

text:
# Question
Title: SKU already in use
I just installed commerce on Drupal 8. I created a Store, Product Type, and a few products. When I was creating the products I was often getting an error message that the sku was already in use. If I create a view based on the Product Variations and show "sku" and "Product Variation Title" I the result shows that there are skus that are not associated with a Product Variation Title. In these cases there are multiple listings of the same sku with different UUID and IDs. I am manually entering the sku on the product add form. The unassociated skus are sequential to the sku I did enter when I created products. What did I do wrong?

# Answer
Install the Commerce Bulk module and create or change your SKUs in bulk. Also, I'd recommend to check if you have any orphaned variations (no parent product) which are legal in Drupal Commerce 2.x but has no any UI to manage them. If you are sure that those should not exist on your site then just delete them all: https://www.drupal.org/project/commerce\_bulk/issues/3027034#comment-12933162
> 1 votes

---
Tags: commerce
---


# Question
Title: How to bulk update (delete) Product Variations
I want to bulk select **product variations for deletion**, just like we can do with content and products in admin.

I tried to duplicate the products admin view, and also creating my own, both throw various error pages. It seems there is a security system in place to prevent variation deletion outside of the product pages?

Is there any way to accomplish this?

This is error I get if I add and use a bulk update field (the view is getting "product variations")

```
    The website encountered an unexpected error. Please try again later.
Error: Call to a member function getPlugin() on null in Drupal\views\Plugin\views\field\BulkForm->viewsFormSubmit() (line 372 of core/modules/views/src/Plugin/views/field/BulkForm.php).

```

# Answer
> 1 votes
Seems now you know the answer :)

https://www.drupal.org/project/commerce\_bulk/issues/3023651

BTW, thank you for your contribution to the module!

---
Tags: 8, commerce
---


title: Adding Price Attributes

text:
# Question
Title: Adding Price Attributes
I am searching how to add price values to existing product attributes in Drupal Commerce 2.X

For Example: T-shirt price = $10.00
A product variation/color = Red = +$2.00
A product variation/size = Large = +$3.00
Choosing the Red would increase the price to = $12.00
And Choosing the Large would increase the price to = $15.00
Is there a way to accomplish this in Drupal 8?
In Drupal 7 there was a module called Commerce Product Attributes that allowed the Admin to add ADDITIONAL pricing after choosing an attribute to the already set pricing.
Ex. Set Price = $10.00 // Selecting a Product Attributes with a price value of $5 would then increase the total cost due at checkout to $15.00

# Answer
> 0 votes
Seems now you know the answer :)

https://www.drupal.org/project/commerce\_bulk/issues/3035971

---
Tags: 8, theming, commerce
---


# Question
Title: Commerce limit the quantity of product to 1
I want to restrict quantity for certain products. Want to add a product only once in cart. How to achieve this?

There are 3 products in my store and I want the users to add only 1 product in the cart at a time.

Which hook do I need to use?

# Answer
What you will want to do is add an event subscriber to the Add to Cart event (https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/cart/src/Event/CartEvents.php#L30).

Here is an example piece of code that would react to that event. This is for a Drupal Commerce site which only allowed purchasing one product at a time with a quantity of one.

```
/**
 * Sets quantity to 1 and ensures only one product in the cart.
 *
 * @param \Drupal\commerce_cart\Event\CartEntityAddEvent $event
 *   The cart event.
 */
public function onProductAdded(CartEntityAddEvent $event) {
  // We only want 1 quantity.
  $cart = $event->getCart();
  $added_order_item = $event->getOrderItem();
  $cart_items = $cart->getItems();
  foreach ($cart_items as $cart_item) {
    if ($cart_item->id() != $added_order_item->id()) {
      $cart->removeItem($cart_item);
      $cart_item->delete();
    }
  }

  $quantity = $cart_items[0]->getQuantity();
  if ($quantity > 1) {
    $cart_items[0]->setQuantity(1);
  }

  $cart->save();
}

```
> 5 votes

# Answer
Install the https://www.drupal.org/project/commerce\_xquantity and set the **max** property on the **/admin/commerce/config/order-item-types/YOUR\_TYPE/edit/form-display/add\_to\_cart** page to 1 or any other value. So, once at a time clicking on the *Add to cart* button or editing quantity on the **/cart** page a customer can't add more than **max**.

But if you want overall to restrict the quantity on some variation then install the **Commerce Extended Quantity Stock**, the submodule of the above module. See more: https://github.com/drugan/commerce\_xquantity/tree/8.x-1.x/modules/xquantity\_stock#commerce-extended-quantity-stock
> 2 votes

---
Tags: 8, commerce
---


title: How to create a teaser of a product

text:
# Question
Title: How to create a teaser of a product
I want to create a product catalog in drupal 8 commerce 2.

I have some products created, I also created a database index and in the view (Home\>Administration\>Structure\>Views) I want to show 'rendered entity'(product teaser) instead of fields, because the variation field contains image, color, size... and I just want to display image, title and price in the catalog.

I tryed creating a new content type with a field 'Remote ID' but I have an error enabling this field, PluginNotFoundException, and I didn't found any solution.

So, I don't know how to create a teaser for a product without create a content type (or fixing the PluginNotFoundException).

# Answer
> 0 votes
You can render individual fields from the variation, setting up a relationship in the View Advanced Section: Product uses variations.

After the relationship is set, then you can select what fields you need to display, filter or order the view results.

# Answer
> 0 votes
It is easy to do with the **Commerce Quick Purchase** module. Just add any number of *Quickly add any product to cart* blocks and set the inline or your custom template to display a variation in the block. See more: https://github.com/drugan/commerce\_quick\_purchase#inline-template

---
Tags: 8, commerce
---


# Question
Title: Commerce, different price based on quantity
Is that even possible?

I read that Drupal 7 has some discount modules for that, but Drupal 8 doesn't have anything. Is that true? And maybe someone can point me in the right direction how to achieve this goal...

I have found this post: Drupal Commerce - product attribute price based on quantity which suggests using https://www.drupal.org/project/commerce\_price\_table module but nothing for Drupal 8.

# Answer
You can set a Promotion based on Product's quantity if that's what you're looking for. Just give a go to commerce\_promotion module (included in Commerce 2.x core) and enable set conditions as on the picture below.
> 1 votes

# Answer
Try the **Commerce Extended Quantity** module price adjustments for a current quantity in the cart: https://github.com/drugan/commerce\_xquantity#quantity-price-adjustments
> 1 votes

---
Tags: 8, commerce
---


title: Related block by entity reference

text:
# Question
Title: Related block by entity reference
I have a 2 content types.

1. Article
2. Page

and the Article content type can reference pages from an entity reference field.

Now I want to display a block on Article nodes that have a same reference.

So I tried this:

1. Create a views block listing Articles.
2. Add some fields.
3. Add a relationship `field_page_reference: Content`
4. Add contexual filters of `Content Id` and provide default value to **Content Id From URl** and **Specify validation criteria** set to Content and select article.

But it doesn't work? Any idea?

# Answer
> 0 votes
You're on the right track, but you're missing another Relationship.

You've added the Relationship that points to a referenced Page. Now you can show that Page info in your views, but that isn't what you want. You want to show all other articles that reference that page (siblings).

To do that you need to add another Relationship that goes in reverse, from Page back to article: **Content using field\_page\_reference** and make it use the first Relationship (this is where the matching is happening!).

Then modify your ID Contextual filter to use the *second* Relationship.

Now you'll have a list of all articles that reference the page that is referenced on the article you're currently viewing.

---

That includes the current article BTW, so if you want to exclude it from the list you have to add *another* ID Contextual filter "Content Id From URl" but don't use any Relationships and under `More` select **Exclude**.

---
Tags: views, 8, entities
---


# Question
Title: How do I programatically get access to the file uploaded to a webform after a submission?
1. I am using business rules custom action to access the submission data on entity insert.
2. I am able to get the file id and ultimately the realpath.
3. the real path is `sites/default/files/private/webform/[webform_name]/_sid_/[file_name]`.
4. When I try to attach this file it is as if it were not there and ultimately gets moved into sites/default/files/private/webform/\[webform\_name\]/\[webform\_submission\_id\]/\[file\_name\].
5. I have tried to use the above path but it as if the file had not been written yet.
6. After the action has been completed I can attach the file with no problem.

The issue I am having is how can I get this illusive file and attach it to an email pragmatically.

here is the snipet of code that will generate the `"/_sid_/"` path

```
$file_id = $event['entity']->getData()[$file_field];
$file = \Drupal\file\Entity\File::load($file_id);
$realpath = \Drupal::service('file_system')->realpath($file->getFileUri());

```

Thank you for your responses and help on this.

# Answer
> 0 votes
Well, as first posts go, it ended up as a "stupid" mistake on my end. The webfrom module is well documented and the solution was very straight forward. (In short I was pushing an array into the -\>AddAtachment method in PHPMailer.) For reference to anyone else here is my working code:

**\[module\_name\]\src\Plugin\BusinessRulesAction\SMTPAuthEmail.php**

```
namespace Drupal\[module_name]\Plugin\BusinessRulesAction;
use Drupal\[module_name]\Controller\[module_name]Controller;
use Drupal\business_rules\ActionInterface;
use Drupal\business_rules\Events\BusinessRulesEvent;
use Drupal\business_rules\ItemInterface;
use Drupal\business_rules\Plugin\BusinessRulesActionPlugin;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render;
use Drupal\Core\File\FileSystem;
use Drupal\file\Entity\File;

```

```
class SMTPAuthEmail extends BusinessRulesActionPlugin {
    public function getSettingsForm(array &$form, FormStateInterface $form_state, ItemInterface $item) {
        //var_dump($item);
        $settings['email_settings'] = [
            '#type'          => 'fieldset',
            '#title'         => t('Email Settings'),
        ];
//this is just to show that I have a form for business rules that is being referenced later below.

```

```
    public function execute(ActionInterface $action, BusinessRulesEvent $event) {
    $send_email = new [module_name]Controller;
    $message = $action->getSettings();
    $css = file_get_contents(drupal_get_path('module', '[module_name]') . '/css/email.css');
    $entity_type = $event['entity']->getEntityTypeID();
    $node_storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $node = $node_storage->load($event['entity']->id());
    $build = $view_builder->view($node, 'table');
    $file_fields = $event['entity']->getWebform()->getElementsManagedFiles();
     if($file_fields){
        foreach ($file_fields as $file_field) {
            if (!empty($event['entity']->getData()[$file_field])) {
                $file_id = $event['entity']->getData()[$file_field];
                $file = \Drupal\file\Entity\File::load($file_id);
                $realpath = \Drupal::service('file_system')->realpath($file->getFileUri());
                $message['attachment'][] = $realpath;
            }
        }
    }
    $message['body'] = '<style>' . $css . '</style>' . render($build);
    $send_email->smtp_email($message);

}

```

**\[module\_name\]\src\Controller\[ModuleName\]Controller.php**

```
class [ModuleName]Controller extends ControllerBase {

    public function smtp_email($data) {

        $mail = new PHPMailer();
        $mail->IsHTML(true);
        $mail->IsSMTP(); // enable SMTP
        $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = true; // authentication enabled
        if($data['tls']){
            $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
        }
        $mail->Host = $data['host'];
        $mail->Port = $data['port']; // or 587

        $mail->Username = $data['username'];
        $mail->Password = $data['password'];
        $mail->SetFrom($data['from']);
        $mail->Subject = $data['subject'];
        $mail->Body = $data['body'];
        if(isset($data['attachment'])) {
            foreach ($data['attachment'] as $attachment) {
                $mail->AddAttachment($attachment);
            }
        }
        foreach(explode(";",$data['to']) as $recipient) {
            $mail->AddAddress($recipient);
        }
        if(!$mail->Send()) {
            $message = "Mailer Error: " . $mail->ErrorInfo;
            $message_type = 'error';
        } else {
            $message =  "Message has been sent";
            $message_type = 'notice';
        }
        \Drupal::messenger()->addMessage(t($message), $message_type);
    }

}

```

I hope this helps someone!

---
Tags: webforms
---


title: How do I include an affiliate script?

text:
# Question
Title: How do I include an affiliate script?
I am trying to add an affiliate script to my Drupal 7 website. I am doing this in a custom block.

Specifically, I create a block, select the scripts text format in my WYSIWYG Editor, add the script and save. I then add the block to the page I want.

This seemed to work for a few months and then suddenly, it disappeared and stopped working (probably due to an update).

The script has the below format:

```
<script src="https://sbhc.portalhc.com/123456/searchbox/234567"></script>

```

I have tried adding the code using all text formats (Plain Text, Scripts, Full HTML etc.). I've also tried adding it using one text format and then switching to another. I've also tried adding it through the Source button on the WYSIWYG editor.

As confirmed above, the script did work for a few months before disappearing and no extra modules have been added. I can confirm the script is correct because I can see what it generates on the provider portal.

# Answer
> 0 votes
If you don't want to code it manually, you can check this module JS injector which lets you inject JS code into your site.

> Allows administrators to inject JS into the page output based on configurable rules. It's useful for adding simple JS tweaks without modifying a site's official theme - for example, a 'nighttime' color scheme could be added during certain hours. The JS is added using Drupal's standard drupal\_add\_js() function and respects page caching, etc.
>
> This module is definitely not a replacement for full-fledged theming, but it provides site administrators with a quick and easy way of tweaking things without diving into full-fledged theme hacking.
>
> The rules provided by JS injector typically are loaded last, even after the theme JS, although another module could override these.

---
Tags: 7, javascript, blocks, wysiwyg, input-formats
---


title: How do i display format_interval?

text:
# Question
Title: How do i display format_interval?
In Drupal 8 I am using

```
$date_service = \Drupal::service('date');
$options = drupal_map_assoc(array(900, 1800, 3600, 7200, 10800, 21600, 32400, 43200,
  64800, 86400, 172800, 259200, 604800, 1209600, 2419200), array($date_service, 'formatInterval'));

```

But this gives me error

> Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "date". Did you mean one of these: "theme.negotiator.system.db\_update", "entity.definition\_update\_manager", "date.formatter", "update.post\_update\_registry", "update.post\_update\_registry\_factory", "access\_check.db\_update", "access\_check.update.manager\_access", "update.manager", "update.processor", "update.fetcher", "update.root"? in Drupal\Component\DependencyInjection\Container-\>get() (line 161 of /Applications/MAMP/htdocs/drupal-8.0.x-dev/core/lib/Drupal/Component/DependencyInjection/Container.php).

What wrong am i doing? Am i missing use class something like this use Drupal.... or something wrong in line `$date_service = \Drupal::service('date');`

# Answer
> 2 votes
My piece of working code:

```
$time_intervals = array(30, 3600, 10800, 21600, 43200, 86400, 172800, 259200, 604800, 1209600, 2592000, 5184000, 7776000);

$options = $this->build_options($time_intervals);

```

Also i have defined following function in the same class:

```
function build_options(array $time_intervals, $granularity = 2, $langcode = NULL) {
  $callback = function ($value) use ($granularity, $langcode) {
    return \Drupal::service('date.formatter')->formatInterval($value, $granularity, $langcode);
  };

  return array_combine($time_intervals, array_map($callback, $time_intervals));
}

```

# Answer
> 1 votes
There is no default service for date in drupal 8, but it has service for date formatter, you could do that simply with following code,

```
\Drupal::service('date.formatter')->format($date, 'date_text');

```

For more formatting check the article

# Answer
> 1 votes
The code contains two errors, since Drupal 8

* doesn't have any *date* service
* doesn't define any `drupal_map_assoc()` function

The equivalent of Drupal 7 `format_interval($interval, $granularity = 2, $langcode = NULL)` is `\Drupal::service('date.formatter')->formatInterval($interval, $granularity = 2, $langcode = NULL)`, which also works on Drupal 8.0.x.

If you need to write code that given an array like `[30, 60]` returns an array like `[30 => '30 seconds ago', 60 => '1 minute ago']`, this is the code I would use.

```
$time_intervals = [30, 3600, 10800, 21600, 43200, 86400, 172800, 259200, 604800, 1209600, 2592000, 5184000, 7776000];

$options = build_options($time_intervals);

function build_options(array $time_intervals, $granularity = 2, $langcode = NULL) {
  $callback = function ($value) use ($granularity, $langcode) {
    return \Drupal::service('date.formatter')->formatInterval($value, $granularity, $langcode);
  };

  return array_combine($time_intervals, array_map($callback, $time_intervals));
}

```

# Answer
> 0 votes
For those who got here by searching how to use **formatInterval** to override a field value here is how it could be done:

```
$interval = time() - strtotime('time string loaded from entity');
$interval = \Drupal::service('date.formatter')->formatInterval($interval, 2);
$output = t('Was found @interval ago', array('@interval' => $interval));

```

The solution above is multilingual friendly, translate the text in **User interface translation**

---
Tags: 8, datetime
---


# Question
Title: Support composer_manager AND drupal-composer/drupal-project with contrib module
## Motivation / use case

I maintain the module package https://drupal.org/project/cfr, which currently requires composer\_manager to be installed, and where composer\_manager is required in the \*.info files of some of the submodules.

Now I also want to support sites that install all their modules via composer, e.g. using https://github.com/drupal-composer/drupal-project.

However, the auto-generated composer.json files now require composer\_manager, because they are generated from the \*.info files.

composer\_manager is undesirable in this context and even creates a conflict with composer\_autoloader which is required by drupal-composer/drupal-project.

One specialty here is that there is no actual module named 'cfr', all the modules in the package are submodules like 'cfrapi', 'cfrplugin', 'cfrplugindiscovery' etc. This may or may not be a good choice, but it is how it is now.

## Technical observations

I found, by looking into ~/.composer/cache/repo/https---packages.drupal.org-7/\*, that Composer / packages.drupal.org creates "meta packages" for submodules.

Even if the submodule already has a composer.json file, this is replaced with a generated composer.json file that requires only the module dependencies from the \*.info file, not the 3rd party dependencies from the composer.json file.

This means: \- The meta packages do require modules like drupal/xautoload and drupal/composer\_manager. \- The meta packages do NOT require vendor libraries like donquixote/annotation-parser anymore. \- The main package 'cfr' seems like a combination of the meta-packages, but still does not require the vendor libraries.

## Question

What do I need to do in a contrib module to support both composer\_manager AND the full-composer scenario?

How can I avoid the 'composer\_manager' dependency in the generated composer.json for metapackages for the submodules?

Especially, with the scenario above?

For my taste it is ok if the root package requires all the 3rd party stuff, so then I only need to prevent to require drupal/composer\_manager.

# Answer
Here are the conclusions I will follow for the CFR module package.

I am writing this as guidelines for module maintainers.

The steps may look different for other module packages with a different structure.

## Start a new major version.

If the existing version of the contrib module requires composer\_manager to work, supporting an alternative method might come with backwards-compatibility-breaking side effects. If this is the case, a new major version should be introduced.

## Use the 'alternatives' module.

The alternatives module allows to replace one dependency with another.

In the \*.info file:

```
dependencies[] = composer_autoloader
alternatives[composer_autoloader][] = composer_manager

```

This means: If 'alternatives' and 'composer\_manager' are enabled, then the module in question can be enabled without enabling 'composer\_autoloader'.

## Depend on composer\_autoloader

Let your modules, or one of them, depend on composer\_autoloader, but add the `alternatives[composer_autoloader][] = composer_manager` as mentioned above.

Doing this in a subdirectory module causes the metapackage to require `drupal/composer_autoloader`.

## Additional composer.json file at the top level

*Why?*

Composer manager will look at composer.json files per (sub)module. If the root dir of the module package contains a composer.json, but no module exists in the root dir of the module package, this composer.json will be ignored by composer\_manager.

On the other hand, the project\_composer module responsible for packages.drupal.org will extract metapackage information from the \*.info file in a subdirectory module, but ignore composer.json files for modules in subdirectories.

Unlike composer\_manager, it does look at the main composer.json in the package root dir, even if there is no module in this place.

*How?*

Put one composer.json at the top level directory of the module package. This has to require the 3rd party libraries from every submodule contained in the module package.

Keep the submodule composerjson files in place.

## Replacement composer\_manager for the transition.

Goal: Transition from composer\_manager to composer\_autoloader + drupal-composer.

*Problem*

If the modules were previously installed with composer\_manager and now we want to use composer\_autoloader, we are in a bit of a pickle:

* At least one of the two dependencies must be enabled at any given time, to allow the dependee module to remain enabled and the 3rd party libraries to be autoloaded.
* Downloading both with drupal-composer is not possible, because composer\_autoloader declares a conflict with composer\_manager in its composer.json.
* Assuming we would find a way to download both composer\_autoloader and composer\_manager at the same time, having both *enabled* would be possible but would perhaps cause weird behavior due to duplicate vendor directory and duplicate autoload.
* Updating code and database at the same time is not possible. We need to call `drush en` and `drush dis`, or do the switch via hook\_update\_N(), in the new codebase.

*Solution*

Let the site builder create a dummy / placeholder version of composer\_manager in sites/all/modules/custom/composer\_manager.

The only thing this would do: \- a hook\_boot(), which would check if composer\_autoloader exists, and if not, it replicate the behavior from composer\_autoloader. \- a hook\_uninstall() to replicate uninstalling the regular composer\_manager.

Then use a hook\_update\_N() to enable composer\_autoloader and disable + uninstall the placeholder composer\_manager module.

Perhaps such a placeholder module could be provided on packagist, with an obfuscated name to prevent the conflict with composer\_autoloader.
> 1 votes

---
Tags: 7, composer
---


title: Custom field "required" validation

text:
# Question
Title: Custom field "required" validation
I built a custom field type using the Field API. In `hook_field_validate` I have some logic to validate some very custom stuff, but when I tried to add a "This field is required" validation, I realized this hook runs on the from that you fill when you're adding a field to an entity. Then, I implemented `hook_field_is_empty`, which I know runs when the entity saves. Problem is, even if the hook runs and the field is empty, no validation occurs (i.e. the user doesn't get the "this is required" message, and the form submits).

So, what's the *right* way to do a "this field is required" validation?

# Answer
> 0 votes
Probably a stupid question but have you tried using the #required setting when you created the field i.e.

```
'#type' =>
'textfield',
'#title' => t('Subject'),
'#default_value' => $node->title,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,

```

from Form API reference https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#required

# Answer
> 0 votes
In Drupal 8, you want to look at Constraints. Constraints are put on the field, so that the value to be stored is validated regardless of the source (web/app etc).

https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint

---
Tags: entities
---


# Question
Title: Table prefixes with db_select() in SimpleTest tests
How can I do database queries using functions like `db_select()` and `db_query()` in my `DrupalWebTestCase` sub-class? When I try to run them, I get an error:

> SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'simpletest421143 WHERE (nid = '1')' at line 2\`

I think it's because the tables aren't properly prefixed, yet I see the prefix in the error string. So it seems that it's trying to prefix, but not doing it properly.

How can I use these functions in my testing class?

# Answer
Executing queries inside SimpleTest tests is not different from executing them in a module. The path.test file contains the following code, and it is executed without errors.

```
$forum_vid = db_query("SELECT vid FROM {taxonomy_vocabulary} WHERE module = 'forum'")->fetchField();
$tid = db_insert('taxonomy_term_data')
  ->fields(array(
    'name' => $this->randomName(),
    'vid' => $forum_vid,
  ))
  ->execute();

```
> 1 votes

# Answer
tl;dr: Put curly braces around your table names.

---

A relatively well-known, but not well documented feature of `db_query()` is to automatically replace `{table_name}` (note the curly braces) with `the_proper_prefix.table_name`. Then it will work with Simpletest and on sites that use table prefixes.

The only documentation on this that I could find is in `DatabaseConnection::prefixTables` which is called from `DatabaseConnection::prepareQuery` which is called from `DatabaseConnection::query` which is called from `db_query`:

> Queries sent to Drupal should wrap all table names in curly brackets. This function searches for this syntax and adds Drupal's table prefix to all tables, allowing Drupal to coexist with other systems in the same database and/or schema if necessary.
> 1 votes

---
Tags: 7, database, testing
---


title: How to export users to a CSV file?

text:
# Question
Title: How to export users to a CSV file?
I would like to export users into a CSV in Drupal 7. I believe I can use the module Views Data Export, but I am not sure how to do that or if it is the correct module I would like.

# Answer
> 13 votes
Yes, Views data export is your best choice.

Create a view displaying users and add a page display. Add the fields you want in your export and change any additional settings you want.

Then add a display of type Data export, and set it to attach to the Page display. This way it'll add a link to the file download to that page (You can probably also skip the Page display and only add a Data export display with a path defined).

Choose your export format (CSV) under format settings. If you have a lot of users, make sure to choose batch operation under 'Data export settings'.

It's also a good idea to require a specific permission or role to access the view.

# Answer
> 3 votes
Yes, the Views Data Export is the right module, but if you've big data files, you've to increase proper PHP limits, such as: PHP `max_execution_time` and `memory_limit`, unless you're using batch process, so you should be fine. You should increase the limits especially when using export via drush which is supported (note it's using separate PHP settings file).

To export users using custom function, check: How can I export all users in a CSV format?

which is basically the following custom code which you can use within some callback function:

```
drupal_add_http_header('Content-Type', 'text/csv');
drupal_add_http_header('Content-Disposition', 'attachment; filename=users.csv');
$results = db_query("SELECT * FROM {users}");
$csvdata = 'Uid,Username,Email' . PHP_EOL;
foreach ($results as $record) {
   $row = array();
   $row[] = $record->uid;
   $row[] = $record->name;
   $row[] = $record->mail;
   $csvdata .= implode(',', $row) . PHP_EOL;
}
print $csvdata;
drupal_exit();

```

# Answer
> 0 votes
Another option to address these requirements is by using the Forena module, as detailed below.

# Delivered reports

After you install/enable it, you get these out-of-the-box ***Drupal Administration*** reports that are delivered with it (among many other reports):

### 1) Active Users

```
+-----------+-----------------------+-------------------------+---------+
| User      | Email                 | Last Logged in          | Actions |
+-----------+-----------------------+-------------------------+---------+
| Webmaster | webmaster@example.com | Sun, 03/27/2016 - 18:39 | logs    |
| Admin     | info@example.com      | Thu, 04/07/2016 - 12:47 | logs    |
| Pierre    | pierre@example.com    | Fri, 04/01/2016 - 18:19 | logs    |
+-----------+-----------------------+-------------------------+---------+

```

Using the hyperlink "logs" (in the column titled "Actions"), you get a new report (= Logs for user) showing the most recent log entries for the selected user with "type", "message", "timestamp" and with a subsequent hyperlink ("details") that will show additional details for the selected log record (such as "severity", "hostname", etc).

### 2) Role Details

After selecting any of the available roles (= a report parameter), you get a report that looks like in this example:

```
+-----------+---------+------------------------------+
| User Name | User Id | Actions                      |
+-----------+---------+------------------------------+
| Admin     | 1       | View Profile    Edit Profile |
| Webmaster | 8       | View Profile    Edit Profile |
+-----------+---------+------------------------------+

```

The hyperlinks View Profile / Edit Profile can be used to actually view/edit the profile of the selected user.

# Tuning/cloning the delivered reports

Optionally, if you want to customize these reports, you can use its report writing features. Such as its WYSIWYG report writer and/or the Forena Query Builder (comes with Forena as a sub-module) to first create a query / report that fits your needs. For a video tutorial about this query writing tool, checkout Define data blocks with optional filters.

The result of it all could be a tabular output and/or graph. After the report content matches the specifications, you could save it as (e.g.) a CSV file. Other supported formats for saving a report are XLS, DOC, HTML, PDF, etc.

# Video demos and tutorials

Video demos and tutorials contains quite some links to live demos about Forena.

# Answer
> 0 votes
To include custom fields from your users you can use:

```
drupal_add_http_header('Content-Type', 'text/csv');
drupal_add_http_header('Content-Disposition', 'attachment; filename=users.csv');
$csvdata = 'Uid,Username,Email,Firstname' . PHP_EOL;

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'user');
$result = $query->execute();

$uids = array_keys($result['user']);

// THIS IS YOUR ARRAY OF UIDS.
$users = user_load_multiple($uids);

foreach ($users as $record) {
   $row = array();
   $row[] = $record->uid;
   $row[] = $record->name;
   $row[] = $record->mail;

   // Custom fields, for example
   $row[] = $record->field_first_name_user['und'][0]['value'] ?? '';
   $csvdata .= implode(',', $row) . PHP_EOL;
}
print $csvdata;
drupal_exit();

```

Hope it helps!

---
Tags: 7, users, importing-exporting
---


# Question
Title: How can I create a link to permission group and configuration page on module install page?
When you install modules I can see some modules have links on the install page directly to the permission groups and the configuration page. How can I create those links for my own module?

# Answer
For settings page, in `your_module.info.yml`

```
configure: 'your_module.route_to_settings.form'

```

Permissions link is automatically shown whenever you have permissions defined in your module.
> 1 votes

---
Tags: 8
---


# Question
Title: Avoid random number cached in preprocess hook
I have a random set of images that appear on the homepage which needs to show each time the page is refreshed. My holding page was doing this comfortably in PHP, but since building the whole site and migrating the PHP into Twig I ran into issues with the cache. I tried moving the code into a preprocess hook for the content type however that too is subject to the caching.

Is there anyway around this problem by disabling caching for anonymous users in the preprocess hook, or updating the random number variable in the cache on each reload etc.?

Ideally I'd like to avoid doing this in JS as per the recommendation here Ignore cache in preprocess function

Here is my preprocess function PHP code which feeds a loop.

```
function freadman_white_preprocess_node__3(&$variables) {

$imageset = (rand(1,8));
$time = array(
    '01:14',
    '10:37',
    '11:16',
    '09:38',
    '04:51',
    '03:24',
    '10:39',
    '10:58'
);
$date = array(
    'pm Saturday 18.08.18',
    'am Sunday 05.08.18',
    'am Sunday 05.08.18',
    'am Wednesday 15.08.18',
    'pm Tuesday 21.08.18',
    'pm Tuesday 21.08.18',
    'am Wednesday 25.07.18',
    'am Saturday 25.08.18'
);

$variables['imageCount'] = 33;
$variables['imageSet'] = $imageset;
$variables['imageTime'] = $time[$imageset-1];
$variables['imageDate'] = $date[$imageset-1];

}

```

# Answer
First, try to pass a render element with a `'#cache'` value set, maybe like so:

```
$variables['imageSet'] = [
  '#type' => 'value',
  '#value' => $imageset,
  '#cache' => [
    'max-age' => 0,
  ],
];

```

---

Next, you could try to completely disable the cache for this node (though that's probably not the best idea).

```
$variables['#cache']['max-age'] = 0;

```

---

And last – but quite advanced – you can provide a custom controller, that returns an uncached JSON response with your calculations and then use a little JS script that fetches the JSON via Ajax and inserts it into some placeholder selector in your markup (for the placeholder you could even provide a pseudo field to be placed at a desired position via the admin UI).

I used exactly the concept described above to build User Online Status. You can simply grab a copy and check its code to get an idea how that works.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How Webprofiler EntityManagerWrapper overrides EntityTypeManager?
In trying to understand the new paradigm of Dependency Injection, I attempted to install Webprofiler into my D8.6.10 project but it seemed it causes a conflict with my already installed fullcalendar\_view. It has a dependency that is expecting an instance of `Drupal\Core\Entity\EntityTypeManager` which is important in this new world to declare what is required for your class/method to work.

Stepping through the stacktrace, at some point Drupal is aware that the fullcalendar dependency is requiring EntityTypeManager but the call is co-opted by WebProfiler into `EntityManagerWrapper` and it breaks the site. I could only get past it by removing the EntityTypeManager requirement. My frustration is that I'm trying to understand when I should pull this stunt to remove a requirement for things like Webprofiler and when I should not. I apologize that I don't have the means to ask a focused question because I don't have enough knowledge about this new paradigm yet.

Which is why I ask here.

Is it Webprofiler not respecting the fullcalendar\_view requirement and invoking the `EntityManagerWrapper` or is the fullcalendar\_view asking for the wrong requirement?

# Answer
> 1 votes
Yes, the module fullcalendar\_view is probably asking for the wrong requirement. Services which implement an interface are supposed to be swappable with services implementing the same interface. So if the module has no reason to check for this specific class it should check for the interface `EntityTypeManagerInterface` instead.

---
Tags: dependency-injection
---


# Question
Title: Basefield 'string' shown as select list widget in entity form
I've got a custom entity ('content\_sharing') and defined one of the fields as `$fields['entity_definition'] = BaseFieldDefinition::create('string')...`. The create-form I'm showing the user is loaded with an empty entity via a controller like so:

```
    $contentSharing = $this->entityTypeManager()
      ->getStorage('content_sharing')
      ->create([]);
    $form = $this->entityTypeManager()
      ->getFormObject('content_sharing', 'custom_mode')
      ->setEntity($contentSharing);
    $output['form'] = $this->formBuilder()->getForm($form);
    ...

```

What I need now is to present the user a select-list of possible strings (options) that are dynamically pre-populated everytime the form is loaded. The only `FieldWidget` for string fields is a textfield. I tried to come up with my own custom FieldWidget similar to this

```
 * @FieldWidget(
 *   id = "string_select_list",
 *   module = "content_sharing",
 *   label = @Translation("Select list for strings"),
 *   field_types = {
 *     "string"
 *   },
 *  multiple_values = FALSE
 * )
 */

class StringSelectList extends OptionsWidgetBase {

```

However, this resulted in an error and I noticed that this needs to have options defined which I cannot (don't know how to) provide for my string basefield.

I could of cource just add a dummy form-element select list that provides the values for my entity field, but I wanted to use the entityform as it is without any further custom elements.

Possible with a custom widget or any other solutions?

# Answer
> 5 votes
Create a list\_string base field and use as widget OptionsSelectWidget.

```
$fields['entity_definition'] = BaseFieldDefinition::create('list_string')
  ->setLabel(t('Entity Definition'))
  ->setSettings([
    'allowed_values' => [
      'value1' => 'Value 1',
      'value2' => 'Value 2',
    ],
  ])
  ->setDisplayOptions('form', [
    'type' => 'options_select',
  ])

```

To update the options dynamically add a callback to the base field settings `allowed_values_function`, see How do I programmatically update the allowed values of a list field?

---
Tags: 8, plugins
---


# Question
Title: Show content of custom content type in a block based on taxonomy term
In D8 I have created two custom content types:

1. *Store*
2. *Store products*

It's not an e-commerce, I just need two custom types to show all the stores on one of the subpages and the products that each store has.

Because there are 24 stores, I would hate to create 24 custom types of a *store products*, so I also added a taxonomy term field to a *Store product*.

Now, I would want to show the Store products in a Block, depending on the taxonomy term.

For example: I created Store A, which has products A1, A2, A3. If I go to the page of Store A, there should be a block that shows those products.

If I would go to Store B, the same block would show products of Store B.

I tried following this answer and added a contextual filter, but no luck so far: Display content based on URL

What I did:

* Created a View Block for *Store Products*
* Added a contextual filter to the block (Has taxonomry term -\> taxonomy term ID from URL)
* Also added another contextual filter node:id
* Added the block under blocks to render on the page *Store*

# Answer
What you're trying to do already come out of the box in "Taxonomy term" content views.

If you have tagged your Store product nodes with taxonomy terms these nodes will appear on the related term pages. You don't need a separate Block, the term pages will show a list of nodes tagged with that term.

You don't even need the Store content type if its whole purpose is to provide categorization. The "Store" Taxonomy Vocabulary is all you need.

Can you try and see if that is enough for you?

---

In your Contextual configuration you should use the option "Load default filter from term page", and *not* "Load default filter from node page" because the information is taken from the taxonomy term page, you're not showing a block on a node page.

Why do you need the second Contextual for NID? This is usually used when you want to exclude the current node from the list (Under `More` \> `Exclude`), but you're not on a node page so there is nothing to comare the NID to. Remove that second Contextual, you don't need it.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How do I properly attach Google Maps API?
So, I've posted on this elsewhere and I seem to either get half answers but they've gotten me closer to a solution but not over the finish line.

I'm trying to implement a custom Google Maps application that pulls data in from GeoJson views that I've made of an OpenLayers application that I've abandoned. The problem that I'm having is that if I follow the Drupal docs and wrap my code in a jQuery closure, then my Google Maps call back which is loaded in the global context is out of scope for the function.

I've written a simple module that loads a block of html with a map div, and then loads my google maps script externally in the footer. My map callback works when I load plain JS via my module, but not when wrapped in a closure and attached to a behavior. This poses two problems for me: 1) I can't use jQuery functions to get my data; 2) it's bad practice (as above). So, I guess my question comes down to how do I pull a callback on an externally loaded script into the scope of my Drupal behavior?

So loaded as plain JS this works:

```
 var map, alumLayer, chapterLayer, assocLayer, userLayer;
  function initMap() {
    map = new google.maps.Map(document.getElementById('json-map'), {
      zoom: 4,
      center: {lat: 38.43, lng: -90}
    });
 //ajax code to get map data here
}

```

But this closure attempt doesn't:

```
    (function ($) {
Drupal.behaviors.gmap_json = {
attach : function (context, settings){
  var map, alumLayer, chapterLayer, assocLayer, userLayer;
  function initMap() {
    map = new google.maps.Map(document.getElementById('json-map'), {
      zoom: 4,
      center: {lat: 38.43, lng: -90}
    });
}
}
};
  alert('it works');
}(jQuery));

```

So, I know that my problem here is scope, but I haven't yet found how to do this.Do I need to modify my callback trying to reference the behavior object somehow? Is there a way of mix and matching scoped jquery? Or best practices be damned, whatever gets it working?

# Answer
As you've figured out, your problem is one of closures. In the code that is not working, you have `initMap()` enclosed in the anonymous function `(function($){}(jQuery))`. This means it's not part of the global scope, and therefore cannot be called from the global scope.

The solution to this is to set your function to be available globally. But of course, you don't want namespace collisions, which is the whole point of wrapping code in an anonymous function in the first place.

There is a happy medium here. You create a global variable, and add your callback to that from within your anonymous function:

```
// Initialize your global object. Set the value to itself (if it exists)
// or an empty object otherwise.
var GoogleMaps = GoogleMaps || {};

// Start your anonymous function.
(function($, Drupal, GoogleMaps) {
  Drupal.behaviors.someKey = {
    attach:function () {
      GoogleMaps.initMap = function () {
        // Initialize your map here
      };
    }
  };
})(jQuery, Drupal, GoogleMaps);

```

Use `&callback=GoogleMaps.initMap` in google maps api script embed.

You can also initialize your map from any other scripts using `GoogleMaps.initMap()`
> 3 votes

---
Tags: 7, javascript
---


# Question
Title: How to include multiple taxes to a product's price?
I am using Drupal commerce and have multiple taxes and tax types.

The product price in my site includes 2 types of taxes already added to them (inclusive of both the 2 taxes).

In the product edit page, I get an option to add one of the taxes to be included in the product price.

My doubt is that, how can I select multiple taxes to be included in the product price?

Any help is much appreciated. Thanks.

# Answer
This is not supported unfortunately; it would require custom code for both the price field widget and the tax module's saving routine. If that's beyond your capabilities, you'll simply have to reverse calculate the price and enter it, accepting that the rounding may not always work out to nice round product prices like you want.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Commerce Product with diffrent prices for different shops
Working with Drupal 7 on a comparison site where a product is sold at different price rates at different physical shops. Now there about 300 of these shops. Going by Commerce default setup, I would have to create 300 product types or products and also create 300 product display nodes, which will be insane.

Since the product name, image, (and other attribute is going to be the same, I thought to create a single product display content type that has a price field and create a single product type with all the default fields except price. So with the content type, several product display nodes can be created that then references the single product type. Great right? But the price field in the product type is locked (you cannot delete it).

What other more civilized process is available to achieve my goal, as I need the Add to cart button on each product so as to be able to add to cart and compare the prices onwards.

I have seen a similar question (Drupal Commerce: How to handle billions of product combinations?) go unanswered, hopefully commerce has matured these past three years. Thank you.

# Answer
To resolve the product display \<-\> product issue, I'd be using Inline Entity Form to embed the product form right into the product display node form. However, that doesn't address your need to have hundreds of unique prices corresponding to different physical locations. That's another issue entirely that we would typically refer to as pricelist functionality.

We do have a Commerce Pricelist module, but since "Store" wasn't a core entity type in Drupal 7, there is no pricelist variant correlating to a store. You'll likely need to enhance that module yourself to make it "simple" for end users. Other options would be dependent on your greater site IA ... and it's worth noting that store based product availability and pricing would be better suited to Drupal 8 if there's any chance at all at upgrading.
> 1 votes

---
Tags: commerce
---


# Question
Title: Drupal 8 - Pathauto taxonomy terms in content paths
I currently have a pattern set up for my site's basic pages. It pulls in some generic fields associated with the content type, and no problems there.

Got a new requirement to associate some data from a taxonomy term into the URL path. The content type already had an entity reference field to pull in the taxonomy terms, so the user could associate any number of those terms with the content.

My issue is that I can only use the Taxonomy Term's Name field in the Pathauto pattern configuration. I see no way to bring in another field associated with that Taxonomy term. So, for example, the vocabulary `Company` has a field called `field_short_name` that I would like to include in the Basic Page's URL.

Example data of what I have:

* Company taxonomy term
    + Title: ACME Limited Corporation
    + Short Name: ACME
* Basic Page content:
    + Title: John Doe
    + Entity Reference: ACME Limited Corporation
* Path Auto:
    + /\[node:field\_company\]/\[node:title\]

This currently gives me `www.example.com/ACME-Limited-Corporation/John-Doe` where I really want it to give me `www.example.com/ACME/John-Doe`.

I hope I'm explaining this in a way that makes sense.

# Answer
If you have a taxonomy vocabulary named `company`

And you have a taxonomy entity reference on your basic page machine-named `field_company`

Then the pattern you want in pathauto is:

`[node:field_company:entity:field_short_name]/[node:title]`

This says, "find the value of field\_company on the current node, get it's referenced entity, find the value of field\_short\_name / the node title"
> 2 votes

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


# Question
Title: Only display content that belongs to User in admin/content
I have a role called **Content Editor** and 2 users **Chang** and **Liang** with that same role.

They can both *add/edit* their own content. The role permission is set in such a way that they can only edit own content.

However, when **Chang** navigates to `/admin/content`, this user can see all the contents written by all the users.

How to restrict Chang so that he can see only the contents he has written when visiting the `/admin/content` link?

# Answer
> 1 votes
I created a sandbox-module for that called Content Admin Access Maybe this is what you are looking for.

> With Content Admin Access you can set permissions to show or hide others content in the admin/content overview.
>
> Enabling this module will by default show only your own content in the admin/content overview.

# Answer
> 0 votes
I'm assuming that with "*see all the contents*" you mean "can browse the actual content" (and not something like "the list of nodes with their titles").

In that case, you might consider using the Rules module. Basically your rule would look like something like this:

* **Event**: Content is viewed
* **Condition**: (User has role = Content Editor) AND (node:author not equal to site:current-user)
* **Action**: Page redirect (to some appropriate node that seems appropriate)

# Answer
> 0 votes
Install Administration Views.

> Replaces administrative overview/listing pages with actual views for superior usability.

You can then alter the view that displays node listing to include content by currently logged in user etc.

# Answer
> 0 votes
We can use hook\_query\_TAG\_alter to filter content at admin/content page

```
/**
 * Implement hook_query_TAG_alter()
 * Need to filter out nodes from admin/content page.
 */
function hook_query_node_admin_filter_alter(QueryAlterableInterface $query) {
  global $user;
  if ($query->hasTag('node_admin_filter')) {
    $query->condition('uid', $user->uid);
  }
}

```

We can bypass super admin by adding condition.

Thanks, Devendra

---
Tags: 7, users, nodes
---


title: Serializing dates

text:
# Question
Title: Serializing dates
In Drupal, we have the time printed as `"2012-03-19 07:22"`.

What I need is just `"\/Date(1198908717056)\/"` or just `"1198908717056"`.

I am trying to get that format using the following code.

```
use Drupal\rest\Plugin\ResourceBase;
use Symfony\Component\HttpFoundation\JsonResponse;

$result =[
  [1402963200000, 92.08],
  [1403049600000, 92.18],
  [1403136000000, 91.86],
  [1403222400000, 90.91],
  [1403481600000, 90.83],
];

return new JsonResponse($result);

```

How can I achieve this?

# Answer
> 0 votes
The format what I needed was called Unix timestamps and Drupal already have him.

In php you need just to write something like this:

```
'time' => date("Y-m-d H:i:s"),
'unix' => date("U"),

```

More about time format you can found here.

Also, this module was useful for me to check if all was good.

Settings for view are the some, just like on photo.

After some testing, it was not Unix. It is unix\*1000. XD

---
Tags: datetime, 8
---


# Question
Title: How do I create a jump link to a paragraph item?
I'm trying to create a jump link to the paragraph item. This is what I tried

1. create a compact display of the page just printing out a title and short summary.
2. using the advanced text formatter I created a link in this index

It takes me to the paragraph page. I figure that I can use a token in the advanced text formatter to create an anchor link from the compact display to the detailed display. Then I have to work out how to add the anchor to the detailed display.

* How do I create a link with the delta as the anchor e.g. /abc/test.html#1?
* How do i create the anchor on the detailed display?

# Answer
Perhaps Paragraphs Table of Contents module is good enough for what you describe.

From the project page

> If you have long pages on your site, then it helps visitors if you can provide in-page navigation, or a table of contents.
>
> If you build your long pages with the Paragraphs module, then you can use Paragraphs Table of Contents to provide the in-page navigation. There is one link in the table of contents (ToC) for each paragraph on the page.
> 2 votes

---
Tags: tokens, paragraphs
---


# Question
Title: Use MenulinkTree::load in page_preprocess
I'm on drupal 8, and i want to get menu links from the main menu in order to create the same menu for mobile (so i need 2 same menu, with differents rendering)

I use like this :

```
function template_preprocess_page(&$variables) {
    $variables['menu'] = \Drupal\Core\Menu\MenuLinkTree::load('main');
}

```

But it's broke my website.

What do you think about that ?

# Answer
It is because you don't use a second (mandatory) parameter. Look at this example:

```
$menu_name = 'main';
$menu_tree_service = \Drupal::service('menu.link_tree');
$menu_parameters = new \Drupal\Core\Menu\MenuTreeParameters();
$menu_parameters->setMaxDepth(1);
$tree = $menu_tree_service->load($menu_name, $menu_parameters);

```

You could also set a root menu item like this:

```
$menu_parameters->setRoot($root_menu_item->getPluginId());

```

To get the menu link title and url:

```
foreach ($tree as $item) {
  $title = $item->link->getTitle();
  $url = $item->link->getUrlObject()->toString();
}

```
> 1 votes

---
Tags: 8, theming
---


title: How do I implement a node hierarchy?

text:
# Question
Title: How do I implement a node hierarchy?
This may be a trivial question, but I haven't been able to find a clear answer how to do this in Drupal 8.

How can I organize nodes in a hierarchy like this?

```
Node
- child
- child
- - child
- child
Node
- child

```

I know about Node Hierarchy and several other modules which seem to offer this functionality, but I haven't found anything for D8.

It would also be good if this would work in a way allowing for listing chilren of a given node (like "In this section:", followed by a listing of child nodes.

Still, this seems like such a must-have ability to me, it's possible that Drupal can do it out of the box and I just don't know about it. Am I missing something?

# Answer
> 3 votes
In Drupal 8 you can do this out of the box. Put a reference field in the parent and target it on the child content type. The label of the field would be "In this section". You can theme the section in a field twig of this specific field, for example `field--field-reference.html.twig`.

You can nest the entities, but if you reference the same content type and you leave the reference field in the view mode of the child there is a risk of an infinite loop, which will result in a time-out.

# Answer
> 1 votes
I know this question is 3 years old, but I am surprised that no one yet mentioned the Book module in Drupal Core. I did not compare it to entity\_hierarchy, so I cannot recommend one or the other, but do take a look if you're looking for hierarchically structured nodes.

# Answer
> 0 votes
you could have two entity reference fields

field\_parent

and field\_grandparent

Then in your query, fore each node, find all items that have the current node referenced in field parent or field grandparent.

```
select entity_id as child_id from node__field_parent where field_parent_target_id = :parent_id;

```

and

```
select entity_id as grandchild_id from node__field_grandparent where field_grandparent_target_id = :grandparent_id;

```

When you display them, you could loop through, and display all children, and if they have children, display those children.

by using the two fields and only displaying three levels, you prevent infinite loops. You also might want to add a constraint that you couldn't add a child or grandchild to a node as its parent or grandparent.

Otherwise you could just NOT call the function that displays them recursively.

# Answer
> 0 votes
There's an official D8 port of node hierarchy ready for review here: https://www.drupal.org/project/entity\_hierarchy.

---
Tags: 8, nodes
---


# Question
Title: How do I add a customized parameter to image links
Lets say I have image fields in my node. When I get that fields values in the twig it returns the image URL without any issue.

```
file_url(node.field_image.entity.uri.value)

```

But now I want to add a specific parameter (lets say ?param=0) to the end of that link. Without hard coding the parameter in the twig file is there a way to write a hook that adds that parameter for all the image links in every node. So if I have to change the param I only need to change it from one place.

# Answer
> 0 votes
You can do this with a preprocess function `THEMENAME_preprocess_field` and check whether the field is an image and it has a URL

```
function THEMENAME_preprocess_field(&$variables) {
  if($variables["element"]["#field_type"] == "image"){
    if(isset($variables["items"][0]["content"]["#url"])){
      $variables["items"][0]["content"]["#url"]->setOption('query', ['param' => '0']);
    }
  }
}

```

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


title: Not able to install modules

text:
# Question
Title: Not able to install modules
I installed Drupal on my localhost (LAMP Stack), and I am trying to install modules, but I get the following error.

I tried changing the permissions of the folder, but still it is not working. It is showing same error from both the methods of installation.

# Answer
> 2 votes
It's not an error, but a warning reminding you that you aren't using an encrypted connection, and that the credentials you are using (username and password) could be read from somebody who can intercept the data exchanged between your computer and the server. If you look at the protocol used for the page, you will notice it's http://, not https://.
It's not an error caused from the file/directory permissions.

If you don't have a SSL certificate, just enter username and password that are accepted from the FTP server, and install the modules. The warning is just suggesting that using a secure communication would be preferable.

You could also avoid Drupal prompts for FTP/SSH credentials by setting the owner of the temporary:// directory (and its subdirectories) to the owner of the sites/default directory (which, in your case, I take is *akshay*).

---
Tags: installation
---


title: Lost CSS when authentifification

text:
# Question
Title: Lost CSS when authentifification
I made a custom theme based on bartik.

In this custom theme I add just one CSS file and a very simple specific view template file.

When I am connected with a user with 'Administrator' Role all is OK. It means that my customed class are loaded an applyed

But when i am connected with a user without 'Administrator' Role all is KO. It's like my customed class are not in the theme.

Any Idea ?

# Answer
> 0 votes
Finaly I found the problem. The real problem was not because the user had this or this role.

But the view that i wanted to show had specifc class for some objects for user with Administrator Role.

Example : an 'article' can have 'contextual' class when the user connected had Administrator Role. the same 'article' does't have it when the user connected didn't have Administrator Role.

I am new in drupal 8, so...

---
Tags: 8, theming
---


# Question
Title: Is it possible to add an Ajax action on a button define in a twig view template?
I have a view for which I customized the views-view-field...html.twig template. On each row, I added a first button A which opens a modal with two buttons: *Button B* to confirm the action and *Button C* to cancel the action.

When the users click on *Button B*, I would like to programmatically create new content and close the modal. I imagine I should use AJAX.

How can I implement this?

# Answer
So i found the solution using webform module
> -1 votes

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


# Question
Title: Programmatically change the available options in a views exposed filter
I have an existing view in which I want to change the available options in a view exposed filter. I can't manipulate the form because the modifications are dependant on other views data, so I thought I could use a view hook:

```
function my_mdoule_views_pre_view($view, $display_id, $args) {
  // This doesn't work unfortunately
  if ($display_id === 'gallery_media_select_modal') {

    $filters = $view->display_handler->getOption('filters');

    $filters['bundle']['operator'] = 'IN';
    $filters['bundle']['value'] = ['image' => 'image'];

    $view->display_handler->overrideOption('filters', $filters);
  }

}

```

This setting is basically the same that you can do in the UI, but like I said I need to do it dynamically.

I can see that this is in fact set correctly (and still set in later view hooks) but it's never picked up by the code that is responsible for building the exposed select.

I've found many similar questions, but conclusively they've only been answered for Drupal 7, e.g. https://groups.drupal.org/node/82219

# Answer
I think you are very nearly on the right track, and I don't think you necessarily need a hook. I was able to perform essentially the same task with the following code in a class method.

```
// Get reference to your view.
$storage = \Drupal::entityTypeManager()->getStorage('view');
$view = $storage->load($view_id);

// Be sure to get a specific display.
$view->getExecutable()->setDisplay($display_id);
$display = $view->getExecutable()->getDisplay();

// Retrieve filters. If the combine fields filter is present,
// edit it then assign back using `overrideOption`.
$options = $display->getOption('filters');
if (isset($options['combine'])) {
  $options['combine']['fields'][$field_name] = $field_name;
  $display->overrideOption('filters', $options);
}

// This is the critical missing step.
$view->save();

```

I hope this helps.
> 1 votes

# Answer
I have used `hook_views_query_alter()` and that works.

`$condition` is an array with the keys `field`, `value` and `operator`.

```
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\node\Entity\Node;

function wb_oh_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  foreach ($query->where as &$condition_group) {
    foreach ($condition_group['conditions'] as &$condition) {

      if (strpos($condition['field'], 'node__field_bank_tenure')) {
        $condition['field'] = str_replace('2005-01-01', '2015-01-01', $condition['field']);
        $condition['field'] = str_replace('2007-12-30', '2017-12-30', $condition['field']);
      }
    }
  }
}

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to remove the core stylesheets from a theme
I am developing a Drupal theme and noticed the following CSS files are added automatically by Drupal. I would like to them to be removed.

```
<link rel="stylesheet" href="/core/themes/stable/css/system/components/ajax-progress.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/align.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/autocomplete-loading.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/fieldgroup.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/container-inline.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/clearfix.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/details.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/hidden.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/item-list.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/js.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/nowrap.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/position-container.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/progress.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/reset-appearance.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/resize.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/sticky-header.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/system-status-counter.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/system-status-report-counters.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/system-status-report-general-info.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/tabledrag.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/tablesort.module.css?owah24" media="all" />
<link rel="stylesheet" href="/core/themes/stable/css/system/components/tree-child.module.css?owah24" media="all" />

```

I have tried two ways to remove it. First one is using `libraries-override`

```
libraries-override:
  system/base:
    css:
      component:
        /core/modules/system/css/components/align.module.css: false

```

The next one is using `hook_alter_css`

```
function hook_css_alter(&$css, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  unset($css[drupal_get_path('module', 'system') . 'css/components/align.module.css']);
}

```

# Answer
> 4 votes
I went to the **stable** theme, checked the `.info.yml` file and `libraries-override` section.

I have removed the stylesheets using the following snippets.

```
libraries-override:
  system/base:
    css:
      component:
        css/components/ajax-progress.module.css: false
        css/components/align.module.css: false
        css/components/autocomplete-loading.module.css: false
        css/components/fieldgroup.module.css: false
        css/components/container-inline.module.css: false
        css/components/clearfix.module.css: false
        css/components/details.module.css: false
        css/components/hidden.module.css: false
        css/components/item-list.module.css: false
        css/components/js.module.css: false
        css/components/nowrap.module.css: false
        css/components/position-container.module.css: false
        css/components/progress.module.css: false
        css/components/reset-appearance.module.css: false
        css/components/resize.module.css: false
        css/components/sticky-header.module.css: false
        css/components/system-status-counter.css: false
        css/components/system-status-report-counters.css: false
        css/components/system-status-report-general-info.css: false
        css/components/tabledrag.module.css: false
        css/components/tablesort.module.css: false
        css/components/tree-child.module.css: false

```

# Answer
> 8 votes
Also, you can **exclude a whole library** at all by adding:

```
libraries-override:
  system/base: false

```

# Answer
> 1 votes
If you override "stable" theme :

```
libraries-override:
  system/base: false

```

is enough...

If you override an other theme as "classy" you have to remove useless css files like that :

```
libraries-override:
system/base:
  css:
    component:
      css/components/ajax-progress.module.css: false
      css/components/align.module.css: false
      css/components/autocomplete-loading.module.css: false
      ...

```

---
Tags: hooks
---


# Question
Title: How can I see all the places an asset or entity is referenced?
In Drupal 8, I have a requirement from a client that they be able to find a reference of a given asset (file, node, entity, etc) throughout a Drupal site. The ultimate goal is to know that if they want to delete this asset, it's not going to create 404 errors throughout the places on the site where this is referenced in other content.

I'm thinking about a Views page where the name or ID or some type of identifier would be a contextual filter and then would show a list of all nodes or blocks where that relationship exists.

Any thoughts on how to approach solving an issue like this?

# Answer
> 0 votes
Have you looked at `/admin/structure/views/view/files`? Is that what you need?

Otherwise, you might try your creating your own view of `files` at `/admin/structure/views/add`.

No matter the view, you will need to check the file before deletion as there will be no functionality to warn admins.

Then for content, I think it would just be a view of content focused on adding the `Content Reference` field (or whatever you content reference field\_name is), which can show where references are coming from.

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_content_reference
  module:
    - node
    - user
id: content_references
label: 'Content References'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: full
        options:
          items_per_page: 50
          offset: 0
          id: 0
          total_pages: null
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          tags:
            previous: '‹ Previous'
            next: 'Next ›'
            first: '« First'
            last: 'Last »'
          quantity: 9
      style:
        type: table
      row:
        type: fields
      fields:
        field_content_reference:
          id: field_content_reference
          table: node__field_content_reference
          field: field_content_reference
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Referenced Content'
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: entity_reference_label
          settings:
            link: true
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          plugin_id: field
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Referenced By'
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
      filters:
        status:
          value: '1'
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
        field_content_reference_target_id:
          id: field_content_reference_target_id
          table: node__field_content_reference
          field: field_content_reference_target_id
          relationship: none
          group_type: group
          admin_label: ''
          operator: 'not empty'
          value:
            min: ''
            max: ''
            value: ''
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            placeholder: ''
            min_placeholder: ''
            max_placeholder: ''
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: numeric
      sorts: {  }
      title: 'Content References'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.node.field_content_reference'
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.node.field_content_reference'

```

I am not sure about an all in one solution...

# Answer
> 0 votes
In D8 there are some related modules you might want to check out:

In D7 there are some modules you might check and see if they have D8 plans:

There are open issues you may contribute to about this:

## Create Views listing back-references

You'll probably have to create a new View for each of the bundles you're using references on (Content, Taxonomy term, File, Comment etc).

The key is to be aware of your project structure, to know where all of the reference fields are. So check your "Manage fields" pages everywhere for reference fields, and note what they reference. Then create a back-reference map from that info so you know which Views you need to create.

You may end up with less Views depending on your structure, you'll need as many as there are entity types that are being referenced. Then if more than one type references it you can use Relationships to add them to the same view. This way you could have taxonomy terms type View that lists all Content and Files that are tagged with it.

Which Relationships and (Contextual) filter exactly needs to be used depends on the particular structure you have. You can use an Exposed filter instead of a Contextual if it's just a tool to check references, but if you want to display a Block on relevant (Edit) pages that would automatically show what references this (smart) then you need the Contextual.

For example, if you have articles referencing other articles through Entity reference field:

1. Create View with Block display listing articles
2. Add the Contextual filter for that Entity reference field:
`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**
**Content**
**Article**
Hide View if the argument doesn't validate, or some other options that makes sense to you.
3. Place the Block on article pages, or article edit pages, adjust `Node from URL` and other Block options.

The block will show if there are any articles that reference the one you're viewing.

Other types of connections will require similar or other types of Views configuration.

---
Tags: views, 8, entities
---


# Question
Title: What is wrong with the following api call to logout user?
When i call drupal rest api to logout with following parameters

```
axios.post('http://my-lando-app.lndo.site/user/logout?_format=json', {
    'csrf_token':  this.state.csrf_token,
    'logout_token' : this.state.logout_token,
    'Content-type': 'application/json'
})

```

I get response

```
{"message":"\u0027csrf_token\u0027 URL query argument is missing."}

```

what is wrong with my request?

# Answer
> 2 votes
I encountered this error with angularjs(D8.5). This code works for me.

```
getUserLogout(logoutToken,csrfToken) {
  // post logout
  return this.http.get(
    'http://localhost:8082/d8/api/user/logout?_format=json&token='+logoutToken,
    {
      headers:
      {
        'X-CSRF-Token': csrfToken
      },
      withCredentials: true
    }
  );
}

```

# Answer
> 0 votes
As it's mentioning a URL query argument, that seems to indicate that the csrf\_token should be appended to the URL as a GET variable, rather than including it in your POST data. Or maybe the entire request is supposed to be GET instead of POST.

# Answer
> 0 votes
It’s trying to load a user with an ID of ‘logout’ it would seem. I haven’t worked with the API much - maybe the endpoint is different for logging out. Or more likely I’m thinking it’s probably supposed to be a GET or some other type of request other than POST.

# Answer
> 0 votes
This works on Drupal 8.5.1:

```
this.serverRequest = axios.get('/user/logout', '', {headers: {
  'X-CSRF-Token': localStorage.getItem('csrf_token')}
});

```

Also works without the csrf\_token header. I did read a call to require a token for logout but I'm not sure if it's the csrf\_token or the logout\_token.

I'm interesed to heard whether this works for you, or did you find another way?

# Answer
> 0 votes
It's probably Drupal cannot read the `token` parameter in the URL. Or can not read the credentials (Cookie for example).

Make sure the POST request that you are making to the /user/logout contain the Cookie header. Or if you are using the `HttpHeaders` make sure to set the `withCredentials: true`.

The URL of this resource is: `user/logout?_format=json&token=TOKEN_HERE`

No need to post something in the body. POST nothing just pass the two parameters in the URL `_format=json&token=TOKEN_HERE`

NOTE: The user should be anonymous in order to have a successful POST to this service. Or you have to clear your browser/client sessions and cookie and try again.

---
Tags: 8, users
---