# Question
Title: Why multilingual site url is not working in production site?
I have multilingual site such as `www.demo.com` and `bn.demo.com` it works fine at dev and local site. but when i deployed at production it's url language is not working.

When I hit www.demo.com it goes english site. and then when i hit bn.demo.com it should come at bangla site but the strings are not translated.

Surprisingly when I logged in then switch url the translated string works fine. Why it does not works at logged out situation? how can I resolve it?

And my .htaccess files and rewrite condition

```
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^(www|bn)\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

# Answer
Just a beginner's suggestion... when you migrate your site, did you turn off clean URLs, clear cache and put into maintenance mode before migrating? If not, I suggest you try that then turn back on clean URLs, and take out of maintenance mode.
> 0 votes

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


# Question
Title: In views, how can you link "read more" to the webform submission?
I have created a view from webform submissions but some of the answer in the submission are too long. I tried to add a "read more" link in the view to be able to view the rest of the answer but I'm not sure which path to give it. When I do node/\[nid\], as you would with a content type, it goes back to the blank webform.

# Answer
I believe the link should be `node/%nid/submission/%sid/view`.

Where `%sid` is the webform submission id.
> 0 votes

---
Tags: 7, views, webforms
---


# Question
Title: Superfish themable hooks not getting called
According to superfish.module these following theme hooks are available.

```
 function theme_superfish($variables) {

    function theme_superfish_build($variables) {

    function theme_superfish_menu_item($variables) {

    function theme_superfish_menu_item_link($variables) {

```

but for some reason using these in my template.php only theme\_superfish is getting called.

```
function nph_superfish($variables){
 dpm("nph_superfish");

        dpm($variables);

  return "HTML";
}

```

works

```
function nph_superfish_menu_item_link($variables) {
dpm("theme_superfish_menu_item_link");
      $menu_item = $variables['menu_item'];
      $link_options = $variables['link_options'];
      return l($menu_item['link']['title'], $menu_item['link']['href'], $link_options);
    }

```

doesn't work

This post is probably the most comprehensive to answer the question for what I am trying to achieve (I want to add classes to menu items based on the title). Any ideas what might be happening?

UPDATE:

I just noticed a setting on the settings page, not mentioned in any of the answers I found around the web....

UPDATE: I've just noticed it says Default:enabled ..., so by checking it I'm disabling it...

# Answer
> 0 votes
As in my image

Make sure these are checked or the theme hooks wont work, and they need to be checked even though, it says default:enabled.

---
Tags: 7, navigation
---


title: Conditionals of a User Role

text:
# Question
Title: Conditionals of a User Role
I have a webform where there are conditional elements that are reliant on the user being a bona fide affiliate of our organisation. Both Anonymous and Authenticated users can use this form.

I currently have it using the CiviCRM elements to look for an existing contact in order to fulfill the conditional; however we have found that if we have had contact with the user (ie they previously were bona fide, or have submitted other forms in the past) then the conditional is fulfilled.

(Yes, that is kind of obvious.... we overlooked it)

I think I have three options;

1. Have a webform field, hidden, pertaining to the user role. this can then be used as a conditional.
2. Use a Workflow Rule to redirect users with particular roles to a different, but identical, webform. Then I would have two webforms each witht eh appropriate elements.
3. Completely remove the connection to CiviCRM for the webform and rely on our staff to filter the wheat from the chaff.

**Option 1** is probably the most logical solution in my mind, but I can not find a way to poll Drupal for the user role.

# Answer
I'd recommend using hook\_form\_alter and user\_has\_role in a custom module. It allows you to alter the form programmatically and perform logic in your hook function so you can access your user's role and modify your fields that way. For example, you could do something like:

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='your_form') {
     global $user;
     if (user_has_role(your_rid)){
       // add the extra field you need here
     }
  }
}

```

there are many examples on how to modify/add fields in the hook docs link above, plus you can google more tutorials on that.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How to change a field type from Integer to Decimal?
I have a content type with an integer content field. The field needs to contain float data. What's the easiest way to change the field type from integer to decimal? (There are thousands of existing nodes I will have to convert).

---

I've found a solution in this comment and this comment. Is it the best?

# Answer
Just to merge all the previous suggestions into one convenient chunk:

```
// Change this to your field name, obvs.
$field = 'field_myfieldname';

// Update the storage tables
$tables = array('field_data', 'field_revision');
foreach ($tables as $table) {
  $tablename = $table .'_'. $field;
  $fieldname = $field .'_value';
  db_change_field($tablename, $fieldname, $fieldname, array(
    'type' => 'numeric',
    'precision' => 10,
    'scale' => 2,
    'not null' => FALSE,
  ));
}

// Fetch the current field configuration
$field_config = db_query("SELECT data FROM {field_config} WHERE field_name = :field_name", array(
    ':field_name' => $field,
  ))
  ->fetchObject();
$data = unserialize($field_config->data);

// Update the settings entry
$data['settings'] = array(
  'precision' => 10,
  'scale' => 2,
  'decimal_separator' => '.',
);

// Store the new field config, update the field type at the same time
db_update('field_config')
  ->fields(array(
    'data' => serialize($data),
    'type' => 'number_decimal',
  ))
  ->condition('field_name', $field)
  ->execute();

// If you are confident about what bundles have instances of this field you can
// go straight to the db_query with a hardcoded entity_type / bundle.
$instances = field_info_field_map();
foreach ($instances[$field]['bundles'] as $entity_type => $bundles) {
  foreach ($bundles as $bundle) {

    // Fetch the field instance data
    $field_config_instance = db_query("SELECT data FROM {field_config_instance}
                                       WHERE field_name = :field_name
                                       AND entity_type = :entity_type
                                       AND bundle = :bundle", array(
        ':field_name' => $field,
        ':entity_type' => $entity_type,
        ':bundle' => $bundle,
      ))
      ->fetchObject();
    $data = unserialize($field_config_instance->data);

    // Update it with the new display type
    $data['display']['default']['type'] = 'number_decimal';

    // Store it back to the database
    db_update('field_config_instance')
      ->fields(array('data' => serialize($data)))
      ->condition('field_name', $field)
      ->condition('entity_type', $entity_type)
      ->condition('bundle', $bundle)
      ->execute();

  }
}

```
> 10 votes

# Answer
A better approach might be to use Drupal's built-in capability to alter the field type, db\_change\_field().

```
db_change_field('field_data_field_number', 'field_number_value', 'field_number_value', array(
  'type' => 'numeric',
  'precision' => 10,
  'scale' => 2,
  'not null' => FALSE,
));

```
> 5 votes

# Answer
I just wrote some code that should handle this for you in my Helper module: http://cgit.drupalcode.org/helper/tree/lib/FieldChangeHelper.php?h=7.x-1.x

```
FieldChangeHelper::changeType('my_int_field_name', 'number_decimal');

```

It should work fine for most simple cases and fields, but should be tested thoroughly. It also currently doesn't update any field formatters, so you'll want to review the display configuration for the field after running this.
> 4 votes

# Answer
Dave Reids drupal.org/project/helper module above is a good simple solution.

Can't add comment above so posting steps here.

1) Download and enable Helper module

2) Create a new file: changeIntField.php

```
<?php
FieldChangeHelper::changeType('my_int_field_name', 'number_decimal');
?>

```

3) Save file in root folder where drupal is installed

4) drush scr changeIntField.php

5) Delete file changeIntFiled.php as you no longer need it.

6) Edit display format for node/entity where field is being used.

7) Edit Views - where the field is used and fix display format settings here as well.
> 4 votes

# Answer
Changing the type of a Drupal 7 content field from integer to decimal is quite simple. There is no need to create a new field and then copy definitions. I've used the following three steps:

1. Find the name of the field's table and the name of the field in that table where the field's value is stored, using MySQL.
2. Use the MySQL alter statment to alter the field's datatype:
`ALTER TABLE field_data_field_myfield MODIFY field_myfield_value decimal(10,2) ;`
3. Change the field definitions in Drupal:
`UPDATE field_config SET type = 'number_decimal' WHERE field_name = 'field_myfield';`

Steps 1-3 are enough. Although, in certain cases it might be beneficial to compare the properties of an integer and a decimal fields on the field\_config table to see if there is anything else which needs to be changed: `SELECT id, field_name, type, CONVERT(data USING utf8) FROM field_config WHERE type like 'number_%'`.
> 2 votes

# Answer
Note that there is another table for each field which is called field\_revision\_field\_{field\_name} and this table mysql column type should also change

Also decimal field has different settings which should be set, use the following script to unserialize field settings modify it and then serialize it again. There are two table field\_config and field\_config\_instance. the following is for field\_config

```
$s = unserialize('field_config table serialize string');

$s['settings'] = array (
    'precision' => '20',
    'scale' => '0',
    'decimal_separator' => '.',
);

print serialize($s);

```

here is for field config instance :

```
$s = unserialize('field_config_instance table serialize string');

$s['display']['default']['type'] = 'number_decimal';

print serialize($s);

```

NOTE : fields may may more than one instance, and the next code should be used for all instances.

Now clear Drupal's cache and head to field settings , edit the field and save it. If you receive no error you're probably good to go :)
> 2 votes

# Answer
I had to change a field called "field\_margin\_percentage" to a decimal

Step 1 - Updated the database fields

```
db_change_field('field_data_field_margin_percentage', 'field_margin_percentage_value', 'field_margin_percentage_value', array(
  'type' => 'numeric',
  'precision' => 10,
  'scale' => 2,
  'not null' => FALSE,
));

```

Step 2 - Update the field\_config so the field knows the correct handler

```
db_query("UPDATE field_config SET type = 'number_decimal' WHERE field_name = 'field_margin_percentage'");

```

Step 3 - Get the existing 'data' column from field\_config and add the decimal settings

