# Question
Title: How to list nodes posted in current month?
I try to list nodes posted in current month, with Views.

I tried to add a Contextual filter: `Created: month`, but no node appears.

I tried a Filter criteria: `Content: post date / Is equal to / An offset ... / "-1 month"`, but no node appears.

Do you know how can it be done?

# Answer
> 5 votes
Add a filter criteria **Content: Post date** and select **Is greater than or equal to**, value type **An offset from current time** and value **-1 month**.

Screenshots:

---
Tags: 7, views, datetime
---


title: How to create a empty module?

text:
# Question
Title: How to create a empty module?
What is the most basic valid module one can create in Drupal?

It would be useful to have a simple blueprint available, for anyone just getting started with Drupal.

# Answer
> 26 votes
The below instructions allows one to create an empty module, and is helpful for anyone just getting started with module building. If you have troubles getting your first module working, or even showing up in Drupal, ensure you've read all the instructions below.

# Drupal 8

A `project` must at least have

1. A machine name.
2. An yaml info file named after the machine name, in the form `module-machine-name.info.yml` with the following attributes:
    1. `name:` A humanly readable name
    2. `type:` A type, defining to be a `module`.
    3. `core:` The major Drupal core version the module is compatible with, `8.x`, in this case.
3. An empty module file, name in the form `module-machine-name.module`

Drupal looks for modules in these locations, as seen from the web root:

1. `/modules/`
2. `sites/[example.com]/modules`
3. `sites/default/modules`
4. `profiles/[install-profile]/modules`

Technically, Drupal also looks for modules in `core/modules`, but one should *never*, place modules there, hence it's not on the list above.

An example module structure, for a module with the machine name `helloworld`, would look like this:

`/modules/helloworld/helloworld.info.yml`

`/modules/helloworld/helloworld.module`

Notice that both the info and module file as named exactly the same as the machine name, which is important.

The module file may be empty, but the info file must contain a few minimum values for Drupal to recognize it as a module. For our helloworld module, that could look like:

```
name: 'Hello world module to demonstrate module building'
core: 8.x
type: module

```

If you follow the above instructions, you should be be able to get a new module listed in your Drupal site, although it won't do anything, at this stage.

# Drupal 7

A module must at least have

1. A machine name.
2. A humanly readable name
3. An info file named after the machine name.
4. An empty module file.

To be loadable by Drupal, it must also define which core version it is compatible with.

Further Drupal looks for modules in these locations:

1. `sites/all/modules/`
2. `sites/[example.com]/modules`
3. `sites/default/modules`
4. `profiles/[install-profile]/modules`

Technically, Drupal also looks for modules in `modules`, but one should *never*, place modules there, hence it's not on the list.

An example module structure, for a module with the machine name `helloworld`, would look like this:

`sites/all/modules/helloworld/helloworld.info`

`sites/all/modules/helloworld/helloworld.module`

Notice that both the info and module file as named exactly the same as the machine name, which is important.

The module file may be empty, but the info file must contain the humanly readable name of the module, and the core version the module is compatible with.

For our helloworld module, that could look like:

```
name = Hello world module to demonstrate module building
core = 7.x

```

If you follow the above instructions, you should be be able to get a new module listed in your Drupal site, although it won't do anything, at this stage.

# Answer
> 8 votes
For Drupal 8, since the question mentioned a blueprint, I figure I'd mention the Drupal Console project.

Once that is installed, one can generate module code (and other things like scaffolding for custom entities, plugins, etc).

To generate a basic module from the command line: `drupal generate:module`. One is then prompted through some basic information gathering, and left with the module files at the end:

---
Tags: 8
---


# Question
Title: Which user does the Rules module execute as?
I've set up a rule which is triggered by "after saving a new user account". This rule simply sends an e-mail. The e-mail contains various tokens, one of them is the field `[account:field_country]`.

I've enabled "custom permission" for this field, and through the Field Permissions module I've configured the following permissions :

All users (selected permissions):

* `Create own value for field Country`
* `View own value for field country`.

Moderators (all permissions) :

* `Create own value for field Country`
* `Edit own value for field Country`.
* `Edit anyone's value for field country`.
* `View own value for field Country`.
* `View anyone's value for field Country`.

The problem is : the `[account:field_country]` gets replaced with an empty string when the rule sends the e-mail. Only when I let all users `View anyone's value for field Country` does the rule properly replace the token with the actually selected country value.

Why do I need to do this? Which user does the rule module run as since the rule apparently need to `View anyone's value for field Country` to be able to get the value for that field.

# Answer
And here is a module that could assist:

Rules switch user

> This module adds two new Rules actions:
>
> * Switch to another user
> * Switch back from another user
>
> These actions could be useful when you have an operation that you want an unprivileged user to use but it fails because the user doesn't have sufficient permissions.

Create a fictitious user with sufficient permissions and switch to this user when performing the Rules action and switch back again when done.

**EDIT** This answer is just a workaround and does not speak to the question directly, namely why the current permissions doled out are not allowing the Rule to execute successfully.
> 1 votes

# Answer
IMO your "issue" (that the value of your field is blank) is because of the event (= "*after saving a new user account*") you are using, which might simply not be the right event. If this user is still "blocked" (= in case your registration procedure requires admin approval), it could make sense for the Rules module to not show the content of this field yet.

Moreover, have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how Rules works ...).

