# Question
Title: How to add prefix and suffix to certain vocabulary term names
I have vocabulary *Height*, with terms 50, 100, 150, etc. On the Taxonomy page, I want the title "Height 50 mm", "Height 100 mm", "Height 150 mm" etc. I know it must be something like this, but the code doesn\`t work for me; it applies the change to all taxonomy, not just my terms.

```
<?php
function mytheme_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term') {
    $tid = arg(2);
    $term = taxonomy_term_load($tid);
    $name = t('Height !name mm', array('!name' => $term->name));
    $vars['title'] = $name;
  }
}
?>

```

How can I apply the title change only to my height vocabulary?

# Answer
> 2 votes
`taxonomy_term_load()` loads a taxonomy object with the `vid` property. You can use that in your logic to target specific vocabulary in your preprocess function. For example:

```
function mytheme_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term') {
    $tid = arg(2);

    // Only alter if we have a valid taxonomy.
    if ($term = taxonomy_term_load($tid)) {

       // Check that the taxonomy is a part of vocab ID = 1
       // @TODO: replace 1 with specified vocabulary ID.
       if ($term->vid == 1) {
         $name = t('Height !name mm', array('!name' => $term->name));
         $vars['title'] = $name;
       }
    }
  }
}

```

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


# Question
Title: How to create multiple variants of a page in page manager
I'm attempting to create multiple pages that use panels within a page in page manager.

For example I'm trying to create the path

```
127.0.0.1/brands

```

And have multiple pages that follow that same path like the following

```
127.0.0.1/brands/brand1
127.0.0.1/brands/brand2
127.0.0.1/brands/brand3

```

I created multiple variants for each brand in the brands page manager. I had a feeling that I could create the various subpages by using the 'Request Path' selection condition. But I've attempted the following

```
/brands/brand1
/brand1

```

and all of these lead to a 'page requested not found' when visiting 127.0.0.1/brands/brand1

Is there a way to create a sub page of a page using page manager, without creating a whole new page?

# Answer
> 1 votes
Create a page with the url /brands and add your variants. Use the "String: URL Path" selection rule to manage each one.

How to:

Under selection rules for the main (panel) page add the "String: URL Path" rule with a single line "/brands"

Do the same with the variants but: Under the first variant use /brands/brand1 Under the second variant use /brands/brand2 ... ...

---
Tags: 8, panels
---


# Question
Title: how to dynamically set query parameter on menu item
Hello I am a very experienced web dev who is brand new to Drupal and learning to build my first site in it.

I have a very simple site I am converting from pure code (html, css, jquery, angular, bootstrap, php) to drupal so that I can add a CMS backend to the site. On this site I need to track what ad campaign sent the user to the site to be stored with the users information later after they submit their email to be contacted again.

This is how it works currently on the non-drupal site: User clicks on a link on an 3rd party site that directs them to my-site.com/get-eBook.html?campaign=google. On get-eBook.html there is a menu item for /ebook-register.php, I use some PHP to grab the value of campaign from the URL and if it is not null I update the menu item to /ebook-register.php?campaign=google in order to pass the value along to the register page where it is used in a SQL statement and captured in the DB with the users email address.

Now I'm not sure how to accomplish the same thing in Drupal. I have my theme set up, I have two pages created (get-ebook and ebook-register) and I have my menu set up with the link to ebook-register. I however have no idea how I can grab the value of campaign on the get-ebook page and add that value onto the desired menu item being returned by the drupal core so that the value of campaign will be preserved when the user navigated from get-ebook to ebook-register.

Any ideas on how I can allow the menu to be maintained via the Drupal backend but still have the ability to dynamically add query parameters to the items after they're returned from the core?

# Answer
> 0 votes
The way I would do this would be overriding the menu link.

You can override a menu link by doing a theme override of theme\_menu\_link() however you don't want to modify the structure of the markup you want to modify the data being printed (in this case the link query string) so I would recommend overriding the variables of that function in hook\_preprocess\_HOOK() (in this case hook\_preprocess\_menu\_link()).

Template variable overriding is often done in the theme, and you can do it in your theme's template.php file, however in your case I would recommend a custom module because this is functionality not visual display. If you put it in your theme's template.php and then change themes it will stop working, which is probably not what you want.

So it would be best in a custom module.

If you look back at the docs for theme\_menu\_link() you can see that the link is created using the l() function and looking at the parameters to the l() function you see that the $options parameter can contain "Additional $options elements used by the url() function", which you can see from the url() docs includes the query string, which is a non-encoded array of key/value pairs.

So from that you can tell that in your theme function preprocessor you need to modify/add your query string in `$element['#localized_options']['query']` something like this:

```
$variables['element']['#localized_options']['query']['campaign'] = 'google';

```

You can also see that the URL of the link is in `$element['#href']`. Since you probably want to affect all links that point to that path I would suggest overriding the link options based on path.

Since you can access the current page's query parameters using basic PHP's superglobal $\_GET you then have all the information you need to set your menu item.

You can do it like this:

```
/**
 * Variable preprocessor for the themeing of menu links.
 *
 * @see theme_menu_link().
 */
function MODULENAME_preprocess_menu_link(&$variables) {
  // If we have an ebook campaign code then add it to the ebook register
  // menu link.
  if ($variables['element']['#href'] == 'ebook-register.php' && !empty($_GET['campaign'])) {
    // Just add our query array element instead of setting query to a new
    // array to avoid possibly overwriting other query parameters.
    $variables['element']['#localized_options']['query']['campaign'] = $_GET['campaign'];
  }
}

```

One other thing worth nothing is that generally in Drupal you shouldn't have pages as custom PHP scripts like ebook-register.php.

Instead you should have a custom module that implements hook\_menu() to make the path 'ebook-register' call a custom callback that then contains your page logic. See the drupal menu system docs for more information (D6 & D7 have the same menu system) and also the examples module's menu & page examples.

# Answer
> 0 votes
**Drupal always caching menu and menu items**, so you can not have custom menu item for each visitor. Sure you can do it by altering menu link but you will face caching/performance issues with this, because this is like having custom item URL for each visitor.

Performance wise: don't use the scope you are talking about try to reach the final result with another way.

I suggest to re-think about how you do this to get the final result. I mean think to save campaign name in the user cookies (client-side) or user session at first page view instead of have this in the URL and move the value to all internal URLs. So, you will save the value in cookie from URL at first time. You can save the value by cookie using jQuery for example, and get the value in server side when submitting form.

---
Tags: theming
---


# Question
Title: how can I change all price view in drupal commerce
I want to change default drupal view of price in all of my field, as a example I want to remove '00' and add my custom postfix to it,

I found `hook_commerce_price_field_formatter_prepare_view` but when I implement it in my module it not called,really I am not sure this hook is suitable and ca achieve my need??

I just want the all price fields changes to my desire only in front-end view (only in view, because my payment method is according to main currency)

# Answer
> 3 votes
You can do this using the Commerce Currency API

Implement `hook_commerce_currency_info_alter` and add your own `commerce_currency_format` handler

e.g:

```
/**
 * hook_commerce_currency_info_alter
 *
 * Add custom currency format to selected currencies
 */
function MY_MODULE_commerce_currency_info_alter(&$currencies){
  $currencies['IRR']['format_callback'] = 'MY_MODULE_commerce_currency_format';
}

/**
 * Currency format callback
 *
 * Remove decimal places from output
 * while keeping commerce_amount_to_decimal formatting the same
 *
 * See: commerce_currency_format
 */
