title: Sum of node count in each row

text:
# Question
Title: Sum of node count in each row
I have a view that uses aggregation to count the number of nodes of a color type. For example, there are 10 red nodes, 10 green nodes, and 20 blue nodes. For each color, I would like the number of nodes of that color and the total number of nodes, to show on each row.

| Color | Count | Total |
| --- | --- | --- |
| Red | 10 | 40 |
| Green | 10 | 40 |
| Blue | 20 | 40 |

Ultimately, I do want to calculate the percentage in each row as well.

How could I achieve this?

# Answer
> 1 votes
A no-custom-code solution could be something like this (not the most performant way though but you could perhaps do something with views caching).

**Explanation:**
Create one view for the total count that with the use of aggregration and a content type filter returns the total number of nodes (the Total column) In another **Taxonomy Terms view** you attach the total count view by adding a **Global: View** field that is provided by the Views Field View module

**Steps**
\- Create a content type e.g. "*Colornode*"
\- Create a taxonomy vocabulary called "*Colors*"
\- Add three terms *Blue*,*Green* and *Red*
\- Add a term reference field and select Colors as the vocabulary \- Install and enable the Views Field View module

Then import these two views in this order:

```
$view = new view();
$view->name = 'nodecounts';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Node counts';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Node counts';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'type_1' => 'type_1',
  'type' => 'type',
);
$handler->display->display_options['row_options']['separator'] = ': ';
/* Field: Content: Type */
$handler->display->display_options['fields']['type_1']['id'] = 'type_1';
$handler->display->display_options['fields']['type_1']['table'] = 'node';
$handler->display->display_options['fields']['type_1']['field'] = 'type';
$handler->display->display_options['fields']['type_1']['label'] = '';
$handler->display->display_options['fields']['type_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['type_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type_1']['element_default_classes'] = FALSE;
/* Field: COUNT(Content: Type) */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
$handler->display->display_options['fields']['type']['group_type'] = 'count';
$handler->display->display_options['fields']['type']['label'] = '';
$handler->display->display_options['fields']['type']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['type']['separator'] = '';
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'colornode' => 'colornode',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');

```

And the second one:

```
$view = new view();
$view->name = 'colorterms';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Color terms';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Color terms';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '100';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Taxonomy term: Content using Color */
$handler->display->display_options['relationships']['reverse_field_color_node']['id'] = 'reverse_field_color_node';
$handler->display->display_options['relationships']['reverse_field_color_node']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_color_node']['field'] = 'reverse_field_color_node';
/* Relationship: Content: Color (field_color) */
$handler->display->display_options['relationships']['field_color_tid']['id'] = 'field_color_tid';
$handler->display->display_options['relationships']['field_color_tid']['table'] = 'field_data_field_color';
$handler->display->display_options['relationships']['field_color_tid']['field'] = 'field_color_tid';
$handler->display->display_options['relationships']['field_color_tid']['relationship'] = 'reverse_field_color_node';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: COUNT(Content: Color) */
$handler->display->display_options['fields']['field_color']['id'] = 'field_color';
$handler->display->display_options['fields']['field_color']['table'] = 'field_data_field_color';
$handler->display->display_options['fields']['field_color']['field'] = 'field_color';
$handler->display->display_options['fields']['field_color']['relationship'] = 'reverse_field_color_node';
$handler->display->display_options['fields']['field_color']['group_type'] = 'count';
$handler->display->display_options['fields']['field_color']['label'] = 'Count';
$handler->display->display_options['fields']['field_color']['separator'] = ', ';
/* Field: Global: View */
$handler->display->display_options['fields']['view']['id'] = 'view';
$handler->display->display_options['fields']['view']['table'] = 'views';
$handler->display->display_options['fields']['view']['field'] = 'view';
$handler->display->display_options['fields']['view']['label'] = 'Total';
$handler->display->display_options['fields']['view']['view'] = 'nodecounts';
$handler->display->display_options['fields']['view']['display'] = 'block';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'colors' => 'colors',
);
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['relationship'] = 'reverse_field_color_node';
$handler->display->display_options['filters']['type']['value'] = array(
  'colornode' => 'colornode',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'color-terms';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Color terms';
$handler->display->display_options['menu']['name'] = 'main-menu';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'color-terms';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Color terms';
$handler->display->display_options['menu']['name'] = 'main-menu';

```

Result

---
Tags: views
---


# Question
Title: Add a class to a Drupal table cell containing ['data']
In Drupal 8, rendering Tables is still a lot like Drupal 7. You build out multi-dimensional arrays of rows and columns in PHP that Drupal transforms into a `<tr>` and `<td>`s respectively. There is still this confusing Drupalism known as `'data'` that lets you add render array elements as cell data (not to be confused with data attributes).

I've been given a site where the developer chose to use 'data' to render the contents of the cell, but I cannot figure out how to add a class to the `<td>` around the data.

I've read the source code and documentation for Table.php and I'm aware of the new `#wrapper_attributes` but I cannot crack this.

I've tried at least four ways to add the class, and none work.

```
$table['row-' . $row_id] = [

  // Option 1: Class appears on <tr> tag
  '#attributes' => [
    'class' => ['option-1-row-attributes'],
    'id' => 'row-' . $row_id,
    'no_striping' => TRUE,
  ],

  // Option 2: Class appears on <td> tag of first column.
  'item' => [
    '#markup' => $row['my_item']->label(),
    '#wrapper_attributes' => [
      'class' => ['option-2-markup-wrapper-attributes'],
    ],
  ],

  // In the following section, the only item that works is
  // the class on the <a> tag.
  'edit_operation' => [
    'data' => [
      '#type' => 'link',
      '#url' => Url::fromRoute('my_module.my_route', ['item' => $row_id]),
      '#title' => $this->t('Edit'),
      '#attributes' => [
        // Option 3: Class appears on the anchor tag
        'class' => ['use-ajax', 'option-3-link-attributes'],
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => 700,
        ]),
      ],
      // Option 4: Has no effect.
      '#wrapper_attributes' => [
        'class' => ['option-4-data-wrapper-attributes'],
      ],
    ],
    // Option 5: Update: This appears to be the correct solution!
    // Class appears on the <td>.
    '#wrapper_attributes' => [
      'class' => ['option-5-wrapper-attributes'],
    ],
    // Option 6: Has no effect.
    '#attributes' => [
      'class' => ['option-6-attributes'],
    ],
    // Option 7: Has no effect.
    'class' => ['option-7-attributes'],
  ],
];

```

# Answer
After writing out the question in general terms, I've gone back to test again, and have determined that Option 5 in the OP with `'#wrapper_attributes'` at the same level of the `'data'` element does work. I believe Drupal 8 was aggressively caching the table, because my changes were not showing up even after a `drush cr`.

The rules for adding classes to tables via backend PHP is:

* Table class requires `#attributes`.
* TR row class inside TBODY requires `#attributes`.
* TD cell class inside TBODY requires `#wrapper_attributes`.
* TR row class inside THEAD/TFOOT requires `'class'` and `'data'` containers.
Neither `#attributes` nor `#wrapper_attributes` work here.
* TH/TD cell class inside THEAD/TFOOT requires `'class'` and `'data'` containers.
Neither `#attributes` nor `#wrapper_attributes` work here.
* *There is no way to add a class directly to a `<thead>` or `<tfoot>` tag without overriding a twig template.*

Here is the most common example for adding classes to the `<tr>` & `<td>` tags inside the main `<tbody>`, as well as to the main `<table>` tag itself:

```
$table = [
  '#type' => 'table',
  '#attributes' => [
    'class' => ['table-class'],
  ],
  'row1' => [
    '#attributes' => [
      'class' => ['tr-class'],
    ],
    // Table data cell using 'data' for renderable elements.
    'column1' => [
      'data' => [
        '#type' => 'link', // Or any other renderable thing.
        '#attributes' => [
          'class' => ['link-class'],
        ],
        // Other elements required to render the link go here...
      ],
      '#wrapper_attributes' => [ // Watch out!
        'class' => ['td-class'],
      ],
    ],
    // Table data cell using '#markup'.
    'column2' => [
      '#markup' => '<span>' . $this->t('text') . '</span>',
      '#wrapper_attributes' => [
        'class' => ['td-class'],
      ],
    ],
  ],
];

```

Note that the `'class'` container will accept either a string or an array, but I suggest always using an array.

From here, the story gets more complicated. If you need to add classes to the TR or TD/TH tags inside a THEAD/TFOOT area, the rules change completely. Neither `#attributes` nor `#wrapper_attributes` work inside `#header` and `#footer` sections and trying to use them produces very strange effects.

The bare minimum structure for tables with header/footer data columns in Drupal 8 is this:

```
$table = [
  '#type' => 'table',
  // Produces <thead> <tr> <th>
  '#header' => [
    'Header 1',
    'Header 2',
    'Header 3',
  ],
  // Produces <tbody> <tr> <td>
  'row1' => [
    'Body 1',
    'Body 2',
    'Body 3',
  ],
  // Produces <tfoot> <tr> <td>
  '#footer' => [
    'Footer 1',
    'Footer 2',
    'Footer 3',
  ],
];

```

You must change the actual structure of the data and introduce two levels of additional multi-dimensional arrays, in order to leverage the `'class'` array index which requires then also introducing the `'data'` array index. This applies both to the row element and the data cell elements, as seen in the following example:

```
$table = [
  '#type' => 'table',
  // This example works the same way for '#footer'.
  '#header' => [
    // First, introduce an extra level to the array to provide a
    // place to store the class attribute on the <tr> element inside
    // the <thead>.
    [
      'class' => 'thead-tr-class',
      // Next place the columns inside a 'data' container, so that
      // the 'class' can be used.  '#wrapper_attributes' will not
      // work here.
      'data' => [
        // The following line produces data inside a <th>
        // without any class.
        'Header 1',

        // The following lines produce data inside a <th>
        // with a class: th-class.
        [
           'class' => 'th-class',
           'data' => 'Header 2',
           'colspan' => 2
        ],
      ],
    ],
  ],
];

```