A possible compromise to avoid these kind of issues, is to transform sending your eMail into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the new user account is for sure saved ... (so that can't be the reason anymore then why that field would still be blank ...).

Using this Rules Component approach, you might even take into consideration that you only want to have this eMail send if the user account is "no longer blocked" (if it is still blocked, add some extra Rules logic to reschedule the same component to re-execute somewhere later on).

And by the way: anything about Rules that uses the Rules Scheduler, runs for sure with "Anonymous" authorizations. There are cases (Rules Actions) for which that auth is insufficient of course (eg: create a new nod is not allowed by Anonymous). Even for these cases there is a way to resolve that also (if you want to know how to do that: post a followup question about it).
> 1 votes

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


# Question
Title: Get array length of a multiple fields of a node content type
I'm developing a site with Drupal 8. I made a custom content type, with a lot of fields; in particular I have a field called `field_categoria_del_libro_presen` that is linked to a taxonomy term. It's possible to specify more than one value. I used `kint()` to obtain the structure of the node. Here:

```
field_categoria_del_libro_presen
→array(2) target_id
  1
    "1"
  2
    "4"

```

how can I get the length of the array?

# Answer
Confirmed that as suggested in the comments, the following works quite well:

```
count($node->field_categoria_del_libro_presen);

```

Here the count would be `2` (based on the example in the question).

This works because even though the `field_categoria_del_libro_presen` property on the node object is a `EntityReferenceFieldItemList`, it implements (by way of implementing `ListInterface`) the native PHP `\Countable` interface.
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: Commerce - access denied on checkout page
When I tried to access the checkout page I get "Access denied"; this happens with every role, all of which have permission to view the cart/make orders/view orders.

This happens even with a complete fresh install of Commerce Kickstart. There must be something going on with the server configuration? All other admin and user functions work without any issue. I am using HHVM instead of standard PHP, but surely I am not the first one to attempt to run Drupal Commerce on HHVM. I can find no trace of this issue elsewhere except someone with the same question 6 months ago that was unresolved.

Any idea what's going on here?

# Answer
> 2 votes
I found out that there is a difference between how Zend and HHVM interprete the php key() function.

In the Drupal commerce\_checkout module there is a function that returns the first key of an array by using the php key() function (commerce\_checkout.module, line 480).

```
/**
 * Returns the page ID of the first checkout page sorted by weight.
 */
function commerce_checkout_first_checkout_page() {
  return key(commerce_checkout_pages());
}

```

On the default Zend rendering engine this returned the desired result of the first array key. But in HHVM this returned nothing. I believe this is because the pointers of the array were not flushed by HHVM (maybe for performance reasons), and they were flushed in the Zend engine.

I don't think it was a good idea of the creaters of this module to use the key() function to get the first key of the array anyway

I now rewrote this function to this:

```
/**
 * Returns the page ID of the first checkout page sorted by weight.
 */
function commerce_checkout_first_checkout_page() {
 return reset(array_keys(commerce_checkout_pages()));
}

```

Getting the keys of the array first and then with reset() rewind the array's internal pointer to the first element and return the value of that first array element. Of course the key() function did the job on the standard Zend engine, but for HHVM this didn't.

I will report this issue to the maintenance crew of the drupal commerce module, and hopefully it will be commited into the next release. I don't think there is anything wrong with the way HHVM interprets the key function (if I am right in thinking this is the root of the problem). I think the key() function just shouldn't be used like this in this situation.

# Answer
> 0 votes
In function commerce\_checkout\_page\_access it calls

```
$first_page = key($checkout_pages);

```

And exactly as wannesderoy has pointed out, it will not return desired result and causes access denied error on HHVM.

---
Tags: commerce, users
---


# Question
Title: Matrix view with content as columns and taxonomy terms as rows
I need to build a view in a matrix format. I have a content type `mycontent` and a taxonomy vocabulary `myvocabulary`. The content type has a term reference field in it, which refers to the vocabulary and can have multiple values.

**I want to list all contents in a view as columns, and all terms in the vocabulary as a table header, i.e. columns.** I want to put a check mark to the corresponding field in the table according to the terms that the content has.

An illustration of what I want to achieve:

```
+-----------+--------+--------+--------+--------+-----
|           | Term 1 | Term 2 | Term 3 | Term 4 | ...
+-----------+--------+--------+--------+--------+-----
| Content 1 |   x    |   x    |        |   x    |
+-----------+--------+--------+--------+--------+-----
| Content 2 |        |        |        |   x    |
+-----------+--------+--------+--------+--------+-----
| Content 3 |   x    |        |   x    |        |
+-----------+--------+--------+--------+--------+-----
| Content 4 |   x    |    x   |        |        |
+-----------+--------+--------+--------+--------+-----
|    ...    |        |        |        |        |

```

**So, my challenge is to dynamically create a column for each taxonomy term in the vocabulary.** I.e. if I add a new taxonomy term, the view should have this column automatically added to the table.

With the default table display I can list the nodes as rows, but it is not possible to make a column for each term in the vocabulary.

I have found 3 different modules which seem to related to my problem:

None of those modules have a stable version for Drupal 7, nor they have a good documentation, if any at all.

I am going to download and install the dev versions of each module and play around. However, before I do that I wanted to ask if anyone has done such a view and if there would be another better approach to achieve such a matrix view.

Other suggestions that doesn't include using Views are also welcome.

# Answer
It can be achieved with the help of hook\_views\_pre\_view() and the Views field template file.

## Create a View

Create a view showing content in `table` format and add two fields:

**Content: Title (Title)**

The title will populate each row of the first column.

**Content: All taxonomy terms (All taxonomy terms)**

select: `Exclude this field from display`

select: `Limit terms by vocabulary` and tick the vocabulary you want to use.

## Your module file

Create a column for each term and populate all the fields with the value from the field `Content: All taxonomy terms (All taxonomy terms)` Then we'll be able to check if a comma-separated list of terms contains the term of the current column.

```
/**
 * Implements HOOK_views_pre_view().
 *
 * Adds a field to the "YOUR VIEW NAME" view.
 */
function YOURMODULE_views_pre_view(&$view) {

  if ($view->name == 'YOUR_VIEW_NAME') {
    // the vocabularies defined in the view.
    $vocabularies = array_filter($view->display['default']->handler->options['fields']['term_node_tid']['vocabularies']);
    $terms = YOURMODULE_terms($vocabularies);
    $count = count($terms);
    for ($i=0;$i<$count;$i++) {
      // define the field id.
      $view->display['default']->handler->options['fields']['tid_' . $i]['id'] = 'tid_' . $i;

      // define the table (it has to be the same table for all fields)
      // if you aren't sure what the table name should be, uncomment the line below and take a look at the first field data.
      // debug($view->display['default']->handler->options['fields'], 'VIEW FIELDS', TRUE);
      $view->display['default']->handler->options['fields']['tid_' . $i]['table'] = 'node';

      // here we need to define our custom field output
      // the field "Content: All taxonomy terms (All taxonomy terms)" has a mashine name 'term_node_tid'
      // this field need to be excluded from display because we do not want to display one column only.
      // Instead we will use the data to populate all our custom fields, then we'll be able to define the output for each of them.
      $view->display['default']->handler->options['fields']['tid_' . $i]['field'] = 'term_node_tid';

      // define the field label
      $view->display['default']->handler->options['fields']['tid_' . $i]['label'] = $terms[$i];

      // we need only term names, not links.
      $view->display['default']->handler->options['fields']['tid_' . $i]['link_to_taxonomy'] = 0;
    }
  }
}

```

A helper function that returns an array of terms. This function will be used twice. First time in `hook_views_pre_view()` where the argument is available from the View. Second time in `YOURMODULE_has_term()` where the argument would be hardly to get. That's why I decided to use a static variable here.

```
/**
 * Helper function that returns an array of terms.
 *
 * @return array
 *   An array of terms from all vocabularies (defined in the view).
 */
function YOURMODULE_terms($vocabularies = NULL) {
  $terms = &drupal_static(__FUNCTION__);
  if (!isset($terms)) {
    $terms = array();
    foreach ($vocabularies as $key => $vocabulary) {
      $vid = taxonomy_vocabulary_machine_name_load($vocabulary)->vid;
      $taxonomy_tree = taxonomy_get_tree($vid);
      foreach ($taxonomy_tree as $term) {
        $terms[] = $term->name;
      }
    }
  }
  return $terms;
}

```

A helper function to determine if a field value (comma-separated list of terms) contains the term of current column. This function will be used in a Views field template file.

```
/**
 * Determines if a comma-seperated list of terms contains the term of the
 * current column.
 *
 * @param $field_alias string
 *   The field alias corresponding to the $field->field_alias value in the view.
 * @param $field_position integer
 *   The column corresponding to the $field->position value in the view.
 * @param $output string
 *   Comma seperated list of terms.
 * @return 'X' if TRUE or bool if FALSE.
 */
function YOURMODULE_has_term($field_alias, $field_position, $output) {

  // because we are using two fields to provide the data
  // we need to skip two positions to get appropriate term keys.
  $field_position = ($field_position > 1) ? $field_position-2 : $field_position;

  // because this is a second call for this function,
  // we don't need to define vocabularies as an argument.
  $terms = testmodule_terms();

  // each column has their own term name.
  $term_name = $terms[$field_position];

  // first column fields.
  if ($field_alias == 'node_title') {
    return $output;
  }

  // the fields in all terms columns.
  else {

    // explode terms and trim whitespaces.
    $term_names = array_map('trim',explode(",",$output));

    // check the term names array contains the term of the current column.
    if (in_array($term_name, $term_names)) {
      return 'X'; // check mark
    }
    return FALSE;
  }
}

```

## Views field template file

Create a View template file `views-view-field--[YOUR-VIEW-NAME].tpl.php` and place in your templates folder.

```
<?php
// We're assuming that this view only has two fields (Content: Title)
// and  Content: All taxonomy terms (All taxonomy terms).
// All other fields are generated by the HOOK_views_pre_view() function in the
// `YOURMODULE.module` and those should be passed through the
// `YOURMODULE_has_term` function which determines if the $output
// (comma-seperated terms) contains the column term name.
print YOURMODULE_has_term($field->field_alias, $field->position, $output);
?>

```

---

I was able to answer this question thanks to a similar post here and added lots of comments to the code. Hope it helps.
> 6 votes

# Answer
I solved this issue using Views Matrix module. Although, as I stated in my question, it has only a dev version, it is working without problems.

> Views matrix provides a matrix style plugin for Views. This overrides pager settings to display items grouped by a row and column header field. Row items that match a row and column value are grouped into the same cell.

The steps how I did it:

1. Create a view showing content in **Matrix** format, which is provided by **Views Matrix** module.
2. Add the *Relationship* to the taxonomy term **Content: *Term reference field (field\_my\_term\_reference)***
3. Add fields **Taxonomy term: Name** and **Content: Title** and exclude them from display, they are for the table headers.
4. Add more fields to display in table content, or a **Global: Custom text** field for just showing an "X" or a check-sign or whatever else..
5. Under **Format** -\> **Settings**, select for column header **Content: *Term reference field*** and for row header **Content: Title**
> 0 votes

---
Tags: 7, views
---


# Question
Title: Automatic Nodetitles IF php statement in between other tokens in title
I have an automatically generated title of an address with an if empty statement in the middle of the other tokens:

```
[node:field_street], [node:field_number],
<?php
$floor= '[node:field_floor]';
$ground = '[node:field_ground_floor]';
if (empty($floor)) { return $ground; }
else
{ return ' Floor '.$floor; };
?>,
[node:field_location_address:postal_code], [node:field_location_address:city]

```

but the token after the php statement is not displayed. If I put the php statement at the end after all other tokens, everything is displayed. What am I doing wrong?

# Answer
> 2 votes
I tried your snippet and could reproduce the problem. What worked for me was printing/echoing instead of returning.

My code that reproduced the error:

```
[current-user:name]
,
<?php
$floor= '[node:nid]';
$ground = '[node:created]';
if (empty($floor)) { return $ground; }
else { return " Floor floor"; }
?>,
[current-page:url]

```

produced the title "admin, Floor 228".

My updated code (echo instead of return) worked:

```
[current-user:name]
,
<?php
$floor= '[node:nid]';
$ground = '[node:created]';
if (empty($floor)) { echo $ground; }
else { echo " Floor $floor"; }
?>,
[current-page:url]

```

and produced the title "admin, Floor 228,http://localhost/drupal/node/228/edit"

Verdict: I believe this is expected behaviour following from the use of return; it exits the current code block, and therefore the rest of the code is never executed.

Hope this helps!

---
Tags: tokens, nodes
---


# Question
Title: Change entity.field.FieldFormatter for a custom view
For an Product entity I’m added custom field "images" // it contains all product images.

To display these images, CustomFieldFormatter is used, it is specified/set on the entity type "manage display" settings page. So each time the entity is rendered, it uses that CustomFieldFormatter, which display grid of images, with on hover and other effects.

But now I want to create a view to display grid of products (catalog page) and display only one (first) image of each product entity.

Please, help me find a way to change FieldFormatter for my field when it is shown inside "catalog" view. Or maybe there is some better architecture/solution?

# Answer
> 0 votes
The correct way to implement this, is to use "Display modes": add custom "Display mode" for entity, and set the another formatter for images field. In the View settings set it to use that "Display mode" to display entity.

---
Tags: theming, 8
---


title: How to add a 'flag link' in an email?

text:
# Question
Title: How to add a 'flag link' in an email?
I want to add a 'flag link' in an email. I have an event content type, and every time a new event created, the users get an HTML Email. I have a flag that the users can flag this event if they want to attend. I want to embed the flag link in the email, so that the users click the link and redirected to the flag confirmation page.

I've tried that with `flag_create_link()` in the email-template but it has two problems that makes it unusable in an email. First, I'm getting 'Bad token' error if click the link in the Email. Second, the URL generated is a relative URL, so I had to manually change the URL in browser to test, which got me to the first problem.

Is there any proper way to embed a flag link in an Email? So that, the user can click and directed to the confirmation page of the flagging, or login page if he's not already logged in.

UPDATE:

I've changed the link type to 'confirmation form' and that solved the first problem. I'm not getting 'Bad token' error anymore. However, the link path is still relative.

# Answer
> 0 votes
With the following code I managed to create the flag link to embed in the email body:

```
global $base_url;
$flag_url = $base_url . base_path() . 'flag/confirm/flag/my_flag/' . $nid;

```

# Answer
> -3 votes
You can try to strip any tags getting in your way:

```
strip_tags ( string $str [, string $allowable_tags ] )

```

https://www.php.net/strip\_tags

---
Tags: emails, flags
---


# Question
Title: How to get only parent term ids of a given term, without loading the terms
I want to find all parent ids of a given taxonomy term id recursively, without loading them. Existing taxonomy functions like `taxonomy_get_parents_all()` and `taxonomy_get_parents()` are loading the terms.

Since I will be using this result in an API function, it is important for me to get the parents with a minimum performance overhead. All I need to get the parents in a simple array like: `$parents = array(6, 3, 2);`

# Answer
Have a look at taxonomy\_get\_parents() and taxonomy\_get\_parents\_all().

You could copy most of the functions but skip

```
$parents[$tid] = taxonomy_term_load_multiple($tids);

```

to not load the terms.

```
/**
 * Load a terms parent.
 */
function MODULE_taxonomy_get_parents($tid) {
  $parents = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($parents[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.tid', $tid);
    $query->addTag('term_access');
    $query->orderBy('t.weight');
    $query->orderBy('t.name');
    // $tids = $query->execute()->fetchCol();
    // $parents[$tid] = taxonomy_term_load_multiple($tids);
    $tids = $query->execute()->fetchAll();
    $parents[$tid] =  $tids;
  }

  return isset($parents[$tid]) ? $parents[$tid] : array();
}

/**
 * Load all parents for a term.
 */
function MODULE_taxonomy_get_parents_all($tid) {
  $cache = &drupal_static(__FUNCTION__, array());

  if (isset($cache[$tid])) {
    return $cache[$tid];
  }

  $parents = array();
  if ($term = taxonomy_term_load($tid)) {
    $parents[] = $term;
    $n = 0;
    // while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
    while ($parent = MODULE_taxonomy_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }

  $cache[$tid] = $parents;

  return $parents;
}

```

If you don't need any access control or sorting you can just query the `taxonomy_term_hierarchy` table directly.

```
$query = db_select('taxonomy_term_hierarchy', 'h');
$query->addField('h', 'parent', tid);
$query->condition('tid', $tid);
$query->condition('parent', 0, '!=');
$tids = $query->execute()->fetchAll();
$parents[$tid] =  $tids;

```
> 2 votes

# Answer
I managed to achieve that as follows:

```
function MYMODULE_taxonomy_get_parents($tid) {
  $taxonomy_hierarchy = db_query('SELECT tid, parent FROM {taxonomy_term_hierarchy}
                                  WHERE parent != 0')
                        ->fetchAllKeyed();
  $parent_tids = array();

  while (!empty($taxonomy_hierarchy[$tid])) {
    $tid = $taxonomy_hierarchy[$tid];
    $parent_tids[] = $tid;
  }

  return $parent_tids;
}

```

I have also added some static caching, but for the brevity I didn't include it in this answer.
> 1 votes

---
Tags: taxonomy-terms
---


title: How to update SOLR document?

text:
# Question
Title: How to update SOLR document?
This question is related to https://drupal.stackexchange.com/questions/193603/solr-views-flag-newly-flagged-users-do-not-appear-in-search-results

Because previous question can be difficult to understand I'm trying to simplify things.

If I understand SOLR - Drupal integration well, every entity is represents as Document in SOLR.

How to invoke update of document for specified entity?

List of modules that I'm using for search page (a View)

```
dependencies[] = date_facets
dependencies[] = facetapi
dependencies[] = facetapi_bonus
dependencies[] = search_api
dependencies[] = search_api_facetapi
dependencies[] = search_api_location_views
dependencies[] = search_api_solr

```

I need to update SOLR document when user flag another user (Flag module).

# Answer
> 0 votes
If you're writing code:

```
search_api_track_item_change('entity_type', array($entity_id));

```

That will mark an entity as 'dirty', and it'll be (re-)indexed on the next run.

If you're not writing code, install the rules module, add a rule with an event of "A *flag type* has been flagged...", and an action of type "Index an entity", with the relevant parameters.

---
Tags: 7, entities, search
---


# Question
Title: Is it possible to add form elements to the existing fields with Field API?
Is it possible solved with field api this task? I need to add new elements to an existing field. For example there is a field image. I create a widget and add a checkbox

```
/**
 * Implements hook_field_widget_form().
 */
function mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $elements = image_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);
  foreach (element_children($elements) as $delta) {

    $elements[$delta]['#process'][] = 'custom_widget_process';

  }
  return $elements;

function custom_widget_process($element, &$form_state, $form) {
  $element['myelement'] = array(
    '#type' => 'checkbox',
    '#title' => t('My checkbox.'),
  );
  return $element;
}

```

How do I save the value of the checkbox? (If I have a table for it)

Can I add additional column into an existing image field scheme? (hook\_field\_schema\_alter - not exist)

# Answer
> 0 votes
File Entity module allows you to add extra fields to file fields.

> File entity provides interfaces for managing files. It also extends the core file entity, allowing files to be fieldable, grouped into types, viewed (using display modes) and formatted using field formatters.

---
Tags: entities
---


# Question
Title: How can I let images uploaded via ckeditor show their full url in a json request via REST?
I have textarea fields in my headless drupal 8 site. When I get the node via REST in json it does not give the domain name in the image urls that are uploaded via ckeditor. So the images are not shown when I display this field.

# Answer
You can relatively easily fix the images on the client using jQuery by following Correct Img Src Path with Javascript and Jquery.
> 1 votes

# Answer
`CKEditor` uses relative urls and that's right, because if service URL changes for some reason urls must not be hardcoded, otherwise image urls will become invalid.

You can impement hook\_entity\_load() and edit your field's value using regular expression.

UPDATE:

To prevent hardcoding of website's url, you can use $base\_url global in `hook_entity_load`.
> 0 votes

---
Tags: wysiwyg, 8
---


# Question
Title: Views and CSS : how to exclude the exposed filters from CSS?
I'm using CSS to make a masonry effect in Views. And it works, but... The exposed filters and the pager get "caught" in the masonry effect instead of being on top (and bottom) of the results.

Question : how to set the CSS so that the exposed filters and the pager stay out of the results.

Thanks!

ps.: I know about Masonry views, but I prefer CSS.

The CSS:

In Views "Other" : CSS Class

```
.brick-user {
    margin: 1.5em 0;
    padding: 0;
    -moz-column-gap: 10px;
    -webkit-column-gap: 10px;
    column-gap: 3em;
    font-size: .85em;
}

```

Settins : Row class

```
.brique-user-item {
    display: inline-block;
    background: #fff;
    border: 1px solid lightgrey;
    padding: 15px;
    margin: 0 0 1.5em;
    text-align: center;
    width: 100%;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;

}

```

# Answer
You could use the "Exposed form in block" setting under Advanced settings to get the exposed filter out of the masonry markup and put it a region above or beneath your masonry view.
> 0 votes

---
Tags: views, theming
---


title: How to use drush with proxy

text:
# Question
Title: How to use drush with proxy
I am using Acquia Dev Desktop 2 for my Drupal 8 project, I tried to download module with Drush. But I can only access the internet via a proxy. How can I configure drush to use the correct http proxy settings for downloading?

# Answer
> 6 votes
Drush by default is using `wget` to download project (if available), otherwise `curl`. This can be change by `--package-handler`. You can check which package handler is in place by running your command with debug parameter (`-d`).

So you configure proxy the same way as you would configure this for `wget` or `curl`.

For wget, you can configure these lines in `~/.wgetrc`:

```
use_proxy = on
https_proxy = http://proxy-host:8080
http_proxy = http://proxy-host:8080

```

Note: Please check `/usr/local/etc/wgetrc` for some examples.

For `curl` this line should in your `~/.curlrc`:

```
proxy=http://username:password@proxy-host:port

```

For both I think you can try to export `http_proxy`/`https_proxy` as a system variable.

---
Tags: drush, proxies
---


title: Change date on icon click event

text:
# Question
Title: Change date on icon click event
I'm trying to create a custom block that display the current date (Only Day of the month, 2 digits with leading zeros and A full textual representation of the day of the week) using the tocken module.

Now my problem is how to change the date when the next, prev icon is cicked? For example: Today is saturday the 05th. When i click next, i get sunday the 6th. And when i click prev, i get friday the 04th. Maybe this can be possible using javascript or php.

# Answer
> 2 votes
There are two ways to go about this.

## Pure JS

You can send the date shown to the JavaScript either via drupal\_add\_js or as a data attribute and let the JavaScript manage the date changes. You would need to change the current date +/- 1 when clicking on a button and figure out the name of the day and the day number of the day and display that. This should be relative simple to do.

## AJAX

You can let the use AJAX and send the selected date to a custom menu callback which returns the markup for the new date.

Of the two solutions I would prefer the pure JS version. The Ajax version is more complex to implement and will generate a bigger load on the webserver. It could be a nice solution if you want to do advanced theming and don't want to place that logic in the JS (like weekends / holidays etc are displayed in different styles)

---
Tags: theming, javascript, datetime, tokens
---


title: Custom line item total calculation

text:
# Question
Title: Custom line item total calculation
I have looked for the solution for weeks, but I have not found any. It must be very trivial that I missed.

I'm adding a line item field in addition of the default unit price and quantity called "length" in the cart view and Order. I would like to get the new calculated line item total = price * quantity * length.

Solutions that I have found so far change the line item unit price, which is not desirable.

How can I do this?

# Answer
The line-item unit price is used throughout commerce and the total order amount is based on the line-item total value (quantity * unit price). There is no way to circumvent this behavior.

Better would be to add another price field to the line-item `Price per length-unit`. Hide the default price field and calculate the sales price as you've found in other answers.

Basically this is a pricing rule in `Store > Configuration > product pricing rules` where you add the event `Set the unit price to a specific amount` to a calculated value.
> 1 votes

---
Tags: commerce
---


# Question
Title: Cannot send drupal_http_request authorization header
I'm trying to post a request using drupal\_http\_request, but my headers are causing authorization errors.

This is my request:

```
$headers =  array('Authorization'=>'Bearer [my token here]', 'Content-Type'=>'application/json' );
$url = "https://api.ionic.io/push/notifications";
$message= new stdClass();
$message->message='That works';
$message->title='titleofmessage';
$data = array('tokens' => array('DEV-f765ac70-1bcb-4e0f-8bfd-adfd9612f185'), 'profile'=>'fake_push_profile', 'notification'=>$message);
$result=drupal_http_request($url, $headers, 'POST', json_encode($data));

```

In cURL it works fine, but I want to use drupal\_http\_request:

```
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer [my token here]" -d '{"tokens": ["DEV-f765ac70-1bcb-4e0f-8bfd-adfd9612f185"],"profile": "fake_push_profile","notification": {"message": "That works", "title": "titleofmessage"}}' "https://api.ionic.io/push/notifications"

```

The error message I get is 'Authorization header is missing' so something seems to be happening to that header.

Any help much appreciated!

# Answer
> 2 votes
You have the second param to `drupal_http_request` wrong; it should be an array of options, not an array of headers. Headers is just one of those options.

To fix:

```
$result = drupal_http_request($url, array('headers' => $headers), 'POST', json_encode($data));

```

# Answer
> 1 votes
While Clive was right for Drupal 6, I am using Drupal 7. I've marked his answer as correct, but the code I ended up using was:

```
$headers =  array('Authorization'=>'Bearer [my token here]', 'Content-Type'=>'application/json' );
$url = "https://api.ionic.io/push/notifications";
$message= new stdClass();
$message->message='That works';
$message->title='titleofmessage';
$data = array('tokens' => array('[device token]'), 'profile'=>'fake_push_profile', 'notification'=>$message);

$options=array('headers'=>$headers, 'data'=>json_encode($data), 'method'=>'POST');

$result=drupal_http_request($url, $options);

```

---
Tags: 7
---


# Question
Title: Is it possible to export webform form snippets?
I have built a small contact form with the Webform module. I want to paste it in the *node.tpl.php* and manually customize its code.

Can I export ready-to-work code from the user interface?

# Answer
The answer is no. This is not the way Drupal theming and form building works. One of the main reasons would be that default Drupal hooks and theme functions will not work consistently if you can get a snapshot of a template, export it and change to your liking.

Let's take an example:

1. You create a webform with several fields.
2. Through this fictive module, you get the output which you can use in template files.
3. You use the code where you want.

The following will not work:

1. `hook_form_alter()` implementations. Fields added through dynamic conditions will not be there as well as custom CSS/JS.
2. Theming overrides will not work as well; say that your theme changes the way `textarea` elements are rendered. By exporting the form, you get the snapshot; if there is any dynamic condition, it won't work because the system cannot alter the markup anymore.

Solving the above problems would end up in a real mess, and I think this is just a tip of the iceberg.
> 1 votes

---
Tags: theming, webforms
---


# Question
Title: Problem with token when unchecked "Enable signatures" and "Enable user pictures"
How when i want unchecked "**Enable signatures**" and "**Enable user pictures**" show those errors:

```
 The Body is using the following invalid tokens: [sito: login-url].
 The Body is using the following invalid tokens: [sito: login-url].
 The Body is using the following invalid tokens: [sito: login-url].
 The Body is using the following invalid tokens: [site: url-breve].

```

??

# Answer
> 1 votes
That error is showing up because you are using wrong names of the tokens.

1. `[sito: login-url]` should be `[site:login-url]`.
2. `[site: url-breve]` should be `[site:url]`.

---
Tags: 7, users, tokens
---


# Question
Title: use multi level/chain of entity reference fields to create a list of nodes using views
I have 3 content types: Outline, Chapter and notes.

Chapter and Notes have 2 entity reference fields chap\_outline\_reference and note\_outline\_reference respectively referring to outline. On the chapter nodes i want to populate a jump menu of all the notes referring to the same outline as the chapter. I'm using Views 7.x-3.13 and Drupal 7.41.

I created a block view using the following relationship:

Entity Reference: Referencing entity ( for chap\_outline\_reference)

Entity Reference: Referenced Entity ( for note\_outline\_reference) and i'm using the above relationship in this relationship.

I am unable to figure out the contextual filter. I tried using Content:nid with either of the above relations, but that didn't work.

Any help would be highly appreciated. Thank You.

# Answer
> 0 votes
For everybody stuck in a similar situation and not having advanced knowledge; this is how I solved it: I broke the problem into 2 views and used "view field view" module to connect the 2 views.

In the first view; i used a relationship(entity referencing) and contextual filter(Content:nid) to reach the nid of the outline from the chapter nid.

In the second view; i used a relationship(entity referenced) and contextual filter(Content:nid) to reach the nid of the notes from the outline nid.

Using the Global: view field (from view field view) module I substituted the Outline nid for the contextual filter (Content:nid) in the second view.

---
Tags: entities, views
---


# Question
Title: Add user email and username under the "View" tab at /user/%
Using Drupal 7 and I would like to display the username and email under the view tab of the /user page.

Out of the box it only shows the user History, which I find a bit meaningles. I think that a user should see all his info under the view tab (including username and email) and then when he wants to edit it he can click on the edit tab.

Would be nice if this could be done with a block or similar so that this does not apply to the admin user.

Thanks!

# Answer
> 1 votes
You can always create a block through Views and display this information. Here's how to do that:

1. Create a new view, choose to show "Users" and create only a block.
2. Add "E-mail" field.
3. Add "Contextual filter" for the "User: Uid" field.
4. For filter configuration choose "Provide default value" and then "User ID from URL".
5. Show the block in content area, and configure it so it's displayed only on specific pages. Enter the aliased path you use for user profiles. For example: `profile/*`. This is necessary because the system URL for user profile pages is `user/[uid]`, which you cannot distinguish from `user/login`, `user/register` and so on.

Do note that this will make the username/email available to everyone who has the permission to view user profiles.

Hope this helps.

---
Tags: 7, users
---


# Question
Title: jQuery csv file export fires multiple times
I have a custom form, and I just want a button in the form that fires a jQuery plugin that generates a csv file for download. The problem I'm having is that it seems to fire multiple times for some reason, and I haven't been able to figure out why. I've tried both a button and a link, but I keep getting the same result.

Here's the form button:

```
$form['export_csv_button'] = array(
  '#type' => 'button',
  '#value' => t('Export to CSV'),
);

```

And here's my jQuery behavior:

```
(function ($) {
  Drupal.behaviors.ons_line_item_export = {
    attach: function (context) {
      $("#edit-export-csv-button").click(function() {
        $("#ons-line-item").tableExport({ type: "csv" });
        return false;
      })
    }
  };
})(jQuery);

```

Is there something obvious I'm missing that is making this happen?

Thanks.

# Answer
Try this:

```
(function ($) {
  Drupal.behaviors.ons_line_item_export = {
    attach: function (context) {
      $("#edit-export-csv-button").once().click(function() {
        $("#ons-line-item").tableExport({ type: "csv" });
        return false;
      })
    }
  };
})(jQuery);

```

I added the `jQuery.once()` method.
> 2 votes

---
Tags: forms, javascript, ajax, importing-exporting
---


# Question
Title: How to implement review ratings with Fivestar?
I want to build a rating functionality identical to what we can see on http://www.meineuni.de/ \- there is a page of a product (or an University as in the example) and that page contains cumulative ratings taken from continuous ratings. A sample page is http://www.meineuni.de/uni/jacobs-university-bremen/bewertungen/

Business case: I want anonymous users to be able to create content of specific type and be able when creating the page, to assign ratings in several categories. This page will then be available online for other anonymous users to rate and the rating will be cumulated with the initial rating to show the weighted (initial+continuous) rating.

Is something like this possible with Fivestar in Drupal 7?

I want to find the right way from the beginning, instead of trial and error approach, which I don't mind, but that is more time consuming.

# Answer
Yes, you can do it, you can combine the Views module with the Views Aggregator Plus or with the Views Calc module.

**Views Calc:**

> Adds simple calculations to a views table. You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

**Views Aggregator Plus:**

> In addition to what Views and Views Calc do, this module:
>
> * enumerates group members
> * produces tallies, i.e. textual histograms
> * aggregates on Views PHP code-snippet evalutations
> * can filter out result rows on regexp patterns
> * gives you sorting on Views' Math expressions
> * can process Webform submissions
> * lets you add your own custom aggregation functions
>
> ... and it puts summary statistics at the bottom of your aggregated table as well!
> 2 votes

# Answer
The Views Calc module (of which I'm a legacy co-maintainer ...) as suggested in the previous answer is indeed something I'd also recommend to investigate. To get an idea of how it is like to use that module, have a look at my answer to "How can I show average votes of fivestar nodes?".

Below are some more options you may want to consider (as per the you used in your question), and which includes the Fivestar module.

# Rating

The VotingAPI module offers a framework to developers of Drupal modules about voting and/or rating. It uses a standardized API and schema for storing, retrieving, and tabulating votes for Drupal content.

VotingAPI offers these key features:

* Create/Retrieve/Update/Delete operations for voting data.
* Whenever a vote is casted, it calculates the results and caches them. These calculations can either be the default calculations (average, total, etc), or they can be implemented via custom tallying functions.
* Via its integration with the **Actions** module, it can trigger workflow steps whenever votes are casted and results are tallied, such as promoting a node to the front page, hiding a comment flagged as spam, or sending some eMail.
* It integrates with the **Views** module, which allows for slice and dice of the content of a site based on user consensus. And tt provides functions to format vote data to display them to users.

**Typical rating related modules with a stable release for D7**:

# Views / Rules / Flag / Message

Everything above relates to "Rating" (or voting). Some more modules that you may want to consider (= add to the mix of modules you might want to consider):
> 1 votes

---
Tags: 7, rating
---


# Question
Title: With REQUEST_URI i get id node or alias path?
I have a big doubt. In `template.php` I am using:

`$_SERVER['REQUEST_URI']`

what will the output like: `node/id-number`**or** `/Alias_page` ?

# Answer
The right way to check on which page are you, is to use the `current_path()` function. Below is an example:

```
if (current_path() == 'your/system/path') {
  // Do whatever.
}

```

This is the best way because aliases can change, while system paths stay the same.

However, if you really need the aliased path, use the `drupal_get_path_alias()` function instead.
> 0 votes

---
Tags: 7, uri
---


# Question
Title: how to setting drupal i18n translation module not to translate system menu I don't want?
In my site I am using drupal7 i18n module to translate to Burmese language. But my problem is I don't like drupal to translate system fields that does not need to translate because translation is totally wrong and might confuse for user, so it is better for user to leave these as English such as system field and something like that. When I click Burmese language in language switcher block, all for content fields, sitemap navigation, content types fields and product fields are changed to burmese, but translation is really really confusing for me and also for customer. So I am thinking that it is easy for me and customer if not system translated, and I will have to manually interpret the fields and taxonomy that I want to local user to understand.

Any suggestion is greatly appreciated.

Thanks

Highlights in above two images are really misunderstanding and that doesn't need for i18n module to interpret.

# Answer
You can try Administration Language module.

> This module lets the administrator see all administration pages in her preferred language.
>
> You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).
>
> You can use the standard Languages page to choose the language of the admin pages.
> 0 votes

# Answer
A very simple solution is to keep translation applying everywhere, assumed you review all confusing translations and replace them by ones of your own.

You can do this at the `admin/config/regional/translate/translate` page of your site.

The only issue with that solution is it might regard a too wide number of strings, so being a huge work.
> 0 votes

---
Tags: i18n-l10n
---


title: Upload File Processing Background

text:
# Question
Title: Upload File Processing Background
Is it possible when uploading a file to a node for it to upload as a background process? Ideally what I would like to do is to be able to upload files in the background while being able to continue navigating through the website. When the uploaded files are complete a notification appears on the website to say that the upload is complete or an email is sent.

# Answer
> 1 votes
After having a look in the Contrib Module space, I would say no, it's not possible. The main problem as you probably already know: A file upload will break if you navigate away from the page.

However, if you have lots of time to invest in implementing this, I could imagine the following workaround: You could ajaxify your whole Drupal website, e.g. with ajaxify so that some outer elements of your page will persist while your navigation is taking place and your content is rendered inside a "content" element. You could then process the file upload in e.g. an iframe that resides outside of your "content" area.

Hope this helps!

---
Tags: files
---


# Question
Title: Why do I need to remove old files first when upgrading Drupal or its modules?
I'm in the process of updating my Drupal version 7.41 to 7.43 and started o follow the guide Update procedure (minor version change) where it says

> 3. Remove all old core files and directories, except for the 'sites' directory, the original install profile in the 'profiles' directory and any custom files you added elsewhere.

and I was wondering why they wanted to have me erasing everything first, can't I just copy all the new content into my ftp folder except the `sites/` directory?

Thanks

# Answer
By deleting all the directories you're ensuring no files are left over that shouldn't be there anymore. A simple overwrite won't always do that.
> 4 votes

---
Tags: updating, files
---


# Question
Title: Rules Conditions being evaluated after schedule time elapsed?
Backstory: I have a content type that will send an email after a period of time if a boolean is true. From the creation of a node to the time the email will be sent, the boolean could change at any time.

My Problem: I would like a clean way to have the conditions of a rules (see if the boolean is true) to be evaluated before going about executing an action set. Through my testing, I cant get the Rule to be properly check the boolean when a node is both created and updated.

Optimally, I would like the conditions to be evaluated after the elapsed time of the Rules scheduler rather than upon initially after being created or updated.

**Clarification Edit:** Make a Rule that will execute sending an email after a given set of time that is set by the user upon node creation. The single condition of sending the email is if a boolean is true. The boolean could be modified on node creation or through a node update. So the Rule can not be activated based on one of those. No Sssweat was able to show me how to move an evaluation from a standard Rule to the component allowing it to only be evaluated when the standard Rule scheduled the component. So the Rule is set up to be triggered on node creation with only a given time frame field as its condition. Depending on which time frame field was selected, the Rules Scheduler will start. During this period the boolean to be evaluated could be shifted from true to false many times. So only be the end of the scheduled time should the boolean even become relevant. The component side of the rules looks at the boolean to see if it should send the email or not. If true \> send email. If false \> do nothing.

**Some more clarifications:**

1. The user has a field to choose the time frame for resolving the node.
2. If a node is updated, the countdown should not be reset. One email should be evaluated to be sent at the end of the given time frame.
3. If the boolean has been changed to false, the email should not be sent and no further action is needed.

# Answer
> 3 votes
Give this a try

## Create a New Component

1) Add Compotent of Rule.