function MY_MODULE_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {

  // Format the price as a number.
  // In our case, we remove decimal places
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  // Establish the replacement values to format this price for its currency.
  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

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

```

# Answer
> 1 votes
I'm gonning to complete what David Thomas wrote. 1/ Create a custom module with the code. Replace My\_Module by the name of your module.

```
/**
 * hook_commerce_currency_info_alter
 *
 * Add custom currency format to selected currencies
 */
function MY_MODULE_commerce_currency_info_alter(&$currencies){
  $currencies['IRR']['format_callback'] = 'MY_MODULE_commerce_currency_format';
}

/**
 * Currency format callback
 *
 * Remove decimal places from output
 * while keeping commerce_amount_to_decimal formatting the same
 *
 * See: commerce_currency_format
 */
function MY_MODULE_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {

  // Format the price as a number.
  // In our case, we remove decimal places
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  // Establish the replacement values to format this price for its currency.
  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount  $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

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

2/ Go to **Custom Currency Setting** (admin/commerce/config/currency/custom-settings) and setup the field Format Callback with: My\_Module\_ommerce\_currency\_format

At this point your node will display what you asked, but not your views (or your fields).

3/ To use this setting into your views display, you have to display the node inside your views. If you display a field it won't work. **Views \> Show: Content**

Cheers

---
Tags: entities, commerce
---


# Question
Title: All "administration pages" in English and admin menu always LTR?
I added a RTL language translation file (e.g. Arabic, Persian, Farsi) to my Drupal 8 site. I want all the administration menus to always be in English and LTR. On the other hand, I want the front-end pages of my site to be in another language (e.g. Persian, Farsi).

I did the following.

1. I enabled the Language module, and set up one additional language. Installation was done in English; I added Persian.
2. I configured the administration language using the following settings.

* /admin/config/regional/language/detection
    Account administration pages: enabled
3. Admin \>\> Edit Profile \>\> Edit

This works properly for all the administration pages. Those are in English and LTR except the front page, user/1/, and admin/structure/block/demo/\[theme name\] where the administration menu is in Persian and RTL.

# Answer
For forcing the administration menu to be LTR, and get rid of jumping to right side, you can add the following styles to the style.css file in the template folder of your site.

```
/* Administration Toolbar
------------------------------------------------------------------ */
//#toolbar-administration, #toolbar-administration *{
    box-sizing: border-box;
    float: left;
    direction: ltr;
}

[dir="rtl"] .toolbar .toolbar-bar .toolbar-tab,
[dir="rtl"] .toolbar .toolbar-tray-horizontal li {
  float: left;
}

[dir="rtl"] .toolbar .toolbar-tray-horizontal > .toolbar-lining {
  padding-right: 5em;
  padding-left: 0;
}

[dir="rtl"] .toolbar .toolbar-bar .contextual-toolbar-tab.toolbar-tab {
    float: right;
}

[dir="rtl"] .toolbar .toolbar-icon {
    padding-right: 1.3333em;
    padding-left: 2.75em;
}

[dir="rtl"] .toolbar .toolbar-icon::before {
    right: auto;
    left: 0.6667em;
}

[dir="rtl"] .toolbar-oriented .toolbar-tray-horizontal .toolbar-toggle-orientation {
    right: 0;
    left: auto;
}

[dir="rtl"] .toolbar .toolbar-bar .toolbar-tab > .toolbar-icon {
    background-position: right center;
    padding-right: 1.3333em;
    padding-left: 2.75em;
}

[dir="rtl"] .toolbar .toolbar-bar .toolbar-tab > .toolbar-icon::before {
    right: auto;
    left: 0.6667em;
}

/* Toolbar Tray Vertical
------------------------------------------------------------------ */
[dir="rtl"] .toolbar-oriented .toolbar-tray-vertical.is-active {
    right: auto;
    left: 0;
}

[dir="rtl"] .toolbar .toolbar-tray-vertical .toolbar-menu a {
    padding-right: 4em;
    padding-left: 2.75em;
    text-align: left;
}

[dir="rtl"] .toolbar .toolbar-icon.toolbar-handle {
    right: 0;
    padding: 0;
    left: auto;
}

[dir="rtl"] .toolbar .toolbar-tray-vertical .toolbar-menu ul a {
    padding-right: 0;
    padding-left: 2.75em;
}

[dir="rtl"] .toolbar .toolbar-tray-vertical .toolbar-menu ul ul a {
    padding-right: 0;
    padding-left: 3.75em;
}

[dir="rtl"] .toolbar .toolbar-toggle-orientation > .toolbar-lining {
  float: right;
}

```

See also Admin toolbar should always be rendered in the admin language (if set).
> 2 votes

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


# Question
Title: Make changes to <head> for homepage only
I need to insert hreflang tags in the head tags, but I only need these on the homepage. At the moment I'm inserting the hreflang tags into the head via the html.tpl.php template, but this puts the code on all pages in the site. How can I edit the head for just one page? I'm using Drupal 7.

# Answer
> 3 votes
You can use:

```
<?php if ($is_front): ?>
 <!-- code here-->
<?php endif; ?>

```

In your html.tpl.php and it'll only affect the homepage.

# Answer
> 2 votes
You can set the condition for front page in html.tpl.php, so set your required flag. Use the condition like:

```
<?php
  if (drupal_is_front_page()){
    // print the desired code
  }
?>

```

# Answer
> 1 votes
I suggest you three solution.

1. Duplicate your `html.tpl.php` and rename one of them to `html--front.tpl.php`, apply your change( hreflang tags ) then clear the cache.
2. another solution is with simple condition apply what you want in `html.tpl.php`, I mean

put your markups here

**But** $is\_front not exists in html.tpl.php varibles and by default available in page templates,you can add it manually by using template\_preprocess\_html

```
function hook_preprocess_html(&$vars) {
  $vars['is_front'] = drupal_is_front_page();
}

```
3. use PHP function in your `html.tpl.php`

( although if you use PHP function in theme, you should forget using PHP in template in Drupal 8 )

```
<?php if (drupal_is_front_page()): ?>
 put your markups here
<?php endif; ?>

```

# Answer
> 0 votes
use html\_head\_alter in template.php and add conditions

```
 function your theme_html_head_alter(&$head_elements) {

$remove = array(
        'apple-touch-icon57',
        'apple-touch-icon72',
        'apple-touch-icon114'
);

foreach ($remove as $key) {
    if (isset($head_elements[$key])) {
        unset($head_elements[$key]);
    }
}

//add
$appleIcon57px = array('#tag' => 'link', '#type' => 'html_tag', '#attributes' => array('rel' => 'apple-touch-icon', 'href' => '/misc/AMU-NUMERIQUE-ICONE-57.png', 'type' => 'image/png', 'media' => 'screen and (resolution: 163dpi)'),);
$appleIcon72px = array('#tag' => 'link','#type' => 'html_tag', '#attributes' => array('rel' => 'apple-touch-icon', 'href' => '/misc/AMU-NUMERIQUE-ICONE-72.png', 'type' => 'image/png', 'media' => 'screen and (resolution: 132dpi)'),);
$appleIcon114px = array('#tag' => 'link','#type' => 'html_tag', '#attributes' => array('rel' => 'apple-touch-icon', 'href' => '/misc/AMU-NUMERIQUE-ICONE-114.png', 'type' => 'image/png', 'media' => 'screen and (resolution: 326dpi)'),);

$head_elements['apple-touch-icon57']=$appleIcon57px;
$head_elements['apple-touch-icon72']=$appleIcon72px;
$head_elements['apple-touch-icon114']=$appleIcon114px;
}

```

---
Tags: 7, theming
---


# Question
Title: Webform block: reload page with anchor link
I have a webform shown in a block that appears at the bottom of my page.

If I select 'no redirect (reload current page)' when the form is submitted you are taken back to the top of the page and the confirmation message is shown above the form, so unless you scroll down it appears as if nothing happened.

If I select 'Custom redirect URL' and enter `[current-page:url]#my-form` when the form is submitted you do get taken down the page to the form only now the confirmation message is shown at the top of the page, so unless you scroll up you won't see it.

Is there a way to refresh the page, scroll down to my form and show the confirmation above it or do I have to use AJAX for this?

# Answer
> 0 votes
You can achieve that by using the Webform Ajax module

> This module adds AJAX support to Webform (3.0 and above).
>
> As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.

---
Tags: ajax, webforms
---


title: Images referring wrong path

text:
# Question
Title: Images referring wrong path
I uploaded some images in content. the images are uploaded to "sites/default/files". but in node page the images are referring "sites/default/files/styles/large" path. how to change it?

# Answer
It is showing the image with default image style of the field, you could change it, I will show you with the "Article" Content type, Goto the page `/admin/structure/types/manage/article/display` you can see the image field in that list, just click the gear icon right side of the image field and then change the 'Image Style' as None (Original Image). It would show you the original images in the node view page.
> 2 votes

# Answer
> Images refering wrong path

I would say, Image is not referring any wrong path and there is nothing wrong in what you are seeing. Whatever you are seeing is by design in Drupal.

If you defined the Image style, the corresponding files automatically gets prepared in the folder. Hence if you upload an image the image gets uploaded at one default place which is for `original images`, But if you have defines the image style for that content type, then images gets saved at other place also. Hence In your case both "sites/default/files" and "sites/default/files/styles/large" are true. You can see the same image at two places.

For Example,

I just uploaded the image in Article and article content type has the image style `Large`. So that image gets uploaded at two places, as below in my folder.

```
FOR ORIGINAL IMAGE - sites/default/files/field/image/exampleImage.jpg
FOR LARGE IMAGE STYLE - sites/default/files/styles/large/public/field/image/exampleImage.jpg

```

So, same way, if I declare new Imgae style, like Medium Or Thumbnail, the new file with that name gets created and image gets saved there.

Hence, I am not getting why you want to change the path. There is nothing wrong in path. It is by Drupal's default desing. Hence, you not have any problem in your folders.

**Hence for image, There is not a concept of changing path here. There is a concept of changing the *Image style* and image style choose their own folder automatically which is path.**

So, you can go to Structure/content type/exampleType/Manage Display/ and from there you can change the Image style which you want and that image style will create/choose its own folder automatically.
> 3 votes

---
Tags: files, media
---


# Question
Title: How can I display the vocabulary description?
I have a View which displays content by taxonomy term from a particular vocabulary, and everything is going fine... except for one thing. I would like to display the Vocabulary description in the View header. I have succeeded in doing this by creating an attachment in the View which just does a select on the Vocabulary but this seems to me rather cumbersome and I wondered if there is a better way to do it.

Also, although I have succeeded in attaching my Attachment to the main Page in the View, I cannot see any way of controlling the order in which they appear. As it happens, things appear in the order I want but it seems to be more by accident than anything else.

# Answer
An `attachment` is the cleanest way to do this using the Views Admin UI. Attachments can be re-ordered in the region they are placed in the parent view.

Another way to do this which requires code is to use `hook_views_pre_view()` and to create a blank `Views Header Area` in your views admin area -- then in code via `hook_views_pre_view()` set the content of that area using PHP to the description of your taxonomy term. But I would recommend trying to stick to the Views Admin for creating your views, as the more custom code you put in files/modules the harder your site is to maintain or change.
> 1 votes

# Answer
```
function YOUR_FUNCTION_NAME() {

  $vocabulary = taxonomy_get_vocabularies();
  $checklist_vocab_array = array(); /* Change to array('0' => '--none--'); if you want a none option*/
  foreach ($vocabulary as $item) {
  $key = $item->vid;
  $value = $item->name;
  $checklist_vocab_array[$key] = $value;
  }

  $form['YOUR_MODULE_NAME_YOUR_FORM_NAME'] = array(
    '#type'             => 'checkboxes',
    '#title'            => t('List of current Vocabularies.'),
    '#position'         => 'left' ,
    '#options'          => $checklist_vocab_array ,
    '#default_value'    => variable_get('YOUR_MODULE_NAME_YOUR_FORM_NAME'),
    '#description'      => t('List of vocabularies displayed as checkboxes'),
  );
     return system_settings_form($form);
}

```

for more information checkout this https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy\_get\_vocabularies/7.x
> 0 votes

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


# Question
Title: How to use the Rules module for assigning a role during user registration based on a select field option?
I need to assign a role to user based on select field at the time of registration.

I have added a field in user registration form (ex: school checkbox) . When user click on school I need to assign a school role to user . otherwise default user role assign by drupal. For this I tried to create role but its not working.

```
{ "rules_user_reg" : {
    "LABEL" : "user reg",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_selector" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "account:roles" ], "value" : { "value" : { "6" : "6" } } } }
    ]
  }
}

```

# Answer
> 1 votes
You need to add a Rules Condition (after the one you already have) to check the value of `field_selector`.

With that your Rules Action should work. Though you also may want to add the Conditional Rules module to implement the "otherwise" part of your question.

# Answer
> 0 votes
Hi according to your requirement this module is useful for you Auto Assign Role and you will get option at the time of account registration http://prntscr.com/bua7cp

---
Tags: 7, rules
---


# Question
Title: Why isn't  the node ID available as "replacement pattern" for the title link?
I have a simple view for a node using an "unformatted list" and fields. I want to link the title to another URL and pass the NID. However, as "replacement pattern" I only have the "\[title\]" token. When I add the NID field to the view I can link it just fine. What am I missing?

# Answer
> 4 votes
You've to add the nid field and exclude it from display, after your NID must be before your title and you'll have access to it.

Even, if is not right, normally you'll have it.

# Answer
> 1 votes
Yvan is right: If you want any link reference, that reference field needs to be added before active (title) field. In that way, you can use "\[id\]" in your pattern.

# Answer
> 1 votes
You have to rearrange and place the Nid (Nid) at the top ( first position )

---
Tags: 7, views
---


title: "is-active" class on all menu levels

text:
# Question
Title: "is-active" class on all menu levels
My main navigation menu is visually split as in the picture:

Level 1 is visualised in the upper-right corner, level 2 below.

`Technology` (like all the current items in level 2) is child of `About`.

In the screenshot, `Technology` has been assigned the class `is-active`. Is there a way to also assign it to `About`? In other words, I would like the entire active branch of the menu to be displayed as active.

# Answer
> 6 votes
You can achieve that by using the Menu Trail By Path module.

> Menu Trail By Path sets the active-trail on menu items according to the current url.
>
> For example if you are at yoursite.com/blog/category1/article1 Menu Items with these paths will get the active-trail class on them and expand accordingly.
>
> blog blog/category1 blog/category1/article1
>
> **8.x-1.x branch**
>
> 8.x-1.x branch is completely rewritten. It should be compatible with any menu.

---
Tags: 8, navigation
---


# Question
Title: How to Add Block with Page on the same view?
Initially, I have displayed the contents in the Block on View. Now I am trying to display Taxonomy Term in the Page ,with Block on the same view.

There is a ADD button in the View, if I add the page for Taxonomy Term in that view, It's showing the same content information for the Page.

How do I add Taxonomy Term for Page and Content for Block on the same View.

Please anyone help me how to sort out this problem.

# Answer
> 2 votes
In Views, click on +Add button and select `Attachment`. (This part is optional, if you have a view block already created you can just attach that).

Make your attachment look like your block.

Now go to your page view in the FOOTER add `Global: View area` and select your attachment or block.

---
Tags: views, nodes, taxonomy-terms
---


# Question
Title: set min - max values drupal date_popup timepicker
Is it possible to set the minimum and maximum values of the timepicker in a date\_popup field? I use this code for the field, but something like 'minTime' is not working.

```
  $form['fetch_date'] = array(
    '#type' => 'date_popup',
    '#description' => t('Datum waarop u uw bestelling wil ophalen.'),
    '#required' => TRUE,
    '#title' => 'Afhaal Datum',
    '#datepicker_options' => array(
      'minDate' => 0,
    ),
  );

```

# Answer
> 0 votes
You may find this one helpful.

Datepicker: minDate and maxDate

# Answer
> 0 votes
try this code

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

  switch ($form_state['view']->name) {
  case 'my_view_name':
    // the Date object works only with this date format:
    $datemask = 'Y-m-d';
    $form['field_date_value']['min']['#default_value'] = date($datemask, time()-30*86400);
    $form['field_date_value']['max']['#default_value'] = date($datemask);
    break;

    $datemask = 'd/m/Y';
    $form['field_date_value']['min']['#date_format'] = $datemask;
    $form['field_date_value']['max']['#date_format'] = $datemask;
  }
}

```

---
Tags: 7, datetime
---


title: AHAH callback is not working

text:
# Question
Title: AHAH callback is not working
I have a form element in d8 as follows :

```
$form['cluster_dropdown'] = array(
    '#type' => 'select',
    '#title' => 'Cluster',
    '#options' => $cluster_options,
    '#default_value' => $cluster_selection,
    '#ahah' => array(
      'path' => 'module_name/admin5/callback',
      'wrapper' => 'dependent-dropdown-wrapper',
      // 'event' => 'change', // default value: does not need to be set explicitly.
    ),
    '#attributes' => array('class' => 'cluster-dropdown'),
  );

```

But in this case `ahah` callback is not working , is there `gasf/admin5/callback` want to replace with `routing path` as am using this in d6? any idea ?

# Answer
> 4 votes
Neither *#ahah* nor *path* are used in Drupal 8. Instead of the first, Drupal 8 uses *#ajax*; instead of the second, it uses *url* which must be a \Drupal\Core\Url to which to submit the Ajax request.

Finally, *callback* is a PHP callback, which generally is a full qualified (using a PSR-4 namespace) method name.

### Reference

---
Tags: 8, ajax
---


# Question
Title: How to block / restrict a list of URLs using Rules?
I'm currently blocking access to some admin menu pages using the Rules module as follows:

**Events**: Drupal is initializing

**Conditions**:

* Data comparison \> Data to compare:\[site:current-page:url\] then URL1 to block
* Data comparison \> Data to compare:\[site:current-page:url\] then URL2 to block
* Data comparison \> Data to compare:\[site:current-page:url\] then URL3 to block
* ...

**Actions**:

* Show a message on the site
* Page redirect to home

I want to supply a list of URLs in one field rather than multiple data comparison conditions, is this possible in Rules?

# Answer
> 2 votes
Assume the relative paths for your 3 URLs are like `my/path1` (for `ULR1`), `my/path2` (for `ULR2`) and `my/path3` (for `ULR3`). And assume your homepage has a relative path `MyHomePage`. And assume this question is about D7.

With these assumptions, you could use a rule that answers your question which looks like so (in Rules export format):

```
{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "site:current-page:path" ],
          "op" : "IN",
          "value" : { "value" : [
              "my\/path1",
              "my\/path2",
              "my\/path3"
            ]
          }
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "MyHomePage" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.",
          "type" : "warning"
        }
      }
    ]
  }
}

