# Question
Title: Dependency injection in Drupal queueworker plugin
I am creating a queueworker plugin, and would need the QueryFactory and EntityManagerInterface. I set these as 'use' statements, and added them in my parameters in \__construct(), but i get following error:

> TypeError: Argument 1 passed to Drupal\custom\_example\Plugin\QueueWorker\SalesQueueProcessor::\__construct() must be an instance of Drupal\Core\Entity\Query\QueryFactory, array given

My QueueWorker plugin:

```
namespace Drupal\simplified_bookkeeping\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\custom_example\Entity\BookingEntity;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityManagerInterface;

/**
 * Processes Sales Tasks.
 *
 * @QueueWorker(
 *   id = "sales_queue_processor",
 *   title = @Translation("Generate sales from bank/cash statements in queue"),
 *   cron = {"time" = 10}
 * )
 */
class SalesQueueProcessor extends QueueWorkerBase {

  public function __construct(QueryFactory $entity_query, EntityManagerInterface $entityManager) {
    $this->entity_query = $entity_query;
    $this->entityManager = $entityManager;
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($bid) {}
}

```

What am I doing wrong?

# Answer
> 12 votes
Long story short, your plugin needs to implement `ContainerFactoryPluginInterface` for services to be injected.

Something like this:

```
namespace Drupal\simplified_bookkeeping\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\custom_example\Entity\BookingEntity;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Processes Sales Tasks.
 *
 * @QueueWorker(
 *   id = "sales_queue_processor",
 *   title = @Translation("Generate sales from bank/cash statements in queue"),
 *   cron = {"time" = 10}
 * )
 */
class SalesQueueProcessor extends QueueWorkerBase implements ContainerFactoryPluginInterface {

  public function __construct(array $configuration, $plugin_id, $plugin_definition, QueryFactory $entity_query, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->entity_query = $entity_query;
    $this->entityTypeManager = $entityTypeManager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.query'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($bid) {}
}

```

As an aside, the entity manager service is deprecated; the entity type manager should be used instead. You also don't strictly need to inject the entity query service as you can get an instance from the manager, e.g.:

```
$query = $this->entityTypeManager->getStorage('node')->getQuery();

```

---
Tags: 8
---


# Question
Title: Render chart with data from Views PHP custom field
How to render a Column Chart using data from Views PHP custom field (**BAR Number (PHP custom)** in the screenshot below)?

I am trying to achieve a Column Chart; with each bar in the chart being **distinct count number of "bar number".**

1. I have tried using aggregation (with charts module chart add-on enabled), but does not give option to aggregate/count on PHP custom fields.
2. have tried Google Chart Tools module, but again it does not consider PHP Views custom fields for Grouping.

Just for more information on what I am trying to achieve, please refer below Requirement screenshot!

Thanks in advance!

# Answer
A work around for issue `1.` & `2.` Add Bar number as a field to each study node. Then add field to view, and aggregate.

How exactly is the Bar Number being calculated? You could use Rules to calculate this value when node is saved and save the calc number to your Bar number field. If there is no calculation, then ignore this part.

Use field permissions to not allow certain roles to change the value of this field, if needed.

---

Add a new field called Bar Number (machine name: field\_bar\_number) to your study content type.

You can create a custom module.

**mymodule.info**

```
name = My Module
description = Makes calculation for Bar Number field in Study content type.
package = Custom
version = 7.x-1.0
core = 7.x

```

**mymodule.module**

```
/**
 * Implements of hook_node_presave
 */
function MYMODULE_node_presave($node) {
  if ($node->type =='study') {
    // calculates bar number
    $node->field_bar_number = $node->some_field - $node->other_field;
  }
}

```

Use Views Bulk Operations and set title = title, and save again all your 500 nodes. As your custom module makes the calculation and sets the bar number before the node is saved. VBO Tutorial.
> 0 votes

---
Tags: 7, views, nodes, charts
---


title: How do I clone an existing site?

text:
# Question
Title: How do I clone an existing site?
I used the following steps for a D8 site: git clone composer update (get the packages) make a database make files folder and settings.php writable navigate to d8.localhost.install.php (host made and site enabled)

Somehow this did not work do I miss something?

# Answer
I think it can depend a little on what your goal for the "clone" is.

When we want to make clones of a live site for development or testing or whatever very little works as well as just making an image of the whole server, spinning it up somewhere else and modifying the allowed domains to account for the new IP address.

If you want specific help about some part of the cloning process then perhaps we need more information about what s going wrong; error messages, WOD etc. I notice in your post you mention making the database but not importing the old database, was that step taken?
> 1 votes

---
Tags: 8, composer
---


# Question
Title: No style only Plain text when try to login
SO I have a problem when I try to login to Drupal (drupal.kalianet.to/user)it gives me a plain text with no style. I realized when I inspect the page that it automatically put user after the domain name. Which Im not sure what really the problem.

# Answer
> 1 votes
Looks like the styles can't be loaded. Have you tried clearing the cache and saving the file-system path? Perhaps the sites/default/files folder isn't writeable.

---
Tags: uri
---


# Question
Title: Views filter (contextual?) by Taxonomy id
Have a question.

I have a D8 website for our company. This website contains service pages and now I would like to add a block with reviews on every service page. But the reviews should match the service. The website has taxonomy vocabulary with all the services. So when I create a service page I have to choose a service from taxonomy (basically, one service page represents one term id from taxonomy vocabulary). And when I create a new review I also have to choose a service from the same taxonomy vocabulary.

So now I would like to add a block with the reviews on the service page. But I have no idea how to make the reviews match with the service page where they are embedded.

