# Question
Title: How to add up all items of a field collection field using Rules?
I have a field collection with unlimited values.

Inside this field collection, there is a field called Price (field\_price).

I would like to **addup** all prices that are inside the field collection **to get the total value** (which I will then set to the total value field that is inside the content type).

I know I can get all the prices like this:

But the tricky part is adding them up.

I tried adding `Calculate a value` to the loop but for data selectors I only get something like this:

And `list-item:field-price` is not available either.

All signs point that this is not the right approach.

Race ya to the answer.

---

> And **list-item:field-price** is not available either.

Turns out that I was in the right path all along, the reason this was not available to me when I tried to do `calculate a value` is because I had changed my `price_field` type to `text-field`. You can't do calculations on non numeric fields. After I changed it back to `decimal`, I was able to use `list-item:field_price`.

# Answer
> 5 votes
At first I thought your Rule needs to perform a Rules Component with 2 parameters (say 'current\_total' and 'next\_item') and simply calculate the sum of both, and return that sum to the Rule (using "provides" for that component parm). And then in your Rule update current\_total with the provided sum, before the loop in your Rule ends.

However you don't need such Rules Component, only 1 rule will do. Have a look at this Rule (in Rules export format), which IMO is a prototype that does exactly what this question is about:

```
{ "rules_calculate_sum_of_prices_in_all_field_collection_items" : {
    "LABEL" : "Calculate sum of prices in all field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E started ..." } },
      { "variable_add" : {
          "USING" : { "type" : "decimal", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "total_price" : "Price total" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "Article details item" },
          "DO" : [
            { "data_calc" : {
                "USING" : {
                  "input_1" : [ "total-price" ],
                  "op" : "+",
                  "input_2" : [ "article-details-item:field-price" ]
                },
                "PROVIDE" : { "result" : { "calculation_result" : "Calculation result" } }
              }
            },
            { "data_set" : { "data" : [ "total-price" ], "value" : [ "calculation-result" ] } },
            { "drupal_message" : { "message" : "After adding a price of \u003Cstrong\u003E[article-details-item:field-price]\u003C\/strong\u003E for field collection item with id \u003Cstrong\u003E[article-details-item:item-id]\u003C\/strong\u003E, subtotal is \u003Cstrong\u003E[calculation-result:value]\u003C\/strong\u003E." } }
          ]
        }
      },
      { "drupal_message" : { "message" : "The \u003Cstrong\u003ETotal price\u003C\/strong\u003E for all prices included as field collection items is \u003Cstrong\u003E[total-price:value]\u003C\/strong\u003E." } },
      { "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E ended ..." } }
    ]
  }
}

```

Some more details about this rule are below ...

### Rules Event:

Content is viewed (of type Article), adapt the machine name of the content type `article` to whatever fits (or use any other Rules Event that fits).

### Rules Condition:

Entity has field, whereas the entity is "node", and the machine name of my field collection field is `field_article_details` (adapt this machine name to whatever fits, but make sure you use the field collection field itself).

### Rules Actions:

Here is where the magic will happen ... These are the Rules Actions involved:

1. `Show a message on the site`, with a message like so:

> Drupal calculator started ...
2. `Add a variable`, whereas it is a variable named `total_price`, decimal (2 digits), initial value 0.
3. `Add a loop`, to iterate over each item of my field collection field (with machine name `field_article_details`), and perform these Rules Actions for each iteration:

* `Calculate a value`, which calculates the sum of `total_price` (defined in Rules Action 2 above) and `article-details-item:field-price` (this is the machine name of the field in the field collection that contains the prices, decimal with 2 digits), and stores the result (sum) in variable `calculation_result`.
    * `Set a data value`, which simply copies the value stored in variable `calculation_result` in my `total_price` (defined in Rules Action 2 above). Remark: not sure (not tested), but maybe this `calculation_result` variable can be replaced straight by `total_price` (in the previous action), so that you would not need this action.
    * `Show a message on the site`, with a message like so:
> After adding a price of 3.40 for field collection item with id 3, subtotal is 15.00.
4. `Show a message on the site`, with a message like so:

> The Total price for all prices included as field collection items is 26.23.
5. `Show a message on the site`, with a message like so:

> Drupal calculator ended ...

Obviously, this rule is rather a prototype. After you're convinced it works as it should, just remove all Rules Actions with `Show a message on the site`. So that only item 2 and 3 (without its last sub-bullet) is left as Rules Actions.

### Showtime ...

Here is a sample of my test results, i.e. the Drupal messages that are shown:

```
Drupal calculator started ...
After adding a price of 2.45 for field collection item with id 1, subtotal is 2.45.
After adding a price of 9.15 for field collection item with id 2, subtotal is 11.60.
After adding a price of 3.40 for field collection item with id 3, subtotal is 15.00.
After adding a price of 1.23 for field collection item with id 4, subtotal is 16.23.
The Total price for all prices included as field collection items is 26.23.
Drupal calculator ended ...

```

### More info

Processing Field collection items with Rules is fun, really! If you're not familiar with that, try to first digest the answer to "How to iterate over all field collection items in an eMail body using Rules?".

# Answer
> 2 votes
I've done this for a muti-valued entityreference field using calculated fields, the general premise is to add a hidden computed field to the entity holding the field collection, it's not particularly easy but it's possible - you'll need to write some custom PHP code to achieve this. I'm including my code (field names changed to generics) below:

```
// Setup Entity Metadata Wrapper.
$wrapper = entity_metadata_wrapper($entity_type, $entity);
// Loop through field_collection.
foreach ($wrapper->field_collection->getIterator() as $related_wrapper) {
  // Expose the parts of the commerce_price field type.
  $price_field_wrapper = commerce_price_wrapper_value($related_wrapper, 'commerce_price_field');
  // Get the amount from the price field.
  $price_field_amount = $price_field_wrapper['amount'];
  // Get the currency type.
  $price_field_currency_code = $price_field_wrapper['currency_code'];
  // Use the amount and currency to covert to a decimal value.
  $price = commerce_currency_amount_to_decimal($price_field_amount, $price_field_currency_code);
  // Increment $total by the decimal stored in $price.
  $total += $price;
}

// Set the field value to $total formatted to 2 decimal places, with no 1000's separator.
$entity_field[0]['value']  = number_format($total, 2, '.', '');

```

# Answer
> 1 votes
> I came up with the same answer as the accepted answer, as per request I have un-deleted my answer.

Set the field\_total to 0

Then in loop add `field_total` \+ `list-item:field_price` and set result to `field_total`.

---
Tags: 7, rules, entities
---


title: substr plugin not working

text:
# Question
Title: substr plugin not working
I have been using Migrate API as a means to pull in RSS Data as nodes. Currently in Drupal 8 it doesn't seem there is any other reasonable way to do this.

One of my fields is a link that ends in a series of 6 numbers. I need those numbers as an id to go into the url. The substr plugin seems like it would be perfectly suited to accomplish this, but doesn't seem to work at all.

What I have in my YAML file :

```
grantid:
-
  plugin: substr
  source: guid
    start: 61
    length: 6

```

The error in my drush window when I attempt to even install the module that uses the plugin.

```
Unable to parse at line 61 (near "  start: 5").' in /var/beetbox/core/lib/Drupal/Core/Config/FileStorage.php:117

```

Currently I'm looking into using explode, but this is certainly not an ideal solution. Does anyone have some insight on why this plugin wouldn't work? It works fine without using this plugin.

Update : It does seem that was the problem. Thanks for the help.

# Answer
> 3 votes
Answered at https://www.drupal.org/node/2829462 \- as mradcliffe says, this is a YAML syntax error.

---
Tags: migrations, 8
---


# Question
Title: How to implement a transaction process between users using the Privatemsg module?
I am trying to develop a transaction process between two users who can do transaction using a form with two fields:

* a text message to communicate back and forth
* a virtual point to trade the product instead of regular currency.

So I customized the checkout process in the Drupal Commerce module. And I tried the Privatemsg module for messages. And Commerce userpoints for the virtual currency. I also customized the "Price" field in Commerce Product field.

I thought I might use Commerce Extra Panes to replace the default checkout steps, but I am stuck because the Privatemsg message text field may not display in the extra pane (I created a content for Privagtemsg to be attached and Extra pane may include the content node with Privatemsg).

This process allows the store owner to use messages and virtual currency to negotiate with the buyer back and forth, so we need a form for them to fill. I also wonder if Rules may provide a form that allows users to enter whatever they want in the checkout process?

I am new in Drupal so I am not sure if this is a good approach. Do you think if this way works? Or any other solution?

# Answer
> 0 votes
You may want to use the integration between the User Points module and the Rules module to "roll your own cookies", by writing some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

```
{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

If you simply adapt the amount of points (-2 and -1) to something like (eg) +25 and -25, you've a prototype to transfer (25) user points from one user to another.

**If** you replace the Rules event by an event like "Something is flagged" (created with the Flag module, and the "something" being a product), **then** a simple click could be used to indicate "*I want to transfer 25 user points of mine to this user*" (probably to trade that product in your case).

You could take this even a step further: since flags are fieldable, you could add these fields to such flag (to implement a bidding-system):

* A field to indicate the amount of points to be "moved" (= like the price to be payed for the product?).
* A field to indicate the price requested by the seller.
* A field to indicate the price offered by a potential buyer.
* A field for some text to be used for storing some message text. Possibly you may want to "deliver" that message text using the Message module, which has a great integration with Rules also (though it's not obvious to get started with the Message module).

Note: The above Rules example may need further refinements, e.g. if you want to ensure that after moving points van User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.

---
Tags: commerce, rules, userpoints, privatemsg
---


# Question
Title: How can I show a parent page's field on all subpages?
I'm trying to get a Basic Page's Banner Image field to display on its Basic Page AND any of that page's children. Those children may or may not be the same content type.

Ideal outcome:

1. The content editor creates a new Basic Page called *About Us*
2. They upload an image for the Basic Page's Banner Image field
3. They create a new page of any content type, let's say a *Contact* webform
4. *Contact's* menu settings make it a child of *About Us*
5. *Contact* and *About Us* both automatically show the Banner Image that was set in *About Us*

I've tried solving this with php in my page template and with views & blocks, but I'm not getting very far. Any ideas?

# Answer
> 0 votes
For posterity, here’s the solution I came up with.

I turned my Banner Image into its own content type, used the nodeblock module so it would automatically be usable as a block, and then just scoped that block to *myParentPage* and *myParentPage/\**.

It’s not the elegant solution I wanted, I was hoping to give the user a one step process that would also keep them from creating top level pages without a banner image. But it gets the job done, so I’m happy enough.

Thank you Kevin for getting me on the right track!

---
Tags: nodes, entities
---


# Question
Title: Get the values of views fields in a Twig template
I have created a view that outputs 3 fields for each row. Just using views, i can get the output to look something like this:

```
<li>[Field1 Value] [field2 value] [field3 value]</li>