2) For Data Type: select Node. Name, Label and Machine name use whatever you want.

3) Add condition of **Content is of type**

* For Data Selector: put your Node Data Type machine name. Ex: if you gave the node data type a machine name of `test` you put `test`
* Select your content type

4) Click on **Add and** select Data Comparison and select your boolean field.

Example: When creating the component, if you gave the Node Data Type a machine name of `test` and your boolean field is named `hello`. For your boolean field you need use `test:field-hello` as your data selector.

5) Add action of Send Mail.

## Now Create a new Rule

1) For action use after content is created

2) Leave the condition empty (no need for condition here)

3) for Action add the scheduled component evaluation and select the component you just created.

* use `node` as your data selector

> I believe this will evaluate your rule component only when the schedule time hits.

# Answer
> 0 votes
The accepted answer to this question is indeed a solution for the question asked. Whereas a condensed version of the question is like "***How to send an eMail after some predefined time after the creation of a node, provided some boolean is (still) true the moment that eMail should e triggered?***".

I think you're making it too complicated by what you're asking for. To explain what I mean, first have a look at my answer to the question "How can I set a reminder for a specific user to be triggered on a specific date?". Obviously, that is not the same question as yours here. But the "specific date" there corresponds to your "predefined time after the node creation date".

With that, you could avoid that (not obvious to implement) validation if you'd just trigger another rule each time that the node is edited, and then verify the relevant data of your node content to decide if you need to do either of these:

* no more need to send the eMail "later on", so just DELETE the scheduled execution of the Rule to send your eMail.
* (re-)schedule the execution of the Rule to send your eMail.

Apart from the simplification of the Rules logic with this approach, you also get the advantage that the "queue" of actually scheduled eMails is always accurate (the scheduled rules correspond to nodes that have a current status that indicates that the eMail is still relevant). While with your current implementation (to validate again at the time the eMail is due), you may have zillions of scheduled rules that are sitting there, while at the very last minute it turns out many of them were just waiting to do .... nothing.

Bottomline: sometimes the solution for a problem is ... to avoid the problem from happening.

---
Tags: 7, rules
---


# Question
Title: Download file after fill in email address
When anonymous users wants to download e.g a PDF file, they must first fill in their email address. What is best way to set this up?

# Answer
> 1 votes
The easiest way without resorting to coding would be setting up a Webform that the user is required to fill out, containing only one email field, and putting the link to the PDF in the completion message.

If you need strict access control on the PDF, you can setup your site with Email Registration and Generate Password, and redirect the user after registration to a node that is visible only to authenticated users. Add a file field using the private file system to the content type and attach the PDF to the node.

---
Tags: 7
---


# Question
Title: How does Drupal Commerce store Addresses for anonymous users
I'm trying to figure out how exactly does Drupal Commerce store Addresses for anonymous users?