Is there some kind of filter what match term IDs from different fields? Regular filter, contextual filter? Tokens? Unfortunately, nothing worked for me :(

I could create different blocks for every single service ... but there would be a more universal solution.

Would be happy to get any help with that.

# Answer
Add Term ID as contextual filter.

When filter value is not available, select Provide Default value

For Type, select Term ID from URL

This is automatically pickup the term from your node, your view preview will go blank, because the actual view edit page does not have a term. It will show up when you look at the node.
> 1 votes

---
Tags: views
---


# Question
Title: Twig templates for nodes in different views
I have a content type, `blog_post`, that is displayed by a number of different views.

I'm having a problem that the node template that gets used first after clearing the cache will then be used for all other views.

For example one page displays a view called "Blog Posts". If I load this page after clearing the cache, it correctly uses the template `node--view--blog-posts.html.twig`.

Another page uses the view "Latest Blog Posts", and this should use the template, `node--view--latest-blog-posts.html.twig`. However if I load this page without clearing the cache first, it uses the `node--view--blog-posts.html.twig` template.

If I clear the cache and reload the second page, it will then use the correct template, but if I go back to the first page, it will be using the template for the second!

I have twig debugging enabled, and it shows the wrong view name under "FILE NAME SUGGESTIONS" as follows:

```
<!-- FILE NAME SUGGESTIONS:
   * node--view--blog-posts--page.html.twig
   x node--view--blog-posts.html.twig
   * node--20--teaser.html.twig
   * node--20.html.twig
   * node--blog-post--teaser.html.twig
   * node--blog-post.html.twig
   * node--teaser.html.twig
   * node.html.twig
-->

```

I expect that lots of other sites theme nodes in multiple views, so I expect I'm done something wrong. Any suggestions how I can debug this?

# Answer
> 4 votes
Do not use node--view-\* templates. They are broken.

Two views with entity view mix up rendered templates

The quick solution:

* create unique view mode for your CT
* display views with content
* use unique view mode for your view

---
Tags: theming, 8
---


# Question
Title: Will renaming the update.php file affect the Drupal update process?
Will renaming the update.php file affect the Drupal update process? What's the correct way of renaming this file/path?

If we want to use /update as alias for a node, there seem to be SEO disadvantages as it's treated as a Drupal core/system URL by crawlers.

# Answer
> Will renaming the update.php file affect the Drupal update process? What's the correct way of renaming this file/path?

There is no correct way. As soon as you rename this, you'll be hacking core which is a no no.

> If we want to use /update as an alias for a node, there seem to be SEO disadvantages as it's treated as a Drupal core/system URL by crawlers.

By default Drupal already addresses this issue because of this line in Robots.txt:

```
Disallow: /update.php

```

So no robot/spider should be crawling update.php.
> 1 votes

---
Tags: updating
---


# Question
Title: User Redirection based on his status (loggedin/loggedout)
So as the title dictates, I'm trying to redirect the user based on his status but I'm facing difficulty in doing so. Here is what i'm doing:

---

In the submit form:

---

```
public  function submitForm(array &$form, FormStateInterface $form_state){
   .......
   $logged_user = json_decode($response);
   $_SESSION['loggedin'] = true;
   $_SESSION["jwt"] = $logged_user->token;
   $form_state->setRedirect('entity.node.canonical', ['node' => 1]);//After submit i redirect the  user to /node/1 which is intercepterd by the route defined in module.routing.yml
   ........
}

```

---

In my routing file:

---

```
user.home:
path: '/node/1'
defaults:
  _controller: '\Drupal\smeno\Controller\SmenoHomeController::index'
requirements:
  _permission: 'access content'

```

---

In my controller file:

---

```
 function index(){
  if (!(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)) {
     return $this->redirect('<front>');
  }
 }

```

Now if the user is not authenticated and attempt to access /node/1 he is redirected to the page, it works fine, however, if the user is authenticated and tries to access /node/1 it gives me an error that there is no error in my controller which is logical because I haven't defined an else in the index() function where the user is already authenticated, then the user should get the page he is demanding. So i did the following:

```
 function index(){
  if (!(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)) {
   return $this->redirect('<front>');
  }else{
   return $this->redirect('entity.node.canonical', ['node' => 1]);
  }
 }

```

but with this it puts me in an infinite loop of redirection which is comprehensible. when an authenticated user request /node/1 the route is activated and it sends him to the index function and the latter redirect him back to /node/1 and the route is activated again and so on.

Now the question is how can i let the authenticated user gets the page he is demanding??

# Answer
> 0 votes
So, in the end, i wasn't able to accomplish this using the route and the controller, all my attempts have failed, but an idea of a friend helped me in solving this. well, the idea has nothing to do with routes and controllers, in fact, i removed the route as well as the controller. the idea is to create two blocks: "AuthSessionCheckBlock.php" is where i validate an anonymous user and "AnonymCheckBlock.php" is where i validate an authenticated user, as follow:

## AuthSessionCheckBlock.php:

```
use Drupal\Core\Block\BlockBase;
use Symfony\Component\HttpFoundation\RedirectResponse;

class AuthSessionCheckBlock extends BlockBase {
    public function build() {
        if (!(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)) {
             $response = new RedirectResponse(\Drupal::url('<front>'));
             $response->send();
             return;
        }
     }
}

```

## AnonymCheckBlock.php

```
use Drupal\Core\Block\BlockBase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;
class AnonymCheckBlock extends BlockBase {
   public function build() {
      if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
         $destination = Url::fromUserInput('/mon-profil/obtenir_document')->toString();
         $response = new RedirectResponse($destination);
         $response->send();
         return;
      }
   }
}

```

Then, i put these blocks in the top of my header region using drupal's BackOffice and i specified that the AnonymCheckBlock to be displayed only in the front page and the AuthSessionBlock to be displayed in all the pages an admin has access to, for me it was "/my-profile/\*" (This step is very **important**, if neglected it will result in an **infinite redirection looping**). So now if an anonymous user tries to access a page that requires authentication such as "/my-profile/something" the AuthSessionCheckBlock will be activated and redirect the anonymous user back to the front page which is in my case the login page. on the other hand, if an authenticated user tries to access pages that he is not allowed to enter (such as login page, registration page...), for me i display the AnonymCheckBlock only in the front (login page, i should display it also in the registration page); so if the authenticated user tries to access the front page the AnonymCheckBlock will be activated and therefore redirect him back to him home (/mon-profil/obtenir\_document).

---
Tags: users, redirection
---


# Question
Title: What might cause duplicate user registrations?
We have a site with about 16,000 registered users. I've just discovered there are over 100 duplicate user registrations.

These users have all the same details (username email etc) and have been created at about the same time and have a uid that is just one more than the original.

We are using Email Registration module 7.x-1.3. I've tried duplicating the problem by hitting the submission button multiple times and be creating an identical submission. However, I *always* get the validation error.

Any suggestions?

**Note**: we also use Rules and there is a rule triggered by a "After updating an existing user account" event. The rule runs some simple PHP code that adds the users details to a CSV file.

# Answer
> 0 votes
I think that this part of your question is crucial:

> ... there is a rule triggered by a "After updating an existing user account" event. The rule runs some simple PHP code that adds the users details to a CSV file.

I.e. to (a) understand what's happening and (b) to come up with some type of workaround. Read on for more details ...

### Understanding what's happening

Your question seems like a variation of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

> some other module code is calling a `user_save` on `hook_user_update` triggering the rules event a second time.

If I was to debug this, I'd disable all contributed modules (except "Rules" and "Entity API") to check if it's indeed a contributed module (I don't expect it to be core). And then re-enable the contributed modules one by one until the issue comes back. As soon as it comes back, you pinpointed the contributed module causing the issue, and you can start working on a possible remedy for that.

### Workaround 1

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):

### Workaround 2

Another workaround to prevent this issue from happening, is to improve your existing rule to make it similar to the rule included in my answer to "How to implement a Rules Condition like \[account:last-login\] = never?". More specifically:

* Add a Rules Condition like: ***User does NOT (!!!) have a role with role id = "`4`"***.
* Add a Rules Action like: ***Grant User the role with role id = "`4`"***.

So this improvement of your rule will check if the user does not yet have some (designated) role with role id = "`4`" (adapt to whatever role id that fits your case, and make sure this role is NOT yet granted when activating a new user id). If that's the case, then the user is granted that role. With this improvement to your existing rule, this is what will happen:

* The **1st time** your Rules Actions will still be performed (and grants the designated role).
* the **2nd time** not ALL of your Rules Conditions will be satisfied (since the designated role was granted before), and therefor your Rules Actions will no longer be performed.

# Answer
> 0 votes
If your PHP code is just adding the details to CSV, there is no point in doubting that rule. However, you can just disable that rule for a while and give it a try again. Also, check if there is another custom/contrib module/code that acts when a user is created.

---
Tags: 7, users
---


# Question
Title: Commerce checkout - Update cart pane after user select a shipping option (ajax)
I am working on a one page checkout and **I'm trying to get the cart review pane updated with a shipping price while user selects a shipping option**.

I have attached #ajax information to the shipping options, to update the cart review form when a shipping option is saved.

Modifying the commerce shipping ajax callback on checkout

```
if($form_id == 'commerce_checkout_form_checkout') {
  $form['commerce_shipping']['shipping_service']['#ajax']['callback'] = 'mshop_shipping_pane_service_details_refresh';
}

```

Ajax callback

```
function mshop_shipping_pane_service_details_refresh($form, $form_state) {
  // Update shipping form
  $commands[] = ajax_command_replace('#' . $form['commerce_shipping']['service_details']['#id'], render($form['commerce_shipping']['service_details']));

  // Update checkout cart review
  list($view_id, $display_id) = explode('|', variable_get('commerce_cart_contents_pane_view', 'commerce_cart_summary|default'));
  $commands[] = ajax_command_replace('.view-mshop-cart-shopping-cart-summary', commerce_embed_view($view_id, $display_id, array(arg(1))));

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

**The issue :** The AJAX is working, the updated cart review view is updated, but the shipping option is not applied.

My guess is that, as the form is only updated and not submitted, the order is not saved. So as the cart review's view is based on the order, and the shipping option is not saved yet in the order, it does not display the right shipping information in the cart review.

Any workaround?

**EDIT:**

Thanks to milkovsky comment I have been able to save the order with the shipping rate applied to the order. Then the cart review view displays correctly with the updated cart rate applied.

```
/**
 * Ajax callback: Returns the shipping details form elements that match the
 * currently selected shipping service.
 */
function mshop_shipping_pane_service_details_refresh($form, &$form_state, $checkout_pane, $order) {

  // Get order from form
  list($order, $checkout_pane) = $form_state['build_info']['args'];

  // Load up to date order
  $order = commerce_order_load($order->order_id);

  // Get selected
  $service_name = $form['commerce_shipping']['shipping_service']['#default_value'];

  commerce_shipping_service_rate_order($service_name, $order);

  // Delete any existing shipping line items from the order.
  commerce_shipping_delete_shipping_line_items($order, TRUE);

  // Extract the unit price from the calculated rate.
  $rate_line_item = $order->shipping_rates[$service_name];
  $rate_line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $rate_line_item);
  $unit_price = $rate_line_item_wrapper->commerce_unit_price->value();

  // Create a new shipping line item with the calculated rate from the form.
  $line_item = commerce_shipping_line_item_new($service_name, $unit_price, $order->order_id, $rate_line_item->data, $rate_line_item->type);

  // Save and add the line item to the order.
  $new_line_item = commerce_shipping_add_shipping_line_item($line_item, $order, TRUE);
  commerce_order_save($order);

  // Update shipping form
  $commands[] = ajax_command_replace('#' . $form['commerce_shipping']['service_details']['#id'], render($form['commerce_shipping']['service_details']));

  // Update checkout cart review
  list($view_id, $display_id) = explode('|', variable_get('commerce_cart_contents_pane_view', 'commerce_cart_summary|default'));
  $commands[] = ajax_command_replace('.view-mshop-cart-shopping-cart-summary', commerce_embed_view($view_id, $display_id, array($order->order_id)));

  $commands[] = ajax_command_after('.main form', theme('status_messages'));

  // $commands[] = ajax_command_after('.'.$form['#attributes']['class'][1].':eq(0)',theme('status_messages'));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> 4 votes
You are right. Shipping rates are applied only after you submit the form (Click "Next").

On submit all your shipping rules(or flat rates) applied and order is saved with new line items (Shipping is implemented via custom line item type).

The calculation is executed in the commerce\_shipping\_pane\_checkout\_form\_submit()

So you can try to execute this function (or some parts of it) in the ajax callback before the cart is updated.

Here is an example how to apply shipping rates if you are using using Flat Rate Module: Adding shipping to order programmatically via module.

# Answer
> 2 votes
*Firstly, thanks for posting this solution!*

I was getting this 500 error from the AJAX response: "EntityMetadataWrapperException: Missing data values. in EntityMetadataWrapper-\>value().

I wanted to offer free shipping on orders over $100 so enabled the commerce\_order\_total module (https://www.drupal.org/sandbox/joshmiller/2718047) which highlighted the error when selecting a shipping method.

After some debugging, I found it was only occurring when the ***commerce\_order\_save()*** line was included.

Since I have set my checkout Panes to all appear on the same page and my Review Pane is disabled, I wrapped this line in an IF statement:

```
//get checkout panes
$panes = commerce_checkout_panes();

//check if the Review pane is enabled
if ($panes['checkout_review']['enabled']){
  //review is enabled
  commerce_order_save($order);
}

```

Comments/improvements are encouraged!

---
Tags: commerce
---


# Question
Title: Call a JS function when a views ajax request completes?
I want to run some JS stuff on the exposed filters of a view which uses ajax. How can I know every time the view is reloaded by ajax, and run some JS?

# Answer
> 1 votes
You can find ahah/ajax success by this function.

**Not a Drupal Way.**

```
$(document).ready( function () {
 $('body').bind('ajaxSuccess', function(data, status, xhr) {
  alert('Ajax Success');
 });
});

```

This function will get invoked on every ajax success.

# Answer
> 0 votes
**Drupal Way**

Create own module Implement hook\_views\_ajax\_data\_alter() in it For ex. if your module has name 'mymodule', code will be

```
function mymodule_views_ajax_data_alter(&$commands, $view)
{
    $commands[] = array('command' => 'customCommand');
}

```

and add your JS stuff to this command

```
(function ($) {
  if (Drupal.ajax) {
    Drupal.ajax.prototype.commands.customCommand = function (ajax, response, status) {
//JS stuff
console.log(response);
    };
  }

}) (jQuery);

```

---
Tags: 7, views, ajax
---


# Question
Title: How to add a custom variable that can be accessed on bootstrap's menu--account.html.twig?
I have a custom theme (subtheme of drupal bootstrap theme). We are overriding `menu--account.html.twig`. So I copied `menu--account.html.twig` from the bootstrap theme template folder into my theme's template folder, and I verified this template is being used because static text changes I added show up on screen.

Now I'm trying to add a variable that the `menu--account.html.twig` template can read.

How do I do that? My variable's name is 'nickname'. I tried this:

```
 function mymodule_preprocess_menu__account(&$variables)
 {
     $variables['nickname'] = 'Jeff';
 }

```

The variable is added to the array, and I can see it if I use dpm, but when I reference {{nickname}} in the template it's always null.

I also read I had to define the variable like this:

```
 function candidate_poral_theme_registry_alter(&$theme_registry)
 {
   $theme_registry['menu__account']['variables']['nickname'] = 'default';
 }

```

But that also doesn't work.

Any assistance would be welcome.

# Answer
I have done this for a theme on past projects. Be sure to pass it in through the `content` item:

**Example**

```
use Drupal\Core\Render\Markup;

function mytheme_theme_registry_alter(&$theme_registry) {
  $theme_registry['menu__account']['variables']['nickname'] = 'default';
}

function mytheme_preprocess_menu__account(&$variables) {
  // code...

  $variables['content']['#nickname'] = [
    .. renderable properties
  ];

  // or also...

  $variables['content']['#nickname'] = Markup::create('Jeff');
}

```

Then, in the twig template:

`{{ custom_var }}`
> 1 votes

---
Tags: theming, 8, hooks
---


title: How to convert an url in a link?

text:
# Question
Title: How to convert an url in a link?
I have some strings that can contain urls inside, and I need to convert this urls into links.

For example if a have this string:

```
Read for more information www.drupal.stackexchange.com/q/246298/28275

```

I need to obtain this string:

```
Read for more information <a href="http://www.drupal.stackexchange.com/q/246298/28275">www.drupal.stackexchange.com/q/246298/28275</a>

```

How can I do this?

# Answer
To achieve this in **Drupal 8** we have in the Core the filter\_url filter that convert URLs into links.

So we just need to apply the filter to our string.

```
use Drupal\filter\FilterPluginCollection;

// The text processing filters service.
$manager = \Drupal::service('plugin.manager.filter');
// Getting filter plugin collection.
$filter_collection = new FilterPluginCollection($manager, []);
// Getting the filter_url plugin.
$filter = $filter_collection->get('filter_url');
// Setting the filter_url plugin configuration.
$filter->setConfiguration([
  'settings' => [
     'filter_url_length' => 496,
   ]
]);
// The string.
$input = 'Read for more information www.drupal.stackexchange.com/q/246298/28275';
// Applying the filter.
$result = _filter_url($input, $filter);

// To use dpm() you need the devel module.
dpm($result);

```

For **Drupal 7** is more simple

```
// Creating the filter.
$filter = new stdClass();
// Adding the filter settings.
$filter->settings = array(
  'filter_url_length' => 496,
);
// The string.
$input = 'Read for more information www.drupal.stackexchange.com/q/246298/28275';
// Applying the filter.
$result = _filter_url($input, $filter);

// To use dpm() you need the devel module.
dpm($result);

```

Output in both examples:

```
Read for more information <a href="http://www.drupal.stackexchange.com/q/246298/28275">www.drupal.stackexchange.com/q/246298/28275</a>

```
> 5 votes

---
Tags: 8, uri
---


# Question
Title: 8 - Views: list pages that are child menu items to the current node
I have three nodes:

* Node A
* Node B
* Node C

In the main menu, these nodes are organized with Node B and C as children of Node A's menu item, like so:

* Node A
    + Node B
    + Node C

When Node A is viewed, I would like to display/list Node B and C in a block under Node A's content.

I would like to do this without using the Book module. I would also like to do this without adding an extra step to the user (i.e. using entity reference on Node A).

Is there a way to do this views? i.e. to create a relationship to the menu structure?

Here's a drawing of what I'm trying to achieve:

Any insight is greatly appreciated.

# Answer
> 3 votes
I hate answering my own question here, but just to save the effort anyone might be going through, here is a module that worked for me:

Views Menu Node Children Filter

Using this module I was able to pass the node ID of the current node and filter the node's children in reference to the menu structure. Works perfectly on 8.4.

---
Tags: views, 8, navigation
---


# Question
Title: How to hide/remove a specific menu heading tittle
I have created a menu using Superfish containing the following items: "Menu 1," "Menu 2," "Menu 3," and "Contact."

When I click on each menu, the heading title is displayed. I want to hide the contact menu title. i was trying to hide it from the block but each menu doesn't have a block title.

How can I hide only the "Contact" menu heading title?

# Answer
You should:

* select the Structure-\>Blocks menu;
* from the blocks list, click on "configure" next to your menu block;
* specify `<none>` as block title.
> 8 votes

# Answer
A simple way: you can hide it by CSS, setting `display:none` to title.
> 1 votes

# Answer
It works

.is-active:before { font-family: FontAwesome; content: "\f015"; }

This doesn't work display:none
> -1 votes

---
Tags: 7, routes
---


# Question
Title: Change row background color on select field change
I have a form with a table that has select boxes inside. I need to have each row of the table with a different background depending on the value of the "action" select box. If it's Create it should be green, if it's Delete should be red.

These colors should be applied when I go to the page and also when I change the select box value.

Below is a screenshoot of the table and the complete module code.

Thanks.

```
function mymodule_menu() {
  $items = array();
  $items['mymodule_menu'] = array(
    'title' => 'My module title',
    'access arguments' => array('access content'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function mymodule_form($form, $form_state) {

    $actions = array(
        'create' => 'create',
        'delete' => 'delete',
    );

    $configurations = array(
        'default' => 'default',
        'conf1' => 'conf1',
        'conf2' => 'conf2',
    );

    for ($i = 1; $i <= 3; $i++) {
        $options['row' . $i] = array(
            'row' => 'row' . $i,
            'action' => array(
                'data'=> array(
                    '#type' => 'select',
                    '#title' => 'Action for row' . $i,
                    '#title_display'=> 'invisible',
                    '#default_value'=> '',
                    '#options' => $actions,
                    '#name' => 'action[row' . $i . ']',
                ),
            ),
            'configuration' => array(
                'data'=> array(
                    '#type' => 'select',
                    '#title' => 'Configuration for row' . $i,
                    '#title_display'=> 'invisible',
                    '#default_value'=> '',
                    '#options' => $configurations,
                    '#name' => 'configuration[row' . $i . ']',
                ),
            ),
        );
    }

    $header = array(
        'row' => t('Row'),
        'action' => t('Action'),
        'configuration' => t('Configuration'),
    );

    $form['myfieldset'] = array(
        '#title' => t("This is a fieldset"),
        '#prefix' => '<div id="checkboxes-div">',
        '#suffix' => '</div>',
        '#type' => 'fieldset',
        '#description' => t('This is the fieldset description.'),
    );

    $form['myfieldset']['tableselect_element'] = array(
        '#type' => 'tableselect',
        '#header' => $header,
        '#options' => $options,
        '#empty' => t('No content available.'),
    );

    $form['action'] = array(
        '#type' => 'value',
    );

    $form['configuration'] = array(
        '#type' => 'value',
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Execute',
    );

    return $form;
}

```

# Answer
> 1 votes
To do this I would handle all logic in some custom js so it can run on the change event.

First add a custom class to your table:

```
$form['myfieldset']['tableselect_element'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No content available.'),
    '#attributes' => ['class' => ['mytable']],
);

```

And a custom class to your action select:

```
'action' => array(
    'data'=> array(
        '#type' => 'select',
        '#title' => 'Action for row' . $i,
        '#title_display'=> 'invisible',
        '#default_value'=> '',
        '#options' => $actions,
        '#name' => 'action[row' . $i . ']',
        '#attributes' => ['class' => ['update-action']],
    ),
),

```

And then also add some custom javascript to the form:

```
$form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/mymodule.js';

```

Then create the file mymodule.js. Here is an example. I've added comments to explain each bit.

```
(function($) {

    /**
     * The Drupal behaviors to copy address from shipping to billing on admin order edit page.
     */
    Drupal.behaviors.mymoduleColorRows = {
        attach: function(context) {

            // Bind change event to select
            $('.update-action').change(function(){
                setColors();
            });

            // Call function on first page load
            setColors();

            function setColors() {
                // Loop rows
                $('.mytable tr').each(function(){
                    // Get color from value of select
                    var color = $(this).find('.update-action').val() == 'create' ? 'green' : 'red';
                    // Set color
                    $(this).find('td').css({'background-color': color});

                });
            }

        }
    };

})(jQuery);

```

Then your table should look like this:

---
Tags: theming, forms
---


title: Adding an Image field in webform module

text:
# Question
Title: Adding an Image field in webform module
I am a newbie to drupal 7 and just started working with it a couple of months ago. My problem is I am making a "webform" where the user filling the form should upload his image. But as there is no such field I am not able to understand how to do it.....

I also tried the "entityform" but as I install it and enable it, the edit links all over my website starts throwing an exception...

So please help me. Any help will be appreciated.

Thanks in advance.

# Answer
**To add an image field to a webform:**

* To go the webform tab where you manage the fields.
* Add a new field of type file:
* On the new field configuration page it's a good idea to set an Upload directory for your images. This means all the images upload from this field will sit in a particular folder in your files directly and help prevent too many files from sitting in one folder. You can also choose what types of files you want to allow users to upload. For an image field I would suggest only gif, jpg, and png.
* Set any other settings such a label or display settings as required.
* Finally save the component.
* Now when you visit the frontend of your webform you should see your new field:
> 2 votes

# Answer
Try Plupload for a start. Hope this helps.
> -1 votes

# Answer
In Webform - If you navigate to manage field of it. Then you should will be able to see field type as **Image**. Just add one field with that Image type after that you can upload your image.

If you are not able to see then check your Drupal db log. Might be there is error you will get to fix.
> -1 votes

# Answer
I'd recommend you to try Webform Select Image. This module adds a new image component to the webform.

> The purpose of this module is to add an images select component for webform (checkboxes or radios buttons).
>
> 1. Download and enable this module
> 2. Go to webform components admin page
> 3. Choose "Select image"
> 4. Upload your image, choose image style and other component settings
> -2 votes

---
Tags: entities, webforms, media
---


title: Where is FID xxx used?

text:
# Question
Title: Where is FID xxx used?
Is there a way to see where a file is used, with FID? I see the entry in the file\_managed-table (Drupal 7), but not where it is used.

# Answer
To show a usage list for a particular FID (file ID) you can visit the following url on your site:

```
/file/FID/usage

```

Just replace FID with the file id you want to check the usage for.

You can see an overview of all file usage at `/admin/content/file`. You can access this page from the admin toolbar at Content \> Files.

Here is an example of what the file usage table looks like on that page:

This shows the name of the entity where the file is in use, the entity type and the usage count.
> 1 votes

# Answer
It's in file\_usage :-)

In my case, the file was in the file\_managed, but not used anymore. Therefore, couldn't find it. A neat module is auditfiles
> 0 votes

---
Tags: files
---


# Question
Title: 7 - How to Add Custom Error Class to Radio Button and Checklist Fields
I created a field with Radio buttons and when it fails to validate, there is no red highlight around it.

There is only an error message at the top.

How can I add a custom CSS class to any radio button fields upon a failed validation?

I am already altering this form with hook\_form\_alter(); and have a custom validation function, so I am willing to work on a custom module for this but just need some help being pointed in the right direction.

I would ideally like to add a ".error" class or something to this div and customize it in my CSS to also give it a red border.

How can this be acheived?

# Answer
Out of the box webforms created with Drupal core and the Webform module do not have in line error messaging and indicators for each form field.

You can either:
> 1 votes

---
Tags: forms, hooks
---


# Question
Title: How to save custom fields when using hook_form_FORM_ID_alter?
I am implementing `hook_form_FORM_ID_alter()`. I have managed to setup for, and be able to collect custom values from the fields. When I submit the form, the node is created without my custom fields (i.e field\_1 an field\_2).

```
function mymodule_form_AYG_node_form_alter(&$form, &$form_state, $form_id){
  $options_first = _mymodule_get_first_dropdown_options();

  $selected = isset($form_state['values']['field_1']) ? $form_state['values']['field_1'] : key($options_first);

  $form['field_1'] = array(
    '#weight'=> -15,
    '#type' => 'select',
    '#title' => 'field 1',
    '#options' => $options_first,
    '#default_value' => $selected,
    '#ajax' => array(
      'callback' => 'mymodule_dependent_dropdown_callback',
      // 'wrapper' => 'dropdown-second-replace',
    ),
  );

   $form['field_2'] = array(
    '#weight'=> -14,
    '#type' => 'select',
    '#title' => 'field:',

    '#prefix' => '<div id="dropdown-second-replace">',
    '#suffix' => '</div>',

    '#options' => _mymodule_get_second_dropdown_options($selected),
    '#default_value' => isset($form_state['values']['field_2']) ? $form_state['values']['field_2'] : '',
  );

  $form['#validate'][] = 'mymodule_form_validate';
  $form['#submit'][] = 'mymodule_form_submit';

  return $form;
}

function mymodule_form_submit(&$form, $form_state) {
  // I can see values for the custom fields here.
  // How do I store them in the node?
  dpm($form_state);
}

```

I have installed the Entity API module, and tried the proposed solution. It gives me an error.

```
function mymodule_form_submit(&$form, $form_state) {
  $node = $form_state['node'];
  $node = node_load(arg(1));

  krumo($node);  // Getting FALSE here

  $obj = entity_metadata_wrapper('node', $node);
  $obj->field_1 = $form_state['values']['field_1'];
  $obj->field_2 = $form_state['values']['field_2'];
  $obj->save();
}

```

This is the error:

> EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityDrupalWrapper-\>set() (line 735 of E:\wamp\www\Classified\sites\all\modules\entity\includes\entity.wrapper.inc).
> The website encountered an unexpected error. Please try again later.

# Answer
> 2 votes
The only thing your form alter has done it added fields to a form. But you need somewhere to store the values of those fields.

When you add a field to an entity (node) using the Field UI module Drupal creates 2 database tables. One to store the field values and one to store older revisions of that fields value. Without these tables you don't have anywhere to store the values.

Here are steps to add that field your node bundle:

1. Make sure the Field UI module is enabled.
2. From the admin toolbar visit Structure \> Content types \> AYG (the name of your node type) \> Manage fields.
3. On this page add your new fields and configure as required.

Now your new fields will show on your node creation / edit forms and you will have tables to store the values of those fields.

# Answer
> 0 votes
My preferred way of saving field values to a node is by using the entity\_metadata\_wrapper() function that comes with the Entity module. It makes it easier for you to set or get values to and from a node object, or any other entity.

There is a good explanation of entity\_metadata\_wrapper() here.

So in your case, with the Entity module installed, you'd do something like:

```
// get the node object
$nid = $form['nid']['#value'];
$node = node_load($nid);

// create the helper object
$obj = entity_metadata_wrapper('node', $node);

// add the field data
$obj->field_1 = $form_state['values']['field_1'];
$obj->field_2 = $form_state['values']['field_2'];

// save the data
$obj->save();

```

# Answer
> 0 votes
For saving custom form element values, you have to implement hook\_node\_insert() in your module. I hope this tutorial will help you to understand.

---
Tags: 7, forms
---


# Question
Title: Programmatically adding registration type (Entity Registration module)
I am trying to programmatically add a registration type using the Entity Registration module and Drupal 7.

Currently I am using the following code:

```
$bundle = array(
    'type' => 'flake',
    'label' => $t('Flake'),
    'base' => 'registration',
    'custom' => TRUE,
);

$registration_type = registration_entity_set_default_settings($bundle);

registration_type_save($registration_type);

```

Among other thing, I have tried 'name' instead of 'label' and 'entity\_registration' instead of 'registration'.

As you can probably gather, I am new to creating types of any sort. I started by working off a tutorial for creating a regular content type and did not run into any problems. Figuring out how exactly that differs from the entity registration type has been a little challenging.

# Answer
Registration \_type is just an entity type so is exactly the same as creating any other entity:

```
$registration_type = entity_create('registration_type', array(
    'name' => 'flake',
    'label' => 'Flake',
));
entity_save('registration_type', $registration_type);

```

Sometimes it helps to create an entity via the UI provided with a module and then load and inspect it to help understand what values can be provided.

For example after creating a registration type visit `/devel/php` (make sure devel module is enabled) and run this code:

```
dpm(entity_load_single('registration_type', 1));

```

You should see an output similar to this:
> 1 votes

---
Tags: 7
---


# Question
Title: Create module with custom entity and CRUD
Using the Drupal CLI I've generated a D8 module. Now I want to generate a content type with additional fields, for which I can define my own CRUD, forms and other logic. I used `drupal generate:entity:bundle` which generates the new content type and makes it possible to add new fields through the admin interface.

I don't want to add fields through the UI; I want to add fields through code, so I can add new logic in the (CRUD) controller. This will be adding fields, defining new views, adding validation etc. I tried to use `drupal generate:entity:content`, but it doesn't seem to get me anywhere.

How could I do this?

# Answer
> 1 votes
The main purpose of content types/entity bundles is to allow users to configure/create subtypes/bundles of your entity type and add configurable fields to them.

If you want to have two different things, just create two different entity types. Each will have its own table then and its own set of fields. Completely separated.

If you want to have a single entity type/table with different sets of additional fields, then you can for example use entity bundles and just don't expose a UI for them, buy removing all forms, routes and the field\_ui\_base\_route. Then the only way to add per-bundle fields would be through the API/Code.

Or you implement it all yourself using bundleFieldDefinitions(), hook\_entity\_field\_storage\_info() and so on. But that would require quite a bit of code as you need to take care of installing the field storage definitions and so on.

# Answer
> 0 votes
I agree with eveything Berdir has said. I'm just adding an additional answer to show an example of how to add additional properties using baseFieldDefinitions().

---

I't important to understand the difference between entity properties and fields. Properties are just extra (database) fields in the entity base table. The advantages of this is you reduce the number of database tables and speed up queries retrieving data. This disadvantages of this is you cannot have multi cardinality fields or attach the same field to multiple bundles or entity types. Choosing whether to use a property of a field will depend on your specific requirements and the data you are trying to store.

---

If you decide that you want to add additional properties to your custom entity then you can follow these instructions.

After `drupal generate:entity:bundle` has finished running it will have created a new class for your custom entity. You can find this at src/Entity/MyEntity.php.

In this class there is a method called baseFieldDefinitions(). You can add additional field defintions in this method that will automatically get created when your module is enabled.

I've found it difficult to find any really good documentation on exactly what configuration options are available for each field type but I've found this page that has quite a good description of of the different field types that can be added and their properties. Looking at what the core modules do is also a good way to learn.

Here are a couple of examples I've used in my own modules:

**String**

```
$fields['type'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Type'))
  ->setSettings([
    'max_length' => 50,
    'text_processing' => 0,
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => 1,
  ])
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    'weight' => 1,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

**Entity reference**

```
fields['campus'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Campus'))
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings', [
      'target_bundles' => [
        'campus' => 'campus'
      ]
  ])
  ->setDisplayOptions('view', [
    'label' => 'above',
    'weight' => 2,
  ])
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 2,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '20',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

---
Tags: 8, entities
---


# Question
Title: Would enabling 'Use Ajax' for view content harm our SEO?
**Background:**

We currently use a View to allow users to browse/search among the several hundred guidance pages on our website.

The current UX of the View is not ideal - using the exposed filters causes the whole page to reload, meaning that users have to:

a). Wait for full page reload b). Scroll back down to the results grid