```

Note `site:current-page:path` token in this rule, which is different from `site:current-page:url`.

To make the above rule work in similar situations, just adapt the paths by changing 'my/pathX' (with X=1, 2, 3) to whatever fits. And adapt the message to be shown.

Some more samples where you can see this technique at work:

**Remark**: Instead of using a data comparison in this Rules Condition, you may also want to try using a text comparison. That would allow you to use regular expressions. If your URLs have a common pattern for which you can write to single regular expression (such as URLx, with x=1, 2, 3, ..., 456, 457, ...), you would only need 1 such Rules Condition.

# Answer
> 1 votes
You can achieve what are you looking for by using "**Execute custom PHP code**" as @2-Stroker mentioned.

If you consider **Execute custom PHP code** as an option to solve your issue, you need to do the following:

* First enable **PHP filter module**
* In your rule add a condition element
* In condition dropdown list select **Execute custom PHP code**
* In the PHP code section add the following code and change URLs accordingly

code:

```
$urls = array('/admin/whatever-url-1', '/admin/whatever-url-2', '/admin/whatever-url-3');

if(in_array(request_uri(), $urls)) {
  return true;
}

```

---
Tags: rules, redirection
---


title: Making a home page without /home

text:
# Question
Title: Making a home page without /home
My website is mycapecodvacations.com I need help how to make the default home page mycapecodvacations.com instead of going to mycapecodvacations.com/home I'm using host gator .com and want to know how to make the home page without /home and just " mycapecodvacations.com" i tried removing the htaccess file. do I need to edit a specific file?

# Answer
You can use Global Redirect module.

> Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match.

Every time when mycapecodvacations.com/home is accessed, Global Redirect will redirect to mycapecodvacations.com.
> 0 votes

# Answer
You need to go to: **admin/config/system/site-information**

Then leave in blank the **Deafult Homepage**

And if you want to customize your homepage HTML, you can create a new TPL (You just need to place it where your main **page.tpl.php** is) called:

**page--front.tpl.php**
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: what's the difference between using js injector module and ['#attached']['js']
Please can any one tell me what's the difference between:

* adding a java script to a webform using js injector module
And
* adding it using Implements `hook_form_alter()` and `$form['#attached']['js']`

# Answer
Technically the difference is very small.

Whatever js you add in `$form['#attached']['js']` is added via drupal\_add\_js() when the form attachments are processed using drupal\_process\_attached() \- just like the JS Injector Module adds js snippets using drupal\_add\_js().

The JS Injector page claims the js it serves is loaded last, so order is an aspect where the two approaches may differ, unless you do some manual adjusting of the loading order afterwards.

If you try to decide what to use - it really depends. If it is just a minor snippet you want to add, the injector has the advantage that you don't need to write an entire custom module just to add some minor js functionality. It might also be nice for front end designers who know js, but have little experience with php or writing modules. If the js to add is part of a larger module/functionality upgrade anyway though, there is little reason to make use of the JS Inspector Module.
> 1 votes

# Answer
The most important difference is all JavaScript code in js\_injector module will only exists in Database, which cannot be managed by version control software. It can be a disaster.
> 1 votes

---
Tags: 7, hooks
---


# Question
Title: Redirect user back to the private page after they have logged in
On my site I have a private page that can only be accessed when the user is logged in. If they aren't logged in they are directed to the login page.

I want to redirect them back to that page after they've logged in

I've tried a lot of solutions already listed on here including: logindestination and logintoboggan.

Every time the person logs in they are always directed to their user page no matter what I change in logintoboggan/logindestination

I tried creating a rule but was getting a 404. I'm not sure what to put in the PHP Evaluation field in the redirect action.

I've added this to my template file

```
global $user;
    if ($user->uid == 0){
        print l("Login","user/login",array('query' =>     drupal_get_destination()));
    }
