title: adding class to drupal8 taxonomy

text:
# Question
Title: adding class to drupal8 taxonomy
i want to add custom class for each term

```
function sometheme_preprocess_field(&$variables) {
  if ($variables ['links']['#title'] == "Consulting"){
    // I'm lost here // how can i assign class here or even add a custom picture // Please help
  }
}

```

# Answer
> 1 votes
You can use preprocess field hook which is supported in drupal 8 also . Example below:

```
function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    //get the value of the field
    dsm($variables);
    // add a class to the field
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}

```

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


# Question
Title: How to set multiple values to an unlimited Term Refence field with Rules
I have two content types: Ingredient and Recipe Sheets.

Both Ingredient and Recipe Sheet have a term refence field called Allergens.

Ingredient has the Allergens term reference field filled in. IE: Milk, Gluten.

While in Recipe Sheets Allergens is empty.

Ingredient has an Entity Reference to Recipe Sheets.

Now, I want when Ingredient content type is viewed, to automtiacally copy all the terms from allergens and put them into the Allergens of the Recipe Sheet that is entity referenced (**the entity reference field can only have 1 value**).

In my rule, when Ingredient is viewed, I use Action of loop then item list to get all the Allergen field terms from A (Ingredient). Then another action to run my component and I pass that list to my component.

Here is my component ("B" refers to "Recipe Sheet"):

When I do this action, for Allergens, only the last tax term gets checked in B.

How do I get it, so it checks all the terms from the list and not just the last one?

---

Sample Rules Export:

```
{ "rules_testing" : {
    "LABEL" : "Testing",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "ingredients" : "ingredients" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-allergens" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "taxonomy_term", "id" : [ "list-item:tid" ] },
                "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
              }
            },
            { "component_rules_lalala" : {
                "node_referenced" : [ "node:field-reference" ],
                "nids_of_terms_from_allergens" : [ "entity-fetched:parents-all" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

Sample Component Export:

```
{ "rules_lalala" : {
    "LABEL" : "lalala",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_referenced" : { "label" : "Node(s) from Entity Reference", "type" : "node" },
      "nids_of_terms_from_allergens" : {
        "label" : "NIDS of Allergens from Ingredients",
        "type" : "list\u003Ctaxonomy_term\u003E"
      }
    },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-referenced" ],
          "type" : { "value" : { "recipe_sheets" : "recipe_sheets" } }
        }
      }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node-referenced:field-allergens" ],
          "value" : [ "nids-of-terms-from-allergens" ]
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
# Part 1: Understanding the problem

Your action **Set a data value** can only set 1 value, which explains what you currently experience, i.e the last one.

Try to replace that action with an action "**Add an item to a list**". When doing so, you probably also want to set "ENFORCE UNIQUENESS" to `true`, so that you "*only add the item to the list if it is not yet contained*". Even though for your case it may not make a difference, IMO that is a kind of safety-belt when using this action.

However, you also have to add a prior action like "**Fetch entity by ID**", before this "Add an item to a list".

For more details, have a look at the tutorial "Lists and loops", starting from around **`9:00`**.

# Part 2: Fixing the problem

Below are more detailed instructions, where appropriate with references to the equivalent that is shown in that video. And a corrected Rule and Rules Component (in Rules export format).

### Step 1: Simplify the Rule

In the **Rule** that calls your Rules Component, apply these changes:

* Delete all Rules Actions you had added (*sorry* ...).
* Only add 1 action, which is to invoke the Rules Component with 2 appropriate parameters, i.e.:
    + for ***Node(s) from Entity Reference*** use `node:field-reference` as its data selector
    + for ***List of Allergens from Ingredients*** use `node:field-allergens` as its data selector.

Here is an export of what I recommend as your (corrected) Rule:

```
{ "rules_copy_all_terms_to_another_node" : {
    "LABEL" : "Copy all terms to another node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "ingredients" : "ingredients" } }
        }
      }
    ],
    "DO" : [
      { "component_rules_add_a_term_to_a_node" : {
          "node_referenced" : [ "node:field-reference" ],
          "list_of_allergens_terms" : [ "node:field-allergens" ]
        }
      }
    ]
  }
}

```

### Step 2: Rework the Rules Component

In your **Rules Component**, apply these changes:

* Remove the action to "Set a data value" (we'll use Rules Action "*Add an item to a list*" instead, as detailed below).
* The 2 parms you passed to the Rules Components seem OK (I just slightly renamed them to improve readability).
* Add a loop, to iterate over each term contained in the list of terms (which is passed as a parameter), and add the extra Action for each item in this loop, like so:
    + Add an action `Fetch entity by ID`, whereas you want to fetch (= load) a taxonomy term, similar to what is shown in the video around **`10:40`**. And the ID of what you want to fetch is the 2nd parm of your Rules Component, followed by "`:tid`", similar to what is shown in the video around **`10:50`**, though your Rules Component should use "data selection" to select your 2nd parm (the video just uses a data identifier of "`1`"). Make sure to remember what you use as variable name here similar to what is shown in the video around **`11:20`**, let's assume you name it "`(allergens_term_fetched`".
    + Add an action to `Add an item to a list`, similar to what is shown in the video around **`11:40`**. The data list to which an item is to be added in your case is `node-referenced:field-allergens` (instead of `node:field-tags` as shown in the video). While doing so, the next thing is similar to what is shown in the video around **`12:00`**: the "item to add" should be "`(allergens-term-fetched`" (if you used that name I suggested). You probably also want to check the "enforce uniqueness" (see video around **`12:40`**, though the video does not check it), and for "insert position" I'd use "append the item to the end" (see video around **`12:55`**).
* Note: the Rules Condition in your Rules Component is fine (and also similar to what is shown in the video), no changes needed to that.

Here is an export of what I recommend as your (corrected) Rules Component:

```
{ "rules_add_a_term_to_a_node" : {
    "LABEL" : "Add a term to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_referenced" : { "label" : "Node(s) from Entity Reference", "type" : "node" },
      "list_of_allergens_terms" : {
        "label" : "List of Allergens from Ingredients",
        "type" : "list\u003Ctaxonomy_term\u003E"
      }
    },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-referenced" ],
          "type" : { "value" : { "recipe_sheets" : "recipe_sheets" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "list-of-allergens-terms" ] },
          "ITEM" : { "next_allergens_term" : "Next Allergens term" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "taxonomy_term", "id" : [ "next-allergens-term:tid" ] },
                "PROVIDE" : { "entity_fetched" : { "allergens_term_fetched" : "Fetched Allergens term" } }
              }
            },
            { "list_add" : {
                "list" : [ "node-referenced:field-allergens" ],
                "item" : [ "allergens-term-fetched" ],
                "unique" : "1"
              }
            }
          ]
        }
      }
    ]
  }
}

```

### Step 3: Time for QA-testing

*Only believe what you've seen with your own eyes* ... So use the Rules UI to import my corrected Rule and Rules Component. If you didn't do so yet, make sure you have a content type with the same machine name `ingredients` (doesn't matter what the content type of the entity referenced node is). And also make sure both content types have a term reference with machine name `allergens`. If the import fails, it must be because those machine names don't match, or the fields are missing (so fix that and retry the import).

After the import completed, and you have at least 1 node of each type (with an entity reference), it's Party Time ... Make sure your taxonomy terms include terms like salt, pepper, strawberries, bananas, whatever.

FYI: in my experimental setup, the combination of the above Rule and Rules Component seemed to work as requested in the question here ... one of my terms for testing was ... ***Champagne***.

***Voilà*** ... No custom code, *sweat*, *no*?

---
Tags: 7, rules
---


# Question
Title: Noitifications about security updates keeps coming after the update is done
I have updated to core version 7.52 and I also ran the database updates accordingly. So why do the notifications keep coming? I have set the update check to be done once a day, and every morning I get an email that states that a security update is available for my version of Drupal. When I click the link the page opens and says that Drupal core is up to date.

# Answer
I think this is the default behavior of the **Update Status** module, which is part of core. Unless you turn it off or reconfigure it, the modules will be checked daily and the site administrator will get email notices.
> 0 votes

---
Tags: 7, updating, notifications
---


# Question
Title: There is no language option in drupal 7 site
When I hit

> Administration \> Configuration \> Regional and language

There is no language option in drupal 7 site. Could I need to install modules? Which modules can I install?

# Answer
> 0 votes
You need to enable Locale(Drupal core) module. Get new option on configuration page for language(`admin/config/regional/language`).

Tutorial - Building a multi-language site

How to Build Multilingual Drupal Sites

# Answer
> 1 votes
It is be because you've installed Drupal with English. You can make Drupal Multi-lingual after it is installed, using the quick steps provided on HowTo: Basic Internationalization setup.

You can also have a look at the Multilingual guide for detailed information.

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


title: How do I hide the default page /node?

text:
# Question
Title: How do I hide the default page /node?
Drupal out of the box comes with a page (which is the default homepage) that is assigned to the *node* path.

How do I avoid users reach it, and redirect them to the actual homepage of the site?

# Answer
There is no easy way to hide that page. If you don't use it, you can implement hook\_menu\_alter(), and either remove it completely, or set its access callback to `FALSE`.
> 17 votes

# Answer
Create a path alias that redirects from /node to the page you want to use as front page.
> 9 votes

# Answer
I prefer to alter the page callback of /node so it shows an error 404 Page.
This always shows your custom 404 page when accessing /node.

```
function yourmodule_menu_alter(&$items) {
    $items['node']['page callback'] = 'drupal_not_found';
}

```
> 6 votes

# Answer
```
<?php
function MY_MODULE_menu_alter(&$callbacks) {
unset($callbacks['node']);
}
?>

```

or add this to settings.php (URL inbound stuff)

```
<?php
function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  if ($path == 'node') {
    $result = '';
  }
}
?>

```
> 4 votes

# Answer
I used the Redirect module: I just added a new 301 redirect from `node` to `<front>`.
> 2 votes

# Answer
Similar to berdirs answer, I have the following code included in a module that is part of a custom distro we build from:

```
function HOOK_menu_alter(&$items) {
  $items['node']['page callback'] = '_HOOK_empty_home';
}

function _HOOK_empty_home() {
  drupal_set_title('');
  return '';
}

```

That way I can keep the 'node' path as the frontpage and use context to position blocks to build the required frontpage.
> 1 votes

# Answer
You can create a page mapped to /node which is not published. So the users who will call this path will have an access forbidden page
> 1 votes

# Answer
The easy solution for me was to create a page that I wanted to be the home page and set the URL to /node. Then under /admin/config/system/site-information set the default front page to /node. You never see "/node" in URL unless someone actually types it in. It's quick, easy and clean, provided you want to set your homepage URL to /node.
> 1 votes

# Answer
You can create a new page with node URL and people can see a message redirecting them to visit the front page or choose a category of something.
> 1 votes

# Answer
Popular question from quite some years ago, with quite some interesting answers already. However, guess what: "These days there's a module for it ... actually even two!" (not mentioned in any of the prior answers).

Read on for more details ... (quotes are from their project pages) ...

**Node page admin** (either D6 or D7):

> This module adds an administration settings panel to handle ***/node*** page access. Once it is activated there are three posible configurations:
>
> * Core - Drupal core will handle node page access as usual: all users with 'access content' permission
> * Disabled - Nobody will be able to access /node. It will return 'Page not found' (404).
> * By permission - Access will be handled by a new permission: 'access node page'

**Node Page Disable** (either D6 or D7, though only rc2 versions):

> Allows easy UI access and disabling of the path ***/node*** when not used. This was inspired by a security consideration in the Production Check Module.
> 1 votes

# Answer
I tried multiple things. Then for Drupal 7 and 8, I found this to be most easy, without writing any code:

download and enable node\_page\_disable, globalredirect and redirect modules.

(Note: node\_page\_disable module redirects /node to 404 not found error page.)

then add a redirect for /node --\> front page

Please note that the redirect redirects both /node and /node/ to front page.

and a useful article to read: https://www.drupalaid.com/blog/3-things-you-should-hide
> 1 votes

# Answer
Create a node, then go to site configuration -\> site information, and set the home page to the path of the node. So if it's your first node, it would be node/1.

Edit: By default, just by creating a node that page will disappear if you check 'promote to front page'. The site information step will make that node your actual front page.
> 0 votes

# Answer
You can use the Rules module to check the url before viewing a page and redirect users to another page if you'd like.

* Add rule with event: *Content is going to be viewed*
* Add condition: *Execute custom PHP code* and check the path
* Add action: *Page Redirect* and choose the path you want to redirect to
> 0 votes

# Answer
the best way is to hide nodes from template\_preprocess\_page function

```
function template_preprocess_page(&$variables) {
    if ($variables['is_front'] == 1) {
        if (isset($variables['page']['content']['system_main'])) {
            unset($variables['page']['content']['system_main']);
        }
    }
}

```
> -1 votes

---
Tags: 7, redirection, nodes
---


# Question
Title: Article page url in chinese language Drupal 7
When i am visiting my site individual article page url in chinese language got below error, even this URL working fine in my localhost.

Uncaught exception 'PDOException' with message 'SQLSTATE\[HY000\]: General error: 1366 Incorrect string value: '\xE7:titl...' for column 'location' at row 1' in /var/www/includes/database/database.inc:2204 cloud-server-01 /zh-hans/articles/%E5%9D%90%E6%8B%A5%E5%95%

# Answer
This error might appear when the MySQL database is encoded as UTF8. In that case, Unicode characters represented with 4 bytes are not accepted. The accepted reply to the following StackOverflow question explains that the database needs to be encoded using the `utf8mb4` encoding and the `utf8mb4_unicode_ci` collation:

https://stackoverflow.com/questions/10957238/incorrect-string-value-when-trying-to-insert-utf-8-into-mysql-via-jdbc

A more complete explanation about the `utf8mb4` encoding on MySQL can be found here:

https://mathiasbynens.be/notes/mysql-utf8mb4

In case you need to re-encode your existing Drupal database, there is an experimental Drush command for it at UTF8MB4 Convert.
> 1 votes

---
Tags: views, database, hooks
---


title: Page node edit content-type

text:
# Question
Title: Page node edit content-type
How I can customize the node edit page? I need to use a custom template for it. page--node--add-content-type.tpl.php works fine, but --edit--content-type.tpl.php doesn't.

# Answer
> 1 votes
I figured it now.

```
function HOOK_preprocess_page(&$variables) {
    if (isset($variables['node']->type)) {
        $nodetype = $variables['node']->type;
        $variables['theme_hook_suggestions'][] = 'page__' . $nodetype;
    }
    if (!empty($variables['node']) && arg(2) == 'edit') {
        $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type .'__edit';
  }
}

```

# Answer
> 3 votes
You need to use function hook\_preprocess\_HOOK.

```
function themeName_preprocess_page(&$vars) {
    if (!empty($vars['node']) && arg(2) == 'edit') {
    $vars['theme_hook_suggestions'][] = 'page__node__' . $vars['node']->type .'__edit';
  }
}

```

This allowed me to use: page--node--\[contentType\]--edit.tpl.php

Clear cache.

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


title: Load a view with parameters

text:
# Question
Title: Load a view with parameters
I got a question regarding the loading of a view within a preprocess function of Drupal 8.

The only working solution I found is this one here:

```
$_block_level_1 = \Drupal::entityManager()->getStorage('block')->load('views_block__myview_ov_block_1');

```

So by using the entity manager.

The view is expecting parameters. How do I send them?

# Answer
You can render view programatically using views\_embed\_views() and pass views arguments to it. Check example below:

```
\Drupal::service('renderer')->render(views_embed_view('VIEW_NAME', 'DISPLAY_NAME', $ARGS_1, $ARGS_2));

```
> 0 votes

# Answer
If you prepare a render element of the view

```
$variables['view_block_1'] = [
  '#type' => 'view',
  '#name' => $name,
  '#display_id' => $display_id,
  '#arguments' => $args,
];

```

you can then render this view in twig:

```
{{ view_block_1 }}

```
> 1 votes

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


# Question
Title: how to get all options values of simple hierarchical select in drupal $form?
i have writed this code to unset empty terms :

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

  if ($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-projet-immobilier-page-1') {
    foreach ($form['field_r_t_tid']['#options'] as $tid => $term_name) {
      if (is_numeric($tid)) {
        $result_count = db_select('taxonomy_index', 'ti')
        ->fields('ti')
        ->condition('ti.tid', $tid, '=')
        ->execute()
        ->rowCount();

        // Removing the option for tags with no-content
        if (!$result_count) {
          unset($form['field_r_t_tid']['#options'][$tid]);
        }
      }
    }

  }
}

```

but is not worked, he show me this error : Undefined index : #options ... how can i resolve this error?

# Answer
In Drupal 7 you can use field\_info\_field(), while in Drupal 6 you can use content\_field\_instance\_read(), which is defined in the CCK module.

You can also use list\_allowed\_values().

```
$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);

```
> 0 votes

---
Tags: 7, hooks, forms, taxonomy-terms
---


# Question
Title: Passing variables that contain HTML through the t() function - ! placeholder has been removed
In Drupal 8, it appears that using the ! (exclamation mark) placeholder with the t() function has been removed.

I have a variable that contains HTML:

```
<span class="fullname_wrapper"><span class="first_name">John</span> <span class="last_name">Hancock</span> <span class="account_name_wrapper">(@JohnH)</span></span>

```

I want to keep this HTML, as it will be styled specifically wherever it appears on the site.

In Drupal 7, I was able to do this:

```
t('Your name is !name', array('!name' => $name));

```

In which $name contains the HTML shown above. However, in Drupal 8, this doesn't work since the exclamation mark pass-through placeholder has been removed.

I tried this:

```
t('Your name is :name', array(':name' => $name));

```

But the HTML is still escaped.

The @ mark also escapes the HTML.

Does anyone know how HTML can be passed through the t() function in D8?

UPDATE:

According to No Sssweat's comment, it seems that my the ! mark does seem to work in t(). So here is my actual code:

```
drupal_set_message(
  $this->t(
    "@amount has been transferred to !account",
    array(
      '@amount' => '¥' . $form_state->getValue('amount'),
      '!account' => $this->accountService->formatAccountName($account)
    )
  )
);

```

And I get this error stack:

```
User error: Invalid placeholder (!account) in string: @amount has been transferred to !account in Drupal\Component\Render\FormattableMarkup::placeholderFormat() (line 235 of core/lib/Drupal/Component/Render/FormattableMarkup.php).