Let's say an anonymous user creates a shopping cart and fills in the shipping information, but has not yet completed the checkout (payment for example, so shipping information is already stored with the order). At this point, has the system already created a shipping entity, if so, then to whom, as the anonymous user ID is 0.

Else if the Shipping information gets stored only upon checkout completion, still, to whom is it assigned? Who is the owner of the address.

Commerce also allows for an anonymous user to later create an account that has all their order history and shipping addresses, has there been assigned a new unused user ID for the user, just in case they decide to register, to associate all this information, or is the address originally only tied to the order it self, with owner ID 0, and the user profile is created upon registration based on the order details?

Why I'm asking for all this, is that I'm creating an order process where the address is assigned for each product separately, and on checkout each product with different shipping address is moved to a new order with the specific shipping address. And with this in mind I still wish to keep the possibility for making anonymous purchases, and am trying to figure out the dynamics of the shipping addresses :)

Best regards,

Alari

# Answer
As billing or shipping data gets entered during checkout, it gets created as a customer profile. Each order has a `commerce_customer_billing` address field and maybe even a `commerce_customer_shipping` field (if shipping is enabled). It holds a reference to the billing profile that got entered during checkout (even for anonymous users).

This is the same for logged in users as well, the only difference is that they are associated with the user.

If you've enabled the rule `Create a new account for an anonymous order`, it will also set the UID of the billing and shipping profiles to the new user as well.
> 1 votes

# Answer
Commerce will always create a new user upon completion of the checkout process of anonymous orders. This happens in a rule named "Create a new account for an anonymous order":

admin/config/workflow/rules/reaction/manage/commerce\_checkout\_new\_account

If you want to clone the order, then, just act after the aforementioned rule has executed by creating a rule with a higher weight.
> 1 votes

---
Tags: commerce, entities
---


# Question
Title: Loading css style present in DOM of another node
I am using the module Simple Background Image Formatter to convert an image into a div background image. It has two options - one to put as an inline style of a div or to choose a CSS selector which it styles with a background image in the DOM. I cannot use the inline style method in views so that is ruled out. Now as per the CSS selector method, it adds a style directly on the page with the 'selectedclass\_id'. I can choose the selectedclass but not the id (appears to be randomly added).

However, since my requirement is through views, it somehow (although with wierd settings) automatically prints the class and adds the id, however, the image for other nodes is not loaded in this node as its html style in not loaded in the current page. That is, the image of every page is converted into a selectedclass\_id (background-image:...) and placed in the html of that page but the selectedclass\_id of the other nodes which are part of the view in this page are not loaded here with their respective values. Therefore, these images are not being displayed in the view.

Is there a solution here? I want the page to load the css selectors for the nodes which are shown in the view (of the same content type) so that the code for each of the view fields is where the id will be different for each of the nodes. The current page should have the values of all such nodes in the view as it does with regard the value of the current page. Presently, only the selectedclass\_id of the current page is being loaded in the head html style.

An alternative for the module is Background Images Formatter but this is dependent on bg\_image which does not have a Drupal 8 version and doesn't work without it.

# Answer
> 0 votes
> I have a related content section on my page through views in which i want one field to be a div with a background-image.

Ok, then you can use Image URL Formatter. Which will output your image as a url instead of the actual image.

Then add the image field, which contains the image you want to use as background

* Hide it from display.
* Select image url as your formatter

Add a custom field OR Rewrite the result of an existing field and use the image replacement pattern.

ex `<img class="[YOUR CLASS]" src="{{ field_image }}">`

OR if you create a **.html.twig** template file for your view, then you can use

`<div class="[YOUR CLASS]" style="background-image: url('{{ field_image }}')"></div>`

---

### Another option

In Style settings you can add a class to your fields.