else{
print l("Logout","user/logout",array('query' => drupal_get_destination()));
}

```

And then in logindestination I added

```
$destination = drupal_get_destination();
print $destination;

```

What am I doing wrong??

# Answer
For logindestination to work properly all you need to do is add an entry using `<current>` as the redirect location. Leave the "Redirect to Page" option as `Internal page or external URL`. This configuration will send a user back to the page they were trying to access before being sent to the login page.
> 2 votes

---
Tags: users, redirection, authentication-authorization
---


title: Add views past date filter dropdown

text:
# Question
Title: Add views past date filter dropdown
Tried if someone has already faced or tried for this but I could not find any forum discussion around this.

Within Drupal views I am trying to add date filter based on a CCK date field. I am trying to add date filter within views like:

* Past 7 days
* Past one month
* Past 3 months
* Past 6 months
* Past one year

I don't see any modules to achieve this neither any discussion around this

# Answer
The Date module has a submodule called **Date Views** that allows Views integration with Date fields.

Once enabled, you should be able to add an **Exposed**, **Grouped** filter on your date field. For each grouped filter, you can add your **Label** (e.g. "Past 7 days"), **Operator** (*is between*), & **Value** which you can set to Relative dates that match your label (e.g. **From:** "-7 day" / **To:** "now").
> 1 votes

---
Tags: 7, views
---


title: Custom Block with form does not submit

text:
# Question
Title: Custom Block with form does not submit
I made a custom form. After submitting you are redirected to a custom page and get a message there. So far nop.

Then I made a custom block that renderw this form into a block region. Everything appears well.

However when submitting this same form, no redirection. I am on localhost and suspect that the form is not submitting in this block. After submit I see all values in the url of my page, just like the method is GET. When I check the code the method is POST, just like the original form, also Drupal added some classes which are the same as in the form.

# Answer
I discover that the reason is because of the localhost. Once life the form is submitting by the FormSubmit handler.
> 0 votes

---
Tags: theming, forms, 8
---


# Question
Title: Views - Add a wrapper DIV around a Group
In Drupal 7, I have created a View that lists several fields. The fields are grouped by another field (the term ID of the field). The mark up looks like this:

```
<h3>[Term 1]</h3>
<div class="views-row views-row-1 views-row-odd views-row-first"> [Field Content] </div>
<div class="views-row views-row-2 views-row-even"> [Field Content] </div>
<div class="views-row views-row-3 views-row-odd views-row-last"> [Field Content] </div>

<h3>[Term 2]</h3>
<div class="views-row views-row-1 views-row-odd views-row-first"> [Field Content] </div>
<div class="views-row views-row-2 views-row-even"> [Field Content] </div>
<div class="views-row views-row-3 views-row-odd views-row-last"> [Field Content] </div>

<h3>[Term 3]</h3>
<div class="views-row views-row-1 views-row-odd views-row-first"> [Field Content] </div>
<div class="views-row views-row-2 views-row-even"> [Field Content] </div>
<div class="views-row views-row-3 views-row-odd views-row-last"> [Field Content] </div>

```

However, I need the mark up to look like this:

```
<div id="term_1">
     <h3>[Term 1]</h3>
     <div class="views-row views-row-1 views-row-odd views-row-first"> [Field Content] </div>
     <div class="views-row views-row-2 views-row-even"> [Field Content] </div>
     <div class="views-row views-row-3 views-row-odd views-row-last"> [Field Content] </div>
</div>

<div id="term_2">
     <h3>[Term 2]</h3>
     <div class="views-row views-row-1 views-row-odd views-row-first"> [Field Content] </div>
     <div class="views-row views-row-2 views-row-even"> [Field Content] </div>
     <div class="views-row views-row-3 views-row-odd views-row-last"> [Field Content] </div>
</div>

<div id="term_3">
     <h3>[Term 3]</h3>
     <div class="views-row views-row-1 views-row-odd views-row-first"> [Field Content] </div>
     <div class="views-row views-row-2 views-row-even"> [Field Content] </div>
     <div class="views-row views-row-3 views-row-odd views-row-last"> [Field Content] </div>
</div>

```

I know that you can use views-view-unformatted.tpl.php (Style Output) to over ride the view and then insert a DIV to wrap the group.

However, I need my wrapper DIV to be like this `<div id="term_ID_{number of ID}">`. The number ID will correspond to the term that has been used to group the fields. By default, if you use views-view-unformatted.tpl.php, you cannot insert tokens for term IDs into it.

Any help would be appreciated.

# Answer
> 52 votes
I needed to do this same thing recently. You can create a template file:

* Find the template under `/modules/views/themes/views-view-unformatted.tpl.php`.
* Copy it into your `/sites/all/themes/<your-theme>` folder and rename to `views-view-unformatted--<nodetype>.tpl.php`.
* Edit the file adding a `div` around the entire template. The `<h3>` tag is the group name.

Here is what the modified template file might look like.

```
<div class="your-class">
<?php if (!empty($title)): ?>
    <h3><?php print $title; ?></h3><!--this is the group name-->
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>
</div>
<?php endforeach; ?>
</div><!--end your div-->

```

# Answer
> 17 votes
Try Format:HTML list. That will wrap the whole thing in an item-list. For my purpose it's perfect (a list of taxonomy items). Hope this helps.

# Answer
> 10 votes
Have you tried the **Rewrite results** feature? Click on the field you wish to edit and scroll down until you see **Rewrite results**. Check the box for *Rewrite the output of this field* and then customize the HTML as necessary. For the tokens, you can use the **Replacement Patterns** shown in the box below the text input area.

Regarding the **Replacement Patterns**, note the warning that Views displays:

> Note that due to rendering order, you cannot use fields that come after this field; if you need a field not listed here, rearrange your fields.

If this isn't enough, try adding a new field, **Global: Custom text**. This will allow you to add some arbitrary HTML and the **Replacement Patterns** are available here as well. You can use two separate **Global: Custom text** fields to add the `<div>` start and end tags.

# Answer
> 4 votes
These days I ran into the same issue. And what I needed beside the group wrapper was a css class like first/last per group.

So I added in views-view-unformatted.tpl.php the following php code:

```
<?php
  #### defs
  // call a global variable every time the template is called
  global $static;
  // be aware of the key_name for the global variable to keep it
  // unique for every display
  // I call the same view in one panel several times with
  // different arguments
  $key_name = $view->name . '_' . $view->current_display ;
  foreach ($view->args as $value) {
    $key_name .= '_' . $value;
  }
  // init classes array
  $group_classes = array();
  ## groups counter - store in global variable
  if (!isset($static[$key_name]['gc'])) {
    $static[$key_name]['gc'] = 1;
  }
  else {
    $static[$key_name]['gc']++;
  }
  #### classes
  ## counter
  $group_classes[] = 'group-' . $static[$key_name]['gc'];
  ## first
  if ($static[$key_name]['gc'] == 1) {
    $group_classes[] = 'first';
  }
  ## last
  // get max row "id" per group
  foreach ($rows as $id => $row) {
    $max_id = $id;
  }
  // count results (-1 because $id starts with 0)
  $count_results = count($view->result) - 1;
  //
  if ($max_id == $count_results) {
    $group_classes[] = 'last';
  }
  ## ret
  $group_class = implode(' ', $group_classes);
?>

```

Here the html part with the wrapper and classes:

```
<div class="views-group <?php print $group_class; ?>">
  <?php if (!empty($title)): ?>
    <h3><?php print $title; ?></h3>
  <?php endif; ?>
  <?php foreach ($rows as $id => $row): ?>
    <div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>
      <?php print $row; ?>
    </div>
  <?php endforeach; ?>
</div>

```

The output will be:

```
<div class="views-group group-1 first">
  content of first group
</div>
<div class="views-group group-2">
  content of second group
</div>
<div class="views-group group-3 last">
  content of third group
</div>

```

Might be helpful - enjoy

# Answer
> 2 votes
So I guess the biggest riddle is how to generate the class using the value of the $title within h3 tags. I'd try Transliteration module and the following snippet:

```
<?php
  $group_class = function_exists('transliteration_get') ? transliteration_get($title) : $title;
  $group_class = trim($group_class);
  $group_class = str_replace(' ', '-', $group_class);
  $group_class = strtolower($group_class);
?>