```
$current_field_config = 'a:7:{s:12:"translatable";s:1:"0";s:12:"entity_types";a:0:{}s:8:"settings";a:0:{}s:7:"storage";a:5:{s:4:"type";s:17:"field_sql_storage";s:8:"settings";a:0:{}s:6:"module";s:17:"field_sql_storage";s:6:"active";s:1:"1";s:7:"details";a:1:{s:3:"sql";a:2:{s:18:"FIELD_LOAD_CURRENT";a:1:{s:34:"field_data_field_margin_percentage";a:1:{s:5:"value";s:29:"field_margin_percentage_value";}}s:19:"FIELD_LOAD_REVISION";a:1:{s:38:"field_revision_field_margin_percentage";a:1:{s:5:"value";s:29:"field_margin_percentage_value";}}}}}s:12:"foreign keys";a:0:{}s:7:"indexes";a:0:{}s:2:"id";s:3:"161";}';

$s = unserialize($current_field_config);

$s['settings'] = array (
    'precision' => '10',
    'scale' => '2',
    'decimal_separator' => '.',
);

print serialize($s); // This will give you the new value for the data column (see below)

```

Step 4 - Get the existing 'data' column from field\_config\_instance and add the decimal settings

```
$s = unserialize('a:7:{s:5:"label";s:17:"Margin Percentage";s:6:"widget";a:5:{s:6:"weight";s:2:"13";s:4:"type";s:6:"number";s:6:"module";s:6:"number";s:6:"active";i:0;s:8:"settings";a:0:{}}s:8:"settings";a:7:{s:3:"min";s:1:"0";s:3:"max";s:3:"100";s:6:"prefix";s:0:"";s:6:"suffix";s:0:"";s:26:"commerce_user_profile_pane";i:0;s:35:"commerce_user_profile_pane_required";i:0;s:18:"user_register_form";b:0;}s:7:"display";a:1:{s:7:"default";a:5:{s:5:"label";s:5:"above";s:4:"type";s:14:"number_integer";s:6:"weight";s:2:"12";s:8:"settings";a:4:{s:18:"thousand_separator";s:1:" ";s:17:"decimal_separator";s:1:".";s:5:"scale";i:0;s:13:"prefix_suffix";b:1;}s:6:"module";s:6:"number";}}s:8:"required";i:0;s:11:"description";s:115:"The Paddy\'s Seals % of this sale. You can enter this OR the Margin Value. The other one will be calculated for you.";s:13:"default_value";a:1:{i:0;a:1:{s:5:"value";s:1:"0";}}}');

$s['display']['default']['type'] = 'number_decimal';

print serialize($s);

```

Step 5 - Use the above serialized strings to update your 'data' columns in field\_config and field\_config\_instance

```
db_query('update field_config set data=\'a:7:{s:12:"translatable";s:1:"0";s:12:"entity_types";a:0:{}s:8:"settings";a:3:{s:9:"precision";s:2:"10";s:5:"scale";s:1:"2";s:17:"decimal_separator";s:1:".";}s:7:"storage";a:5:{s:4:"type";s:17:"field_sql_storage";s:8:"settings";a:0:{}s:6:"module";s:17:"field_sql_storage";s:6:"active";s:1:"1";s:7:"details";a:1:{s:3:"sql";a:2:{s:18:"FIELD_LOAD_CURRENT";a:1:{s:34:"field_data_field_margin_percentage";a:1:{s:5:"value";s:29:"field_margin_percentage_value";}}s:19:"FIELD_LOAD_REVISION";a:1:{s:38:"field_revision_field_margin_percentage";a:1:{s:5:"value";s:29:"field_margin_percentage_value";}}}}}s:12:"foreign keys";a:0:{}s:7:"indexes";a:0:{}s:2:"id";s:3:"161";}\' where field_name=\'field_margin_percentage\'');

db_query('update field_config_instance set data=\'a:7:{s:5:"label";s:17:"Margin Percentage";s:6:"widget";a:5:{s:6:"weight";s:2:"13";s:4:"type";s:6:"number";s:6:"module";s:6:"number";s:6:"active";i:0;s:8:"settings";a:0:{}}s:8:"settings";a:7:{s:3:"min";s:1:"0";s:3:"max";s:3:"100";s:6:"prefix";s:0:"";s:6:"suffix";s:0:"";s:26:"commerce_user_profile_pane";i:0;s:35:"commerce_user_profile_pane_required";i:0;s:18:"user_register_form";b:0;}s:7:"display";a:1:{s:7:"default";a:5:{s:5:"label";s:5:"above";s:4:"type";s:14:"number_decimal";s:6:"weight";s:2:"12";s:8:"settings";a:4:{s:18:"thousand_separator";s:1:" ";s:17:"decimal_separator";s:1:".";s:5:"scale";i:0;s:13:"prefix_suffix";b:1;}s:6:"module";s:6:"number";}}s:8:"required";i:0;s:11:"description";s:115:"The Paddy-s Seals % of this sale. You can enter this OR the Margin Value. The other one will be calculated for you.";s:13:"default_value";a:1:{i:0;a:1:{s:5:"value";s:1:"0";}}}\' where field_name=\'field_margin_percentage\'');

```
> 1 votes

# Answer
Here's how I did it Drupal 7 in an update\_hook\_N().

The plan was to change one field called "field\_ui\_current\_salary" from DECIMAL(10) to DECIMAL(10,2) which would allow 2 decimal points for the values instead of no decimals at all!

```
/**
 * Changing Database Currenty Salary field to allow decimals.
 * Replace MYMODULE with your module's name and number N with your next incremented value.
 */
function MYMODULE_update_7001() {
  // field_ui_current_salary scale = 2 in field_config table.
  // Use your 'data' value for $new_data from 'field_config' table for your field and just change where 'scale' is from 0 to 2 (or your desired number of decimals)
  $new_data = 'a:8:{s:12:"entity_types";a:0:{}s:17:"field_permissions";a:1:{s:4:"type";i:0;}s:7:"indexes";a:0:{}s:8:"settings";a:5:{s:3:"max";d:99999999.989999995;s:3:"min";d:-99999999.989999995;s:9:"precision";i:10;s:16:"profile2_private";b:0;s:5:**"scale";i:2;**}s:12:"translatable";i:0;s:7:"storage";a:5:{s:4:"type";s:17:"field_sql_storage";s:8:"settings";a:0:{}s:6:"module";s:17:"field_sql_storage";s:6:"active";s:1:"1";s:7:"details";a:1:{s:3:"sql";a:2:{s:18:"FIELD_LOAD_CURRENT";a:1:{s:34:"field_data_field_ui_current_salary";a:2:{s:6:"amount";s:30:"field_ui_current_salary_amount";s:8:"currency";s:32:"field_ui_current_salary_currency";}}s:19:"FIELD_LOAD_REVISION";a:1:{s:38:"field_revision_field_ui_current_salary";a:2:{s:6:"amount";s:30:"field_ui_current_salary_amount";s:8:"currency";s:32:"field_ui_current_salary_currency";}}}}}s:12:"foreign keys";a:0:{}s:2:"id";s:3:"372";}';
  db_query('UPDATE {field_config} SET data = :new_data WHERE field_name = :salary;', array(':new_data' => $new_data, ':salary' => 'field_ui_current_salary'));

  // field_data_field_ui_current_salary and its revision copy -> DECIMAL(10,2)
  db_query("ALTER TABLE {field_data_field_ui_current_salary} MODIFY field_ui_current_salary_amount DECIMAL(10,2);");
  db_query("ALTER TABLE {field_revision_field_ui_current_salary} MODIFY field_ui_current_salary_amount DECIMAL(10,2);");

  cache_clear_all();
}

```
> 0 votes

# Answer
The original question was regarding Drupal 7, but I suspect a lot of people are wondering how to do this in Drupal 8. Unfortunately, there isn't any good method for this at the moment. The least bad option is to simply delete the field (and any data it contains) and let Drupal recreate it from scratch.

I'm trying to find a better solution and will post here if and when it's available: https://www.drupal.org/node/2843108
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: How to embed fields from a view to another view´s exposed filter
I am stuck with this problem. I created a view (type=term) with exposed filter. Thanks to http://leanderlindahl.se/en/dynamically-filter-content-drupal-view/ I managed to display the exposed filter as a list of "buttons."

Now I want to display fields of content with these taxonomy terms in the exposed filter.

My knowledge of php is very limited, sorry for newbie mistakes. I learn new things every day.

my .module:

```
function exposedfilter_buttons_form_alter(&$form, &$form_state, $form_id) {
if ($form['#id'] == 'views-exposed-form-test-lektori-page') {
$form['#attached']['js'] = array(
  drupal_get_path('module', 'exposedfilter_buttons') . '/js/exposedfilter_buttons.js',
);
$links = $form['tid']['#options'];
$newlinks = array();
$my_value = views_get_view_result('lektori', 'block_1'); //trying to obtain results of the second view

foreach ($my_value as $key => $result) { //trying to assing results to $key
}
foreach ($links as $tid => $term_name) {
if (taxonomy_term_depth_get_by_tid($tid) == 1) {
   $newlinks[] = array('data' => '<span class="filter-tab"><a href="" id="' .$tid . '">' . $term_name .'  ' . $key . /*so we directly see its value for control */' '. $my_value[$key]->node_field_data_field_workshop_lektor_title . '</a></span>', 'class' => array('pop-filter-label'));
}
}

$prefix = theme(
  'item_list', array(
  'items' => $newlinks,
  'type' => 'ul',
  'attributes' => array('id' => 'pop-filter-list'),
  'container_id' => 'scope-list-wrapper',
));

$form['links'] = array(
  '#type' => 'markup',
  '#value' => $prefix,
  '#markup' => $prefix,
);
}
// extra submit form handle
$form['#submit'][] = 'exposedfilter_buttons_form_submit';
}
// handle form submition
function exposedfilter_buttons_form_submit($form, &$form_state){
$values = $form_state['values'];
}

```

What I need: $my\_value\[$key\]-\>node\_field\_data\_field\_workshop\_lektor\_title should have $key obtained as a value 0 or 1 or 2.... so it will display correct name according to $key.

Image to make things more clear:

Any help is highly appreciated.

# Answer
So this finaly worked for me. Ruben, once more many thanks for your help - it put me on a right path.

```
$my_value = views_get_view_result('lektori', 'block_1');
$view_results = array_keys($my_value);
foreach ($links as $tid => $term_name) {
if (taxonomy_term_depth_get_by_tid($tid) == 1) {
     $key = each($view_results);
     $actual_key = current($key);
    $newlinks[] = array('data' => '<span class="filter-tab"><a href="" id="' .$tid . '">' . $term_name .' ' . $actual_key . '   '. $my_value[$actual_key]->node_field_data_field_workshop_lektor_title . '</a></span>', 'class' => array('pop-filter-label'));
}
}

```
> 1 votes

