# Question
Title: Getting node view mode in field preprocess
I am trying to get the view mode of a node to use it in a field twig file by writing this function in my\_theme, but it doesn't work:

```
function MY_THEME_preprocess_field(&$variables, $hook) {
 if ($node = \Drupal::routeMatch()->getParameter('node')) {
  $variables['view_mode_2'] = $node->view_mode;
 }
}

```

I don't know if the variable is correct, but when I write some echo code I see that already the if condition isn't fulfilled.

EDIT: the if condition is only fulfilled when the node is open, but not when its teaser is shown as part of a view on the front page.

# Answer
In a field template the view mode is stored here:

```
$variables['element']['#view_mode']

```

So you could check in preprocess, if the node is not displayed as teaser:

```
function MY_THEME_preprocess_field(&$variables) {
  if ($variables['element']['#view_mode'] != 'teaser')  {
    // node is not displayed on the front page
  }
}

```

The same condition in a field twig:

**field.html.twig**

```
{% if element['#view_mode'] != 'teaser' %}
  node is not displayed on the front page
{% endif %}

```
> 15 votes

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


# Question
Title: Multiple forms one page always submit with the values of the first
I have got a form defined that is displayed multiple times on a single page. For each instance of the form, different values (node ids) are inserted into the hidden fields, which seems to be there once the form is rendered.

However, when I submit any of the forms on the page, the submit handler always gets the values that have been inserted for the first instance and I can't seem to get hold of why this is happening.

One thing that I noticed though is that all of my forms have the same form\_id, form\_token and only the form\_build\_id changes.

Any idea why this is happening, I can't find a solution to this problem anywhere.

Thanks a lot.

Code:

I'm attaching the form to the nodes in hook\_node\_view like this:

```
$node->processed['add_collection_form'] = drupal_get_form('add_to_collection_form', $node->nid);

```

when I try to do it in hook\_node\_load drupal always complains about the memory limit in PHP even though I have set it to a generous 1GB, which is pretty weird.

The form on the page are rendered the standard way:

```
print drupal_render($node->processed['add_collection_form']);

```

in node--.tpl.php

# Answer
> 2 votes
To use multiple instances of the same form on a page you need to implement hook\_forms(), which allows you to essentially use 'aliases' for your forms.

```
function hook_forms($form_id, $args)
{
  $forms = array();

  // Check if the form id is of the pattern add_to_collection_form-[NUMBER]
  if(preg_match('/^add_to_collection_form-\d+$/', $form_id)
  {
    $forms[$form_id]['callback'] = 'add_to_collection_form';
  }

  return $forms;
}

```

The above code tells Drupal that if a form ID has the pattern add\_to\_collection\_form-\[NUMBER\], to use the add\_to\_collection\_form form callback.

Now you can call the forms on your page like this:

```
drupal_get_form('add_to_collection_form-1', $node->nid);
drupal_get_form('add_to_collection_form-2', $node->nid);
drupal_get_form('add_to_collection_form-3', $node->nid);

```

---
Tags: 7, forms
---


# Question
Title: Views show list of nodes that have referenced node on another content type
I have research and people content types. In people content type I have nodes that are authors for researches. I referenced author name field on research content type to people content type. Now I want to show all people type nodes that referenced in research content type nodes. In another word I want to show list of all my authors from my people content type. Thank you very mach.

# Answer
I found the solution:

1. Add view from people content type.
2. and add relationship referencing entity with the author\_name field and check Require this relationship.
3. To remove repeated rows use Views Distinct module.
> 0 votes

---
Tags: views
---


title: The "tag" plugin does not exist

text:
# Question
Title: The "tag" plugin does not exist
The issue is about page loading like the following ones:

1. Front page
2. Taxonomy pages (for instance, https://talash.by/taxonomy/term/33)
3. Any view pages in edit mode /admin/structure/views/view/block\_content
4. Content list page /admin/content
5. User list page /admin/people

I have a message "The website encountered an unexpected error. Please try again later."

Apache log shows:

> Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "tag" plugin does not exist." at /var/www/site/public\_html/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 52,

The issue happens even if I make a site copy (files and database) on the same physical server, but as different virtual server. Internal pages can be loaded (for example, https://talash.by/terms-of-use)

I am using Drupal 8.2.4 (standard) on Ubuntu 16.04, with PHP 7.0.8-0ubuntu0.16.04.3 (cli).

These are the non-core modules:

* Media Colorbox (colorbox) Module Not installed 8.x-1.2

+ Other Backup and Migrate (backup\_migrate) Module Not installed 8.x-4.0-alpha1
    + Other Colorbox Inline (colorbox\_inline) Module Not installed 8.x-1.0-rc2
    + Other Disqus (disqus) Module Enabled 8.x-1.0-rc3
    + Other Exclude node title (exclude\_node\_title) Module Not installed 8.x-1.0-beta1+7-dev
    + Other Ultimate Cron (ultimate\_cron) Module Not installed 8.x-2.0-alpha1
    + Web services HAL (hal)
    Bootstrap Bootstrap (bootstrap)
    + Theme Enabled 8.x-3.1
    Bootstrap Bootstrap Clean Blog (bootstrap\_clean\_blog)
    + Theme Enabled 8.x-1.0-rc2

# Answer
> 2 votes
Tag is the views cache plugin: \Drupal\views\Plugin\views\cache\Tag, that is in core.

If you are missing that then the files of your installation are messed up, you are possibly missing other files as well. You might want to re-upload all files and also consider using a more reliable deployment method like composer and not upload files over FTP or so.

---
Tags: 8
---


# Question
Title: Every link except home directes to 'Not found' page?
I have created site directly on the shared host server by downloading fresh Drupal 8. Every think went Ok with installation and site installed properly. But whenever I click on any link of admin bar or my-accont/logout it directs me to `Not Found` page.

*For example I clicked on `Extend` from admin menu and following message did appear.*

>

*Not found message*

>

Any idea why this is happening and how to correct that. Very thanks.

# Answer
You are missing (or having a malformed) htaccess file.

You can download a .htaccess file directly from drupal.org with the following link: https://raw.githubusercontent.com/drupal/drupal/8.2.x/.htaccess

If you want an htaccess file for a different disk version then you can change the version number in the above link.
> 3 votes

# Answer
As Eyal said, you have a problem with your .htaccess file. For further instructions, you may follow my blog post if you wish: https://masky-the-tech-nerd.blogspot.com/2016/12/how-to-install-drupal-on-ubuntu-1610.html
> 0 votes

---
Tags: 8
---


title: Add field to DFP module

text:
# Question
Title: Add field to DFP module
I need to add a `<div>` wrapper with a specific ID to a DFP AD tag within the block.

The DFP Module appears to create AD tags as entities. I cannot determine where the AD tags are stored or how to create another field to the AD tag entity that I can pull out in a preprocess function to send to my template.

I am hacking the DFP module.

Does anyone have a pointer on where to start?

# Answer
> 1 votes
If you look in the source code of the module you find that `tag` is a configuration entity (http://cgit.drupalcode.org/dfp/tree/src/Entity/Tag.php). This type of entities are not fieldable like content entities. But you can add custom fields by altering the config form and store the added fields in your module configuration.

Here is a how-to for this:

https://www.webomelette.com/drupal-8-custom-data-configuration-entities-using-thirdpartysettingsinterface

---
Tags: 8
---


# Question
Title: Prepopulate custom fields during checkout with data from user account
I have installed Drupal Commerce in an existing site and I am currently trying to figure out how to prepopulate fields during the checkout process. I use the Commerce Extra Adress Popuplate module to fetch the address information from the user account, but how do I do this exact same thing with other custom fields? For instance I have a custom `Client number` field in the user account that I really would need to prepopulate to the checkout form.

I have read a bunch of other post on this subject (for instance Populating fields from the User entity during a Commerce checkout, but I haven't found a solution that seems to do exactly what I am looing for.

EDITED: to be more specific, I have created a new Customer Profile using the Customer Profile Type UI module. It contains one field so far, the client number field. How can I fetch the current user's value from the same field in the User account, during checkout?

EDITED AGAIN: With rules I have tried using this setup:

```
{ "rules_kopiera_kundnummer_fran_anvandaren" : {
    "LABEL" : "Kopiera kundnummer fr\u00e5n anv\u00e4ndaren",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "commerce_order_insert" : [] },
    "DO" : [
      { "data_set" : {
          "data" : [ "commerce-order:owner:field-kundnummer" ],
          "value" : [ "site:current-user:field-kundnummer" ]
        }
      }
    ]   } }

```

But the current client number is not copied into the field in question. Any ideas?

# Answer
> 1 votes
If I am not mistaken, you can do this with rules. Use the 'after saving a new commerce order' event and choose to 'set a property' on the commerce order. For the value you can navigate to the customer profile and select your field.

Optionally you can also add the 'after saving an existing commerce order' to update the field at every step in the process. (commerce saves the order after each checkout step).

Update

This requires some knowledge about how Drupal commerce works. An order is created as soon as you place a product in the cart. You now have a product in the `cart` state. As you proceed to checkout, the order state updates with every step. If you leave the checkout, the state is frozen and you could continue it at every time.

Since your rule only acts on `commerce_order_insert` this means the number will only be copied if you create a new cart. (proceed to checkout your current order or delete the entire order by going to the order overview.) This is why I proposed to also add the `commerce_order_update` event as a trigger. That should update the number at every step of the checkout process.

Also there appears to be a misconfiguration in the rule (or I misunderstood your question). If the number is on a customer profile type, you should get it from there. `[ "site:current-user:field-kundnummer" ]` assumes this is a field configured on the user profile. And `[ "commerce-order:owner:field-kundnummer" ]` is really the user if of the order owner. (Changing that might mess up everything).

I guess you should be setting `[ "commerce-order:<commerce-customer-profile-reference>:field-kundnummer" ]` instead. That would be the field on the customer profile.

---
Tags: 7, commerce
---


# Question
Title: "View any coupon of any type " permission for anonymous reduces the Score in acquia
In my e-commerce website, anonymous user can't able to view the add coupon field until and unless I gave `"View any coupon of any type"` permission. Because its having notice like this: `Warning: Give to trusted roles only; this permission has security implications.` Acquia Reduced the score of our website.So any other way is there to solve this problem?

# Answer
The Acquia Insight tool (I am assuming you are referring to that score) is a tool that helps you find potential problems in your website and configuration. It is an automated tool that performs simple checks. It is a guide and a tool. Not exact science. (It could throw a false positive.)

However in my installation of `Commerce Coupon 7.x-2.0-rc2`, there is also the permission to `Redeem any coupon` (and the per type `Redeem <type> coupons` permission). And that works for anonymous user as well. Perhaps you should try that instead?
> 0 votes

---
Tags: 7, commerce, users
---


title: Best way to add Vcard to node

text:
# Question
Title: Best way to add Vcard to node
I have a content type with CCK fields that make up contact information. I was asked to add a VCard / Add to outlook feature.

I have a few ideas on how to do this but not sure which one is good. My only actionable idea at the moment is to edit a template file for where it is displayed and create the vCard link within there. However, I also use these in views and I'm not sure if that would translate to the view (I think not)

Is there such a thing as a field that is totally generated? For instance, I could add a vcard field that would then take you to the generated vCard?

I know that there is a module for this but it seems to only work with user profiles.

# Answer
Forgive me for a little self-promotion here, but I had the exact same issue a long time ago. This was the reason to build the Views vCards module.

> This module aims to provide a vCard attachment for views in a similar way as the views built in feeds system does.
>
> The existing vCards modules vCard and vCard Field work with either Profile2 data, or data the user has to enter himself. There was however no solution for websites that use the Core profile system. This module attempts to fill that gap. (But should in theory be able to use all content that views has access to.)

So this module works with data from nodes and other entities as well.
> 0 votes

# Answer
Like you said, there is a vcard module for user profiles, but there is also a vcard module for cck fields; you might want to try the module on a local test site, and check if there isn't any issue, as the usage statistics of this module is very low.
> 2 votes

---
Tags: 7, entities, theming
---


title: file pattern name for content type

text:
# Question
Title: file pattern name for content type
What is Drupal 8 file pattern name for a specified content type?

Suppose I have a *Movie* content type. What is the pattern name for its page? Is it `page--node--movie.html.twig`?

# Answer
> 3 votes
This is what your looking for.

The Drupal 8 code is the following one.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $suggestions[] = 'page__' . $node->getType();
  }
  return $suggestions;
}

```

# Answer
> 1 votes
Quoting from the same page as ssibal:

> ## Nodes
>
> Pattern: node--\[type|nodeid\]--\[viewmode\].html.twig
>
> Base template: node.html.twig (base location: core/modules/node/templates/node.html.twig)
>
> Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:
>
> 1. node--nodeid--viewmode.html.twig
> 2. node--nodeid.html.twig
> 3. node--type--viewmode.html.twig
> 4. node--type.html.twig
> 5. node--viewmode.html.twig
> 6. node.html.twig
>
> Note that underscores in a content type's machine name are replaced by hyphens.
>
> See the node.html.twig API documentation.

So for your content type it should be `node--movie.html.twig`

---
Tags: theming, 8
---


# Question
Title: Google indexes the page using the domain alias
I have a Drupal 8 page which is indexed from Google without any error. The front page is a node configured as a front page in the *Basic site* settings (admin/config/system/site-information) using the path alias /front or de/heim.

The point is that the path alias for the front page should be the root (e.g. example.com) which is it. So, everything is working fine if I navigate the page.

Why is the path alias shown in Google search results, and not the root domain? It shows example.com/en/front or example.com/de/heim, not example.com.

I have never seen this problem before using Drupal 6 or Drupal 7.

# Answer
It really depends on what page Google finds first, I guess. So, I do now know.

> Why is the alias shown in Google search results, and not the root domain?

However in order to overcome this, you would have used the global redirect in Drupal 7, which has been merged with Redirect. I have not tried it, but if it an exact port it should still be able to.

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

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


title: Username Token in block doesn't work

text:
# Question
Title: Username Token in block doesn't work
I'm using Drupal 7 and installed the Token filter module.

I want to display a welcome message in block; I used `<h2>Welcome [user:name]! </h2>` as token, but the token is not recognized.

Why isn't the token recognized? Which token should I use?

# Answer
> 2 votes
Try this token instead:

```
[current-user:name]

```

# Answer
> -1 votes
This `[current-user:name]` token works in block title.

---
Tags: tokens
---


# Question
Title: How to place multiple blocks in one column in bootstrap theme
I am using bootstrap theme. I have 4 blocks: block1, block2, block3, block4. Bootstrap has 12 columns grid. I would like to place block 1 in first 7 columns(using bootstrap class "col-md-7"). I would like to place block 2,3,and 4 to the right of the block 1. Can you please advise how to achieve it?

# Answer
> 2 votes
This approach might suit your case.

Create 2 new regions in your template info file and render them in your page.tpl.php

> If you are using a bootstrap subtheme, this file will be located in siites/all/themes/bootstrap/templates/system so you will have to copy it and put in your templates folder under you subtheme folder. Remember to clear the Theme Registry cache after this.

So I would do this like below

**info file**

```
regions[main_block] = 'Main Block Region'
regions[side_block] = 'Side Block Region'

```

**page.tpl.php file**

```
<div class="row">
  <div class="col-md-7">
    <?php print render($page['main_block']); ?>
  </div>
  <div class="col-md-5">
    <?php print render($page['side_block']); ?>
  </div>
</div>

```

After go to the blocks admin interface and select the blocks to show on the correct region. Also for the Side Blocks render all three blocks you need in the Side Block Region and use the correct weights to sort them as you like.

# Answer
> 0 votes
You need to override/create tpl files depends on your situation. After that use the Bootstarp class you need to use.

See **bootstrap\_subtheme/templates/README.txt**.

You should put those files in yourtheme/templates/ (no sub-folder) and a quick cache clear after that.

---
Tags: 7, theming
---


# Question
Title: Create imagefield with maximum number of values programmatically
I've created an imagefield in my own module, like this:

```
$form['heading_img'] = array(
    '#type' => 'media',
    '#title' => t('Heading image'),
    '#default_value' => isset($content['settings']['heading_img']) ? $content['settings']['heading_img'] : '',
    '#theme' => 'media_widget',
    '#media_options' => array(
      'global' => array(
        'types' => array('image'),
        'schemes' => array(
          'public' => 'public',
        ),
        'file_extensions' => 'png gif jpg jpeg',
        'min_resolution' => '1920x550',
        'max_filesize' => '750 KB',
        'uri_scheme' => 'public',
      ),
    ),
);

```

Sometimes I need more heading images. Is it possible to make this field unlimited?

So you could click on a button: Add an other image. Something like this.

# Answer
> 0 votes
When scanning though the field definition of the media fields, you'll notice the `multiselect` property on line 118. Which gets the value of `$multiselect` from line 103:

```
$multiselect = ($field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED);

```

So in your definition you could try adding this multiselect property with an integer value (eg. 5 to allow 0-5 images), or `FIELD_CARDINALITY_UNLIMITED`.

```
$form['heading_img'] = array(
    '#type' => 'media',
    '#title' => t('Heading image'),
    '#default_value' => isset($content['settings']['heading_img']) ? $content['settings']['heading_img'] : '',
    '#theme' => 'media_widget',
    '#media_options' => array(
      'global' => array(
        'types' => array('image'),
        'schemes' => array(
          'public' => 'public',
        ),
        'file_extensions' => 'png gif jpg jpeg',
        'min_resolution' => '1920x550',
        'max_filesize' => '750 KB',
        'uri_scheme' => 'public',
        'multiselect' => FIELD_CARDINALITY_UNLIMITED
      ),
    ),
);

```

---
Tags: forms, media
---


title: views custom link like page more link

text:
# Question
Title: views custom link like page more link
I want to add a custom link at the end of the loop of my view just like Pager More Link do. But I want to create a custom link. What I've tried so far:

I have created a `Custom Text` field, rewrote it to a link that I want and made it exclude from display. Then I group my this field and with css I place it where I want it. The only problem is that this grouped field is displayed with an `<h3>` tag that I don't want.

Is there any way to group field but not in tag `<h3><h4>...` or there is a module or something which can give me a option to create a link similar to the pager more link but with a custom url?

# Answer
> 0 votes
Why not add a `Text area` view footer field?

You can set it to full HTML and just add an HTML anchor there. Optionally there is checkbox to 'Display even if the view has no results'.

This adds a custom link below your view.

---
Tags: views, navigation
---


# Question
Title: How do I diagnose a unstable installation on ubuntu 16 server?
I'm deploying a site to a Digital Ocean Ubuntu 16 server. I'm using PHP 5.6, but otherwise using the default versions of the necessary database software. The site functions; however, I frequently have database related errors, specifically, the following one:

> PDOException: SQLSTATE\[HY000\] \[2002\] Connection refused in lock\_may\_be\_available() (line 167 of /var/www/html/phisigmarho.org/includes/lock.inc).

I usually get that error, but I also get "the website experienced an error" errors when I to do anything database or process intensive (updating modules through the UI, etc). I'm relatively new server administration, so I'm not sure what could be wrong or which logs I should be looking at for clues to what's wrong. For the moment, restarting MySQL from the terminal is letting me move forward with setting up the site, but I can't let anyone use the site the way that it is now.

How do I figure out why MySQL keeps going away?

# Answer
Unless you are using Drupal 6, I suggest you start again from scratch and use/install PHP 7.

Drupal 8 and 7 (since 7.50) support PHP 7, which is twice as fast as PHP 5.

```
sudo apt-get update
sudo apt-get install apache2
sudo apt-get install curl
sudo apt-get install mysql-server
sudo mysql_secure_installation

```

Would you like to setup VALIDATE PASSWORD plugin? **n**

Change the password for root ? **n**

Now, for the rest of the questions put **y**

```
sudo apt-get install php php-cli php-curl php-gd php-mbstring php-mcript
a2enmod rewrite
sudo service apache2 restart

```

Now, Install and Secure phpMyAdmin and create a database with and a user with privileges. Do a fresh Drupal install and make sure you get no errors in the install screens.

Once all ok, dump all your DB tables and import your site. Make sure your Drupal directory contains all your modules and the files folder contains all your images and files of your importing site.
> 0 votes

# Answer
Just to expand: part of the issue here was that the MySQL server kept crashing. It was difficult to diagnose initially because the apache and php logs didn't tell me much about why the server was failing. It is a fairly large site with a large number of modules. I finally checked the right Mysql logs and determined that the server was failing due to a memory failure due to the size of my Digital Ocean Droplet. (512mb VPS). My research showed that there are the following solutions: 1) reduce the load to the server and run a low-memory mysql installation; 2) create a swap to better process the requests with the available ram; 3) increase the amount of ram on the server. I chose the third option and it seems to have fixed the problem. I am currently going with php7, but I assume I could also use php5.6 with the ram issue solved.
> 0 votes

---
Tags: 7, database, debugging
---


# Question
Title: Re-using the already themed output of another module in a custom module
I have a function in a custom module that pulls out the formatted (already themed) output of another module:

```
function custom_get_ph1() {
  module_load_include('inc', 'another_module', 'includes/another_module.pages');
  global $user;
  $list = another_module_list_page('user', $user->uid);
  return $list;
}

```

And I am trying to put its output into an unordered list of my custom module:

```
/**
 * Implements hook_menu().
 */

function custom_menu() {
  $items['user/%/hobbies'] = array(
    'title' => 'Hobbies',
    'page callback' => 'custom_hobbies',
    'page arguments' => array('user', 1),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
  return $items;
}

function custom_hobbies() {
$content ='
  <ul>
    <li>placeholder1</li>
    <li>placeholder1</li>
    <li>placeholder1</li>
  </ul>'
 return $content;
}

```

How to get themed output of another module (object) into the list of my custom module (string).

# Answer
> 2 votes
It is quite hard to tell without knowing what `another_module_list_page()` returns, but I assume it is a render array. This can be converted to HTML by passing it through `drupal_render()`

So I guess you should be able to do this using theme\_item\_list():

```
function custom_hobbies() {
  // Add one render array as a child of another one.
  $items = array();
  $items[] = custom_get_ph1();

  $content = array(
    '#theme' => 'item_list',
    '#items' => $items,
    '#type' => 'ul',
    '#attributes' => array('class' => 'my-list'), // optional
  );

  return $content;
}

```

---
Tags: theming
---


# Question
Title: hook_form_commerce_checkout_form_checkout_alter() changes are not reflecting on checkout page
I am trying to make the changes in commerce\_checkout\_form but I am facing some issues. Here is my hook\_form\_FORMID\_alter :

```
function MYMODULE_form_commerce_checkout_form_checkout_alter($form, $form_state, $form_id){
  drupal_add_js(drupal_get_path('module','MYMODULE').'/js/checkout_validate.js');
  $form['customer_profile_shipping']['#title'] = '<h2><b>Shipping Information</b></h2>';
  if(isset($form['account'])){
    $form['account']['#title'] = '';
  }

  if ($form_id == 'commerce_checkout_form_checkout') {
    $form['buttons']['continue']['#validate'][] = 'MYMODULE_form_commerce_checkout_form_checkout_validate';
    dsm($form['buttons']['continue']);
    $form['buttons']['continue']['#attributes']['class'][] = 'classTest';

    if (isset($form['buttons']['continue']['#value'])) {
        $form['buttons']['continue']['#value'] = t('Continue');
    }

    // $form['buttons']['continue']['#validate'] = array_reverse($form['buttons']['continue']['#validate']); // I tried this to give preference to my validate function
    dsm($form['buttons']['continue']);
    dsm($form_state);
  }
}

function MYMODULE_form_commerce_checkout_form_checkout_validate(&$form, &$form_state){
  // This is function is not getting called.
  watchdog('MYMODULE_form_commerce_checkout_form_checkout_validate','partner ID. Response details: @request_details',array('@request_details' =>  print_r($form_state,true)), WATCHDOG_DEBUG);
}

```

I am getting all the dsm on page, means MYMODULE\_form\_commerce\_checkout\_form\_checkout\_alter is getting called but I can see that, neither 'classTest' is added to continue button nor value of continue button is changed.

This is part of dsm($form\_state) :

```
rebuild :  (Boolean) FALSE
rebuild_info :  (Array, 0 elements)
redirect :  (NULL)
temporary :  (Array, 0 elements)
submitted :  (Boolean) FALSE
executed :  (Boolean) FALSE
programmed :  (Boolean) FALSE
programmed_bypass_access_check :  (Boolean) TRUE

```

$form\_state\['rebuild'\] value is false. Is this the reason, I am not abel to see the changes?

# Answer
Try your code inside `hook_form_alter` instead of `hook_form_commerce_checkout_form_checkout_alter`.

```
function MYMODULE_form_alter($form, $form_state, $form_id){
  if ($form_id == 'commerce_checkout_form_checkout') {
    drupal_add_js(drupal_get_path('module','MYMODULE').'/js/checkout_validate.js');
    $form['customer_profile_shipping']['#title'] = 'Shipping Information';
    $form['customer_profile_shipping']['#prefix'] = '<h2><b>';
    $form['customer_profile_shipping']['#suffix'] = '</h2></b>';
    if(isset($form['account'])){
      $form['account']['#title'] = '';
    }
    $form['buttons']['continue']['#validate'][] = 'MYMODULE_form_commerce_checkout_form_checkout_validate';
    dsm($form['buttons']['continue']);
    $form['buttons']['continue']['#attributes']['class'][] = 'classTest';
    if (isset($form['buttons']['continue']['#value'])) {
       $form['buttons']['continue']['#value'] = t('Continue');
    }
     // $form['buttons']['continue']['#validate'] = array_reverse($form['buttons']['continue']['#validate']); // I tried this to give preference to my validate function
    dsm($form['buttons']['continue']);
    dsm($form_state);
   }
}

```
> 1 votes

# Answer
Should it not be that the arguments are passed by reference? You are not returning anything, therefore any changes you make within the function will have no affect outside it's scope.

function MYMODULE\_form\_commerce\_checkout\_form\_checkout\_alter(**&**$form, **&**$form\_state, $form\_id){ .... }
> 3 votes

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


# Question
Title: Call to undefined function entity_create()
i try to include a node creation form by a field attach form. So i try to load the entity of a custom content type created by the back-office with is called 'friterie'. But when i call the entity\_create function i get this error : Call to undefined function entity\_create()

Here is my code :

```
function fritr_register_friterie_form($form, &$form_state) {
    $form = array();

    // INCLUDE FRITERIE ADD FORM
    $form['friterie'] = array();
    //module_load_include('inc', 'node', 'node.pages'); this is an old method
    //$form['friterie'] = node_add('friterie');
    global $language;
    $entity = entity_create('node', array('type' => 'friterie', 'language' => $language->language));
    //$form['friterie'] = field_attach_form('node', $entity, $form['friterie'], $form_state);

    // INCLUDE USER REGISTER FORM
    //$form['user'] = drupal_get_form('user_register_form');

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Enregistrer la friterie'),
    );

    dsm($form);
    return $form;
}

```

I don't know why i get this error, i watch on the official documentation and it says i can do it like i did :/

# Answer
As Gulok said, check if the module entity is installed and enabled.

Be sure to add entity as a depencencie in your .info file as well.
> 0 votes

# Answer
As tenken said in related question

```
require_once "./includes/bootstrap.inc";
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```
> 0 votes

---
Tags: 7, forms, entities
---


title: Conditional Custom Text Filter plugin

text:
# Question
Title: Conditional Custom Text Filter plugin
I have created a custom text filter plugin by extending `FilterBase` class. The `process()` function looks like

```
 public function process($text, $langcode) {
    // Get the current node to determine if it has the glossary field and if
    // that field is enabled.
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node && $node->hasField('field_glossary') && $node->field_glossary->value) {

      // Get all the terms in the Glossary vocabulary.
      $terms = $this->getTerms('glossary');

      // Make all the replacements.
      $new_text = $this->doReplace($text, $terms);

      // Create a filtered text object with the updated text.
      $result = new FilterProcessResult($new_text);
      return $result;
    }
    else {
      // Don't do the replacement.
      $result = new FilterProcessResult($text);
      return $result;
    }
  }

```

I am letting editor to choose to turn off/on text filtering via plugin by creating a flag field as used in code `$node->field_glossary->value`. The problem comes when I need to check the field value on non-node page, as on node page I can get the node object and check the value but for other entites like blocks how can I get the source entity for text?

# Answer
That's not so easy, because the filter is normally not aware from which field it is called from.

The token filter module does this trick:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function token_filter_preprocess_field(&$variables) {
  if (isset($variables['element']['#object']) && $variables['element']['#object'] instanceof ContentEntityInterface) {
    $entity = &drupal_static('token_filter_entity');
    $entity = $variables['element']['#object'];
  }
}

```

The parent entity of the field is stored in a static variable and can be used in the filter:

```
  public function process($text, $langcode) {
    $entity = drupal_static('token_filter_entity', NULL);
    if (!is_null($entity) && $entity instanceof ContentEntityInterface) {
      // use entity
    }
  }

```

http://cgit.drupalcode.org/token\_filter/tree/token\_filter.module?h=8.x-1.x

This may not be the best solution for most cases. If possible look for a better place for the code where you have direct access to the entity. For example in hook\_entity\_view\_alter().
> 2 votes

---
Tags: 8
---


# Question
Title: How do I programmatically store a file reference in a node?
We have content type Image and it have image\_data field for Image reference. So, how we could use static image path for node creation as well as for updating the image reference in the node.

# Answer
> 4 votes
Assume, we have content type : **Image**

It have following fields in the content type.

1. **title**
2. **field\_imagedata** for Image field

Now, we want to create custom node.

**Step : 1** We need to get static image path which we would like to attach in the node. We have in "**sites\default\files\2017-01\source.png**"

So, In drupal, we could access this image uri by "**public://2017-01/source.png**".

**Step : 2** We need to create file reference in our Drupal database. Se we need to use "**File::Create**" method.

**Step : 3** After that, we could generate node using "**entity\_create**".

Please look at the whole code.

```
    $uri  = file_unmanaged_copy("public://2017-01/source.png", "public://2017-01/destinatio.jpg", FILE_EXISTS_REPLACE);
    $file = File::Create([
      'uri' => $uri,
    ]);
    $file->save();

    $new_page_values = array();
    $new_page_values['type'] = 'image';
    $new_page_values['title'] = "PARAG";
    $new_page_values['field_imageda'] = array('target_id' => $file->id());
    $new_page = entity_create('node', $new_page_values);
    $new_page->save();

```

Also, you could update the node, by using the following code.

```
    // Load existing node and attach file.
    $node = Node::load(1);
    $node->field_imageda->setValue([
      'target_id' => $file->id(),
    ]);
    $node->save();

```

Using this code, you could create new node with the static file.

---
Tags: nodes, 8, media
---


# Question
Title: How can I make my site only accessible to logged-in users?
I want to make my site accessible to logged-in users. How can I achieve this?

# Answer
There is a permission in the permissions list called "View published content". The permissions are set under `/admin/people/permissions`. You can remove this permission from the Anonymous user.

If you want to show some pages but not all of them, more granular access controls can be set up with Content Access.

Custom 404 and 403 pages can be set to use any content on your site, using settings at `/admin/config/system/site-information` (in Drupal 7). Sidebars are automatically hidden on 404 and 403 pages but if there are any other blocks (such as menus) you want to hide, you can control which roles see those on their block config pages.

The content of these nodes will also be unaccessible to anonymous users unless you install Content Access and make at least th 403 page allowed for anonymous users. I suggest allowing the 404 page too. Otherwise, you can still get info through if you put it in a node-specific template for your custom 404 page.

The login block can also be invoked programmatically in a tpl.php file with the code from this d.o comment or it can be shown to anonymous users via the block settings.
> 3 votes

# Answer
### First solution

It can be a combo of the permission "View published content" and LoginToboggan.
In LoginToboggan, there is setting to put login form on access denied page as well. "Present login form on access denied (403)". So every anonymous user will see a login form whenever they visit the site.

### Second solution

See this comment, which is valid.

> I think setting the "Default 403 (access denied) page" to the login page is a bad idea because just because someone has access denied does not mean they are not logged in; they may just not have permission to view that particular page.
>
> A better method is to put a little code in your themes template.php.
>
> ```
> function YOUR_THEME_NAME_preprocess_page(&$variables) {
>     if(!$variables['user']->uid && arg(0)!='user' && arg(1)!='login') {
>         drupal_goto('user/login');
>     }
>  }
>
> ```

### Third solution

See this answer.
> 0 votes

---
Tags: users
---


# Question
Title: Why do templates never update dynamic variables after cached?
Given my twig extension:

```
use \Symfony\Component\HttpFoundation\Session\Session;

class RainbirdTwigExtension extends \Twig_Extension {

  public function getGlobals() {
       $session = new Session();
       return array(
           'session' => $session->all()
       );
   }

  public function getFilters()  {
      return array(
          'getservertimezone'  => new \Twig_Filter_Method($this, 'getServerTimeZone'),
      );
  }

  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('render_menu',
        array($this, 'render_menu'),
        array('is_safe' => array('html'))
      ),
      new \Twig_SimpleFunction('session_var',
        array($this, 'session_var'),
        array('is_safe' => array('html'))
      )
    );
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName() {
    return 'rainbird_twig_extension';
  }

  public function session_var($key) {
    $session = new Session();
    return $session->get($key);
  }

  public function getServerTimeZone()   {

       if (date_default_timezone_get()) {
           return date_default_timezone_get();
       } else if (ini_get('date.timezone')) {
           return ini_get('date.timezone');
       } else {
           return false;
       }
   }

  /**
     * Provides function to programmatically rendering a menu
     *
     * @param String $menu_name
     *   The machine configuration id of the menu to render
     */
    public function render_menu($menu_name) {
      $menu_tree = \Drupal::menuTree();

      // Build the typical default set of menu tree parameters.
      $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

      // Load the tree based on this set of parameters.
      $tree = $menu_tree->load($menu_name, $parameters);

      // Transform the tree using the manipulators you want.
      $manipulators = array(
        // Only show links that are accessible for the current user.
        array('callable' => 'menu.default_tree_manipulators:checkAccess'),
        // Use the default sorting of menu links.
        array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      );
      $tree = $menu_tree->transform($tree, $manipulators);

      // Finally, build a renderable array from the transformed tree.
      $menu = $menu_tree->build($tree);

      return  array('#markup' => drupal_render($menu));
    }

}

```

or module hook:

```
function rainbird_theme_preprocess_block__personaselector(&$variables){
  $session = new \Symfony\Component\HttpFoundation\Session\Session();
  $variables['mypersona'] = $session->get('mypersona');
  // kint($variables); die(); - THIS ONLY HAPPENS WITH CLEAR CACHE
}

```

and my module's services.yml

```
services:
  rainbird.rainbirdsubscriber:
    class: Drupal\rainbird\EventSubscriber\RainbirdSubscriber
    tags:
      - {name: event_subscriber}
  rainbird.twig_extension:
    class: Drupal\rainbird\RainbirdTwigExtension
    public: false
    tags:
      - { name: twig.extension }

```

and my sites/default/services.yml

```
parameters:
  session.storage.options:
    gc_probability: 1
    gc_divisor: 100
    gc_maxlifetime: 200000
agents,
  twig.config:
    debug: true
    auto_reload: true
    cache: false
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']
    auto_placeholder_conditions:
      max-age: 0
      contexts: ['session', 'user']
      tags: []
  http.response.debug_cacheability_headers: false
  factory.keyvalue:
    {}
  factory.keyvalue.expirable:
    {}
  filter_protocols:
    - http
    - https
    - ftp
    - news
    - nntp
    - tel
    - telnet
    - mailto
    - irc
    - ssh
    - sftp
    - webcal
    - rtsp
  cors.config:
    enabled: false
    allowedHeaders: []
    allowedMethods: []
    allowedOrigins: ['*']
    exposedHeaders: false
    maxAge: false
    supportsCredentials: false

```

i've tried all of these in `block--myblock.html.twig`:

```
RESET1: {{ app.session.mypersona }}
RESET2: {{ session_var('mypersona') }}
RESET3: {{ app.session.get('mypersona') }}
RESET4: {{ mypersona }}
RESET5: {{ session.get('mypersona') }}
RESET6: {{ session.mypersona }}
RESET7: {{ session.get('mypersona') }}
RESET8: {{ dump(session) }}
RESET9: {{ dump(app) }}

```

yet NOTHING updates `myperson` after the template is cached by twig/symfony/drupal. ?

I've disabled: `devel`, `twig_tweak` and `settings.local.php`.

WTF am i doing wrong?

# Answer
If you put new data in a block you also need the cache metadata for this:

```
function rainbird_theme_preprocess_block__personaselector(&$variables){
  $session = new \Symfony\Component\HttpFoundation\Session\Session();
  $variables['mypersona'] = $session->get('mypersona');
  $variables['#cache']['contexts'][] = 'session';
}

```
> 1 votes

# Answer
Try to disable Twig cache from **services.yml** inside `docroot/sites/default` directory as

```
# Twig auto-reload:
#
# Automatically recompile Twig templates whenever the source code changes.
# If you don't provide a value for auto_reload, it will be determined
# based on the value of debug.
#
# Not recommended in production environments
# @default null
auto_reload: true

```

**Or,**

```
# Twig cache:
#
# By default, Twig templates will be compiled and stored in the filesystem
# to increase performance. Disabling the Twig cache will recompile the
# templates from source each time they are used. In most cases the
# auto_reload setting above should be enabled rather than disabling the
# Twig cache.
#
# Not recommended in production environments
# @default true
cache: false

```

**Note:** auto\_reload setting above should be enabled rather than disabling the Twig cache.
> 0 votes

---
Tags: theming, 8, sessions
---


# Question
Title: Print out recaptcha webform verification
I created a webform-form-230.tpl to readjust the webfrom layout.

```
<div class="one_half">
    <?php print drupal_render($form['submitted']['name']); ?>
    <?php print drupal_render($form['submitted']['e_mail']); ?>
    <?php print drupal_render($form['submitted']['subject']); ?>
    <?php print drupal_render($form['submitted']['date']); ?>
</div>
<div class="one_half last">
    <?php print drupal_render($form['submitted']['message']); ?>
</div>
<div class="clearfix"></div>
<?php print drupal_render($form['submitted']); ?>
<?php print drupal_render_children($form); ?>

```

I added recaptcha module. How do I add recaptcha script in it?

# Answer
> 1 votes
You can use this code for adding in temlate.php or in custom module for adding captcha.

```
if (strstr($form_id, 'webform_form_id')) {
        $form['my_captcha_element'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'image_captcha/Image',
        );
    }

```

Also refer https://www.drupal.org/node/1254710 link.

One module is there you can check CAPTCHA Webform Bridge.
This is a simple module that automatically set (or unset) CAPTCHA challenges to webforms.

---
Tags: 7
---


# Question
Title: How do I debug "unexpected % in php_eval()"?
While testing with PHP 7 a site, which works fine with PHP 5.5, I get this error on some pages:

> *ParseError* : syntax error, unexpected '%' in `php_eval()` (line 7 of ..\modules\php\php.module(80) : eval()'d code).

I have no idea where to search that %. It could be in code, or a token in panels or anything. I already read comments in this similar question, but maybe someone got same bug while testing PHP 7.

# Answer
This error is from php code in a text field.

> Speaking of debugging, errors in eval()’d codes throw up error messages that don’t provide much help in identifying or locating the error. There’s a good chance you might have to go through your database manually to find and fix the error. Such errors might even be fatal in certain instances, for example, if the error is in a block that is displayed on all pages.

Source: http://valuebound.com/resources/blog/enabling-php-filter-in-drupal-7-core-what-can-go-wrong
> 1 votes

---
Tags: debugging
---


# Question
Title: How to block temporarily comments from specific IP address?
Can we block specific IP address for a period of time and block posting comments from that IP address for this period of time?
Only posting comments, not viewing pages.

# Answer
I have not used this module but you can check Comment IP module.

> This module displays a comments IP address in the comment overview page and allows you the option to "Delete the selected comments and block their IP's" from the comment overview dropdown list.
> 1 votes

---
Tags: 7, comments
---


# Question
Title: View main wrapper markup (div.view) not getting rendered though view content gets rendered
One of my view 'Stylist Analytics' has a **block** display - 'Sales' which is getting rendered in such a way that its **main wrapper markup** **(div.view)** is missing and simply view fields' markup gets rendered along with the pager though all other views work fine in this regard. So, this cannot be possibly a global view setting and has to be specific to this view. I am not sure but probably there is no such setting in a view to enable/disable rendering/appending of view main wrapper markup. I have tried using this view block in panel pane, quicktabs, mini-panel but they all exhibit the same view markup. I'm using Views v3.13 .

Here's the export of my view:

```
$view = new view();
$view->name = 'stylist_analytics';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'commerce_commission';
$view->human_name = 'Stylist analytics';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['disable_sql_rewrite'] = TRUE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Commerce commission: Order */
$handler->display->display_options['relationships']['order_id']['id'] = 'order_id';
$handler->display->display_options['relationships']['order_id']['table'] = 'commerce_commission';
$handler->display->display_options['relationships']['order_id']['field'] = 'order_id';
/* Field: COUNT(Commerce commission: Order) */
$handler->display->display_options['fields']['order_id']['id'] = 'order_id';
$handler->display->display_options['fields']['order_id']['table'] = 'commerce_commission';
$handler->display->display_options['fields']['order_id']['field'] = 'order_id';
$handler->display->display_options['fields']['order_id']['group_type'] = 'count';
$handler->display->display_options['fields']['order_id']['label'] = '';
$handler->display->display_options['fields']['order_id']['exclude'] = TRUE;
$handler->display->display_options['fields']['order_id']['element_label_colon'] = FALSE;
/* Field: SUM(Commerce commission: Commission amount) */
$handler->display->display_options['fields']['commission_amount']['id'] = 'commission_amount';
$handler->display->display_options['fields']['commission_amount']['table'] = 'commerce_commission';
$handler->display->display_options['fields']['commission_amount']['field'] = 'commission_amount';
$handler->display->display_options['fields']['commission_amount']['group_type'] = 'sum';
$handler->display->display_options['fields']['commission_amount']['label'] = '';
$handler->display->display_options['fields']['commission_amount']['exclude'] = TRUE;
$handler->display->display_options['fields']['commission_amount']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['commission_amount']['short_scale_check'] = TRUE;
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = '';
$handler->display->display_options['fields']['nothing']['alter']['text'] = '<div class="hns-merchant-analytics-info">
<div class="hns-merchant-analytics-number">[order_id]</div>
<div class="hns-merchant-analytics-text">Sales</div>
</div>
<div class="hns-merchant-analytics-info">
<div class="hns-merchant-analytics-number">[commission_amount]</div>
<div class="hns-merchant-analytics-text">Commission</div>
</div>';
$handler->display->display_options['fields']['nothing']['element_label_colon'] = FALSE;
/* Contextual filter: Commerce commission: User */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'commerce_commission';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Analytics */
$handler = $view->new_display('block', 'Analytics', 'block');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['default_field_elements'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;

/* Display: Sales */
$handler = $view->new_display('block', 'Sales', 'block_1');
$handler->display->display_options['defaults']['css_class'] = FALSE;
$handler->display->display_options['css_class'] = 'custom-class';
$handler->display->display_options['defaults']['use_ajax'] = FALSE;
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['defaults']['group_by'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['defaults']['query'] = FALSE;
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['disable_sql_rewrite'] = TRUE;
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'load_more';
$handler->display->display_options['pager']['options']['items_per_page'] = '3';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['pager']['options']['effects']['speed'] = 'slow';
$handler->display->display_options['defaults']['header'] = FALSE;
$handler->display->display_options['defaults']['empty'] = FALSE;
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['empty'] = TRUE;
$handler->display->display_options['empty']['area']['content'] = 'The products you endorsed haven\'t been purchased yet';
$handler->display->display_options['empty']['area']['format'] = 'full_html';
$handler->display->display_options['defaults']['relationships'] = FALSE;
/* Relationship: Commerce commission: Order */
$handler->display->display_options['relationships']['order_id']['id'] = 'order_id';
$handler->display->display_options['relationships']['order_id']['table'] = 'commerce_commission';
$handler->display->display_options['relationships']['order_id']['field'] = 'order_id';
/* Relationship: Commerce Order: Referenced line items */
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['id'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['table'] = 'field_data_commerce_line_items';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['field'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['relationships']['commerce_line_items_line_item_id']['relationship'] = 'order_id';
/* Relationship: Commerce commission: Product */
$handler->display->display_options['relationships']['product_id']['id'] = 'product_id';
$handler->display->display_options['relationships']['product_id']['table'] = 'commerce_commission';
$handler->display->display_options['relationships']['product_id']['field'] = 'product_id';
/* Relationship: Commerce commission: Product node */
$handler->display->display_options['relationships']['node_id']['id'] = 'node_id';
$handler->display->display_options['relationships']['node_id']['table'] = 'commerce_commission';
$handler->display->display_options['relationships']['node_id']['field'] = 'node_id';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Path */
$handler->display->display_options['fields']['path']['id'] = 'path';
$handler->display->display_options['fields']['path']['table'] = 'node';
$handler->display->display_options['fields']['path']['field'] = 'path';
$handler->display->display_options['fields']['path']['relationship'] = 'node_id';
$handler->display->display_options['fields']['path']['label'] = '';
$handler->display->display_options['fields']['path']['exclude'] = TRUE;
$handler->display->display_options['fields']['path']['element_label_colon'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'node_id';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['exclude'] = TRUE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Field: Designer */
$handler->display->display_options['fields']['field_designer']['id'] = 'field_designer';
$handler->display->display_options['fields']['field_designer']['table'] = 'field_data_field_designer';
$handler->display->display_options['fields']['field_designer']['field'] = 'field_designer';
$handler->display->display_options['fields']['field_designer']['relationship'] = 'node_id';
$handler->display->display_options['fields']['field_designer']['ui_name'] = 'Designer';
$handler->display->display_options['fields']['field_designer']['label'] = '';
$handler->display->display_options['fields']['field_designer']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_designer']['element_type'] = '0';
$handler->display->display_options['fields']['field_designer']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_designer']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['field_designer']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_designer']['settings'] = array(
  'link' => 0,
);
$handler->display->display_options['fields']['field_designer']['field_api_classes'] = TRUE;
/* Field: Commerce Product: Images */
$handler->display->display_options['fields']['field_product_images']['id'] = 'field_product_images';
$handler->display->display_options['fields']['field_product_images']['table'] = 'field_data_field_product_images';
$handler->display->display_options['fields']['field_product_images']['field'] = 'field_product_images';
$handler->display->display_options['fields']['field_product_images']['relationship'] = 'product_id';
$handler->display->display_options['fields']['field_product_images']['label'] = '';
$handler->display->display_options['fields']['field_product_images']['exclude'] = TRUE;
$handler->display->display_options['fields']['field_product_images']['element_type'] = '0';
$handler->display->display_options['fields']['field_product_images']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_product_images']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['field_product_images']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_product_images']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_product_images']['settings'] = array(
  'image_style' => 'line_image_medium',
  'image_link' => '',
);
$handler->display->display_options['fields']['field_product_images']['group_column'] = 'entity_id';
$handler->display->display_options['fields']['field_product_images']['delta_limit'] = '1';
$handler->display->display_options['fields']['field_product_images']['delta_offset'] = '0';
$handler->display->display_options['fields']['field_product_images']['field_api_classes'] = TRUE;
/* Field: Commerce Product: SKU */
$handler->display->display_options['fields']['sku']['id'] = 'sku';
$handler->display->display_options['fields']['sku']['table'] = 'commerce_product';
$handler->display->display_options['fields']['sku']['field'] = 'sku';
$handler->display->display_options['fields']['sku']['relationship'] = 'product_id';
$handler->display->display_options['fields']['sku']['label'] = '';
$handler->display->display_options['fields']['sku']['exclude'] = TRUE;
$handler->display->display_options['fields']['sku']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['sku']['link_to_product'] = 0;
/* Field: Commerce Product: Price */
$handler->display->display_options['fields']['commerce_price']['id'] = 'commerce_price';
$handler->display->display_options['fields']['commerce_price']['table'] = 'field_data_commerce_price';
$handler->display->display_options['fields']['commerce_price']['field'] = 'commerce_price';
$handler->display->display_options['fields']['commerce_price']['relationship'] = 'product_id';
$handler->display->display_options['fields']['commerce_price']['label'] = '';
$handler->display->display_options['fields']['commerce_price']['exclude'] = TRUE;
$handler->display->display_options['fields']['commerce_price']['element_type'] = '0';
$handler->display->display_options['fields']['commerce_price']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['commerce_price']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['commerce_price']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['commerce_price']['click_sort_column'] = 'amount';
$handler->display->display_options['fields']['commerce_price']['settings'] = array(
  'calculation' => '0',
);
$handler->display->display_options['fields']['commerce_price']['group_column'] = 'entity_id';
$handler->display->display_options['fields']['commerce_price']['field_api_classes'] = TRUE;
/* Field: Commerce commission: Date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'commerce_commission';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = '';
$handler->display->display_options['fields']['created']['exclude'] = TRUE;
$handler->display->display_options['fields']['created']['alter']['alter_text'] = TRUE;
$handler->display->display_options['fields']['created']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created']['date_format'] = 'medium';
$handler->display->display_options['fields']['created']['second_date_format'] = 'search_api_facetapi_YEAR';
/* Field: Commission amount */
$handler->display->display_options['fields']['commission_amount']['id'] = 'commission_amount';
$handler->display->display_options['fields']['commission_amount']['table'] = 'commerce_commission';
$handler->display->display_options['fields']['commission_amount']['field'] = 'commission_amount';
$handler->display->display_options['fields']['commission_amount']['ui_name'] = 'Commission amount';
$handler->display->display_options['fields']['commission_amount']['label'] = '';
$handler->display->display_options['fields']['commission_amount']['exclude'] = TRUE;
$handler->display->display_options['fields']['commission_amount']['element_label_colon'] = FALSE;
/* Field: Global: Custom text */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = '';
$handler->display->display_options['fields']['nothing']['alter']['text'] = '  <div class=\'order-image\'>
    <a href="[path]">[field_product_images]</a>
  </div>
  <div class=\'order-info\'>
    <div class=\'order-item-brand\'>[field_designer]</div>
    <div class=\'order-item-title\'><a href="[path]">[title]</a></div>
    <div class=\'order-item-total\'>[commerce_price]</div>
  </div>
  <div class=\'order-other-info\'>
    <div class=\'order-item-date\'>[created]</div>
    <div class=\'order-item-sku\'>[sku]</div>
  </div>
  <div class=\'order-link\'>
    <div class=\'commission-sale-item-info-right-commission\'>[commission_amount]</div>
  </div>';
$handler->display->display_options['fields']['nothing']['element_type'] = 'div';
$handler->display->display_options['fields']['nothing']['element_label_colon'] = FALSE;
$handler->display->display_options['defaults']['sorts'] = FALSE;
/* Sort criterion: Commerce Order: Line items (commerce_line_items) */
$handler->display->display_options['sorts']['commerce_line_items_line_item_id']['id'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['sorts']['commerce_line_items_line_item_id']['table'] = 'field_data_commerce_line_items';
$handler->display->display_options['sorts']['commerce_line_items_line_item_id']['field'] = 'commerce_line_items_line_item_id';
$handler->display->display_options['sorts']['commerce_line_items_line_item_id']['relationship'] = 'order_id';
$handler->display->display_options['sorts']['commerce_line_items_line_item_id']['order'] = 'DESC';
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;

```

Here is the markup that gets rendered:

```
<div id="quicktabs-tabpage-quicktabs_stylist_commission-1" class="quicktabs-tabpage"><div id="block-views-stylist-analytics-block-1" class="block block-views">

  <div class="content">

  <div class="views-field views-field-nothing">        <div class="field-content">  <div class="order-image">
  <a href="/watchjewelry/9-carat-gold-acorn-cufflinks"><div class="field field-name-field-product-images field-type-image field-label-hidden"><div class="field-items"><div class="field-item even"><img src="https://honeandstrop.qed42.webfactional.com/sites/default/files/styles/line_image_medium/public/product_images/image.jpg?itok=V1SmL8lc" width="180" height="150"></div></div></div></a>
</div>
<div class="order-info">
  <div class="order-item-brand"><div class="field field-name-field-designer field-type-entityreference field-label-hidden"><div class="field-items"><div class="field-item even">Emma Willis</div></div></div></div>
  <div class="order-item-title"><a href="/watchjewelry/9-carat-gold-acorn-cufflinks"></a><a href="/watchjewelry/9-carat-gold-acorn-cufflinks">9 Carat Gold Acorn Cufflinks</a></div>
  <div class="order-item-total"><div class="field field-name-commerce-price field-type-commerce-price field-label-hidden"><div class="field-items"><div class="field-item even">$2,000.00</div></div></div></div>
</div>
<div class="order-other-info">
  <div class="order-item-date">14/10/2016 22:49</div>
  <div class="order-item-sku">EM00011</div>
</div>
<div class="order-link">
  <div class="commission-sale-item-info-right-commission">$0.50</div>
</div></div>  </div>
<div class="views-field views-field-nothing">        <div class="field-content">  <div class="order-image">
  <a href="/accessories/tie"><div class="field field-name-field-product-images field-type-image field-label-hidden"><div class="field-items"><div class="field-item even"><img src="https://honeandstrop.qed42.webfactional.com/sites/default/files/styles/line_image_medium/public/blackbird-black-ties.jpg?itok=Z0pAGlZE" width="180" height="150"></div></div></div></a>
</div>
<div class="order-info">
  <div class="order-item-brand"><div class="field field-name-field-designer field-type-entityreference field-label-hidden"><div class="field-items"><div class="field-item even">Audemars Piguet</div></div></div></div>
  <div class="order-item-title"><a href="/accessories/tie"></a><a href="/accessories/tie">Tie</a></div>
  <div class="order-item-total"><div class="field field-name-commerce-price field-type-commerce-price field-label-hidden"><div class="field-items"><div class="field-item even">$50.00</div></div></div></div>
</div>
<div class="order-other-info">
  <div class="order-item-date">07/10/2016 04:22</div>
  <div class="order-item-sku">Test Tie</div>
</div>
<div class="order-link">
  <div class="commission-sale-item-info-right-commission">$5.00</div>
</div></div>  </div>
<div class="views-field views-field-nothing">        <div class="field-content">  <div class="order-image">
  <a href="/apparel/black-tuxedo"><div class="field field-name-field-product-images field-type-image field-label-hidden"><div class="field-items"><div class="field-item even"><img src="https://honeandstrop.qed42.webfactional.com/sites/default/files/styles/line_image_medium/public/BC27.jpg?itok=34eriI_m" width="180" height="150" alt="BLACK TUXEDO" title="BLACK TUXEDO"></div></div></div></a>
</div>
<div class="order-info">
  <div class="order-item-brand"><div class="field field-name-field-designer field-type-entityreference field-label-hidden"><div class="field-items"><div class="field-item even">KITON</div></div></div></div>
  <div class="order-item-title"><a href="/apparel/black-tuxedo"></a><a href="/apparel/black-tuxedo">BLACK TUXEDO</a></div>
  <div class="order-item-total"><div class="field field-name-commerce-price field-type-commerce-price field-label-hidden"><div class="field-items"><div class="field-item even">$8,500.00</div></div></div></div>
</div>
<div class="order-other-info">
  <div class="order-item-date">26/09/2016 10:00</div>
  <div class="order-item-sku">kt98008</div>
</div>
<div class="order-link">
  <div class="commission-sale-item-info-right-commission">$850.00</div>
</div></div>  </div>
<div class="item-list"><ul class="pager pager-load-more"><li class="pager-next first last"><a href="/user/455/analytics?page=2">Load more</a></li>
</ul></div>
</div>
</div>
</div>

```

# Answer
After looking into view theming information, I actually found a template overriding the Display Output and the main wrapper div was missing over there.
> 0 votes

---
Tags: 7, views, panels
---


# Question
Title: How to resolve error "Failed to load MailChimp PHP library. Please refer to the installation requirements."?
I'm try to set up Mailchimp module but i keep geeting Failed to load MailChimp PHP library. Please refer to the installation requirements.

My steps:

* disable mailchimp module
* install composer\_manager package locally
* run: curl -sS https://getcomposer.org/installer | php on my root
* change composer.json(which lay on my root) - see it below
* run: php composer.phar install --no-dev
* mailchimp/mailchimp directory is installed in my /vendor folder
* clear cache, re=enable module but still getting the error. In my report i see that the module cannot be found.

What i'm doing wrong??

```
{
    "name": "drupal/composer_manager",
    "type": "drupal-module",
    "description": "Composer Manager is a bridge to best-in-breed, standards compliant PHP libraries that are managed by Composer and Packagist.",
    "homepage": "http://drupal.org/project/composer_manager",
    "license": "GPL-2.0",
    "authors": [
        {
            "name": "Chris Pliakas",
            "email": "opensource@chrispliakas.com",
            "role": "Project Lead"
        },
        {
            "name": "See contributors",
            "homepage": "http://drupal.org/node/1929436/committers",
            "role": "Developer"
        }
    ],
    "support": {
        "issues": "http://drupal.org/project/issues/composer_manager"
    },
    "require": {
        "php": ">=5.3.0",
        "mailchimp/mailchimp": ">=2.0.4"
    }
}

```

MailChimp module =\> 7x.3-3

mailchimp library =\> 2.04

# Answer
Here are some steps to troubleshoot this error according to this thread: Issue #2054037 Failed to load MailChimp PHP library. Please refer to the installation requirements. (provided by @rtome, above)

* Re-read the instructions in MailChimp module's README.txt
* Clear the cache
* Ensure Libraries module is installed and is working properly
* Ensure Mailchimp library is located at *sites/all/libraries/mailchimp*
* Check your versions:

> MailChimp module 7.x-2.x requires MailChimp library 1.3
> MailChimp module \> 7.x-3.x requires MailChimp library 2.04

* If MailChimp library updated, reinstall MailChimp module
> 1 votes

# Answer
The mailchimp module 7.x-2.x and 7.x-3.x branches rely on MailChimp’s API version 2.0 and has became unsupported by MailChimp at the end of the year 2016.To upgrade to the latest version, please go through with the following link http://cgit.drupalcode.org/mailchimp/tree/README.txt.
> 0 votes

---
Tags: emails, composer
---


# Question
Title: "Fatal error: Cannot use string offset as an array in theme.inc"
i am adding custom modules in drupal 7. while creating a custom table i got the error like this "Fatal error: Cannot use string offset as an array in /srv/bindings/code/includes/theme.inc on line 2002"

```
            $form = array();
            $headers = array(t('Teacher Name'), t('Paypal Id '),  t('Status'), t('Action'));
            $query = "SELECT * FROM `users_roles` ur JOIN `users` u ON u.uid=ur.uid WHERE rid=4";
            $rs = db_query($query);
            $row = array();
            if ($rs) {
                  foreach($rs as $data) {
                    $name = $data->name;
                    $mail = $data->mail;
                    $status = $data->status ;
                    $row[] = array(stripslashes(ucwords($data->name)), $mail, $status,
                    "<a href='#'>" . t('Pay Now') . "</a>  " );
                }}
                echo "<pre>";
                print_r($headers);
                print_r($row);
            return theme_table('table', array('header' => $headers, 'rows' => $row));

```

I dont know where i done mistake. Please give some ideas.

# Answer
You're calling `theme_table` directly instead of `theme`, but still passing the name in.

Use this instead:

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

```

Or even better (depending on context), a render array.
> 1 votes

# Answer
```
        $form = array();
        $headers = array(t('Teacher Name'), t('Paypal Id '),  t('Status'), t('Action'));
        $query = "SELECT * FROM `users_roles` ur JOIN `users` u ON u.uid=ur.uid WHERE rid=4";
        $rs = db_query($query);
        $row = array();
        if ($rs) {
              $result = $rs->fetchAll();
              foreach($result as $data) {
                $name = $data->name;
                $mail = $data->mail;
                $status = $data->status ;
                $row[] = array(stripslashes(ucwords($data->name)), $mail, $status,
                "<a href='#'>" . t('Pay Now') . "</a>  " );
            }}
            echo "<pre>";
            print_r($headers);
            print_r($row);
        return theme_table('table', array('header' => $headers, 'rows' => $row));

```

Now, it will work correctly for you.
> 0 votes

# Answer
You don't report exactly which line is causing the error, but if it is between the lines you shown, then the line causing the error is the following one.

```
return theme_table('table', array('header' => $headers, 'rows' => $row));

```

It happens because `theme_table()`, as any other theme function, is expecting an array as first argument, not a string.

The correct line would be the following one.

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

```

Keep in mind that on Drupal you never directly call a theme function like `theme_table()` because the theme function for generating a table could not be that. In fact, modules can change the theme function called from theme() by implementing `hook_theme_registry_alter()`.

Then, in Drupal 7 is possibile to return a render array, instead of a string. Instead of `return theme_table('table', array('header' => $headers, 'rows' => $row));` you can use `return array('#theme' => 'table', '#header' => $headers, '#rows' => $row);` in most of the cases.
> 0 votes

---
Tags: theming
---


title: Help with dynamic page cache

text:
# Question
Title: Help with dynamic page cache
I have a page generated by a custom module that contains two sections:

* Product info
* Recently viewed products

The product info only changes when the product is updated.

Recently viewed products are unique to every visitor (data is stored in `$_SESSION`).

Each section has its own render array.

```
'productinfo' => [
    // ...
    '#cache' => [
        'tags' => ['product:1234']
    ]
],
'recentlyviewed' => [
    // ...
    '#lazy_builder' => array(
      // ....
    ),
    '#create_placeholder' => TRUE,
    '#cache' => [
        'max-age' => 0
    ]
]

```

The behaviour I expect is that the dynamic page cache can cache the `productinfo` section, but the recentlyviewed would never be cached. However, if a session has not yet been started (i.e. first page view), the *entire* html page is cached to the `cache_render` DB table, and `cache_dynamic_page_cache` is always empty.

The `X-Drupal-Dynamic-Cache` header is always set to `UNCACHABLE`.

How can I get the dynamic page cache to cache the product info section?

# Answer
> 3 votes
Your question has two different topics:

> 1. How can I get the dynamic page cache to cache the product info section?

Set cache keys:

```
'productinfo' => [
    // ...
    '#cache' => [
        'keys' => ['mymodule', 'product', '1234'],
        'tags' => ['product:1234'],
    ],
],

```

Sections of a render array are only cached, if they have cache keys. The keys are used to build the unique cid for the cache render table.

> 2. However, if a session has not yet been started (i.e. first page view), the entire html page is cached

Anonymous traffic is cached by the *Internal Page Cache*. If you start a session, the next request will be able to pass the *Internal Page Cache* and is handled by the *Dynamic Page Cache*.

---
Tags: 8, caching
---


# Question
Title: Need help optimizing a site for speed and response time
In my Drupal 6 site (fairly busy about 200 anonymous users on average at at time) I have the following setup to speed up the site.

* Caching Mode - normal
* Optimize JavaScript files
* Gzip enabled via .htaccess
* Cloudflare - normal setting
* Disabled database logging

Can I add memcached or Varnish into this setup? Which one will work better for this site? Should I even care about Varnish and memcached in this setup?

# Answer
> 2 votes
You can use both as per my knowledge.

For Drupal generally, Varnish works for unauthenticated users traffic and memcached will cache authenticated users traffic.

Memcache saves your DB from doing a lot of read work, Varnish saves your dynamic web server from CPU load by making you generate pages less frequently.

But in your case I think Varnish is better option.

---
Tags: 6, proxies, caching
---


# Question
Title: How do I prevent D7's ajax_deliver() from loading CSS?
For some crazy reason, using ajax\_deliver() in a menu callback is causing 4 theme CSS files to be loaded into my page, breaking the page styles.

What I'm doing:

* Using Seven as my admin theme
* Created a basic admin page for a module
* Admin page has a link (no form) which should return content via AJAX
* Link points to a menu path which uses a custom callback
* Custom callback uses the /nojs trick and returns content via ajax\_deliver()

What's happening:

* AJAX content is loading into the page just fine, working as expected
* **4 *Bartik* CSS files are being dynamically added to my admin page** (using Seven theme)

Anyone experienced this? Any ideas on how I can prevent this CSS from loading?

# Answer
> 3 votes
Just to answer your question of how to do this.

ajax\_render() calls `drupal_alter('css')` which would allow you to create a `hook_css_alter()` in your code.

This could check the delivery method (or check for ajax in the path) and remove style sheets if you wanted to.

Most of the time you won't want to do this as they will be needed for the returned markup but it is possible that you would want to tweak it.

# Answer
> 4 votes
Figured out the reason Bartik CSS was loading when the admin page was using Seven.

My admin page was located at /admin/mymodule/settings

My menu callback for the AJAX link was /mymodule/special-form

Because /mymodule is outside the admin area, the theme *would* be Bartik when actually visiting that page. So Drupal's AJAX system assumes I want the CSS that goes along with that page. Not a bug, but a feature to be aware of.

# Answer
> 4 votes
The correct drupal way is to use ajax\_base\_page\_theme in hook\_menu theme callback. as explained in http://api.drupal.org/api/drupal/includes!ajax.inc/function/ajax\_base\_page\_theme/7

or you can force ajax to use admin theme by altering its Drupal.settings.ajaxPageState

something like :

```
  <?php
  // Force ajax to use admin theme
  $admin_theme = variable_get('admin_theme', '0');
  $settings = array(
    'ajaxPageState' => array(
        'theme' => $admin_theme,
      'theme_token' => drupal_get_token($admin_theme),
    ),
  );
  drupal_add_js($settings, 'setting');
  ?>

```

# Answer
> 2 votes
A very handy work around that I used for this was to implement hook\_admin\_paths() to define the ajax path as an admin path. For example, I had an issue where hierarchical\_select on admin pages (i.e node edit) was loading the entire front end theme's css into the page causing all sorts of issues. The fix was simply this:

```
/**
 * Implements hook_admin_paths().
 */
function my_module_admin_paths() {
  $paths = array(
    'hierarchical_select_ajax/*' => TRUE,
  );
  return $paths;
}

```

# Answer
> 1 votes
Following Jason's recommendation I came to use ajax\_base\_page\_theme() I came to this simplified solution as mentioned on https://api.drupal.org/api/drupal/includes!ajax.inc/function/ajax\_base\_page\_theme/7.x

All code is written into custom.module

```
/**
 * Implements hook_menu().
 *
 * Provide an AJAX menu callback.
 */
function custom_menu() {

  $items['custom/ajax/%'] = array(
    'page callback' => 'custom_ajax_response',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
    // Use the current page's theme instead of always the admin theme:
    'theme callback' => 'ajax_base_page_theme',
  );

  return $items;
}

/**
 * AJAX response callback.
 *
 * Writes "foo replacement" into <div id="ajax-placeholder"></div>
 */
function custom_ajax_response($argument) {
  $output = 'foo replacement';
  $dom_id = '#ajax-placeholder';
  $commands = array('effect' => 'slide', ajax_command_replace($dom_id, $output));
  return ajax_deliver(array('#type' => 'ajax', '#commands' => $commands));
}

```

---
Tags: 7, ajax
---


# Question
Title: Why could Drush not find the alias @local?
I am usin Drupal 8 and Drush 8. I have ~/.drush/local.aliases.drushrc.php. That is the only alias under ~/.drush

Inside local.aliases.drushrc.php, I have

```
$aliases['local'] = array(
  'root' => '/var/www/html/test/testme/amber/amber_school_dev',
  'uri' => 'http://amber_school_dev.local',
);

```

Run this `drush @local status --debug`

```
Using the Drush script found at /home/kenpeter/.composer/vendor/drush/drush/drush.launcher using pcntl_exec
Cache HIT cid: 8.1.8-commandfiles-0-88373346a2ca94c0c49a48b75b15bd40 [0.02 sec, 3.23 MB]                                                [debug]
$aliases['local'] = array(
  'root' => '/var/www/html/test/testme/amber/amber_school_dev',
  'uri' => 'http://amber_school_dev.local',
);

$aliases['local'] = array(
  'root' => '/var/www/html/test/testme/amber/amber_school_dev',
  'uri' => 'http://amber_school_dev.local',
);

$aliases['local'] = array(
  'root' => '/var/www/html/test/testme/amber/amber_school_dev',
  'uri' => 'http://amber_school_dev.local',
);

Could not find the alias @local [0.06 sec, 6.05 MB]                                                                                [error]
Undefined index: command notify.drush.inc:60 [0.06 sec, 6.06 MB]                                                                       [notice]
Undefined index: command notify.drush.inc:60 [0.06 sec, 6.06 MB]                                                                       [notice]

```

`drush sa` in site root gives me

```
@none
@self
default

```

# Answer
> 7 votes
You are missing the `<?php` at the beginning of your aliases file. That's why the contents of your file are printing out when Drush tries to load them.

# Answer
> 1 votes
The aliases are recognized by Drush using the file names prefixed with the alias name.

You could try `drush @local.local status --debug`

First `local` from `@local.local` is the comes from the file name `local.aliases.drushrc.php`, and the second is the key of the `$aliases` array from the file.

To see a list of all the aliases present on the system, you would use `drush sa`.

---
Tags: 8, drush
---


# Question
Title: How to bulk re-index the whole site for core search?
I have a website that has about 100,000 nodes.

In the core search page (`admin/config/search/settings`) it shows that:

> **There are 80801 items left to index.**

It index 100 (or at most 500) nodes per cron run but it's useless.

I want to bulk index the whole site (all nodes) for **core** search.

## How can I do that?

The Reindex and Batch indexing modules are created for this but there are only a few users use these modules and I couldn't be sure to use them. And also there is a module called Elysia Cron for modifying the cron per job but it's still useless for me because there are thousands of nodes to index.

*(Note: I want to do this for core search not for other search solutions).*

# Answer
You can use the following drush command.

```
drush search-reindex --immediate --verbose

```
> 1 votes

---
Tags: search
---


# Question
Title: No Emails sent on User Creation in D8 through Rest API
I'm working in Drupal 8.2.4 currently and building a headless webapp using Rest Web Services module for the endpoints I need. I'm using the endpoint `/entity/user` to create users, however the default welcome emails are not getting sent out by Drupal when I create the users.

I do have the emails set up to be sent properly and I know this because if I create a user like normal in Drupal with "Notify user of new account" checked, it does send the email. Is there some simple way that I am just missing to get this to work?

I have also tried using `hook_ENTITY_TYPE_insert` using `_user_mail_notify` to trigger the email to be sent, however this is not working either for what I want. My code is as follows:

`/**
 * Implements hook_ENTITY_TYPE_insert().
 * When a new user is created, do things.
 */
function custom_rules_user_insert(Drupal\Core\Entity\EntityInterface $entity)
{
 _user_mail_notify('register_no_approval_required', $entity);
}`

Am I doing something wrong, is there a simple way to get this to work or does this just not work at all yet in Drupal 8? I will also need to set up Pass Reset emails, so any feedback would be appreciated.

# Answer
I've tested this and it seems like `_user_mail_notify` just isn't working currently in 8.2.4, however I did find a workaround using the `hook_ENTITY_TYPE_insert()` still, but using `hook_mail` and `MailManager` also.

```
/**
 * Implements hook_mail().
 */
function custom_rules_mail($key, &$message, $params) {
$options = array(
    'langcode' => $message['langcode'],
);
 switch ($key) {

   case 'create_user':
     $message['from'] = \Drupal::config('system.site')->get('mail');
     $message['subject'] = t('Welcome to the site!', $options);
     $message['body'][] = $params['message'];
     break;
 }
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 * When a new user is created, do things.
 */
function custom_rules_user_insert(Drupal\Core\Entity\EntityInterface $entity)
{
  global $user;

//  _user_mail_notify('register_no_approval_required', $entity);

  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'custom_rules';
  $key = 'create_user';
  $to = $entity->getEmail();
  $params['message'] = "Welcome to our site! \r\nYour username is " . $entity->getUsername() . " " . "\r\nIf you would like to reset your password, you can at the following link: \r\n" . user_pass_reset_url($entity);
  $langcode = $entity->getPreferredLangcode();
  $send = true;

  $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
  if ($result['result'] !== true) {
    drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
  }
  else {
    drupal_set_message(t('Your message has been sent.'));
  }

}

```

The way I have this set up works. When a user is created (through drupal GUI or REST API), they are sent a welcome email that also includes a link to reset their password. To do this, you use the `user_pass_reset_url` function that is defined here. MailManager was pretty simple to use and figure out.

I followed this blog to figure out how to do this.
> 1 votes

---
Tags: users, hooks, emails, 8
---


# Question
Title: Preprocess Node function not being called
I'm attempting to perform an action in a preprocess node hook inside my .theme file, but I can't seem to get it to fire.

Here's the content of my customtheme.theme file

```
<?php

function mytheme_preprocess_page(&$variables){

    $menu = \Drupal\block\Entity\Block::load('custom_main_menu');

    $variables['main_menu'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($menu);
}

function mytheme_preprocess_node(&$variables){
    die('Test');
}

```

Everytime I load a node, even though I have a die() statement in my mytheme\_preprocess\_node function it never fires, and the page loads just fine. I'm making sure that I'm loading pages that are nodes. Such as basic pages, and other custom content types. What's odd is that the mytheme\_preprocess\_page function does fire. It's able to load the main\_menu variable inside the page.html.twig template just fine. I also made sure I was clearing the cache.

Why would a preprocess\_page hook function fire but not a preprocess\_node function.

# Answer
> 1 votes
You need check your page url. Hook\_preprocess\_node only run with page is node (example node/1...) or page have content is node (example page views have entity is node). If you done, you need clear cache.

---
Tags: theming, 8, blocks
---


title: How to make this entity fieldable?

text:
# Question
Title: How to make this entity fieldable?
I want to make my entity fieldable and manageable from admin area with manage display and manage field admin ui. I have read few tutorials, but I still not understand how to do it? This question is related to my other question. Here is my entity code.

```
function statuses_entity_info() {
  $backupControl = module_exists('entity') ? 'EntityAPIController' : 'DrupalDefaultEntityController';
  return array(
    'status' => array(
      'label' => t('Status'),
      'plural label' => t('Statuses'),
      'description' => t('A status update.'),
      'entity class' => 'StatusEntity',
      'controller class' => module_exists('statuses') ? 'StatusesEntityController' : $backupControl,
      'base table' => 'statuses',
      'load hook' => 'statuses_load',
      'uri callback' => 'statuses_uri',
      'module' => 'statuses',
      'entity keys' => array(
        'id' => 'sid',
        'label' => 'message',
      ),
       'bundles' => array(
        'status' => array(
          'label' => t('Status'),
        ),
      ),
      'view modes' => array(
        'full' => array(
          'label' => t('Status message'),
          'custom settings' => FALSE,
        ),
      ),
      'entity cache' => FALSE,
    ),
  );
}

function statuses_entity_property_info()  {
  $info = array();

  $info['status']['properties']['sid'] = array(
    'label' => t('Status ID'),
    'description' => t('The ID of the status'),
    'type' => 'integer',
    'schema field' => 'sid',
  );

  $info['status']['properties']['sender'] = array(
    'label' => t('Status sender'),
    'description' => t('Sender uid of the status message'),
    'type' => 'integer',
    'schema field' => 'sender',
  );
  $info['status']['properties']['recipient'] = array(
    'label' => t('Status recipient'),
    'description' => t('Recipient uid of the status message'),
    'type' => 'integer',
    'schema field' => 'recipient',
  );
  $info['status']['properties']['type'] = array(
    'label' => t('Type'),
    'description' => t('Type of status message'),
    'type' => 'text',
    'schema field' => 'type',
  );
  $info['status']['properties']['created'] = array(
    'label' => t('Created'),
    'description' => t('UNIX Timestamp of creation date'),
    'type' => 'integer',
    'schema field' => 'created',
  );
  $info['status']['properties']['message'] = array(
    'label' => t('Message'),
    'description' => t('Status message'),
    'type' => 'text',
    'schema field' => 'message',
  );
  return $info;
}

function statuses_uri($status)  {
  return array(
    'path' => 'statuses/' . $status->sid,
  );
}

class StatusesEntityController extends EntityAPIController  {
//TODO
}

if (class_exists('Entity')) {
  class StatusEntity extends Entity {
    public function __construct(array $values = array(), $entityType = NULL)  {
      parent::__construct($values, 'status');
    }

    public function buildContent($view_mode = 'full', $langcode = NULL) {
      $content['sender'] = array(
      '#markup' => 'Sender Markup TEST',
      );
      $content['recipient'] = array(
        '#markup' => 'Recipient Markup TEST',
      );
      $content['created'] = array(
        '#markup' => 'Created Markup TEST',
      );
      $content['message'] = array(
        '#markup' => 'Message Markup TEST',
      );
      $content['sid'] = array(
        '#markup' => 'sid Markup TEST',
      );
      $content['type'] = array(
        '#markup' => 'type Markup TEST',
      );
      return entity_get_controller($this->entityType)->buildContent($this, $view_mode, $langcode, $content);

    }
  }
}

```

# Answer
Just add the `fieldable` key and set it to true:

```
return array(
  'status' => array(
    'label' => t('Status'),
    'plural label' => t('Statuses'),
    'fieldable' => TRUE,
    ...

```
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Twig template name for field when content type is viewed in particular view mode
Based on twig template naming conventions I have created twig for any field type of given content:

```
field--node--myContentType.html.twig

```

Is it possible to use different twig when `myContentType` is visible in "full" view mode? I've already tried:

```
field--node--myContentType--full.html.twig

```

But it **does not** triggers. I can use `node--myContentType.html.twig` and `node--myContentType--full.html.twig` for full view of the node, but it doesn't work for `field` twig.

# Answer
Field templates have no name suggestion for the view mode.

From the linked page:

> This page lists the conventions used for the base html structure, the page, regions, blocks, nodes, fields, and other core components. (It's good to know that it is possible to create custom template name suggestions using function hook\_theme\_suggestions\_HOOK\_alter.)

You have to create a custom name suggestion.

You find the view mode in the variables of the field: Getting node view mode in field preprocess
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Boolean field inside node twig renders ok but does not work in if statement
I have an node twig and I want to use field of that node inside if of that twig. I managed to get the boolean value via `content.field_sample|raw`. But it looks like it doesn't work in `if` statement. For give code:

```
Value: {{ content.field_sample|raw }}
{% if content.field_sample|raw == '1' %}
    OK
{% else %}
    Error
{% endif %}

```

I get output:

```
Value: 1
Error

```

Sames goes for `{% if content.field_sample|raw == 1 %}`.

`{% if content.field_sample|raw == true %}` always returns true, regardless the boolean is on or off (it returns true for both `Value: 0` and `Value: 1`). I guess it's because it just checks if fields exists.

# Answer
> 2 votes
In content is the render array of the field output. A boolean is probably a text in `#markup`. What text this is for 0/1 can be configured in the display mode. But don't try to find it there, better use for coding the node. There you get the values directly from the database.

```
{% if node.field_sample.value %}

```

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


title: Display 0 if no results from view

text:
# Question
Title: Display 0 if no results from view
I have created a view to show users their uploaded content. It works well enough. Now if the user has not created any content then the view should output 0 or some custom message.

In earlier versions, there used to be a Empty Text field under Basic settings. I am using Drupal 7 with the latest Views.

So after some searc, I found it should occur under "No Results Behavior" in "Advanced Settings" but I do not seem to find an empty text there. I found "Global text" so there I write my message, but it does not display anything if the view is empty.

Do you have any suggestions?

# Answer
> 4 votes
Click on **NO RESULTS BEHAVIOR** on the right side.

Add a **Global: Text area**

Enjoy...

# Answer
> 0 votes
I was also not able to get it show up after setting up 'NO RESULTS BEHAVIOR' in my view. I realized the problem was with the template file. So, I copied the code from the views-view.tpl.php file and got it working again. Of course, I had to adjust the code. Here it is, in case you want to see it:

> ```
>   if(isset($empty)){
>             print $empty;
>     }
>
> ```

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


# Question
Title: Whats the correct way to programmatically include unpublished content in entity reference fields? (without views)
I have a node reference field whose options get reduced to those nodes in which the current user is referenced:

```
function mymodule_process_form_field_project_ref(&$field) {
  $field['#required'] = true;
  $field['widget']['#required'] = true;
  $options = $field['widget']['#options'];

  $project_nids = mymodule_user_get_referenced_projects();

  foreach ($options as $key => $label) {
    if (is_numeric($key)) {
      if (!in_array($key, $project_nids)) {
        unset($options[$key]);
      }
    }
  }

  $field['widget']['#options'] = $options;

}

```

The problem is, in `$field['widget']['#options']` unpublished nodes are being removed in the first place. How to keep those? Do I have to define an own `ServiceProviderBase` class using the alter function?

# Answer
You will need to create a custom EntityReferenceSelection plugin. Which should probably extend the NodeSelection plugin in core.
> 1 votes

---
Tags: 8, users
---