\[

Then with css give it a `z-index: 0;` and give everything else `z-index: 1;` and move img around by giving it `position: absolute; top: -100px;` etc..

---
Tags: 8, media
---


# Question
Title: How to show block based on browser language?
In Drupal 8, I would like to show a block to a visitor based on their browser language (I guess based on the `Accept-Language` HTTP header).

The page should stay in English but there should be something like "*this site is available in your language, click here*" (translated into the relevant language, of course).

# Answer
I don't think this is possible without custom code if you want to do this differently from the current language.

However, you don't need to do all the heavy lifting yourself. See LanguageNegotiationBrowser and the code there, you should be able to more or less copy that 1:1.

Then it will only do it if the language actually exists, respects language mappings and so on. You just have to call that, check if it's different from the current language and if so, display something.

However, properly caching that is going to be fun:

You need a cache context for an arbitrary http header, similar to CookiesCacheContext. so something like http\_header:HTTP\_ACCEPT\_LANGUAGE as a cache context.

That will however not work for anonymous page cache, since that doesn't check cache contexts at all. To work around that, you need your own page cache implementation, that caches by that header, which will obviously result in lots and lots of variations.

So.. maybe you should just do this completely in JS?
> 1 votes

# Answer
Because i needed the same i have created a solution based on Berdir's answer. I created a menu callback where i compare the active language against the browser language. This callback i access with ajax, and based on the json result i do something. In my case i rewrite the language string itself in the browser language and highlight it. You can see the result here https://www.masterhomes.net/.

```
/**
 * Implements hook_menu().
 *
 * Add a menu callback to compare the browser language with the active language.
 */
function custom_menu() {
  $items = array();
  $items['browser-lang'] = array(
    'title' => 'Check browser language',
    'page callback' => 'custom_browser_lang',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page Callback to handle the browser language.
 */
function custom_browser_lang() {
  // Set default output.
  $output = FALSE;
  // Get active langcode.
  global $language;
  $active_lang = $language->language;
  // Get browser langcode.
  $browser_lang = locale_language_from_browser(language_list());
  // If we found the browser language and it's not the same like the current
  // language.
  if ($browser_lang && $active_lang != $browser_lang) {
    // Get "Language" string in browser language.
    $output = array(
      'langString' => t('Language', array(), array(
        'langcode' => $browser_lang,
      )),
      'langCode' => $browser_lang,
    );
  }
  // Output json data.
  drupal_json_output($output);
  // Prevent caching.
  exit;
}

```
> 1 votes

# Answer
Either use DI for the block plugin or call \Drupal::request() directly and determine the language in similar manner to(just a guide, I know it's ugly):

```
$languages = \Drupal::request()->server->get('HTTP_ACCEPT_LANGUAGE');
$languages = explode(';', $languages)[0];
$languages = explode(',', $languages);
$language = explode('-', $languages[0])[0];
print $language;

```

If you want to apply this to any block, not just your own block plugin block, then I would suggest you create a route context provider. See implementations of \Drupal\Core\Plugin\Context\ContextProviderInterface
> 0 votes

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


title: How do I configure SSO by SAML?

text:
# Question
Title: How do I configure SSO by SAML?
At first, I am new in SAML. Could somebody tell step by step, how to configure SSO on Drupal using simplesamlphp? Or how to test by "Test configured authentication sources"?

What I have now.

1. Installed simpleSAMLphp Authentication module.
2. Add simplesamlphp library to my site (mysite/simplesamlphp).
3. Changed config.php
4. Added meta to saml20-sp-remote.php

$metadata\['name'\] = array( 'SingleSignOnService' =\> 'url\_login', 'SingleLogoutService' =\> 'url\_logout', 'certFingerprint' =\> 'key', );
5. When I go to mysite/saml\_login, I am return to login page on IdP. After login I return to my site (mysite/sso/login?params) with SAMLRequest and other GET-params. But site show page not fount error. On wiki it step 2.

So what I did wrong? May be I must set same page callback to handle this GET-params?

I also try to did this by simplesaml "Test configured authentication sources", but I got the same result.

Please, help!

# Answer
This is a very old question but worth solving it.

By:

> I also try to did this by **simplesaml** "Test configured authentication sources", but I got the same result.

It seems that @misha-from-lviv didn't configure simpleSAMLphp correctly.

> $metadata\['name'\] = array( 'SingleSignOnService' =\> 'url\_login', 'SingleLogoutService' =\> 'url\_logout', 'certFingerprint' =\> 'key', );

The metadata is incomplete

The process to configure the simplesamlphp is way more complex that the 5 steps described there. This Vagrant box setup simplesAMLphp (as an SP and IdP) and Drupal 7 for you and let's you start testing SAML right away.

Disclaimer: I created the box
> 1 votes

---
Tags: 7, users
---


# Question
Title: Why can the Views Gantt module not find the DHTMLX Gantt JS library?
I am trying to use the Views Gantt module and getting nowhere fast.

The Status Report is complaining that it cannot find the dhtmlxgantt JS library in the libraries directory - despite my having checked its presence over and over.

Has anyone any ideas what I might be doing wrong?

# Answer
Are you sure the dhtmlxgantt JS library is located in: `sites/all/libraries/dhtmlxgantt` ?

Within that folder you should have extracted the original library which should have: `sites/all/libraries/dhtmlxgantt/codebase` and `sites/all/libraries/dhtmlxgantt/samples`.

Also make sure the "dhtmlxgantt" folder name is all lower case.
> 0 votes

# Answer
A typical explanation for this is that **if** you're using the older version in the 7.x-1.x branch (eg because there is no stable 2.x version yet) **then** you should use the older DHTMLX 1.3 library, which you can still download from this DHTML Gannt link.
> 0 votes

---
Tags: 7, views, theming
---


# Question
Title: How to set field values when creating new node with Rules?
We can create new nodes using Rules Actions. However, when creating new nodes, if we want to set the fields' values for the new node, there seems to be no way to do that in Rules.

E.g. I want to create a new node, using Rules Action, which has a field `field_age`. And I want to set it to some value depending upon the event. How do I do this?

Can this be done using Rules?

# Answer
> 3 votes
Yes you can.

Add action: Create a new entity \>\> select your content type

Add action: Set A Data Value and for data selector use, for example if want to set a value for the body then you use: `entity-created:body`

In your case `entity-created:field-age`

Add action: Save Entity \>\> `entity-created`

---
Tags: 7, nodes, rules
---


title: Comment with email or social networks

text:
# Question
Title: Comment with email or social networks
I am developing my personal site in drupal 7. Actually i am searching for a module which allows anonymous users commenting with their email or any social n/w like twitter,facebook or google+. Is there any good module available or is drupal 7 supports anonymous users commenting with their email address ?

# Answer
We can achieve that using the Disqus module
> 0 votes

# Answer
You can achieve that using the OpenID Selector module

> This module integrates Javascript OpenID Selector with Drupal's OpenID client.
>
> This module substitutes Drupal's default OpenID form with Javascript OpenID Selector widget, so users do not even need to know what OpenID URL is.
> 1 votes

---
Tags: users, 7, comments
---


title: Rules replacement pattern missing

text:
# Question
Title: Rules replacement pattern missing
I have a content type including these two fields

and now I want to use those fields in a "Rules" action, but they are not present in the replacement patterns to choose, and they're not present in the Data Selection mode either.

What have I missed? Would appreciate if someone could point me in the right direction.

My rule export code

```
{ "rules_fiberbest_llningsemail" : {
"LABEL" : "Fiberbest\u00e4llningsemail",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_insert--fiberbestallning" : { "bundle" : "fiberbestallning" } },
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "fiberbestallning" : "fiberbestallning" } }
    }
  }
],
"DO" : [
  { "mail" : {
      "to" : "me@example.com",
      "subject" : "Fiberbest\u00e4llning",
      "message" : "Ny fiberbest\u00e4llning fr\u00e5n hemsidan skapad [node:created]\r\n\r\n[node:url]\r\n[node:field-f-rnamn]\r\n[node:field-efternamn]\r\n[node:field-adresss]\r\n[node:field-postnummer]\r\n[node:field-postadress]\r\n[node:field-fibertyp]",
      "language" : [ "" ]
    }
  }
]

```

# Answer
You need to:

Add Condition \>\> Content is of Type \>\> \[your content type\]

OR

Add Condition \>\> Entity Has Field \>\> node:field-telefon

Add Condition \>\> Entity Has Field \>\> node:field-signatur

OR

Add Action \>\> Fetch Entity by Property \>\> Node \>\> telefon \>\> node:field-telefon

Add Action \>\> Fetch Entity by Property \>\> Node \>\> signatur \>\> node:field-signatur
> 2 votes

---
Tags: rules
---


# Question
Title: How to render $site_name without html tag?
The $site\_name variable get the name of the site wrapped in `<a>` tag but I want print only the value without html?

Is possible?

Thank you in advance.

> **EDIT**
>
> I'm using the strip\_tags() function of php `<?php print strip_tags($site_name); ?>` but I don't know if is the best solution to solve the issue.

# Answer
> 1 votes
In a preprocess function you can get the title like this:

```
variable_get("site_name");

```

---
Tags: theming
---


# Question
Title: Setting a variable as a class (using set classes) in a region template
I am attempting to set a common class if any preface region in my theme appears. I am trying to render this with a variable using `set classes = []` in the region template in my theme.

So far I have set a variable in a preprocess region like this:

```
function gratis_preprocess_region(&$vars) {
  // Check to see if any of the preface regions have content and if so
  // Set a common var for use as a class in the region template.
  if (!empty($vars['page']['preface_first']) || !empty($vars['page']['preface_second']) || !empty($vars['page']['preface_third'])) {
    $vars['preface_region'] = '';
  }
}

```

Then in my theme's region template I attempt to render the variable within the `set classes` area.

```
  set classes = [
    'region',
    'region-' ~ region|clean_class,
    region == preface_region ? 'region-preface'
  ]

```

I am pretty sure I am not doing this the correct way though and it does not work.

# Answer
It seems the way to do this was to create a theme hook for all preface regions and then it can have its own template. So first I create an alter preprocess function in my theme's .theme file.

```
function MYTHEME_theme_suggestions_region_alter(&$suggestions, $vars, $hook) {
  // Print the $vars.
  kint($vars);

  // Define a var for the #region.
  $preface = $vars['elements']['#region'];

  // Now check for any of the three preface regions and create a theme hook.
  if ($preface == 'preface_first' || $preface == 'preface_second' || $preface == 'preface_third') {
    $suggestions[] = 'region' .  '__' . 'preface';
  }
}

```

Next, voila, when I look at Twig debug, I see a suggestion for my new theme hook.

```
   * region--preface.html.twig >> **** This is the new template from the alter
   * region--preface-second.html.twig
   x region.html.twig

```

Now I can create a common template for all three preface regions with `region--preface.html.twig`.

Then in the new template, I print the classes like so:

```
 {%
set classes = [
'region',
'region-preface',
'region-' ~ region|clean_class
]
%}

```

This gives me exactly what I set out to do and prints this HTML:

```
<div class="region region-preface region-preface-second">

```

Now I can use `.region-preface` for common theming / HTML for any of the three the preface regions.
> 1 votes

---
Tags: 8, theming
---


# Question
Title: How do I verify that the form input date is valid?
Some browsers (e.g. Safari) allow rubbish dates to slip through a form `Date` field so that we get a fatal PHP error (`Call to a member function format() on null`) when we invoke the `DrupalDateTime::format()` per the code below which doesn't catch any exception.

The user can type `19-00` into the time part of the date field instead of `19:00:00` and this will cause Drupal 8.0.5 to crash.

What is the correct way to test that a date in a `DrupalDateTime` object in the form array can be formatted properly? This doesn't work (snippet from an `entity_builder` for new and changed *Meeting* Nodes in our *Meeting* module):

```
try {
    $formatted_date_of_meeting = $date_of_meeting->format('l, j F Y');
} catch (\Exception $e) {
    $form_state->setError($form, $e->getMessage());
}
$node->setTitle($name_of_meeting.' on '.$formatted_date_of_meeting);

```

# Answer
If the date is valid, then the form state will return an object of type `Drupal\Core\Datetime\DrupalDateTime`, and otherwise it will return an array with the invalid values. Since the invalid date format will be caught elsewhere, the custom code need only check if the value is an instance of `DrupalDateTime`:

```
if ($date_of_meeting instanceof DrupalDateTime) {
  $formatted_date_of_meeting = $date_of_meeting->format('l, j F Y');
  $node->setTitle($name_of_meeting.' on '.$formatted_date_of_meeting);
}

```
> 2 votes

---
Tags: 8, datetime
---


# Question
Title: How to translate the book pages content using the Book Translation module?
My requirement is that a user can see the complete book pages in the selected language (English, Hindi, Bengali, etc) as per the preference. That's why I installed the Book Translation i18n\_book\_navigation module.

As I installed the module and enabled the language block but it didn't translate my node's content. It only translate the inbuilt of Drupal taxonomy like View, Edit, Outline, etc into other languages. Do I need to configure some other settings for translating the book pages content or am I missing any module to install or enable?

# Answer
If I understood your question correctly, you need to enable translations for the "Book page" content type.

* Go to `/admin/structure/types` and click on "Edit" next to the content type you use for storing the book pages.
* Under "Publishing options" make sure that "Multilingual support" is set to "Enabled, with translation".
* Save the content type.
* After you save this, you can go back to the edit page and configure extended language options in "Multilingual settings" tab.
> 1 votes

---
Tags: nodes, i18n-l10n
---


# Question
Title: Geshi does not detect libraries on Drupal 7
I have installed the Geshi Filter and Field modules, but Drupal does not detect the GeShi Libraries.

1. I got the Geshi Libraries from sourceforge. To be sure, I put it in: `/sites/all/libraries/` , `/sites/all/modules/libraries/` and `/sites/all/modules/geshifilter/`
2. I am using 7.x-1.x-dev

Yet, it cannot find the libraries. How can I get it to work? Please do not suggest syntaxhighlighter. I have tried it and I would prefer a server side solution.

From the Status Report

# Answer
The files should be copied, for example, in "sites/all/libraries/geshi" or "$config/libraries/geshi," where "$config" is the directory containing the settings.php file used for the Drupal site.
In the first case, the class.geshi.php file is put in "sites/all/libraries/geshi/class.geshi.php," and the "geshi" directory that is in the downloaded archive is put in "sites/all/libraries/geshi/geshi."

As for where the Libraries API module looks for the directory containing the library files, the documentation comment for `libraries_get_libraries()` reports the following text:

> Returns an array of library directories from the all-sites directory (i.e. sites/all/libraries/), the profiles directory, and site-specific directory (i.e. sites/somesite/libraries/).

The site-specific directory is the one that I reported as "$config/libraries/geshi."
The module doesn't look in "sites/all/modules/libraries."
> 1 votes

# Answer
Based on the comments in this bug report, flushing all caches once or twice will resolve the issue. Worked on my end after one flush.
> 0 votes

# Answer
Flushing cache didn't work for me -- but flushing all caches then turning off the geshifilter module, and reenabling it -- that worked.
> 0 votes

# Answer
On the module home page, it clearly says:

> ### Important Note
>
> only the 1.0.x branch of the GeSHi library is supported, so **do not use the development branch GeSHi 1.1.x**. Direct link to GeSHi 1.0.x releases: http://sourceforge.net/projects/geshi/files/geshi/

The source forge link you provided downloads **GeSHi-1.1**.2-alpha3.zip which you are not suppose to use.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Private File System and Externally Modified Files
I have a D7 site that includes a few hundred nodes that have PDF attachments that use the core file field and the private file system. The site uses a custom module to dynamically watermark these PDFs and we're going through an update that requires each PDF to be updated to use a new layout.

In order to minimize downtime, what I was hoping to do was pull the site to a development environment, directly edit the PDFs that are stored in the private file system and then push the updated files and changes to the watermarking feature back to production.

All seemed like a good plan, but I'm finding that Drupal will no longer serve the updated files after they've been modified. No error messages in the logs (Drupal, PHP or server) and the site just times out when you request new files from /system/files/...

I haven't been able to find any documentation or relevant issues on the subject, but I'm wondering if Drupal's private file system is failing to deliver the file due to changes to the timestamp or file size?

Has anyone run into this before? I'm hoping there's a workaround that does not require that we update hundreds of nodes by editing and manually re-uploading each file one at a time.

Thanks much!

# Answer
The files won't be served if the entry in the `file_managed` table for that file does not have the correct `filesize`.
> 0 votes

# Answer
There are a few problems with storing very large (\>2GB) files in Drupal using the private file system.

1. The filesize column doesn't allow recording values this large (https://www.adammalone.net/post/dealing-large-filesizes-drupal#.VtuIZjYc7AV)
2. If you attempt to upload a small placeholder file, and then replace it with the larger file, you will have the problem that @Drupal-Hater refers to.

The first problem has a fix in the link I provided.

An approach to resolving the second problem is:

```
function hook_file_download($uri) {

  // Get file length
  $length = filesize($uri);

  // Set timeout to unlimited for this request
  // (could do this conditionally for larger files only)
  drupal_set_time_limit(0);

  // Return length
  return array('Content-Length' => $length);

}

```

This will mean a performance hit for any privately hosted files. A better approach would probably be to store the file length in the `file_managed` table. However, it's up to you to decide when you should do this, maybe when the node is being viewed/edited? The approach I've listed above works and the perf hit is minimal - hard to notice at all and shouldn't be a problem if you use private files selectively.
> 0 votes

---
Tags: 7, files
---


# Question
Title: How to sort a view so that, say, all the nodes with stock=0 come last, and not sort by stock?
I want to sort an output of a view so that the elements with a filed value of "0" be at the end of the list, but all the others are to be treated equally. In fact, it's an Drupal Commerce site, and I want all products with stock \>0 to appear first in the lists, regardless of the stock quantity, so that the unavailable stuff get at the end, but still be in the view (after that, I sort alphabeitcally). Any ideas how to do that? That means making the output of a boolean forumla stock=0 the sorting criterion

# Answer
> 1 votes
You could do this if you use something like the Views php module, because that will allow you to use php code to sort by. I know that module is currently looking for additional maintainers, I just can't think of an alternative.

Once you've enabled it, and added a php field to sort by, I'd have it return something like:

```
min([commerce_stock], 1);  // replace [commerce_stock] with whatever your available stock variable is.

```

What that code will do is return 1 (the minimum) if you have any stock more than 1, but it will return 0 if the product is all out.

So it will only return 1 (there are items) or 0 (there are none), which is exactly what you want. Next, you can add a sort by name or whatever you want to sort these two groups further.

Let us know if it works. I was having a bit of problems getting this rolling, since my stock variable is just returning my product ID, and I'm not sure if I'm just running slightly out-of-date modules or what. So let us know if a similar approach works when you try it!!

# Answer
> 1 votes
May not be the right answer but it works. On main view (filter stock\>0), add a view block, add a filter by stock=0, on main view, insert the new block view as a footer, you can inherit url data on settings. Make CSS as needed.

# Answer
> 0 votes
I have not implemented this idea but this might help you.Add a hidden field to your product and give it a text value like A for those on stock and value B for those not in stock. Now u can sort by this field and i guess you might get what you wanted.I guess this might work.

---
Tags: commerce, views
---


# Question
Title: Access Denied even if permission is given
I have this module, as admin users I can access this module normally. But when I add permission to other roles (and it saved), other users who have the permimssion couldn't access it. Please help me.

This is the code.

```
include_once(drupal_get_path('module', 'tb') .'/tb.menu.inc');
include_once(drupal_get_path('module', 'tb') .'/tb.inc');

function tb_perm() {
  global $user;
  return array('trial_balance');
}

function tb_menu() {
  global $user;
  $items = array();

  $items['akuntansi/tb'] = array(
    'title' => 'Trial Balance',
  'type' => MENU_NORMAL_ITEM,
    'page callback' => 'tb_neracapage',
    'file' => 'tb.inc',
    'access arguments' => array('akuntansi'),
    'access callback' => TRUE,
    //'type' => MENU_CALLBACK,
  );

  $items['akuntansi/tb/pdf'] = array(
    'page callback' => 'tb_neracapage_pdf',
    'file' => 'tb.inc',
    'access arguments' => array('akuntansi'),
    'type' => MENU_CALLBACK,
  );
$items['akuntansi/tb/xls'] = array(
    'page callback' => 'tb_neracapage_xls',
    'file' => 'tb.inc',
    'access arguments' => array('akuntansi'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

?>

```

# Answer
> 1 votes
Your implementation of `hook_perm()` (which is not valid for Drupal 7), only defines the *trial\_balance* permission, not the *akuntansi* permission your code is trying to use.
The fact the user #1 has the permission to see those pages is just because the user #1 by-passes all the permissions; in fact, `user_access()` returns `TRUE` for that user.

```
  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

```

To make it clear, without explicitly setting an access callback, the access arguments are expected to be an array with the user permission string, which in your case would be *trial\_balance*.

If the module is for Drupal 7, then `hook_perm()` is not even used; instead, Drupal 7 uses `hook_permission()`, which is not a simple renaming of the previous hook. It is expected to return a differently structured array; using the same array as Drupal 6, will cause it to not properly work.

---
Tags: users
---


title: Store credit card details

text:
# Question
Title: Store credit card details
I've built website using drupal 7. Site is having store of products, for transactions using commerce, commerce\_payflow\_pro modules. Requirement: Store -\> Orders table not containing used credit card details i.e. last 4 digit of credit card number, used to place transaction & card type used to place the transaction.

Please suggest solution.

# Answer
> 1 votes
Commerce Card on File module was built exactly to solve this purpose!

> Commerce Card on File provides an API and user interface for storing and reusing credit card data on subsequent orders within Drupal Commerce. The module does not retain full card numbers locally but instead stores the remote ID of the full card data from the payment gateway used to validate and process your credit card transactions. This means card on file data will only be good for a single payment gateway; if you change payment gateways or accounts, your stored card data may no longer be usable.

---
Tags: commerce
---


# Question
Title: Is it possible to POST values to another page from the FORM SUBMIT function
I have a module that allows authenticated users to book a "Facility" and then pay for it online. The module that facilitates the online payment is different from the booking module.

In the booking module I accept the details from the "authenticated" user in a form and in submit function I store the record in the DB with the following code

```
$form['$source'] = array(
  '#type' => 'hidden',
  '#default_value' => 'obb',
);

$form['uv_amount'] = array(
  '#type' => 'hidden',
  '#default_value' => $amount_final,
);

$form['description1'] = array(
  '#type' => 'hidden',
  '#default_value' => 'OBB - Booking Charges for ' . $hall_type_code . ' ON ' . $arri_date,
);

$form['#method'] = 'post';
$form['#action'] = '/mymodule/pgi/confirm';

```

In the module that handles the payment gateway I pass these values to the payment gateway after calculating the mandatory HASH values etc (as per the payment gateway integration document)

During testing I figured out that the values are not being posted to the PG page. Is there a way to post the values to the PG page after I store the booking/reservation details in the form submit function? Or is there a better way of accomplishing this. Would appreciate any help.

# Answer
> 0 votes
It sounds like you are doing a multi step form (given the URL in your form is "confirm"). You don't want to be looking at $\_POST values, you'll want to utilize FormAPI all the way through.

See for examples:

http://www.sitepoint.com/building-multi-page-wizard-like-form-drupal/

http://jamesdavidson.io/blog/how-create-multi-step-form-drupal-7

http://www.webomelette.com/ctools-object-cache-multi-step-form

---
Tags: forms
---


# Question
Title: How to change active link css class (is-active)
What the best way to change css class for an active link from 'is-active' to (in my case) 'active'?

Also, need I really to replace it or to append my class? I know the 'is-active' class is hard-coded (here and in several php classes) and it is so strange for me since drupal is overloaded with many abstraction layers and tons of settings. What is it: "legacy of the past" or really well-founded idea?

I need 'active' class just for my current css-framework, but may be 'is-active' used in core or so?

Thank you!

# Answer
You can override the theme\_menu\_link function like this:

```
function theme_menu_link($variables)
{
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = \Drupal::service('renderer')->renderRoot($element['#below']);
  }

  foreach ($element['#attributes']['class'] as &$class) {
    if ($class == 'is-active') {
      $class = 'active';
      break;
    }
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '<li' . new Attribute($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Redirect loop, add-{type}-node redirects to add-{type}-node for non-admin users when parent type not availab.e
Users without admin permissions get a redirect loop error when they try to create a certain (organic group content) content type, when the parent (organic group) content type does not exist.

That is, instead of getting the edit form or a 403 error, they go straight to a redirect loop error. We do not have have any 403 redirect overrides, so that's not the cause. The .htaccess file is the default one provided by the Drupal installation.

Using the "display redirection page" reveals that the add node form is redirected to the add node form in this situation. I've been unable to find any any Rule or other setting that could be causing this.

I am not using the Global Redirect module (which research indicates is the most common cause of this problem). Putting the site into maintenance mode and turning off all path, url, and indexing related modules, including Pathauto and Rules, (and reverting to the default Drupal theme) doesn't solve the problem.

The problem does not occur for anyone with the "override access permissions" privilege set.

Any thoughts

1. as to what might be causing this or
2. next steps I can take trying to debug this problem?

# Answer
The Rules module that can be used to perform redirects also. So check if your sites uses this module. If so, verify if you have any "**Active**" Rules (and/or Rules Components) with a **Rules Action** that issues a redirect.

If no such Rules can be found, then it is not Rules causing your issue. If such Rules (and/or Rules Components) do exist, then temporary disable all such Rules and check if the redirect loop still happens.

If the redirect loop no longer happens, then re-enable the temporary disabled Rules again, one by one, until the problem (loop) starts again. Then disable that Rule again and use Rules debugging facilities to find out what the (customization related) problem with that rule is. For more details about debugging facilities in Rules, refer to my answer to ""How to loop through comments using the Rules module?".
> 1 votes

---
Tags: users, organic-groups, redirection
---


title: Nivo Slider jQuery plugin Not installed

text:
# Question
Title: Nivo Slider jQuery plugin Not installed
I´m trying to install Nivo Slider to my website. I was following this tutorial from the official plugin website.

I have the folder "all" an inside it I have "libraries", "modules", and "themes". I extracted the FlexSlider-master.zip in my libraries folder, and rename it to "nivo-slider".

The second step was install the extension from the url drupal/project/nivo\_slide without drush, download the folder an upload to my server in modules/.

I have clear the cache but the problem persist.

Can someone help me? I can´t upload pictures or links with less than 10 reputation.

# Answer
If it's drupal 8, which sounds like it, your libraries folder needs to be **outside** of the sites folder. Where you main Drupal stuff is, like the modules folder.

ex: Needs to be `drupal/libraries` and not `drupal/sites/libraries`

The `drupal/sites/libraries` is only for Drupal 7.
> 0 votes

---
Tags: 7
---


# Question
Title: How can I check if a select field has been used with states?
I have a form where I'd like to hide a fieldset until the user has used a select (which option doesn't matter).

So far I've the following code:

```
$form['location'] = array(
  '#type' => 'select',
  '#options' => $locations,
  '#required' => true,
);

$form['uploads'] = array(
  '#type' => 'fieldset',
  '#title' => 'Foobar',
  '#states' => array(
    'visible' => array(
      'select[name="location"]' => array('empty' => false)
    )
  )
);

```

Apparently *empty*, *checked*, *filled* don't do the trick. If I check for one specific value with the following code works.

```
'#states' => array(
  'visible' => array(
    'select[name="location"]' => array('value' => 'foo')
  )
)

```

But what would be the solution for the check if *any value* has been selected?

# Answer
> 13 votes
I haven't tried it but a simple negate on an empty string might work:

```
'#states' => array(
  'visible' => array(
    'select[name="location"]' => array('!value' => '')
  )
)

```

---
Tags: 7, forms
---


# Question
Title: Flush cache on specific drupal 8 page/route
I am building a CRUD form in Drupal 8. Users get navigated to it from a list that shows the entities they are editing. After an edit or add they get redirected to the list again. The list is generated in a twig template that is being cached. It's a custom route/controller.

How do i invalidate/delete the cache on that specific list page/route after an edit/add of an entity?

The data in the list is build in custom action, it's no view, and as far as drupal knows, there are no nodes shown in the template. So no default cache functions are triggered.

# Answer
> 1 votes
AFAIK, cache invalidation should not depend on the page or route. When an entity (eg. node #5) is changed, it should in validate all caches tagged with "node:5". If the list of entities is correctly tagged with its cache dependencies, you should be fine.

I realize this answer is rather theoretical and not very specific. Hopefully other answers will be more detailed.

---
Tags: theming, 8, caching
---


# Question
Title: Rewrite output of a field and include another one templated
As a newbie with Drupal 7, I'm wondering if it is possible to rewrite the output of a field, including another field **templated**.

Right now, my rewrite looks like :

```
[field_a] [field_b]

```

And it is displaying field\_b as a raw value and not using its template.

Is it possible to display \[field\_b\] using its template ?

Thanks !

# Answer
> 0 votes
As you might excluded the field from display which bypasses the template file that build the display of the field.

So you have to use .tpl file to build the markup you need or put the markup in the rewrite which is not the best solution but may be accepted if you just write simple markup of one tag and classes to let css style apply.

---
Tags: 7
---


title: Select node if there periods overlap

text:
# Question
Title: Select node if there periods overlap
I have a content type that has a start\_date and end\_date fields.

I need to make a view with a filter: start\_period - end\_period

The view should select all nodes where the two periods overlap, for example:

node: 1 jan 2015 - 31 Dec 2015

filter values to select this node could be: 1 oct 2014 - 1 feb 2015 1 oct 2014 - 1 mar 2016 1 apr 2015 - 1 may 2015 1 apr 2015 - 1 mar 2016

Filter values that do not select the node could be: 1 oct 2014 - 1 dec 2014 1 jan 2016 - 1 mar 2016

Is there a module to do that? thank you in advance

# Answer
Try contextual range filter module that lets you define a range filter applies that rule

> Start value \<= Filter value \>= End value.

For your case you have to define two filters.

for start date with that rule

> filter start date \<= node start date \>= filter end date.

for end date with that rule

> filter start date \<= node end date \>= filter start date.
> 0 votes

---
Tags: 7, views, datetime
---