```

This worked for me when I had to make named anchors within a view.

# Answer
> 1 votes
Very useful - I needed to add in some alpha / omega classes for a grid based layout and also some odd even to be able to clear both for each row. I edited the line from:

```
$group_classes[] = 'group-' . $static[$key_name]['gc'];

```

to this:

```
$group_classes[] = 'group-' . $static[$key_name]['gc'] . ($static[$key_name]['gc'] % 2 ? ' alpha even' : ' omega odd');

```

Which gives the required output.

# Answer
> 1 votes
You don't need the transliteration module. Drupal core has the drupal\_html\_class function for this.

# Answer
> 1 votes
I had a similar issue today, but needed a specific class on the wrapper html, in my case the view is grouped by taxonomy terms, and we need a specific style on each term, so a specific class per term. Here's how we changed the view unformatted template:

```
<?php if(is_numeric($title)) { $term = taxonomy_term_load($title); $title = $term->name; } ?>
<div class="term-<?php print $term->tid;?>">
<?php if (!empty($title)): ?>
    <h3><?php print $title; ?></h3><!--this is the group name-->
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>
</div>
<?php endforeach; ?>
</div><!--end your div-->

```

In the view the display of the taxonomy term field is set to: "Show entity id". So we get the id as part of the class name, and then loads the title based on the same id.

# Answer
> 1 votes
For anyone who doesn't want to dive into the code and mess about with templates there's an easy way to do this by stripping the default div classes using Fences and adding your own div into the prefix and suffix of the field using Simple field formatter . If you have multiple fields simply add the the containing div in the prefix of the first field, and the in the suffix of the last field.

So the native structure with the prefix and suffix areas unstripped would look something like:

```
<div class="field field-name-field-test field-type-text field-label-above">
 <div class="field-label">Foobar field: </div>
  <div class="field-items">
   *:prefix posted here*
   <div class="field-item even">Leaner markup means better front-end performance.</div>
   *:suffix posted here*
 </div>
</div>

```

If you were going to add the class "foo" It would become

```
   <div class="foo"> *:prefix posted here*
    Leaner markup means better front-end performance.
   </div> *:suffix posted here*

```

# Answer
> 1 votes
The answer from chrisjlee above explains it well except for what to name the template file. If you want to change only one view, the new file must include the machine name of the view. You can find this in the url for the view's edit page. It's explained very well in this comment on a similar issue: https://www.drupal.org/node/1383696#comment-6729128

I needed a class around the rows using the value of $title so that I could render them in 2 columns. Here's the code:

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<div class="<?php print strtolower($title); ?>" > <!--added div with class-->
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>
</div> <!--end of added div-->

```

# Answer
> 1 votes
I came across a similar issue. I wanted my grouped rows to display within a bootstrap accordion. I couldnt have it working with the Views Bootstrap module.
Comment #4 solved my problem.
Here is what my `views-view-unformatted-[my_view_name]-[my_display_name].tpl.php` looks like

```
<?php

/**
 * @file
 * YOUR_THEME simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>

    <?php
    #### defs
      // call a global variable every time the template is called
      global $static;
      // be aware of the key_name for the global variable to keep it
      // unique for every display
      // I call the same view in one panel several times with
      // different arguments
      $key_name = $view->name . '_' . $view->current_display ;
      foreach ($view->args as $value) {
        $key_name .= '_' . $value;
      }
      // init classes array
      $group_classes = array();
      ## groups counter - store in global variable
      if (!isset($static[$key_name]['gc'])) {
        $static[$key_name]['gc'] = 1;
      }
      else {
        $static[$key_name]['gc']++;
      }
      #### classes
      ## counter
      $group_classes[] = 'group-' . $static[$key_name]['gc'];
      ## first
      if ($static[$key_name]['gc'] == 1) {
        $group_classes[] = 'first';
      }
      ## last
      // get max row "id" per group
      foreach ($rows as $id => $row) {
        $max_id = $id;
      }
      // count results (-1 because $id starts with 0)
      $count_results = count($view->result) - 1;
      //
      if ($max_id == $count_results) {
        $group_classes[] = 'last';
      }
      ## ret
      $group_class = implode(' ', $group_classes);
      $group_id = implode($group_classes); // helps me having a id whithout spaces for my accordions panels.
    ?>

    <div class="panel panel-default <?php print $group_class; ?>">
        <?php if (!empty($title)): ?>
          <?php if($group_id == 'group-1first'): ?>
                <!--<h3><?php //print $title; ?></h3>-->
                <div class="panel-heading" role="tab" id="heading<?php print $group_id; ?>">
                    <h3 class="panel-title">
                        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse<?php print $group_id; ?>" aria-expanded="true" aria-controls="collapse<?php print $group_id; ?>">
                            <?php print $title; ?>
                        </a>
                    </h3>
                </div>
                <div id="collapse<?php print $group_id; ?>" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading<?php print $group_id; ?>">

            <?php else: ?>
                <div class="panel-heading" role="tab" id="heading<?php print $group_id; ?>">
                    <h3 class="panel-title">
                        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse<?php print $group_id; ?>" aria-expanded="false" aria-controls="collapse<?php print $group_id; ?>">
                            <?php print $title; ?>
                        </a>
                    </h3>
                </div>
                <div id="collapse<?php print $group_id; ?>" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading<?php print $group_id; ?>">

            <?php endif; ?>
        <?php endif; ?>

                    <div class="panel-body">
                        <?php foreach ($rows as $id => $row): ?>
                                    <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
                                        <?php print $row; ?>
                                    </div>
                        <?php endforeach; ?>
                    </div>
            </div>
    </div>

```

of course, for the accordion to work, you also need to edit views-view-\[my\_view\_name\]-\[my\_display\_name\].tpl.php in order to have

```
<?php if ($rows): ?>
    <!--<div class="view-content">-->
    <div class="view-content panel-group" id="accordion" role="tablist" aria-multiselectable="true">
      <?php print $rows; ?>
    </div>
  <?php elseif ($empty): ?>
    <div class="view-empty">
      <?php print $empty; ?>
    </div>
  <?php endif; ?>

```

I left the default code from the module between html comments.
Hope it helps.

---
Tags: views
---


# Question
Title: How do I query entities to get all fields values - including referenced ones (INNER JOIN)
I have custom content types in my Drupal 8 module and want to query nodes of those content types programmatically.

Querying through entityQuery is easy. However, I have also entity reference fields (so a node of one content type has a relation to a node of another content type).

Is there a way how to make a query that will return 'rows' of field values, exactly as when I use raw SQL INNER JOIN? I want to have an associative array of all field values, not only the specific node, but also the referenced nodes/entities.

Right now I have an own class to handle this, but it's way too much complicated and, I believe, unnecessary, so I guess I'm missing something.

Thank you.

# Answer
> 0 votes
Views uses joined tables a lot, you can implement this in UI and run it in code.

Or use a db\_select.

Example from Drupal\taxonomyTermStorage:

```
public function getNodeTerms(array $nids, array $vocabs = array(), $langcode = NULL) {
    $query = db_select('taxonomy_term_field_data', 'td');
    $query->innerJoin('taxonomy_index', 'tn', 'td.tid = tn.tid');
    $query->fields('td', array('tid'));
    $query->addField('tn', 'nid', 'node_nid');
    $query->orderby('td.weight');
    $query->orderby('td.name');
    $query->condition('tn.nid', $nids, 'IN');
    $query->addTag('term_access');
    if (!empty($vocabs)) {
      $query->condition('td.vid', $vocabs, 'IN');
    }
    if (!empty($langcode)) {
      $query->condition('td.langcode', $langcode);
    }

    $results = array();
    $all_tids = array();
    foreach ($query->execute() as $term_record) {
      $results[$term_record->node_nid][] = $term_record->tid;
      $all_tids[] = $term_record->tid;
    }

    $all_terms = $this->loadMultiple($all_tids);
    $terms = array();
    foreach ($results as $nid => $tids) {
      foreach ($tids as $tid) {
        $terms[$nid][$tid] = $all_terms[$tid];
      }
    }
    return $terms;
  }

```

# Answer
> 0 votes
No, there is not.

Entity query only returns IDs, you need to load those and then from there access the referenced entities.

---
Tags: nodes, entities, 8, database
---


title: Altering the admin/content form

text:
# Question
Title: Altering the admin/content form
After having added a “changed by” on nodes I now need to display the user who modified each node on the `node_admin_content` form (at `admin/content`) right next to the "Author" column.

I've managed to easily solve this by altering node.admin.inc and adding just 2 lines of code:

```
...
'changed_by' => t('Changed By'),
...

...
'changed_by' => theme('username', array('account' => user_load($node->changed_by))),
...

```

This, of course, is not a proper solution since it alters the core.

So I then tried altering the form via:

```
function hook_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
  $form['admin']['nodes']['#header']['changed_by'] = t('Changed By');
  // ... ?
}

```

Using `dpm` I can see that the form has the nodes in options. The problem is that this is the result of rendering the nodes as table options. I don't have access to the original nodes, nor do I want to re-execute the node fetch query in order to get the "changed by" information. I guess doing this in the form hook would not be solving it in the correct layer. Or is it?

So, what is a good way to alter the `node_admin_content` form to add more data that exists on nodes?

# Answer
> 19 votes
The bad news is that having inspected the code, the form alter layer is the only place to really do this; your approach is pretty much spot on.

The good news is, Drupal implements all sorts of static caching throughout the page load, which minimises the need to go back into the database. So while altering the content table may appear cumbersome, you're not actually taking a noticeable performance hit.

The following code (or similar) should work; see the comments for more info about the caching issue:

```
function MYMODULE_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
  // Load the nodes. This incurrs very little overhead as
  // "$nodes = node_load_multiple($nids);" has already been run on these
  // nids in node_admin_nodes(). The static cache will be used instead of
  // another db query being invoked
  $nodes = node_load_multiple(array_keys($form['admin']['nodes']['#options']));

  // Grab a list of all user ids that have been responsible for changing the node
  $uids = array();
  foreach ($nodes as $node) {
    $uids[] = $node->changed_by;
  }

  // Filter out duplicates (one user may have been the last to change more than one node)
  $uids = array_unique($uids);

  // Load a list of all involved users in one go. This is about as performant
  // as this is going to get, as you're going to need the user objects one
  // way or the other for the call to theme_username
  $users = user_load_multiple($uids);

  // Add another column to the table header
  $form['admin']['nodes']['#header']['changed_by'] = array('data' => t('Changed by'));

  // Loop through the rows in the table and add the changed by column
  foreach ($form['admin']['nodes']['#options'] as $nid => $row) {
    // Grab the user related to this node.
    $this_user = $users[$nodes[$nid]->changed_by];

    // Add data for the new column
    $form['admin']['nodes']['#options'][$nid]['changed_by'] = theme('username', array('account' => $this_user));
  }
}

```

The above code produces a nice shiny new column like this on the content admin page:

# Answer
> 4 votes
Just replace admin/content with a View, and then add whichever fields you want. Admin Views will even do it for you.

# Answer
> 0 votes
A little off subject, but this answer shows how you can do this programmatically (for example by adding it as a module update in the MY\_MODULE.install file.)

You'll need a little more work if you want to add your new field before last existing field. Merge it in before the end of the $view-\>display\['default'\]-\>display\_options\['fields'\] array.

```
    function MY_MODULE_update_7101(){
        // update the admin/content view, need to do it manually because it's
        // set by admin_views module
        $view_name = 'admin_views_node';
        $view = views_get_view($view_name, TRUE);

        //  add the relationship
        $view->display['default']->display_options['relationships']['uid_1']['id'] = 'uid_1';
        $view->display['default']->display_options['relationships']['uid_1']['table'] = 'node_revision';
        $view->display['default']->display_options['relationships']['uid_1']['field'] = 'uid';
        $view->display['default']->display_options['relationships']['uid_1']['label'] = 'Revision User';
        // new column settings
        $new_column = array(
            'name_1' => array(
                'id' => 'name_1',
                'table' => 'users',
                'field' => 'name',
                'relationship' => 'uid_1',
                'label' => 'Updated By',
            )
        );
        // need to use this because array_splice by itself resets 'name_1' key to '0'
        // see http://php.net/manual/en/function.array-splice.php#56794
        $temp_array = array_splice( $view->display['default']->display_options['fields'] , 0, 7);
        $view->display['default']->display_options['fields'] = array_merge($temp_array , $new_column, $view->display['default']->display_options['fields']);

        views_save_view($view);
    }

```

---
Tags: 7, users, nodes
---


# Question
Title: How do I get an article's author email programmatically?
I would like to send an email to authors when their content updated. How can I get the email of author(s)?

I think `$to = \Drupal::currentUser()->get('mail');` is not my friend.

# Answer
Since you are talking of *authors*, I take you are referring to users who posted a node. In that case, supposing you have a `$node` variable, you should use the following code.

```
// Add these two lines on the top of the file containing this code.
use \Drupal\node\Entity\Node;
use \Drupal\user\UserInterface;

/** @var \Drupal\user\UserInterface $user */
$user = $node->getOwner();
$email = $user->getEmail();

```

If you are trying to get the email from the currently logged-in user, you cannot use `\Drupal::currentUser()->get('mail')` because `\Drupal::currentUser()` returns an object that implements `\Drupal\Core\Session\AccountProxyInterface`, which doesn't have the `get()` method.

If you want the email used by the currently logged-in user, you need to use the following code.

```
// Put this line on the top of the file containing this code.
use \Drupal\Core\Session\AccountProxyInterface;

/** @var \Drupal\Core\Session\AccountProxyInterface $user */
$user = \Drupal::currentUser();
$email = $user->getEmail();

```

If you need a `User` object for other purposes, you should use the following code.

```
// Add the following two lines on the top of the file containing the code.
use \Drupal\Core\Session\AccountProxyInterface;
use \Drupal\user\Entity\User;

/** @var \Drupal\user\Entity\User $user */
$user = User::load(\Drupal::currentUser()->id());
// You can access the email address with the following line.
$email = $user->get('mail')->value;
// That is exactly equivalent to the following line, which should be prefered.
$email = $user->getEmail();
// The following line require an object implementing UserInterface,
// not AccountProxyInterface, such as the object returned from  User::load().
$user->block();

```
> 7 votes

# Answer
```
$to = \Drupal::currentUser()->getEmail();

```

Works on User entities.
> 0 votes

---
Tags: users, 8
---


title: Receiving form values on mail

text:
# Question
Title: Receiving form values on mail
I am trying to receive the values of the form on my email, but I just receive empty mails. What is wrong in my code?

```
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state) {
   $langcode = 'fr';
   $to = 'my_mail@gmail.com';

   $mailManager = \Drupal::service('plugin.manager.mail');
   $module = 'FrenchForm';
   $key = 'New contact';
   $params = array(
    'body' => 'test',
    'subject' => 'Website Information Request',
    );
   $send = true;
   $message['subject'] = t('New mail');
   $message['body'][] = t('test');

   $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
}

```

# Answer
> 0 votes
To send an email, Drupal 8 is not different from Drupal 7: You also need to implement `hook_mail()` as described in `MailManager::mail()`.

See also the code used from `MailManager::doMail()`, which is the method that effectively composes and sends the email.
First, it initializes the `$message` variable.

```
  // Bundle up the variables into a structured array for altering.
  $message = array(
    'id' => $module . '_' . $key,
    'module' => $module,
    'key' => $key,
    'to' => $to,
    'from' => $site_mail,
    'reply-to' => $reply,
    'langcode' => $langcode,
    'params' => $params,
    'send' => TRUE,
    'subject' => '',
    'body' => array(),
  );

```

It passes that variable to the implementation of `hook_mail()` done from the module that is sending the email.

```
  // Build the email (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use
  // moduleHandler()->invoke() as we need to have $message by reference in
  // hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

```

Then, it sends the email.

```
  // Optionally send email.
  if ($send) {
    // The original caller requested sending. Sending was canceled by one or
    // more hook_mail_alter() implementations. We set 'result' to NULL,
    // because FALSE indicates an error in sending.
    if (empty($message['send'])) {
      $message['result'] = NULL;
    }
    // Sending was originally requested and was not canceled.
    else {
      // Ensure that subject is plain text. By default translated and
      // formatted strings are prepared for the HTML context and email
      // subjects are plain strings.
      if ($message['subject']) {
        $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
      }
      $message['result'] = $system->mail($message);
      // Log errors.
      if (!$message['result']) {
        $this->loggerFactory->get('mail')
          ->error('Error sending email (from %from to %to with reply-to %reply).', array(
            '%from' => $message['from'],
            '%to' => $message['to'],
            '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
          ));
        drupal_set_message($this->t('Unable to send email. Contact the site administrator if the problem persists.'), 'error');
      }
    }

```

As you see, the email is sent using `$message`, not `$parameters`. If you don't implement `hook_mail()`, `$message['body']` will be an empty array, and `$message['subject']` will be an empty string.
That is why you get empty emails.

---
Tags: forms
---


# Question
Title: Using taxonomy to give option of page layout - working but showing error (Notice: Undefined variable: node in include())
I have been building a site in Drupal 7. I have the content type "Basic Page" but added taxonomy terms for the user to be able to select "Standard" or "Full Width" page.

If the user selects "Full Width" the page.tpl.php file has some code which recognises the value chosen for the page removes a sidebar (usually seen on the "Standard" page).

It is working perfectly on the frontend but has an error in the backend.

Here is the code in the page.tpl.php page:

```
<?php $field_page_width = field_view_field('node', $node, 'field_page_width'); ?>

            <?php if ($field_page_width['#items'][0]['taxonomy_term']->name == 'Standard') { ?>

                <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8 internal_content">

                    <?php print render($page['content']); ?>

                </div>

                <div class="hidden-xs hidden-sm hidden-md col-lg-1"></div>

                <div class="col-xs-12 col-sm-12 col-md-4 col-lg-3 side_content">

                    <?php print render($page['side_content']); ?>

                </div>

                <div class="clearfix"></div>

            <?php } else { ?>

                <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 internal_content">

                    <?php print render($page['content']); ?>

                </div>

                <div class="clearfix"></div>

            <?php } ?>

```

I am receiving this error:

> Notice: Undefined variable: node in include() (line 76 of /home/public\_html/sites/all/themes/zen/child\_theme/templates/page.tpl.php).

Why do I get this error? Do I need to have something which establishes `$node` in the template.php file?

# Answer
The page.tpl.php template file will receive a `$node` variable only if the user is visiting a node page; in other cases, it will not get any `$node` variable, even if the template file is still used (if a module doesn't suggest another template file that takes the precedence).
In fact, the documentation for `page.tpl.php` clearly describes the `$node` variable as follows. (Emphasis is mine.)

> **$node**: The node object, **if there is an automatically-loaded node** associated with the page, and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345).

Before accessing `$node`, you should be sure it has been set.

```
if (isset($node)) {
  $field_page_width = field_view_field('node', $node, 'field_page_width');
}

```

Also, `field_view_field()` is used to render a field. If you just need to get its value, you should use `field_get_items()`.

```
if (isset($node)) {
  $items = field_get_items('node', $node, 'field_page_width');
}

```
> 0 votes

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


title: What URIs are accessed by drush?