**Question:**

I was wondering if anyone had any experience using the '*Use Ajax*' setting on a View - specifically in terms of any effect on their SEO?

All our guidance pages are listed on our sitemap, and most are linked to from other pages, but this View is the main, most trafficked area pointing towards them.

How likely is it that the switch would mean that search engines aren't able to/are less able to find/index them?

# Answer
> 1 votes
It will only have an effect if there is content that you want to be visible to the search engine crawlers that is only accessible after having run any JavaScript (aka an ajax call).

For example maybe you want to be optimising for the key word carrot, and there is lots of content about carrots that only appears on page 2 of your view. To get to page two you have to do an ajax request so crawlers will never get there and it will in this instance negatively impact your SEO.

This is quite specific though, and could easily be mitigated against by ensuring your important content on carrots appears on the first page of the view.

So I guess it could have an impact, but it's unlikely that it will be a very big one. But certainly something to consider.

Google has a tool that allows you to fetch a page of your website and preview how it looks to the crawler. This could be useful for testing exactly what impact enabling ajax on your view will have.

---
Tags: views, ajax
---


# Question
Title: Private file folder outside document root
I am setting up a private files folder outside of www. I have set the permissions to allow access to the folder by www-data to read and write but not execute, however, my drupal 8 site is now showing an error:

> PRIVATE FILES DIRECTORY Not fully protected See https://www.drupal.org/SA-CORE-2013-003 for information about the recommended .htaccess file which should be added to the /var/drupal\_data directory to help protect against arbitrary code execution.

That link is to an advisory and fixes regarding Drupal 6 and 7. There is no mention of of Drupal 8 and it appears reasonably out of date:

> 20 Nov 2013

I didn't think apache could even utilise htaccess outside of the www folder in such a way.

Is there some other configuration or permission I need to be changing?

Up until now, for testing, I have had a private folder within the public files directory. I wish to move the private files directory outside the root directory as I am lead to believe it is better for security.

While many guides discuss the best practice of moving this folder outside the root directory few go in to much detail about either why that is beneficial or how that changes the site setup. If there are good recent explanations for this practice I would appreciate being directed to them.

# Answer
Looking at the code in system.install that raises this error it just checks if `private://.htaccess` exists:

```
$htaccess_files['private://.htaccess'] = [
    'title' => t('Private files directory'),
    'directory' => drupal_realpath('private://'),
];

...

foreach ($htaccess_files as $htaccess_file => $info) {
  // Check for the string which was added to the recommended .htaccess file
  // in the latest security update.
  if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
    $url = 'https://www.drupal.org/SA-CORE-2013-003';
    $requirements[$htaccess_file] = [
      'title' => $info['title'],
      'value' => t('Not fully protected'),
      'severity' => REQUIREMENT_ERROR,
      'description' => t('See <a href=":url">@url</a> for information about the recommended .htaccess file which should be added to the %directory directory to help protect against arbitrary code execution.', [':url' => $url, '@url' => $url, '%directory' => $info['directory']]),
    ];
  }
}

```