# Answer
I think you made a mistake in the foreach loop:

```
foreach ($my_value as $key => $result) { //trying to assing results to $key
}
foreach ($links as $tid => $term_name) {
if (taxonomy_term_depth_get_by_tid($tid) == 1) {
   $newlinks[] = array('data' => '<span class="filter-tab"><a href="" id="' .$tid . '">' . $term_name .'  ' . $key . /*so we directly see its value for control */' '. $my_value[$key]->node_field_data_field_workshop_lektor_title . '</a></span>', 'class' => array('pop-filter-label'));
}

```

should be something like

```
$view_results = array_keys($my_value);
foreach ($links as $tid => $term_name) {
  if (taxonomy_term_depth_get_by_tid($tid) == 1) {
    $key = each($view_results);
    $newlinks[] = array('data' => '<span class="filter-tab"><a href="" id="' .$tid . '">' . $term_name .'  ' . $key . /*so we directly see its value for control */' '. $my_value[$key]->node_field_data_field_workshop_lektor_title . '</a></span>', 'class' => array('pop-filter-label'));
  }
}

```
> 1 votes

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


# Question
Title: Views, Taxonomy, Block and Context... What am I doing wrong?
**What I want:**
When I navigate to a page... Of a certain Content Type... which is tagged with a Term... I want a Block created via Views should generate a list of pages with that Term.

I've adjusted my setup to key off of Articles with a Taxonomy: Sports and Terms: Golf, Hockey, Etc.

**Setup**
I have a Content Type "Article" with the fields (amoungst others):

```
Title
Portal (Term - Singular term allowed)

```

I have a Views Taxonomy filter setup such that given a context of a Term, it should filter into a list of pages that have that Term (Code at bottom of question) ...

It works when setup as a page, and in the "Preview" section (As shown in the picture). It doesn't work when moved into an block.

**What's showing:**
Notice the "Sports: Golf" yet the Sports List shows ALL portal pages (Not filtered). The Article is tagged, but the list isn't getting the "context". If I was to scroll down, all "Sports Pages" would be shown, but I only want those listed in the given context (golf in this example).

**Edit**
It's mentioned to use "Taxonomy ID By URL"... this doesn't work. There is no "Taxonomy" in the URL - Either stock node/# or via URL Alias myip/portal/safety/home (pathauto alias that has the term NAME in it... but not the ID. portal/8/home isn't very "pretty" and I'm not sure that would work either, although I may try)

Okay... I adjusted the auto alias via pathauto... making it portal/8/home (\[node:term:vocabulary\]/\[node:tid\]/\[node:title\]) still doesn't work. that Alias points to node/# and that still doesn't resolve into a "Term via URL" since there is no term in the URL.

Various attempts to make a relationship have been unsuccessful as well.

I don't want to go to "Content Type as a Term" - where each Portal has it's own content type - but at this point... if I want to move forward I may have too.

**View Export**

```
$view = new view;
$view->name = 'content';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Content';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Portal List';
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
);
$handler->display->display_options['style_options']['override'] = 1;
$handler->display->display_options['style_options']['sticky'] = 0;
$handler->display->display_options['style_options']['empty_table'] = 0;
$handler->display->display_options['exposed_block'] = TRUE;
/* Field: Taxonomy: Term */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['external'] = 0;
$handler->display->display_options['fields']['name']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = 0;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = 0;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Sort criterion: Taxonomy: Term */
$handler->display->display_options['sorts']['name']['id'] = 'name';
$handler->display->display_options['sorts']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['sorts']['name']['field'] = 'name';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
/* Contextual filter: Taxonomy: Term */
$handler->display->display_options['arguments']['name']['id'] = 'name';
$handler->display->display_options['arguments']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['name']['field'] = 'name';
$handler->display->display_options['arguments']['name']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['name']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['name']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['name']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['name']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['name']['glossary'] = 0;
$handler->display->display_options['arguments']['name']['limit'] = '0';
$handler->display->display_options['arguments']['name']['transform_dash'] = 0;
$handler->display->display_options['arguments']['name']['break_phrase'] = 0;
$handler->display->display_options['arguments']['name']['add_table'] = 0;
$handler->display->display_options['arguments']['name']['require_value'] = 0;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'portal' => 'portal',
);

/* Display: Portal List */
$handler = $view->new_display('block', 'Portal List', 'portal_list');
$handler->display->display_options['display_comment'] = 'Displays a list of pages for a given Taxonomy Term Context
';
$handler->display->display_options['block_description'] = 'Portal';
$translatables['content'] = array(
  t('Master'),
  t('Portal List'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('All'),
  t('Portal'),
);

```

# Answer
> 1 votes
I've actually moved on from this into a module "node hierarchy" which when paired with path-auto and menu-block does wonders.

But for the Views... the issue was solved with the right "relationships". Either a relationship on the Taxonomy ID, description or title... against the field on the node. I don't have it in front of me, but if requested I still have it in my notes somewhere.

# Answer
> 2 votes
The fundamental "problem" is that block displays don't get the argument from the url, which is fine. So you need to provide a way to give the block display the argument from url. Wait there is just the nid in the url.

So there is the wonderful thing called "default argument", which you can configure in the argument which allows you to bring any kind of arguments into. What you need is "taxonomy: term from url" and that's it.

# Answer
> 0 votes
I had to do all of the above AND remove the third argument from my views\_embed\_view function call:

```
<?php print views_embed_view('recommended_documents', 'three', **$node->id**); ?>

```

I believe the arguments from the third onwards become the contextual filters values that are checked against, which we're looking to override with the URL.

---
Tags: views, taxonomy-terms, blocks, 7
---


# Question
Title: Get node_type entity for default value in form
I'm attempting to allow users to enter a number of node types in an entity reference field inside a custom config form. However I can't seem to supply it with a proper default value. My field in the form looks like this:

```
$config = $this->config('contentform.settings');
    $form['content_types'] = [
        '#type'          => 'entity_autocomplete',
        '#description'   => t('Choose what content types to map'),
        '#target_type'   => 'node_type',
        '#default_value' => $config->get('content_type'),
    ];

```

However $config-\>get('content\_type') only supplies me with the label of the content type.

So I get the following error

> InvalidArgumentException: The #default\_value property has to be an entity object or an array of entity objects

I'm saving the value in the submit function like so:

```
    $content_type = $form_state->getValue('content_types');
    $this->config('contentform.settings')
         ->set('content_type', $content_type)
         ->save();

```

I've also tried $form\_state-\>get('content\_types') and $form\_state-\>get('content\_types')-\>entity; But those didn't work either.

How would I get the node\_type entity or object instead of just the label? Or is there a way to load the node\_type from just the name?

# Answer
You can load a `node_type` entity by specifying the node type id

```
$node_type_entity = \Drupal\node\Entity\NodeType::load($node_type_id);

```

or if you have multiple node types an array of entities:

```
$node_type_entities = \Drupal\node\Entity\NodeType::loadMultiple($node_type_ids);

```
> 2 votes

---
Tags: 8, forms, entities
---


# Question
Title: Entity reference field dependent on entity reference in referenced entity of another entity reference field
I have a content type 'order' with 2 entity reference fields. One is a reference to another content type 'brand' and the other is a reference to a taxonomy term 'categories'.

Now the content type 'brand' has an entity reference field aswell, containing a selection of taxonomy term 'categories'.

When creating a new 'order' I can select a 'brand'. Now the second field with the 'categories' should only show taxonomy terms available (selected) for the selected 'brand'.

I have tried to achieve this with the second entity reference field (categories) to use a view.

In this view I configured the following:

Relations: \- Content using field\_categories \- Content referenced from field\_brand

This worked when I had only 1 brand, since this brand was not connected to all categories. But now with multiple brands, the view just returns all the terms used in ALL brands.

Any idea how to achieve what I try? Any help is very appreciated. Thank you!

# Answer
> 0 votes
This isn't easily possible at the moment with the standard widget/autocomplete API as it has no context from where it is referenced.

To get something like that, you need a custom widget, one that supports to pass an argument to the views query based on your current node and then you need to connect it with your other field so that setting/changing a value there sends an ajax request to update your other widget, which then needs to get that value and pass it along to the views selection plugin.

Some related core issues: * https://www.drupal.org/node/2776571 * https://www.drupal.org/node/2280479

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


title: Image style and loss of fidelity

text:
# Question
Title: Image style and loss of fidelity
There is at least one other question dealing with this, but I found no satisfactory explanation, let alone a solution.

My site used to deliver 800x600 native images hosted externally that were scaled by the browser and CSS. To improve the Google Page Speed, my client asked me to ingest and serve the images on the Drupal site and to size them on the server. So far, so good.

Now I am noticing a big degradation in quality - not good for a real estate site:

(this is slightly enlarged to better show the issue)

On the right is the old site with scaling/cropping done by Chrome from 800x600 down to 315x208, left is the new site with an image style using imagemagick set to 100% quality, doing the same size reduction and cropping. I tried the "resize" filter but that has the same issue and does not give me the desired results.

The images are not from a stale cache, the image field max size is 800x600, and the file on the server is unaltered and has the original size. It is definitely the image style filter that is causing this.

Previous recommendations were to increase the quality setting for the image toolkit (admin/config/media/image-toolkit), switch to imagemagick, and ensure that the max resolution of the image field does not cause scaling. I have done all that and don't see any improvement.

Any other suggestions?

# Answer
I was wrong about not pulling from a stale cache. Credit goes to Jeff who does not want it:

Changing a filter does not mean the image toolkit renders the image again. This only happens once the **/files/styles** folder is cleared out. Once I did this, the quality improved and I don't see a difference between old and new anymore.
> 2 votes

---
Tags: 7, media
---


# Question
Title: How do I redirect to an external URL without caching it?
I can't use a normal `RedirectResponse` \- Drupal prevent's it when it detects I'm redirecting to an external site. Instead I need to use a `TrustedRedirectResponse`, but this is a cacheable response - which I don't want.

