# Question
Title: Is this correct usage of hook_node_view()?
```
hook_node_view_alter(&$vars, $hook) {

  global $base_url;

  if($vars['#node']->status == 0) {
    header('Location: '.$base_url.'/?errCode');
  }
}

```

Simple hook to redirect unpublished nodes to prevent 404s (this is just a proof of concept).

Factor 1: There is already existing unpublished pages that have redirects (via the Redirect Module from Drupal Core) - this shouldn't affect that.

This is placed in my theme/template.php file but I'm not confident that this hook is best suited (although it works). Is there a lower level menu router hook which I can use?

# Answer
> Is there a lower level menu router hook which I can use?

Yes, there is - you would need to use `hook_menu_alter()` to achieve this. Here's the code you should use:

```
function YOUR_MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'YOUR_MODULE_node_page_handler';
}

function YOUR_MODULE_node_page_handler($node) {
  // If the node is unpublished, redirect the user.
  //
  // Note: I would recommend adding an extra check so administrators and
  // users who can manage the nodes are not redirected. This way, they can
  // work with unpublished nodes.
  //
  // This is what you would use instead in that case:
  // if ($node->status == NODE_NOT_PUBLISHED && !user_access('administer nodes')) {
  //
  // This will work for ALL users on the site, including the administrators.
  if ($node->status == NODE_NOT_PUBLISHED) {
    drupal_goto('<front>', array('query' => array('errCode' => 1)));
  }

  // Let the core node handler serve the request otherwise.
  return node_page_view($node);
}

```

Notes:

1. You should do this through a custom module instead of the theme.
2. Bear in mind that this might interfere with functionality of other modules, as well as workflows. See my comments and alternative version of the code.
3. Use `drupal_goto()` for redirection instead of setting the location in header.

Hope this helps.
> 5 votes

---
Tags: 7, nodes, hooks
---


# Question
Title: How to search by hierarchical taxonomy in views?
I have a view with a `Global: Combine fields` filter with some fields, one of theese fields is a hiererchical select field of a taxonomy terms. But it doesn't work.

How can I set a search box to search by text in a hiererchical select field (and other fields)?

# Answer
> 0 votes
You can use Chosen Module and it supports for hiererchical select

> By default the module will automatically apply itself to any select elements that have more than 20 options, which is a reasonable default for which having Chosen will be useful. To change or disable this automatic enhancement, you can change the selectors (or remove all selectors) from the Apply Chosen to the following elements field on the Chosen administration page.

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


title: How do I add a condition to a query?

text:
# Question
Title: How do I add a condition to a query?
```
$acl_ids = array(1,2,3);
$database = \Drupal::database();

$result = $database
  ->query("SELECT {nid} FROM {acl_node} WHERE grant_update = :grant",
    ['grant' => 1,])
  ->condition('acl_id', $acl_ids, 'in')
  ->fetchField();

```

Unfortunately the `->condition` part does not work, since I get the following error:

> Call to undefined method Drupal\Core\Database\Statement::condition()

What method should I instead use?

# Answer
> 14 votes
Conditions are only used in dynamic queries; the `query()` method is for running static SQL.

The dynamic version would be something like:

```
$result = $database
  ->select('acl_node', 'n')
  ->fields('n', ['nid'])
  ->condition('grant_update', 1)
  ->condition('acl_id', $acl_ids, 'IN')
  ->execute()
  ->fetchField();

```

And the static:

```
$result = $database
  ->query("SELECT nid FROM {acl_node} WHERE grant_update = :grant AND acl_id IN (:acl_ids[])", [':grant' => 1, ':acl_ids[]' => $acl_ids])
  ->fetchField();

```

# Answer
> 2 votes
The code you wrote is equivalent to the Drupal 7 code that used `db_query()`. You cannot use `condition()` with the object returned from `\Drupal::database()->query()`. I would also change your code in two points:

* You are using `{nid}` in your query, which is what you should use when nid is a table name, not a table field name <sup>*</sup>
* You are using `['grant' => 1,]` as array of arguments, when it should be `[':grant' => 1,]` basing on Drupal/PHP documentation (Notice the colon before the table field name.)

If you don't want to use functions that are going to be deprecated in Drupal 9, see the answer given by Clive. I will add that you can still use `db_query()` or `db_select()` also in Drupal 8. In fact, Drupal 8.2.x still contains 160 calls to `db_query()` and 128 calls to `db_select()`.

```
$acl_ids = array(1,2,3);

$result = db_query("SELECT nid FROM {acl_node} an WHERE an.grant_update = :grant AND an.acl_id IN ( :ids[] )", [':grant' => 1, ':ids[]' => $acl_ids]);

foreach ($result AS $row) {
  // access the node ID as $row['nid'].
}

```

This code is similar to the one used in `history_read_multiple()`.

```
  $result = db_query('SELECT nid, timestamp FROM {history} WHERE uid = :uid AND nid IN ( :nids[] )', array(
    ':uid' => \Drupal::currentUser()->id(),
    ':nids[]' => array_keys($nodes_to_read),
  ));
  foreach ($result as $row) {
    $nodes_to_read[$row->nid] = (int) $row->timestamp;
  }
  $history += $nodes_to_read;

```

### Notes

Using `{nid}` would cause a wrong query being executed if Drupal is using prefixes for the table names. Still, it is not correct to use `{nid}` if you don't want Drupal to alter it as it alters a table name.

---
Tags: 8, database
---


# Question
Title: How do I change the date format of a single result?
I have a view that gives me a list of nodes titles and when it was last updated.

I want to display the changed date with only time if it is today, otherwise I just want the date, e.g. 17.00 or 15 may 2016.

If I look at the result in views\_pre\_render it has a node\_changed timestamp. It uses the date format set in the view. How do I change the format just for the first result?

# Answer
> 1 votes
You can create a template file and in that you can have and the template files you can get that in

```
if($view->row_index == 1){
   // do your stuff
}

```

and put your own condition

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


title: How do I theme the user register page?

text:
# Question
Title: How do I theme the user register page?
In Drupal 7, we can use a template file like page--user--register.tpl.php, or we can register our own template file.

How we can do it in Drupal 8?

# Answer
This is similar in D8. Copy page.html.twig from core or base theme and put it into the template directory of your theme.

Rename it like this:

```
page--user--register.html.twig

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: How do I set the HTML element of a text field?
My request couldn't be simpler - I have a custom text field on a node (field type `text`), and I want this field to be placed in a Panels layout in a `<h3>` element.

For `Node title`, I can choose the HTML element. For text fields, there seems to be no such option. The available formatters are `Default`, `Trimmed` and `Plain text`, none of which have any settings. Views fields have all sorts of easy field rewriting features, but I can't find anything equivalent in Panels.

How can I get the drop down of HTML elements like you get for Node Title for a custom field? Or change the output another way?

I'd prefer not to have to rewrite my entire Panels layout and create a whole new region for this one field in its .tpl file simply to put some text in a `<h3>`.

# Answer
> 2 votes
Have you tried Panels Extra Styles ? As per module page :

> **Panels Wrapper**
>
> Wrap your panes and regions with unlimited possibilities. Go HTML5! Wrap your content in the newly defined tags. Add custom containers and HTM
>
> **Wrapper: Element**
>
> Wrap any region or pane with one of several dozen tags, including HTML5 elements.
>
> **Wrapper: Raw**
>
> Wrap any region or pane with a custom raw prefix and suffix.
>
> Sample output after applying the wrapper elements on 1 region and 2 content panes: the powered by block and a main menu.

# Answer
> 0 votes
Because Drupal, this requires another custom module, Clean Markup:

* Download clean\_markup and enable the `clean_markup_panels` submodule
* Edit your panel pane's **Style** settings from its cog menu
* Choose the Clean Markup option
* This allows you to choose the HTML wrapper for the pane from a huge list that includes HTML5 elements as well as every H\* element

BONUS - you can also turn off the unnecessary wrappers Panels loves to add to panes. Actually, no, despite the name it seems to stuff the `<h3>` full of divs regardless of your settings, I don't understand why. If you don't mind your element being full of unnecessary divs, this is a good option.

---
Tags: 7, panels
---


title: Print theme logo path in my twig file

text:
# Question
Title: Print theme logo path in my twig file
In `mytheme.theme` file I have:

```
function mytheme_preprocess_page(&$variables) {
      $variables['logopath'] = '/' . drupal_get_path('theme','mytheme') . '/logo.png';
}

```

In my `menu--main.html.twig` I have:

```
<img class="img-responsive" src="{{ logopath }}" />

```

But it's not printing my logo? The src is still empty?

# Answer
> 1 votes
You use different theme hooks `page` and `menu`.

If you want to use the variable in

```
menu--main.html.twig