```

I have a requirement to set a data-attribute on the list items to on of the field values. Also, I want to wrap an anchor linking to the detail view of the content around all three field values.

I've tried using a twig template like views-view-fields.html.twig (too generic i know, but for testing purposes) but the values dont seem to be there. I can do {{ dump (fields|keys) }} and i see my fields there, but if i do {{ dump (fields.my\_field|keys) }} then its just an empty array.

I also tried using a template like page--\[name of my page created by views\].html.twig but couldn't seem to find the values for those fields there either.

Any help on advice as to where I should be looking, particulary which twig templates I might create/override and how to get the values would be very much appreciated!

# Answer
> 7 votes
In the template file (views-view-field), you can use

```
<li> {{ row._entity.field_name1.value }} {{ row._entity.field_name2.value }} {{ row._entity.field_name3.value }}</li>

```

Or, in your theme, in the preprocess function you can overwrite the output:

```
function your_theme_name_preprocess_views_view_field(&$variables) {
    $view = $variables['view'];
    if ($view->storage->id() == 'your_view_name') {
        $variables['output'] = '<li>' .
          $variables['row']->_entity->field_name1->value .
          $variables['row']->_entity->field_name2->value .
          $variables['row']->_entity->field_name3->value .
        '</li>';
    }
}

```

# Answer
> 2 votes
Actually you can use views templates the way it was in Drupal 7. Although there is no theme info in the advanced part of views settings you can take basic templates from templates folder of the core views module. To create a views template for each row name it **views-view-fields--VIEW-NAME.html.twig** where **VIEW-NAME** is a machine name of your view or **views-view-fields--VIEW-NAME--DISPLAY-NAME.html.twig** where DISPLAY-NAME is a display you are using(block, page etc). Add them in your templates theme folder.

Use template\_preprocess\_views\_view\_fields(&$variables) function to preprocess each row.

In your template fields are available this way {{ fields.field\_name.content }}

# Answer
> 0 votes
Will $row get what you need instead of the processed field entity?

{{ kint(row.node\_field\_data\_created) }}

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


# Question
Title: Field collection with Entity reference strange behaviour
I have an interesting setup That uses a field collection as a host for line items. These line items contain two entity references to different nodes.

One entity reference is for a node that is considered a parent or a trunk item. When a user is ready as part of an external workflow, they view this field collection line item and create a 'child item' which is intended to populate the second entity reference. And the 'child item' is also linked to its parent.

Generally this has been working well, and there is a custom module that handles the child item generation (which is essentially a clone of the parent item).

The problem is, suddenly a situation has developed where in certain cases When the user initiates the copy from the field collection level, it can attach the 'child item' to more than one item. (if there is three in a list, it may attach to the first and last item in the field collection, if there is four, first and last, if it's 8, it could be first and 5th, for example.

This is the code that decides if it should make a copy. (below) the strange thing is I pass into the function ONLY that field collection item, the story id, and the node that contains the field collection. No other line items are loaded, so it shouldn't even be able to do what it is doing.

```
/**
 * Implements hook_menu().
 */