# Answer
> 5 votes
**Disable caching in responses**

You can build the cacheable metadata and put max-age = 0 in it:

```
$build = [
  '#cache' => [
    'max-age' => 0,
  ],
];
$cache_metadata = \Drupal\Core\Cache\CacheableMetadata::createFromRenderArray($build);
$response->addCacheableDependency($cache_metadata);

```

If you want to put this in one line:

```
$response
 ->addCacheableDependency((new \Drupal\Core\Cache\CacheableMetadata())->setCacheMaxAge(0));

```

**Disable caching for anonymous requests**

Also you have to disable the page cache for anonymous requests

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

This is necessary no matter if you use a normal redirect response or one with drupal caching.

---
Tags: 8, caching, redirection
---


# Question
Title: Where to input hook_element_info_alter() to remove format description in date_popup form field?
I want to remove format description in date\_popup form field (code posted here). The solution requires me to implement hook\_element\_info\_alter() to add a process function to the element.

I found the code I was looking for, but being a novice, I don't know where to input it?

Could someone please guide me?

I have Drupal 7.53 with Date Module Version: 7.x-2.9 installed

Thanks

# Answer
You need to create a custom module.

You can follow this guide to creating your first module.

However you won't need any form code... just your element info alter, and process function. After enabling and clearing cache, you should see the desired behavior you are after.
> 1 votes

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


title: D8 -> D8 node migration

text:
# Question
Title: D8 -> D8 node migration
I assumed that, since migrate is now in core, migrating nodes from a Drupal 8 site to another Drupal 8 site would be baked in. However, it seems not so.

I have already exported all the node configuration: fields, storage, etc. How can I get the actual node content from a Drupal 8 site to another Drupal 8 site?

# Answer
As of Jan 11, 2017, there are still no Drupal 8 sources available, per Berdir, Mike Ryan, and others.

To follow along at home, see this issue: https://www.drupal.org/node/2607524
> 2 votes

---
Tags: nodes, 8, migrations
---


title: How to compare dates in a View?

text:
# Question
Title: How to compare dates in a View?
I'm trying to build a new View in Drupal 8. I want to display list of News. Each item has **field\_date** where is date (without time) stored. And second field is **body** with basic text information.

I'm trying to set FILTER CRITERIA to display only items with date \<= NOW(). It seems that it's impossible to enter this filter. There is no condition for it. Do you have idea how to enter this? This is filter what I see in modal window for new filter citerium

```
<select id="edit-options-operator" name="options[operator]" class="form-select">
  <option value="=" selected="selected">Je rovno</option>
  <option value="!=">Není rovno</option>
  <option value="contains">Obsahuje</option>
  <option value="word">Obsahuje jakékoliv slovo</option>
  <option value="allwords">Obsahuje všechna slova</option>
  <option value="starts">Začíná na</option>
  <option value="not_starts">Does not start with</option>
  <option value="ends">Končí na</option>
  <option value="not_ends">Does not end with</option>
  <option value="not">Neobsahuje</option>
  <option value="shorterthan">Délka je kratší než</option>
  <option value="longerthan">Délka je delší než</option>
  <option value="regular_expression">Regulární výraz</option>
  <option value="empty">Je prázdný (NULL)</option>
  <option value="not empty">Není prázdný (NOT NULL)</option>
</select>

```

(Sorry for Czech localization but you can still see key of each option :)

I thought that shorterthan we be right option, but it seems to be suitable only for string. I know that Drupal 8 is still in beta today but this problem must have some solution. I'm using already included core extension Datetime.

# Answer
> 1 votes
In Drupal 8.2.5 the option is available. See this picture:

---
Tags: 8, views, datetime
---


# Question
Title: Disable specific view display in drupal 8 via database or programmatically
I was modifying a display mode in my view and must have added a criteria which doesn't exist and when I saved my changes, I was immediately thrown to a wsod. After checking the logs, here is the error that I've found:

```
Exception: No entity type for field vid on view newsletters in Drupal\views\Plugin\views\HandlerBase->getEntityType() (line 697 of /home/admin/domains/zend8.sitesbycoop.com/public_html/core/modules/views/src/Plugin/views/HandlerBase.php).

```

Does anyone know of a way to disable this view mode via the database or programmatically so I'm not locked out of my view anymore?

Much appreciated!

# Answer
In D8 views are configuration.

If you can use the admin ui, go to `/admin/config/development/configuration/single/export`, choose *Configuration Type* `View` and the view you want to change, modify it and paste in the single import section.

If you can't access the admin ui, you can use drush:

```
drush cedit views.view.newsletters

```
> 1 votes

---
Tags: views
---


# Question
Title: Drupal 7: How can I get path for node or term in drupal with php code?
I must build a block that retrieves children of a specific term id by selecting it through $node-\>title of a page. So, I get it with taxonomy\_get\_termBy\_name. With this $term-\>tid I can get children of it by calling taxonomy\_get\_children(). Ok, it returns an array of children. For each child I must take name and path in order to build an . How can i retrieve these properties? I am unable to find a module that performs these operations, so I must build my own block.

# Answer
> 2 votes
You can use the l() function to do this.

Example:

```
$link = l('Link Title', 'node/' . $node_id);
$link = l('Link Title', 'taxonomy/term/' . $term_id);

```

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


# Question
Title: How do I add another field after saving entity metadata wrapper?
I'm trying to do something like this:

```
function create_content($type,$content){
  $node = entity_create('node', array('type' => $type));
  $emw_node = entity_metadata_wrapper('node', $node);
  $fields = field_info_instances("node",$type);
  foreach ($content as $field => $value){
    if (array_key_exists($field,$fields)){
      $type=field_info_field_by_id($fields[$field]['field_id'])['type'];
      if ($type=='link_field') {
        $emw_node->$field->url = $value;
      }
      else {
        $emw_node->$field = $value;
      }
    }
  }
  $emw_node->save();
  $id = $emw_node->getIdentifier();
  $emw_node->other_field = $id;
  $emw_node->save();
}

```

With the idea of copying the node id to another field. However, I get an error:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at node(9999)-\>field\_other\_field: 9999. in EntityMetadataWrapper-\>set() (line 122 of /sites/all/modules/entity/includes/entity.wrapper.inc).

How do I do this properly, preferably while still using an entity metadata wrapper?

# Answer
> 1 votes
The problem can be with your field format. If your field other\_field is a text field check what text format is set for it in admin/structure/types/manage/your\_content\_type/fields. EG:

If it is different from the plain text format you have to assign an array as a value to your field. EG:

```
$emw_node->other_field = array('value' => $id, 'format' => 'filtered_html');

```

or just

`$emw_node->other_field = array('value' => $id);`

---
Tags: entities
---


# Question
Title: Drupal jquery behaviors & views - Ajax multiple times / wrong arguments - triggerHandler('RefreshView')
I am having some problems using ajax to trigger an views update (D7).

Basically there is a map (leafletMap) and when it is moved/changed/zoomed, a function gets a list of node ids and triggers a views ajax refresh. Those node ids are passed into a contextual filter, so only matching packages in that view are displayed below the map.

The problem with the ajax is it often fires multiple ajax requests. When I inspect the extra requests one or two will have the correct arguments, but one will have the old arguments and then the view will refresh with the wrong nodes.

I've tried using `return false` and binding what I can to `this` or `context`. As you can see I've tried `unbind()`ing the `<div />` but nothing seems to help. Often the first set of ajax calls append the wrong view, but then the next one works. And so on. To be honest I'm a bit out of my depth.

Basically I need there to be one ajax call with the correct arguments, or at least multiple ajax calls that use the correct arguments.

Any hints, ideas or suggestions would be most welcome. Many thanks.

TLDR; The below code triggers an ajax refresh of a view. This view has a contextual filter. It is triggering multiple ajax requests, some of which retain the old ajax arguments & therefore refresh incorrectly. Thanks!

```
Drupal.behaviors.packageFilter = {
    attach: function (context, settings) {

      if (typeof window.leafletMap === 'undefined' || window.leafletMap.length == 0) {
        return;
      }
      this.leafletMap = window.leafletMap[0];
      this.leafletMap.$map.once(function () {
        this.leafletMap.map.on('moveend', this.refreshView.bind(this));
        return false;
      }.bind(this));
      // Reset arguments back to default when not filtering map.
      $.each(Drupal.settings.views.ajaxViews, function (key, value) {

        if (value.view_name === 'packages') {
          Drupal.settings.views.ajaxViews[key].view_args = '';
        }

      });
      $('.views-exposed-form-packages-search', context).attr('action', '/packages.json');
    },

    refreshView: function (context, settings) {

      Drupal.attachBehaviors('ViewsAjaxView');

      // This gets markers from the map and converts them to node ids
      var visibleMarkers = this.leafletMap.getVisibleMarkers();
      var totalMarkers = this.leafletMap.markers.length;

      // Do not run if map isn't filtered.
      if (visibleMarkers.length < totalMarkers) {

        var visibleMarkers = this.leafletMap.getVisibleMarkers();

        var nids = '';
        $.each(visibleMarkers, function (i, v) {
          nids += v.node.nid + '+';
        });
        nids = nids.slice(0, -1);

        // nids is an array of node ids for the view to return

        $.each(Drupal.settings.views.ajaxViews, function (key, value) {

          if (value.view_name === 'packages') {
            // this should add the node ids as an views ajax argument
            // to a contextual filter
            Drupal.settings.views.ajaxViews[key].view_args = nids;
          }

        });

        var throbber = '<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>';
        $('.views-submit-button').append(throbber);

        $.each(Drupal.settings.views.ajaxViews, function (key, value) {

          if (value.view_name == 'packages' && value.view_args == nids) {
            $('.view-id-packages').triggerHandler('RefreshView');
          }

        });

        $('.view-id-packages').unbind();

      }
    }
  }

```

# Answer
For the sake of posterity & future visitors with this issue, here is how I eventually got it to work.