Drupal\Component\Render\FormattableMarkup::placeholderFormat('@amount has been transferred to !user', Array) (Line: 204)
Drupal\Core\StringTranslation\TranslatableMarkup->render() (Line: 15)
Drupal\Core\StringTranslation\TranslatableMarkup->__toString() (Line: 451)
drupal_set_message(Object) (Line: 128)

```

The user error is what made me think the ! mark is not allowed, but I must have misdiagnosed it. Does anyone know what is happening here?

# Answer
It appears that any arguments passed to t() function are escaped unless they implement *MarkupInterface*. So that you need to represent the name as an object.

```
use Drupal\Component\Render\FormattableMarkup;

$formatted_name = new FormattableMarkup(
  '<span class="fullname-wrapper">
    <span class="first-name">@first_name</span>
    <span class="last-name">@second_name</span>
    <span class="account-name-wrapper">(@user_name)</span>
   </span>',
  [
    '@first_name' => 'John',
    '@second_name' => 'Hancock',
    '@user_name' => '@JohnH',
  ]
);

drupal_set_message(t('Your name is @name', ['@name' => $formatted_name]));

```
> 29 votes

# Answer
Yes, the user error you are seeing means the placeholder you are using is not recognized from `t()`. `FormattableMarkup::placeholderFormat()`, the method that does the job behind the scene, recognizes just 3 placeholder-types: *@variable*, *%variable*, and *:variable*. If the placeholder starts with a different character, it executes the following code, which causes the behavior you are seeing.

```
  default:
    // We do not trigger an error for placeholder that start with an
    // alphabetic character.
    // @todo https://www.drupal.org/node/2807743 Change to an exception
    //   and always throw regardless of the first character.
    if (!ctype_alpha($key[0])) {
      // We trigger an error as we may want to introduce new placeholders
      // in the future without breaking backward compatibility.
      trigger_error('Invalid placeholder (' . $key . ') in string: ' . $string, E_USER_ERROR);
    }
    elseif (strpos($string, $key) !== FALSE) {
      trigger_error('Invalid placeholder (' . $key . ') in string: ' . $string, E_USER_DEPRECATED);
    }
    // No replacement possible therefore we can discard the argument.
    unset($args[$key]);
    break;

```

The description for *@variable* says that the value of the variable could be:

In your case, I would just use the following code.

```
use Drupal\Component\Render\FormattableMarkup;

drupal_set_message(
  $this->t(
    "@amount has been transferred to @account",
    [
      '@amount' => '¥' . $form_state->getValue('amount'),
      '@account' => new FormattableMarkup($this->accountService->formatAccountName($account), [])
    ]
  )
);

```
> 5 votes

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


# Question
Title: How to display a page of a taxonomy term differently from the default view?
I activated the "Taxonomy term" view to customize the time display. I want to display some terms from another differently. How to do this ?

I have cloned my view "Taxonomy term" and applied to it a criterion of filtering by type of content displaying only my "sujet". Then I customized its display.

The problem, when the cloned view is enabled, all terms show a blank page.

# Answer
Maybe you should check Taxonomy Views Integrator

> The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice
> 0 votes

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


# Question
Title: Ho to improve Drupal site score on PageSpeed Insights Site
I have check score on PageSpeed Insights, But I am getting following error

Should Fix: Eliminate render-blocking JavaScript and CSS in above-the-fold content Your page has 16 blocking script resources and 8 blocking CSS resources. This causes a delay in rendering your page. None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

# Answer
> 2 votes
A possible starting point might be the Advanced CSS/JS Aggregation module.

The following article shows some possible configuration options that can increase your PageSpeed Insights score:

https://www.northstudio.com/blog/increase-your-drupal-site-pagespeed-score-part-2-advagg

---
Tags: javascript, theming
---


title: Error after updating

text:
# Question
Title: Error after updating
I recently updated to Drupal 8.2.0 from 8.0. Updating was successful, but the *Status report* page shows this error.

How can I solve it?

# Answer
> 5 votes
Execute `drush entity-updates`. As usual, test this on non-production system.

---
Tags: 8, entities, updating
---


# Question
Title: Update webform submitted data through the DataBase?
I see in the DataBase the table `webform_submitted_data` which contains the components's data of all webforms

But a token suddenly stop working as intended so the hidden fields of the webform, its data were incorrect for my use case. I fixed the issue but now want to update the affected submissions (luckly are only 10)

It is safe to update the respectives rows through a SQL statement? I do not need to trigger hooks, or other stuff, only need the correct data for the little code i write that uses it

# Answer
> 1 votes
Yes, that should be perfectly safe to do.

Take a backup first just in case, clear the cache after you've done it, and that should be fine.

---
Tags: 7, database, webforms
---


title: Unable to print form element

text:
# Question
Title: Unable to print form element
I am not able to get form element qty twice. I have 2 line item IDs, but I am getting 1 instead of printing qty twice. Please help me out this. This is my code.

```
function mol_split_delivery_form($form, &$form_state, $order_id) {

$order = arg(1);
$line_item_idds = get_total_line_item_ids($order);

if (!empty($line_item_idds)) {
  $line_items = commerce_line_item_load_multiple($line_item_idds);

}
else {
  $line_items = array();
}

foreach ($line_items as $line_item_id => $line_item) {

$form = array();
$option_first = array(1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9');
$form['line_items'][$line_item_id]['quantity'] = array(
    '#title' => 'Qty',
    '#type' => 'select',
    '#options' => $option_first,
    '#default_value' =>  $line_item->quantity,
 );

 }
return $form;
}

```

# Answer
Take the `$form = array();` line out of the foreach loop. This is clearing the $form array every time it loops around. You don't want it to do that.

```
foreach ($line_items as $line_item_id => $line_item) {

   $option_first = array(1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9');

   $form['line_items'][$line_item_id]['quantity'] = array(
     '#title' => 'Qty',
     '#type' => 'select',
     '#options' => $option_first,
     '#default_value' =>  $line_item->quantity,
   );
}

```

Also, if `$order_id` is a argument, you should not need to call `arg(1)`. Consider passing the commerce order object as an argument instead, using %commerce\_order as a URL parameter. Drupal will load it and pass it for you (if this function is a menu item callback).
> 1 votes

---
Tags: 7, forms, commerce, hooks
---


# Question
Title: How to make the comment author name required for anonymous users?
I'm trying to make the comment author name required with this code:

```
use Drupal\Core\Form\FormStateInterface;
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_comment_comment_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['name']['#required'] = true;
}

```

But I can't find the way to do so. How to make the comment author name required for anonymous users?

# Answer
> 3 votes
You can try:

```
if (\Drupal::currentUser()->isAnonymous()) {
  $form['author']['name']['#required'] = TRUE;
}

```

It is necessary because it is not right to check if user is authenticated by checking if the name field is prefilled.

We have to use `\Drupal::currentUser()` service in theme or module file (in controller you have to use `Drupal\Core\Session\AccountProxy`).

currentUser() Documentation

```
/**
 * Implements hook_form_FORM_ID_alter().
 */

function MODULE_form_comment_comment_form_alter(array &$form, FormStateInterface $form_state, $form_id)
{
  if (\Drupal::currentUser()->isAnonymous()) {
    $form['author']['name']['#required'] = TRUE;
  }
  else {
    $form['author']['name']['#required'] = FALSE;
  }
}

```

# Answer
> 10 votes
I found the answer:

Implementing the `hook_form_FORM_ID_alter()` hook you can use the comment form id (`comment_comment_form`) to alter the form.

The problem was that the field name is inside the author, so you need to use `$form['author']['name']['#required'] = TRUE;`

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_comment_comment_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['author']['name']['#required'] = TRUE;
}

```

---
Tags: 8, comments
---


# Question
Title: How to use Font-your-face fonts with CKEditor?
I am using some Google fonts via the Font-your-face module on my D7 website as well as CKEditor for content editing. To achieve full wysiwyg effect I would like to display the text in editor with these Google fonts. However I can't find the way to to this.

Should I give a try to the appropriate CKEditor plugin or is there a way to solve this on Drupal level? Any ideas?

# Answer
> 1 votes
This looks like a long awaited and unanswered issue - https://www.drupal.org/node/1234030 \- however I have found a page that describes how you can manually updated your CKEditor fonts list.

http://www.zyxware.com/articles/3692/drupal-how-to-add-fonts-in-ck-editor

I think this seems a bit too much, you would think that there would be a better system in place to support more fonts dynamically. There are apparently some hooks with the WYSIWYG module and Font Your Face - however as far as my knowledge goes CKEditor works better on it's own than as a part of WYSIWYG.

---
Tags: 7, wysiwyg, theming
---


# Question
Title: Populate a hierarchical select field programmatically
I have to create a user, and one of the fields (**Profession**) is a hierarchical select based on a two level taxonomy, where the **first level is "profession"**, and **each profession has different specialities**.

I can create a user and save the profession field, but the speciality is not saved, and that's what I want to do. Here is how I save the profession :

```
$fields = array(
    'name' => $name,
    'mail' => $email,
    'pass' => $password,
    ...
    'field_profession' => array('und' => array(array('tid' => $tid_profession))),
);
user_save('', $fields);

```

Here, `$tid_profession` is the id of the profession term. However, when I use the id of the speciality term, the field is not saved.

Any idea how to make this work ? Any help would be greatly appreciated.

# Answer
I have saved user with custom hirerarical select field named "field\_register\_state" like below: it's working very well.

```
$account = new stdClass;
$account->is_new = TRUE;
$account->name = $username;
$account->pass = user_hash_password($form_state['values']['pass']);
$account->mail = $form_state['values']['mail'];
$account->init = $form_state['values']['mail'];
$account->status = TRUE;

$account->field_user_code = array(LANGUAGE_NONE => array(array('value'=>$userCode)));
$account->field_full_name = array(LANGUAGE_NONE => array(array('value'=>$form_state['values']['field_full_name']['und'][0]['value'])));
$account->roles = array(DRUPAL_AUTHENTICATED_RID => 'authenticated user',$form_state['values']['roles']=>getRoleNameById($form_state['values']['roles'],$form));

$account->field_user_area_name = array(LANGUAGE_NONE => array(array('value'=>$areaName)));
$account->field_created_by = array(LANGUAGE_NONE => array(array('value'=>0)));
$account->field_register_state = array(LANGUAGE_NONE => array(array('tid'=>$statecode)));
$account->timezone = variable_get('date_default_timezone');
user_save($account);
drupal_set_message(t('User Created Successfully'), 'status');

```

Hope this help's you..
> 1 votes

# Answer
The solution was not in the code, which works fine, but in the configuration of the field.

Instead of saving all the lineage, I had to save only the deepest term, and then, both my child and parent fields were correctly saved.
> 1 votes

# Answer
The following may not work for you but it did turn out to be the right approach on my end. Thanks Kamal!

```
/**
 * Implements hook_user_login().
 */
function custom_module_user_login(&$edit, $account) {
  $tid = 10;
  $account = user_load($account->uid);
  $account->field_location_map = array(LANGUAGE_NONE => array(array('tid'=> $tid)));
  user_save($account);
}

```
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to create an Ecommerce Loyalty scheme for customers?
How can I create a 'loyalty scheme' where customers are awarded with 5 pence for every £ spent, to be used on furture purchases. The rewards will be saved up until the user decides to redeem them against an order.

I have looked for a few solutions but cannot seem to find a way to make this work.

Any suggestions?

# Answer
> 0 votes
This may be too much overhead for your system of point usage, but check out the Commerce Userpoints module. It integrates Commerce with the Userpoints module, which should handle most of what you're after.

# Answer
> 0 votes
User Points module is the best suited for you.

However there is one Customer Loyalty and Retention Management which we developed to get Loyalty and Retention Management to next level, we offer REST APIS to integrate your system to it.

> Pegke loyalty platform solution, is a robust real-time, fully customizable and scalable solution that offers security and privacy standards required and is seamless to any business.

# Answer
> 0 votes
What you're looking for is typically implemented using the User Points module (that's obvious, and already mentioned in the prior answers).