At no point does it check if your private file directly is actually inside webroot or not.

This means in your case it's a false warning and you can ignore it, as your right in saying there is no point putting an .htacess file to deny access in a folder outside of webroot.
> 2 votes

---
Tags: 8, files
---


# Question
Title: Views REST Export and Multi-Value Fields
I'm having trouble getting the Views REST export to work nicely with multi-value fields. I have an image field that can have multiple images. I have added the field to my REST export View, however all values are being output on the same line. Like this:

```
[
    {
        "nid": "11",
        "image": "http://example.com/sites/default/files/2016-02/mobile-1.jpg\n,   http://example.com/sites/default/files/2016-02/mobile-2.jpg\n"
    }
]

```

What I would like to achieve is something like this:

```
[
   {
      "nid":"11",
      "image":{
         "0":"http://example.com/sites/default/files/2016-02/mobile-1.jpg\n",
         "1":"http://example.com/sites/default/files/2016-02/mobile-2.jpg\n"
      }
   }
]

```

Is this possible? Perhaps using HOOK\_views\_pre\_render() to change the returned value?

# Answer
> 1 votes
This looks like it's a plain bug. Please report it to the `views.module` issue queue in Drupal core: https://drupal.org/project/issues/drupal?component=views.module.

# Answer
> 0 votes
This happens even in 8.4, so I had to use the Views Field View plugin to create a view for just the list items (in your case, a list of image URLs) and add that view as a field to the main view. This works conceptually, but the output of the child view is littered with HTML which I can't seem to figure out a way to get rid of.

---
Tags: views, 8
---


# Question
Title: How to add discount programmatically in drupal commerce
I have custom staff interface where staff select products and select discount for overall order. On click of submit all data are passed in json format to drupal custom menu.

Custom function correctly create order, product, tax. Below is custom function which is called on submit

```
function add_to_cart() {
  $reservationData = json_decode(file_get_contents("php://input"));
  foreach($reservationData as $key => $values) {
  if (!empty($values->rooms)) {
    foreach ($values->rooms as $k => $v) {
      .... //more code
      $product = commerce_product_load($product_id);
      $line_item = commerce_product_line_item_new($product, 1, 0, array(), 'roomify_accommodation_booking');
      $ntype = array('target_id'=> $product_id);
      // Add line item to cart.
      $line_item = commerce_cart_product_add($userID, $line_item, FALSE);
      .... //more code
      //calculate tax rate for each line item
      $taxRates = commerce_tax_rates();
      commerce_tax_rate_apply($taxRates["room_tax"], $line_item);
      commerce_line_item_save($line_item);
    }
   }
  }
  $order = commerce_cart_order_load($userID);
  $order->status = 'pending';
  commerce_order_save($order);
}

```

Even after adding below code it give me error

```
// Add the line item to the order using the wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  commerce_discount_fixed_amount($order_wrapper, 'discount_test_discount');

```

**Fatal error**: Call to undefined function commerce\_discount\_fixed\_amount() in **../sites/all/modules/reservation/reservation.module** on line **145**

how should I apply DISCOUNT on overall total amount?.

# Answer
I haven't tried what you are trying to achieve. You need to enable the commerce\_discount module in order to use the function (commerce\_discount\_fixed\_amount).
> 1 votes

---
Tags: commerce
---


# Question
Title: how to get location tokens to work in pathauto
I am attempting to use a city location in the URL via pathauto. I have this for the URL \[node:title\]/\[node:location:city:0\]

When I create a new node, however, only the title is inserted into the URL.

Any ideas how to make this work?

# Answer
> 0 votes
Remember that token \[node:location:city:?\] is from location\_node module, not from cck field. Did you created your own field with location in your node? In this case you have to enable location\_entity module and using \[node:field\_mylocation:city:?\] token.

---
Tags: tokens, location
---


# Question
Title: How to get Search API module to index the full country and state name from Addressfield Module?
The Addressfield module stores an abbrivated name for countries and state such as US for United States and FL for Florida. The Search API indexes the these words which are not very useful when doing searches for places like New York, Boston, France, ect.. Should I just discard the Addressfield module and make text fields or is there another way to go about doing this?

# Answer
you might want to use SOLR search and write a synonym.txt file to translate the state and country codes into names
> 1 votes

# Answer
I have created a sandbox module called Search API Addressfield Country Name which handles the conversion of 2-letter country codes to country names.

For expanding state names, check out the issue on Drupal.org Integrate Addressfield with Search API
> 1 votes

# Answer
Unless somebody is going to write a rather sophisticated plugin or module to do this as contrib to either the Addressfield module or Search API I doubt this will ever work. The Addressfield module is extremely complex not opening itself to easy integration. Sadly, the best solution is the simplest which is to create text fields. The Geocode module still geocodes the addresses which can be used by the Apache Solr Seach API which is nice.
> 0 votes

---
Tags: search, entities
---


# Question
Title: Get a dropdown for Views: Filter: Taxonomy Term Name
I'm using taxonomy term name to filter views based on their taxonomy. I've tried basic or Better Exposed Filters and setting a relationship but still no option for a drop-down select menu.

I can't use filter by "Taxonomy Term: Term" because this uses the TID not Term Name in URL.

# Answer
> 0 votes
If your views is based in content type, you should use the term reference field in the filter. Example:

I have a content type of services composed of *title, body, service category(term reference)*. In my services views, I will add service category as filter. In my **Better Exposed Filter**, I can configure that service category if I want a drop down filter or autocomplete.

Using taxonomy term name shows autocomplete filter.

I hope it helps

---
Tags: 7, views
---


title: Filter content by taxonomy url

text:
# Question
Title: Filter content by taxonomy url
I have a view page that displays a group of content fields. Attached to the content type there is a taxonomy term field.

How do I get contextual filters to recognize second path component of the URL and then filter it against the taxonomy terms on the page views? See attached images

# Answer
You can do this approach:

First create a views and add a path with wildcard

Second add a contextual filter Content: Has taxonomy term ID and do this:

Third test it, type the path name of your taxonomy and hit update preview.

I hope this helps you.
> 2 votes

# Answer
You have to create a relationship to your taxonomy, and on your view path you can specify which field you want to use to filter. You also have to add a contextual filter to your view.
> 2 votes

---
Tags: views
---


# Question
Title: Passing values from EntityFieldQuery to db_select
Checked for this, but don't seem to be any specific answers to this question.

I'm trying to pass results from EntityFieldQuery to a db\_select query, via a string. However, although debugging both queries with set values shows that they are operating correctly and providing the desired results, when using the string in db\_select I am getting null results.

The purpose is to get certain node ID's as an integer value and pass them as an array of Entity\_ID integer values, so the db\_select function only selects table rows which match a certain Entity\_ID.

I presume I'm making a output format error for the EntityFieldQuery, but can't work out what exactly it is. Code is as follows:

```
// EntityFieldQuery
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                   ->entityCondition('bundle', 'contenttype1')
                   ->propertyCondition('status', 1)
                    ->fieldCondition('field_field', 'value', $contenttype2, '=')
                   ->fieldOrderBy('field_field', 'value', 'ASC')
                    ->execute();

// Debugging functions only, return correct values when tested
$show = array_keys($entities['node']);
echo 'this is show: ' . $show;

$print = var_dump($show);
echo 'this is print: ' . $print;

// db_select function, returns correct sum when '$entities' is replaced with integer value for entity_id
$dbquery = db_select('tablename', 't')
  ->condition('t.entity_id', '$entities', '=');
$dbquery->addExpression('SUM(value)', 'value');

$result = $dbquery->execute()->fetchField();

// Debugging function only
print 'this is result: ' . $result;

```

The EntityFieldQuery is producing the correct values, but it isn't clear that they are in the correct format. The $print output is:

```
array(2) { [0]=>int(213) [1]=>int(214) }

```