```
refreshView: function (context, settings) {
  // Unbind event to prevent multiple ajax refreshes.
  $('.view-id-packages').unbind();
  Drupal.attachBehaviors('ViewsAjaxView');

  // When map changes, update the grid of packages below the map.
  var visibleMarkers = this. leafletMap.getVisibleMarkers();

  // Get all the node IDs to pass into the views contextual filter.
  var nids = '';
  $.each(visibleMarkers, function (i, v) {
    nids += v.node.nid + '+';
  });
  nids = nids.slice(0, -1);

  // Update the Drupal ajax object to use our new set of node IDs.
  $.each(Drupal.settings.views.ajaxViews, function (key, value) {
    if (value.view_name === 'packages') {
      Drupal.settings.views.ajaxViews[key].view_args = nids;
    }
  });

  // Add the throbber on since it doesn't show automatically.
  var throbber = '<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>';
  $('.views-submit-button').append(throbber);
  // Trigger the ajax.
  $('.view-id-packages').triggerHandler('RefreshView');
}

```

---

And then my view \> advanced \> contextual filter looks like:
> 0 votes

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


# Question
Title: D7 Rules - Unable to get data value & Unable to evaluate action in custom module
I am working on a module that gets the order data upon commerce checkout completion and sends it to an api elsewhere for processing. In testing, everything was working fine until I called my method from my rule, which led me here.

I am wondering if my inexperience with Drupal has caused me to make an error in defining my rule. Any additional information that can point me in the appropriate direction is always welcome.

I have researched this topic rather intensely and did not find any solid remedy, please don't assume I have not searched. I assure you I have, I have been stuck on this issue for 4 days now :/ Thanks in advance.

Here is my rule:

```
function my_module_rules_action_info() {
  $actions = array();
  $actions['my_module_sync_inventory'] = array(
    'label' => t('Sync inventory'),
    'callbacks' => array(
      'execute' => 'my_module_rules_sync_inventory'
    )
  );
  return $actions;
}

```

and here are the defaults:

```
function my_module_default_rules_configuration() {
  $rules = array();
  $rule = rules_reaction_rule();
  $rule->label = t('Sync Inventory on Checkout');
  $rule->tags  = array('Commerce Cart', 'Commerce', 'Inventory', 'Sync');
  $rule->weight = 20;
  $rule->active = TRUE;
  $rule
    ->event('commerce_checkout_complete')
    ->action('my_module_sync_inventory');
  $rules['my_module_sync_inventory'] = $rule;
  return $rules;
}

```

this is the callback

```
function my_module_rules_sync_inventory() {
  global $user;
  $data = commerce_cart_order_load($user->uid);
  // ... process data
}

```

# Answer
For any future readers who encounter this issue:

It turns out the answer all along was using the `hook_commerce_checkout_complete` in my module, rather than trying to insert an action with rules.

Here is an example I used for debugging:

```
function MYMODULE_commerce_checkout_complete($order){
  $file = fopen("checkout_debug.json", "w") or die("Unable to open file!");
  fwrite($file, json_encode($order, JSON_PRETTY_PRINT));
}

```

of course the reason I used `json_encode` is because `$order` is not a string and I could pretty print it.

Hope it helps someone, eventually. Thanks again.
> 2 votes

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


# Question
Title: Why doesn't the following HTML/CSS code appear on Drupal sites?
The following HTML with CSS inline shows up correctly in the editor, but not when it's saved. what's the reason? I've checked it with Drupal 7 and Drupal 8 (if you wan't to quick-test it yourself: simplytest.me)

```
<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <title>Responsive CSS Tabs</title>

      <style>
      @import url("http://fonts.googleapis.com/css?family=Open+Sans:400,600,700");
@import url("http://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.css");
*, *:before, *:after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
}

body {
  font: 14px/1 'Open Sans', sans-serif;
  color: #111;
  background: #fafafa;
}

h1 {
  padding: 50px 0;
  font-weight: 400;
  text-align: center;
}

p {
  margin: 0 0 20px;
  line-height: 1.5;
}

main {
  min-width: 320px;
  max-width: 800px;
  padding: 50px;
  margin: 0 auto;
  background: #fff;
}

section {
  display: none;
  padding: 20px 0 0;
  border-top: 1px solid #ddd;
}

input {
  display: none;
}

label {
  display: inline-block;
  margin: 0 0 -1px;
  padding: 15px 25px;
  font-weight: 600;
  text-align: center;
  color: #bbb;
  border: 1px solid transparent;
}

label:before {
  font-family: fontawesome;
  font-weight: normal;
  margin-right: 10px;
}

label[for*='1']:before {
  content: '\f1cb';
}

label[for*='2']:before {
  content: '\f17d';
}

label[for*='3']:before {
  content: '\f16b';
}

label[for*='4']:before {
  content: '\f1a9';
}

label:hover {
  color: #888;
  cursor: pointer;
}

input:checked + label {
  color: #6EC8D7;
  border: 1px solid #ddd;
  border-top: 2px solid #6EC8D7;
  border-bottom: 1px solid #fff;
}

#tab1:checked ~ #content1,
#tab2:checked ~ #content2,
#tab3:checked ~ #content3,
#tab4:checked ~ #content4 {
  display: block;
}

@media screen and (max-width: 650px) {
  label {
    font-size: 0;
  }

  label:before {
    margin: 0;
    font-size: 18px;
  }
}
@media screen and (max-width: 400px) {
  label {
    padding: 15px;
  }
}

    </style>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

</head>

<body>
  <h1>Responsive CSS Tabs</h1>

<main>

  <input id="tab1" type="radio" name="tabs" checked>
  <label for="tab1">Codepen</label>

  <input id="tab2" type="radio" name="tabs">
  <label for="tab2">Dribbble</label>

  <input id="tab3" type="radio" name="tabs">
  <label for="tab3">Dropbox</label>

  <input id="tab4" type="radio" name="tabs">
  <label for="tab4">Drupal</label>

  <section id="content1">
    <p>
      Bacon ipsum dolor sit amet beef venison beef ribs kielbasa. Sausage pig leberkas, t-bone sirloin shoulder bresaola. Frankfurter rump porchetta ham. Pork belly prosciutto brisket meatloaf short ribs.
    </p>
    <p>
      Brisket meatball turkey short loin boudin leberkas meatloaf chuck andouille pork loin pastrami spare ribs pancetta rump. Frankfurter corned beef beef tenderloin short loin meatloaf swine ground round venison.
    </p>
  </section>

  <section id="content2">
    <p>
      Bacon ipsum dolor sit amet landjaeger sausage brisket, jerky drumstick fatback boudin ball tip turducken. Pork belly meatball t-bone bresaola tail filet mignon kevin turkey ribeye shank flank doner cow kielbasa shankle. Pig swine chicken hamburger, tenderloin turkey rump ball tip sirloin frankfurter meatloaf boudin brisket ham hock. Hamburger venison brisket tri-tip andouille pork belly ball tip short ribs biltong meatball chuck. Pork chop ribeye tail short ribs, beef hamburger meatball kielbasa rump corned beef porchetta landjaeger flank. Doner rump frankfurter meatball meatloaf, cow kevin pork pork loin venison fatback spare ribs salami beef ribs.
    </p>
    <p>
      Jerky jowl pork chop tongue, kielbasa shank venison. Capicola shank pig ribeye leberkas filet mignon brisket beef kevin tenderloin porchetta. Capicola fatback venison shank kielbasa, drumstick ribeye landjaeger beef kevin tail meatball pastrami prosciutto pancetta. Tail kevin spare ribs ground round ham ham hock brisket shoulder. Corned beef tri-tip leberkas flank sausage ham hock filet mignon beef ribs pancetta turkey.
    </p>
  </section>

  <section id="content3">
    <p>
      Bacon ipsum dolor sit amet beef venison beef ribs kielbasa. Sausage pig leberkas, t-bone sirloin shoulder bresaola. Frankfurter rump porchetta ham. Pork belly prosciutto brisket meatloaf short ribs.
    </p>
    <p>
      Brisket meatball turkey short loin boudin leberkas meatloaf chuck andouille pork loin pastrami spare ribs pancetta rump. Frankfurter corned beef beef tenderloin short loin meatloaf swine ground round venison.
    </p>
  </section>

  <section id="content4">
    <p>
      Bacon ipsum dolor sit amet landjaeger sausage brisket, jerky drumstick fatback boudin ball tip turducken. Pork belly meatball t-bone bresaola tail filet mignon kevin turkey ribeye shank flank doner cow kielbasa shankle. Pig swine chicken hamburger, tenderloin turkey rump ball tip sirloin frankfurter meatloaf boudin brisket ham hock. Hamburger venison brisket tri-tip andouille pork belly ball tip short ribs biltong meatball chuck. Pork chop ribeye tail short ribs, beef hamburger meatball kielbasa rump corned beef porchetta landjaeger flank. Doner rump frankfurter meatball meatloaf, cow kevin pork pork loin venison fatback spare ribs salami beef ribs.
    </p>
    <p>
      Jerky jowl pork chop tongue, kielbasa shank venison. Capicola shank pig ribeye leberkas filet mignon brisket beef kevin tenderloin porchetta. Capicola fatback venison shank kielbasa, drumstick ribeye landjaeger beef kevin tail meatball pastrami prosciutto pancetta. Tail kevin spare ribs ground round ham ham hock brisket shoulder. Corned beef tri-tip leberkas flank sausage ham hock filet mignon beef ribs pancetta turkey.
    </p>
  </section>

</main>

</body>
</html>

```

# Answer
> 0 votes
Check your "text filter", ideally this kind of stuff doesn't go into a text field and is stored as a CSS file. It's likely that the text filter is set to "Filtered HTML", which will strip anything that isn't basic text formatting html, images, etc.

The text filter that will allow this stuff through is "Full HTML"

---
Tags: theming, wysiwyg
---


# Question
Title: D7 errors given when authenticated user changes password but pwd still changes
I have a user role for content managers and I don't want to give them the permission to administer users. I do want them to have the ability to change their passwords so they aren't stuck with the temporary one I set them up with.

I have been able to add a link to their own 'edit profile' page on the default user landing page, and the link works and displays the change password form as expected. If they try to change their password, they are then given an access denied error because they are not authorized to view /admin/people, which is where they are sent after a password change.

HOWEVER: THE PASSWORD DOES GET CHANGED

So, it's confusing to the user because they think their password change has failed when it hasn't.