However, by ALSO using the Goals module (disclosure: I'm its maintainer) you can have the Rules module take care of granting the appropriate number of userpoints. The advantage of using the Goals module, is that you can keep track of all sorts of events that are happening asynchronously (which you cannot do by only using Rules and its events).

So with that it seems that your question (challenge) is reduced to finding a way to configure the appropriate set of **Goals** and related **Tasks**. For a basic introduction about Goals, have a look at:

Moreover, it would be straight forward to implement some special reward(s) for something like ***frequent buyers***. Here is what it would take:

1. **Goal** = "New customer", with only 1 **Task** = "Buy 1 product" (say with machine name = `buy_product`).
2. **Goal** = "Silver customer", with **Task** = "Buy 10 products, on 10 different days, in a timeframe of 3 months".
3. **Goal** = "Gold customer", with **Task** = "Buy 100 products, on 25 different days, in a timeframe of 12 months".

The interesting part of this is that you'd only have to write 1 rule (related to that machine name = `buy_product`) to keep track of the progress of any user to become a new/silver/gold customer (check the video for a similar sample).

---
Tags: 7, commerce
---


# Question
Title: What's the correct way of referencing a method in a controller for running through batch processing?
I have a set of batch operations with:

```
foreach ($urls as $url) {
  $test_sites[] = array('\Drupal\my_module\Controller\BatchTestSite::TestSite', $url);
}

```

When I run it I get the following:

```
Deprecated function: Non-static method Drupal\my_module\Controller\BatchTestSite::TestSite() should not be called statically in _batch_process()

```

What's the correct way of referencing a method in a controller for running through batch processing (even if it's not static)?

# Answer
Controllers are services and should be initiated as such. Either use the static `create` method to create an instance of the controller or define a service for it and use `\Drupal::service('...')`
> 0 votes

# Answer
Drupal\my\_module\Controller\BatchTestSite::TestSite is not a function but class method. You need to make it static to use as batch callback.
> 1 votes

---
Tags: 8, batch-operations
---


# Question
Title: How to remove the default cache tags on a block?
Here's what I'm noticing:

* I set the cache array to what I want it to be in my block
* It propagates up to BlockViewBuilder.php and gets put into the `$build`'s `content` array
* There is still a `#cache` array on the $build itself, which by default has three contexts: `array('languages:language_interface', 'theme', 'user.permissions')`

I want to get rid of the languages and user.permissions contexts for my block, because they shouldn't affect its content and I don't want the two contexts to have inconsistent data, but setting my block's contexts won't affect the ones set by the top level $build object. Is there a way for me to do that?

It looks like CacheableMetadata::createFromRenderArray() will try to merge the two #cache arrays, but from the way it's doing it, it seems it will grab unique values from the two arrays. Is there a place where I can remove the bad contexts?

# Answer
Nope, you can't really opt out of those.

They are defined as required cache contexts in services.yml. So even if you'd manage to remove them, they are added in Renderer.php.

You could change that globally, but you have to be aware of the risks as it is likely that not every contrib/custom code is adding the user.permissions cache context when required, so we decided to make that a default so that at least that kind of cache/acess separation is enforced.
> 3 votes

---
Tags: 8, blocks, caching
---


# Question
Title: How to name multi-sites for different environments (dev and staging)?
I have a Drupal project that is a multi-site setup. I currently have my sites named like so:

```
sites/site1.example.dev
sites/site2.example.dev
sites/site3.example.dev

```

This is fine for working locally in development, as I can point my browser to **site1.example.dev**, **site2.example.dev**, or **site3.example.dev** and it works. However, when I push this up to staging, I want to be able to access these sites at the following addresses:

```
site1.example.com
site2.example.com
site3.example.com

```

Is it possible to simply name these as "\[specific\_name\].example" and configure it so that I don't need to rename/update depending on the environment?

Thanks.

# Answer
I think you may be looking into aliases.

On your `sites` folder there should be a `example.sites.php`. It basically allows aliasing sites to different names.

You could create an `if` and based on some environment condition (maybe the output of `hostname`? or a file somewhere that contains `prod` vs `dev`), enable or disable the aliases.

More documentation:
> 1 votes

# Answer
You can modify the site names for staging site in the file sites/site.php

Also update the settings.php file with the credentials of staging site.

Also need to update the site url from the host settings.
> 1 votes

---
Tags: multi-sites, subsites
---


title: Remove date folder on uploaded files

text:
# Question
Title: Remove date folder on uploaded files
Currently the path where the files are saved looks like this: www.mysite.com/sites/default/files/\[date when the file is uploaded\]/\[filename\].

Is there anyway to remove the "date when the file is uploaded" directory and save it directly on the files directory?

Thanks!

# Answer
Yes You can just follow few steps given below :

1. Go to Structure \> Content-Type
2. Click on Manage Fields of {{Custom Content Type}}.
3. Edit the file field . From File directory remove \[date:custom:Y\]-\[date:custom:m\].
4. And you will end up with storing files under files directory
> 6 votes

# Answer
Also you can add your File directory name in file field configuration to save your specific uploded files in your directory under sites/default/files/\[your directory \] path
> 2 votes

---
Tags: 8, files
---


# Question
Title: how to do a list navigation into a node content
I have a content type with some custom text fields. when the node displays I'd like to show it like this:

node-title

* field-1 (link)
* field-2 (link)
* field-3 (link)

field-1-content

field-2-content

field-3-content

this is for a new site, so I'd like to do that on Drupal 8 (with bootstrap theme).

# Answer
> 0 votes
For this requirement you should go for twig to your content type:

> node--content-type.html.twig

In hook\_preprocess\_HOOK render all the fields you would like to show in twig file.

For better understanding of twig file follow this.

---
Tags: entities, navigation
---


# Question
Title: How do I hide an article if it doesn't have an image?
How do I hide an article if it doesn't have an image?

In Drupal 6, the setting is *Block: Configure filter Content: (field\_image)*, but I can't find this settings in Drupal 7.

# Answer
> 1 votes
You can put a condition on view filter. If image field is empty then row will not display.

> Content: field\_image:fid (not empty)

OR

> Content: Slide image:fid (!= 0)

---
Tags: 7, views
---


# Question
Title: Problem adding button to custom content type form
I am trying to add a cancel button to a custom content type form (typename/type/add). I have looked around and there seems to be two main ways of doing this:

1. Creating a template file with the name page--node--add--typename.tpl
2. Implementing the `hook_form_alter` either in the theme **template.tpl.php** or in a custom module.

then adding code like

```
$form['actions']['cancel'] = array(
    '#type'   => 'submit',
    '#value'  => t('Cancel'),
    '#access' => TRUE,
    '#weight' => 55,
    '#submit' => array('cancel_button_form_cancel', 'node_form_submit_build_node'),
    '#limit_validation_errors' => array(),
);

```