```

use

```
function mytheme_preprocess_menu(&$variables) {

```

---
Tags: theming, 8
---


# Question
Title: Administration page doesn't show pop-up (overlay) windows
When I try to place new block by clicking "Place block" button or when I click "Configure" on the block I see no pop-up window as I see in tutorial videos, like here: https://www.youtube.com/watch?v=D2KvCGGtBuk 3:10 and 4:25. It seems that this problem is persistent in other administration menus (like views, when I try to choose view format). How do I enable them? Why aren't they shown?

I'm on Drupal 8.1.1, with Nginx web server, Ubuntu 14.04 x32, DigitalOcean. There are no errors in status report except not protected configuration files and trusted host settings, which will be solved when site opens to public.

# Answer
The block layout is in the standard installation of drupal. This popup should work out of the box.

When you press the button "Place block" this ajax is used:

/admin/structure/block/library/mytheme?region=header&\_wrapper\_format=drupal\_modal...

So I would check first if this ajax is fired and second if there are any js errors in the browser debug tool (F12).
> 1 votes

---
Tags: 8, javascript, modal-dialogs
---


# Question
Title: How to redirect to another page after submitting the ctools modal form
Actually i want to redirect to some other page after submitting the multistep ctools modal form .I have tried using form\_state\['redirect\] and drupal\_goto in submit function but didnt work.

```
function get_quote_menu(){

$items=array();
$items['get_quote'] = array(
  'title' => 'Get Quotation',
  'page callback' => 'get_quote_form',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);
$items['get_quote/%ctools_js/details'] = array(
  'title' => 'Get Quotation',
  'page callback' => 'quote_ajax_details_form',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);
return $items;
}
function quote_ajax_details_form($js = NULL, $step = NULL){

if ($js) {

    ctools_include('modal');
    ctools_include('ajax');
 }
  $form_info=array(

    'id' => 'quote_details',
    'path' => "get_quote/" . ($js ? 'ajax' : 'nojs') . "/details/%step",
    'show trail' => TRUE,
    'show back' => TRUE,
    'show cancel' => TRUE,
    'show return' => FALSE,
    'next callback' =>  'get_quote_details_next',
    'finish callback' => 'get_quote_details_finish',
    'cancel callback' => 'get_quote_details_cancel',

    'order' => array(
        'start' => t('View the plans and premiums best suited to you <br/>in 4 straight forward steps.'),
        'second'=>t(''),
    ),

    'forms' => array(
        'start' => array(
            'form id' => 'get_quote_start',
       ),
       'second'=>array(
            'form id'=> 'get_actual_quote_details',
       )
    ),
);

$object_id = 1;

if (empty($step)) {
// We reset the form when $step is NULL because that means they have
// for whatever reason started over.
get_quote_cache_clear($object_id);
$step = 'start';
}

// This automatically gets defaults if there wasn't anything saved.
$object = get_quote_cache_get($object_id);

$form_state = array(
'ajax' => $js,
// Put our object and ID into the form state cache so we can easily find
// it.
'object_id' => $object_id,
'object' => &$object,
);

ctools_include('wizard');
$form = ctools_wizard_multistep_form($form_info, $step, $form_state);
$output = drupal_render($form);

if($js){

$commands=array();

if($output===FALSE  || !empty($form_state['complete'])){

  $commands[] = ajax_command_html('#ctools-sample', finish($form_state['object']));
  $commands[] = ctools_modal_command_dismiss();

}else if(!empty($form_state['cancel'])) {

    $commands[] = ctools_modal_command_dismiss();

}else {

     $commands = ctools_modal_form_render($form_state, $output);
}

 print ajax_render($commands);
 exit;
}else{

 return $output;

 }
}
 function get_quote_start($form, &$form_state){
            $form['first_name'] = array(

'#title' => t('Your Name'),
'#type' => 'textfield',
'#size'=>20,
'#default_value' => $form_state['object']->first_name,
'#attributes'=>array(
    'placeholder'=>t('First Name'),
    'id'=>array('quote-first-name'),
),
//'#required'=>true,
);
$form['middle_name'] = array(
'#type' => 'textfield',
'#default_value' => $form_state['object']->middle_name,
'#size'=>20,
'#attributes'=>array(
    'placeholder'=>t('Middle Name'),
    'id'=>array('quote-middle-name'),
 ),
//'#required'=>true,
);
 return $form;
}
 function get_quote_start_submit(&$form, &$form_state){

global $user;

 $form_state['object']->uid=$user->uid;
}
function get_actual_quote_details($form, &$form_state){
$form['adults']=array(

    '#type'=>'select',
    '#title' => t('Adults'),
    '#options'=>array(
        1=>1,
        2=>2,
        3=>3,
    ),

 );
return $form;
}
function get_actual_quote_details_submit(&$form, &$form_state){

    // Not working redirect
       // drupal_goto('node/add/page');
        $form_state['redirect]='node/add/page',
}

```

# Answer
This is a bit old, but hopefully it'll help someone. Down where you write your commands\[\] array. Change it to something like this. In the submit function of one of the earlier forms I set the redirectpath parameter on the object, then i just use that in ctools\_ajax\_command\_redirect() after calling the dismiss modal function ctools\_modal\_command\_dismiss().

```
  // If $output is FALSE, there was no actual form.
  $commands = array();
  if ($output === FALSE || !empty($form_state['complete'])) {
    // Dismiss the modal.
    $finish = _aap_main_add_finish($form_state['object']);
    $commands[] = ctools_modal_command_dismiss();
    ctools_add_js('ajax-responder');
    $commands[] = ajax_command_html('#ctools-sample', $finish);
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ctools_ajax_command_redirect($form_state['object']->redirectpath);
  }
  else if (!empty($form_state['cancel'])) {
    // If cancelling, return to the activity.
    $commands[] = ctools_modal_command_dismiss();
  }
  else {
    $commands = ctools_modal_form_render($form_state, $output);
  }

```
> 1 votes

# Answer
Add destination for links. I have also similar problem with drual modal form. After user registration and forgot password I have to send it on thanks page. Create tpl file and make registration link using below code.

```
<?php
echo l('Sign up here', 'user/register', array('query'=>array('destination'=>'thanks')));
?>

```

Create tpl file and make forgot password link using below code.

```
<?php
print l('Forgot Your Password?', 'user/password', array('query'=>array('destination'=>'thanks')));
?>

```
> 1 votes

# Answer
@Hitesh Jain : Thank you for the answer. Your comment helped me. Just adding this as an answer so that it can help others.

`ctools_include('ajax');`
`ctools_add_js('ajax-responder');`
`$commands[] = ctools_ajax_command_redirect('node/add/page');`
`// Redirect to url u want.`
`print ajax_render($commands);`
`exit;`
> 1 votes

# Answer
I recommend you strongly to use rules module. there is no need to programming, simply add event and action and it works great.
> -2 votes

---
Tags: 7, chaos-tool-suite
---


# Question
Title: How can I construct a table view with columns passed as a parameter?
I have a content type, referenced by multiple subsequent content types and at some point I made a spreadsheet with all that data. My new assignment is to display a view like that and then export it to Excel, but before that let the user choose which columns appear in the table. I'm also going to need to be able to display exposed filters for all the chosen columns and save the columns and the filters as a report template.

Is it possible to do all that using Views or perhaps create it from scratch as a new entity?

I've been trying to do that in Views and I've hit a few walls. I thought about creating a bunch of PHP fields for all possible columns and check if they should be displayed based on the list of columns to display. Displaying data that way worked, but I can't put filters on PHP fields so I pretty much can't use them here.

After that I tried simply displaying all the columns initially and then in the "modify output" part of the fields display an empty string if that column is not on the list of columns to display (this way I could simply hide the empty columns). Only to realize you can't put PHP code anywhere in the view field settings.

Haven't managed to get that far but I think you can't simply display a node and x referencing nodes in one table row. How it works in my db is that there's a "Examination" content type, which has different types. Multiple examinations might reference the same node so I'd have to find a way to display that node and all referencing examination types in the same row. Assuming each type can occur once.

^ This part might deserve it's own question though.

To put it shortly: I need to populate table view columns based on a list of columns while still being able to expose full filters to each column

# Answer
> 1 votes
What you'll want to do is create a new display (using the table style) on the fly and then use that display to render the output.

If you take a look at views exports, you can get an idea of how columns are added to new displays:

From commerce\_cart.views\_default.inc:

```
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['title'] = 'Shopping cart';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'quantity' => 'quantity',
  'commerce_display_path' => 'commerce_display_path',
  'line_item_title' => 'line_item_title',
  'commerce_total' => 'commerce_total',
);

// Ignoring relationships...

$handler->display->display_options['style_options']['info'] = array(
  'quantity' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
      'align' => '',
    'separator' => '',
  ),
  'commerce_display_path' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
  'line_item_title' => array(
    'align' => '',
    'separator' => '',
  ),
  'commerce_total' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => 'views-align-right',
    'separator' => '',
  ),
);

  /* Field: Commerce Line Item: Quantity */
  $handler->display->display_options['fields']['quantity']['id'] = 'quantity';
  $handler->display->display_options['fields']['quantity']['table'] = 'commerce_line_item';
  $handler->display->display_options['fields']['quantity']['field'] = 'quantity';
  $handler->display->display_options['fields']['quantity']['relationship'] = 'commerce_line_items_line_item_id';
  $handler->display->display_options['fields']['quantity']['label'] = '';
  $handler->display->display_options['fields']['quantity']['precision'] = '0';
  $handler->display->display_options['fields']['quantity']['suffix'] = ' × ';
  /* Field: Commerce Line item: Display path */
  $handler->display->display_options['fields']['commerce_display_path']['id'] = 'commerce_display_path';
  $handler->display->display_options['fields']['commerce_display_path']['table'] = 'field_data_commerce_display_path';
  $handler->display->display_options['fields']['commerce_display_path']['field'] = 'commerce_display_path';
  $handler->display->display_options['fields']['commerce_display_path']['relationship'] = 'commerce_line_items_line_item_id';
  $handler->display->display_options['fields']['commerce_display_path']['label'] = '';
  $handler->display->display_options['fields']['commerce_display_path']['exclude'] = TRUE;

```

And so on. Then, just save the view (`views_save_view()`) and render the output. Commerce has a function called `commerce_embed_view()` that shows how to make this happen. This is slightly modified, though:

```
// You can get the ID after you save it.
$view->set_display($display_id);

// Set the specific arguments passed in. Optional.
$view->set_arguments($arguments);

// Prepare and execute the View query.
$view->pre_execute();
$view->execute();

// Return the rendered View.
return $view->render();

```

# Answer
> 1 votes
I found a module that pretty much covers what I needed to do:

Views Dynamic Fields

Insead of providing a list of columns you can simply let the user choose which columns to display.

As for the exposed filters, my idea, albeit not a perfect one, would be to create exposed filters for all possible fields and upon applying the Dynamic Fields filter using some jQuery to hide/display respective filters.

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


# Question
Title: Disable user creation at login with Simple LDAP
I have the simple LDAP module installed and running, and I would like to prevent Drupal from creating a new user after a user authenticates if it does not already exist in Drupal.

I found the function 'simple\_ldap\_user\_load\_or\_create\_by\_name', `if (!$Drupal_user) ...`

I cannot find a hook to modify this function, no way to do it without changing the module?

# Answer
As you are describing it, this is not possible. You can limit authentication and user creation to only LDAP accounts, but you ***must*** have a local Drupal user.
> 0 votes

# Answer
The Simple LDAP module's Simple LDAP Role submodule probably allows you to do something that would achieve the result you want (only a few people have more access than anonymous users). You can create a role in Drupal for privileged users, map that role to a group in LDAP, and then map everyone else to Authenticated user. If the authenticated user role has the same permissions as Anonymous you will have a very similar effect. That module *might* also allow you to control which groups can authenticate at all.

To have more features and more control you likely will need to create a custom submodule or switch to the larger LDAP module. The LDAP Module is powerful and useful, but not the best supported module in the community.
> 0 votes

---
Tags: 7, hooks, authentication-authorization
---


title: How do I know the discount rate?

text:
# Question
Title: How do I know the discount rate?
Hi I wont to know about how can I use discount rate ?

```
$report_query = db_select('commerce_order','co');
$report_query->fields('co');
$report_query->orderBy('co.created','ASC');
$report_res = $report_query->execute();
while ($re = $report_res->fetchObject()) {
    $o_id = $re->order_id;
    $o_load = commerce_order_load($o_id);
    echo "<pre>";print_r($o_load);
}

```

**Output:**

```
[1] => Array(
[name] => tax|vat_cst
[price] => Array(
        [amount] => 27556
        [currency_code] => INR
        [data] => Array(
                [tax_rate] => Array(
                        [name] => vat_cst
                        [display_title] => VAT/CST
                        [description] => VAT
                        [rate] => 0.125 // here display tax rate
                        [type] => vat
                        [rules_component] => commerce_tax_rate_vat_cst
                        [default_rules_component] => 1
                        [price_component] => tax|vat_cst
                        [calculation_callback] => commerce_tax_rate_calculate
                        [module] => commerce_tax_ui
                        [title] => VAT/CST
                        [admin_list] => 1
                    )
            )
    )
[included] => 1
)

[2] => Array(
   [name] => discount-20% Off
   [price] => Array(
        [amount] => -49600
        [currency_code] => INR
        [data] => Array(
          [discount_name] => discount_full_discount_20_
          [discount_component_title] => 20% Off
        )
   )
   [included] => 1
)

```

In vat\_cst the rate is 0.125 but,how can I know which rate is used on total order?

# Answer
> 0 votes
The discount *rate* isn't always available as a percentage (like, for instance, taxes are) because discounts can be whole numbers as well. Regardless, you can ultimately get information about how a price is calculated by looking at the `commerce_order_total` field on an `order` or the `commerce_total` field on a `line_item`.

Here's an example:

In this screen shot, we'll take a look at 4 items. For the comments assume `$price = $order->commerce_order_total[LANGUAGE_NONE][0]`.

1. `$price['data']['components'][0]['price']['amount']` is the original amount. You know this because `$price['data']['components'][0]['price']['amount']` is `"base_price"`.
2. A discount price component will a name of `"discount|DISCOUNT_ID"` where `DISCOUNT_ID` is the machine name of the discount that is being referenced.
3. `$price['data']['components'][1]['price']['amount']` in this instance is the discount that is applied.
4. `$price['amount']` is the combination of all of the components under `$price['data']['components']`.

There is a `data` array under the price information on the discount. It contains the label and the machine name of the discount, but it doesn't have any other information. Custom discounts might put more information on there, but you can't necessarily depend on anything else being there.

---
Tags: commerce
---


# Question
Title: Cannot get value of form field of type 'file' in drupal form
I have a form field such as ,

```
   $form['fileTransfer_settings']['file_path'] = array(
    '#type' => 'file',
    '#title' => t('Choose file'),
    '#size' => 22,
    '#description'   => t('path for the csv file'),

  );

```

Now I am looking to save the path of the uploaded file in the submit handler ,

But when I look into the value of the form field in the submit handler I get null,

```
function transferfile_submit_handler($form, &$form_state) {

     dpm($form_state[values]); //other fields show value
     dpm($form_state['values']['fileTransfer_settings']['file_path']); //null
 }

```

What am I doing wrong here?

# Answer
> 1 votes
Submitted values are flattened unless the form element contains the `#tree` property.

So either use:

```
$form_state['values']['file_path'];

```

Or change the wrapper:

```
$form['fileTransfer_settings'] = array(
  '#tree' => TRUE,
  ...
);

```

And use your current submission code.

---
Tags: forms, files
---


# Question
Title: How to add the node settings "Exclude node title" to a field group?
Since the module does not provide an entry in the manage form settings, how to move "Exclude node title" to a field group in Drupal 8?

# Answer
In the `form_alter` function:

```
  if (isset($form['exclude_node_title']) && isset($form['title']) && isset($form['#group_children']['title'])) {
    $form['#group_children']['exclude_node_title'] = $form['#group_children']['title'];
  }

```

this will move the exclude title into the same group as title is in
> 0 votes

---
Tags: 8, forms
---


# Question
Title: How can i have a SimpleNews signup form as modal/lightbox
Is it possible to have the Simplenews sign up form block as a modal - I'd like to present people to the signup a bit more visible than a static block. Would i be possible to present the modal when eg. 3 pages have been viewed. Assuming that visitors with 1-2 page views would not be interessted in a newsletter.

# Answer
> 0 votes
It's certainly possible, however, modals aren't as simple as clickkng a few things together (at least not before drupal 8 :p).

One way to do it would be to add a counter to user's Session. Increase the counter every time a new page is viewed and once it reaches 3, trigger the display of a modal, for instance by using ctools modal generation api.

---
Tags: emails, cookies
---


# Question
Title: Config for using PUT with Services Module
I'm integrating DrupalGap with Drupal 7 and Services module. Issue I'm running into is that all PUT requests are returned as 405 Method Not Allowed.

For example: `GET http://example.com/?q=drupalgap/user/1.json` works just fine. After I update the json and try `PUT http://example.com/?q=drupalgap/user/1.json` gives me the 405.

This is happening locally and on the hosted server, hosting is with Pantheon, they use nginx if that's relevant.

I also tried doing the PUT using the Poster browser extension, same result, which makes me think it's a config setting that's incorrect.

# Answer
> 1 votes
Turns out that the issue was with Pantheon hosting, something they have configured doesn't allow DrupalGap to PUT or PUSH to Drupal Services, I went through their support and they showed they can GET, PUT, PUSH to Drupal services, but they don't provide support for 3rd party modules if they don't work as expected. Switched over to Acquia managed hosting and all services work as expected now, also worked fine on a basic shared hosting server.

# Answer
> 1 votes
There is no configuration needed in drupal to accept put requests the web server may be refusing PUT requests and requires some configuration see why-does-my-web-server-software-disallow-put-and-delete-requests for more information about this issue.

Try curl and see response example below

> curl -X PUT **the request**

The advanced rest client s chrome extension I prefer to use over others.

---
Tags: services, javascript
---


# Question
Title: How to add element not appearing on the page via node_view_alter?
Given the following code:

```
function mymodule_node_view_alter(&$build) {
  $node = $build['#node'];
  if ($node->type != 'podcasts') {
    return;
  }

  $build['new_section'] = array(
    '#weight' => 15,
    '#markup' => 'test injected data'
  );

  dpm($build);
}

```

In the `dpm()` output, I can see that my test data is in the array; however, nothing shows up on-screen.

Do I need to pre-define this new section or set it to allow any new sections?

# Answer
> 0 votes
hook\_node\_view\_alter() documentation reads:

> This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.

This means it is for logic that fires after the render array has been constructed, eg changing weights or items in the array you cannot control (items from other modules).

What you are looking for is hook\_node\_view(). That should allow you to add new sections into a render array.

The example from the linked resource:

```
function hook_node_view($node, $view_mode, $langcode) {
  $node->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}

```

# Answer
> 0 votes
Problem solved, I hope this question/answer helps someone else down the road.

The "Manage Display" for the node in question was assigned a template.

Removing the template allowed the added fields to display.

This makes sense, as a newer Drupal developer, I was told to simply add in the elements with weights and they'll just display. The caveat needs to be, "as long as you're not using a defined/custom template for the page which only displays specific page elements."

---
Tags: nodes, hooks
---


# Question
Title: An illegal choice has been detected. after leaving form page
I have a form with only a select element and no submit button. Upon change, I issue an ajax call to retrieve the details of the selected Project. Everything works as expected, however after I leave the page, I see the error "An illegal choice has been detected. Please contact the site administrator."

I only get the error if I change the select input. Ex. if I navigate to:

> Home-\>Projects-\>Home

I don't see the error on the last Home page. If i navigate to:

> Home-\>Projects(change select input)-\>Home

I see the error on the last Home page.

Here is my module code:

```
class ExpeditionController extends ControllerBase {
  public $client;

  public function __construct() {
    $this->client = \Drupal::service('http_client');
  }

  public function listProjects() {
    $select_form = \Drupal::formBuilder()->getForm('Drupal\myModule\Form\ExpeditionSelectForm');
    // Remove the submit button.
    unset($select_form['actions']['submit']);

    $result = $this->client->get('myRESTService', ['Accept' => 'application/json']);
    $expeditions = json_decode($result->getBody());

    foreach ($expeditions as $value) {
      $select_form['expeditions']['#options'][$value->{'expedition'}->{'expeditionId'}] = $this->t($value->{'expedition'}->{'expeditionTitle'});
    }

    return array(
      '#theme' => 'myModule_expeditions',
      '#form' => $select_form,
    );
  }

  public function expeditionDetail($form, $form_state) {
    $expedition = [];
    $response = new AjaxResponse();
    if ($form['expeditions']['#value'] != "") {

      $client = \Drupal::service('http_client');
      $result = $client->get(
        'myService' . $form['expeditions']['#value'],
        ['Accept' => 'application/json']
      );
      $expedition = json_decode($result->getBody());
    }

    $response->addCommand(new HtmlCommand(
      '#expeditionDetail',
      array(
        '#theme' => 'myModule_expeditions_detail',
        '#expedition' => $expedition,
      )
    ));

    return $response;
  }

  public function deploymentDetail($project_id, $deployment_id) {
    $result = $this->client->get(
      'myService' . $project_id . '/' . $deployment_id,
      ['Accept' => 'application/json']
    );

    return array(
      '#theme' => 'myModule_deployment_detail',
      '#deployment' => json_decode($result->getBody()),
    );

  }
}

class ExpeditionSelectForm extends ConfigFormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'myModule_expeditions';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['expeditions'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose Project'),
      '#empty_option' => $this->t('Select a project'),
      '#default_value' => '',
      '#ajax' => [
        'callback' => 'Drupal\myModule\Controller\ExpeditionController::expeditionDetail',
      ],
    );

    return parent::buildForm($form, $form_state);
  }

  /**
   * Gets the configuration names that will be editable.
   *
   * @return array
   *   An array of configuration object names that are editable if called in
   *   conjunction with the trait's config() method.
   */
  protected function getEditableConfigNames() {
    // TODO: Implement getEditableConfigNames() method.
    return [];
  }
}

```

# Answer
You change the options after the form is built:

```
 $select_form['expeditions']['#options'][$value->{'expedition'}->{'expeditionId'}] = $this->t($value->{'expedition'}->{'expeditionTitle'});

```

The Form API doesn't know about this. On submit the Form API checks if the submitted option is in the original option list. If not, it rejects the submit with the error "An illegal choice has been detected. Please contact the site administrator."
> 2 votes

---
Tags: forms, 8
---


# Question
Title: Steps for Changing the Order of the Payment Methods on Checkout
I have two payment methods: Cheque and PayFlow Pro enabled for my products. However, they are showing up on the checkout form in an undesirable order:

Pay by Cheque (selected by default) Pay by Credit Card

I'd like to reverse those and make Credit Card the default option. This question APPEARS to be answered here, but I don't understand the answer.

Would someone kindly provide the steps needed to make this happen?

# Answer
Edit the payment method and click on **SETTINGS** on the bottom of the page.
> 2 votes

---
Tags: 7, commerce
---


title: How do I use "drush qd"?

text:
# Question
Title: How do I use "drush qd"?
In Drupal 7, I use `drush qd -y` and `php -S localhost:8000` almost weekly to get a fresh development copy of Drupal 7 to build modules or test modules before I put them into our actual development boxes.

I'm looking at Drupal 8 without much prior knowledge. Can I still use `drush qd` as I do with in Drupal 7?

# Answer
`drush qd` still works fine with Drupal 8, provided that you are using the 8.x or `master` branch of Drush. In fact, I just used the latest Drush to download, install and open Drupal 8.1.1, and it worked like a charm.
> 3 votes

---
Tags: 8, drush
---


# Question
Title: Enable field inside Manage Display from a .yml file
When I create a field `field.field.node.custom.body.yml` in my custom module with the following code:

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.body
    - node.type.customblog
  module:
    - text
id: node.customblog.body
field_name: body
entity_type: node
bundle: customblog
label: Body
description: ''
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  display_summary: true
field_type: text_with_summary

```

The *Body* field is created and added to the appropriate CT when installed, but is set as disabled in the manage display. This seems to be default behavior. I would like the field to be enabled as the module is installed through the use of `.yml` files, is this possible?

# Answer
> 1 votes
There is a single config entity per *entity\_type*, *bundle* and *view/form mode*. If you fully control that, then you can provide those config entities, if you just add a single field to something existing, you need to use the API to add your fields configuration to it.

See `core.entity_form_display.node.article.default.yml` in standard.profile and various others for examples.

---
Tags: installation-profiles, 8
---


# Question
Title: Need to alter response headers for error pages
We have Cloudflare sitting in front of our Drupal sites - and in order to take advantage of their "AlwaysOnline" feature - we need to alter the response code sent in the event of an error.

I want to cater for when the database is unavailable - as this can sometimes happen when upgrading the MySQL server.

The only way I've found so far is to hack the errors.inc file:

```
if ($fatal) {
    drupal_add_http_header('Status', '504 Service unavailable (with message)');
  }

```

Is there a more elegant way to achieve what I'm after?

# Answer
> 2 votes
You could use a `template_preprocess_maintenance_page()` invocation in your theme's **template.php** so that when you go to maintenance mode (or the DB is down) it will trigger your needed status code:

```
function MYTHEME_preprocess_maintenance_page(&$variables) {
  drupal_add_http_header('Status', '504 Service unavailable (with message)');
}

```

---
Tags: http-request
---


# Question
Title: How to eliminate direct access to files in private directory?
I have set up my Drupal 7 site for private files in a directory above root (../private). I also set my filefield on my node type to upload the image files to that private directory.

I have two user roles: man and woman. Both user roles can create nodes of a certain type, containing that image file field. Men can never see another man's photo; same thing for women. Men can always see a woman's photo; same thing for women.

Here are my current results:

When a man visits a woman's node, he can view the photo within the node content: http://example.com/members/76/gallery/public/photo-123

When that man views the page source and copies the image URL, he can view that image directly in his browser: http://example.com/system/files/styles/apply\_simplecrop/private/pictures/1/Public/filename.jpg?itok=ABC123&sc=abcdefghijklmnop

If that man shares that direct link with another man, that other man can view that picture as well. If he shares the direct link with a woman or a non-logged-in user they are served an Access Denied message and cannot view that picture.

If a man tries to access that image URL without the "itok=" text in the link, he receives an Access Denied message.

**My desired result in all of those examples above is to display an Access Denied message.**

The ../private directory has an htaccess file containing **Deny from all**.

Am I missing a step? What can I do to securely deny direct access to those files in the way that I described above?

Thanks!

# Answer
> 0 votes
The issue is that the other man that gets the link should get an Access denied right? (The rest seems to work.) This is not how if works unfortunately. Private files are only private if the user is explicitly denied access to them (as happens to women and anonymous users). Since any man is allowed access to that file (he can view it under certain circumstances), the system will serve him that file.

Files are served from this part of system\_menu():

```
$items['system/files'] = array(
  'title' => 'File download',
  'page callback' => 'file_download',
  'page arguments' => array('private'),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

```

Then file\_download():

```
function file_download() {
  // Merge remainder of arguments from GET['q'], into relative file path.
  $args = func_get_args();
  $scheme = array_shift($args);
  $target = implode('/', $args);
  $uri = $scheme . '://' . $target;
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
    $headers = file_download_headers($uri);
    if (count($headers)) {
      file_transfer($uri, $headers);
    }
    drupal_access_denied();
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}

```

As you can see, Drupal serves an access denied in case there are no headers. So, you should make sure that file\_download\_headers() does not return any headers.

You can achieve this by implementing hook\_file\_download() in a custom module and have it return the value of `-1` as described in it's documentation. This will however always deny the user access to the file. So within hook\_file\_download you will have to find some way to conditionally allow the user access to the file. It is entirely up to you how you want to implement this, but a suggestion is:

* Lookup the file object, by loading it from the `file_managed` table by its path.
* Lookup the node(s) that have this image attached.
* Lookup if the current user visited the node within x minutes by querying the `history` table. If not, return `-1`.

This gives a general idea of how Drupal serves these files and what you can do to restrict access. If you run into any problems implementing this, feel free to open a new question and reference this one.

And on a sidenote, if you are trying to prevent user from leaking photo's. If I find a pretty girl, I can also save the image and email it to a friend. If you block that I send a screenshot. In these case he does not even need an account. People will always find a way to circumvent limitations. Is it worth the effort to block this?

---
Tags: 7, .htaccess, files
---


title: Custom commerce order_id

text:
# Question
Title: Custom commerce order_id
Where is the default commerce order\_id set and how can i change it to my custom order number?

I am using the Commerce Order Counter module to set a custom order number. drupal.org/project/commerce\_order\_counter

The problem i have is the order\_id that is passed to paypal is the default commerce order\_id and not my custom order number.

# Answer
> 1 votes
You cannot change order id as other functionalities are dependent on it.But you can change order number before saving order to shopping cart status by using hook\_commerce\_order\_presave($order).

```
function example_commerce_order_presave($order) {
   if ($order->status == 'cart') {
   $order->order_number = 'new order number;
   commerce_order_save($order);
   }
 }

```

# Answer
> 0 votes
Try the hook\_commerce\_order\_presave($order)

which has options to alter the order object before saving. Maybe you can add your custom code inside this function an alter the order id.

---
Tags: rules, commerce, payment-gateways
---


title: inject translator service in my service

text:
# Question
Title: inject translator service in my service
I am confused by this one.

I want the translator service injected in my service. The closes thing I've found is this one: Drupal\Core\StringTranslation\TranslationManager; ( https://api.drupal.org/api/drupal/core!lib!Drupal!Core!StringTranslation!TranslationManager.php/class/TranslationManager/8.2.x) but it has no method "t" and it really makes emphasises to not use it's translate function, to use \Drupal\Core\StringTranslation\StringTranslationTrait; instead. But I can't inject this in my service, can I? (how?)

Ultimately, I just want to call t function in my own service.

# Answer
It looks that there is no need to inject anything. Just use a "use" statement *inside* the class

```
class MyModuleService {
  use \Drupal\Core\StringTranslation\StringTranslationTrait;

  function a() {
    $this->t('should at least not complaint.');
  }
}

```
> 1 votes

---
Tags: 8, dependency-injection
---


# Question
Title: How to change the autocomplete for a user reference to show First/Last name instead of username?
I want to add a user reference field to an "event" content type, and reference the user who will present.

But I wonder how to change the entity reference - I've tried using the "filter by an entity reference view" with a view I created, but it still only shows the username.

# Answer
> 2 votes
Similar to Show node IDs along with titles in Entityreference Autocomplete list except in the rewrite of your user name field use `{{field_first_name}} {{field_last_name}}` and you need to add those fields ABOVE your user name field, in order to get access to those replacement patterns.

---
Tags: nodes, 8, views, ajax
---


# Question
Title: user.routing.yml -- What is the significance of "_entity_form: user_role.default"?
In user.routing.yml, I'm not able to understand the line 83.

```
user.role_add:
  path: '/admin/people/roles/add'
  defaults:
    _entity_form: user_role.default
    _title: 'Add role'
  requirements:
    _permission: 'administer permissions'

```

What does \_entity\_form: user\_role.default mean?

# Answer
> 4 votes
In short, it means that route shows an entity form to edit the user role entity; in particular, it shows its default form.

In details, `user_role` is the ID for the `Role` class, which implements the user role entity.

```
@ConfigEntityType(
  id = "user_role",
  label = @Translation("Role"),
  handlers = {
    "storage" = "Drupal\user\RoleStorage",
    "access" = "Drupal\user\RoleAccessControlHandler",
    "list_builder" = "Drupal\user\RoleListBuilder",
    "form" = {
      "default" = "Drupal\user\RoleForm",
      "delete" = "Drupal\Core\Entity\EntityDeleteForm"
    }
  },
  admin_permission = "administer permissions",
  config_prefix = "role",
  static_cache = TRUE,
  entity_keys = {
    "id" = "id",
    "weight" = "weight",
    "label" = "label"
  },
  links = {
    "delete-form" = "/admin/people/roles/manage/{user_role}/delete",
    "edit-form" = "/admin/people/roles/manage/{user_role}",
    "edit-permissions-form" = "/admin/people/permissions/{user_role}",
    "collection" = "/admin/people/roles",
  },
  config_export = {
    "id",
    "label",
    "weight",
    "is_admin",
    "permissions",
  }
)

```

`user_role.default` is referring to the default form the annotation for that class describes.

```
"form" = {
  "default" = "Drupal\user\RoleForm",
  "delete" = "Drupal\Core\Entity\EntityDeleteForm"
}

```

In this case, it's the form implemented from the `RoleForm` class.

When you see `_entity_form` in a route, it always mean the route is showing a form implemented from an entity.

---
Tags: 8, routes
---


# Question
Title: Entity Field Query OR condition,between node title and a custom field
I am executing a query for searching in the node title and a field using LIKE.How do I use the OR condition? \`

```
function hook_somefunction($keys) {
$query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', 'product_display_one');
  //$query->addTag('customproductstag');
  $query->addMetaData('keys', $keys);

//both conditions below are working fine individually ,but I need to use OR in between them
  //$query->fieldCondition('field_usage_number', 'value','%'. $keys .'%', 'LIKE');
  //$query->propertyCondition('title',$keys .'%', 'LIKE');
  $result = $query->execute();
  return $result;
}

//This part below is not working
function hook_query_customproductstag_alter(QueryAlterableInterface $query) {
  $keys = $query->getMetaData('keys');
  $or = db_or()
    ->fieldCondition('field_usage_number', 'value','%'. $keys .'%', 'LIKE')
    ->propertyCondition('title','%'.$keys .'%', 'LIKE');

`$query->condition($or);
}`

```
\`

Thanks.

# Answer
> 0 votes
\`

```

function hook_query_customproductstag_alter(QueryAlterableInterface $query) {
  $keys = $query->getMetaData('keys');
  $or = db_or()
    //->fieldCondition('field_usage_number', 'value','%'. $keys .'%', 'LIKE')
    //->propertyCondition('title','%'.$keys .'%', 'LIKE');
    ->condition('usage.field_usage_number_value', '%' . db_like($keys) . '%', 'LIKE')
    ->condition('node.title', '%' . db_like($keys) . '%', 'LIKE');

`$query->condition($or);
}`

```
\`

fieldCondition didn't work because db\_or is not a part of entity query.

---
Tags: entities, hooks
---


# Question
Title: Programatically is it possible to list up all the path aliases that my site has?
A site has many path aliases generated using the Pathauto module, or from the user interface.

I want to get all the aliases the site has. how can I achieve this?

# Answer
> 2 votes
I got a fresh installed d8.1 and a fresh pathauto 8.1.x-dev. I got the url\_alias table in my database by installing the module.

the table schema is \[pid | source | alias | langcode\]

I guess what you want to do is something like this:

```
$query = db_select('url_alias', 'ua')
  ->fields('ua', array('alias'))
  ->execute();

```

that should give you the result you want.

---
Tags: 8, path-aliases
---


# Question
Title: Body field doesn't display in any view mode
I inserted some articles in my Drupal 7 site, the body field doesn't display, the manage display setting is ok, I tried to change the theme. Even though I still to display it in edit mode.
One thing is that I imported this content type with bundle copy , it's the same Article default content type with some custom fields.

# Answer
> 0 votes
I deleted the body field and I recreate it again. that's slove my problem, while I have not yet had any contents
I didn't find a second solution

---
Tags: 7, entities
---


# Question
Title: cache_render database table growing in size
I am having a drupal 8 website where cache\_render table is growing to GBs. I am not sure why this growing huge, any starting pointers would be helpful.

Thanks

# Answer
> 2 votes
There are some ongoing improvements to e.g. cache 404 pages only for a short time.

Make sure that cron is running, so that expired caches are deleted.

Also consider using an alternative cache backend like Redis or Memcache, both have a max size that the allocate and delete items that have not been used for a while.

# Answer
> 1 votes
Did you inspect the content of the table `cache_render`? The page element that uses the most space will be obvious, because it has the most entries.

For example a block with a cache context on `url.path`:

```
cid:
entity_view:block:block_name:[languages:language_interface]=??:[url.path]=/aaa/bbb/ccc:[user.permissions]=???

```

The cache contexts are in square brackets \[\].

In this example you would get a new entry in the cache table for every page with a different url you visit which has this block on it.

In this case you could think about changing this to \[url.path.parent\] like the breadcrumb block does, this would reduce the amount of data.

---
Tags: 8, caching
---


# Question
Title: Search API Solr Autocomplete no results when more than x Nodes indexed
I encounter a strange behavior on a site I'm working on.

I use Search API views exposed form for autocomplete. My nodes reference nodes of another content type. The title of this referenced node's should be returned by autocomplete. This works all fine until more than 22 nodes are indexed. It seems like it does not matter which nodes are indexed, when 22 are exceeded the autocomplete will not return any results anymore.

I also tried to index the field as different types but the outcome is the same.

If i type in the term and click search the results are fine. I also ran the query in Solr's backend which returns the result as well.

Log's of Drupal and Solr show nothing.

Any suggestion on what and how to debug this?

# Answer
RTFM - Today i finally found this: https://www.drupal.org/node/1999392#hidden-variables

> **search\_api\_solr\_autocomplete\_max\_occurrences** By default, keywords that occur in more than 90% of results are ignored for autocomplete suggestions. This setting lets you modify that behaviour by providing your own ratio. Use 1 or greater to use all suggestions. Defaults to 0.9.

This makes perfect sense since 90% of my total 25 nodes is 22.5. I just set in a custom module:

```
variable_set('search_api_solr_autocomplete_max_occurrences', 0);

```

And it works.
> 0 votes

---
Tags: commerce, ajax, search
---


# Question
Title: How to remove "leave blank for all" message from Views exposed filter
After updating the Views module from 3.11 to 3.13, I get an annoying text that says:

> Leave blank for all. Otherwise, the first selected **term** will be the default instead of "Any".

Does anyone know how to remove it, besides using CSS?

This only happens in *taxonomy term* exposed filters.

Could it be a bug?

# Answer
There is a problem with view 3.13. It happened due to this commit https://www.drupal.org/node/339384#comment-10548388.

Stated as:

> Issue #339384 by colan: Added help text to keep the exposed filter terms list unset to keep unfiltered "Any" option default.

Apply this patch or revert your view back to version 3.11.
> 10 votes

# Answer
A quick, temporary "fix" is to use String Override module to hide this string. Just leave Replacement field blank or change to more applicable string.
> 1 votes

# Answer
I fixed this by "hiding" the helptext message from being displayed using CSS. .description { display: none;} I am not sure though if this poses any security risk. I think this is better than hacking Views or at least until patch is included to the current version (not the dev version).
> 1 votes

---
Tags: views
---


# Question
Title: How to run jquery function on every page load
I have a Views grid that contain images in DIV containers. I want these containers to have one of two possible heights 60px or 104px, depending on the images height. So I came up with this function (contained in a `$(document).ready function()`) that I have added in my theme's JS file.

```
  $('div.givarbild img').each( function() {
    var container = $(this).closest('div.givarbild');
    var pic = new Image();
    pic.src = $(this).attr("src");
    var picHeight = pic.height;
    console.log(picHeight);
    if(picHeight < 60){
        container.height(60);
    }else if(picHeight > 60){
        container.height(104);
    }

  });

```

Now, my problem is that this only works once, after clearing the caches in Config -\> Performance. If I simply reload the page after clearing all caches in Drupal all DIVs are 60 px high and the `container.height` value is zero in the js console (Firebug).

How can I force this little function to run after every page load?

EDITED: Hmmm, I am obviously doing something wrong here :-)... but with this code:

```
(function($) {
    Drupal.behaviors.related_content = {
        attach: function (context) {
            $('div.givarbild img').each( function() {
                var container = $(this).closest('div.givarbild');
                var pic = new Image();
                pic.src = $(this).attr("src");
                var picHeight = pic.height;
                console.log(picHeight);
                if(picHeight < 60){
                    container.height(60);
                }else if(picHeight > 60){
                    container.height(104);
                }
            });
        }
    }
})(jQuery);

```

... I get the exact same result. It works immediately after clearing all caches in Drupal 7 but not when I reload the page after that. Is there something fishy with my custom script itself?

EDITIED AGAIN: I post this change to my js code in case anyone else is having the same issue. This code does the same thing as the previous one, except that it works every time, and not just the first time after clearing all caches in D7. The only thing I changed was the method for getting the natural image height. It would be interesting to know why this latter code works though and not the first one... it actually works every time even without the added `Drupal.behaviors` rows.

```
(function($) {
    Drupal.behaviors.related_content = {
        attach: function (context) {
            $('div.givarbild img').each( function() {
                var container = $(this).closest('div.givarbild');
                $("<img>").attr("src", $(this).attr("src")).load(function(){
                    var picHeight = this.height;
                    console.log(picHeight);
                    if(picHeight < 60){
                        container.height(60);
                    }else{
                        container.height(104);
                    }
                });
            });
        }
    }
})(jQuery);

```

# Answer
> 3 votes
```
(function ($) {
  Drupal.behaviors.custom_scripts = {
    attach: function (context) {

      //write your custom code

    }
  }
})(jQuery);

```

Along with this for the first time you have to clear cache, and this will work in all pages and all the times.

# Answer
> -1 votes
You could try to disable the caching of the view. To do this go admin/structure/views and edit your view under the advanced section there is a caching option.

---
Tags: 7, javascript
---


# Question
Title: Values disappear in $form_state['values']
I have some tableselect in a form which I can click a button and update from a database. When I update it, I need to be able to access those values in my submit function. But those values aren't available in $form\_state\['values'\] if I have updated the tableselect via AJAX. How can I make those available, or are they not available before the form is submitted?

Here is the AJAX function:

```
function module_data_table($form, &$form_state) {

  $tableselect_header = array(
    'id' => t('ID'),
    'row_id' => t('Room number'),
    'start-end' => t('Start date - end date'),
    'sum' => t('Sum'),
    'type' => t('Type'),
  );

  foreach ($form['data_tableselect'] as $data => $val) {
    if (is_int($data)) {
      unset($form['data_tableselect'][$data]);
    }
  }

  // This function just gets the data from the database and returns it as an array
  $lines = module_data_from_database($form, $form_state, true);
  $form['data_tableselect'] = array(
    '#type' => 'tableselect',
    '#tree' => 'true',
    '#attributes' => array(
      'id' => 'data_tableselect'
    ),
    '#header' => $tableselect_header,
    '#options' => $lines,
    '#multiple' => true,
    '#empty' => t('No data to show.'),
    '#parents' => array('data_tableselect'),
    '#default_value' => '',
    '#weight' => 14
  );

  $form['data_tableselect'] = form_process_tableselect($form['data_tableselect']);

  $commands = array();
  $commands[] = ajax_command_replace("#data_tableselect", render($form[['data_tableselect']));

  return array('#type' => 'ajax', '#commands' => $commands);

```

}

And here is the relevant part of the hook\_form\_alter function where I defined the button that triggers the above function. The code that defines the tableselect there is much the same as that above:

```
$form['data_get'] = array(
  '#type' => 'submit',
  '#value' => t('Import data'),
  '#attributes' => array(
    'class' => array('col-sm-3', 'col-xs-4')
  ),
  '#parents' => array('data_get'),
  '#limit_validation_errors' => array(),
  '#ajax' => array(
    "callback" => 'module_data_table',
    "wrapper" => 'data_tableselect',
    'progress' => array(
      'type' => 'throbber',
      'message' => t('Importing...')
    ),
    "event" => 'click'
  )
);

```

# Answer
> 1 votes
You have to move the code for changing form elements from ajax callback to form build (which includes hook\_form\_alter()). The form build is executed for every ajax request before the callback function is called. In the callback you are not allowed to change the form array. Put only code there to return form elements.

More information: Ajax Forms in Drupal 7

Quote:

> Changes to the form must only be made in the form builder function (ajax\_example\_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state.

# Answer
> 0 votes
I have the feeling you are mixing up regular AJAX functions and form API AJAX. Also see the link 4k4 posted.

If you append the replace method to your `#ajax` definition, you can have the form callback return a portion of the form.

```
'#ajax' => array(
  "callback" => 'module_data_table',
  "wrapper" => 'data_tableselect',
  'progress' => array(
    'type' => 'throbber',
    'message' => t('Importing...')
  ),
  "event" => 'click'
  'method' => 'replace',  // < here.
)

```

And then have your callback only return the relevant part of the form:

```
function module_data_table($form, &$form_state) {

  $tableselect_header = array(
    'id' => t('ID'),
    'row_id' => t('Room number'),
    'start-end' => t('Start date - end date'),
    'sum' => t('Sum'),
    'type' => t('Type'),
  );

  foreach ($form['data_tableselect'] as $data => $val) {
    if (is_int($data)) {
      unset($form['data_tableselect'][$data]);
    }
  }

  // This function just gets the data from the database and returns it as an array
  $lines = module_data_from_database($form, $form_state, true);
  $form['data_tableselect'] = array(
    '#type' => 'tableselect',
    '#tree' => 'true',
    '#attributes' => array(
      'id' => 'data_tableselect'
    ),
    '#header' => $tableselect_header,
    '#options' => $lines,
    '#multiple' => true,
    '#empty' => t('No data to show.'),
    '#parents' => array('data_tableselect'),
    '#default_value' => '',
    '#weight' => 14
  );

  return  $form['data_tableselect'];
}

```

You do not need those AJAX command and those might be the reason your form does not behave as expected. In my experience (I used above method) the values of all elements have always been in `$form_state['values']`.

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


# Question
Title: How to get selected Value in the listbox by using form api
I have created a form with fields titled State and City. After selecting the state's appropriate city records, they will be loaded into city listbox. Until now they were working fine, but after clicking the submit button I am not able to store the city's value into variable called `$data1`. How can I get it to return the city value?

Source code

```
function form_test_form($form,&$form_submit) {
  $query_state=db_select('state', 's');
  $query_state->fields('s',array('State_code','State_name'));
  $query_state->orderBy('State_name','ASC');
  $state_results = $query_state->execute();
  $options_state = array();

  foreach($state_results as $state_record) {
    $options_state[$state_record->State_code]=t($state_record->State_name);
  }

  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
    ),
  );

  $form['city_element_wrapper'] = array(
    '#prefix' => '<div id="divaroundseconddropdown">',
    '#suffix' => '</div>',
  );
  return $form;
}

```

Ajax Function

```
function _ajaxfunction($form, $form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  foreach ($city_results as $city_record) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  $form['city_element_wrapper']['city']= array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,);

  return $form['city_element_wrapper'];
}

```

Now I am trying to store the value of what I have selected in City listbox into `$data1` variable but I am not able to store it, Please guide me how to store. It is printing empty value (i.e blank)

```
function form_test_custom_form_submit($form, $form_state) {
  $data1 = $form_state['values']['city_element_wrapper'];
  print_r($data1); // it is printing empty value
}

```

# Answer
> 0 votes
1) Try `form_test_custom_form_submit($form, &$form_state) {}`

2) Try to print all values. `print_r($form_state['values']);`

> // $form\_state\['values'\]\['city'\]; you may get values here.

You can write `$form['city_element_wrapper']['city']` array inside the `form_test_form` itself, instead of writing inside ajax callback.

# Answer
> 0 votes
```
function form_test_form($form,&$form_submit) {
  $query_state=db_select('state', 's');
  $query_state->fields('s',array('State_code','State_name'));
  $query_state->orderBy('State_name','ASC');
  $state_results = $query_state->execute();
  $options_state = array();

  foreach($state_results as $state_record) {
    $options_state[$state_record->State_code]=t($state_record->State_name);
  }

  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
    ),
  );

  $form['city_element_wrapper'] = array(
    '#prefix' => '<div id="divaroundseconddropdown">',
    '#suffix' => '</div>',
  );
  // Submit Button
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}
form_test_custom_form_submit($form, &$form_state) {
print_r($form_state['values'])
}

```

Try this

---
Tags: forms, ajax
---


# Question
Title: Why are `drush pm-list` & `drush pm-updatestatus` disabling the default theme?
I have a Drupal 7 site with 3 themes enabled:

* Foo
* Adminimal
* Shiny

Foo is a custom theme for the front-end, located in `/sites/foo/themes/` and set as the default.

Adminimal and Shiny are both installed via `drush make` into `sites/all/themes/contrib/`.

Running `drush pm-updatestatus` disables the default 'Foo' theme.

```
$ drush pm-updatestatus
Checking available update data ...                             [ok]
Failed to check available update data for Foo settings.        [ok]
Checked available update data for Administration menu.         [ok]
...
Checked available update data for Adminimal.                   [ok]
Checked available update data for Shiny.                       [ok]
Failed to get available update data for one project.           [error]
Checked available update data for 64 projects.                 [status]
 Name                                                        Installed Version  Proposed version  Message
 Administration menu Adminimal Theme (adminimal_admin_menu)  7.x-1.6            7.x-1.7           Update available
...
 Adminimal (adminimal_theme)                                 7.x-1.21           7.x-1.24          Update available
 Shiny (shiny)                                               7.x-1.6            7.x-1.7           Update available

```

The `Failed to check available update data for Foo settings.` & `Failed to get available update data for one project. [error]` lines from the output clearly look relevant, but I'm struggling to identify the underlying cause.

With the Drush's `-d` debug flag enabled the output includes this line before the `Failed to get update data for on project [error]`:

```
Undefined index: foo theme.inc:100 [1.78 sec, 35.7 MB]            [notice]

```

`drush pm-list` has the same effect.

Presumably there's something wrong with the declaration, or location of the Foo theme?

Checking the status report via the Drupal admin does not disable the Foo theme.

Why would `drush pm-list` & `drush pm-updatestatus` disable the default theme?

# Answer
> 0 votes
Your themes for Drupal 7 should live here:

* `/sites/all/themes/THEMENAME` \- for all sites and all themes
* `/sites/example.com/themes/THEMENAME` \- for example.com of a multisite setup

Now in your case there is an additional note: You have the option to put your theme in a `contrib` and a `custom` subfolder. Themes in the custom subfolder would be skipped during the update process (see /r/drupal for cross reference). There is a caveat though: Apparently once you use `contrib`you also *have to* use `custom` otherwise it seems the whole tree breaks (see disqus)

Try to move the foo theme too: `/sites/all/themes/custom/foo` or `/sites/example.com/themes/custom/foo` then run `drush rr` and `drush cc all`

---
Tags: drush
---


title: How do I keep content's styles?

text:
# Question
Title: How do I keep content's styles?
I have created a new custom content type: `tw-how-to-guide`.

This is a simple content type that only has one field: a paragraph module. And this paragraph module contains:

* some nested paragraph modules
* a number list

I would like the contents of the custom node template to display exactly as it does today. I am only looking to make two changes:

* Wrap of the tw-how-to-guide content in a div with a css class
* based on the selected number from the number list, add an additional div below the wrapper div, with the same class.

I have created a template file: `node--tw-how-to-guide.html.twig` However, this is not displaying anything. I have tried using kint, with the following:

```
<div class="printPage" >

  {{ kint(content) }}

</div>

```

And I get the array in Kint, which is nice. However I do not wish to customize the display of the contents. I want the content to display as before. I am just interested in modifying the wrapping div.

I am concerned that I will need to recreate, or doing some complex work, to simply add some div tags.

I am really hoping this task can be done easily without having to parse each time in the array and call new templates. As I mentioned, it just adding a wrapper div, and then addition same divs based on selected number.

Any ideas on how to achieve this?

# Answer
Content is not a variable of a field template. This is the reason kint(content) does not produce any output. The content of the field is in items:

```
  {% for item in items %}
    <div{{ item.attributes }}>{{ item.content }}</div>
  {% endfor %}

```

Did you try twig debug to find the right template?

Debugging Twig templates

**Edit:** (Template in question was edited to node template)

This is no problem to add divs and classes to the node twig. Here is an example:

```
<div class="container-outside-article">
  <article{{ attributes.addClass('class-added-to-article') }}>
    <div class="container-inside-article">
      <div{{ content_attributes }}>
        {{ content }}
      </div>
    </div>
  </article>
</div>

```

I've added two container inside and outside the article tag and one class to the article tag itself.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: You are not authorized to access this page with blocks displayed
I made a custom module in Drupal 7 with a simple page.

I used hook\_menu to make permission :

```
function mymodule_menu() {
  $items = array();
  $items['prestart'] = array(
            'title'             => t('Prestart page'),
            'page callback'     => array('mymodule_show_page'),
            'access arguments'  => array('access content'),
            'access callback'   => 'mymodule_isUserAuthenticated',
            'type'              => MENU_NORMAL_ITEM,
  );
  return $items;
}

```

The function to check if the user is authenticated :

```
function mymodule_isUserAuthenticated() {
   if (!user_is_logged_in()) {
       return FALSE;
    }
     return TRUE;
  }
}

```

After I created block (admin/structure/block) and I added to the page.

**Problem :** If I go on the page in a private navigation tab (so not connected), I can see *You are not authorized to access this page* but all blocks are displayed.

How can I fix it ?

# Answer
> 1 votes
You probably need to adjust the visibility settings of your blocks (see screenshot below). You can, for instance, restrict the visibility to authenticated users only.

It is also possible to do it programmatically. See this question, for some guidance.

---
Tags: 7, users
---


# Question
Title: CSS/JS aggregation, huge number of files
I use css and js aggregation for increase the speed of a drupal 7 website. Now, when I log in with an user A, four news files (one css and one js) are added in the files website directory. (for each website page) Then, when I log in with an user B, four news files (one css and one js) are added in the files website directory. ...etc

I'm afraid because the website will have many thousand of users. So, there will be huge number of css/js files.

When theses files are deleted ? Can I configure that ?

# Answer
As noted in the post you found:

> They will be deleted automatically 30 days (or whatever your drupal\_stale\_file\_threshold variable is set to) after they were created via drupal\_clear\_css\_cache() and drupal\_clear\_js\_cache().

If you are going to have many thousands of users worrying about file system performance at this stage is likely getting ahead of yourself. Depending on your hosting setup you are more likely to run into other kinds of performance issues (PHP, database, fewer non-file caches, etc) before the file system becomes the bottleneck. You may indeed need to solve that problem eventually but it is unlikely to be the first challenge you need to overcome.
> 2 votes

# Answer
I can second this. My experiences with Drupal's build-in caching system are not that good - I would moreover suggest you using minified .CSS and .JS files by default and/or compressing them on server-side (gzip, JSmin & co.) - .htaccess-examples for doing so can be found easily on Google (although these technologies depend quite much on your server-environment)!
> 0 votes

---
Tags: 7, css-js-aggregation
---


# Question
Title: What does parent::form($form, $form_state) do?
I'm not able to understand what `parent::form($form, $form_state)` does in a content entity form. If I comment it out, the entity form still get rendered.

```
class AdvertiserForm extends ContentEntityForm {
  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    /** @var \Drupal\redirect\Entity\Redirect $redirect */
    $advertiser = $this->entity;
    $form['status_code'] = array(
      '#type' => 'textfield',
      '#title' => t('Redirect status'),

    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
      $form = parent::form($form, $form_state);

  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $this->entity->save();
    drupal_set_message(t('The redirect has been saved.'));

  }
}

```

What does `parent::form($form, $form_state)` do, exactly?

# Answer
> 4 votes
It's executing a method with the same name on its parent class. This is standard fare in any language when you're dealing with inheritance, when functionality from the base class is still (or may be in the future) required.

In this case it's the `ContentEntityForm::form()` method that will be invoked. The fact that it doesn't appear to do/change anything is irrelevant - something might change in the future that *does* require that base class's method to be called, and by referencing it now, you're future-proofed.

Have a read up on OO PHP if this concept is unfamiliar to you, it's one of the more basic ones, so easy to learn. There are a lot of OO concepts used in D8, learning them early on will really help you get to grips with the framework more quickly.

# Answer
> 7 votes
If you look at `ContentEntityForm::form()`, the method called with `parent::form()` since `ContentEntityForm` is the parent class, you will notice what exactly it is doing.

```
  $form = parent::form($form, $form_state);
  // Content entity forms do not use the parent's #after_build callback
  // because they only need to rebuild the entity in the validation and the
  // submit handler because Field API uses its own #after_build callback for
  // its widgets.
  unset($form['#after_build']);

  $this->getFormDisplay($form_state)->buildForm($this->entity, $form, $form_state);
  // Allow modules to act before and after form language is updated.
  $form['#entity_builders']['update_form_langcode'] = [$this, 'updateFormLangcode'];
  return $form;

```

It doesn't significantly change the form, so it is expected the form doesn't apparently change, or it is rendered the same if you don't call `parent::form()`, but (as the comment says), it allows modules to act when the form language is updated. You could not see anything different, but you are actually avoiding modules can do anything when the form language is changed.

---
Tags: forms, 8
---


title: How To: Change Block Text Color

text:
# Question
Title: How To: Change Block Text Color
I need to change the text color of a block on my main page. The existing theme uses blue text on a light blue background which makes it somewhat difficult to read. I used Firebug to find the div ID and created a local.css file per this post.

```
#block-views-team-events-calendar-block-2 .content
{
color: #ffffff;
}

```

I changed the color to white, but, I don't see any change on the page. I tried clearing the cache, but, I got the same results. How can I change the text color for one single block on my main page?

# Answer
> 2 votes
There can be multiple reasons why your styles are not applied to the page elements:

* **CSS aggregation is enabled.** Disable aggregation and see if your custom CSS works. If it doesn't, you probably forgot to include the file in your theme - move to the next option.
* **CSS stylesheet is not added to the theme via THEMENAME.info file or other methods**. Placement of the CSS file in your theme's css folder does not make it load while Drupal pages are loading.
* **wrong selector used**
* **styles are overridden by a selector with higher specificity** ...etc.

To add CSS stylesheet to the Drupal theme, add the following to the current theme's .info file and clear cache:

```
stylesheets[all][] = css/local.css

```

You can also add CSS files to your theme via drupal\_add\_css function that you can use in `hook_preprocess_page()`.

Hope this helps.

---
Tags: 7, blocks
---


# Question
Title: How can I reduce the initial load of page?
I've been monitoring the speed of my site load on Drupal 7 and I would like to increase its initial loading speed. Currently it takes 6 seconds just to get data from the server. What is the first page called? In total it takes about 10 seconds for my site to load.

What methods are there to reducing this initial startup load time? I've tried boost, but I can't use it as it renders all my webforms useless. I've already used the lazyloader module for images and enabled gzip aswell.

# Answer
> 2 votes
There isn't much you can do with the browser debugging tools in this case. You need to debug this on the server:

https://docs.acquia.com/articles/using-xhprof-evaluate-code-performance

---
Tags: 7, performance
---


# Question
Title: "It is not safe to rely on the system's timezone settings."
I'm finding the following error in the *Recent log messages* report:

> Warning: DateTime::createFromFormat(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date\_default\_timezone\_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in Symfony\Component\HttpFoundation\Response-\>sendHeaders() (line 331 of /var/www/drupal/drupal-8.1.1/vendor/symfony/http-foundation/Response.php).

My site does include any custom module, but as far as I can see, the only date function it calls is `time()`. Shouldn't Drupal handle the timezone setting?

Is there any way I can isolate where this function is getting called from?

It's not a major problem, but I'd prefer to minimise unnecessary warnings in my log.

# Answer
This is a php setting, put this into php.ini:

```
date.timezone = 'Europe/Dublin'

```

All timezones:

http://php.net/manual/en/timezones.php
> 13 votes

---
Tags: 8
---


# Question
Title: Script exits on drupal_bootstrap_full when run from system cron
I have a script that imports data into custom entities created in a drupal 7 database. It needs to run daily so i've added it to my system crontab (running CentOS 6.7). The problem i am having is that when it's run from cron (the script is executable and there's a symlink to it added in /usr/sbin) it runs but fails when the drupal bootstrap is run. It works flawlessly when run from my user id, the service account user id, another persons id, and on so i know that the script is written correctly. There is no error reported to the console (grabbing std\_out and std\_err output in my cron command) and there are no php errors logged. I am at a loss of where to look for the answers i need to find out why it's failing. I assume it's something to do with the environment when run from cron but i've confirmed the shell is bash as expected and i'm not using any environment variables that aren't set explicitly within the script. Where can i look for more answers?

Here's My crontab:

```
55 16 * * * svc_load cs-import >> /var/log/import-log-`date "+\%Y.\%b.\%d"`.log 2>&1

```

Here's the relevant lines to load drupal from my script. I see all the echo's print out except the last "drupal loaded". I even tried an or die() after the bootstrap function but it didn't do anything, there must be a crash of some sort that aborts the script before php can process the die() function.

```
// Drupal Connectivity
echo "Start Loading Drupal\r\n";
define('DRUPAL_ROOT', dirname($parent_dir)."/httpdocs");
echo "Set Drupal Root\r\n";
require_once (DRUPAL_ROOT.'/includes/bootstrap.inc');
echo "Included Bootstrap.inc\r\n";
drupal_override_server_variables();
echo "Overrided Server Variables\r\n";
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
echo "Drupal Loaded\r\n";

```

I have PHP logging on, here's the relevant lines from php.ini but the file size never increments when I run this script (it does on other errors).

```
log_errors = On
log_errors_max_len = 1024
error_log = /var/www/vhosts/dev/logs/php_errors.log

```

Thank you in advance for any help you can provide! ~Lindsay

# Answer
> 1 votes
I found the issue is i have multiple PHP versions installed on my system because my hosting company is running plesk. PHP 5.2 is a base version and it looks like drupal loads something that makes php5.2 fail. After upgrading my script to point to the proper 5.5 version of php everything is running as expected. Thanks to all who replied.

---
Tags: 7, cron, bootstrapping
---


# Question
Title: Migrating XML data with many-to-one relationships
I'm using Drupal 8's migrate system to import data from an XML source which has this simple layout:

```
<books>
    <book>
        <isbn>...</isbn>
        <title>...</title>
        <author>...</author>
    </book>
</books>

```

My code creates 'book' and 'author' entities on the Drupal side, with each 'book' referencing its corresponding 'author'. The problem is that different books can have the same author. This ends up creating a separate 'author' entity for every occurrence of the same author in the XML file.

I've looked at the $row variable in PrepareRow to see if there are ways of manipulating the ID map table to avoid the duplicates but haven't had any luck. So I'd appreciate any suggestions or ideas!

By the way, my code has two source plugins - one for 'author' (which runs first) and another for 'book'. I'm using the 'plugin: migration' in my YAML file to make the book entity pickup the author entity's ID. It all works except that author gets duplicated.

# Answer
> 1 votes
I ended up not using the "plugin:migration" option because apparently it assumes one-to-one relationships. So instead, I added code to the 'author' plugin's prepareRow to rejected incoming duplicate authors. Then I added code to my 'book' plugin's prepareRow to retrieve the author entity ids from the database and add it to the book entity. I was hoping for a built-in solution in the migrate system but this will do.

# Answer
> 0 votes
What is the source key you're using for the author migration? If you use a unique identifier for the book, then in your author migration's prepareRow(), if you find the author already exists, map the source (book) ID to the existing author on the Drupal 8 side:

```
$this->idMap->saveIdMapping($row, ['author_id' => $existing_author_id], MigrateIdMapInterface::STATUS_IGNORED);
return FALSE;

```

Then, the author's map table maps each book ID that shares an author to the same author, and the migration plugin in the book migration looks up that book ID and gets the single author record.

---
Tags: 8, migrations
---


title: Migrating Views

text:
# Question
Title: Migrating Views
As Drupal 6 is officially EOL, I was planning to upgrade my Drupal 6 site to Drupal 8. My current site consists of lots of contents and views. I saw a discussion saying that Drupal 6-x-3.x can be migrated to drupal 8. But using the migrate, Drupal migrate UI, I was not able to do so. Is the best method to upgrade the site first to D7 and then to D8, other than creating the view manually? What about the D6 sites with views 6.x-2.x?

# Answer
> 1 votes
Migration of views is not currently supported - see https://www.drupal.org/node/2500547. Note that the destination D8 system would only be able to see views that are stored in the database (i.e., those created manually through the UI, not those provided in code).

---
Tags: 8, migrations
---


# Question
Title: Migrate files with directories and sub directories
I am having issues with migrating my files locally on my computer. Im using the migrate UI and my `source_dir = /Users/cwahlfeldt/Sites/dev.urbanaillinois.us/sites/default/files/` which is a full path to the files I'm trying to migrate. `destination_dir = public://`. Im getting the following errors when attempting a migration:

```
Informational   Undefined property: stdClass::$value File /Users/cwahlfeldt/Sites/drupal-7.x-dev/sites/all/modules/migrate/plugins/destinations/file.inc, line 704(file: /Users/cwahlfeldt/Sites/drupal-7.x-dev/sites/all/modules/migrate/plugins/destinations/file.inc, line 704)

Error   The specified file /Users/cwahlfeldt/Sites/dev.urbanaillinois.us/sites/default/files/ could not be copied to public://files: "copy(): The first argument to copy() function cannot be a directory File /Users/cwahlfeldt/Sites/drupal-7.x-dev/sites/all/modules/migrate/plugins/destinations/file.inc, line 393"

```

The sources files directory has many sub directories within it and the `copy()` function thats used by the migrate module doesn't seem to want to take a directory. Is there a solution to this? Or is this caused by something else.

# Answer
> 0 votes
How is destination\_file mapped in your file migration? See https://www.drupal.org/node/1540106 for information on how the file options interact to determine the full destination filespec.

---
Tags: 7, migrations
---


# Question
Title: How can I debug/test my custom migrate module?
I've written a custom migrate module in Drupal 8. (Based on these instructions: https://github.com/wunderkraut/migrate\_source\_example/)

The migration reads data from a XML file with the "migrate\_source\_xml" extension and should write/update the data in a node.

I have a yml config file in /config/install/ and some logic in /src/migrate/source/

When I run the migration with "drush mi --all" I get the correct values in my prepareRow function. Unfortunately, no nodes were create and I get the message "Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored)"

With the prepareRow function I'm able to stop the script at this position. But how can I debug the script afterwards? Does exist a postImport function or something similar?

How do you test your D8 migrations?

Thank you very much for your inputs!

# Answer
> 2 votes
The place you want to step through is the while loop in MigrateExecutable::import() - this is where each source row is received after prepareRow(), run through the processing pipeline ($this-\>processRow), and saved to the destination plugin ($destination-\>import()).

---
Tags: 8, migrations
---


title: Sub theming Seven theme

text:
# Question
Title: Sub theming Seven theme
Is it possible to create a subtheme for the core Drupal Seven theme (in drupal 7)? If so, how do I do this? I had already tried to do it a few months ago to override the templates for Simplenews but it wasn't working.

# Answer
Creating a sub-theme is pretty basic:

1. Create a sub-dir for your themes in your configured sites dir (e.g. **sites/default/all/my\_subtheme**).
2. Copy over the .info file of the theme you want to subtheme (e.g. **themes/seven/seven.info**) to your new theme directory with it renamed to match your directory (e.g. **sites/default/all/my\_subtheme/my\_subtheme.info**).
3. Edit your sub theme .info so that it also contains the line `base theme = seven`. You can optionally give it another `name` or `description`.

From there you should be able to enabled it and start using it. You can copy over other resources that you'd like override in your subtheme. In your example, you can create templates subdirectory (e.g. **sites/default/all/my\_subtheme/templates**) and copy the simplenews templates that you wish to override.
> 0 votes

---
Tags: 7, theming, emails
---


title: How to render paragraphs module in twig

text:
# Question
Title: How to render paragraphs module in twig
I am creating a custom template for my theme and I am constructing a page.html.twig page. I want to call of the individual node fields into separate rows. I have been able to successfully display everything except the paragraph field.

I have tried.

```
{{ node.field_benefits }}
{{ node.field_benefits.value }}
{{ paragraph.field_benefits }}
{{ paragraph.field_benefits.value }}
{{ node.paragraphs.field_benefits }}

```

And nothing has worked. Does anyone have any idea of the correct structure to call in the paragraph module?

Or would a for function work

```
{% if node.field_benefits %}
{% for field_items in node.field_benefits %}
{{ field_item.value }}
{% endfor %}
{% endif %}

```

# Answer
> 7 votes
First add a `paragraph--your_paragraph_machine_name.html.twig` to the templates directory of your theme.

Accessing your paragraph fields can be done by adding twig variables in a format similar to `{{ content.field_your_field }}`.

If you want only the field value, that's a little trickier. For instance if you had a List (text) field and wanted to get the value from the selected option, you could do something like:

```
{% for item in content.field_select_list %}
  {% if item is iterable %}
    {% for key,value in item %}
      {% if not value is iterable %}
        {% if key == '#markup' %}
          {{ value }}
        {% endif %}
      {% endif %}
    {% endfor %}
  {% endif %}
{% endfor %}

```

You can always run a `{{ dump(content) }}` to see the structure and get the values you're looking for. Hope this helps!

**EDIT:** You can avoid all the silly nested loops. The above example should be written like:

```
{% set value = content.field_select_list.0['#markup'] %}
{{ value }}

```

For a Text (plain) field it might look something like:

```
{{ content.field_text.0['#context'].value }}

```

To get a URL value from a Link field I've seen suggestions like:

```
{{ content.field_link['#items'].0.value.uri }}

```

But it would have an "internal:/" prefix, so I've had better luck with something like this:

```
{{ content.field_link.0['#title'] %}

```

---
Tags: views, theming
---


# Question
Title: How can I add a custom form menu link to the administrative menu programmatically?
How can I add a custom form menu link to the administrative menu programmatically?

I am trying to add this form as admin menu link like content, structure and module.

# Answer
> 3 votes
Create a new menu using hook\_menu. Like this

```
$items['admin/config/my_form'] = array(
    'title' => 'My Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_id'),
    'access callback' => TRUE, // Give access as per your need.
    'type' => MENU_NORMAL_ITEM,
);

```

Using this your form will be created with the link / menu item under configuration menu.

Thanks.

---
Tags: forms
---


# Question
Title: How to make user's access to nodes depend on the year a node relates to?
User profile is organizer of this year boat show. After registering, user can create basic pages with main photo and basic text. Afterwards, user is given another role through rules, so he can not by accident create more basic pages but can still setup images, dates, videos, announcements, which are all visible as different views contextual blocks on basic page of the user.

All is fine, except i have no idea how to setup same thing for next year? User can edit basic page, but i would rather leave past year (basic page with views blocks) somehow be archived and visible on the website and his profile, and give him option to setup data for next year.

# Answer
# Option 1 - Add a field to reflect the year

If you'd add a (select list) field to indicate the year that the basic page relate to, you could use the value of that field with some Rules conditions to perform all sorts of validations to prevent a user creating and/or updating pages for any years you do not want to allow.

The Rules Event would probably be "Before saving content". And the Rules Conditions would simply be (a) "Entity has field" (for this extra field) and (b) "data comparison" (to find out which year the basic page is about).

# Option 2 - Use the Group module

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

So to answer this question, you'd create a group for each year. For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources:

PS: Group is available as of D7, and has a D8 version also.
> 2 votes

---
Tags: 7
---


# Question
Title: How i could save a block that i had called it before with block_load?
I call a block via a block\_load function and i do some changes. What i want to save this block with my changes..

# Answer
> 1 votes
After reading the code in the `block.module` file I can suggest the following:

1. Leave your code in `hook_block_info_alter` unchanged.
2. From your `hook_enable` hook call the following function to force calling and saving your `hook_block_info_alter` code:

```
_block_rehash();

```

Quoting from the function's documentation:

> Updates the 'block' DB table with the blocks currently exported by modules.

Hope this does it for you!

# Answer
> 0 votes
You can use Block View Alter hook or Block Save hook

And a complete Block hooks you can find it here.

---
Tags: 7, blocks, installation
---


title: Pluralize Flag/Unflag Link Text

text:
# Question
Title: Pluralize Flag/Unflag Link Text
I want to rewrite the link text for Flags such that it includes the number of flaggings for that node, as pluralizing the output.

e.g.

* 1 Flag
* 3 Flags

I can get as far as getting the flag count and pluralizing the output using a field rewrite, but the Ajax link breaks, and the field can no longer be clicked to flag or unflag the node.

I've tried the dlike module, but this doesn't seem help with pluralizing the flag/unflag link

# Answer
> 1 votes
I found I was able to do this by changing the flag link text (in the flag configuration) to `[node:flag-machinename-vote-count]`, which gave the number of flag for that node.

Then, modifying line 57 of the flag theme file: `flag.tpl.php` to

```
<a href="<?php print $link_href; ?>" title="<?php print $link_title; ?>" class="<?php print $flag_classes ?>" rel="nofollow"><?php print format_plural($link_text, '1 Flag', '@count Flags') ; ?></a><span class="flag-throbber"> </span>

```

Note that this is actually only changing the small php snippet that displays the link text to us the format\_plural function:

this `<?php print $link_text; ?>`

to this `<?php print format_plural($link_text, '1 Flag', '@count Flags') ; ?>`

# Answer
> 0 votes
Put the code below in your views **Global:PHP** field

```
print flag_create_link('your-flag-machine-name',$row->uid);(\

$counts = flag_get_counts('user', $row->uid);

//note in my case i have to add flag links on user profiles
//change according to your need here, say('node', $node->nid).

if ($counts['your-flag-machine-name'] == 0) {
  echo 'please vote first!!';
}

if ($counts['your-flag-machine-name'] == 1) {
  echo $counts['your-flag-machine-name'] .' Like';
}
else {
  if ($counts['your-flag-machine-name'] >= 2) {
    echo $counts['your-flag-machine-name'] .' Likes';
  }
}

```

---
Tags: flags
---