Is it possible to change what page they are directed to after a password change? I would prefer to send them back to their profile or even the homepage. (I would REALLY like to send them right to the content page so they can get to work.)

I would even settle for being able to edit the access denied error to better explain the situation to them.

# Answer
Something doesn't add up with what the information you have given. When a user edits their own profile, the default is to simply reload the same page.

You said that you have added a link on their profile (view) page, that points to the user edit page.

I'm guessing that the following is part of the link you've added:

destination=admin/people

If there is, then you need to remove this. Anytime there is a destination=\[SOMEPATH\] in the URL and a form is submitted, it will redirect the user to the path given in the URL.
> 2 votes

---
Tags: 7, users
---


# Question
Title: I want to filter to show orders that their ending date is today
I am using Drupal 7 and I have a webform where people can order a product and they enter the date that they will pick up that product. I want to make a view that will show me the poeple that are picking a product today, but when I try to make a filter for that the fields that are given are only the date that they submited the order not the date\_field. Here is a picture of which fields are given to select.

# Answer
In order to use webform fields in views filter/sort, you will need to add relationship with them. They should be available for relationship in the format or `Webform submissions: Data :XXX`.

Once you add them, you can further use them in filter/sort with more conditions. Hope it helps !!
> 0 votes

---
Tags: datetime, input-formats
---


# Question
Title: Restrict access for a specific forum to a specific user role
I am using Drupal 8 and the core Forum module.

I have several forums on a site.

I wish to restrict access for some of the forums based on the role of the user.

eg:

```
Forum A: 'Moderator' and 'Role A' can access ('Role B cannot access')
Forum B: 'Moderator' and 'Role B' can access ('Role A cannot access')

```

I cannot seem to find a way to do this and am having trouble finding a straight answer about how to do it online.

# Answer
Taxonomy Access Control Lite is a good module to achieve this.

> This node\_access module governs access to nodes based on the taxonomy terms applied to the nodes. A simple scheme based on taxonomy, roles and users controls which content is visible.
>
> As the name implies, this module shares some functionality with an earlier module called Taxonomy Access Control (TAC). If you are shopping around for an access control module to use, consider that one as well. See this module's README.txt for an explanation of "why yet another access control module".

I have implemented one of my site for same purpose.

You can also go for

Content Access and ACL modules.

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

One more Option Using Group module.

> The Group module allows you to create arbitrary collections of your content and users on your site and grant access control permissions on those collections
>
> Out of the box, Drupal only allows a person to view, create or edit the different content types you create. However, you might want to be able to let them view or edit all content types, but only in a specific section of the site.
> 2 votes

---
Tags: 8, nodes
---


# Question
Title: Link to node for each of the items in a view
I have a D8.2.0 website with a view showing unformatted list of content of certain content type. For each item in the content two field values are shown.

I want one of the fields to be a link to the content item node. I used `Rewrite Results > Output this field as a custom link` and put the following value:

```
/node/{{ node.id }}

```

But no luck. I also tried `nid`. I cannot seem to find a documentation or a blog post that discusses different values that can be used in twig-enabled fields in D8 views.

If possible please add references to documentation or posts that explain what variable names are available in addition to what is the correct way to use the node id by twig.

# Answer
> 4 votes
If you have option link to content you can check it:

Else you can:

1. Add new field "Content:Path"
2. Hide this new field from display
3. Place it before your desired linked field
4. Rewrite output of field with: `<a href="{{ path }}">{{ field_name }}</a>`

Step 3 is very important : field rewriting tokens needs to be placed before your field.

# Answer
> 2 votes
Firstly you need to add ID as a hidden field and then for the field you want to have link, just create REWRITE RESULTS for that as shown in below image:

# Answer
> 1 votes
If you want to add the link in the html with content text, then use below way. Case1:

1. Add the content text field.
2. Add html like( Read Post ) in text.

Case 2: If You want add link to the node page without using any html then Add field link to content and add the display text(ead more).

---
Tags: views, 8
---


# Question
Title: Is the MODULE.schema.yml required when you define the MODULE.settings.yml?
Is the `MODULE.schema.yml` required when you define the `MODULE.settings.yml`? It seems that it also works when I remove the `MODULE.schema.yml` file from install/schema.

# Answer
It is not absolutely required but **strongly** recommended to have one.

By default, Drupal doesn't validate the schema, but it does in tests and there is an issue that will enable it if you use the provided example.settings.local.php/development.services.yml. That's why you don't see an error right now when you install, but you'll see it when you write your first test.

It is currently used to ensure the saved configuration has the right data type (e.g. a float and not an integer); not doing that correctly can break stuff and the ability of translating the configuration. More things might follow later, for example a module that generates a settings form.
> 11 votes

# Answer
The settings.yml is only needed when you want to have default values to start with in your config after the module is installed.
> 1 votes

# Answer
`MODULE/config/install/MODULE.settings.yml` file is not mandatory.

`MODULE.settings.yml` file is basically used for configure default values. and that will only affect when you install module first time.

Two options available for reflect changes in `MODULE.settings.yml`:

1. Uninstall `MODULE` and Install it again!
2. Use `MODULE.install` file and `hook_update_N(&$sandbox)`

e.g. Filename: `MODULE/MODULE.install`

```
    /**
     * Write a line or two here about what the updates are for.
     * This is shown to users on the update.php page.
     */
    function mymodule_update_8001(&$sandbox) {
      $config_factory = \Drupal::configFactory();
      $default_value = 'Test';
      $config_factory->getEditable('MODULE.settings')->set('config_field_key', $default_value)->save();
    }

```

Reference Link
> 1 votes

---
Tags: 8, database
---


# Question
Title: How do I disable APC caching just changing any Drupal setting?
Is it possible to disable APC caching completely in Drupal 8 without modifying the php.ini settings (i.e. only by modifying the Drupal settings)?

# Answer
> 3 votes
There are multiple settings necessary to do so:

in active settings.php:

```
/**
 * Class Loader.
 *
 * If the APC extension is detected, the Symfony APC class loader is used for
 * performance reasons. Detection can be prevented by setting
 * class_loader_auto_detect to false, as in the example below.
 */
$settings['class_loader_auto_detect'] = FALSE;

// Default cache backend.
$settings['cache']['default'] = 'cache.backend.database'; // or any other alternative cache backend

```

After looking at Berdirs comment and diving further into code and looking at more usages of apcu within Drupal it appears to be pretty much impossible to catch every usage / and even if you manage to find all of them - disabling at some points is not possible (e.g. no configuration options present).

---
Tags: 8, caching
---


title: How to preprocess view field?

text:
# Question
Title: How to preprocess view field?
I have view with one date field. Now I want to preprocess this date field(lets say I want to change the date format).

Twig file override : **views-view-field--field\_date.html.twig**

Prepocess code I have tried but **kint** is showing me only **DEPTH TOO GREAT** value.

```
function my_sub_theme_preprocess_views_view_field__field_date(&$variables) {
    kint($variables['view']);
}

```

Please let me know how to preprocess this field. Is it possible to change date format in twig itself?

# Answer
The output of views field templates is flat markup. You can't change a render array like you can in field templates when rendering entities in view modes.

So if you want to change the output you have to start from scratch with the values that are in the database. In views field templates you can use the getValue() method from the field variable. As parameter you have to provide `row`:

```
{{ field.value(row) }}

```

The result is a single value or an array for multivalue fields.

## Example

**views-view-field--created.html.twig**

The raw value from `created` is a unix timestamp

```
Timestamp: {{ field.value(row) }}

```

You can use the timestamp for example to reformat the date with the date filter from twig:

```
Date: {{ field.value(row)|date("m/d/Y") }}

```
> 4 votes

# Answer
Yes. A date format can be changed from TWIG template itself. Look for more documentation on Date in Twig here - http://twig.sensiolabs.org/doc/2.x/filters/date.html

About **DEPTH TOO GREAT** of Twig. It's coming due to Kint having setting of less maxLevel than what is there in the variable you are trying to dump.

You can change DEPTH in same function itself by writing something like -

```
$_kintSettings['maxLevels'] = 10;

```
> 2 votes

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


# Question
Title: How to use a div class to wrap some selected fields of a grid views view
I have came through this:

but can't understand how to use a div class to wrap some selected fields of a grid views view. In my case, i want to wrap three fields of a view into a div class as the image shows below:

# Answer
> 13 votes
It's really simple by using the Field overwrites.

First, set the `(author) User: Picture` and `(author) User: Name` fields to "Exclude from display".

Then open the settings for `Content: Post date` field, and open "Rewrite results" fieldset.

Check "Rewrite output of this field". This will reveal another fieldset "Replacement Patterns" which should show you the tokens for all the fields above the current field. All you need to do is put a `<div>` wrapper in the textbox and copy the tokens you want in between the div tags.

# Answer
> 3 votes
you should use hook\_views\_pre\_render(&$views) or theme\_process\_views\_view\_field()

```
function YOUR_THEME_preprocess_views_view_fields(&$vars) {

  if ($vars['view']->name == 'view_name') {

    foreach( $vars['view']->result as $key => $value) {
      $add_start_div = '<div class="add_div">';
      $markup_for_field_name_1 = $value->field_name1[0]['rendered']['#markup'] ;
      $value->field_name1[0]['rendered']['#markup'] = $add_start_div . $markup_for_field_name_1;
      $markup_for_field_name_3 = $value->field_name3[0]['rendered']['#markup'];
      $add_end_div = '</div>';
      $value->field_name3[0]['rendered']['#markup'] = $value->field_name3[0]['rendered']['#markup'] . $add_end_div;
    }
  }
}

```

# Answer
> 2 votes
Create a template for rows style output for example: views-view-fields--frontpage-promoted-news-story--block.tpl.php . Look in views-\>advanced-\>themes for options. Copy and paste the name of the specificity of template you want and create a file with that name, then run 'rescan' so Drupal finds the new template.

Then do something like:

```
<?php
$field_vals = [];
foreach($fields as $id => $field){
    $field_vals[$id]= $field->content;
}
?>
<!-- layout fields -->
<div class="promoted-news-story">
<!-- image, title, date, body, link -->
    <div class="promoted-news-story__image-wrap">
        <?php print $field_vals['field_standard_header_image'];?>
    </div>
    <div class="promoted-news-story__content-wrap">
        <h2><?php print $field_vals['title'];?></h2>
        <?php print $field_vals['field_news_date'];?>
        <?php print $field_vals['body'];?>
        <?php print $field_vals['view_node'];?>
    </div>
</div>

```