text:
# Question
Title: What URIs are accessed by drush?
What URIs are accessed by drush up? Is it drupal.org? Are there any other URIs? I have tried using drush up --debug, but I can't seem to find a list of URIs. I have also googled it using the key words drush access URL and drush access URI, among others.

# Answer
> 0 votes
I just took a look through the drush code. In Drush/UpdateService/ReleaseInfo.php, you can see that drush grabs project release info via this url: https://updates.drupal.org/release-history

You can test it yourself - try https://updates.drupal.org/release-history/views/7.x for example.

The release info contains the download links for the projects.

Drush actually has two package handlers, git and wget (see commands/pm/download.pm.inc)

The wget one uses the download\_link from the release history, and the git method uses git.drupal.org. See commands/pm/package\_handler/wget.inc and commands/pm/package\_handler/git\_drupalorg.inc

# Answer
> 2 votes
If you are referring to `drush dl`, then by default Drush downloads from drupal.org, if you don't tell Drush to use another URL.
For example, if you use `drush dl views --source="updates.modules.org/history"`, Drush would probably download the Views module from modules.org, instead of drupal.org. From where the module would be downloaded depends from what updates.modules.org/history/views/7.x (for Drupal 7) or updates.modules.org/history/views/8.x (for Drupal 8) returns.

If you look at what https://updates.drupal.org/release-history/views/7.x retuns, you will notice a line like `<download_link>https://ftp.drupal.org/files/projects/views-7.x-3.14.tar.gz</download_link>`, which is telling to Drush to download the Views module version 7.x-3.14 from https://ftp.drupal.org/files/projects/views-7.x-3.14.tar.gz.

---
Tags: drush
---


# Question
Title: Database in settings.php doesn't exist yet site is live. Where is the data?
I've inherited a Drupal 6 site running on an Ubuntu 10.04.4 LTS server. I'm trying to understand the configuration of it to create a local version of it work on.

I can't figure out how the data is being accessed. The settings file shows the following:

```
$db_url = 'mysql://root@localhost/drupal';
$db_prefix = 'dru_';

```

However when I list the databases, I can't find it:

```
mysql -u root
mysql> show databases \g
+--------------------+
| Database           |
+--------------------+
| information_schema |
| gitpull            |
| mysql              |
+--------------------+
3 rows in set (0.01 sec)

```

In addition running drush status says it can't find it either.

```
$ drush status
SQLSTATE[42000] [1049] Unknown database 'drupal'                   [warning]

```

The site is up and running so it's got to have access to the database somehow.

I figure I'm in the right directory because it's defined in `/etc/apache2/sites-available` and `/etc/apache2/sites-enabled/`

Any help would be greatly appreciated.

# Answer
> 0 votes
The hints from Tony Mao & Alexei pointed me in the right direction. It turned out there were a bunch of backups in non-intuitively named folders, so I was looking in the wrong place.

I ended up finding the right settings.php file with `sudo find . -name settings.php`.

---
Tags: 6, database, configuration
---


# Question
Title: Why Can't Panels Select My Organic Groups?
I'm trying to create panels that are visible or show up on pages specific to certain groups. I'm using Organic Groups 7.x-2.7 on Drupal 7.34. So, our company's technicians would only see panels specific to them and the same for office staff. I'm having an issue integrating Panels with Organic Groups. When setting the "Selection Rules", "Visibility" or any other value for a panel to the group of the User who is viewing, the option to select the group is there and selectable BUT it only shows up as an empty string and the panel doesn't abide by this rule. I'm pulling my hair out and eating it in a mad attempt at proving to the gods of drupal code that I am worthy of a solution.

**Update (3/20/15)**

I changed my Organic Groups installation to version 1.5. This seems to work. I'll try each version incrementally until I reach the first one that breaks and just place it here. I still have no idea why this is occurring, though.

# Answer
> 0 votes
The way I accomplished this was with Views Contextual Filters and the Views Content Panes module, displaying only content belonging to the particular groups I wanted to see the content. This approach, however, requires the content being viewed to have a field instance of the group ID that it belongs to (and, incidentally, a field instance for "other" groups the content will be visible in). Note, in order for the two contextual filters to work properly here (i.e. for the content pane to be visible in two or more groups) I had to install the "Views Contextual Filters OR" module (I can't link twice because no rep).

I couldn't comment because I don't have enough rep, but this approach worked for me, but it might not work in your specific use case. It should be noted that if nothing matches the filter, the pane is omitted from display entirely (which is what you are ostensibly trying to accomplish). So many ways to skin a cat with Drupal.

---
Tags: 7, panels, organic-groups
---


# Question
Title: How do i attach a an element to user account?
I have added a custom form element in login form. I need to link this new element to user account on logging in.

I need to add and get entry to the table "users\_data" in Drupal 8. This can be done by defining a class EmployeeDetails and then fetch the value like this :

```
$employee_details = new EmployeeDetails($account);
$employee_details->setEmployeeNumber($value);

```

My Question is in which file should i define EmployeeDetails class? What should be file name, should i use .inc extension and where in the module should be this file placed?

# Answer
As reported in users.data column replaced with user\_data API, the equivalent of using the user.data column, in Drupal 8, is using the user.data service.

So, if in Drupal 7 you used `$value = $account->data['mymodule_xyz'];`, in Drupal 8 you will use the following code.

```
$value = \Drupal::service('user.data')->get('mymodule', $account->id(), 'xyz');

```

The code to set its value is the following one.

```
\Drupal::service('user.data')->set('mymodule', $account->id(), 'xyz', $value);

```

As usual, when possible, use dependency injection to get the service, instead of using the `\Drupal` class.
> 2 votes

---
Tags: users, 8
---


# Question
Title: How do you add a nodequeue to an existing view on the front page?
I'm confused on how to get a nodequeue to appear on the front page?

I took over an existing Drupal website with Views and Nodequeue installed.

* I created the nodequeue I want to add to the front page view as well as the nodes to include in the queue.
* I duplicated the "relationship" and "sort"/ "filter" settings from the views that are already on the homepage.
* This nodequeue I created looks fine when I preview it..

How do I actually assign the nodequeue to display on the front page like the others? I can't figure it out for the life of me.

# Answer
**OPTION 1**

Edit your Nodequeue view and click on +Add button and select `Attachment`.

Now go to your front page view and in the FOOTER add `Global: View area` and select your attachment.

**OPTION 2**

In blocks, place the Nodequeue view block on a region and configure the block, for **Visivility Settings** select `only listed pages` and put `<front>`
> 1 votes

---
Tags: 7, views, nodes
---


# Question
Title: How do I hide translation vertical tab programmatically?
I would like to hide the *Translation* vertical tab. I tried with `$form['content_translation']['#access'] = FALSE;` but it seems not working.

How do I remove that vertical tab?

>

# Answer
I think I found it.

In core\modules\content\_translatio\src\ContentTranslationHandler.php, there is an `entityFormAlter()` method, which adds this vertical tab. It seems that this method is executed after your code. I would try changing the weight of your module (so your code will run later).

(I found this looking for the *If you made a significant change* string in core; doing so, I found where the translation tab was coming from.)
> 0 votes

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


# Question
Title: How do I use node_load() with an array as first parameter?
In Drupal 6, I would use the following code.

```
$nodes = node_load(array('title' => $vcenter_name, 'type' => 'vcenter'));

```

What is the equivalent code for Drupal 8? I could use `node_load($nid)`, but not `node_load(array('title' => $vcenter_name, 'type' => 'vcenter'))`.

**UPDATE**

As per the answer , am getting the the `$nodes` array as

```
Array
(
    [1147] => Drupal\node\Entity\Node Object
        (
            [in_preview] =>
            [values:protected] => Array
                (
                    [vid] => Array
                        (
                            [x-default] => 9272
                        )

                    [langcode] => Array
                        (
                            [x-default] => und
                        )

                    [revision_timestamp] => Array
                        (
                            [x-default] => 1452106357
                        )

                    [revision_uid] => Array
                        (
                            [x-default] => 0
                        )

                    [revision_log] => Array
                        (
                            [x-default] =>
                        )

                    [nid] => Array
                        (
                            [x-default] => 1147
                        )

```

and i can't access the fields like `$nodes->field_name[0]->value;`

But how i get like this :

```
Drupal\node\Entity\Node Object
(
    [in_preview] =>
    [values:protected] => Array
        (
            [vid] => Array
                (
                    [x-default] => 9173
                )

            [langcode] => Array
                (
                    [x-default] => und
                )

            [revision_timestamp] => Array
                (
                    [x-default] => 1448312269
                )

            [revision_uid] => Array
                (
                    [x-default] => 0
                )

            [revision_log] => Array
                (
                    [x-default] =>
                )

            [nid] => Array
                (
                    [x-default] => 1107
                )

```

# Answer
> 4 votes
The equivalent of `$values = array('title' => $vcenter_name, 'type' => 'vcenter'); $nodes = node_load($values);` for Drupal 8 is `entity_load_multiple_by_properties()`, whose first parameter is the entity type, differently from `node_load()`.

Since `entity_load_multiple_by_properties($entity_type, array $values)` is deprecated, you should use the following code.

```
$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties($values);

```

---
Tags: nodes, 8
---


# Question
Title: Customising image in the first row in a views
I would like to be print for the first row in different display style for the image field. Thx all!

```
<div class="row first">
    <h3>Title1</h3>
    <img class="this is the first image with specific style of output"/>
</div>
<div class="row">
    <h3>Title2</h3>
    <img class="standard style output"/>
</div>
<div class="row">
    <h3>Title3</h3>
    <img class="standard style output"/>
</div>
<div class="row last">
    <h3>Title4</h3>
    <img class="standard style output"/>
</div>

```

I tried using the php field. Something like:

```
<?php
  if ($view->row_index == 0) {
    print $row->field_foto_principale;
  } else {
    print "other";
  }
?>

```

But I can not render the image.

# Answer
> 1 votes
you can also use hook

```
function HOOK_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->name == 'your_view_name' && $vars['view']->row_index == 1) {
    // your code
  }
}

```

# Answer
> 0 votes
At the moment I'm using this code in a Custom PHP field:

```
<?php
    if ($view->row_index == 0) {
        $img_url = $data->field_field_foto_principale[0]['rendered']['#item'][uri];
        $style = $data->field_field_foto_principale_1[0]['rendered']['#image_style'];
    } else {
        $img_url = $data->field_field_foto_principale[0]['rendered']['#item'][uri];
        $style = $data->field_field_foto_principale[0]['rendered']['#image_style'];
    }
?>
<img src="<?php print image_style_url($style, $img_url) ?>" />

```

---
Tags: views
---


# Question
Title: Ajax request return field without name attribute
Instead of getting multiselect on making ajax request while I select content type, I got single select and this select hasn't any name (select tag hasn't attribute name). So here's problem and I don't know how to fix it. Can anybody help?