At present, the SUM result works correctly when I replace '$entities' in the db\_select with (e.g.) '213', but returns 0.0 when I use '$entities'.

EDIT: using

```
dpq($dbquery);
dpr($result);

```

Gives the confirm message:

```
SELECT SUM(value) AS value
FROM
{votingapi_vote} v
WHERE  (v.entity_id = )

```

And the error message:

```
Warning: PDO::quote() expects parameter 1 to be string, array given in dpq() (line 1835 of /var/www/html/sites/all/modules/devel/devel.module).

```

What is the output format code / function I should be using for EntityFieldQuery?

# Answer
Try this approach. after getting your entities using **EntityFieldQuery**, create a **for loop** in order to check the **val** that was stored in your **variable $entities**. Then use **dsm or dpm** to check if it **returns a result**.

```
$results = '';
for ($i=0; $i < count($your_entity) ; $i++) {
    $query = db_select('yourtablename', 't');
    $query->fields('t');
    $query->condition('t.entity_id', $your_variable);
    $results = $query->execute()->fetchAll();
}
dsm($results);

```

Hope this helps you.
> 0 votes

---
Tags: 7, database
---


title: Sort with entityTypeManager

text:
# Question
Title: Sort with entityTypeManager
I'm running an app where I am searching for every nodes of a given content type.

```
$nids = \Drupal::entityTypeManager()
  ->getListBuilder('node')
  ->getStorage()
  ->loadByProperties([
    'type' => 'courses',
    'status' => 1,
]);

```

I'm searching for a way to sort the results among a custom field of my nodes.

EDIT: I do not understand what's going on. Thanks to @4k4, I wrote this query:

```
$query = \Drupal::entityTypeManager()
    ->getListBuilder('node')
    ->getStorage()
    ->getQuery();
$query->condition('type', 'post');
$query->condition('status', 1);
$query->condition('field_category', $k);
$query->sort('field_ordering', 'ASC');

$nids = $query->execute();
$nids = Node::loadMultiple($nids);

```

A `var_dump` on `$r[1]` prints nothing. Same for `$r[2]`. But $results contains my results. What's going on ? The sorting doesn't work by the way.

# Answer
> 8 votes
The change record says if you have entityTypeManager injected, use

```
$query = $this->entityTypeManager->getStorage('node')->getQuery();

```

For non-OOP code, `$query = \Drupal::entityQuery();` is not deprecated and can still be used.

The linked example for sorting an entity query by using `$query`:

```
$query->condition('type', 'blog_post')
  ->sort('field', 'DESC');
$nids = $query->execute();

```

---
Tags: 8, entities
---


# Question
Title: How to reduce the time needed to export a view with 50k rows into a CSV file?
I am having a view with 50k records I want to export the view as CSV. I tried Views data export module but it takes around 20 min to export the data.

I have configured the view to use Batch export with **Segment size** 100. I want to reduce the export time. Is there any way to do it?

# Answer
As an alternative to using Views (and Views data export), you may want to give it a try using the Forena module (disclosure: I'm a co-mainter). If you do, I doubt it'd take 20 mins to complete such export (my bet is somewhere around 30 to 60 secs, at max ...).

To perform such export using Forena, just create a "report" to select (and sort, etc) the 50K records you want to export using the Forena module. And specify what kind of hyperlinks you want to make available for performing such "export". These hyperlinks correspond to various supported "formats", such as: CSV, PDF, XLS, XML, DOC, HTML ... (the "report designer" selects what the allowed/enabled export formats for a report are).

To get an idea of how that would look like, visit the Customized Simple Table of States. Notice the links in it, such as "CSV" (upper right), which in this case would "export" the results in a CSV file.
> 1 votes

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


# Question
Title: Durpal 8 on install new module, insert data in new created table
I created a new table into the new schema and I want to insert default data into it. How can I do this in the module.install file ?

# Answer
> 1 votes
To run tasks when your module is installed, use `hook_install()`, e.g.

```
function module_install() {
  \Database::getConnection()->insert(...)->execute();
}

```

---
Tags: 8, hooks, installation
---


# Question
Title: Drupal 8: How to retrieve field values when i use loadMultiple to load multiple node ids
I am loading multiple node ids like below

```
$node_storage = \Drupal::entityTypeManager()->getStorage('user')->loadMultiple($nids);
foreach ($node_storage as $node){
  $value = $node->get('field_merchant_id')->value;
}

```

After this, I am getting an object and I don't know how to access my values. I have used `get('field_name')->value` but its saying `Error: Call to a member function get() on array`. How can I get an array that contains all values of one specific column from all nodes?

# Answer
> 7 votes
You should do like

```
$node_storage = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($node_storage as $node){
   $field_merchant_id = $node->get('field_merchant_id')->value;
}

```

Here you are using "user" which should be replaced by "node" to access node values. And also to access "field\_merchant\_id", you need to get that from $node.

---
Tags: nodes, entities
---


# Question
Title: How can I programatically change the (D8 core) workflow state of an entity with Content Moderation?
I'm using Drupal 8.4-rc2. When you enable the Workflow and Content Moderation modules, you automatically get the **Editorial Workflow** as a demonstration.

The states are as follows:

* Archived
* Draft
* Published

And the transitions are as follows:

* Create new draft (from draft/published to draft)
* Publish (from draft/published to published)

How can I programatically call a transition? Or, how can I programatically change the state without calling a transition (although this seems to violate the spirit of having transitions defined in the first place)?

Specifically, I have a node subject to content moderation (states: archived, draft, published). By default, on the edit node page, the node is saved in the original state (so a draft node is saved as a draft). I want to add a second button "save as published" with a submit handler, but I don't understand how I can programatically change the state.

What I do understand so far is that workflows are entities and so are states, so it's different than Drupal 7 in which most workflow-type modules used fields to track what was going on.

I checked the Examples module but there's nothing on configuration management/workflows yet.

# Answer
A great example could be found in Content Moderation module's code.

```
$entity->set('moderation_state', $new_state);
if ($entity instanceof RevisionLogInterface) {
  $entity->setRevisionLogMessage($form_state->getValue('revision_log'));
  $entity->setRevisionUserId($this->currentUser()->id());
}
$entity->save();

```
> 12 votes

# Answer
I'm not heavily using D8 yet, but in D7's Workbench Moderation module nodes had a moderation\_state field that was Draft or Published. Transitions in D7 were typically for User Role workflows whereas in code you typically modified the node states directly via node\_load and node\_save .... If D8 was inspired by the d7 module, the implementation may be similar.

Did you see the Tests referenced here found in the Examples links: https://www.drupal.org/docs/8/core/modules/workflows/overview and example node moderation field modifications here http://cgit.drupalcode.org/drupal/tree/core/modules/content\_moderation/tests/src/Functional/ModerationStateNodeTest.php
> 2 votes

---
Tags: 8, configuration, workflows
---


# Question
Title: How do I enable a REST resource for a custom content type?
I've created a bunch of custom content types like "Car Makes" and "Car Models", but I can't seem to figure out how to enable a REST resource for them. In my REST settings page, I see the default content, content type, user, user registration enabled and a lot of disabled types below it. This list doesn't contain any of my custom created types.

If I go to the permissions page, under "RESTful Web Services", I only see "Administer REST resource configuration" and "Access POST on User registration resource". How can I enable "Car Makes" as a REST resource and directly `GET`/`POST` with it?

I saw this screenshot, but I don't get anything like this in Drupal 8.4:

In this screenshot, Todo is a custom resource, which requires writing a plugin. Do I have to write a plugin module just to expose each of my custom content types in REST?

I can work directly with the content endpoints, i.e. `POST /node/123`, but I would like to `POST /carmakes`, for example.

# Answer
If you want to access these types of content separately, you must do the following:

1. download the module restui: https://www.drupal.org/project/restui/releases/8.x-1.x-dev
2. Go to Extend, activate the modules, HAL, HTTP Basic Authentication, RESTful Web Services, Serialization, and REST UI.
3. go to `/ admin / config / services / rest`
4. Edit the RESOURCE NAME Content, and mark all the checkboxes.
5. Then you should perform a test in the browser with the following path: `drupal8 / node / 1? _format = json`

note: if the information is displayed, it means that the rest server is set correctly.

6. Create a view and select the type of content you want to display and in the "REST EXPORT SETTINGS" section mark the "Provide a REST export" checkbox and in "REST export path" type "car\_makes".

This way if you go to the route: `/ drupal8 / en / car_makes` you will see that it will show the information in json format.
> 0 votes

---
Tags: nodes, 8
---


# Question
Title: Language fallback for unpublished translation
on our Drupal 7, we have pages in 6 different languages. We'd like to remove the translation for some nodes.

I thought that users would be automatically redirected to the default (English) language when trying to access this unpublished translation, but this is not the case, they have a "not found" page.

I installed the language fallback module and configured all languages to fallback to English, but this did not help.

Is there something else I can do so that all traffic to unpublished translations is redirected to the default node translation ?

# Answer
> 0 votes
I never used it, but this module seems correspond to your problem https://www.drupal.org/project/multilink

---
Tags: 7, i18n-l10n
---


# Question
Title: WSOD after installing and setting a customtheme (subtheme of thunder_base)
I'm pretty new to Drupal so bear with me pls. I created a customtheme (following standards that "some" guides described) i can install my customtheme from "Appearances" everything worked fine thus far but i have no markup at all on my site it's blank (no error whatsoever) and i can't seem to figure out why (since my info.yml and my libraries.yml seem to be correct containing all the "required" settings). I rechecked all file&directory names and the dir.-structure and everything "seems" to be correct (aside from the fact that i have no markup on my page). I'm using the latest Acquia installation (8.3.7). Any help would be appreciated let me know if i should bring up more information about the issue. Thanks in Advance. I attached my libraries.yml and my info.yml

**dptheme.info.yml**

```

name: dptheme
type: theme
base theme: thunder_base
description: 'all golden and fancy DPtheme.'
package: custom
core: 8.x
libraries:
  - dptheme/global-styling

```

**dptheme.libraries.yml**

```

global-styling:
  version: VERSION
  css:
    theme:
      css/dptheme.css: {}
      css/components/taxonomy-term.css: {}
      css/node-image-field-fix.css: {}
      css/components/tour.theme.css: {}

```

# Answer
> 0 votes
As the OP answered there was a problem with folder structure custom theme files being empty and fixing that resolved the issue.

With this answer though I want to emphasize that Drupal 8 has a well documented theming guide here and also you can find specifics for folder structure here.

# Answer
> -2 votes
Well i had empty template files in my "custom" templatedirectory so the core templates wouldnt be "applied" (i didnt know about that and no guide mentioning this at all but having me apply a "certain" folder structure with "certain" required files wether they are actually required or not). So 2 "solutions" either copy/paste the core templates (block.html.twig, node.html.twig etc.) in your template folder or remove the empty twig files (from the custom templatedir so the core templates can be applied). Thx for the help guys !

---
Tags: wsod
---


# Question
Title: How can we get Block Bundle Type for block in code?
I am trying to override block content by using hook\_preprocess\_block(&$variables). I was expecting to find bundle type in `$variable`, but not getting anything related to this.

Here is kint display of $variable inside the function -

More Info - This is a block type (say `content_slider`) created from Drupal UI & a block (say `content_slider_homepage`) is added.

# Answer
> 4 votes
The UUID from the custom block is in the variable `derivative_plugin_id`. You can use this UUID to load the block and get the bundle:

```
$block = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);

if ($block) {
  $block_type = $block->bundle();
}

```

Or look in `$variables['elements']`. Here you'll find the custom block entity loaded in the variables and probably the block type as well. You can also use `hook_block_content_view()` if this is for a module. See the comments from @Berdir.

# Answer
> 7 votes
This is how I would do it:

```
use \Drupal\block_content\BlockContentInterface;

/**
 * Implements HOOK_preprocess_block().
 *
 * @param $variables
 */
function mymodule_preprocess_block(&$variables) {
  $content = $variables['elements']['content'];
  if (isset($content['#block_content']) && $content['#block_content'] instanceof BlockContentInterface) {

    if ($content['#block_content']->bundle() == 'xxx') {
      // ...
    }

  }
}

```

---
Tags: 8, blocks
---


# Question
Title: Expand sub-menus on hover in a menu block
I need to show menus expanded in the sidebar. I used the menu blocks to show the submenus. But now the problems is when I hover on the parent menu initially it is not showing the submenus which was appearing before.
And also submenus is expanded only when click the parent menu which then lists all the submenus with expanded.

Please tell me how to show the submenus on hover in menu blocks when the submenus are not expanded

# Answer
You can use this module Nice Menus. Nice Menus enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)