# Answer
> 1 votes
Group some fields into views div .. Please find this module ( Views fieldsets ): https://www.drupal.org/project/views\_fieldsets

---
Tags: views
---


title: How to get webform to reply to sender?

text:
# Question
Title: How to get webform to reply to sender?
For some reason I'm stuck on this!

Is there a setting in webform so that I can simply click on reply when I receive and email from contact form?

Been out of the loop for a while for health reasons!

# Answer
> 0 votes
Found it:

webform/emails/

E-MAIL REPLY-TO DETAILS

Component: email

# Answer
> 1 votes
Set the from of the e-mail that is send to the e-mail that is used by the person submitting the webform. This is a token that you can use in the settings of your webform.

# Answer
> 1 votes
From 7.x-4.3 version the functionality to set the Reply-To header is included.

If you are below version 7.x-4.3 you can use this module https://www.drupal.org/project/webform\_reply\_to

---
Tags: webforms
---


# Question
Title: How to check if a term has a published content associated with it?
I have taxonomy term list called clients. I have managed to list all the terms on the taxonomy term list page by adding contents for each term, some contents are published some are not. what I want to do is check and remove the term page link for those terms whose contents are not published and display them without the link.

# Answer
There is an existing Question that handles this for views 2 and views 3: https://stackoverflow.com/questions/421972/how-to-display-only-taxonomy-terms-with-nodes-associated-to-in-views-2
> 4 votes

---
Tags: theming, 8
---


title: Page as homepage of subdomain

text:
# Question
Title: Page as homepage of subdomain
I have View page like example.com/abc and I need to create subdomain abc.example.com that will show this page, but not like abc.example.com/abc.

I need to looks like it's the homepage of this subdomain.

How I can do this? Do I need some additional configuration on hosting or htaccess? What is the best way to go?