```
$form['export_what'] = array(
    '#type'  => 'select',
    '#multiple' => FALSE,
    '#title' => t('Select content type'),
    '#required' => TRUE,
    '#options' => $form['export_what1_options']['#value'],
    '#ajax'    => array(
        'callback' => 'insttance_ajax_fill_content',
        'wrapper' => 'replace_model_div',
        'effect' => 'fade',
        'event'  => 'change',
    ),
);

$form['export_data'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#required' => TRUE,
    '#default_value' => '',
    '#prefix' => '<div id="replace_model_div">',
    '#suffix' => '</div>',
    '#options' => $content,
);

function insttance_ajax_fill_content($form, $form_state)
{
    $i = $form['count_field']['#value'];
    $content = getAllContentByType($form_state['values']['export_what']);

    $form['export_data'] = array(
        '#type' => 'select',
        '#multiple' => TRUE,
        '#required' => TRUE,
        '#default_value' => '',
        '#prefix' => '<div id="replace_model_div">',
        '#suffix' => '</div>',
        '#options' => $content,
    );

    return $form['export_data'];
}

```

# Answer
The attribute name is missing because you have replaced the select element in ajax callback. You just need to update the `#options`

```
function insttance_ajax_fill_content($form, $form_state)
{
    $i = $form['count_field']['#value'];
    $content = getAllContentByType($form_state['values']['export_what']);

    $form['export_data']['#options'] = $content;

    return $form['export_data'];
}

```
> 2 votes

---
Tags: forms, ajax
---


title: How do I update core with Composer?

text:
# Question
Title: How do I update core with Composer?
Ok, admittedly I'm a composer novice. So, in my previous site, I used composer manager to update Drupal's core. That was pretty straight forward to use (just run "composer drupal-update"). However, composer manager now says it's deprecated.

> The Drupal 8 version of this module is deprecated and no longer needed, due to improvements in Drupal 8.1. Use Composer directly to get the needed modules, which will also download their required libraries.

So today I got a warning that I need to apply security updates to core, but I can't find any documentation on how you would update Drupal core with composer.

Is this done through Drupal Console, Drush or is it an actual composer command I need to run? I'm not very clear on what the preferred process is outside of "download the latest version of Drupal from drupal.org and replace all the files manually".

# Answer
To update Drupal using Composer, you just need to move the `"drupal/core": "~8.1"` line from the *replace* section to the *require* section. At the end the content of the composer.json file is like the following one.

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/core": "~8.1"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
}

```

I was used to run `drush upc` to update Drupal, but that overriden my composer.json file, and the vendor directory. As consequence of this, I should run `composer update` all the times to update the content of the *vendor* directory.

Now, using Composer to update Drupal, I can also use it to download/update the modules I am using.

The composer.json file I am using is the following one.

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/core": "~8.1",
        "drupal/imagick": "8.1.*@dev",
        "drupal/mollom": "^8.1",
        "drupal/honeypot": "^8.1"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packagist.drupal-composer.org"
        }
    }
}

```

Apart from moving that line as I said, I also executed the following commands.

```
composer config repositories.drupal composer https://packagist.drupal-composer.org
composer require drupal/honeypot
composer require drupal/mollom
composer require drupal/imagick 8.1.*@dev

```

The first allows me to require Drupal modules and update them.

The last time I tried, the Drupal official repository was still in alpha stage, and it gave me problems with modules that declared themselves as Composer packages, but not setting the package type (i.e. drupal-module). I hope they fixed the problem, now. For the Drupal Packager repository, the commands to use are the following.

```
composer config repositories.drupal composer https://packages.drupal.org/8
composer require drupal/honeypot
composer require drupal/mollom
composer require drupal/imagick 1.*@dev

```

If you were already using https://packagist.drupal-composer.org, and you want to replace with the official Packagist site, you need to replace the first command with `composer config repositories.0 composer https://packages.drupal.org/8`, which works if you don't have other repositories, basing on Using packages.drupal.org.

Notice also that packagist.drupal-composer.org is scheduled to be deprecated in January 2017 (or when the official Package Repository from Drupal.org is ready).
> 10 votes

---
Tags: 8, composer
---


# Question
Title: Add attributes to options elements in a select box
I am working with a Drupal 7 site; I have a vocabulary setup with an additional text field. On one of my content-type nodes, this is rendered as a drop-down select box with all the terms under that vocabulary. However, I would also like for the additional vocabulary field to be included as a `data-country` attribute. It is rendered rendered as follows.

```
<select id="..." name="..." class="...">
    <option value="145">UK8</option>
</select>

```

I'd like it to be rendered as follows.

```
<select id="..." name="..." class="...">
    <option value="145" data-country="United Kingdom">UK8</option>
</select>

```

Is this possible?

# Answer
There is Form Options Attributes module wich adds support for the attributes.
> 5 votes

# Answer
Unfotunately there is no way to do it using Form API. You need to involve some theming. Please check the following answer:

https://stackoverflow.com/a/9264589/2620782
> 3 votes

---
Tags: 7, entities
---


# Question
Title: How do I use user_save() to add a new category?
In Drupal 7, there is `user_save($account, $edit = array(), $category = 'account')`. How do I create a new category for an existing account in Drupal 8?

Also, $user = \Drupal::currentUser(); and $user-\>save(); gives error as well. I need to attach a form element value to user object.

How to link a login form element to user account on logging in?

# Answer
> 0 votes
Here is piece of my working code:

To attach the element & set the value:

```
\Drupal::service('user.data')->set('module_name', $account->id(), 'category_name', $category_value);

```

To fetch the value:

```
$account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $remember_me_value = \Drupal::service('user.data')->get('module_name', $account->id(), 'category_name');

```

# Answer
> 1 votes
The category concept has been removed. So the answer is, you don't.

Not sure what you are trying to do, if you need a better answer, you will need to provide more details.

User is an entity with fields. There's nothing special about it, you change and save data in the same way like any other entity.

# Answer
> 0 votes
You cannot create a new category, since in Drupal 8 the category system has been removed. As said in The category system is removed from user edit and view, you just need to remove any reference to user categories in your code.

If you need to add a custom form field to the user edit form, and save the submitted value, you simply:

* Implement `hook_form_alter()` to add the new form field, and a form submission handler
* In the form submission handler, save the value submitted for the form field you added

`hook_form_alter()` and `hook_form_FORM_ID_alter()` still works for Drupal 8. You just need to know correct form ID for the user edit form, which is *user\_form*. See for example `contact_form_user_form_alter()`, which shows also a way to save custom data associated with user accounts.

```
  $form['contact'] = array(
    '#type' => 'details',
    '#title' => t('Contact settings'),
    '#open' => TRUE,
    '#weight' => 5,
  );
  $account = $form_state->getFormObject()->getEntity();
  if (!\Drupal::currentUser()->isAnonymous() && $account->id()) {
    $account_data = \Drupal::service('user.data')->get('contact', $account->id(), 'enabled');
  }
  $form['contact']['contact'] = array(
    '#type' => 'checkbox',
    '#title' => t('Personal contact form'),
    '#default_value' => isset($account_data) ? $account_data : \Drupal::config('contact.settings')->get('user_default_enabled'),
    '#description' => t('Allow other users to contact you via a personal contact form which keeps your email address hidden. Note that some privileged users such as site administrators are still able to contact you even if you choose to disable this feature.'),
  );
  $form['actions']['submit']['#submit'][] = 'contact_user_profile_form_submit';

```

As you see, the code uses the *user.data* service to retrieve the value submitted for the checkbox it adds. `contact_user_profile_form_submit()` then shows how to save the value submitted for that checkbox.

```
  $account = $form_state->getFormObject()->getEntity();
  if ($account->id() && $form_state->hasValue('contact')) {
    \Drupal::service('user.data')->set('contact', $account->id(), 'enabled', (int) $form_state->getValue('contact'));
  }

```

As for why `$user = \Drupal::currentUser(); $user->save();` doesn't work, that is simply because the object returned from `\Drupal::currentUser()` is an object implementing `AccountProxyInterface`, which doesn't implement any `save()` method. The only way to alter the user account for the logged-in user is using code similar to the following one.

```
use \Drupal\Core\Session\AccountProxyInterface;
use \Drupal\user\Entity\User;

$user = User::load(\Drupal::currentUser()->id());
if ($user) {
  // Add the administrator role.
  $user->addRole('administrator');
  $user->save();
}

```

---
Tags: users, 8
---