The above example `#header` example produces:

```
<table>
  <thead>
    <tr class="thead-tr-class">
      <th>Header 1</th>
      <th class="th-class" colspan="2">Header 2</th>
    </tr>
  </thead>
</table>

```
> 14 votes

---
Tags: theming, 8
---


title: Adding block to the specific content

text:
# Question
Title: Adding block to the specific content
I want to have the same style of block for similar content type but the matter should be different.

For instance, I have a content type of hotel which has different fields in it and I have created a view for list of hotels. Now what I want to do is display the information of of some field from hotel(say Brochure as pdf) as a block when that particular hotel info is requested, rest as content itself.

I know one way of doing it is creating a custom block and restricting it to particular url. But it is too hectic. Is there a simple way of connecting the field from content to the block to that particular content display?

Personal observation: I have tried to place the block(say sidebar first) of content type in "block layouts". Though it shows up, no luck in placing it.

# Answer
> 1 votes
The easiest way is with a View.

* Create a new view
* Disable the Page that will be checked by default.
* The view should take as argument the `Node ID`.
* Also add a filter based on the content type
* Then in the view, add the fields you want (File, PDF)
* On the top (+ Add next to Master), you need to add a display as a `block`

Now, you go to `/admin/structure/blocks` and add the block. Filter it by Content Type.

:)

Views module - https://www.drupal.org/project/views

---
Tags: views, blocks
---


title: Empty body in node edit page

text:
# Question
Title: Empty body in node edit page
I have created a node entering content for its body field; when I return to the node edit form, the body field is empty.

What may cause this problem?

# Answer
If you are using node translations, when Drupal gets an empty body, it first search a translation with non empty body and, if found, shows it. That's probably why you are viewing body content in the node view but an empty textarea in the node edit form, the content surely comes from one translation.
> 3 votes

# Answer
Easy solution. Just go to your database and change the body to "en" language if it says "und". It is in field\_revisions\_body and field\_data\_body in drupal 7
> 0 votes

# Answer
1. Go to 'Wysiwyg profiles'
2. Full HTML -\> Edit
3. Basic Setup -\> Interface language -\> Select English

That worked for me.
> 0 votes

---
Tags: 7
---


# Question
Title: How to resolve "Referenced error: Highcharts not defined" when using Easychart?
I installed the Easychart module 7.x-3.7 in my Drupal 7.51 site. Using Highcharts 4.2.7 in libraries 7.x-2.3. I extracted highcharts and easychart-master contents into `all/libraries/highcharts` and `all/libraries/easychart` folders respectively. Easychart\_ex and Chart contenttypes are shown when adding content.

However in my browser console I am getting this error:

> Referenced error: Highcharts not defined.

I tried all the suggestions mentioned in the ***Notes*** at the end of the answer to "How to plot a chart from CSV uploaded in a content type?", but none of them helped.

Is there any Easychart latest module I am missing or is it the way it is supposed to work (only with Highcharts 4.2.7) is a question left to Drupal!

# Answer
> 1 votes
Easychart 7.x-3.7 ***recommends*** version 4.2.7 of the Highcharts library. This is also what you can see in this specific commit.

And the Easychart project page states "***... v4.x of the Highcharts library***".

So it appears that using Highcharts 5.0.3 is not yet supported, which probably also explains the folder problems you described in your own answer. I don't think that you're missing anything else (or some other "latest" module) that you're missing (as long as you stick to the recommended version of Highcharts you should be fine).

PS: Be aware that there is also the feature request about "make use of new Highcharts 5.0.0 methods" (for the Easychart plugin).

# Answer
> 0 votes
I found that Easychart expects file path for highcharts as js/highcharts and recommended version is "highcharts 4.2.7". In highcharts 5.0.3, the folder structure got changed to code/js/highcharts.js. If file path is changed easychart.module (all/modules/easychart) from js/highcharts to code/js/highcharts, there will be subsequent problems in ec.min.js (Highcharts.getoptions.color2 undefined)-meaning entire folder structure is not correct. When I replaced with the recommended version of highcharts4.2.7, easychart appeared without any problem.

---
Tags: 7, charts
---


title: How can I destroy or unset session?

text:
# Question
Title: How can I destroy or unset session?
I create module with many sessions . I want unset all session after module work . When I use `session_destroy();` end of my module code , I have error and after that my sessions seem delete (`session_unset();` not worked) . but after 4 or 5 time refresh page all sessions show to me .

Error:

```
Warning: session_destroy(): Trying to destroy uninitialized session in Drupal\...

```

How can I fix this problem in my drupal 8 ?

# Answer
> 8 votes
Don't use low level session\_destroy(), use the session manager instead:

```
\Drupal::service('session_manager')->destroy();

```

This will remove all session data and the user is logged out, if that's what you want. You still get a warning if there is no session, so you might want to check this first.

A better solution might be to use the symfony Session object

```
$request = \Drupal::request();
$request->getSession()->clear();

```

if you have set the session data in the request object or

```
$_SESSION = [];

```

if you have used the deprecated $\_SESSION superglobal.

Normally you don't destroy the session or clear all session data, because there might be other modules that also use session data. Simply remove session variables in the same place where you have set them.

```
$request = \Drupal::request();
$session = $request->getSession();
$session->set('mymodule.value', $value);

// remove later when you don't need the value anymore
$session->remove('mymodule.value');

```

When all modules removed their values the session is destroyed by Drupal automatically (for anonymous users).

---
Tags: 8
---


title: Module installation issue

text:
# Question
Title: Module installation issue
I am attempting to install modules on Drupal 8 but I'm getting a failure that says i need to install commercial guys, addressing and zone libraries. When I put the libraries inside the library directory: (public\_html/mysite.com/sites/all/libraries) I still get this error. I'm thinking I need to install them somewhere else since I'm using Drupal 8.

Also, there is a module called composer manager which according to my reads automatically installs needed libraries for modules. The problem i'm facing is that its asking to use the command prompt to install them. see the link below:

How to install the commerceguys libraries for Drupal Commerce 2.x?

Im using Hostgator hosting, how can I install this using command prompt? Which command prompt do I use, Drush, Bash?

# Answer
> 1 votes
Probably better to ask the Hostgator support if/how they support that.

One alternative is setting up and running those commands locally, that will download the necessary files and you can then upload them.

---
Tags: 8
---


# Question
Title: How to translate plurals in language with multiple cases (most of European)
Function format\_plural is useable only if language has only one plural case (English), but I need to use it for Czech language what has (like most languages from slovenian and roman family) more cases for plural.

For example English has two cases:

* 1: bed
* 2-∞: beds

But in Czech we needs more cases for the same word:

* 1: postel
* 2-4: postele
* 5-∞: postelí

~~And the schema is usually different for different words.~~ (Mistake, it is the same for all words in one language, but different between languages.)

Is there some API in core or in some module that can translate this (for Americans crazy :-)) cases?

# Answer
> 2 votes
format\_plural() does support multiple plural versions in general.

format\_plural() only has arguments for singular and plural because english only has those two and the input is always english, Drupal does not support translating interface text from another language than english.

However, it is something that defined per language and not per word, that doesn't work. I'm not aware of a workaround that can handle per-word differences.

Actually, according to https://en.wikipedia.org/wiki/Czech\_declension#Plural\_forms, those rules (1, 2-4, 5+) are always the same? So that should just work.

This is how it looks in the UI

---
Tags: 8, i18n-l10n
---


# Question
Title: How to detect insertion of new item(s) into Drupal's queue?
I need to trigger some code when new items are added to Drupal's queue system. My question, how to do that? How to capture that event?

**Further details**

I have created a custom views bulk operation which enqueues items into Drupal's queue system for further processing. Usually, the enqueued jobs would run when Cron runs. I need to execute a function when new items are added to the queue by VBO. I could query the database every minute to check for new items, but I hope it is possible to listen to that insertion event using a rule or a hook.

# Answer
There is another question here with some equal requirement: Insert task to Queue only if unique

The idea is to create a custom queue class extending the original one. Your custom class only overrides the createItem method. Just copy the original one and add your custom functionality.

After that you need to let Drupal know about your new queue class.

The downside is that it would override the class of your queue for every operation on it.
> 2 votes

---
Tags: 7, hooks, queue
---


# Question
Title: How can I remove decimals when I award user points via commerce-order-total:amount
I want award users after completing the checkout process. For this task I use this modules (Commerce, UserPoints, Commerce Credits).

I create a product with a price equal 15$ and create a rule which award user after complete checkout. When checkout is complete, rule works great, but it gives user 1500 userpoints instead 15. I tried use module (Commerce Price Decimals Formatter, Commerce Extra Price Formatters) which remove decimals from commerce also I tried use some code from internet but all of it doesn't solve my issue.

Does anybody know solution for this issue?

it's code that I found on the internet:

```
<?php
/**
 * Implements hook_commerce_currency_info_alter().
 */
function Zero_commerce_currency_info_alter(&$currencies, $langcode) {
  $currencies['USD']['format_callback'] = 'Zero_rub_currency_format';
}

 /**
 * Currency format callback.
 */
function Zero_rub_currency_format($amount, $currency, $object) {
  $round_amount = commerce_currency_round(abs($amount), $currency);
  $price = number_format($round_amount, 0, $currency['decimal_separator'], $currency['thousands_separator']);

  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

  return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}

```

It is my Rule:

```
{ "rules_grantpointaftercheckout" : {
"LABEL" : "GrantPointAfterCheckOut",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "userpoints_rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"DO" : [
  { "data_convert" : {
      "USING" : {
        "type" : "integer",
        "value" : [ "commerce-order:commerce-order-total:amount" ],
        "rounding_behavior" : "down"
      },
      "PROVIDE" : { "conversion_result" : { "conversion_result" : "Conversion result" } }
    }
  },
  { "userpoints_action_grant_points" : {
      "user" : [ "site:current-user" ],
      "points" : [ "conversion-result" ],
      "tid" : "0",
      "entity" : [ "site:current-cart-order" ],
      "operation" : "bla bla bla",
      "display" : "1",
      "moderate" : "approved"
    }
  }
]
}
}

```

# Answer
Have a look at the Drupal Commerce issue about "Revise the way we handle price amount values". Especially comment nr 37 in it, which states:

> The price field is and will continue to store price amounts as integers ...

So rounding an amount of 1500 dollarcents is ... still 1500, right? And that is the amount of user points you're granting. And because of that, your rule works as implemented: you're using that value of 1500 as the amount of userpoints to be granted.

Obviously, all you need to do next is to expand your rule to devide the price by 100 first (before rounding it). I assume you know how to do that, if not use this link ... bonus hint: have a look at the example rule included in the answer to "How to add up all items of a field collection field using Rules?", especially the "Calculate a value" Rules Action.
> 1 votes

---
Tags: 7, commerce, rules, userpoints
---


# Question
Title: How to specify entity reference fields when programmatically submitting to user_register_form
You'd think this would be easy. I'm calling `drupal_form_submit('user_register_form', $form_state)` to automatically register users after they have completed filling out a Webform.

But I have some Entity Reference fields in my user profile and `form_validate` is not happy with what I am submitting for them. All of the ER fields are references to taxonomy terms. Some of them are single-value fields, some of them are unlimited value fields. They have various widgets attached such as Select List, Autocomplete, Checkboxes and Radio Buttons. Some of them are Required fields, others are not.

I've tried setting all of the following in `$form_state['values']` before submitting the form:

```
$form_state['values']['field_foo']['und'] = $tid;
$form_state['values']['field_foo']['und'][0] = $tid;
$form_state['values']['field_foo']['und'][0]['target_id'] = $tid;

```

But Drupal still throws out 'An illegal choice has been detected' when it comes to validate the field, or sometimes a 'Field is required' error.

What am I doing wrong and how do I go about figuring out the right way to specify each of the fields?

# Answer
I think form might be expecting in proper format that is "\[entity-title\] \[entity\_id\]", so field array should look like.

```
'field_foo' = {
    'und' = [
        0 = {
            'target_id' = 'Title of entity ($tid)'
        }
    ]
}

```

Just to make sure you can form alter user form, add a custom validate and do a `dsm($form_state);`
> 0 votes

---
Tags: 7, forms, entities
---


# Question
Title: Why are my webform conditionals not always working?
We have 2 partially same webforms with conditional fields, opening a number of components depending on the selection with radio buttons. When logged on as administrator, both forms work fine. when logged on as simple user, only one webform all works fine, the other shows all components as it were designed.

We did recreate the conditionals already and the permissions are same on both forms. Also no error message is generated in any way. Anyone has similar problem or has ideas?

# Answer
As our native language is Belgian Dutch and we use a comma for decimal separator, I added a simple replacement for comma to dot in webform\_calculations.js.
This resulted initially in a javascript error for empty fields, and meanwhile the code was reproduced in Drupal's default files.
Since only one webform has calculated fields only that form was affected when logged on as user.
After correction a new file was generated and strange enough only administrator login used it, so all worked fine, while the user logon kept using the faulty file, even after all cache cleaning (Drupal and browser) and rebuilding.
Replaced all files with correct code..
Problem solved.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: Entity token availabe in Rules but non-functional
I'm building a submission-review page where submitters select a reviewer. Submissions show up on reviewers profile page and have accept and decline buttons implemented with Button Field module. When the reviewer clicks the accept button, he gets redirected to a new review content form.

Review content type has a node reference field to submission content type which should get populated automatically using Node Reference URL Widget.

I use the Rules module to check if accept button has been clicked and to fire the *Page redirect* action:

After defining condition *Entity is of type Node* replacement patterns show up and seem to be available:

So I fill *URL to redirect to* with the relative url and the entity id:

```
node/add/review/[entity:nid]

```

But it doesn't have effect. Rule gets fired correctly but \[entity:nid\] is empty and reviewer gets redirected to node/add/review/ and so node id to prepopulate node reference field is not available.

Am I doing something wrong or is it a bug in Button Field? Any hints to implement that funcionality in a different way?

# Answer
I'm not familiar with using the Button Field module in combination with the Rules module.

But from your question details, it seems that the `entity:nid` value is indeed blank. A possible solution is typically to add a Rules Action which is either of these:

* "Fetch entity by ID" (if you know the ID you're processing).
* "Fetch entity by Property" (if you have some criteria to build a list of things to be processed in a subsequent Rules Loop).

Especially the "Fetch entity by ID" is what I think you should give it a try. Also because of what's written in Comment nr 3 of issue nr 1796952, and which has some pseudo code like so:

* event : on User clicks a button field
* condition: Entity is of type on entity (make sure everything is in scope of rule)
* actions:
    + Fetch entity by id with ID (data selector) : entity:nid
    + pump the 'fetched entity' into a component and do things in there

If none of the above helps, then the "***Submissions show up on reviewers profile page***" part of your question is something that may help to use a completely different approach. If that's something like a Views result" (is it?), then you could maybe use either of these approaches:

* Add a Rules Action to load a list the list of results created via a VBO enabled view.
* Use the Views Rules module to have each row of that view processed via Rules, whereas you can make each column of such view available as a rules token, so if that "nid" is included in it, you have what you're looking for.

If none of the above help, You may want to use Rules debugging (eg to display values of relevant things using the Devel module, so that you can (temporary) add a Rules Action like "Display a value". For more suggestions about that, refer to "How can I display the value of a variable inside a condition?".

PS: those 2 ***AND*** Rules Conditions are not needed in your case (that's the default of how Rules combines multiole Rules Conditions).
> 2 votes

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


# Question
Title: How To Remove Table border or hid to show my page
I made a view and display " tender" and the Page Format is Table and I don't want show the table border how to hide or remove?

# Answer
Add this to your theme CSS:

```
table {border: none;}

```

Which will alter all the tables in your theme To limit the border removal to just this view, find the view class \[in Google chrome, use the code inspector\] to find the div with the class 'view' and select the class appropriate to this view. For example if you have the classes:

```
view
view-Tender
view-display-id-page_1

```

you can limit the table border css by:

```
.view-Tender table {border: none;}

```

for all the displays in the view or

```
.view-Tender.view-display-id-page_1 table {border: none;}

```

for just this display.
> 1 votes

---
Tags: views
---


# Question
Title: Automatic registration for anonymous node authors
I need anonymous users to be automatically sent drupal 'welcome' link when they create nodes (it's required to enter email and to create login when creating nodes). So AFTER the node is created, the user can go on with registration.

# Answer
I am not sure how easily you would be able to do this, but you might be able to do this using rules.

Have a look at Inline Registration. You can configure quickly to attach a registration form to the node creation form.
> 0 votes

# Answer
I have also got some success using the HybridAuth Social Login module. This is pretty easy to configure. I think there are a couple of videos online for how to configure it. I have it configured for Facebook, and it's a one click registration for the user. Not sure about the other providers though. I also wonder about site security implications and bots. But I seem to have been OK so far.

You could also look at Anonymous publishing module. This may do what your looking to do as well.
> 0 votes

---
Tags: nodes, users
---


# Question
Title: print custom image field for taxonomy page (page--taxonomy.html.twig) template
How do I load an image from a taxonomy custom field into a custom location on the taxonomy page template?

It's easy to accomplish it when the image is in a node. The following code works for images, but it doesn't work for taxonomy pages.

```
    {{ file_url(node.field_reference_background.entity.uri.value) }}

```

How can I accomplish the same for taxonomy pages?

# Answer
> 5 votes
Only entities from type node are loaded in the page template by default. If you want this for other entity types you have to add custom code to page preprocess:

```
function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['term'] = $term;
  }
}

```

Then you can access the fields from the term in page--taxonomy.html.twig:

```
{{ file_url(term.field_image.entity.uri.value) }}

```

---
Tags: theming, 8, taxonomy-terms
---


# Question
Title: How to join the dots and reduce the dot size in scatter plot using Easychart?
I am using Easychart 7.x-3.7 with Drupal 7.51. I uploaded a CSV to display a scatter chart with x-axis (1st column) and y-axis (2nd column). The size of the dots are so big. Here is a screenprint of what I have so far:

How will I reduce the size of the dots and also how will I join the dots to show it like a line?

# Answer
Part of what you're asking for (= "***How will I reduce the size of the dots***"), is a typical example of how it is like to use a UI (= Easychart), and find out that you need some special option/facility of the Highcharts library, but which you cannot enter via the Easychart UI.

Here are some hints/directions to try to resolve that part of your question anyhow:

* As you must have noticed using the Easychart UI, there is nothing (out-of-the-box) that you can use to reduce that size of those dots.
* So head over to the Highcharts options reference which outlines the chart configuration options, and the methods and properties of Highcharts objects. Attention: don't get overwhelmed, there are a zillion of options ... in this case, your question boils down to plotOptions.scatter.marker.radius, which is the "radius of the point marker" (don't ask me how I know, I just do ...). It turns out that its defaults is "`4`". So with that your question becomes like this: How do I overwrite that default value of `plotOptions.scatter.marker.radius` with (eg) "`1`"?
* To understand where we're going, first have a look at the Feature request Other chart types. It's a request about "*Is it possible to use more chart types like Donut, 3d Pie, or any available HighCharts examples*". So that is actually way more then just adapting the default value of "radius of the point marker". Nevertheless, comment nr 3 in that feature request contains the actual answer. The crucial part of that comment is that it contains "***an example of an interface with more options than those provided by our default set***". It takes some effort to digest it (what it is about), but the most important part of that sample is at the end of it, and which looks like so:

> ```
> {
>   "panelTitle": "Advanced Chart options",
>   "pane": [
>     {
>       "title":"Pie/Donut",
>       "options": ["plotOptions.pie.innerSize","plotOptions.pie.allowPointSelect","plotOptions.pie.depth","plotOptions.pie.cursor"]
>     },
>     {
>       "title":"3D",
>       "options": ["chart.options3d.enabled","chart.options3d.alpha","chart.options3d.beta"]
>     }
>   ]
> }
>
> ```
* To understand what this sample is about, have a look at the image in the next comment (nr 4), which looks like so:

As shown in the above image, by adding (near the end) those specifications about "Advanced Chart options", it is perfectly possible to add that panel with title "Advanced Chart options", and with the 2 panes titled "Pie/Donut" and "3D" (each with their related "options" also).
> 1 votes

---
Tags: 7, charts
---


# Question
Title: How can I limit submissions within a period of time?
How can I limit submissions within a period of time?

I am moving from webforms to entity forms and need to limit the number of submissions a user can make within a given time. I want to restrict access to form based on this. This would be only apply to anonymous users.

* List item

1 Submission per week 3 submission per day etc. Similar to the setting on webforms

# Answer
You need to identify a unique identifier.

It can't be the `UID` as schlicki mentioned in the comment.

You can add an email field. But if you don't add validation to this, people can just make up something up.

If you're going to add email + validation, would an account on the site be worth it?

Another option is a combination that identifier the browser as unique. You can look into https://github.com/Valve/fingerprintjs2. You can take all those properties and hash all of those together. That should give you a good identifier.

**THIS CAN BE FOOLED. BY DEFAULT THEY WILL BE ABLE TO SUBMIT A FORM PER EACH BROWSER ON EACH DEVICE THEY HAVE.**

If it doesn't have to be super strict, it would work.

This link, https://panopticlick.eff.org/ may have more information on what you're exploiting.

What I would do,

* Generate a hash based on all the properties from `fingerprintjs2`.
* Take that hash and add it to a hidden field
* On submit, you can check the value
    + Validate that it's not empty.
    + Check the value in the database (you'll need a table for this)
    + If it is on your table,
        - Check when was the last time this was submitted
        - Apply your rules.
            * If it can be submitted again, perfect.
            * If it can't be submitted again, show a message. You can show how much time they need to wait for the next submission.
    + If it's not on your table,
        - Add the value to the database
        - Allow the submission through

That's the logic that you would have to apply.
> 0 votes

---
Tags: forms
---


title: copies of installations for each client

text:
# Question
Title: copies of installations for each client
I have built a Drupal based web app product that I want to give (a trimmed down version) for free. I am expecting 100s and 1000s of subscribers. Each one should get an exclusive code base (drupal files) and database- thats my product's need.
I plan to use AWS- amazon web services.

1). I want users to visit my company site and click and install the product(the web app site) for themselves. This should automatically
a. create a sub-domain,
b. copy my main code base and database. How to do these?

2). For maintenance and upgrades management, I want to have a single parent code base (probably at private github) and would want each of these sites to replicate that. This is to avoid upgrading 1000s of sites individually. How to do this?

3). Some of my subscribers may want to upgrade to paid version. So I may have to customize their instance. How to ensure the custom changes are not overridden on maintenance acts of above point.

I have a low budget so I cannot buy any service to do this. I am hoping that a module or some Drush way can solve this.

# Answer
> 0 votes
You may be able to use Aegir (Hostmaster): https://www.drupal.org/project/hostmaster

---
Tags: multi-sites
---


title: Set a session when page is loaded

text:
# Question
Title: Set a session when page is loaded
I want to define a session in contributed module (field collection module) in drupal 7 when the page is loaded.

This session takes a value from the URL and fill one of the field that depend on it. I defined a session in the form\_alter function but I need to refresh the page to let the session take the value? So, could anyone tell me where I can define it? In which function of the module?

# Answer
> 2 votes
You can use the session that Drupal creates. Just add your data to an element of the $\_SESSION variable:

```
$_SESSION['my_module']['some_key'] = 'some value';

```

It will

---
Tags: 7, forms
---


title: Create a new order

text:
# Question
Title: Create a new order
I am working with Drupal commerce and I want to create a new order with the Rules module, when the *Completing checkout process* event is fired.

The second order should have all the same commerce line items the first order has.

Could anyone help me?

# Answer
> 2 votes
Perhaps you can do the following (not entirely sure though)

Create a rule that triggers on Checkout completion and execute custom php code.

**How it works:** On the event *Completing the checkout process* the order that is involved in this checkout process is available through the variable *$commerce\_order*. Then we assign this order to a new variable and use it in the code provided by the function referenced below. We save the uid and profile\_id from the order we want to clone so we can set the user and the billing information on the clone.

Import code of rule

```
{ "rules_clone_order" : {
    "LABEL" : "Clone order",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "custom" ],
    "REQUIRES" : [ "php", "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "php_eval" : { "code" : "$previous_order = $commerce_order;\r\n$uid = $previous_order-\u003Euid;\r\n$profile_id = $previous_order-\u003Ecommerce_customer_billing[LANGUAGE_NONE][0][\u0027profile_id\u0027];\r\n\r\nforeach (commerce_order_load_multiple(array(), array(\u0027status\u0027 =\u003E \u0027pending\u0027), TRUE) as $previous_order) {\r\n  $product_ids = array();\r\n  foreach (entity_metadata_wrapper(\u0027commerce_order\u0027, $previous_order)-\u003Ecommerce_line_items as $delta =\u003E $line_item_wrapper) {\r\n    if (in_array($line_item_wrapper-\u003Etype-\u003Evalue(), commerce_product_line_item_types())) {\r\n      $product_ids[] = $line_item_wrapper-\u003Ecommerce_product-\u003Eraw();\r\n    }\r\n  }\r\n}\r\n\r\n    $order = commerce_order_new ( $uid , \u0027pending\u0027 );\r\n    \/\/ Save the order so its ID is assigned.\r\n    commerce_order_save ( $order );\r\n\r\n    $order_wrapper = entity_metadata_wrapper ( \u0027commerce_order\u0027 , $order );\r\n\r\n    \/\/add products to order by ids array\r\n    foreach ( $product_ids as $product_id ) {\r\n        $product = commerce_product_load ( $product_id );\r\n\r\n        \/\/ Create a line item with quantity 1 and this product.\r\n        $line_item = commerce_product_line_item_new ( $product , 1 , $order-\u003Eorder_id );\r\n\r\n        \/\/ Save the line item to get its ID.\r\n        commerce_line_item_save ( $line_item );\r\n\r\n        \/\/ Add the line item to the order using the wrapper.\r\n        $order_wrapper-\u003Ecommerce_line_items[ ] = $line_item;\r\n    }\r\n\r\n\r\n    $profile_object = array ( \r\n        \u0027und\u0027 =\u003E array ( array ( \u0027profile_id\u0027 =\u003E $profile_id , ) , ) , ); \r\n    \r\n    \r\n    $order-\u003Ecommerce_customer_billing = $profile_object;\r\n\r\n    \/\/ Save the order.\r\n    commerce_order_save ( $order );" } }
    ]
  }
}

```

**Credits**: The code to save an order comes from this post: https://drupalcommerce.org/comment/3491#comment-3491

---
Tags: commerce, rules
---


title: Execute jQuery after form submit

text:
# Question
Title: Execute jQuery after form submit
I have a non-ajax form for which I'm trying to execute a jQuery function after the form has been submitted and processed.

I don't need ajax for the form, but I do need to wait until 600 odd form fields have been processed before executing my jQuery function.

There are a lot of answers out there, but I can't quite figure them out.

Should I do this via ajax (even though not required for the form) or is there a better way to do it?

Given the form takes a good few seconds (10 or so) to process (more on mobile, etc.) how should I go about it?

**EDIT:**

Another go at explaining exactly what I'm trying to do.

1. I have a form that collects 600+ pieces of data
2. After the form has been submitted and processed, I need to open a new window that processes the data, displaying it graphically (via canvas) and then saves that canvas as an image to the user profile.

Because there is so much data that needs to be processed, I've elected to run everything in a new window, so if the user navigates away from the main window, their canvas is drawn and saved, etc. in the background.

It appears that jQuery is the only way to open this new window, and I have to execute this after the form submission (otherwise the canvas is drawn with pre-submitted data)

Of course, there could be a better end to end way to do it, but jQuery post form submit seems to be it.

# Answer
You can use Drupal.behaviors, which is fired upon page load.

```
function doSomething()
{
  // Do something
}

Drupal.behaviors.myModule = {
  attach:function() {
    doSomething();
  }
};

```
> 0 votes

---
Tags: forms, javascript
---


# Question
Title: After moving document root, pages can't be found
Drupal 8 installed on shared hosting. To access the site from the web during development, I installed D8 in `/www/d7/d8`.

Then I moved `d8`, which contains the D8 install, to `/www/d8` and then set my document root in Cpanel to `d8`.

The theme and blocks load, and I can fill out the form at `/user/login`, but after that, every time I try to access a page, I get an "access denied" message and the link is pointing at `mysite.com/d8/page` instead of `mysite.com/page`.

I looked in `settings.php` and `.htaccess` but I couldn't find any references to a base directory.

How can I get my D8 site working after moving the directory and changing the document root?

# Answer
> 2 votes
Browser cache was the issue. Resetting the cache made everything go back to normal.

---
Tags: 8, installation
---


title: Q&A answers not publishing

text:
# Question
Title: Q&A answers not publishing
We are using Commons modules and among other parts of it a Q&A module. We noticed that when a user question is answered ,, answers do not get published. Not even when admin answers the question. Instead, we have to go in and set publishing options for all answers, one at a time.

The content type used for answers is called "Answers" and a default setting for publishing options is set to "published".

When the answer form is submitted the publishing option is not checked..

Does anyone know why this is getting overridden and how to make this work?

Thanks!

# Answer
> 2 votes
Recently I had a slightly different but similar issue with answers in commons. When a user answers a question it was by default visible to trusted contacts of that user but not visible to group members and there was no way to change that even as an admin. After spending quite some time, I tried disabling the commons feature "**Commons Trusted Contacts**" which solved the problem.

So, one thing is clear it is this feature/module which is overriding. If you don't need trusted contacts functionality, you can just disable this. Otherwise, Commons trusted contacts is the right place to look into to solve the actual cause.

# Answer
> 1 votes
I think the answer you want is the patch in this issue: https://www.drupal.org/node/2399695

# Answer
> 0 votes
You could look to see if there is a custom module implementing `hook_from_alter` or `hook_form_FORM_ID_alter` and overriding the default behavior. Search the code base for \_form\_alter in custom module directory to get started. If you could not find the what is actually overriding the default behaviors then you could implement `hook_form_alter` or `hook_form_FORM_ID_alter` and override the behavior yourself. Do something along these lines:

```
<yourmodule>_form_node_form_alter(&$form, $form_state) {
   // Do some checks to verify this is the content type you are targeting.
  $form['options']['status']['#default_value'] = TRUE;
}

```

---
Tags: 7, nodes
---


# Question
Title: What might be causing my problem to access user variables in Rules?
I use the module Rules link event to trigger a rule based on visited path. The problem I have that in condition I need to use user variables but get an error - variable user is not defined. If I try php condition and use `global $user`, I get `Notice: Trying to get property of non-object in eval() and Warning: in_array() expects parameter 2 to be array, null given in eval()`

What could be the problem here?

# Answer
Not sure what the reason might be that is causing your problem. But something that you could do to make this work, for sure, is like so:

* Add a Rules Action "Fetch entity by id", whereas you want to fetch the user entity, and where you use the `uid` of the "current-user". For any subsequent Rules Action, you then have all fields of that user available as tokens.
* Enable the Conditional Rules module, which allows you to specify Rules Conditions as part of Rules Actions. Using that technique, you can then like "move" any of your existing Rules Conditions (ie the ones where you need those user variables, as per your question). In doing so, you can then use any of the tokens that you made avaiable via the preceeding Rules Action "Entity has field".

BTW, no dangerous PHP code (stored in your database) needed to get this to work ...

***Easy, no***?
> 0 votes

---
Tags: 7, rules, tokens
---


# Question
Title: Why is my Rules data comparison not evaluating correctly?
This should be easy, but I can't figure out what is going wrong. I have created a field on the user account called "User profile type." It has two options: "General user" and "Grant Network user".

I am trying to create a rule (using the Rules module)to apply a role to these options if they are selected upon saving or updating of the user account form.

However, despite everything I have tried, I can't get the data comparison to evaluate as TRUE:

* I am selecting `site:current-user:field-user-profile-type:0` as the data to compare.
* Then, in the conditions field, I am given the option in the direct input method to choose the item I want.
* I am trying to choose "Grant Network user" and it evaluates to FALSE every time no matter what I try.
* I have set it up with an OR statement, so that I also am selecting `site:current-user:field-user-profile-type:1` as well. But, neither of these will evaluate to TRUE.

The weird thing is that when I test these data selection values in a rule to show a message on the site, they both display a message of "Grant Network user."

So, I don't understand why the data comparison is evaluating to FALSE.

Any ideas? It's probably something simple, but I can't seem to figure it out.

**Note**: I have tried selecting the field without the colon, but it doesn't seem to work either. It makes sense to try that, but part of my problem is also that I want to be able to select for more than one item. I'd prefer to use a "contains" operator, but it isn't available, so I'm trying to use the "`...:0`" and "`...:1`" options with an OR statement to allow for both options being selected. Am I understanding this wrong?

# Answer
As per the "`site:current-user:field-user-profile-type:X`" part of your question (X=0 or 1), it seems that your "User profile type" field is a multi value field. Whereas you're trying to use a *Data Comparison* rules condition. Sorry to say, but for a multi value field, you should NOT use a "Data Comparison", because that's like trying to compare an array with a single value (which doesn't make sense).

To get your rule to work like you want it to work, you should use these Rules Conditions (in the specified order):

* ***Entity has field***, for your "User profile type" field, to make it available for subsequent Rules Conditions and/or Rules Actions.
* ***List contains item***, whereas:
    + the list is also about that same "User profile type" field (since your field allows multiple values, it is also considered as a list).
    + the item you want to check for (if it is contained in the list) is (e.g) "`Grant Network user`".

With those 2 Rules Conditions, your Rules Actions should be performed as you want it to work. For the sake of (basic) unit testing, just (temporary) add a Rules Action like "Display a Drupal Message" (as the very first Rules Action), with whatever message text (eg: "*bingo, Pierre is right ...*").

For an example Rule (in rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.

PS: I'm assuming this question is about D7 ...
> 0 votes

---
Tags: users, rules
---


# Question
Title: What causes my Rules error when trying to send an email if profile field contains some value?
I'm using Rules and Profile2 in a D7 site.

I'm looking for help to check my logic for the following rule. I can't get it to work and don't know where I'm going wrong.

**Event:** After saving a new profile

**Condition:** Data Comparison--\> Selected data: `site:current-user:profile-main:field-become-a-distributor`

**Action:** send e-mail

Condition is what breaks. Here is what is in my error log:

> Unable to get the data value for the variable or parameter data. Error: Unable to get the data property field\_become\_a\_distributor as the parent data structure is not set.

# Answer
Your question is a bit cryptic, but here are a few hints of what might possibly be causing your error:

* The token `site:current-user:...` that you're using in your Rules Condition may not be the correct token to be used. E.g. think of some (super) admin (like user/1) who is triggering the Rules Event you're using (but for an account which is different from user/1) ... In this scenario, your Rules Condition refers to a field related to ... user/1 (and not the account that triggered the Rules Event).
* You're trying to access that token in your Rules Condition, but are you sure its value is available? To be sure of that, preceed that Rules Condition by an "Entity has field" Rules Condition (for the account for which a new profile is being created, and for the field you're trying to use in your Rules Condition).
* If none of the previous hints solve your issue, it may be that you also need to perform a "Fetch entity by ID" (for the account being created), as your first Rules Action. And then combine this with the execution of a Rules Component (with parameter the data returned by the "Fetch entity by ID"), whereas you replace your existing Rules Condition by an equivalent Rules Condition of that Rules Component, and with your existing Rules Action (to send an eMail) also moved to an equivalent Rules Action in that Rules Component.
> 0 votes

# Answer
Use Data selector `account:field-YourField`
> 1 votes

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


# Question
Title: Why do my Commerce rules incorrectly award double userpoints?
I have 2 products and when user buy it I want award userpoints depend on quantity.

For this task I use specific module (Rules array create and commerce rules extra) it let me create array base on quantity. If user buy on of my product all work correct but when product is mix, all work wrong. My rules double userpoints.

What I want: I have products "A" and "B". Product "A" costs 15$ and product "B" costs 25$. When user buy "A" I want award 20 userpoints, for "B" I want award 30 userpoints also if user increase quantity of product I want award userpoint for each number (example: Ax2=40 userpoints; (Ax2=40 Bx1=30)=70 userpoints ).

In my rules I check condition: I check order for contains sku.

What I have: When user buy one of product my rule work correct. But when user buy both product (A and B) my rules double userpoints and user get double amount (A=20 points, B=30 points amount = 100 instead 50)

How can I avoid this trouble?

This is my rule for first product:

```
{ "rules_grantpointaftercheckout" : {
"LABEL" : "GrantPointAfterCheckOut",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [
  "commerce_rules_extra",
  "rules_array_create",
  "userpoints_rules",
  "commerce_checkout"
],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "commerce_rules_extra_product_sku_contains" : {
      "commerce_order" : [ "commerce_order" ],
      "product_id" : "15_min",
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "array_create" : {
      "USING" : { "size" : [ "commerce-order:commerce-order-quantity" ] },
      "PROVIDE" : { "array_added" : { "array_added" : "Added array" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "array-added" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "userpoints_action_grant_points" : {
            "user" : [ "site:current-user" ],
            "points" : "20",
            "tid" : "0",
            "entity" : [ "" ],
            "operation" : "sdadsasad",
            "display" : "1",
            "moderate" : "approved"
          }
        }
      ]
    }
  }
]
 }
 }

```

This is my rule for second product:

```
{ "rules_grantpointaftercheckout_cloned_" : {
"LABEL" : "GrantPointAfterCheckOut (cloned)",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [
  "commerce_order",
  "rules_array_create",
  "userpoints_rules",
  "commerce_checkout"
],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "commerce_order_contains_product" : {
      "commerce_order" : [ "commerce_order" ],
      "product_id" : "30_min",
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "array_create" : {
      "USING" : { "size" : [ "commerce-order:commerce-order-quantity" ] },
      "PROVIDE" : { "array_added" : { "array_added_2" : "Added array 2" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "array-added-2" ] },
      "ITEM" : { "list_item2" : "Current list item 2" },
      "DO" : [
        { "userpoints_action_grant_points" : {
            "user" : [ "site:current-user" ],
            "points" : "30",
            "tid" : "0",
            "entity" : [ "" ],
            "operation" : "sdadsasad",
            "display" : "1",
            "moderate" : "approved"
          }
        }
      ]
    }
  }
]
}
}

```

This is update, Rules with Conditional Rules module.

Description:

I installed module "Conditional Rules" and make rules with logic like that: If: Order contains a particular product (commerce-order:commerce-line-items:0:order) -\> Create an array (commerce-order:commerce-line-items:0:quantity) -\> Loop (Created array) -\> Grant userpoint. then I add condition again and make second part of rule, but now it check 1 line item. I create 2 rules for both product. If I test it alone all work great, but when I add both product to the cart, userpoints grant only for position avoid quantity.

Rule for A product

```
{ "rules_a_userpoints" : {
"LABEL" : "A_userpoints",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [
  "rules_conditional",
  "rules_array_create",
  "userpoints_rules",
  "commerce_order",
  "commerce_checkout"
],
"ON" : { "commerce_checkout_complete" : [] },
"DO" : [
  { "CONDITIONAL" : [
      {
        "IF" : { "commerce_order_contains_product" : {
            "commerce_order" : [ "commerce-order:commerce-line-items:0:order" ],
            "product_id" : "A_sku",
            "operator" : "\u003E=",
            "value" : "1"
          }
        },
        "DO" : [
          { "array_create" : {
              "USING" : { "size" : [ "commerce-order:commerce-line-items:0:quantity" ] },
              "PROVIDE" : { "array_added" : { "array_added_a_line_0" : "array_added_a_line_0" } }
            }
          },
          { "LOOP" : {
              "USING" : { "list" : [ "array_added_a_line_0" ] },
              "ITEM" : { "loop_a_line_0" : "loop_a_line_0" },
              "DO" : [
                { "userpoints_action_grant_points" : {
                    "user" : [ "site:current-user" ],
                    "points" : "20",
                    "tid" : "0",
                    "entity" : [ "" ],
                    "operation" : "2123",
                    "display" : "1",
                    "moderate" : "approved"
                  }
                }
              ]
            }
          }
        ]
      },
      { "ELSE" : [
          { "CONDITIONAL" : [
              {
                "IF" : { "commerce_order_contains_product" : {
                    "commerce_order" : [ "commerce-order:commerce-line-items:1:order" ],
                    "product_id" : "A_sku",
                    "operator" : "\u003E=",
                    "value" : "1"
                  }
                },
                "DO" : [
                  { "array_create" : {
                      "USING" : { "size" : [ "commerce-order:commerce-line-items:1:quantity" ] },
                      "PROVIDE" : { "array_added" : { "array_added_a_line_1" : "array_added_a_line_1" } }
                    }
                  },
                  { "LOOP" : {
                      "USING" : { "list" : [ "array-added-a-line-1" ] },
                      "ITEM" : { "loop_a_line_1" : "loop_a_line_1" },
                      "DO" : [
                        { "userpoints_action_grant_points" : {
                            "user" : [ "site:current-user" ],
                            "points" : "20",
                            "tid" : "0",
                            "entity" : [ "" ],
                            "operation" : "adw",
                            "display" : "1",
                            "moderate" : "approved"
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]
}
}

```

Rule for B product

```
{ "rules_b_userpoints" : {
"LABEL" : "B_userpoints",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [
  "rules_conditional",
  "rules_array_create",
  "userpoints_rules",
  "commerce_order",
  "commerce_checkout"
],
"ON" : { "commerce_checkout_complete" : [] },
"DO" : [
  { "CONDITIONAL" : [
      {
        "IF" : { "commerce_order_contains_product" : {
            "commerce_order" : [ "commerce-order:commerce-line-items:0:order" ],
            "product_id" : "B_sku",
            "operator" : "\u003E=",
            "value" : "1"
          }
        },
        "DO" : [
          { "array_create" : {
              "USING" : { "size" : [ "commerce-order:commerce-line-items:0:quantity" ] },
              "PROVIDE" : { "array_added" : { "array_added_b_line_0" : "array_added_b_line_0" } }
            }
          },
          { "LOOP" : {
              "USING" : { "list" : [ "array-added-b-line-0" ] },
              "ITEM" : { "loop_b_line_0" : "loop_b_line_0" },
              "DO" : [
                { "userpoints_action_grant_points" : {
                    "user" : [ "site:current-user" ],
                    "points" : "30",
                    "tid" : "0",
                    "entity" : [ "" ],
                    "operation" : "sdf",
                    "display" : "1",
                    "moderate" : "approved"
                  }
                }
              ]
            }
          }
        ]
      },
      { "ELSE" : [
          { "CONDITIONAL" : [
              {
                "IF" : { "commerce_order_contains_product" : {
                    "commerce_order" : [ "commerce-order:commerce-line-items:1:order" ],
                    "product_id" : "B_sku",
                    "operator" : "\u003E=",
                    "value" : "1"
                  }
                },
                "DO" : [
                  { "array_create" : {
                      "USING" : { "size" : [ "commerce-order:commerce-line-items:1:quantity" ] },
                      "PROVIDE" : { "array_added" : { "array_added_b_line_1" : "array_added_b_line_1" } }
                    }
                  },
                  { "LOOP" : {
                      "USING" : { "list" : [ "array-added-b-line-1" ] },
                      "ITEM" : { "loop_b_line_1" : "loop_b_line_1" },
                      "DO" : [
                        { "userpoints_action_grant_points" : {
                            "user" : [ "site:current-user" ],
                            "points" : "30",
                            "tid" : "0",
                            "entity" : [ "" ],
                            "operation" : "sf",
                            "display" : "1",
                            "moderate" : "approved"
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]
}
}

```

It's my debugging rules log:

```
Rule Update the order status on checkout completion fires.
        0 ms Rule Update the order status on checkout completion fires.
        0.069 ms Evaluating the action commerce_order_update_state. [edit]
        15.016 ms Rule Update the order status on checkout completion has fired.
    20.585 ms Evaluating conditions of rule A_userpoints. [edit]
    20.598 ms AND evaluated to TRUE.

    Rule A_userpoints fires.
        0 ms Rule A_userpoints fires.
        3.964 ms The condition commerce_order_contains_product evaluated to TRUE [edit]
        4.071 ms Evaluating the action array_create. [edit]
        4.146 ms Added the provided variable array_added_a_line_0 of type list [edit]
        4.293 ms Looping over the list items of array_added_a_line_0 [edit]
        5.989 ms Evaluating the action userpoints_action_grant_points. [edit]
        15.5 ms Rule A_userpoints has fired.
    36.183 ms Evaluating conditions of rule B_userpoints. [edit]
    36.197 ms AND evaluated to TRUE.

    Rule B_userpoints fires.
        0 ms Rule B_userpoints fires.
        0.88 ms The condition commerce_order_contains_product evaluated to TRUE [edit]
        0.972 ms Evaluating the action array_create. [edit]
        1.046 ms Added the provided variable array_added_b_line_0 of type list [edit]
        1.202 ms Looping over the list items of array-added-b-line-0 [edit]
        1.376 ms Evaluating the action userpoints_action_grant_points. [edit]
        4.833 ms Rule B_userpoints has fired.

```

Well, I have new information after I enabled Devil module.

When I increase quantity of first line my userpoint, it automatically add to my array 2 item and how I can assume my second rule use the same array. I think it is reason of my trouble.

Ok if I remove array module, how can I start loop via quanlity of product? Maybe anybody suggest another way for my task?

# Answer
### Problem in your current rule

I'd have to do some Rules debugging to be 100% sure, but I'm "*pretty*" sure that the core of your problem is the ***Loop*** in each of your 2 Rules. Because your rule seems to be iterating over each of your products (A and B in your sample), and for each iteration you grant those userpoints. So if you have 2 iterations (products, like A and B), you'll grant the products ***twice*** (which explains the "double" part of your question). Moreover, I bet that if you'd have a testcase with a 3rd product C, you'd tripple the user points that get granted.

### Possible solution

To get your rule to work like you want it to work, you need to "rework" your Rules Condition (for both rules) towards a ***`Rules Condition inside your Rules Loop`***, so that the user points are only granted provided the appropriate Rules Condition is satisfied.

But using a Rules Condition within Rules Actions is not possible ... you might think. Indeed ... except if you also use the Conditional Rules module (that's exactly what this module is for). As an alternative, you could create a Rules Component, with a Rules Action equivalent to the user points to be granted, and with a Rules Condition equivalent to your current Rules Condition. And then perform that Rules Component inside your Rules Loop. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".

### Rules debugging

If none of the above helps, then move on to **Rules debugging**, as explained in my answer to "How can I display the value of a variable inside a condition?".

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

If appropriate, update your question to add more details about how the Rules debugging log looks like (I might update my answer afterwards depending on what that log would show).
> 1 votes

---
Tags: 7, commerce, rules, userpoints
---


title: How do i control validateForm?

text:
# Question
Title: How do i control validateForm?
how do i control: `validateForm`

```
public function validateForm(array &$form, FormStateInterface $form_state) {
  // form validation here
  // if validation success then proceed to submit
  // else dont submit and send notification to the respective field
}

```

i have done my fields validation inside that method, however, how do i control from there?

how to stop the submit process if the validation failed? and how to send notification/error message to the respective field?

Thank you,

# Answer
```
public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);
  $values = $form_state->getValues();
  if ($values['your_field'] == 'some_forbidden_value') {
      $form_state->setErrorByName('your_field', $this->t('This value is forbidden!'));
   }
}

```

About setErrorByName().
> 5 votes

---
Tags: 8, forms
---


# Question
Title: What is the correct way to implement a custom block with twig template?
I know there are tons of posts for this but I think I have a problem with understanding how a custom block with a custom template is meant to work in Drupal 8.

## Problem

### My aim:

To place a custom block to display social icons. The block needs some logic (generate a url for example).

### My main problem:

Everything seems to work so far but I do not get the variables passed through the twig-template (url and urlencode). They always contain the default value from the module-file (null).

### What I have so far:

Files under /modules/custom/wzm\_social\_icons:

* wzm\_social\_icons.info.yml
* wzm\_social\_icons.module
* src/Plugin/Block/WzmSocialIconsBlock.php
* templates/block--wzmsocialicons.html.twig

I installed the module and also placed a custom block with id "socialicons". The block itself is just a placeholder with no special fields.

## Files

**wzm\_social\_icons.module**

```
function wzm_social_icons_theme($existing, $type, $theme, $path) {
  return array('block__wzm_social_icons' =>
    array(
      'variables' => array(
        'url' => null,
        'urlencoded' => null
      ),
      'template' => 'block--wzmsocialicons'
    )
  );
}

```

**WzmSocialIconsBlock.php**

```
class WzmSocialIconsBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $oUrl = Url::fromRoute('<current>');
    $sUrl = $oUrl->toString();
    $sUrl = \Drupal::request()->getSchemeAndHttpHost() . $sUrl;
    $sUrlEncoded = urlencode($sUrl);

    return array(
      '#url' => $sUrl,
      '#urlencoded' => $sUrlEncoded
    );
  }
}

```

Nothing special in the twig-template - just the output for {{ url }} and {{ urlencode }}.

I think my main problem is to understand what needs to be declared with which key in the module-file and if the custom-block-id is used somewhere. No clue so far.

Thanks for any help!

Cheers

# Answer
> 0 votes
You're almost there. In your `WzmSocialIconsBlock.php` return the following:

```
return array(
  '#theme' => 'block_wzm_social_icons',
  '#url' => $sUrl,
  '#urlencoded' => $sUrlEncoded,
);

```

You might also want to simplify your `hook_theme` by letting it autodetect your template by name:

```
return array('block_wzm_social_icons' =>
  array(
    'variables' => array(
      'url' => null,
      'urlencoded' => null
    ),
);

```

And name your template `templates/block-wzm-social-icons.html.twig`.

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


# Question
Title: Download file from field instead of going to node page
What I'm trying to achieve is: create a new content of type arquivo, then when accessing the new content url, instead of showing a page with the fields and etc., the file from a field\_file is opened/downloaded. Tried to achieve this using a custom template for the content type with no success. The code for the tpl.php is:

```
<?php
$items = field_get_items('node', $node, 'field_arquivo');
$filepath = $items[1]['uri'];
$path = file_create_url($filepath);
drupal_goto($path);
?>

```

Any help is appreciated

# Answer
> 3 votes
You could make a custom module and put this function in it

```
/**
 * Implements hook_node_view().
 */
function custom_tweaks_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'arquivo' && $view_mode == 'full') {
    $file = $node->field_file[$langcode][0]['uri'];
    if ($file) {
      $file_uri = file_create_url($file);
      drupal_goto($file_uri);
    }
  }
}

```

---
Tags: files
---


# Question
Title: How to generate feature containing date types and date format?
I have created new date types and date formats using Drupal 7 UI. But I can't generate feature for both of them (format and type). Only format is available in Strongarm but type isn't. Please tell me how to generate feature for both of them.

# Answer
There is another option: hardcode the date format in the preprocessor. And print it in the node you are using. In this way it is in your code base and you do not need to have it in your feature.
> 0 votes

---
Tags: 7, features
---


# Question
Title: How to resolve my Open Atrium installation error?
I am very new to open atrium. I installed Open Atrium and now the home page is not loading properly. Instead I have the following error:

> Warning: file\_put\_contents(temporary://fil29F1.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream\_open" call failed in file\_unmanaged\_save\_data() (line 1936 of C:\wamp\www\openatrium\includes\file.inc). The file could not be created.

# Answer
> 0 votes
Try this

open -\> admin/config/media/file-system

Change Temporary directory -\> sites/default/files

# Answer
> 0 votes
Another option, if this where to happen during installation, is adding,

```
$conf['file_temporary_path'] = 'sites/all/files/tmp'

```

To the `settings.php` file and making sure that the folder exists and the permissions are correct.

This is assuming that you can't use `/tmp` for some reason.

---
Tags: installation, distributions
---


# Question
Title: Form built by Ajax commands not sending values
My problem has to do with Ajax commands and the form being rebuilt after calling `ajax_command_append()`.

I have a form with two elements an option and a textfield. These are built-in with the form on page load. Then, in an Ajax callback function I add two other fields, i.e. another textfield and a text area.

The form runs and rebuilds perfectly fine, but when I try to read the values typed in or stored-from-beginning, nothing happens except that only the values for the first two fields that were originally built-in with the form are displayed.

I think the problem is either 1) I am not rebuilding the (same?) form properly, or 2) I am not calling the elements/fields properly when reading values.

Any hints will be greatly appreciated

Here is a simplified version of the test code I gathered from various examples:

```
function module_form($form, &$form_state) {
$form = array();
 $form['changethis'] = array(
 '#type' => 'select',
 '#options' => array(
  'one' => 'one',
  'two' => 'two',
  'three' => 'three',
  ),
   '#ajax' => array(
     'callback' => 'ajax_example_simplest_callback',
     'wrapper' => 'replace_textfield_div',
     'method' => 'replace',
     'effect' => 'fade',
    ),
  );
  $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t("The default value will be changed"),
    '#description' => t("Say something about why you chose") . "'" .     (!empty($form_state['values']['changethis']) ? $form_state['values']['changethis'] :     t("Not changed yet")) . "'",
    '#prefix' => '<div id="replace_textfield_div">',
    '#suffix' => '</div>',
   );
 $form['box'] = array(
   '#type' => 'markup',
   '#prefix' => '<div id="box">',
   '#suffix' => '</div>',
   '#markup' => '<h1>Initial markup for box</h1>',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'ajax_example_submit_driven_callback',
      'wrapper' => 'box',
     ),
    '#executes_submit_callback' => TRUE,
    '#value' => t('Submit'),

   );
  return $form;
}

function ajax_example_simplest_callback($form, $form_state) {

   $commands = array();

   $commands[] = ajax_command_append(NULL, '<div id=replace_textfield_div><input name=replace_textfielddd id=replace_textfielddd value=79898>test data</input></div><br>');

  $commands[] = ajax_command_append(NULL, '<br><textarea rows=4 cols=30 name=replace_textarea id=replace_textarea>Changethis value: '. $form_state['values']['changethis'] .'</textarea>');
  $page = array('#type' => 'ajax', '#commands' => $commands);

  ajax_deliver($page);

  //print ajax_render($commands);       // not helping
  //drupal_exit();

 // return $form['replace_textfield'];  // not helping
 }

function ajax_example_submit_driven_callback($form, $form_state) {
   $form_state['rebuild'] = true;  // not helping
   $element = $form['box'];
   $element['#markup'] = "Clicked submit ({$form_state['values']['op']}): " .  $form_state['values']['replace_textfield']. " - ".  $form_state['values']['replace_textfielddd'] ." -.";
   return $element;
}

```

Thanks

**EDIT**

I also tried calling this function from the inside of command: function display\_my\_form(){

```
 $form = drupal_get_form('CPR_Calculator_form');

 $form['replace_textfielddd'] = array(
    '#type' => 'textfield',
    '#title' => t("bye"),
    '#description' => t("ummm"),
    '#prefix' => '<div id="replace_textfield_divvv">',
    '#suffix' => '</div>',
  );
  $display = '<div id="replace_textfield_divvv">';
  $display .= render($form);
  $display .= '</div>';

  return $display;
}

```

and then in the callback I replaced the ajax\_command\_append() with this line:

```
$commands[] = ajax_command_replace(NULL, display_my_form());

```

# Answer
You need to build conditional elements in the form definition (`mymodule_form`) and not in the ajax callback. When the form is rebuilt using ajax, `$form_state['values']` will be set, whereas it's not set on the initial form build.

Here is an example:

```
function mymodule_form($form, &$form_state)
{
  if(isset($form_state['values'])
  {
    // put your conditional form elements here
  }
}

```
> 1 votes

# Answer
Drupal will ignore any form data from elements not created with Form API, so you cannot expect elements created like this to work:

```
$commands[] = ajax_command_append(NULL, '<br><textarea rows=4 cols=30 name=replace_textarea id=replace_textarea>Changethis value: '. $form_state['values']['changethis'] .'</textarea>');

```

You should create element using `$form` array instead, and then use callback function to return changed area of your form. See Form API example in Examples for Developers for correct way.
> 0 votes

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


# Question
Title: Loading a library only for the front page
I want to load JavaScript only on the home page of my site. I found this preprocess function but I don't know how to customize it for the home page:

```
function mytheme_preprocess_maintenance_page(&$variables) {
  $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
}

```

I was originally including the library I needed in every page of my site, but I only need it on the home page, so I need to figure this out.

Originally I had it in the .info.yml file like so:

```
libraries:
 - 'themename/library'

```

Any help is appreciated.

# Answer
> 9 votes
```
function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') {
        $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
    }
}

```

# Answer
> 8 votes
The other workaround would be using the method from drupal's path matcher interface which returns true if the current page is the front page.

```
function themename_preprocess_page(&$variables) {

//using the method from the pathmatcherinterface
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $variables['#attached']['library'][] = 'themename/cuddly-slider';
  }
}

```

---
Tags: 8, javascript
---


# Question
Title: What could stop a component appearing on the front end?
I'm new to Drupal and have been given a task beyond my knowledge.

I am trying to transfer a component (simple image gallery) from one site to another. I've simply copied the component files (.tpl, .module, .inc) into the new site's equivalent directories.

The back-end appears fine: I can add the component to a Panel and adjust its settings. I've replicated exactly what was on the previous site. But nothing appears on the front end.

I've tried clearing the cache and rebuilding the registry, of course.

Would anyone know what file/function I should be looking at to get this working?

# Answer
> 0 votes
In this instance it was an error in the component's render function

```
gallery_grid_render($subtype, $conf, $args, $contexts) {

```

where it was returning the information to the block.

```
$block->content = theme('this_name_was_wrong', $tpl_vars);

```

---
Tags: 7
---


# Question
Title: How to Schedule a node "Promoted to front page"?
I am looking for a way to schedule "Promoted To home page" nodes to appear after a particular time.

When user creates a new node and checks "Promoted To home page", it should not appear immediately on publish on the homepage.

Then need a scheduler which set "Promoted To home page" nodes to appear on front page.

The node will published and visible if accessed directly or seen in other section.

# Answer
You can do this using the Rules module in combination with the "Rules Scheduler" (a submodule of it). After you enable these 2 modules, create a Rules Component and a Rule. Here is a blueprint of doing so:

* Create a Rules Component which accepts "node" as a parameter, and which has a Rules Action to set the node to "published".
* Create a Rule like so:
    + Rules Event: Before saving a new node.
    + Rules Actions: (1) set the node to "unpublished" (to be sure it is not "published" when the node is saved) and (2) schedule the Rules Component created in the previous step.

**Note**: From the comment below this answer (which states "*The node will remain Published all the time.*") it doesn't seem to apply for the question here, but using a similar approach you could also schedule another Rules Component to mark it unpublished again later on, eg X days after the node gets published. In that case, you use Rules Event "After updating an existing node", combined with a Rules Condition to check if the update changed "unpublished" to "published".
> 0 votes

---
Tags: 7
---


title: I can't insert images to articles

text:
# Question
Title: I can't insert images to articles
I installed Drupal 8 today, the release candidate 3. I had not done any modifications to it. When I edit my first article, I can't insert images. I clicked on the image button, but it keeps loading forever. I saw other people clicking the image button and a pop-up appearing.

Do I have to install a module?

# Answer
**My solution was simple: After updating Drupal8, ensure you run any pending scripts!** Otherwise you will not be able to do certain things with your Drupal8 site. Yesterday I updated my Drupal from some ancient version to the latest stable Drupal8. I noticed I can't add images \[the forever loading problem\], and I'm just a home user not behind a fancy firewall. After updating 13 pending scripts, everything was fine. I'm not a very technical person, but I wanted to share my solution because no one else had shared this. My website is ontu.org and thus the settings page for me was here: http://ontu.org/admin/reports/status

Change that URL to your site and you'll quickly go to your settings page. There may be multiple issues reported on that page, so notice everything on there.
> 1 votes

# Answer
There have been a number of bugs fixed with dialogs in general and the Text Editor dialogs in particular during the RC phase of Drupal 8. It's definitely been working fine ever since Drupal 8.0.0.
> 0 votes

# Answer
Be sure your firewall doesn't filter too many HTTP response header lines. They are used to validate the Ajax response.

```
X-Drupal-Ajax-Token: 1

```

etc.

It's a known bug: https://www.drupal.org/node/2580191
> 0 votes

---
Tags: media, 8
---


# Question
Title: Redirect after login through different login form
I try redirect user to specific tab on user profile page. I found couple solution how I can do that but it doesn't work if I use login form modules like Super Login, Bootstrap login form, fancy login, etc. When I try redirect user via trigger It give me AJAX error.

Then I try use Rules module and it doesn't redirect after login at all. All of it works fine if I login through standard login form.

I spent 2 days for this issue and can't find any solution. Please give me right way how to do that.

I use Bootstrap login module

link to my tab: user/\[account:uid\]/mytab

This is my rule:

```
    { "rules_red" : {
"LABEL" : "redirect",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "user_login" : [] },
"DO" : [ { "redirect" : { "url" : "user\/[account:uid]\/mytab" } } ]
 }
}

```

# Answer
I found out how to solve this issue. I install popup module and activate popup block submodule. then go to block and set "User login" block in "Navigation" region (I use bootstrap theme), after that open configuration of "User login" module and do it popup. I hope it will usefull for anybody.
> 0 votes

# Answer
You can alter the form in custom module and alter its submit hook , so after submission it will redirect to your desired destination
> 0 votes

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


# Question
Title: Difference between drupal_static and \Drupal::state?
Imagine I have a hard-to-compute value.

```
$my_heavy_value = compute_heavy_value();

```

What's the difference, at performance level, between storing the computed value using `drupal_static()` and using `\Drupal::state()`?

Which one is stored in the database? Is there one that is stored in memory?

# Answer
They perform different tasks.

`drupal_static()` only stores data for the current page load (or ajax load). For example, if you are loading something from a database table multiple times on a single page load (ie - a user account), the first time it is loaded it is saved to memory, and the next time it is needed, it is pulled from memory, rather than reloading it from the database, saving that second database query.

`Drupal::state()` saves data to the database, where it can be recovered in future requests. It's a cache of sorts.

You can actually use them in conjunction with each other as follows:

```
function get_some_value() {
  // Instatiate the static
  $value = &drupal_static(__FUNCTION__);
  // Check if the value has already been set in this page load
  if(is_null($value)) {
    // The value has not yet been set for this page load,
    // so retrieve it from the state if it exists, and if it
    // does, then save that to the static
    $value = \Drupal::state()->get('my_value');
    // Check if the value was retrieved from the state
    if(!$value) {
      // The value was not retrieved from the state, so
      // it needs to be generated. Below is an example
      // fetching it from the database
      $value = db_query('SELECT some_value FROM {some_table} WHERE some_column = :some_value', [':some_value' => 'some value'])->fetchField();

      // Save it to the state for future page loads
      \Drupal::state->set('my_value', $value);
    }
  }

  // Return the value
  return $value;
}

```

With the above code, the first time this function is hit, it will first check if the value exists in the static cache (this page load), and when it doesn't, it attempts to retrieve it from the state cache, and when it doesn't it finally generates it with a database query, saving it both to the static cache, as well as the state.

If it hits this function again on the same page load, the value will be in the static cache, so none of the internal code is needed, and the value is returned from the static cache.

On a future page load, the first time this function is hit, nothing is retrieved from the static cache, so it will pull it from the state cache. If the function is hit again on that page load, the value will be in the static cache and returned from that.

-- Edit from comments --

Note that if you use `Drupal::state` as cache, you will then need to manage expiration on your own. If you nee in-memory caching, use the drupal\_static cache. If you need a persistent cache, it is likely better to use `\Drupal::cache` than to use `Drupal::state`.
> 13 votes

# Answer
`drupal_static()` is used to cache data within a single page request. it stores the data in a static variable.
The class returned by `\Drupal::state()` handles values that need to be preserved between requests. As such, it is probable it stores its values in a database table. (It depends from the exact implementation done from that class.)

`drupal_static()` is faster since it saves its values in the memory, but using states doesn't make a lot of difference.

As for recommending one, both are recommended. It's up to you using the one that suits your needs. Do you need a cross-request value, or a value you use only in one request?

If you are looking to replace `drupal_static()` with OOP code, Drupal 8.6 introduced the `MemoryCache` class, that stores cache items in memory using a PHP array. It has been added to allow classes that would previously maintain state on a protected property (as a static cache to avoid persistent cache or database lookups) to inject a service to hold that state instead. (See Added memory cache.)
Notice that the class isn't used directly. The module needing it should define a new service, similarly to what Drupal core does with the *entity.memory\_cache* service.

```
entity.memory_cache:
  class: Drupal\Core\Cache\MemoryCache\MemoryCache

```
> 8 votes

# Answer
When you want to store hard to compute data in memory you use a static variable. But to store this data in the database the State API is not the right place, despite the similar name:

> The State API provides a place for developers to store information about the system's state.

A system state is for example the last time cron has run. So the State API `\Drupal::state` has nothing to do with caching at all.

Use the Cache API `Drupal::cache()` instead.

Example how to store data in cache:

```
\Drupal::cache('data')->set($cid, $data, Cache::PERMANENT, ['heavy:' . $heavy_id]);

```

`$cid` is a unique cache key, which is used to retrieve the data from cache:

```
$data = \Drupal::cache('data')->get($cid);

```

You can use the cache tag you've set above as fourth parameter to invalidate the cache entry if it becomes outdated:

```
\Drupal\Core\Cache\Cache::invalidateTags(['heavy:1']);

```
> 6 votes

---
Tags: 8, performance
---


# Question
Title: What's the difference between creating a 'Content' or a new 'Pages>>Add Custom Page'?
I'm working on a pre-established site. I've noticed that I can add new 'Content' (Content\>\>Add Content) or I can add a new Page (Structure\>\>Pages\>\>Add custom page).

The site seems to use an indiscriminate amount of both, though Content seems to be used more with templates for blog and product pages.

What are the differences between the two and in what scenarios should I use them?

# Answer
Structure -\> Pages menu link comes from ctools and it allows you to create more complex pages than your basic drupal core ones (Content -\> Add Content link). This may include components comming from other modules (Panels, Fieldable Panel Panes, Views Content Panes and many other that intergrate with Ctools).

With Page Manager (and panels in general) you can create more complex versions of a page (or more, if you use the right contexts).
> 1 votes

---
Tags: 7
---