In the first case, after rendering the form with `drupal_render($form)` the button is added but only the form is rendered. Main menu and other blocks are not rendered.

However in the second case the button never appears. Even though something like `drupal_set_title('Title')` does change the title.

Any solution to either issue would be most welcome.

**Edit** The first part of this question is now a separate one here.

# Answer
Ok found the problem with implementing the hook, I copy pasted the code from some post and it was passing $form variable by value. The correct signature of the alter\_form should be

```
modulename_form_alter(&$form, &$form_state, $form_id)

```
> 0 votes

# Answer
Yes, you have to use hook\_form\_alter or hook\_form\_FORM\_ID\_alter functions to alter your form and to add new form elements to an existing form in your theme template.php or module files. You should not edit your form in template files directly.

Example (template.php):

```
 function your_theme_form_YOUR_FORM_ID_alter(&$form, &$form_state, $form_id){
$form['actions']['cancel'] = array(
    '#type'   => 'submit',
    '#value'  => t('Cancel'),
    '#access' => TRUE,
    '#weight' => 55,
    '#submit' => array('cancel_button_form_cancel', 'node_form_submit_build_node'),
    '#limit_validation_errors' => array(),
);
}

```

After that you can get rendered form in template\_preprocess\_page function:

```
 function your_theme_preprocess_page(&$variables) {
$variables['your_form'] = render(drupal_get_form('your_form_id'));
   }

```

Now variable $your\_form is available in your page template file.

You can print it this way `<?php print $your_form; ?>`

Maybe main menu and other blocks are not rendered because you didn't added their regions to the template file like this `<?php print $page['content']; ?>`

You have to place your drupal\_set\_title('Title') function in the your\_theme\_preprocess\_page or your\_theme\_form\_YOUR\_FORM\_ID\_alter function to change title.
> 0 votes

---
Tags: 7, forms, nodes
---


# Question
Title: How to use Rules to prevent the creation of nodes if certain conditions are true?
I need this in Rules:

> When a node is being created (before the node is saved), and certain conditions are true, the user **can't** create the node, and an error message appears instead.

I have a rule that is working, and the error message is displaying. But the node is still created.

Is there a way to prevent node creation in rules?

**Note**: I'm using Drupal 7. I selected the Action "Show error message" directly on rules.

# Answer
Out-of-the Rules module-box, I think there is no solution to "***prevent node creation in rules?***" (as in your question). However, without using custom code and custom PHP in your Rules conditions or actions and without deleting the node after it got created, you may get it to work if you also use the Rules Forms Support module.

More details about Rules Forms Support (from its project page):

> Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.
>
> For help getting started with Rules Forms Support, please see the module documentation.
>
> Features
>
> * Activate events for form creation, validation, and submission on a form-by-form basis.
> * Target individual form elements or the entire form in conditions and actions.
> * Manipulate the attributes of a form element like title, description, weight, and more.
> * Validate the values of form elements during form validation.
> * Set form errors when rule-based validation fails.
> * Redirect users to a different page upon viewing or submitting a form.
> * Examine the attributes of elements in active forms with the element inspection tool.

Especially the "***Set form errors when rule-based validation fails***" should help to address your question.

More details about how to use this module can be found in the community documentation "Altering & validating forms".
> 1 votes

# Answer
I solved this by using the drupal\_goto function.
> 0 votes

---
Tags: nodes, rules
---


title: database selection(db_Select)

text:
# Question
Title: database selection(db_Select)
The database contains a *mcms\_field\_data\_field\_cage\_id\_vbc* table, which has more than 6000 records. I am using the following code to get the content of that table.

```
function hello_db() {
  $query = db_select('mcms_field_data_field_cage_id_vbc', 'tb');
  $query->fields('tb', array('field_cage_id_vbc_target_id'));
  $result = $query->execute()->fetchAssoc();
  foreach($result as $record) {
    drupal_set_message($record);
  }
}

```

The code doesn't show all the records in that table, but a single value.

>

Why doesn't the code work as expected?

# Answer
> 2 votes
`fetchAssoc` fetches a single record as an associative array; you're then looping over that one array and setting a message for the single column in that array, `field_cage_id_vbc_target_id`. Hence just the one result, an integer instead of the expected array(s).

You can use `fetchAllAssoc` instead:

```
$result = $query->execute()->fetchAllAssoc();

foreach($result as $record){
  drupal_set_message($record);
}

```

# Answer
> 1 votes
You can also try

```
$result = $query->execute()->fetchAll();

```

**fetchAll()** will fetch all the records.

Instated of

```
$result = $query->execute()->fetchAssoc();

```

**fetchAssoc()** Will fetch single record.

Or

```
$result = $query->execute();
while($record = $result->fetchAssoc())
  drupal_set_message($record);
}

```

**while($record = $result-\>fetchAssoc())** Will fetch record one by one.

# Answer
> 0 votes
You can call the column of your selection with `$record -> columnname`

```
foreach($result as $record){

     drupal_set_message($record->field_cage_id_vbc_target_id);
}

```

---
Tags: 7, database
---


title: Replace author ID with user name

text:
# Question
Title: Replace author ID with user name
I created a view to display a list of the discussion of my forum. I want to show the author of the last comment, but only the ID is displayed.

How do I replace the author ID with the username ?