# Answer
1. Install and enable domain module
2. Enable the submodule named **Domain Configuration**
3. Add a subdomain **abc.example.com** by clicking **Create domain**
4. Go to *admin/structure/domain/* and click on **edit domain** for abc.example.com
5. click the **Settings** tab
6. Set the value of the **Site frontpage** field to **abc**
> 1 votes

---
Tags: .htaccess, subsites
---


# Question
Title: Display the node edit form on a node view page
Can we show the node edit form in a custom block and show that on a node view page?

# Answer
You could use Form Block module and place the block above your view block. Some details about it (from its project page):

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks.

OR go with Clive's answer to this Q: Why doesn't loading a form in the view header work? and load the form in your View's header.
> 2 votes

---
Tags: nodes, 8
---


title: Webform emails threading

text:
# Question
Title: Webform emails threading
I have a client Webform and I use a custom template for delivering the submissions to the Gmail inbox. I've set the sender's email to the component e-mail field.

The problem is that Gmail puts all the received emails into one thread as if though the sender is the same for all the emails. So it becomes impossible to manage the clients emails as everything is being mixed up.

Is it a Webform configuration or am I missing something?

# Answer
> 0 votes
This isn't really a Drupal question. Go to https://mail.google.com/mail/#settings/general and look at the `Conversation View`. This sets whether emails of the same topic are grouped together. So they aren't grouped together based on the `from:` address but on the title. Just set it to `Conversation view off` and save the settings.

Alternatively, make the subject of the mail unique. For example by adding the name or email address to it, or a unique key.

---
Tags: 7, webforms
---


# Question
Title: How to add button to webform to set value to a field
Using Drupal 7 and Webform (both up to date), I'm looking for a way to add a button that when clicked, set the value of a field.

I can add a button using code like this:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {

switch ($form_id) {

case 'webform_client_form_ID':
  $form['alt_button'] = array(
  '#type' => 'submit',
  '#value' => t('Alternative Action'),
);

```

I now need to figure how to perform the action of changing the value of one of the the webform field when this button is clicked...

Any help will be appreciate!

# Answer
You will have to create a button in a

```
function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    // Your code here.
}

```

and use the #ajax property of the button to update the field when the button is clicked.

The examples D7 module has some nice AJAX examples that will show you how the mechanism works.
> 1 votes

---
Tags: 7, webforms, forms
---


# Question
Title: Is it Inethical/Bad Practise to create a custom table and save content instead of using drupal fields?
I was going through the Drupal 8 and find that it offers a lot in terms of structural data. There are many modules that use this structure data to execute very important web tasks. Like Search engine optimization, Feeds, API etc.

As a developer for a quick fix, we often create some content and save it on a custom table using a custom module, instead of putting content into Drupal structure as node field. Though this will solve our problem for short span of time quickly.

So is it something we should never do in case of Drupal?

# Answer
Not at all. It's up to the developer and the needs of the site. Setting up a field to tie in with the Field UI has a lot of benefits - it makes the field reusable on different entities, and allows it to be altered and manipulated as necessary. But it also adds a lot of overhead, and if you have to code your own fields, it adds time. If you know your data is to only be used for a single-case situation, then often it can be better to set up your own table and APIs in order to make the code more lightweight, and quicker to develop.

It's a case-by-case situation really.
> 5 votes

---
Tags: 8, database
---


# Question
Title: Bootstrap 3 - parent nav element disabled
Let's say I have a menu which is structured like this:

-- About (`href="/about"`)
----- Company (`href="/about/company"`)
----- History (`href="/about/history"`)
-- Offer (`href="/offer"`)
-- News (`href="/news"`)
-- Contact (`href="/contact"`)

So the 'Company' and 'History' are children of the 'About' element. Now, Bootstrap automatically creates the dropdown and if I want to visit 'About' and click it, it only opens the dropdown containing the children. So I can't actually visit 'About' from the menu. How can I force the Bootstrap theme to prevent this behavior?

Any idea how to do this?

# Answer
it took me ages but if you go to *menu-link.func.php* and take out line 33 `$element['#localized_options']['attributes']['data-toggle'] = 'dropdown';`

works!!! took me like 3 weeks of reading :)
> 2 votes

# Answer
You can also add a jQuery script to remove the href tab and disable the link.

```
$('#mainlink a').removeAttr('href');
$('#mainlink a').addClass('disabled');

```

Just to add another case scenario sometimes the drop-down is only offered on the sibling pages. On a Drupal 8 site you need to go into the parent menu item and enable the - Show as expanded (all languages)
> 0 votes

---
Tags: navigation
---


title: Entity Reference + View + security

text:
# Question
Title: Entity Reference + View + security
I have this scenario in DRUPAL 7

A content type named "Students" with a field "Legal guardian" that references to a User (her/his legal guardian).

A content type named "Reports" with a field "Student" that references to a Student.

With these reports I can do a view with 2 contextual filters (student id/date) to display a chart with the data provided from an specific report (using google chart tools).

All works like a charm, the problem is about the security because the url can be altered by anybody and get info for any student.

With Rules I can control:

* A student is visible if you are the legal guardian (or if you are an admin)
* A report is visible if you are an admin. I don't know how to control the legal guardian (in Students) of the Student field specified in this content type. But anyway, cos this information is used only to generate the charts, I don't really mind.

The problem is, as you can guess, that I need to control the access to the view. Only users that are legal guardian of student specified in that report can access the information.

All that comes into my mind is to set some rules to change the owner of the contents (Student, Reports) to the legal guardian's user and control the permissions, but maybe isn't the best way.

Could you please help me?

# Answer
You might be able to get this to work by using the Rules module. Depending on how the format of your URLs look like, you may want to also use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface. Using those you might be able to build an appropriate rule to issue a redirect (+ display a message if needed) based on some Rules Conditions that implement your access restrictions.

For more details, refer to my answer to the question "How to use the Rules module to implement a custom redirect for an outdated URL?".
> 0 votes

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


title: Node permissions - administer content

text:
# Question
Title: Node permissions - administer content
Can someone explain to me how node permissions are structured (or point me in the direction of a detailed list) - I'm trying to setup an editor role and want this to have full access to every content types.

It appears the only way is to tick 'Bypass content access control'?

Yet 'Administer Content' ("Promote, change ownership, edit revisions, and perform other tasks across all content types.") doesn't seem to do very much?

For example, I tick 'Administer Content' and untick 'Bypass Content Access Control', I don't seem to be able to "Promote" anything using the Actions dropdown, nor do I have an edit button next to anything on /admin/content, or any other way of accessing revisions or the ownership settings.

If I tick all the options for one content type, e.g. Basic Page, I get full access to those nodes, as expected.

# Answer
> 3 votes
I now understand how this works:

If you want a user to be able to edit all content types, regardless, you **are** supposed to use "Bypass Content Access Types".

"Administer Content" allows people without "Bypass Content Access Types" access to the Author and Promotion panels on the rhside of the node edit screen. i.e. they can change the Author (UID) and the creation date/time, and can either promote the content to the homepage or make it sticky.

"Administer Content" also gives access to the Revisions tab for all content types - but those permissions are duplicated - a user may already have them if type-specific revision permissions have been set, e.g:

* Basic page: Delete revisions
* Basic page: Revert revisions

(Note: Administer Content used to be called Administer Nodes and the latter name is still used internally.)

# Answer
> 0 votes
An option is to use this module: https://www.drupal.org/project/permissions\_by\_term. It will allow you to restrict content access based on taxonomy terms.

Another option is to edit the view at /admin/structure/views/view/content.

If you want to go deeper, you can check the implementation of hook\_node\_access() + hook\_node\_grants() + hook\_node\_access\_records() in the Permissions by Term module.

---
Tags: 8, users
---


# Question
Title: Is it possible to use a user display form in a page?
I've seen that it's possible to create different user display form here :

/admin/config/people/accounts/form-display/my\_infos\_form

How can I call it in a particular page for instance : /my/infos ?

As we have a lot of fields, we would like to separate the user edit page into multiple form page.

# Answer
> 0 votes
Unlike view modes there is no UI in core to apply different form modes other than the user register form. You can try one of these modules:

https://www.drupal.org/project/form\_mode\_control

https://www.drupal.org/project/form\_mode\_manager

---
Tags: 8, forms, users
---


title: Drupal Page Process

text:
# Question
Title: Drupal Page Process
Help me understand the best practice on how basic site building should work in Drupal 8.

Say I have a section on a website that is all about teaching. I'm going to create a basic page content type that has a title, body and various paragraphs elements that a user can add to the page. I then create the page called Teaching and say to add it to the main menu as this is going to be a main section of my website and then use URL alias to make the URL website.com/teaching.

Now, I want to add another page to my website which should fall under the Teaching branch of the site and call it Learning Cafe. Would I just go and use the same Basic Page content type and add all the info to it, and then add it to the main menu except as a child of the Teaching menu item? If I was to do this, wouldn't I just end up with a URL of website.com/learning-cafe instead of what I really want, website.com/teaching/learning-cafe?

How do I tell Drupal that this new page should be a type of "sub-page" in the Teaching section of the website? And how do I use URL aliases to automatically create the URL as a sub-section of /teaching instead of manually doing this for every page I create? I mean, yes I could do it, but when I hand the site off to non technical people, I wouldn't expect them to know to do this.

Also, if I do it this way, the breadcrumbs don't recognize this as being a sub page of Teaching. Instead of showing Home / Teaching / Learning Cafe, I just see Home / Learning Cafe.

Am I going about this the wrong way? Am I overthinking? If I could get a thorough explanation on how this should be done properly, that would be great. I feel like I know quite a bit about how to use everything else in Drupal but the site building portion of it seems to be confusing me.

Also, if more information is needed, let me know and I'll try to answer it.

# Answer
> 2 votes
If you add the node under another node in the Menu section of the node form, that page is the child of the page you set it to in the menu.

You need Pathauto to configure automatic aliases to get what you want, URL alias wise. You may also want Menu Breadcrumb to get the breadcrumb to behave a bit better and follow the menu.

As far as the 'page' content type - this is a fine approach. The differences in content types comes down to their purpose and field set. If you are creating five nodes, and theres virtually no difference between them or anything unique (like say, Article vs Product vs Job listing vs Page where fields may be different) - being a Page is fine. To understand your needs better, you should probably flesh out a content wireframe or information architecture / sitemap document. It will help you identify content, and their differing types, which will help you plan their fields and other configurations.

---
Tags: nodes, 8, path-aliases, breadcrumbs
---


# Question
Title: List of referenced entities appended to a node
I have two content types: "project" and "task" Using flag and with support of entity reference \+ flagging form, users can append very rapidly new "task" nodes to the current "project" node they are viewing. The structure then is the following:

1. Node type 1 \>\> project
2. Node type 2 \>\> task
3. Flag \>\> task appended to project; actually is a "container" of an Entity Reference(with multiple value) field linked to task

My target is create with views, a list of appended "task" nodes and show that list in a block to the related "project" node. I believe that I should use relationship + contextual filter, but I have no idea on how to achieve my needs.

Could you help me? Thank you all in advance!

Update on 13-01-2017 16:45: Attached step by step after suggestion from pierostz. These steps were done before the configuration window uploaded at 15:00.

Update on 13-01-2017 15:00: Attached contextual filter Nid after a first aattempt after suggestion from pierostz.

# Answer
> 0 votes
Create a new view showing tasks nodes. In your view use these settings.

1. Add a relationship "Entity Reference: Referencing entity".
2. Add a contextual filter of "Content:nid" with the relationship you previously created as the selected option on the relationship select box. Also provide the default value from "Content ID from URL".

3. Create another contextual filter with "Content: References".
4. Choose what fields to show as you normally do in a view.

I think this should do the trick.

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


# Question
Title: What is the rule on licensing and third party code?
When you create a module that uses third party code, is there any instance in which it is "okay" to include it in the module as opposed to have the user download it themselves?

For instance, if you make a module that integrates a CKEditor plugin - I would think that you *can't* or rather, *shouldn't* put it into your module on drupal.org.

I see this here: https://www.drupal.org/node/422996

My gut tells me it is likely not good practice to bundle it up into your module.

# Answer
> My gut tells me it is likely not good practice to bundle it up into your module.

You shouldn't. That page starts out with:

> This is the policy for 3rd party code libraries in Drupal's contribution repositories.
>
> > In general 3rd party libraries and content are forbidden, so do not commit any. Instead, document for your users how to find and install the library/content themselves.

The other way is exceptions and they're clearly defined and you need to request approval.
> 2 votes

---
Tags: 8
---


# Question
Title: Create just one .tpl.php file for several nodes?
I created these .tpl.php file for two node:

html--node\__39.tpl.php html--node\__14.tpl.php

**Question**: can I create just one file for both node?, something like:

html--node\__39&&14.tpl.php

# Answer
Here is an example to change the template dynamically on node type with a preprocess function. Of course you can also use this based on nids. https://www.drupal.org/node/1142800
> 3 votes

# Answer
You can create template file for your node type `node--yournodetype.tpl.php`

or `node--your-node-type.tpl.php`. It depends on your node type name. In that template you can create a condition just for two nodes with defined node ids. EG:

```
<?php if (in_array($node->nid, array('39', '14'))): ?>

<?php // Code just for predefined nids ?>

<?php else: ?>

<?php // Code for all other nodes of this type ?>

<?php endif;

```

It's just a proposition, of course, you can use above mentioned variants:

`function <THEME_NAME>_preprocess_node($variables){
 if (in_array($variables['node']->nid, array('39', '14'))) { array_push('node__template_nnn', $variables['theme_hook_suggestions']);
 }
}`
> 1 votes

---
Tags: 7, theming
---


title: Programmatically add button to block

text:
# Question
Title: Programmatically add button to block
7 - How do I programmatically create a button, place it in a block, 'weight it' and then make it visible to certain pages?

Code I've tried:

```
function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => 'user/',
  );

  $blocks['openid_connect_register'] = array(
      'info' => t('Register Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => '/user/register',
  );
  return $blocks;
}

```

This code creates the button but doesn't put it under the content block and doesn't make it only visible on the specified pages.

# Answer
> 1 votes
Why not render in a tpl so you can control the look of it?

I see you already used `hook_block_info()` so you can complete this using `hook_block_view()` with a custom callback function to use `hook_theme()`

Here is a complete example of it:

```
function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'region' => 'content',
      'pages' => 'user/',
  );

  return $blocks;
}

```

then:

```
function openid_connect_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'openid_connect_login':
      $block['content'] = openid_connect_login();
      break;
  return $block;
}

```

then:

```
function openid_connect_login() {
  return theme('openid_connect_login_tpl', array('data' => NULL));
}

```

last thing here:

```
    function openid_connect_theme($existing, $type, $theme, $path) {
      return array(
        'openid_connect_login_tpl' => array(
          'variables' => array('data' => NULL),
          'template' => 'openid-connect-login',
          'path' => drupal_get_path('module', 'openid_connect') . '/theme',
        ),
);
}

```

create your file inside you module under the name we gave openid-connect-login.tpl.php and put it in a folder I named theme ..

I hope I understood it right and was helpful for you issue ..

---
Tags: 7, blocks
---


title: Check if page view is example node/page

text:
# Question
Title: Check if page view is example node/page
I'm having some trouble trying to put an if else statement into my "page.tpl.php". I don't remember (I did it in the past), how to check something like that, but with some other page for example "www.example.com/home-2" or www.example.com/info . In my case is a page view, I would really appreciate any help you can provide.

# Answer
Well if I understand you right...

### In template.php

```
function mytheme_preprocess_page(&$variables) {
  $node = menu_get_object('node');

  if (isset($node) {
    $variables['node_type'] = $node->type;
  }
}

```

### In page.tpl.php

```
<?php if ($node_type == 'your_type') : ?>
  // something here for node type your_type
<?php endif; ?>

```

Additionally, you can simply add new template suggestions.

### In template.php

```
function mytheme_preprocess_page(&$variables) {
  $node = menu_get_object('node');

  if (isset($node)) {
    $variables['node_type'] = $node->type;
    $variables['theme_hook_suggestions'][] = 'page__node__' . $node->type;
  }
}

```

After clearing your cache, you can create `page--node--(node_type).tpl.php` and put page specific markup for that node type there.
> 1 votes

# Answer
Yes, the first two anwsers did the trick.

I knew that i can do the theme\_suggestions, but i didn't want to create more files so the menu\_get\_object worked like charm.

PD: I did it before but i couldn't remember how (i deleted those files).

THANKS!!!

EDIT: The solution in my case was to put the

```
  if (isset($node)) {
    $variables['node_type'] = $node->type;
  }

```

into the template.php

and then put my custom code with a conditional (for example):

```
<?php if ($is_front || $node_type == 'info_list'): ?>

```

into the page.tpl.php

I hope it helps somebody.
> 0 votes

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


# Question
Title: Rules Fetch entity by property using fixed User Role
# Versions

Drupal 7
Rules 2.9

# Problem

I am trying to loop through all users with a given role. I am trying to pull the users using the action "Fetch entity by property" with property "User Roles" But the value does not allow me to enter a static role. It forces me to select some available variable using tokens. If I enter a static value and save it returns a validation error.

How do I set the property to a static role?

Note the role is not the same as the user creating the node.

# Rule

I would include a serialized copy of the rule but frankly none of the rest of the rule matters. Roughly:

Trigger: node create.
Condition: node is published.
Action: Grab all users with editor role.
Action: loop through all users and send e-mail or add to a nodequeue (havn't decided which yet).

# More info

The documentation seems to indicate I should use "direct" input mode. However that option does not appear to be available on this form. Am I missing something? is this maybe a bug?

# Answer
Answering my own quesiton. I guess I should have found this sooner. But writing it down here helped me process the vocabulary I needed to search for.

I do indeed need to switch to direct input mode. In fact if you switch to direct input mode it will give you a list of roles to select. However direct input mode is not available on initial creation.

**To fix simply save as some value (I used site:user:role). Then edit the rule again and direct input will be available.** It appears to be a bug listed here: https://www.drupal.org/node/2168961

Thanks and hope this helps someone else.
> 1 votes

---
Tags: rules
---