> Three styles/types of menus are currently possible: horizontal, menus drop down; vertical, menus fly to the left; vertical, menus fly to the right. There is a handbook page that provides a list of sites that use Nice menus.
> 1 votes

# Answer
The DHTML Menu module https://drupal.org/project/dhtml\_menu should do what you're looking for. The module description suggests that you need to click on items to expand them, but newer versions of the module have a "hover" option. Make sure you use the "dev" version as the recommended release is very old and doesn't contain the newest features.
> 0 votes

# Answer
First you can display all the elements of the menu and then using CSS you can hide all the child elements and when you hover over the parent elements to display their childs.

Or, simpler you can use this module (CSSMenu), you can read the documentation on how to do it, but it's pretty straightforward. Also here is a demonstration on what this module does.
> 0 votes

# Answer
For all versions there is easy solution I haven't found anywhere:( Go to CSS and add display: block; to expandable menu on :hover.In my case as example:

```
.navbar-default .navbar-nav li:hover .dropdown-menu{
    display: block;
}

```
> 0 votes

---
Tags: routes, blocks
---


title: How to use minipanels in a menu

text:
# Question
Title: How to use minipanels in a menu
I tried to install the module Menu Minipanels, without success. I tried both the 1.x and 2.x version but the minipanel don't show up in the menu. After half a day I gave up.

I do like the idea of a megamenu using minipanels, so this question is: How to use minipanels in a menu, without the 'Menu Minipanels' module?

EDIT: I got Menu Minipanels working at last, but it has a major bug that anonymous users can't see the minipanels in the menu! Back to square one.

So again the same question..

# Answer
I now used a workaround, instead of the 'menu minipanels' module, i am using 'Menu Attach block' which simply allows to insert minipanels too since they are available as blocks.
> 0 votes

---
Tags: 7, panels
---


# Question
Title: How do I filter users by status not blocked?
I created a Drupal 7 view that displays users profile 2 fields. However if i disable the user their fields are still visible in the view. Is there a way i can filter users by their status of blocked or active?

# Answer
> 1 votes
The steps are:

View name: test Show: Profiles of type: All

Page title: test Display format: table.

click "Continue & edit" button.

In the "FIELDS"

add the "Profile: User uid" field and add all fields related to the profile module.

Then add a relation in the path: Advanced-\> RELATIONSHIPS

select the "Profile: User uid" field.

mark the checkbox "Require this relationship".

Click "apply (all displays)" button.

Then add a filter to "FILTER CRITERIA".

Seach and check the field: "User: Active"

We checked the checkbox: "Expose this filter to visitors, to allow them to change it"

Click "apply (all displays)" button.

Click "save" button.

---
Tags: 7, views
---


title: D8: render block in node?

text:
# Question
Title: D8: render block in node?
We're migrating some code to D8 and in some of our nodes' body field we used to call PHP code directly with the now defunct `module_invoke` to render a block in the node before the content.

All the examples I can find explain how to do that in D8 with themes or templates, but I need to render the block inside the node body using PHP code, is there a way to do that?

We already tried:

```
\Drupal::moduleHandler()->invoke($module, $hook, $args = array())

```

but it doesn't show the block, presumably because it only takes modules?

From this answer we also tried:

```
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);

```

Trying to print or render `$render` either doesn't show anything or literally prints out an array.

# Answer
You can do the following:

In hook\_preprocess\_page() add the following code.

```
$block_entity = Drupal\block_content\Entity\BlockContent::load(BLOCK_ID);// BLOCK_ID
$block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'DISPLAY_VIEW_NAME');
if ($block_view) {
    $variables['page']['my_block'] = $block_view;
}

```

In your Twig template, print the block with the following code.

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

```
> 2 votes

---
Tags: 8, nodes, blocks
---


title: How to import rules on site install?

text:
# Question
Title: How to import rules on site install?
When I go and export my rule, I get the following:

```
{ "rules_vote_points" : {
    "LABEL" : "Vote points",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "userpoints_rules", "voting_rules" ],
    "ON" : [ "voting_rules_insert_node" ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "3",
          "tid" : "0",
          "entity" : [ "node" ],
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "approved"
        }
      }
    ]
  }
}

```

Where could I put this to import it in the site install? E.g. I am importing views with a `hook_views_api` hook in my module and a `module.views_default.inc` file that searches through the views folder and imports the views, and content types are created with hook\_install in .install files in my modules. But how do I import the following?

# Answer
Assuming this is for D7, try this code (which includes a copy of your exported rule):

```
function my_module_default_rules_configuration() {
  $configs = array();
  $rule = '{ "rules_vote_points" : {
      "LABEL" : "Vote points",
      "PLUGIN" : "reaction rule",
      "REQUIRES" : [ "userpoints_rules", "voting_rules" ],
      "ON" : [ "voting_rules_insert_node" ],
      "DO" : [
        { "userpoints_action_grant_points" : {
            "user" : [ "node:author" ],
            "points" : "3",
            "tid" : "0",
            "entity" : [ "node" ],
            "operation" : "Insert",
            "display" : 1,
            "moderate" : "approved"
          }
        }
      ]
    }
  }';
  $configs['rules_vote_points'] = entity_import('rules_config', $rule);
  return $configs;
}