```
$view = new view();
$view->name = 'sujet';
$view->description = 'A view to emulate Drupal core\'s handling of taxonomy/term.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Sujet';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'time';
$handler->display->display_options['cache']['results_lifespan'] = '3600';
$handler->display->display_options['cache']['results_lifespan_custom'] = '0';
$handler->display->display_options['cache']['output_lifespan'] = '3600';
$handler->display->display_options['cache']['output_lifespan_custom'] = '0';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'views_bootstrap_table_plugin_style';
$handler->display->display_options['style_options']['columns'] = array(
  'nid' => 'nid',
  'field_image' => 'field_image',
  'title' => 'title',
  'commerce_price' => 'commerce_price',
  'field_rating' => 'field_rating',
  'body' => 'body',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'nid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_image' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'commerce_price' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_rating' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'body' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['style_options']['bootstrap_styles'] = array(
  'striped' => 'striped',
  'bordered' => 'bordered',
  'hover' => 0,
  'condensed' => 0,
);
$handler->display->display_options['style_options']['responsive'] = 0;
/* Relation: Contenu : Auteur */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Relation: Commentaire : Dernier commentaire */
$handler->display->display_options['relationships']['cid']['id'] = 'cid';
$handler->display->display_options['relationships']['cid']['table'] = 'node_comment_statistics';
$handler->display->display_options['relationships']['cid']['field'] = 'cid';
/* Relation: Commentaire : Auteur */
$handler->display->display_options['relationships']['uid_1']['id'] = 'uid_1';
$handler->display->display_options['relationships']['uid_1']['table'] = 'comment';
$handler->display->display_options['relationships']['uid_1']['field'] = 'uid';
$handler->display->display_options['relationships']['uid_1']['relationship'] = 'cid';
/* Champ: Contenu : Titre */
$handler->display->display_options['fields']['title_1']['id'] = 'title_1';
$handler->display->display_options['fields']['title_1']['table'] = 'node';
$handler->display->display_options['fields']['title_1']['field'] = 'title';
$handler->display->display_options['fields']['title_1']['label'] = '';
$handler->display->display_options['fields']['title_1']['exclude'] = TRUE;
$handler->display->display_options['fields']['title_1']['element_label_colon'] = FALSE;
/* Champ: Utilisateur : Nom */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* Champ: Contenu : Date de publication */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = '';
$handler->display->display_options['fields']['created']['exclude'] = TRUE;
$handler->display->display_options['fields']['created']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created']['date_format'] = 'short';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
$handler->display->display_options['fields']['created']['format_date_sql'] = 0;
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = 'Sujets';
$handler->display->display_options['fields']['nothing']['alter']['text'] = '[title_1]

par [name] le [created]';
/* Champ: Contenu : Nombre de commentaires */
$handler->display->display_options['fields']['comment_count']['id'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['label'] = 'Réponses';
/* Champ: Contenu : Uid du dernier commentaire */
$handler->display->display_options['fields']['last_comment_uid']['id'] = 'last_comment_uid';
$handler->display->display_options['fields']['last_comment_uid']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['last_comment_uid']['field'] = 'last_comment_uid';
$handler->display->display_options['fields']['last_comment_uid']['label'] = '';
$handler->display->display_options['fields']['last_comment_uid']['exclude'] = TRUE;
$handler->display->display_options['fields']['last_comment_uid']['element_label_colon'] = FALSE;
/* Champ: Contenu : Heure du dernier commentaire */
$handler->display->display_options['fields']['last_comment_timestamp']['id'] = 'last_comment_timestamp';
$handler->display->display_options['fields']['last_comment_timestamp']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['last_comment_timestamp']['field'] = 'last_comment_timestamp';
$handler->display->display_options['fields']['last_comment_timestamp']['label'] = '';
$handler->display->display_options['fields']['last_comment_timestamp']['exclude'] = TRUE;
$handler->display->display_options['fields']['last_comment_timestamp']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['last_comment_timestamp']['date_format'] = 'short';
$handler->display->display_options['fields']['last_comment_timestamp']['second_date_format'] = 'long';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_1']['id'] = 'nothing_1';
$handler->display->display_options['fields']['nothing_1']['table'] = 'views';
$handler->display->display_options['fields']['nothing_1']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_1']['label'] = 'Dernière contribution';
$handler->display->display_options['fields']['nothing_1']['alter']['text'] = 'par [last_comment_uid]

le [last_comment_timestamp]';
/* Critère de tri: Contenu : Épinglé (en haut des listes) */
$handler->display->display_options['sorts']['sticky']['id'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['table'] = 'node';
$handler->display->display_options['sorts']['sticky']['field'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['order'] = 'DESC';
/* Critère de tri: Contenu : Date de publication */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filtre contextuel: Contenu : Possède l'identifiant de terme de taxonomie (avec profondeur) */
$handler->display->display_options['arguments']['term_node_tid_depth']['id'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth']['field'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['default_action'] = 'not found';
$handler->display->display_options['arguments']['term_node_tid_depth']['exception']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['term_node_tid_depth']['exception']['title'] = 'Tout';
$handler->display->display_options['arguments']['term_node_tid_depth']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['term_node_tid_depth']['title'] = '%1';
$handler->display->display_options['arguments']['term_node_tid_depth']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['term_node_tid_depth']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['term_node_tid_depth']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['term_node_tid_depth']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['term_node_tid_depth']['validate']['type'] = 'taxonomy_term';
$handler->display->display_options['arguments']['term_node_tid_depth']['depth'] = '0';
$handler->display->display_options['arguments']['term_node_tid_depth']['break_phrase'] = TRUE;
/* Filtre contextuel: Contenu : Possède l'identifiant du terme de taxonomie avec modification de profondeur */
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['id'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['field'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['exception']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['exception']['title'] = 'Tout';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['specify_validation'] = TRUE;
/* Critère de filtrage: Contenu : Publié ou admin */
$handler->display->display_options['filters']['status_extra']['id'] = 'status_extra';
$handler->display->display_options['filters']['status_extra']['table'] = 'node';
$handler->display->display_options['filters']['status_extra']['field'] = 'status_extra';
$handler->display->display_options['filters']['status_extra']['group'] = 0;
$handler->display->display_options['filters']['status_extra']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['metatags'] = array(
  'und' => array(
    'title' => array(
      'value' => '[view:title] | [site:name]',
      'default' => '[view:title] | [site:name]',
    ),
    'description' => array(
      'value' => '',
      'default' => '[view:description]',
    ),
    'abstract' => array(
      'value' => '',
      'default' => '',
    ),
    'keywords' => array(
      'value' => '',
      'default' => '',
    ),
    'robots' => array(
      'value' => array(
        'index' => 'index',
        'follow' => 'follow',
        'noindex' => 0,
        'nofollow' => 0,
        'noarchive' => 0,
        'nosnippet' => 0,
        'noodp' => 0,
        'noydir' => 0,
        'noimageindex' => 0,
        'notranslate' => 0,
      ),
      'default' => array(
        'index' => 'index',
        'follow' => 'follow',
        'noindex' => 0,
        'nofollow' => 0,
        'noarchive' => 0,
        'nosnippet' => 0,
        'noodp' => 0,
        'noydir' => 0,
        'noimageindex' => 0,
        'notranslate' => 0,
      ),
    ),
    'news_keywords' => array(
      'value' => '',
      'default' => '',
    ),
    'standout' => array(
      'value' => '',
      'default' => '',
    ),
    'rating' => array(
      'value' => '',
      'default' => '',
    ),
    'referrer' => array(
      'value' => '',
      'default' => '',
    ),
    'rights' => array(
      'value' => '',
      'default' => '',
    ),
    'image_src' => array(
      'value' => '',
      'default' => '',
    ),
    'canonical' => array(
      'value' => '[view:url]',
      'default' => '[view:url]',
    ),
    'shortlink' => array(
      'value' => '[current-page:url:unaliased]',
      'default' => '[current-page:url:unaliased]',
    ),
    'publisher' => array(
      'value' => '',
      'default' => '',
    ),
    'author' => array(
      'value' => '',
      'default' => '',
    ),
    'original-source' => array(
      'value' => '',
      'default' => '',
    ),
    'prev' => array(
      'value' => '',
      'default' => '',
    ),
    'next' => array(
      'value' => '',
      'default' => '',
    ),
    'revisit-after' => array(
      'value' => '',
      'period' => '',
      'default' => '',
    ),
    'content-language' => array(
      'value' => 'fr',
      'default' => 'fr',
    ),
    'geo.position' => array(
      'value' => '',
      'default' => '',
    ),
    'geo.placename' => array(
      'value' => '',
      'default' => '',
    ),
    'geo.region' => array(
      'value' => '',
      'default' => '',
    ),
    'icbm' => array(
      'value' => '',
      'default' => '',
    ),
    'refresh' => array(
      'value' => '',
      'default' => '',
    ),
    'itemtype' => array(
      'value' => '',
      'default' => '',
    ),
    'itemprop:name' => array(
      'value' => '',
      'default' => '',
    ),
    'itemprop:description' => array(
      'value' => '',
      'default' => '',
    ),
    'itemprop:image' => array(
      'value' => '',
      'default' => '',
    ),
    'og:type' => array(
      'value' => '',
      'default' => '',
    ),
    'og:url' => array(
      'value' => '',
      'default' => '',
    ),
    'og:title' => array(
      'value' => '',
      'default' => '',
    ),
    'og:determiner' => array(
      'value' => '',
      'default' => '',
    ),
    'og:description' => array(
      'value' => '',
      'default' => '',
    ),
    'og:updated_time' => array(
      'value' => '',
      'default' => '',
    ),
    'og:see_also' => array(
      'value' => '',
      'default' => '',
    ),
    'og:image' => array(
      'value' => '',
      'default' => '',
    ),
    'og:image:url' => array(
      'value' => '',
      'default' => '',
    ),
    'og:image:secure_url' => array(
      'value' => '',
      'default' => '',
    ),
    'og:image:type' => array(
      'value' => '',
      'default' => '',
    ),
    'og:image:width' => array(
      'value' => '',
      'default' => '',
    ),
    'og:image:height' => array(
      'value' => '',
      'default' => '',
    ),
    'og:latitude' => array(
      'value' => '',
      'default' => '',
    ),
    'og:longitude' => array(
      'value' => '',
      'default' => '',
    ),
    'og:street_address' => array(
      'value' => '',
      'default' => '',
    ),
    'og:locality' => array(
      'value' => '',
      'default' => '',
    ),
    'og:region' => array(
      'value' => '',
      'default' => '',
    ),
    'og:postal_code' => array(
      'value' => '',
      'default' => '',
    ),
    'og:country_name' => array(
      'value' => '',
      'default' => '',
    ),
    'og:email' => array(
      'value' => '',
      'default' => '',
    ),
    'og:phone_number' => array(
      'value' => '',
      'default' => '',
    ),
    'og:fax_number' => array(
      'value' => '',
      'default' => '',
    ),
    'og:locale' => array(
      'value' => '',
      'default' => '',
    ),
    'og:locale:alternate' => array(
      'value' => '',
      'default' => '',
    ),
    'article:author' => array(
      'value' => '',
      'default' => '',
    ),
    'article:publisher' => array(
      'value' => '',
      'default' => '',
    ),
    'article:section' => array(
      'value' => '',
      'default' => '',
    ),
    'article:tag' => array(
      'value' => '',
      'default' => '',
    ),
    'article:published_time' => array(
      'value' => '',
      'default' => '',
    ),
    'article:modified_time' => array(
      'value' => '',
      'default' => '',
    ),
    'article:expiration_time' => array(
      'value' => '',
      'default' => '',
    ),
    'profile:first_name' => array(
      'value' => '',
      'default' => '',
    ),
    'profile:last_name' => array(
      'value' => '',
      'default' => '',
    ),
    'profile:username' => array(
      'value' => '',
      'default' => '',
    ),
    'profile:gender' => array(
      'value' => '',
      'default' => '',
    ),
    'og:audio' => array(
      'value' => '',
      'default' => '',
    ),
    'og:audio:secure_url' => array(
      'value' => '',
      'default' => '',
    ),
    'og:audio:type' => array(
      'value' => '',
      'default' => '',
    ),
    'book:author' => array(
      'value' => '',
      'default' => '',
    ),
    'book:isbn' => array(
      'value' => '',
      'default' => '',
    ),
    'book:release_date' => array(
      'value' => '',
      'default' => '',
    ),
    'book:tag' => array(
      'value' => '',
      'default' => '',
    ),
    'og:video' => array(
      'value' => '',
      'default' => '',
    ),
    'og:video:secure_url' => array(
      'value' => '',
      'default' => '',
    ),
    'og:video:width' => array(
      'value' => '',
      'default' => '',
    ),
    'og:video:height' => array(
      'value' => '',
      'default' => '',
    ),
    'og:video:type' => array(
      'value' => '',
      'default' => '',
    ),
    'video:actor' => array(
      'value' => '',
      'default' => '',
    ),
    'video:actor:role' => array(
      'value' => '',
      'default' => '',
    ),
    'video:director' => array(
      'value' => '',
      'default' => '',
    ),
    'video:writer' => array(
      'value' => '',
      'default' => '',
    ),
    'video:duration' => array(
      'value' => '',
      'default' => '',
    ),
    'video:release_date' => array(
      'value' => '',
      'default' => '',
    ),
    'video:tag' => array(
      'value' => '',
      'default' => '',
    ),
    'video:series' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:card' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:creator' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:creator:id' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:url' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:title' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:description' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:image:src' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:image:width' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:image:height' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:image0' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:image1' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:image2' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:image3' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:player' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:player:width' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:player:height' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:player:stream' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:player:stream:content_type' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:country' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:name:iphone' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:id:iphone' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:url:iphone' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:name:ipad' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:id:ipad' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:url:ipad' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:name:googleplay' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:id:googleplay' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:app:url:googleplay' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:label1' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:data1' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:label2' => array(
      'value' => '',
      'default' => '',
    ),
    'twitter:data2' => array(
      'value' => '',
      'default' => '',
    ),
  ),
);
$handler->display->display_options['path'] = 'taxonomy/term/%';
$translatables['sujet'] = array(
  t('Master'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('auteur'),
  t('Dernier commentaire'),
  t('Sujets'),
  t('[title_1]

par [name] le [created]'),
  t('Réponses'),
  t('.'),
  t(','),
  t('Dernière contribution'),
  t('par [last_comment_uid]

le [last_comment_timestamp]'),
  t('Tout'),
  t('%1'),
  t('Page'),
);

```