function click_printflow_menu() {

  $items['print-create/%/%/%'] = array(
    'title' => 'Generating Story from Wire',
    'page callback' => '_click_print_create',
    'page arguments' => array(1, 2, 3),
    'access arguments' => array('stories curate'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['generate-shell/%'] = array(
    'title' => 'Generating Story from Wire',
    'page callback' => '_generate_empty_node',
    'page arguments' => array(1),
    'access arguments' => array('stories curate'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
 * Function to check for and hand off creation of print child.
 *
 * @param int $rnid
 *   Node ID of run list.
 * @param int $snid
 *   Node Id of story we want print child from.
 * @param int $fcitem
 *   Field collection item ID that is host to this story.
 */
function _click_print_create($rnid, $snid, $fcitem) {
  $host_line_item = entity_metadata_wrapper('field_collection_item', $fcitem);

  $story = $host_line_item->field_story->value();
  $child = $host_line_item->field_print_child->value();

  // First, let's check for held flag. If set, Prevent movement.
  if (isset($story->field_hold_for_approval[LANGUAGE_NONE])) {
    $held = $story->field_hold_for_approval[LANGUAGE_NONE][0]['value'];

    if ($held == "held") {
      drupal_set_message(
        'This story has been <strong>held</strong> for approval. It will need to be approved to continue.',
        'error'
      );
      drupal_goto('node/' . $story->nid);
    }
  }

  if (isset($story)) {
    if (isset($child)) {
      drupal_set_message('A Print child already exists. It has been loaded below.', 'status');
      drupal_goto('node/' . $child->nid);
      return FALSE;
    }
    else {
      $new_print_child = _generate_print_entity($rnid, $snid, $fcitem);

      // Go to print child edit screen.
      drupal_goto('node/' . $new_print_child . '/edit');
    }
  }
  else {
    // drupal_set_message('Invalidly set run list item detected, skipping', 'warning');
  }
}

```

For fun, here's the function that actually writes the child node: (\_generate\_print\_entity($rnid, $snid, $fcitem))

```
/**
 * Function to generate new print entity and return nid.
 *
 * @param int $rnid
 *   Node ID of run list.
 * @param int $snid
 *   Node ID to clone from.
 * @param int $fcitem
 *   Field collection item ID that is host to this story.
 *
 * @return int
 *   Return nid of new child node.
 *
 * @throws Exception
 */
function _generate_print_entity($rnid, $snid, $fcitem) {

  $node = node_load($snid);

  global $user;

  $values = array(
    'type' => 'print_child_story',
    'uid' => $user->uid,
    // Do not publish story.
    'status' => 0,
  );

  $print_version = entity_create('node', $values);

  // Set entity wrapper for new node.
  $entity_data = entity_metadata_wrapper('node', $print_version);

  $entity_data->language(LANGUAGE_NONE);

  // Set up data for new node inside wrapper.
  if (isset($node->title)) {
    $entity_data->title->set($node->title);
  }

  if (!empty($node->body)) {
    $body = array(
      'value' => $node->body[LANGUAGE_NONE][0]['value'],
      'format' => 'filtered_html',
    );
  }

  if (isset($body)) {
    $entity_data->body->set($body);
  }

  if (isset($node->field_related_photos[LANGUAGE_NONE])) {
    foreach($node->field_related_photos[LANGUAGE_NONE] as $files) {
      $fid = $files['fid'];
      $files_array[] = array('fid' => $fid, 'display' => 1);
    }
    $entity_data->field_related_photos->set($files_array);
  }

  if (isset($node->field_name_story[LANGUAGE_NONE])) {
    $entity_data->field_name_story->set($node->field_name_story[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_byline_final[LANGUAGE_NONE])) {
    $entity_data->field_byline_final->set($node->field_byline_final[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_owner[LANGUAGE_NONE])) {
    $entity_data->field_owner->set(intval($node->field_owner[LANGUAGE_NONE][0]['target_id']));
  }

  if (isset($node->field_publication_of_origin[LANGUAGE_NONE])) {
    $entity_data->field_publication_of_origin->set(intval($node->field_publication_of_origin[LANGUAGE_NONE][0]['tid']));
  }

  if (isset($node->field_category[LANGUAGE_NONE])) {
    $entity_data->field_category[0]->set(intval($node->field_category[LANGUAGE_NONE][0]['target_id']));
  }

  if (isset($node->field_factbox_headline[LANGUAGE_NONE])) {
    $entity_data->field_factbox_headline->set($node->field_factbox_headline[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_factbox_text_area[LANGUAGE_NONE])) {
    $entity_data->field_factbox_text_area->set($node->field_factbox_text_area[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_jump_headline[LANGUAGE_NONE])) {
    $entity_data->field_jump_headline->set($node->field_jump_headline[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_field_pull_quote[LANGUAGE_NONE])) {
    $entity_data->field_pull_quote->set($node->field_field_pull_quote[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_field_pull_quote[LANGUAGE_NONE])) {
    $entity_data->field_pull_quote->set($node->field_field_pull_quote[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_subheadline[LANGUAGE_NONE])) {
    $entity_data->field_subheadline->set($node->field_subheadline[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_notes[LANGUAGE_NONE])) {
    $entity_data->field_notes->set($node->field_notes[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_slug[LANGUAGE_NONE])) {
    $entity_data->field_slug_text->set($node->field_slug[LANGUAGE_NONE][0]['value_token_filtered']);
  }

  // Set parent story link.
  if (isset($node->nid)) {
    $entity_data->field_parent_story->set($node->nid);
  }

  // Set Run list link.
  if (isset($rnid)) {
    $entity_data->field_run_list->set($rnid);
  }

  // Entity API cannot set dates. Old Method:
  $print_version->field_story_date[LANGUAGE_NONE][0] = array(
    'value' => date_format(date_create($node->field_story_date[LANGUAGE_NONE][0]['value']), 'Y-m-d 00:00:00'),
    'timezone' => 'America/Moncton',
    'timezone_db' => 'America/Moncton',
  );

  if (isset($node->field_embargo[LANGUAGE_NONE])) {
    $print_version->field_embargo[LANGUAGE_NONE][0] = array(
      'value' => date_format(date_create($node->field_embargo[LANGUAGE_NONE][0]['value']), 'Y-m-d 00:00:00'),
      'timezone' => 'America/Moncton',
      'timezone_db' => 'America/Moncton',
    );
  }

  $entity_data->revision->set(TRUE);
  $entity_data->log->set('Print Story Created.');

  $entity_data->save();

  $the_node = $entity_data->getIdentifier();

  // Load and Add to run list item
  $rli_row = entity_metadata_wrapper('field_collection_item', $fcitem);
  $rli_row->field_print_child->set(intval($the_node));
  $rli_row->save(TRUE);

  return $the_node;
}

```

At the end of this function, it loads the field collection item, and sets the entity referennce for the child item and saves that field collection row only (not the entire run list node). could it have something to do with this?

# Answer
> 0 votes
Turns out there was a module that was interfering called Corresponding Entity References (CER) that was not needed anymore. Disabling it solved the issue.

---
Tags: 7, entities
---


# Question
Title: How to fix floated elements extending height of non-floated elements within a single zen theme region?
I'm updating a site built on D7 with a 7.x-56 zen sub theme. The theme is laid out with responsive horizontally stacked content regions. I've created a custom blog content type, and three views blocks based on taxonomy, archive, and recent posts, but I'm having trouble with the layout of the individual blocks within the content region.

What I want is the three blog content filter blocks stacked and floating to the right, while the blog itself is floated left. I've more or less pull this off, but floating and clearing the blocks to stack on top of each other, but the issue I'm having is that they are somehow influencing the height of the first blog post. .

So, why are the floated elements influencing the views row's height and how can I fix this? You can see a live version of the site here live site. Should I add a sidebar region here? or is there a css fix for this? For context, page is a view constructed from a custom content type, and the filter views are placed using the context module with equal row height of -9.

# Answer
So, the simplest approach ended up being adding another region to the theme. I made sure to add the region within the content region div to facilitate alignment, this gave me a container to float the block divs altogether with the clear: both declarations messing with the internal layout of the content region.
> 0 votes

---
Tags: 7, theming
---


title: Preprocess node in module

text:
# Question
Title: Preprocess node in module
It's more general question. Just to clarify. I can use preprocess function in my template.php file in a way:

```
function mytheme_preprocess_node(&$vars) {
  // Do some stuff
}

```

But is there a way to preprocess node in a module? I've been searching for function hook\_preprocess\_node() in drupal API, but there's no such function for D7, although it does exists for all other versions of drupal, including 8. May I treat template\_preprocess\_node() as a function which I can use in my module? For example, if my module has name 'custom' then can I use it this way?

```
function custom_preprocess_node(&$vars) {
  // Do some stuff
}

```

How can I override node in custom module?

# Answer
> 6 votes
You sure can. hook\_preprocess\_HOOK() is what you're looking for. From the docs...

> Preprocess theme variables for a specific theme hook.
>
> This hook allows modules to preprocess theme variables for a specific theme hook. It should only be used if a module needs to override or add to the theme preprocessing for a theme hook it didn't define.

# Answer
> 6 votes
In Drupal7, both modules and themes are able to use preprocess functions in the same way, and a given theme hook can have many preprocess implementations, originating from both modules and themes.

As with anything like this in the Drupal framework, knowing the order in which these functions run is important. Preprocess implementations from modules run first, and implementations by themes run last.

A quick search of Drupal core modules will give you examples in the node and rdf modules.

# Answer
> 0 votes
Have found good article about this http://themery.com/dgd7/advanced-theming/preprocess-process/implement

---
Tags: 7, nodes, theming
---


# Question
Title: How to open a popup form from a view link?
I'm really struggling with this issue. Well I'm having a view, in this view a field configured as personalized text as a link. I want to open a popup form on click on the link. Here is what I did in the method called by the link:

```
 $response = new AjaxResponse();
  $title = 'Title for the Popup.';
  $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
  $response->setAttachments($form['#attached']);
  $content = '<div class="test-popup-content">' . 'Content in HTML format' . '</div>';
  $options = array(
    'dialogClass' => 'popup-dialog-class',
    'width' => '75%',
  );
  $modal = new OpenModalDialogCommand($title, $content, $options);
  $response->addCommand($modal);
  return $response;

```

But It's not working at all! Please help!

# Answer
Your code is building an ajax response. This only works in ajax callbacks, nowhere else.

If you want to make a link modal, so that it will open in a popup, you have to set the class `use-ajax` and the attribute `data-dialog-type`. Like in this example from ConfigSync.php:

```
$links['view_diff'] = [
  'title' => $this->t('View differences'),
  'url' => Url::fromRoute($route_name, $route_options),
  'attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => 'modal',
    'data-dialog-options' => json_encode([
      'width' => 700,
    ]),
  ],
];

```

For modal links to work you need to attach a library, see How to create modal windows (pop-ups)?
> 5 votes

---
Tags: views, 8
---


title: Wrong URL being generated in a view

text:
# Question
Title: Wrong URL being generated in a view
I have a very strange issue with a Drupal 8 install. My production setup is running on NGINX in a subdirectory - something like `www.example.com/abc`.

The site is running great, but I have seen an error occur that I can't pinpoint. One page that I setup as the frontpage (ie, `/abc/index.php`) is made with a view that uses the Slick Carousel module to show a carousel of nodes of a certain content type (news).

Here's what's going on:

* *sometimes* the URL on an item of the carousel loses the `/abc` part of the path, effectively sending users away from the site (ie, `/node/123` when it should be `/abc/node/123`).
* this happens when the user who created the node has a certain role (lower than admin). If admins create the node it doesn't happen.
* it is only visible/only affects anonymous (not logged) users. If a user is logged in, be it either admin or otherwise (including the role for who this happens), the page shows up the correct URL (ie, `/abc/node/123`).
* it only happens on that page/view. In other pages/views which list the `news` content type, the same node shows the correct URL for all users, either anonymous and/or logged in.
* I (admin) can solve it in at least 2 ways:
    + unpublish/publish the problematic node;
    + clearing the cache
* the problematic role has no way of solving this using the above methods.

Now, to add difficulty to the whole process, I have no control over the NGINX configuration, although I was told it was setup according to NGINX's Drupal recipe.

Also, in my dev environment this doesn't occur, even though the configuration settings are the same (it's exported every time I deploy to production). The only thing that might be different is the `settings.php` file.

Obviously, I have no debug facilities in place for the production website, so there isn't much I can do to trace the issue. Also, there are no log messages indicating something might be wrong with this page.

I'm now trying to find a way to replicate the production environment in a VM, but even so, I'm not sure where to start looking for the problem.

Can anyone share any thoughts on this?

**EDIT:** I have replicated the production environment with Docker containers and I can't replicate the bug.

Meanwhile, I have seen some even weirder things happening: *sometimes* (again, fixable by clearing cache), the menus also get the wrong URLs - I have a block menu holding a link to the login page that instead of going to `www.example.com/abc/user/login`goes to `www.example.com/user/login`.

I guess clearing the cache forces the URLs to be rebuilt and apparently it gets fixed. But aren't URLs rebuilt anyway when you publish content? Why can this affect the menus as well?

# Answer
There are a few options to what might be wrong:

### 1. Globals are created incorrectly

What you want to do, is to have a look at `DrupalKernel::initializeRequestGlobals()` this is where `$base_url` and `$base_path` globals are generated. Behind the scenes, this is what Drupal 8 uses to figure out how links should look.

The issue might be related to these being resolved incorrectly

### 2. Relative URLs / Globals not used.

If the urls that are generated various places are relative, there might be some places that assumes that it should only include the drupal part, like `/node/123` and thus remove the `/abc` part of the of the full url

## Way forward

What I would do in your situation is to figure out how the urls are that causes trouble are generated. For starters you don't need to go through the entire trace, but you could find some theme function and log final URL + globals. In production where the issue can arise you can obtain information about what the root cause of the issue is, which has to be one of:

* Urls don't use globals
* Globals are wrong

Once you know the root cause, you can fix it.

The globals are generated from `$_SERVER['SCRIPT_NAME']`, I haven't heard example of this being buggy or inconsistent so most likely issue is some urls doesn't use this.

Urls are mostly generated through `\Drupal\Core\Routing\UrlGenerator`. I have seen Drupal having some some issues when menus are user created. Since the url is not created from a route. When you dig into it, it gets rather complex, since especially internal urls are converted a lot of times.
> 1 votes

# Answer
Perhaps it is a NGINX config problem? Running Drupal in a subdirectory under Apache normally requires you to alter .htaccess and RewriteBase. I am not a NGINX admin but I would start by getting a copy of the running config. It might need stuff along

```
location ~ \.php$ {
        fastcgi_split_path_info ^(/abc)(/.*)$;
}

```

To avoid loosing in base directory.
> 1 votes

# Answer
Did you try sites.php in the sites folder?

This file has a good documentation which probably might resolve you issue. Just rename example.sites.php to sites.php and put this in the beginning of the file:

```
 $sites = array(
   'www.example.com.abc' => 'abc',
 );

```

This asks drupal to look into abc folder in the root of your site when you try to access www.example.com/abc path. If that does not help I'd recommend to look what you have in the .htaccess file both in the root and abc subfolder. But with this file it is difficult to advise something as its settings may be very specific to the hosting environment and what the base settings it has. If you don't need to access www.example.com path you could put this in the .htaccess in the root of the site (public\_html, www, or similar)

```
DocumentRoot "/abc"

```

After saving the setting flush caches both on the site and in your current browser too just to see the effect. Or look the site in another browser where the site was not seen before.
> 1 votes

---
Tags: uri, 8
---


# Question
Title: how to make images clickable in a listing (numerous thumbnails)
in our event\_parent https://i.stack.imgur.com/u9ELE.jpg content view we have a listing (field\_listing) field that contains numerous thumbnails and they need to redirect to their specified event page. we are on drupal 7

# Answer
Click on the field for the image and you should see "link image to" and you can select "content". Set the filter criteria so that the system knows what content to link to. Also, the image should be coming from the content, such as as a thumbnail.
> 1 votes

---
Tags: views
---


# Question
Title: drupal_mail() strips all html tags from emails
So as the title explains, when sending an HTML email with drupal\_mail(), email comes with no HTML tags.

```
    $module = 'module';
    $key = 'contact_message';
    $language = language_default();
    $params = array();
    $email = 'sender@email.com';
    $from = variable_get('site_mail', 'admin@example.com');
    $send = TRUE;
    $message = drupal_mail($module, $key, $email, $language, $params, $from, $send);
    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8';
    $message['subject'] = 'Test';
    $message['body'] = array();
    $message['body'][] = '<a href="#">Testing anchor in mail</a>';
    $system = drupal_mail_system($module, $key);
    $message = $system->format($message);
    $message['result'] = $system->mail($message);

```

And when recieving the email, and viewing the source:

```
Message-Id: <201305090722.r497MLAV005654@test.server>
X-Authentication-Warning: testserver : www-data set sender to sender@email.com using -f
To: from@email.com
Subject: Test
X-PHP-Originating-Script: 1000:system.mail.inc
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 8Bit
X-Mailer: Drupal
Sender: sender@email.com
From: from@email.com

Testing anchor in mail [1]

[1] #

```

So you can see that any HTML tags were stripped. And it doesn't matter what HTML tags I put in body.

I thought it might be related to Text Fomats, but I have "Filtered HTML" and "Full HTML" active filters with any permissions.

---

The thing confused me were the Ubercart invoices. At first they were sent with HTML, and then at some point it stopped. They were received plain text. After digging a bit @develkar answer, I've found this in one of ubercart updates:

```
/**
 * Installs HTML Mail System for Ubercart.
 */
function uc_store_update_7004() {
  // Set mail handler for all Ubercart modules
  variable_set('mail_system',
    array_merge(
      variable_get('mail_system', array('default-system' => 'DefaultMailSystem')),
      array(
        'uc_cart'  => 'UbercartMailSystem',
        'uc_order' => 'UbercartMailSystem',
        'uc_file'  => 'UbercartMailSystem',
        'uc_roles' => 'UbercartMailSystem',
        'uc_stock' => 'UbercartMailSystem',
        'uc_store' => 'UbercartMailSystem',
      )
    )
  );
}

```

I guess that at some point, one of installed modules (I suspect SMTP module) overridden this variable, and that's why emails were coming plain text. After running this update manually again, Ubercat invoices are HTML again.

For the rest of emails, I'll have to install some modules as suggested in other answers.

Thanx.

# Answer
> 10 votes
drupal\_mail(), by default sends a mail as plain text.

If you print out the array `$message['headers']`, you will get something like:

```
array(
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal',
  );

```

As you can see, the `Content-Type` in the mail header is `text/plain; charset=UTF-8; format=flowed; delsp=yes`. You can try by modifying this header in hook\_mail\_alter(), you could use one of the modules which allows you to send the mail as HTML, like HTML Mail, or Mime Mail.

**Edit:**

Following the comments by @Ayesh and @alechko and after looking into the APIs, I found out that the headers are not the only reason for sending the mail as plain text. Because `drupal_mail()` internally makes a call to drupal\_mail\_system(), which returns an object that implements the MailSystemInterface interface. The `format()` method implemented by `drupal_mail_system()` is responsible for stripping out the HTML from the emails. So, even if the headers of the mail show the formats to be HTML, the mails would be sent as plain text only. So, I guess one could not send an HTML mail using `drupal_mail()`. You should look for some other alternative (module) mentioned above.

# Answer
> 3 votes
In hook\_mail also,you can define the headers as text/html,then you will get mail as an html format,as for example:

```
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';

```

# Answer
> 2 votes
Give a try with HTML Mail module installed and configured.

> Lets you theme your messages the same way you theme the rest of your website.

# Answer
> 0 votes
It doesn't matter what the header Content-Type is, Drupal's default mail system converts html to plain text. See DefaultMailSystem::format() in mail.inc

```
<?php
public function format(array $message) {
// Join the body array into one string.
$message['body'] = implode("\n\n", $message['body']);
// Convert any HTML to plain-text.
$message['body'] = drupal_html_to_text($message['body']);
// Wrap the mail body for sending.
$message['body'] = drupal_wrap_mail($message['body']);
return $message;

```

}

To send allow html in the message body you will need to:

1. create a custom mail system class that implements MailSystemInterface that has a format method that does not convert html to plain text
2. Include that new class in your modules.info file
3. Let Drupal know you want to use your custom mail system class

`variable_set('mail_system', array('default-system' => 'ExampleMailSystem'));`
4. Set the Content-Type header from "text/plain" to "html/plain"

`$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';`

This documentation on d.o. does a good job of describing the solution and providing an example.

https://www.drupal.org/docs/7/converting-drupal-6-modules-to-drupal-7/creating-html-formatted-emails-in-drupal-7#comment-11792179

---
Tags: 7, emails
---


# Question
Title: #states and #ajax are not working on pop up
I need to get form only with HTML. To do this, I've used delivery callback in `hook_menu()`. This is my sample code:

```
function test_menu() {
  $items['htmlform'] = array(
   'access callback'  => TRUE,
   'page callback'    => 'test_htmlform'
   'delivery callback' => 'delivery_text_plain',
   'type'             => MENU_CALLBACK,
 );
  return $items;
}

```

In this form, I've used #states and #ajax.

I've another form which is in the normal callback. I need to show htmlform into this Drupal form. So I've written a ajax callback to 'htmlform', get html, paste it into the drupal form & show this in pop up.

This is my ajax callback:

```
$.ajax({
    url: '/htmlform',
    success: function(data) {
      $('#formpopup').empty();
      $('#formpopup').html(data);
      $("#form_demo_pup").modal({backdrop: 'static',keyboard: false});
      Drupal.attachBehaviors($('#form_demo_pup'));
    }
  });

```

Now the drupal form page have all the CSS and JavaScript but the pop up (htmlform) have only the HTML.

On this pop-up, #states and #ajax are not working since it has no Drupal form JavaScript.

How do I fix this? Even I tried "Drupal.attachBehaviors" in my custom ajax.

# Answer
You need to load the required JS on page load, not on Ajax load. You will need to load the Drupal.ajax library as well.
> 0 votes

---
Tags: ajax, javascript
---


title: User preprocess not working

text:
# Question
Title: User preprocess not working
I'm trying to pass a variable to an user template, here is my code:

```
function template-name_preprocess_user(&$variables) {
  $variables['foo'] = 'foo';
}

```

It doesn't work. I tried adding these line in the core User module preprocess and it works!

# Answer
Template hooks like `template_preprocess_user()` are implemented by custom module/theme by replacing `template` with `[MODULE_NAME/THEME_NAME]`. So, for example, if your theme short name is bartik, then the function name will be `bartik_preprocess_user()` which will be implemented in the bartik.theme file.

```
function [MODULE/THEME_NAME]_preprocess_user(&$variables) {
  $variables['foo'] = 'foo';
}

```
> 5 votes

---
Tags: theming, 8, users
---


title: Translation of list (text) values

text:
# Question
Title: Translation of list (text) values
I am new do Drupal. I am testing out Drupal 8's multilingual capabilities.

I created a new content type with a field of type List (text) and a field of type Text. I have provided a translation for the text field, and switching language works fine when displaying it in a view. I have also entered a translation for the list field values, but those do not change when changing language. How do I get them to display in the selected language? I did set the Rendering Language to "Interface text language selected for the page". I don't see an option to make field values render in the selected language, but it's working fine for text fields. I cannot figure out why it does not work for list values.

# Answer
> 0 votes
Oh! After adding a translation for a list value, you have to edit (and save) one of the content entries containing the list, and after that the translations show up.

# Answer
> 1 votes
You can refer the following tutorial for the same, it's well explained.

https://www.ostraining.com/blog/drupal/d8-multi-lingual/

https://www.drupal.org/docs/8/multilingual/choosing-and-installing-multilingual-modules

---
Tags: 8
---


# Question
Title: How to add tokens in an text-area in the contact module?
In contact module there is an text-area of auto reply in which I want to add tokens to it. Could anyone give solution for above issue.

# Answer
> 1 votes
That is not a supported feature right now, you would have to implement that yourself using the token API, e.g. through a `hook_mail_alter()`.

But there are a lot of details involved after that and you won't get a detailed answer here that you can just copy & paste. You could open a feature request for http://drupal.org/project/contact\_storage

# Answer
> 1 votes
I have not yet try Contact module.

But if that is text area and can be applied a Text format, you can add Token filter module then edit the text format to Replace token with actual value.

---
Tags: 8, emails
---


# Question
Title: I can't filter list term under admin/content
I can't filter list term under admin/content.

There is not filter option for list term, just the types (taxonomy)

This is Drupal 7, ther is no category option.

This is Drupal 6, it can filter category.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Installed Admin Views and add the following settings to /admin/structure/views/view/admin\_views\_node/edit

But term list still not appearing.

# Answer
admin/content page doesn't list taxonomy terms, it shows content nodes. Those options in the select list are actually Content Types you can filter by.

To view taxonomy terms, the link is admin/structure/taxonomy.

Anyway, in the remote case you do want to have better filtering options for nodes, I recommend the module Admin Views.

After enabling Admin Views module, you can go to /admin/structure/views/view/admin\_views\_node/edit to edit the view that's responsible for displaying the admin node list. Here you can add as many exposed filters you need, in your case, the term reference field.

Admin Views also requires Views Bulk Operations module which allows you to execute operations on multiple nodes at once.

Edit: Your taxonomy vocabulary filter needs to be exposed to appear in the form (click on the filter, then click on 'Expose this filter to visitors, to allow them to change it'). Then all vocabularies should appear in the filter form.
> 1 votes

# Answer
One alternate way:

-\>You need to create a separate view for this.
-\>Add a expose filter for taxonomy term field.
-\>Add Views Bulk Operations (VBO) module.
-\>Delete the articles in bulk.

If you need more details for this process let me know.
> 0 votes

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


# Question
Title: How to assign roles to grant permissions to update particular pages?
I have a menu like Publications, About us , Services and i want to assign a roles to the users like one user can update the content of about us and other can services means need to give permission for specific pages.

Is this is possible?

Some more details about what I'm trying to do: I do not want to give the permission to whole content type (that is not required). I want a user wise permissions like I have a role named ***ouroffice-user***. Then under this I have a 10 users and I want to allocate different permissions to these 10 users like no. 1 have a permission to update the `welcome` content and no. 2 have a permission to update the `about us` page all users belong to single role that ouroffice-user.

# Answer
> 2 votes
The Group module allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

**Group** creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Group provides an extensive API to attach entities to groups.

For way more details about this module, such as how to configure it or available integrations with other modules, refer to my answer to "What are the alternatives for the Organic groups module?".

For this specific question you'd only need 1 Group *Type*, with 1 Group (of that Group Type) for each set (= collection) of "*Specific Pages*" (as in your question). BTW, available for either D7 or D8.

Have a look at the Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site". Even though it is about D8 (already), the key concepts of it are the same as in the D7 version. Maybe also review the answers to various questions around here tagged with the tag.

Some more details about this part of your question:

> Some more details about what I'm trying to do: I do not want to give the permission to whole content type (that is not required). I want a user wise permissions like I have a role named ouroffice-user. Then under this I have a 10 users and I want to allocate different permissions to these 10 users like no. 1 have a permission to update the welcome content and no. 2 have a permission to update the about us page all users belong to single role that ouroffice-user.

* Be aware that "roles" in the Group module are different from the typical (standard) roles in Drupal. For more details about the various roles and permissions that can be configured, refer to my answer to "What are the various roles supported by the Group module?".
* Assume you create a custom Group role like "content manager". And you allow members with this group role to **edit** nodes of content type ABC.
* From those 10 users (in your comment), those that correspond to your "no 1" should become members of some group (say titled **Group no 1**), in which they receive access to that Group role "content manager". And assume you create a similar group titled **Group no 2**, for those that correspond to your "no 2" users.
* Using the `gnode` submodule you assign the nodes such as `Welcome` to the **Group no 1** group and `About us` is assigned to the **Group no 2** group. Note that it doesn't matter what the content types are (if they are the same or not), which is part of the beauty of the Group module.

Done ... really! Give it a try to get the idea ... those who try, love it ... after they get it ...

# Answer
> 1 votes
Yes its possible Look into Content Access module.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

One can install the ACL module and set per user access control settings per content node.

> The ACL module, short for Access Control Lists, is an API for other modules to create lists of users and give them access to nodes. It has no UI of its own and will not do anything by itself; install this module only if some other module tells you to.

---
Tags: 7, users
---


# Question
Title: Load all titles and body text from one content type into array
I'm working on an input format filter that should work as following. I have a content-type called glossary, the user can fill in a word (title) and description (body). Then there is a content-type article. When a word in the article matches a word in the glossary it should wrap that word with a span. Something like word. I already did a quick and dirty tryout and that worked fine. I already did a speed test and it worked out fine only a delay of 0.2s max. But now I try to make it as it should and I got stuck.

The way I think this could work is to have an array with all words and descriptions from the glossary content-type in a array. And then search through the text.

So I created a Plugin/Filter/Filtername.php file. In this file I try to load all node from the glossary content-type (as advised) via dependency injection.

What I found is a way to get all nids, via this code added in to my filter class:

```
class FilterName extends FilterBase {
    public function __construct(QueryFactory $entity_query)
    {
        $this->entity_query = $entity_query;
    }

    public static function create(ContainerInterface $container){
        return new static(
          $container->get('entity.query')
        );
    }

    public function process(){
        $query = $this->entity_query
        $query->condition('bundle','woordenlijst');
        $nids = $query->execute();
    }
}

```

So this should give me all nids of the node I'm looking for but how do I get these node loaded to get there title and body text? I found this lesson about entity loading. Which is usefull but there are some deprecated functions used and I have no idea how to combine these to to get een array of titles and body texts.

So what is currently the best method to load nodes and how can I combine this with the code I already have? And am I even on the right path or not, or is there a better/easier way to do this?

Thanks in advance.

# Answer
If yau have lots of node's than its difficult load all nodes at a time and also , to get only title and body, its not fair to load complete node. Rather than load node and get values, we can use select query and fetch required values.

I am using cache concept here, once your query loaded, set it in cache untill any node values changes or any new node creates. Use node hooks to remove cache for "node\_data" Below is the query:

```
  $nodedata = array();
  // Check cache exists
  $cache_node = \Drupal::cache()->get('node_data');
  if ($cache_node) {
    $array = $cache_node->data;
    $nodedata = json_decode($array, TRUE);
  }
  else {
    // Query for node title and body.
    $connection = \Drupal::database();
    $query = $connection->select('node', 'n');
    $query->leftJoin('node__body', 'b', 'b.entity_id = n.nid');
    $query->leftJoin('node_field_data', 't', 't.nid = n.nid');
    $query->fields('t', array('title'));
    $query->fields('b', array('body_value'));
    $query->condition('n.type', 'glossary', '=');
    $result = $query->execute()->fetchAll();
    foreach ($result as $key => $value) {
      $nodedata[] = array(
        'node_title' => $value->title,
        'node_body' => $value->body_value,
      );
    }
    // Set Cache.
    \Drupal::cache()->set('node_data', json_encode($nodedata));
  }
  dsm($nodedata);

```
> 3 votes

# Answer
you can use entityQuery like this for load all nodes of content type.

```
$node_array = array();
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'woordenlijst');
$entity_ids = $query->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);
 foreach ($nodes as $node) {
  $title = $node->getTitle();
  $body = $node->get('body')->getValue();

  $node_array[] = array(
'node_title' => $title,
'node_body' => $body,
);
}

```

Finally you got a array with title and body.Use dpm($node\_array);
> 0 votes

---
Tags: nodes, 8
---


title: Insert region into html.html.twig

text:
# Question
Title: Insert region into html.html.twig
Is there any way to add a region into html.html.twig? I want to have one inside tag to be able to render different js counters through Block Layout

# Answer
> 3 votes
So, the solution is to add a new region into your theme.info.yml (say `before_body`) Then the code you'd place into theme\_name.theme be:

```
function theme_name_preprocess_html(&$vars) {
  /**
   * moves region before_body into before_body var inside basic html
   */
  if (isset($vars['page']['before_body'])) {
    $vars['before_body'] = $vars['page']['before_body'];
}
function theme_name_preprocess_region(&$vars){
  /**
   * Cleans before_body from standard html markup
   */
  if ($vars['region'] === 'before_body') {
    $vars['content'] = theme_name_clean_special_content($vars['content']);
  }
}
/**
 * Cleans content from basic markup
 * @param $content
 * @return \Drupal\Component\Render\MarkupInterface|string
 */
function theme_name_clean_special_content($content) {
  /** @var \Drupal\Core\Render\Markup $content */
  $content = preg_replace('~<\/?section.*?>|<h\d?.*?>.*<\/h\d?>|<\/?div.*?>~', '', $content);
  $content = preg_replace('/(?=<!-- (THEME DEBUG|BEGIN OUTPUT|THEME HOOK|FILE NAME SUGGESTIONS|END OUTPUT))([\s\S]*?)-->/i', '', $content);
  $content = preg_replace('/((\r\n|\n|\r)$)|(^(\r\n|\n|\r))$/m', '', $content);
  return \Drupal\Core\Render\Markup::create(trim($content));
}

```

Just don't forget to add `before_body` variable into your basic html template.

# Answer
> 0 votes
There is no way to place regions directly in the html.html.twig template as regions that you operate through block layout are part of the page variable and are rendered in body tag.

`HtmlRenderer::prepare()` receives the main content render and ensures we have a '#type' =\> 'page' render array (which corresponds to ):

1. if the main content render array already is '#type' =\> 'page', then we're done
2. otherwise, we need to build that '#type' =\> 'page' render array. The RenderEvents::SELECT\_PAGE\_DISPLAY\_VARIANT event is dispatched, to select a page display variant.

* By default, SimplePageVariant is used, which doesn't apply any decorations.
    * But, when the Block module is enabled, BlockPageVariant is used, which allows the site builder to place blocks in any of the page regions, and hence "decorate" the main content.
    * Drupal 8 modules can subscribe to this event as well, and use a different page variant, even on a per-route basis. (Panels, Page Manager etc. can be cleanly implemented thanks to this event.)
3. `HtmlRenderer::prepare()` now is guaranteed to be working on a '#type' =\> 'page' render array. `hook_page_attachments()` and `hook_page_attachments_alter()` are invoked. (For attaching page-level assets, that aren't bound to a specific page.)
4. Renderer (formerly `drupal_render()`) is called on the `'#type' => 'html'` render array, which uses the `html.html.twig` template and the return value is a HTML document as a string.
5. This HTML string is returned as the Response (specifically, a `HtmlResponse` object, which is a more specialized subclass of `Response`).

More info on this page: https://www.drupal.org/docs/8/api/render-api/the-drupal-8-render-pipeline

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


title: YAMLFORM Element Settings

text:
# Question
Title: YAMLFORM Element Settings
I'm using yamlform in my Drupal 8 site and I want to add a new setting **(i.e General Settings, Form Display etc)** to each of my fields based on if I have a handler attached to my form.

I have used the

```
function prepare()

```

method for this in my custom elements, but I would like to add it to all existing elements as well, there are several hooks available but I'm not sure which one would be ***most appropriate.***

I realise that yamlform gives you a custom settings box, but I need something a bit more obvious for my non-tech end users.

Thanks.

# Answer
So In the end I had to use hook\_form\_alter, here's a quick trimmed down example of how I achieved my particular problem:

```
function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {

if ($form_state->getFormObject() instanceof YamlFormUiElementEditForm and hashandler) {

$form['newsection'] = [
  '#type' => 'fieldset',
  '#title' => t('New Section'),
];
$form['newsection']['newfield'] = [
  '#type' => 'textfield',
  '#title' => t('New field'),
];

```
> 0 votes

---
Tags: forms, 8
---


# Question
Title: Filter a view by a value being absent from a multiple value field
Given a field "field-participants" on a node type "discussion" that references an unlimited number of users:

How can I produce a view that shows all discussions that do NOT have the current user listed in their field\_participants?

The problem comes from the fact that views creates a separate row of results for each reference in field\_participants in any given discussion.

I can use 'Distinct' or Aggregation to get rid of duplicate rows, but while this would work to include results (showing discussions that listed the current user as a participant) it doesn't work to exclude results.

This is because a contextual filter on the current user with "excludes" checked only excludes the one of these rows that matches the current user. It doesn't exclude all the rows from that discussion. Therefore I get false positives: the view shows all discussions that have someone other than the current user listed as a participant.

Right now I'm thinking that I either need to figure out some arcane HAVING clause and add it to the query programmatically, or try to use the pre-alpha Flag module (setting a per-user flag and filtering by that instead of field\_participants).

# Answer
> 1 votes
You could use hook\_views\_query\_alter() to modify SQL query.

```
/**
 * Implements hook_views_query_alter().
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'discussions') {
    // Exclude discussions the current logged user has participated in.
    $uid = Drupal::currentUser()->id();
    $nids = Drupal::entityQuery('node')
      ->condition('type', 'discussion')
      ->condition('field_participants', $uid)
      ->execute();
    $query->addWhere(0, 'nid', $nids, 'NOT IN');
  }
}

```

In the example above we are getting ID's of excluded nodes using entity field query and then them to NOT IN condtion.

The resulting SQL query will be as follows:

```
SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
WHERE (nid NOT IN ('1', '2', '3')) AND (node_field_data.type IN ('discussion'))
ORDER BY node_field_data_created DESC

```

Alternative way would be using JOIN with extra conditions:

```
/**
 * Implements hook_views_query_alter().
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'discussions') {
    // Exclude discussions the current logged user has participated in.
    $uid = Drupal::currentUser()->id();
    $definition = [
      'table' => 'node__field_participants',
      'field' => 'entity_id',
      'left_table' => 'node_field_data',
      'left_field' => 'nid',
      'extra' => [
        0 => [
          'field' => 'field_participants_target_id',
          'value' => $uid,
        ],
      ],
    ];
    $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
    $query->addRelationship('participants', $join, 'node');
    $query->addWhere(0, 'field_participants_target_id', NULL, 'IS NULL');
  }
}

```

The generated SQL query:

```
SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_participants} participants ON node_field_data.nid = participants.entity_id AND participants.field_participants_target_id = '1'
WHERE (field_participants_target_id IS NULL) AND (node_field_data.type IN ('discussion'))
ORDER BY node_field_data_created DESC

```

The view itself becomes quite simple. No need of contextual argument and aggregation.

---
Tags: 8, views
---


# Question
Title: How to get list of activated and deactivated module using some script from database?
How to show list of activated and deactivated module using some script from database?

# Answer
For disabled modules: SELECT * FROM `system` WHERE `type`='module' AND `status`=0

For enabled modules: SELECT * FROM `system` WHERE `type`='module' AND `status`=1

If you need to do this using drupal functions, you can try something like:

```
    $query = db_select('system', 's')
    ->fields('s', array('name', 'weight'))
    ->condition('type', 'module')
    ->condition('status', 0);
    $result = $query->execute();

    foreach ($result->fetchAll() as $record) {
      // do something here...
    }

```

And process the results from $result.
> 0 votes

# Answer
After you install/enable the Forena module (Disclosure: I'm a co-maintainer), you can use one of the reports that's delivered with it. I.e. the ***Enabled Modules and Themes*** report in category "Drupal Administration", which you can find at `reports/drupaladmin.enabled_contributions`.

If you don't like the report (eg you neem more or less data (columns) to be shown, just tune the report (using a WYSIWYG report designer) and/or adapt the related SQL query (using a WYSIWYG query builder). So no custom (PHP) code ivolved.

And if you want to save (export) the format, pick whatever fits for you, such as CSV, PDF, XML, JSON, MS Excel, MS Word, ...
> 0 votes

---
Tags: 7
---


# Question
Title: Fatal error: Call to undefined function wincache_ucache_get()
After downloading fresh files and restoring fresh database from prod website, on my local server (IIS) I have a problem.

> Fatal error: Call to undefined function wincache\_ucache\_get() in E:\XXX\sites\all\modules\wincachedrupal\drupal\_win\_cache.inc on line 145\`

* Permissions are good (for IUSR and IIS\_IUSR)
* settings.php passwords are OK
* I updated the wincachedrupal module to newest version
* I cannot do anything with Drush (same error as above)
* I cannot rebuild the registry
* if I delete or change the name of the wincachedrupal module, I get this error:

> Fatal error: require\_once(): Failed opening required 'E:\XXX/sites/all/modules/wincachedrupal/drupal\_win\_cache.inc' (include\_path='C:\xampp\php\PEAR') in E:\terma\includes\bootstrap.inc on line 2413\`

Have you any idea on what can be wrong?

# Answer
I would assume that this is cache related. Try clearing your cache directly on the database by truncating the cache\_\* tables (since Drush is not working).

You cannot delete modules by removing them from in your modules folder. You have to disable/uninstall the module first, if you cannot disable the module through Drush or UI you can edit the system table by searching the column 'name' for your module and setting the column 'status' to 0. After that clear your cache again.
> 0 votes

---
Tags: caching
---


# Question
Title: Why do I get an Error 500 when loading all news items?
I developed a News Website.

I have more than 5000+ news items on the site, displayed in a view with a pager (100 items per page).

In my view configuration, I enabled *Expose items per page* and *Include all items*.

When I select the -ALL- link, the site displays an AJAX error 500, meaning I cannot display all news items.

Can this be fixed, and if so, how?

# Answer
> 0 votes
The error 500 is most likely caused by Drupal running out of available resources when trying to retried all the results it's being asked to serve. You may wish to consider the following:

* Use a caching mechanism to allow the results to be served without using all available memory or running out of time.
* Increase the memory available to Drupal/PHP.
* Make changes to your view to reduce the memory requirement (fewer items shown per page etc.)

With that said I fail to see the usefulness of a page containing 1000 news stories and you may wish to re-evaluate having the -All- option and/or the option to have 1000 items per page.

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


# Question
Title: How to find out if an entity type is provided by core or a contrib/custom module?
How can I find out which module is providing a particular entity type? I'm implementing hook\_entity\_type\_alter() in a custom module, and I want to identify the entities that are provided by core. Is there a way to get information about the module that implements an entity type, so that I can gets its origin (set in core/lib/Drupal/Core/Extension/ExtensionDiscovery.php) or its package (set in module.info.yml)?

# Answer
There is no definitive way to derive this. Here is why.

1. A decent, but not perfect solution is to maintain a static list of core entity type plugin IDs. However this will change and has changed every minor release due to experimental modules.
2. Checking the "package" of a module will not work because some core modules are in packages that may be re-used by contrib, and there is nothing stopping a contrib or custom module from re-using a package name.
3. If following best practice, then definitively, any module within the `core/modules` directory is in core. This breaks down when someone hacks core and places their modules in `core/modules` for some reason.

I would implement #3 because it is the closest to a definitive, unchanging list for the majority of Drupal sites. However doing #1 is also pretty easy and could easily create a hash of core modules based on core version. Here's an untested approach for #3:

**Edit 2016.11.23**

See @Peacog's answer to their own question for an implementation that takes into account @Berdir's correction about provider not being equivalent to module, and that it is necessary to take into account entity types provided by core, but not core modules.

```
$moduleHandler = \Drupal::service('module_handler');
$entityTypeManager = \Drupal::service('entity_type.manager');
$coreModules = [];

/** @var \Drupal\Core\Entity\EntityTypeInterface $entity_type */
foreach ($entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
  $module_name = $entity_type->getProvider();
  if (!in_array($module_name, $coreModules)) {
    /** @var \Drupal\Core\Extension\ExtensionInterface $module */
    $module = $moduleHandler->getModule($module_name);
    // Test the module's relative path against core. I think this should work using ^ RegExp operator.
    if (preg_match('/^core/', $module->getPath()) {
      // A core module implements an entity.
      $coreModules[$entity_type_id] = $module_name;
    }
  }
}

```
> 3 votes

# Answer
You can make use of module handler to get path to extension info file.

```
/**
 * Implements hook_entity_type_alter().
 */
function example_entity_type_alter(array &$entity_types) {
  $module_handler = \Drupal::moduleHandler();
  foreach ($entity_types as $entity_type => $entity_type_info) {
    $provider = $entity_types['block']->getProvider();
    $module = $module_handler->getModule($provider);
    $info_file = $module->getPathname();
    drupal_set_message("$entity_type ---> $provider ($info_file)");
  }
}

```
> 4 votes

# Answer
Thanks for all the great answers. Here's what I ended up with:

```
foreach ($entity_types as $entity_type_id => $entity_type) {
  $core_entity = FALSE;
  $module_name = $entity_type->getProvider();
  if ($module_name != 'core') {
    // Identify core entity types that are provided by modules.
    $module = $module_handler->getModule($module_name);
    if (preg_match('/^core/', $module->getPath())){
      $core_entity = TRUE;
    }
  }
  else {
    // Some core entity types are not provided by a module.
    $core_entity = TRUE;
  }
}

```
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How can I print a variable in the node template?
How can I print a variable in the node template?

For example, if it's a variable of content, we can print it with the following code.

```
{{ content.field_name }}

```

If I have a `{{ counter }}` variable, how do I display it with Twig?

# Answer
If it's a variable that came from a hook\_preprocess\_node, you can just print it in your twig template as you wrote it in your example:

```
{{ variable_name }}

```
> 1 votes

---
Tags: theming, nodes, 8
---


# Question
Title: How can I add points for selected answers to questions implemented using Polls?
The users of my page have to answer a test, which I'm making with the Polls module.

I have a custom currency called "points". The users points have to grow when they answer the test correctly, in order to buy things in the store with Drupal Commerce.

I really don't know how to do this, any suggestions?

# Answer
> 0 votes
By using the Rules module, and some extra work, you can get this to work, as detailed below ...

### Step 1: Use Rules to grant User Points

Use Rules to create a custom rule with a Rules Action that grants points (using the User Points module). Have a look at the rules exammple included in my answer to "How to grant userpoints only for modifying nodes last changed at least 20 days ago?", especially the very first Rules Action in it. Here is how that Rule looks like:

```
{ "rules_grant_userpoints_after_updating_old_content" : {
    "LABEL" : "Grant userpoints after updating old content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "node-unchanged:changed" ],
          "op" : "\u003C",
          "value" : "-20 days"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "123",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Modify existing node (nid=[node:nid]) that was not updated in the last 20 days.",
          "operation" : "Grant points",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

```

The 2nd and 3rd Rules Action is rather to facilitate testing (you may want to ignore those Actions after QA-testing).

### Step 2: Make (core) Poll trigger the Rule

To continue with the Rule from Step 1, you don't want to use that ***Rules Condition*** there, so just delete that. However the crucial part for your case is to have an appropriate ***Rules Event*** to replace the event used in the Rule from Step 1. In your case you want to use a Rules Event like "***When user casts a vote***".

Guess what, there seems to be a (sandbox) module that provides exactly that Rules Event: the Poll Rules Integration. If you don't want to use a sandbox project, then just look at this project to see what's needed for that event to build your own custom module to create such event.

### Step 3: Further complete your Poll-puzzle

After you complete Step 1 and 2 above, the only thing left to complete your "puzzle", is to implement an appropriate Rules Condition to check "*if they answer the test correctly*" (as in your question, for which you did not specify any further details).

---
Tags: polls
---


title: Custom cache context confusion

text:
# Question
Title: Custom cache context confusion
I made my own custom cache context by creating the service which links to a class which implements `CacheContextInterface`, and it seems to work, but the problem is, on page load, it doesn't seem to check if the context itself has changed. Neither the getContext() function nor the getCacheableMetadata() function runs on page load. If, for example, I go to a page that is a different route, it will run those functions for my cache context, as well as others. Also, if any cache tag on any page is invalidated, it will go to my custom cache context and update, but otherwise it will remain cached. How do I get that same invalidation goodness that different routes seem to have?

I notice, in core's core.services.yml, the `cache_context.route` service depends on the `current_route_match` service, which links to CurrentRouteMatch.php and depends on the `request_stack` service. Which of these things is what causes Drupal to end up checking if the route has changed? I want to do this same thing for my custom cache context.

Will I have to depend on some core service, or is there something I can put in either a service definition (in the module's services.yml) or the service class itself that says it wants to be updated?

**EDIT:** What was happening was that I put this new context on a block which loads on the main page, and it was indeed checking the context only for logged in users (just as 4k4 said) but for anonymous users, on page load, it wasn't checking the context so it wasn't updating the block. I guess when it comes to requiring a cache context for anonymous users, it would be better to have the page invalidate more frequently, or get the content with ajax instead.

# Answer
> 2 votes
> How do I get that same invalidation goodness that different routes seem to have?

Cache contexts are not invalidated. If you set a cache context, you increase the number of variants cached. For example if you would make a custom cache context for the weekday and set this cache context on a block, you would get 7 variants of the block in the cache. If you don't set any other cache metadata they will remain in the cache and will never be invalidated or updated.

> I notice, in core's core.services.yml, the cache\_context.route service depends on the current\_route\_match service, which links to CurrentRouteMatch.php and depends on the request\_stack service. Which of these things is what causes Drupal to end up checking if the route has changed? I want to do this same thing for my custom cache context.

Injecting other services in your own service is not enough. You have to use the injected service.

As example this code from the `cache_context.route` service you've mentioned:

```
public function getContext() {
    return $this->routeMatch->getRouteName() . hash('sha256', serialize($this->routeMatch->getRawParameters()->all()));
  }

```

`$this->routeMatch` is the injected service `current_route_match`. You can see how the service is used to build the context from the route name and the hashed route parameters.

> Will I have to depend on some core service, or is there something I can put in either a service definition (in the module's services.yml) or the service class itself that says it wants to be updated?

You only have to inject other services, if you need them in your code. But this depends, on what you try to do with your custom cache context.

---
Tags: 8, caching
---


# Question
Title: How to get my custom 404/403 pages to work with Bootstrap?
I use this in my `template.php` for custom error pages:

```
  //custom 404 not found page
  $header = drupal_get_http_header("status");
  if($header == "404 Not Found") {
    $vars['theme_hook_suggestions'][] = 'page__404';
    drupal_add_css('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css', array('type' => 'external'));
  }

  //custom 403 access denied page
  $header = drupal_get_http_header("status");
  if($header == "403 Forbidden") {
    $vars['theme_hook_suggestions'][] = 'page__403';
    drupal_add_css('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css', array('type' => 'external'));
  }

```

And I have custom `page--403.tpl.php` and `page--404.tpl.php` (these don't exist as nodes)

And they work if it's non-Bootstrap theme, e.g. it works on Zen theme, but it doesn't work on Bootstrap theme. When you go to some random URL it just gives the default page not found error and doesn't load my custom pages.

And I don't get it why.

Also with Bootstrap theme you have to put your custom pages inside `templates/system` and put your custom functions inside `page.vars.php`.

# Answer
You're using `$vars` instead of `$variables` (per conversation in IRC).
> 0 votes

---
Tags: 7, theming, bootstrapping
---


# Question
Title: Views exposed filter error "An illegal choice has been detected. Please contact the site administrator."
I am having a very odd problem with an exposed filter in one of my Views. The page I am talking about is here: http://epsindustry.org/eps-packaging-map2

When I select one of the last 2 options in the menu (EPS Packaging Recyclers or Loose Fill Recycling Drop-off) I get an error that says `An illegal choice has been detected. Please contact the site administrator.` This is really weird to me because it only happens with these 2 options. I don't believe they are set up any differently than the other taxonomy terms. There's nothing all that special about them, its just a term that the admin selects when creating a location for the map.

Any ideas as to why this is happening or how to fix it?

# Answer
I was having the same issue. In my case the 'illegal choice' message was displayed when changing the country from 'United States' (the default value) to 'United Kingdom' and selecting 'North Yorkshire' as state/province and saving.

I did the following to fix it:

* Go to the Configure page of the Location field (by editing the node type and going to 'Manage fields').
* In the 'Events settings' section (not the 'Locative information' section), there is a drop down group called 'Default value'. I set 'Country' to United Kingdom.
* Save field settings.
* Done.

Using:

* Drupal 6.28
* MySQL 5.1.72
* PHP 5.3.3.7+squeeze17
* Location: 6.x-3.3-rc3+6-dev (2013-Oct-25)
* GMap Location: 6.x-2.0-beta5+1-dev (2013-Sep-30)

Hope it helps.
> 1 votes

# Answer
I also faced the same problem i used query alter

I have used node reference as my select field. you can dynamically chance and set the value for select list

**STEP 1:** uncheck **select all** option and select any one item in the drop down.

**Step 2:** alter your value based on what page you are in with use of arg() values.

We used to change the select based in the node id for every node we select one option dynamically. Below is the sample code we used to alter

```
function modulename_views_query_alter(&$view, &$query) {
    if($view->name == "view_name"){
          if($view->current_display == "block_name"){
        $query -> where[4]['conditions'][1]= array('field' => 'field_data_field_field_name.field_selectlist_id', 'value' => $passthevaluetobesent, 'operator' => '=');
            }
    }
}

```

alter the condition class in query alter according to your need dynamically

hope it will be helpful dude.
> 0 votes

# Answer
This can also be caused by a reference to an entity that is set to Unpublished. If you reference an entity and want the options to be visible to Anonymous users the entity will need to be published.
> 0 votes

# Answer
Generally this issue is coming when the exposed form is getting undefined value, if you limit the items to the selected list it will not be taken any other undefined values.

So go to the corresponding filter criteria field and if you check the exposed checkbox you can there is a checkbox "Limit list to selected items". Now check it and save the view.

Thats all.
> 0 votes

---
Tags: 7, views, location, google-maps
---


# Question
Title: Custom module .install does not create table in database
I want to create database table for my custom module.

Inside `mymodule.install` I have:

```
function mymodule_schema(){
    $schema['a_visits'] = array(

    'description' => 'visits table',
    'fields' => array(
        'id' => array(
            'description' => 'make id primary key auto increment',
            'type' => 'serial',
            'not null' => TRUE,
        ),
        'oferta' => array(
            'description' => 'nazwa oferty',
            'type' => 'varchar',
            'length' => '255',
            'not null' => TRUE,
        )
    ),
    'primary key' => array('id'),
    );
    return $schema;
}

function mymodule_install() {
   drupal_install_schema('a_visits');
}

function mymodule_uninstall() {
   drupal_uninstall_schema('a_visits');
}

```

Then I've moved the module's file to server under `sites/all/modules/custom/mymodule` and enabled it via admin panel. Unfortunately **no table in database has been created** (the module is listed as active now).

# Answer
`hook_schema` alone is sufficient to create database tables. I assume you are just disabling and then enabling the module which will not help you to create tables in the database. To get it working, `admin/modules' locate your module and disable it. Then navigate to 'admin/modules/uninstall' and again locate your module and uninstall it.
After this, go to`admin/modules', and enable your module. Now you can find the respective tables in your database.

You can also use drush for the same. `drush dis module_name`, then `drush pm-uninstall module_name` and finally `drush en module_name`.

Also, as per @OPTASY Canada, do check your dblog for any warning or error.
> 4 votes

# Answer
Only this much will work. make sure you first uninstall and reinstall this module again.

```
function mymodule_schema(){
    $schema['a_visits'] = array(

    'description' => 'visits table',
    'fields' => array(
        'id' => array(
            'description' => 'make id primary key auto increment',
            'type' => 'serial',
            'not null' => TRUE,
        ),
        'oferta' => array(
            'description' => 'nazwa oferty',
            'type' => 'varchar',
            'length' => '255',
            'not null' => TRUE,
        )
    ),
    'primary key' => array('id'),
    );
    return $schema;
}

```
> 2 votes

---
Tags: 7, database, installation
---


# Question
Title: Is it possible to call a custom module function in the theme template file?
I created a custom module and there is a simple `hello_world()` function. Is it possible to call this function in the page template file?

Module file looks like this.

```
function choco_custom_newui_total_students(){
return 500;
}

function choco_custom_newui_preprocess_page(&$variables) {
    $variables['total_students'] = total_students();
}

```

**page--front.tpl.php**

```
<h2><? echo $total_students?></h2>

```

# Answer
You can do it, but it's not recommended, because in the Model-View-Controller pattern, your logic is in the Controller (in this case your module) and in the View (your `.tpl` file) you should only have code to show the values that comes from the Controller.

The idea is that all variables are prepared in template preprocess functions (in modules or in your `template.php`).

You can implement the `hook_preprocess_page()`:

```
function YOUR_MODULE_preprocess_page(&$variables) {
    $variables['my_var'] = hello_world();
}

```

and in your `page.tpl.php` file you can now use `$my_var` to output the value set in your preprocess function:

```
echo $my_var;

```
> 3 votes

---
Tags: 7, theming, hooks
---


# Question
Title: How to make an existing website responsive using zengrids?
i'm creating a website using drupal 7, `zen theme` with some other modules, like `superfish menu` for example, for now the website is empty, i'm wondering how to make the website responsive from now ? Can i just (from my starterkit theme) access to the css (or create my own) that contains some media queries and it will work ? or `zengrids` is a best solution ?

# Answer
> 0 votes
I have found the Superfish module plays well with the Zen theme. By default, it will toggle wide dropdown menus to accordion style menus at 768px.

The superfish library includes sass and css template files you can drop into your theme's scss or css folders.

I am using a custom theme based on Zen 7x-6x starterkit.

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


# Question
Title: Append html after node content in custom module in Drupal 7
I have an custom `tpl.php` inside of theme for some node type. It works fine but I would like my custom module to append some HTML after each such node (content of `tpl.php`). And I don't want to override the output from `tpl.php` inside of theme (just add something at the end of it).

Is there an hook for that or should I use different approach?

# Answer
> 1 votes
You can use the node view alter hook in your module to add/change your node object:

> This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.

If you have devel enabled, you can dpm($node) inside your node\_view\_alter function to see the node structure and then you can add to it as needed from the module.

---
Tags: 7, theming
---


# Question
Title: XML Source Won't import without a Source ID
I'm using Drupal 8's Migrate API to pull in an RSS Feed as Nodes. The simple\_xml data parser seems to require a Unique ID for the import or else I get an error on import.

The XML data is coming from the internet and only has one field applicable as a unique id, however it is preceded by a URL. I process the field with the substr plugin in order to pull in the ID, but when I run the import I get the following error message :

```
Migration failed with source plugin exception: field_guid has no value

```

The YAML file includes the following:

```
  source:
    plugin: migrate_gitem_xml
    data_fetcher_plugin: file
    data_parser_plugin: simple_xml
    urls:
      - www.somesite.com/source/xml-source.xml
  item_selector: '/rss/channel/item'
  ids:
    field_guid:
      type: integer
   fields:
    -
      name: title
      label: 'Title of the Item'
      selector: title
    -
      name: link
      label: 'Link to the Item'
      selector: link
    -
      name: body
      label: 'Body'
      selector: >
        content:encoded
    -
      name: guid
      label: 'ID of the Item'
      selector: guid
  process:
    type:
      plugin: default_value
      default_value: content_type
    uid:
    -
      plugin: default_value
      default_value: 1
    title: title
    field_link: link
    body/value: body
    body/format:
    plugin: default_value
    default_value: basic_html
    changed: '@created'
    field_guid:
    -
      plugin: substr
      source: guid
      start: 61
      length: 6

```

Any insight on how to get the Migration to work?

# Answer
field\_guid doesn't exist until the process pipeline runs, which is too late to use as a source ID. You can either simply use guid itself as your ID (with type: string), or do the truncation in prepareRow().
> 1 votes

---
Tags: 8, migrations
---


# Question
Title: How do I update modules with security release only using composer?
On a Drupal 8 site, using the drupal-composer/drupal-project template, how would I go about updating only those modules which have a security release?

Our policy is to not update any module in our monthly maintenance routine unless it has a security update.

Ideally I'd like to find a solution which could be automated.

# Answer
(I am using Drupal 7 modules as example, but just because there are more examples of security updates for Drupal 7 modules.)

Without custom coding, it's not possible. Drupal.org doesn't use a different name schema for security updates. From the version number you cannot know that version 7.x-3.14 of the Views module was a security update, while version 7.x-3.13 was not a security update.

That information is kept in https://updates.drupal.org/release-history/views/7.x, for the Drupal 7 version of the Views module, or in general in `https://updates.drupal.org/release-history/<project short name>/<Drupal version>`.
In the list of terms associated with a release, a *Release type* term whose value is *Security update* means the release is a security update.

```
<release>
  <name>views 7.x-3.14</name>
  <version>7.x-3.14</version>
  <tag>7.x-3.14</tag>
  <version_major>3</version_major>
  <version_patch>14</version_patch>
  <status>published</status>
  <release_link>
    https://www.drupal.org/project/views/releases/7.x-3.14
  </release_link>
  <download_link>
    https://ftp.drupal.org/files/projects/views-7.x-3.14.tar.gz
  </download_link>
  <date>1466019539</date>
  <mdhash>168bb684c8f34297be94b03c797841e5</mdhash>
  <filesize>1656594</filesize>
  <files>...</files>
  <terms>
    <term>
      <name>Release type</name>
      <value>Security update</value>
    </term>
    <term>
      <name>Release type</name>
      <value>Bug fixes</value>
    </term>
  </terms>
</release>

```

The classes under the `\Drupal\update` namespace can help in writing the required code. `UpdateProcessor::parseXml()` is the method used to parse the XML data for a single project, but you would probably need to access one of the services Drupal implements.
> 3 votes

---
Tags: 8, composer
---


# Question
Title: Disable ajax history except for some views
I use Views Ajax history so that customers keep track of a search when they navigate from a view with exposed filters to a product, and then back to the view.

But in other parts on the website, this generates unwanted things, such as *node?page=1 / node?page=2* and so on at homepage, whenever using pagers of blocks views.

I performed a huge **SEO audit**, where these paths are pointed as undesirable, also when you go back with browser buttons it can take 10 clicks before you reach precedent page, not very UX friendly.

But after thinking about it, I really don't know how I could limit ajax history to my products views. Any suggestion welcome !

# Answer
My bad, Views\_ajax\_history is such a minimalist module in fact !

To avoid hacking it, `hook_js_alter` did the trick :

```
/**
 * Implements hook_js_alter().
 */
function example_js_alter(&$javascript) {

  if(arg(0)!='taxonomy' ) {//my products views are taxonomy lists

    $history_js = libraries_get_path('history.js') . '/scripts/bundled/html4+html5/jquery.history.js';
    $views_ajax_history = drupal_get_path('module', 'views_ajax_history') . '/views_ajax_history.js';
    $views_ajax_history_2 = array('viewsAjaxHistory' => array('onloadPageItem' => isset($_GET['page']) ? $_GET['page'] : 0));

    unset($javascript[$history_js]);
    unset($javascript[$views_ajax_history]);
    unset($javascript[$views_ajax_history_2]);

  }
}

```
> 1 votes

---
Tags: 7, ajax
---


# Question
Title: How do I get the plain text value for the {{ label }} field in a twig node template?
Very simply put, I want to print the plain text from the title field of my node without any additional html. Currently I have this in my node--custom-template.html.twig file

```
<h3 class="fancy">
      {{ label }}
</h3>

```

but it outputs it like this

```
<h3 class="fancy">
          <span data-quickedit-field-id="node/13/title/en/teaser">My Title</span>
</h3>

```

I'd like it like this

```
<h3 class="fancy">My Title</h3>

```

I've tried using some of the twig filters like |striptags and |raw, but then nothing displays. I'm wondering if there is a template I could edit for this field, or any other way to just get the plain text string of the node title.

# Answer
You can get the unformatted title from the node object:

```
{{ node.label  }}

```
> 17 votes

---
Tags: theming, 8, entities
---


title: Access entity reference in Block Plugin

text:
# Question
Title: Access entity reference in Block Plugin
I have a content type that has an entity reference field. It's a content type for news articles with a field for tagging the article with taxonomy terms.

I'm attempting to access these terms in a block plugin, however I'm having difficulty. Getting other fields like text fields, and dates work just fine. For example

```
    $node = \Drupal::routeMatch()->getParameter('node');
    $node->get('body')->value

```

Successfully returns the contents of the node's body but when I use:

```
    $node = \Drupal::routeMatch()->getParameter('node');
    $tags = $node->get('field_tags')->value;

```

$tags comes up empty.

```
 die(print_r($tags));

```

Does not display anything. I know it's in there somewhere though because when I use

```
die(print_r($node));

```

I do see the tag id's in there.

Is there a way to display the value of an entity reference field for taxonomy terms, in a block plugin?

# Answer
-\>value is what most field types use but it is in no way restricted to that, they can use whatever they want.

What you want is $node-\>get('field\_tags')-\>target\_id for the ID or $node-\>get('field\_tags')-\>entity for the referenced term object. You can also loop over it with foreach ($node-\>get('field\_tags') as $item) and then $item-\>target\_id/entity.

As always, have a look at the amazing Entity cheat-sheet here: https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for more examples and info.
> 1 votes

# Answer
I found that in order to get the values I had to use getValue() instead of -\>value like so:

```
$tags = $node->get('field_tags')->getValue();

```
> 1 votes

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