```

PS: have a look at the code of the Answers Userpoints module for an example where this technique is used also (contained in `answers_userpoints.rules_defaults.inc`).
> 1 votes

---
Tags: rules, installation
---


# Question
Title: Creating paragraph entities and adding to a node
I am using the Paragraph module in and I need to programmatically create paragraph entities and attach them to nodes.

Using the following code in a for-loop:

```
$paragraph = new ParagraphsItemEntity(array('field_name' => 'field_page_body', 'bundle' => 'text'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);
$paragraph->save(TRUE);

```

The paragraph entities are created and attached to the target node but the data is `NULL` for all 3 entries as the image below shows:

A properly working set of Paragraph entities attached to a node look like the following:

So, instead of **UND** i:e undefined, I am trying to attach programmatically created arrays of paragraph entities to my nodes.

Can anyone advice how I can modify my code to include my array of Paragraphs data?

# Answer
I have a similar function and would recommend that if you already know what language your node is, you capture it from the node and use it for the language in the paragraph field. I only had 1 language to worry about but you could easily replace LANGUAGE\_NONE('und') with the appropriate language code from the node.

```
$paragraph = new ParagraphsItemEntity([
  'field_name' => $host_field_name,
  'bundle'     => $para_bundle,
]);
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', node_load($this->node->nid));
$paragraph->field_long_text[LANGUAGE_NONE][0]['value'] = $field_content;
$paragraph->field_long_text[LANGUAGE_NONE][0]['format'] = 'wysiwyg';
$paragraph->save();

```
> 0 votes

---
Tags: 7, entities, paragraphs
---


# Question
Title: Different home pages based on different conditions?
I have two pages:

```
/home
/pr

```

Currently, under site configuration, I have /home as the home page. So whenever someone open mysite1.com, it will show the contents at /home. However, multiple domains are parked on this site. I want it in the case of mysite2.com is opened, the /pr page must show, but if mysite1.com is opened, it must show /home like it always does.

At what point would I be able to do this? Where can I incorporate this logic?

# Answer
You could do this in settings.php and define `$conf['site_frontpage']` from a server variable like `$_SERVER['HTTP_HOST']`. The same logic would allow you to set your `$base_url`(D7) or `$settings['trusted_host_patterns']`(D8) to the correct domain as well.
> 0 votes

---
Tags: 8
---


# Question
Title: Referenced Entity not Updating Correctly When Saved
I have node A that contains an Entity Reference Revisions field in it set to display as a Rendered Entity that points to node B of a different content type.

Initially this works fine. However, if I make an update to node B and save it, the changes don't appear on node A until I edit and save node A again.

It seems like it should update without having to re-save the parent node. Is there a way around this?

# Answer
What is the reason you use a *Entity Reference Revisions* field? Normally this is more suitable for entities edited inline like paragraphs.

In your case this behavior seems to be what you would expect from this field, because you reference a specific revision of node B and not the latest version you've saved. If you want to do this, then use the core reference field.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: How do I update Drupal 8.2.3 REST configurations for an entity?
According to the documentation, I need to update the REST configuration for each entity type. RESTUI seems not to work with 8.2.3, so I figure I'm supposed to update this by hand, for example in rest.resource.entity.node.yml.

I do that, and then I'm stuck. Where does this file go? Does it go in my code somewhere? Am I supposed to import it through Configuration Synchronization (admin/config/development/configuration/single/import)?

I did try to import using Config Synch, but I got the following error, which means nothing to a newbie like me: `An entity with this machine name already exists but the import did not specify a UUID.`

Sorry if this is already documented somewhere, but I can't find an explanation anywhere for how to update these settings, and they seem pretty important for using the REST services. I'm currently using the Features Module as a workaround but it's kind of an ugly approach for something that seems like it should be simple.

Thanks in advance!

# Answer
> 1 votes
To answer your second question, you'll want to remove the imported configuration from the database and then reimport it with an included UUID - after which you can overwrite the config by re-importing it as many times as you like.

But first, when you upload a config, you should give it a more meaningful ID; rather than 'entity.node', you want something like 'my\_config\_for\_this\_thing'.

So in steps:

1. In your DB, find the config you uploaded (and see note about about the config ID):

```
select name from config where name like '%entity.node%';

```
2. Copy the full name that matches your config. It will be something like 'migrate\_plus.migration.entity.node'.
3. Delete that row from the database

```
delete from config where name = '*paste that name here*';

```
4. In your yml file, include a uuid. You can generate one locally or using a web tool such as https://www.uuidgenerator.net. This will look something like

```
id: some_meaningful_identifier
label: 'A label to describe my config'
status: true
uuid: ac1d69cc-382f-49d2-921e-bb0673fd62ea

```
5. Clear your Drupal cache
6. Then re-import and you should be in better shape.

---
Tags: 8
---


# Question
Title: How to redirect anonymous user to 404 instead of 403?
I'm new to Drupal so am struggling here. I've created a checkbox field and the goals is that when it is checked it redirects anonymous to the 404 page.

I have the following condition:

```
function page_module_preprocess_page(&$variables) {

 // code to retrive checkbox value

 if (user_is_anonymous() && $page_hidden_value == 1) {
    drupal_not_found();
  }
}

```

But this doesnt work.

However, interestingly enough if I do the reverse and check that the user is logged in (`!user_is_anonymous()`) it does work and does redirect to 404.

I can DPM the value of the checkbox (`$page_hidden_value`) so I know that's working correctly.

Would anyone know what could be going on here?

# Answer
I have had some odd experiences with `user_is_anonymous()`. Try using negation with `user_is_logged_in()`. For example:

```
if (!user_is_logged_in()) {
    // Do stuff
}

```
> 0 votes

# Answer
I kind of got this working with `drupal_goto`

```
 if (user_is_anonymous() && $page_hidden_value == 1) {
    drupal_goto('/404');
  }

```
> 0 votes

---
Tags: 7, users, redirection
---


title: Drupal form_state sanitization

text:
# Question
Title: Drupal form_state sanitization
I'm new to Drupal and I am doing some module development for a Drupal 7 install. I've done development outside of Drupal and normally its best to always sanitize user input. I've seen different opinions of the matter but from what I have picked up is dont use form\_state\['input'\] but what about form\_state\['storage'\] or form\_state\['value'\]. I'm seeing some people say the API does the sanitizing and others say always sanitize. Can anyone explain to be best practice?

# Answer
The values in `$form_state['values']` are all sanitized.

The values in `$form_state['input']` are the raw unsanitized form values.

`$form_state['storage']` is usually only used on multistep forms to keep data for other form steps.

Where possible always use the values from `$form_state['values']`.

See this post for more information: Avoid using data from $form\_state\['input'\]

To quote that linked article:

> The Form API's drupal\_validate\_form() and \_form\_validate() functions take care of populating a safe set of data in $form\_state\['values'\], using sanitized data from $form\_state\['input'\].
> 2 votes

---
Tags: webforms, security
---


# Question
Title: How to share content and files with other users within the site (not in facebook or other social media)?
Users would like to be able to share content with other users within the site (not on Facebook or any other social media).

For example, if I read a blog that I like and think my colleague would be interested I could click 'SHARE' and send it to another user's profile or work e-mail address. Or tag someone? This would require a notification to the user that they have shared or tagged in something.

It would be great to be able to do this with blog posts, files, photos, and videos. "

# Answer
> 1 votes
Besides the custom approach identified above, you may also want to look into using the Forward module.

https://www.drupal.org/project/forward

It includes some basic tracking for reports as well.

---
Tags: 7, users
---


title: Combine 2 fields in one div with Twig

text:
# Question
Title: Combine 2 fields in one div with Twig
I have three templates

1. field--field-custom.html.twig
2. field--field-custom1.html.twig
3. field--field-image.html.twig

I also have a teaser template containing all three fields like that:

```
<div{{ content_attributes.addClass('node__content', 'container') }}>
    {{ content }}
</div>

```

I want to have the first two templates in a bootstrap div, for example

```
col-sm-6

```

and the third template in the other div

```
col-sm-6

```

If I include the second template in the first template file it just repeats the field instead of rendering the intended field (both templates are name suggestions of the same file). What can I do in order to have both fields in the same template file?

# Answer
Just chunk the output by using the field names:

`<div class=“col-6-sm”>{{ content.field_custom }} {{ content.field_custom1 }}</div>`

Then do the same for the remaining field.
> 1 votes

# Answer
```
<div{{ content_attributes.addClass('node__content', 'container', 'col-sm-6') }}>
    {{ content.field_imagen }}
  </div>
  <div{{ content_attributes.addClass('node__content', 'container', 'col-sm-6') }}>
    {{ content.field_resumen }}
    {{ content.field_leer_mas }}
  </div>

```

Thanks to Kevin!
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Taxonomy child terms as Select options in CCK form
I have a vocabulary with parent-child terms. Every user is linked to a parent term in their profile field. And, I have CCK that the users fill in.

I need to add a Select Field with options as Child terms of a parent term that the User is linked to. (and save as term ref preferably) How do I achieve this?

```
Vocabulary: "Sites"
ONE
 -a
 -b
 -c
TWO
 -d
 -e
THREE
 -f
 -g

User1 => profile field term ref => "ONE"
User2 => profile field term ref => "TWO"

CCK type: "Study"
node/add/study  =>  select field (term ref) => "Select Site"
for User1 => Select site options => a, b, c
for User2 => Select site options => d, e

```

# Answer
For this you can add a term reference field and use the full vocab. Then you will need to do a form alter hook in one of your custom module and filter out options based on logged in user.
> 1 votes

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


# Question
Title: How do I create a unified list of referenced users in a multi-entry entity-reference field in a multi-entry field collection field?
My set up is similar to the setup in this question: How to integrate Field collection module in Views?

I have a content type with a field collection field (hereafter itineraries) that accepts unlimited entries. In the field collection is a (user) entity reference field (hereafter travelers) that accepts unlimited values. It also has another (user) entity reference field (hereafter approvers) separate from the field collection.

I've created a user view, with a contextual filter to select the current logged in user. This view has a relationship to bring in the nodes that reference the current user via the approvers field. I have another relationship pulling in the itineraries attached to the node.

What I would like to do is make a field in my view that has a comma separated list of travelers on the node. I can get the travelers from a single itinerary into a field, but nodes with multiple itineraries result in multiple rows.

I guess the solution must be to somehow embed a view to feed this view, but I'm not sure how to approach that, perhaps that would require an additional module?

**Update:** At @no-sssweat's recommendation I tried out the Views Field View module.

I tried a content view, passing the `nid` and using a relationship to get the field collection items.

With that I was able to get something like this for a node with the two itineraries, the first with two travelers and the second with one:

> **Travelers:**
>
> Person One, Person Two
>
> Person Three

I also tried a field collection item view, with the intention of passing in the field collection item ids as contextual filters. Testing this in the view itself, I got one traveler per row, but in practice I couldn't figure out a good way to pass id1,id2,id3 to the view. The view with ids input manually looks like this:

> **Travelers:**
>
> Person One
>
> Person Two
>
> Person Three

So in both cases I would get all the travelers listed in one field as the result of the embedded view, but they are listed each in their own divs within the field. I'm trying to figure out how I can get them listed as a comma separated list of values. I want to get to a field that looks like this:

> **Travelers:**
>
> Person One, Person Two, Person Three

Can you help me get over that last hump?

# Answer
> 2 votes
> I guess the solution must be to somehow embed a view to feed this view, but I'm not sure how to approach that, perhaps that would require an additional module?

You're on the right track, use the Views Field View module to achieve that.

---

You could also do this programmatically if you have a template file or a preprocess function

Ex:

```
<?php print views_embed_view('blog_posts','block_1', $contextual_filter_value); ?>

```

---

To make it as a list, use CSS:

```
.view-id-test.view-display-id-block .views-row {
  display: inline-block; /* If it doesn't work try display: inline; */
}

.view-id-test.view-display-id-block .views-row .field-content::after {
    content: ",";
}

.view-id-test.view-display-id-block .views-row-last .field-content::after {
    content: "";  /* or content: normal; */
}

```

**.view-id-test.view-display-id-block** being the unique parent classes wrapper as you don't to affect every single view and only a specific view & view display. (Use inspect element with your browser, to find a good parent wrapper.)

---

If you don't want to use CSS, then you will have to do it programmatically in your view's fields template file.

```
// load view
$view = views_get_view('view_name');
// set arguments for view
$view->set_arguments($contextual_filter_value);
// execute view
$view->execute();
// get all travelers from the result
foreach ($view->result as $result) {
   // capture the result of your field in an array.
   $travelers[] = $result->field_traveler;
}
//make array into comma list
$travelers_list = array(implode(", ", $travelers));
// print the list
print $travelers_list;

```

---
Tags: 7, views, entities
---