# Answer
You should be able to place the Author Name field from Views into your view - using the relationship you have between Comment ID and User ID to fetch the name of the *user who submitted the comment* or using the relationship between Node ID and User ID for fetch the name of the *user who submitted the original Node*

From looking at your exported views it seems you have the neccessary relationships to make this work without significant alterations to your view.
> 2 votes

---
Tags: 7, views, comments
---


# Question
Title: In Commerece 2.x can address be selected in the country's official language?
Upon setting up the address book, how can the select list of Country/Province/City etc. be displayed in the country's local language rather than in English? e.g 廣東省 instead of Guangdong Sheng if China is selected as the Country?

# Answer
> 0 votes
Country and subdivision translations are selected based on the current language. If your site language is "zh" you should be seeing the local labels.

For non-native languages the latin script alternative is shown for readability. If this is not working as I described, you can open an issue in the address issue queue.

---
Tags: commerce
---


# Question
Title: How to show attribute dropdown in add to cart form in Commerce 2.x
The attribute dropdown list doesn't show, instead I get an autocomplete field labelled "Product Variation" and it contains the full title of the variation. When I enter text, a list of variations appear but when selecting a different variation the product doesn't refresh.

I would like it to show the label of the attribute with a dropdown list of the values. I'd like it to say "colour : "Value"". I have two attributes one showing a weight capacity the other a colour. They are both appended to the variation title but I need to select combinations of the two. I've trawled the internet and it seams the dropdown list should work out of the box.

I have a matching Product type and variation type. On the manage display of the product type the variation field format is "Add to Cart". On the variation type the attribute field is enabled but it doesn't show up.

Where am I going wrong please?

# Answer
You have somehow disabled the proper widget. Go to the "Order item types" page and click "Manage form display" for your order item type, the widget for the "Purchased entity" field should be "Product variation attributes".

I would love to find out how your system ended up in this state. Was this a fresh install? Did you create a custom order item type? Let us know in the Commerce issue queue.
> 3 votes

---
Tags: commerce
---


# Question
Title: How to disable sortable headers in Admin theme tables
I'm outputting some data from a custom module as follows

```
theme('table', array('rows' => $rows, 'header' => $headers ));

```

to a custom `/admin` page that will be viewed using the Administrative theme.

Problem is that the headers are generated as (a) clickable and (b) the selected columns have up/down sort arrows. But when you click on the arrows, no sorting happens.

How can I either remove this styling from the header, or implement a sort for the table?

# Answer
> 1 votes
Found the answer by reading this fine article

https://knackforge.com/blog/karalmax/drupal-7-creating-drupal-style-tables-paging-sorting-and-filter

"If you do not want a particular column to be sortable, do not specify the 'field' parameter for its header."

My headers array is now simply

```
   $headers = array(
      array('data' => 'UID'),
      array('data' => 'Username'),
      array('data' => 'Given Name'),
      array('data' => 'Family Name'),
      array('data' => 'Email Address')
    );

```

with no 'field' value specified, and the clickable headers have disappeared.

---
Tags: theming
---


# Question
Title: Is there a node hook that runs AFTER a node is fully inserted into the database?
I want to run some code after a node is inserted into the database. `hook_node_insert()` is close, of course, but as the doc says, "when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress". Is there a hook that I can implement that give me access to the newly-inserted node after it's completely in the database? `hook_path_insert()` does this, and is related to what I want to do, but it's not optimal for all sorts of reasons. Thoughts?

# Answer
> 5 votes
There isn't a hook that is called after the transaction is completed, as the code `node_save()` executes is executed during the transaction.

```
function node_save($node) {
  $transaction = db_transaction();

  try {

    // ...

  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('node', $e);
    throw $e;
  }
}

```

If `node_save()` is called from `node_form_submit()` (the form submission handler for the node form), you can add a form submission handler that is called after `node_form_submit()` to the node edit form. It would be executed after the node is saved in the database.

What the documentation for `hook_node_insert()` means is that, since the data are not still saved in the database table, you cannot query a table making a join with the "node" table, as that table still contains the old data; in the same way, you should not call a function that queries the "node" table.

# Answer
> 8 votes
There is another way this can be achievable by adding your custom callback submit function in hook\_form\_alterwhich will execute after insert/update node.

E.g:
Check the following code which is for article.

```

/**
 * Implement hook_form_alter
 *
 * @param type $form
 * @param type $form_state
 * @param type $form_id
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    // Checking form_id
    if ($form_id == 'article_node_form') {
        // Adding custom callback function.
        $form['actions']['submit']['#submit'][] = '_callback_on_postsave';
    }
}

```

Now you can do your post save functionality in **\_callback\_on\_postsave** function. E.g:

```

/**
 * General Callback for form_alter
 *
 * @param type $form
 * @param type $form_state
 */
function _callback_on_postsave($form, &$form_state) {
    $nid = $form_state['values']['nid'];
    $node = node_load($nid);
    // Do your stuff here
}

```

# Answer
> 3 votes
Easiest solution is to use this module:

Hook Post Action

It allows you to use new hooks:

* hook\_entity\_postsave
* hook\_entity\_postinsert
* hook\_entity\_postupdate
* hook\_entity\_postdelete
* hook\_node\_postsave
* hook\_node\_postinsert
* hook\_node\_postupdate
* hook\_node\_postdelete

---
Tags: 7, hooks
---


# Question
Title: Best way to clear cache / reload site when theming css
I have a huge drupal 7 project.

When I make changes on my css-files and reload the site in the browser (I work locally), the changes do not appear.

I have to clear the cache (theme caching is deactivated in drupal), have to reload the site many time, have to laod .../style.css file in Browser to check if the changes appear in css file ...).

But loading and re-loading the site the changes do not appear. Mybe browser cache is the problem?

What is the best way to to these theming and test after some css changes in browser? (It is a huge projects, loading and clearing cache etc. lasts very very long, so all these things take a lot of time).

How to work timesaving? Thank you.

# Answer
> 1 votes
The best way would be to use Drush for that. Commands are very easy and helps a lot specially with caching.There are other useful features of it.

Drush Git Hubm URL

Specifically, once you have Drush installed. Use 'drush cc' (cache-clear).

---
Tags: 7, theming
---


title: Create RenderArray of Field

text:
# Question
Title: Create RenderArray of Field
In my theme\_preprocess\_taxonomy\_term function I am loading a node. Then want to move its "body field" to the content array of my template.

```
    mytheme_preprocess_taxonomy_term(&$variables){
        $import_content_node_id = 32;
        //load node
        $import_content_node = $node = Node::load($import_content_node_id);
        variables['content']['body'] = $import_content_node->getFields()['body'];
}

```

This does not work because variables\['content'\]\['body'\] is NOT a render array.

But from where I get the render array? Or how do I create one from an by script loaded node?

# Answer
You can use the method `view()` of the field.

Example, to get the render array of the `body` field as configured in the viewmode `full`:

```
$renderarray = $node->body->view('full');

```
> 4 votes

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


# Question
Title: Why is user_role_change_permissions() throwing an error?
I want to change the permission of anonymous user to view content hits only for a blog section. I came across `user_role_change_permissions()`, but it is throwing an error when I use the following code.

```
 if ($user->uid == "0") {
   $custom_role = user_role_load_by_name('anonymous user');
   $custom_rid = $custom_role->rid;
   $custom_permissions = array(
     'view content hits' => TRUE,
   );
  user_role_change_permissions($custom_rid, $custom_permissions);
 }

```

The error I get is the following:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'module' cannot be null: INSERT INTO {role\_permission} (rid, permission, module) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> 1 \[:db\_insert\_placeholder\_1\] =\> view content hits \[:db\_insert\_placeholder\_2\] =\> ) in user\_role\_grant\_permissions() (line 3154 of C:\xampp\htdocs\capacad\modules\user\user.module).

> Notice: Undefined index: view content hits in user\_role\_grant\_permissions() (line 3152 of C:\xampp\htdocs\capacad\modules\user\user.module).

I tried also with `user_role_grant_permissions()`, but it doesn't work too.

How do I set a new permission for a role?

# Answer
It should be like this:

```
if($user->uid == "0"){
  $custom_role = user_role_load_by_name('anonymous user');
  $custom_rid = $custom_role->rid;
  $custom_permissions = array('view content hits');
  user_role_change_permissions($custom_rid, $custom_permissions);
 }

```

Here you have given

> $custom\_permissions = array( 'view content hits' =\> TRUE, );

TRUE should not be there.
> 1 votes

# Answer
As described in `user_role_change_permissions()`, the second argument of `user_role_change_permissions()` (`$permissions`) is:

> An associative array, where the key holds the permission name and the value determines whether to grant or revoke that permission. Any value that evaluates to `TRUE` will cause the permission to be granted. Any value that evaluates to `FALSE` will cause the permission to be revoked.

The array given as example makes clear what that description means.

```
array(
  'administer nodes' => 0,                // Revoke 'administer nodes'
  'administer blocks' => FALSE,           // Revoke 'administer blocks'
  'access user profiles' => 1,            // Grant 'access user profiles'
  'access content' => TRUE,               // Grant 'access content'
  'access comments' => 'access comments', // Grant 'access comments'
)

```

Your code is correct. The problem is that there isn't any module defining the *view content hits* permission. This causes `user_role_grant_permission()` to fail since it is using this code.

```
  $modules = user_permission_get_modules();
  // Grant new permissions for the role.
  foreach ($permissions as $name) {
    db_merge('role_permission')
      ->key(array(
        'rid' => $rid,
        'permission' => $name,
      ))
      ->fields(array(
        'module' => $modules[$name],
      ))
      ->execute();
  }

```

Without a module defining that permission, `$modules[$name]` is `NULL`, but the database field for *module* doesn't accept `NULL` values, and Drupal throws that error.
The warming error is caused by the code I shown, which tries to access `$modules['view content hits']` when that is not a defined index for the `$modules` array.

In short, your code is correct, but you need to use a permission that a module is defining in its `hook_permission()` implementation. It is fine if you set a permission defined by a Drupal core module, or any third-party module. You cannot just set any random permission.

As side note, if the `$user` variable you are using is the global one, you can use the following code.

```
if (user_is_logged_in()) {
   $permissions = array(
     'view content hits' => TRUE,
   );

   $role = user_role_load_by_name('anonymous user');
   user_role_change_permissions($role->rid, $permissions);
 }

```

Otherwise, you can just use the following code, keeping in mind what I said in the rest of my answer.

```
if (!$user->uid) {
   $permissions = array(
     'view content hits' => TRUE,
   );

   $role = user_role_load_by_name('anonymous user');
   user_role_change_permissions($role->rid, $permissions);
 }

```
> 1 votes

---
Tags: 7, users
---


title: How to pass an array to a template?

text:
# Question
Title: How to pass an array to a template?
I am trying to get my first module to work which is supposed to render an array in his own template file.

1) I got an array of variables and return it in my controller

```
        array(
        '#theme' => 'myTheme',
        '#test_var' => $this->t('Test Value'),
        '#array' => array('key'=>$myArray),
        );

```

2) in my .module I declare the hook\_theme()

```
  return array(
'myTheme' => array(
  'variables' => array(
    'test_var' => '',
    'array' => array(),
    ),
),

```

);

3) Then I would like to print the variables I am sure I missing something, and if I'm missing basic knowledge please let me know. I'm sure something is wrong in the hook\_theme since I don't know how to iterate my array in the template file.

```
<p>test_var: {{ test_var }}</p>
<p>{{ array }}</p>

```

If somebody could point me in the right direction, that would be nice :)

edit: the "Test Value" is rendering just fine

# Answer
> 6 votes
The variable names in the render array and theme hook need to match:

```
array(
  '#theme' => 'myTheme',
  '#test_var' => $this->t('Test Value'),
  '#doubles' => array('key'=>$myArray),
);

```

Iterating an array in Twig is pretty straightforward:

```
{% for key,value in doubles %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}

```

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


# Question
Title: Prepopulate new Taxonomy Term's Parent via the URL
I currently have a views page made up of taxonomy terms. Each term has a link next to it that redirects to the Add Term page. The add term page should auto-populate the parent of the corresponding term.

The Prepopulate module should make something like this possible and it works with all other fields, but not with the Parent select field for some reason.

I am using the following query parameter=`?edit[parent][]=24` in the URL (where 24 is the value).

Any help getting this to work with Prepopulate, or using another method would be extremely helpful. Thanks in advance for any assistance.

# Answer
I found out that the fieldset name must also be included, and for whatever reason the "\[\]" is also not required. To get it to work, I used the following:

```
?edit[relations][parent]=24

```
> 1 votes

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


title: Calendar in date exposed filter?

text:
# Question
Title: Calendar in date exposed filter?
I'm looking for a Views exposed filter for node creation date that:

* Shows a calendar (not popup)
* Highlights days corresponding to existing node creation dates
* Allows to click those days to see nodes created on that day

Does such a thing exist?

# Answer
I ended up using the Calendar module to perform what I wanted. But since I was not using the stock Calendar view, I had to customize some things. Basically, Calendar Block and Calendar Period together achieve the display I need. I had to alter these plugins to show them in Views UI - for some reason the module authors decided to hide them :

```
/**
 * Implementation of hook_views_plugins_alter().
 */
function liveblog_views_plugins_alter(&$plugins) {
  unset($plugins['display']['calendar_block']['no ui']);
  unset($plugins['display']['calendar_period']['no ui']);
}

```

I also had to patch the module to avoid a hard-coded condition, as explained in this issue I submitted: http://drupal.org/node/1409520.

Based on this, I edited my view to add a Calendar Block display, with a Date argument, and a Calendar Period display attached to the Calendar Block, with the same argument. That was it!
> 0 votes

# Answer
This issue will help you out
http://drupal.org/node/502824
> 0 votes

# Answer
You could use views and date or date picker module like datepick

> This module extends the date\_popup module (from the date project) to provide a JQuery UI inline datepicker, rather than a popup out of a textfield. For an example of this see http://jqueryui.com/demos/datepicker/#inline

There are 3 ways to use this module.

Using the Views filter handler for Date filters. Using the Form API, by setting #type to "datepicker",

With views you can use jQueryUI Date picker see here for a tutorial.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: How to use Tokens [current page arguments]?
I dont know how to use tokens to get arguments from url.

I have url: **site/country**

On this page i have links to terms, i want them to have in alias first argument from current page **/country/term-name**.

But instead of this my terms have alias **/batch/term-name** Can i have a little help and show me a little example of how to use tokens of current

# Answer
If you want to use tokens with taxonomy terms urls you have to enable token, pathauto and Chaos tools module. You can do it by runing drush command **drush en pathauto -y** After these modules are enabled go to admin/config/search/path/patterns

Hope this is what you asked about.
> 0 votes

---
Tags: 8
---


# Question
Title: How to add client side validation to form via FAPI?
I can't figure what to add Client Side Validation for form fields.

```
'#element_validate' => array('_file_generic_settings_max_filesize'),

```

I also don't know which value to put for different types of validation such as digit, email etc. '#element\_validate' =\> 'email',

Also if I use this documentation https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7.x/#element\_validate:

```
'#element_validate' => array('email'),

```

it states that it needs to be string not an array.

And after all this documentation doesn't state that how to add validation instead just creating own validation: https://www.drupal.org/node/1324788

# Answer
Solution was to add following for each integer field with form alter:

```
['#rules'] = array('digit');

```

And perhaps it was also needed to set 'views\_exposed\_filters' as a custom form for validation in the settings of Client Side Validation module.
> 1 votes

---
Tags: forms
---


# Question
Title: Boolean checkbox in sytems_settings_form
I have written the following code

```
$form['checking'] = array(
    '#type' => 'checkbox',
    '#default_value' => variable_get('checking',0),
    '#title' => t('title'),
    '#required' => TRUE
  );

  return system_settings_form($form);

```

the checkbox preserve its checked and unchecked state in the form but I can't get value of the checkbox.

I'm printing its value

```
dsm(variable_get('checking);
print_r(variable_get('checking',0));

```

Whether a checkbox is checked or unchecked, in both cases it returns me `1`

How can I know whether the checkbox is checked or not?

# Answer
> 1 votes
Have you tried removing the "#required" =\> TRUE line? If you uncheck the checkbox and the form item is required the form won't validate and your submit callback will not be called.

Also, you should check that your variable isn't overridden in settings.php https://www.drupal.org/node/1525472

# Answer
> -1 votes
hmmm, looks like you're print\_r'ing the result from *variable\_get()* \- ie. you're unwillingly asking "did *variable\_get()* run correctly?"

try storing the result from *variable\_get* in a variable then print\_r'ing that. or use *dsm()* instead (from the **Devel** module).

cheers, Luco

---
Tags: 7, forms
---


# Question
Title: How can I add a custom currency to commerce?
I'm trying to add a custom currency (like points) but I can only choose the "real world" currency. Can I change the currency in commerce or I have to do it with a module? If so, which module should I use? Thank you ! PS: I have to do it in commerce, is for a school project

# Answer
Have a look at the Commerce Userpoints module. Some details from its project page:

> It allows users to create commerce\_line items with negative points value, behaving like a discount system in the order process.
>
> The user can choose how many points he wants to use, they will be automatically taken from his userpoints account.
> 1 votes

---
Tags: commerce
---